auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Function<Throwable, Throwable> getThrowableFunction(CoreEvent event) { return throwable -> { Throwable cause = getMessagingExceptionCause(throwable); CoreEvent exceptionEvent = event; if (throwable instanceof MessagingException) { exceptionEvent = ((MessagingException) throwable).getEvent(); } // MessagingException cause is set to null in order to avoid RETRY:EXHAUSTED ErrorType replacement // during ErrorType resolution (see ChainErrorHandlingUtils and MessagingExceptionResolver) return new MessagingException(exceptionEvent, new RetryPolicyExhaustedException(createStaticMessage(UNTIL_SUCCESSFUL_MSG_PREFIX, cause.getMessage()), null, owner), owner); }; }

Target:
should this be done internally by `RetryPolicyExhaustedException`? What other uses are there for it?
Source:
private void checkIfCrashRecoveryAndFinishActivity(final Activity context) { if (isRecoveredFromCrash()) { if (!(context instanceof MainMenuActivity)) { context.finish(); } else { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(RECOVERED_FROM_CRASH, false).commit(); } } CrashReporter.sendUnhandledCaughtException(); }

Target:
Please move the line in the if isRecoveredFromCrash block. ```java if (isRecoveredFromCrash()) { CrashReporter.sendUnhandledCaughtException(); … ``` This way we don't change the behavior in any kind. We will discuss where to put it later on.
Source:
public boolean evaluate(String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent) { return Pageview.isPageview(uriHost.toString(), uriPath.toString(), uriQuery.toString(), httpStatus.toString(), contentType.toString(), userAgent.toString()); }

Target:
Loooooong line
Source:
public Integer replayObserverFromIndex(Integer idx, SubjectObserver<? super T> observer) { int i = idx; while (i < index.get()) { accept(observer, i); i++; } return i; }

Target:
The `index` field should be read into a local variable outside the loop.
Source:
public String getUnmodifiedInstance() { return m_ipAddress + "[" + m_serviceName + "]"; }

Target:
```suggestion return getInstance(); ```
Source:
public LogEntry save(LogEntry delegate) throws ResourceDoesNotSupportOperationException { return null; }

Target:
Try to fill more of these methods bodies by copying ideas from that pull request or even the classes i pointed you to in the ticket description.
Source:
protected int indexOfChild(String localName) { AbstractDataTreeNode[] nodes = this.children; NoDataDeltaNode localNameNode = new NoDataDeltaNode(localName); return Arrays.binarySearch(nodes, localNameNode, (n1, n2) -> n1.name.compareTo(n2.name)); }

Target:
Two things: * Arrays.binarySearch() returns a negative if not found, but not necessarily -1 like the original code. And that will make line 453 above fail. You'd also have to check other callers. * IIRC this operation is called *very* frequently. I think you absolutely want to avoid allocating a dummy object here; it'll just put additional pressure on GC.
Source:
public void test() { connect(); jq(".z-listbox-body").scrollTop(10000); waitResponse(); Assert.assertTrue(jq("@listcell:contains(199)").exists()); }

Target:
need to wait before doing scrollTop
Source:
@Override public void initialize(Context context, ValueMap settings, LogLevel logLevel) throws IllegalStateException { if (!hasPermission(context, Manifest.permission.INTERNET)) { throw new IllegalStateException("Apptimize requires INTERNET permission"); } Apptimize.setup(context, settings.getString("appkey")); }

Target:
Our SDK can't be initialized without the internet permission either, so you don't need to check for this.
Source:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = createMainView(inflater, container, savedInstanceState); return rootView; }

Target:
Nitpick: AS is complaining about the unnecessary `rootView` variable. 😿
Source:
public static Set<FieldDeclaration> mergeFDs( DirectCompilerResult... sets ) { Set<FieldDeclaration> result = new HashSet<>(); for ( DirectCompilerResult fs : sets ) { result.addAll(fs.getFieldDeclarations()); } return result; }

Target:
Formatting of `( DirectCompilerResult... sets )`, should be `(DirectCompilerResult... sets)`.
Source:
private Long getHostsByCapability(List<Long> hostList, String hostCapability) { int totalHostswithCapability = 0; for (Long host : hostList) { //TODO: Fix this in single query instead of polling request for each Host Map<String, String> details = hostDetailsDao.findDetails(host); if (details.containsKey(Host.HOST_UEFI_ENABLE)) { if (details.get(Host.HOST_UEFI_ENABLE).equalsIgnoreCase("Yes")) { totalHostswithCapability++; } } } return totalHostswithCapability > 0 ? new Long(1) : new Long(0); }

Target:
Better return here when a host found with UEFI capability as that satisfies the return cond.
Source:
void setUniverseWrapper(UniverseWrapper wrapper) { this.universeWrapper = wrapper; }

Target:
Probably another access modification we don't need (probably the same for `isLoadingAsServer()` ?)
Source:
public Double getAggregate(AverageAccumulator<Double> result) { return (result.value)/result.count; }

Target:
I suggest to check whether count is 0, and return null (so that the aggregate constraint simply will not match) in that case.
Source:
public static void openClassLoader() throws IOException { ClassLoader myClassLoader = RetentionPolicyTest.class.getClassLoader(); assert myClassLoader != null; // Load the annotated class (and annotation classes) from the annotations-test.jar. See // http://b/132100102. File jarFile = new File(temporaryFolder.getRoot(), "annotations-test.jar"); try (InputStream in = myClassLoader.getResourceAsStream("annotations-test.jar"); OutputStream out = new FileOutputStream(jarFile)) { Streams.copy(in, out); } classLoader = new PathClassLoader(jarFile.getAbsolutePath(), myClassLoader); }

Target:
Did you mean to use the assert keyword here? Is it functional? Suggest either remove or switch to assertNotNull()
Source:
private boolean isWithoutRoot(Parameter[] parameters, JsonObject root, ControllerMethod method) { if(method.containsAnnotation(Consumes.class) && method.getMethod().getAnnotation(Consumes.class).withoutRoot()) { return true; } for (Parameter parameter : parameters) { if (root.get(parameter.getName()) != null) return false; } return true; }

Target:
I think that the 1st check is not needed, because if method doesn't contains `Consumes`, observer will not called.
Source:
public String getValue(ITask task) { AbstractRepositoryConnector connector = TasksUi.getRepositoryConnector(task.getConnectorKind()); TaskRepository repository = TasksUiInternal.getRepository(task); URL url = connector.getBrowserUrl(repository, task); if (url == null) { return task.getUrl(); } return url.toString(); }

Target:
This should check that repository is not null.
Source:
protected void onInit() { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); if (this.mongoTemplate == null) { this.mongoTemplate = new ReactiveMongoTemplate(this.mongoDbFactory, this.mongoConverter); } this.initialized = true; }

Target:
No, `this.` when you call methods.
Source:
public String read(String key) { String data = dataManager.read(key); return (data == null) ? null : encode(cryptoBox.decrypt(iv, decode(data)); }

Target:
Missing a close bracket (`)`) before the `;`.
Source:
protected void executeVdsBrokerCommand() { try { DeviceInfoReturn deviceInfoReturn = getBroker().attachManagedBlockStorageVolume(getParameters().getVolumeId(), JsonHelper.mapToJson(getParameters().getConnectionInfo())); setReturnValue(deviceInfoReturn.getDeviceInfo()); } catch (IOException e) { log.error("attachment of managed block storage device failed {}", e); return; } }

Target:
please break the line
Source:
public IndexedInts getRow() { // Treat any non-single-valued row as a row containing a single null value, to ensure consistency with // other expression selectors. See also ExpressionSelectors.supplierFromDimensionSelector for similar behavior. final IndexedInts row = selector.getRow(); if (row.size() == 1) { if (nullAdjustment == 0) { return row; } else { return new SingleIndexedInt(row.get(0) + nullAdjustment); } } else { // Can't handle non-singly-valued rows in expressions. // Treat them as nulls until we think of something better to do. return new SingleIndexedInt(0); } }

Target:
Could be cached, `SingleIndexedInt.of()` and cache 0-127 :)
Source:
public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); LOG.info("channelRegistered {}", ctx); }

Target:
These look like they are for debugging. could we make them debug logs instead?
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Member)) { return false; } if (!getClass().equals(obj.getClass())) { return false; } Member other = (Member) obj; return getId() == other.getId(); }

Target:
Shouldn't this be at line 134 ? Replacing ``.getClass()`` check instead of ``obj == null`` check ? Like in ``User`` object ? I know it will return ``false`` for ``null`` anyway, but this will also return false if you compare ``Member`` and ``RichMember`` which we wanted to be comparable. In ``User`` object you just continue with params comparison when you compare ``User`` and ``Candidate`` or ``RichUser``. I believe implementation should be at least equivalent in both ``Member`` and ``User`` objects.
Source:
public List<RefRight> getAllRights(final ApprovalCategory.Id id) { List<RefRight> l = new ArrayList<RefRight>(); l.addAll(getLocalRights(id)); l.addAll(getInheritedRights(id)); Collections.sort(l, RefRight.REF_PATTERN_ORDER); l = Collections.unmodifiableList(RefControl.filterMostSpecific(l)); return l; }

Target:
Style-nit: You can just return Collections.unmodifiableList ... here and avoid assignment back to l.
Source:
public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { if ((i.getValue().equals(value)) && i.getChecked() == false) { i.setChecked(true); } }); return values; }); }

Target:
is this needed?
Source:
public synchronized Marshaller<Key> getKeyMarshaller() { return keyMarshaller; }

Target:
Instead remove synchronized from the setter, and make the variable volatile
Source:
public void loadMyStep(int id) { try { if (!Objects.equals(id, null)) { setMySchritt(this.serviceManager.getTaskService().getById(id)); } } catch (DAOException e) { Helper.setFehlerMeldung("Error retrieving task with ID '" + id + "'; ", e.getMessage()); } }

Target:
An `int` type can or should never be null, maybe you want to use an `Integer` type which can be null. On other places you are comparing this with value `0`, so maybe only a wrong written condition?
Source:
private void addBootstrap3And4Style( String bootstrap3FileName, InputStream bootstrap3Data, Resource bootstrap4resource) { try (InputStream bootstrap4Data = bootstrap4resource.getInputStream()) { String bootstrap4FileName = bootstrap4resource.getFilename(); LOG.debug("Adding matching bootstrap 4 theme with name {}", bootstrap4FileName); styleService.addStyle( bootstrap3FileName, bootstrap3FileName, bootstrap3Data, bootstrap4FileName, bootstrap4Data); } catch (IOException e) { LOG.error("error adding new bootstrap 4 theme", e); } }

Target:
Is a bit surprising that it gets one InputStream and one Resource.
Source:
public void init() throws DBException { synchronized(RocksDBClient.class) { if(rocksDb == null) { rocksDbDir = Paths.get(getProperties().getProperty(PROPERTY_ROCKSDB_DIR)); System.out.println("RocksDB data dir: " + rocksDbDir); try { rocksDb = initRocksDB(); } catch (final IOException | RocksDBException e) { throw new DBException(e); } } references++; } }

Target:
please use a logging framework instead of System.out for messages. preferably slf4j.
Source:
protected void registerExtraDatabaseTypes( Properties configuration ) throws KettlePluginException { /*String hiveSimbaDriverName = configuration.getProperty( "hive2.simba.driver", "com.simba.hive.jdbc41.HS2Driver" ); JDBC_POSSIBLE_DRIVER_MAP.put( "hive2Simba", hiveSimbaDriverName );*/ String impalaSimbaDriverName = configuration.getProperty( "impala.simba.driver", "com.cloudera.impala.jdbc41.Driver" ); JDBC_POSSIBLE_DRIVER_MAP.put( "ImpalaSimba", impalaSimbaDriverName ); }

Target:
We don't need impala for hdi35, it's Cloudera only.
Source:
void addEntriesAndRotateLogs(EntryLogger entryLogger, int numOfRotations) throws IOException { EntryLogManagerBase entryLogManager = (EntryLogManagerBase) entryLogger.getEntryLogManager(); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); Random rand = new Random(); for (int i = 0; i < numOfRotations; i++) { addEntries(entryLogger, 10); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); } addEntries(entryLogger, 10); }

Target:
nit: make this static
Source:
public static ArrayList<Guid> getGuidListFromString(String str) { if (StringHelper.isNullOrEmpty(str)) { return new ArrayList<Guid>(); } return getGuidListFromStringArray(Arrays.asList(str.split(SEPARATOR))); }

Target:
We're trying to kill off the entire compat package - please don't add new dependencies to it. You can use common-lang's StringUtils.isEmpty(str)
Source:
public FileMockContext(Context context) { mContext = context; // default requestedPermissionName = "android.permission.INTERNET"; responsePermissionFlag = PackageManager.PERMISSION_GRANTED; permissionMap.put(requestedPermissionName,responsePermissionFlag); }

Target:
do you still need the requestePermissionName and responsePermissionFlag?
Source:
public static MultipartInput buildMultipartInput(Object input, String content) throws IOException { MultipartInput mpinput = new MultipartInput(); mpinput.setRequest(content); if (input instanceof Blob) { Blob blob = (Blob) input; mpinput.setBlob(blob); } else if (input instanceof Blobs) { mpinput.setBlobs((Blobs) input); } else { throw new IllegalArgumentException("Unsupported binary input object: " + input); } return mpinput; }

Target:
No need for intermediate `blob` variable
Source:
private ImmutableListMultimap<String, Availability> getAvailabilities(List<Episode> episodes) { ImmutableListMultimap<String, Availability> availabilities; try { availabilities = availabilities(episodes); } catch (GlycerinException e) { throw Throwables.propagate(e); } return availabilities; }

Target:
Just do `return availabilities(episodes)` here. Same for the rest of them.
Source:
public static boolean isWhitespaceOrComment(int kind) { switch (getCategory(kind)) { case WHITESPACE: case COMMENT: return true; default: return false; } }

Target:
nice. Maybe we can have a `isWhitespaceOrComment` method on the category and change this to: `return getCategory(kind).isWhitespaceOrComment()`
Source:
public List<String> getRuleChainVisits() { if (xPathRuleQueryNeedsInitialization()) { initXPathRuleQuery(); for (final String nodeName : xpathRuleQuery.getRuleChainVisits()) { super.addRuleChainVisit(nodeName); } } return super.getRuleChainVisits(); }

Target:
Unwanted final?
Source:
private boolean appliesToEvent(ITmfEvent event) { String eventName = event.getType().getName(); String eventHandlerName = fName; // test for correct name if (eventName.equals(eventHandlerName)) { return true; } // test for the wildcard at the end if ((eventHandlerName.endsWith(TmfXmlStrings.WILDCARD) && eventName.startsWith(eventHandlerName.replace(TmfXmlStrings.WILDCARD, TmfXmlStrings.NULL)))) { return true; } return false; }

Target:
cut at &&
Source:
@NonNull public String server() { // A protocol-relative URL can be returned from the API. // Protocol-relative URLs need to guarantee to be accessible via https, so we assume // https in this case. if (server.startsWith("//")) { server = "https:" + server; } return server; }

Target:
Maybe we should derive this from Prefs.getMediaWikiBaseUri() or require the client to pass in a default protocol. I think I prefer the latter to avoid complicating this nice and simple model type.
Source:
public void init(OrganizationalUnitsScreen presenter) { this.presenter = presenter; if (!presenter.canCreateOrganizationalUnit()) { createOrganizationalUnit.setHidden(true); } else { createOrganizationalUnit.setTextContent(ts.format(LibraryConstants.CreateOrganizationalUnit, translationUtils.getOrganizationalUnitAliasInSingular())); } title.setTextContent(translationUtils.getOrganizationalUnitAliasInPlural()); filterName.setAttribute("placeholder", ts.getTranslation(LibraryConstants.FilterByName)); cardByOrganizationalUnitIdentifier = new HashMap<>(); }

Target:
Here I would make this view, or any view, as "stupid" as possible. The `if` here could be in presenter and as could this variable `cardByOrganizationalUnitIdentifier`. This way you see what the component does by looking at the presenter and the functionality can be tested with the unit test.
Source:
private CertificateDTO addCertByAlias(List<CertificateDTO> toList, List<CertificateDTO> fromList, String alias){ for(CertificateDTO cert : fromList){ if(StringUtils.isNotEmpty(cert.getAlias()) && StringUtils.isNotEmpty(alias) && cert.getAlias().compareTo(alias)==0){ toList.add(cert); fromList.remove(cert); return cert; } } return null; }

Target:
Can we use .equals() instead of .compareTo?
Source:
public static ArrayList<Guid> getGuidListFromStringArray(List<String> strings) { ArrayList<Guid> guidList = new ArrayList<Guid>(); if (CollectionUtils.isEmpty(strings)) { for (String guidString : strings) { guidList.add(Guid.createGuidFromString(guidString)); } } return guidList; }

Target:
pls replace with strings != null && strings.isEmpty()
Source:
public void withAssertions_assertThat_iterator_Test() { assertThat(Arrays.asList(ITEMS).iterator()).toIterable().contains(ITEMS[0]); }

Target:
Should be an iterator assertion, e.g: ``` assertThat(Arrays.asList(ITEMS).iterator()).hasNext(); ```
Source:
public LogEntry deserializeLogData(ILogData logData) throws Exception{ LogEntry logEntry; try { logEntry = logData.getLogEntry(runtime); } catch (Exception e) { log.error("Cannot deserialize log entry" + logData.getGlobalAddress(), e); throw e; } return logEntry; }

Target:
I dont think this try/catch is necessary to just log this message. Why don't you move the message to processLogData
Source:
public QueryMetrics<Query<?>> makeMetrics(SegmentMetadataQuery query) { query.withAnalysisTypes(getFinalAnalysisTypes(query)); return queryMetricsFactory.makeMetrics(query); }

Target:
The result of this call is unused. I don't think it should be here.
Source:
private static void checkAssertion(SamlAssertionWrapper assertion, String confirmMethod) throws WSSecurityException { if (OpenSAMLUtil.isMethodHolderOfKey(confirmMethod)) { if (assertion.getSubjectKeyInfo() == null) { LOG.debug("There is no Subject KeyInfo to match the holder-of-key subject conf method"); throw new WSSecurityException(ErrorCode.FAILED_CHECK, "noKeyInSAMLToken"); } // The assertion must have been signed for HOK if (!assertion.isSigned()) { LOG.debug("A holder-of-key assertion must be signed"); throw new WSSecurityException(ErrorCode.FAILED_CHECK, "invalidSAMLsecurity"); } } }

Target:
This isn't really a debug statement, more of an info or trace.
Source:
public void checkChangedColumn() throws Exception { test(String.format("ALTER session SET `%s` = %d;", SLICE_TARGET, ExecConstants.SLICE_TARGET_DEFAULT)); testBuilder() .sqlQuery("SELECT status FROM sys.options WHERE name = '%s' AND type = 'SESSION'", SLICE_TARGET) .unOrdered() .baselineColumns("status") .baselineValues("DEFAULT") .build() .run(); }

Target:
you can remove `String.format` here too
Source:
public void tearDown() throws Exception { this.mTranslateSpecialChar = null; this.mTestStr.clear(); this.mVerifyStr.clear(); }

Target:
remove "this."
Source:
private String search(SearchRequest searchRequest, Model model, HttpServletRequest request) { SearchResultResponse resultResponse = doSearch(searchRequest, model, request); String queryText = formatQueryText(request); model.addAttribute("resultType", "searchResults"); model.addAttribute("pageSubtitle", "Search results for <span class=\"query-request\">\"" + queryText + "\"</span>"); return "searchResults"; }

Target:
I'd like to keep formatting/mark up out of our controllers. Maybe we could put the `queryText` into its model attribute and use it in `searchResults.jsp`
Source:
private FetchV0Request(@NonNull Set<ObjectId> wantIds, int depth, @NonNull Set<ObjectId> clientShallowCommits, long filterBlobLimit, @NonNull Set<String> clientCapabilities) { super(wantIds, depth, clientShallowCommits, filterBlobLimit, clientCapabilities); }

Target:
I prefer to leave this as package-private to avoid a synthetic accessor.
Source:
public static WeightedReservoirSampleStateStrategy deserialize(SliceInput input) { WeightedDoubleReservoirSample reservoir = WeightedDoubleReservoirSample.deserialize(input); return new WeightedReservoirSampleStateStrategy(reservoir); }

Target:
I'd inline this variable: `return new WeightedReservoirSampleStateStrategy(WeightedDoubleReservoirSample.deserialize(input));`
Source:
private void cleanup(File execDir) { if (execDir != null) { try { FileUtils.deleteDirectory(execDir); } catch (IOException e) { Throwables.propagate(e); } } }

Target:
Isn't this an anti-pattern described by https://github.com/google/guava/wiki/Why-we-deprecated-Throwables.propagate Shall we move away from using a deprecated method in general?
Source:
public SELF isEqualTo(String stringTemplate, Object ... args){ String expected = String.format(stringTemplate, args); this.comparables.assertEqual(info, actual, expected); return super.isEqualTo(expected); }

Target:
delete this line as the call to `super.isEqualTo(expected);` should be the only required assertion
Source:
public String getText() { if ("textarea".equals(getWrappedElement().getTagName())) { return getWrappedElement().getText(); } Optional<String> enteredText = Optional.of(getWrappedElement().getAttribute("value")); return enteredText.orElse(""); }

Target:
can be inlined i think
Source:
public double getTotalPopulationWeight() { return (double) reservoir.getTotalPopulationCount(); }

Target:
you shouldn't need to cast to double here
Source:
public void draw(Batch batch, float parentAlpha) { batch.setShader(shader); if (alpha == 0.0f) { super.setVisible(false); } else { super.setVisible(true); } if (lookData instanceof DroneVideoLookData) { lookData.draw(batch, alpha); } if (isLookVisible() && this.getDrawable() != null) { super.draw(batch, this.alpha); } batch.setShader(null); }

Target:
Please synchronize it.
Source:
protected boolean canSearchUsersAndGroups(NuxeoPrincipal principal) { if (principal.isAdministrator() || principal.isMemberOf(POWER_USERS_GROUP)) { return true; } UserManager um = Framework.getService(UserManager.class); List<String> adminGroups = um.getAdministratorsGroups(); return adminGroups.stream().anyMatch(principal::isMemberOf); }

Target:
Isn't this redundant with `principal.isAdministrator()`, knowing that `UserManager#makePrincipal` goes through `NuxeoPrincipalImpl#setVirtualGroups` and `NuxeoPrincipalImpl#updateAllGroups`? See https://github.com/nuxeo/nuxeo/blob/master/nuxeo-services/nuxeo-platform-usermanager-api/src/main/java/org/nuxeo/ecm/platform/usermanager/NuxeoPrincipalImpl.java#L367.
Source:
void setSucceeded() { this.succeeded = true; this.done = true; }

Target:
minor: `this` not required anywhere.
Source:
public void addPapyrusTable(Table tableInstance) { getResource().getContents().add(tableInstance); }

Target:
Might not work with controlled models
Source:
public <T> ReportedConfigurations add(ReportedConfigurationType type, T actual, T expected, boolean inSync) { String actualValue = actual != null ? actual.toString() : "null"; String expectedValue = expected != null ? expected.toString() : "null"; reportedConfigurationList.add(new ReportedConfiguration(type, actualValue, expectedValue, inSync)); return this; }

Target:
Done
Source:
public String toString() { StringBuilder sb = new StringBuilder("MaprDBJsonRecordReader[Table="); if (table != null) { sb.append(table.getPath()); } if (reader != null) { sb.append(", Document ID=") .append(IdCodec.asString(reader.getId())); } sb.append(", reader=") .append(reader) .append(']'); return sb.toString(); }

Target:
For the case when `table` is null, the string will be formed incorrectly - `Table=` should be appended only if `table != null`
Source:
private static Statistics stringColumnStats(String minimum, String maximum) { Statistics.Builder builder = Statistics.getBuilderForReading(new PrimitiveType(Type.Repetition.OPTIONAL, PrimitiveType.PrimitiveTypeName.BINARY, "testFile", OriginalType.UTF8)); builder.withMin(minimum.getBytes()) .withMax(maximum.getBytes()) .withNumNulls(0); return builder.build(); }

Target:
You can import `OPTIONAL`, `BINARY`, `UTF8`.
Source:
private static Dsn resolveDsn(Lookup lookup, @Nullable String dsn) { try { if (Util.isNullOrEmpty(dsn)) { dsn = Dsn.dsnFrom(lookup); } return new Dsn(dsn); } catch (Exception e) { logger.error("Error creating valid DSN from: '{}'.", dsn, e); throw e; } }

Target:
Does this belong in `SentryOptions`? In other SDKs we have it more as a POJO type of class. Perhaps these methods could be pulled out into an internal helper class.
Source:
public void reset(WritableByteChannel channel) throws IOException { this.channel = channel; }

Target:
This code should be: ``` this.channel.close(); ```
Source:
public void stop(ComponentContext context) throws InterruptedException { super.stop(context); providers.values().forEach(KeyValueStoreProvider::close); }

Target:
You should do the close before calling `super.stop`
Source:
void foo1() throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { byte[] bytes = "111".getBytes("UTF-8"); random.nextBytes(bytes); IvParameterSpec iv = new IvParameterSpec(bytes); // Compliant }

Target:
What does this list of exceptions bring to the test? Can't we replace it with `throws Exception`?
Source:
private static PathAddress createDeploymentAddressPrefix(DeploymentUnit deploymentUnit) { if (deploymentUnit.getParent() == null) { return PathAddress.pathAddress(DEPLOYMENT, deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME)); } else { return createDeploymentAddressPrefix(deploymentUnit.getParent()).append(SUBDEPLOYMENT, deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME)); } }

Target:
I'm pretty sure removing the change to this line will help fix the test failure problem. I don't think a subdeployment has this attachment, and in any case a subdeployment never has a management name that is different from deploymentUnit.getName(). A user can't assign a management name to a subdeployment as it's an internal part of the top level deployment, not something independently added to the server config.
Source:
void addUnloadedPlayer(String id, EntityData.PlayerStore unloadedPlayer) { unloadedPlayers.put(id, unloadedPlayer); }

Target:
More likely meaningless access changes
Source:
public void stop() { if (isStarted.compareAndSet(true, false)) { stopQueue(); dispatcher.stop(); } if (config.getPersistentQueueMode() == PersistentQueueMode.STICKY_POLLING) { reaper.stop(); } }

Target:
I would always call `stop` regardless of the mode (and make sure that `stop` is a no-op if it wasn't started). That way, as we implement other modes, we don't have to update that piece of code.
Source:
public static synchronized void setupRetentionPolicyMgr(int numThreads) { if (s_retentionPolicyMgr == null) { s_retentionPolicyMgr = new RetentionPolicyMgr(numThreads); } else if (s_retentionPolicyMgr.getRetentionThreadPoolSize() != numThreads) { s_retentionPolicyMgr.updateThreadPoolSize(numThreads); } }

Target:
Why not just always call the update and have the update either apply the change if it is different or ignore it
Source:
public String toString() { return String.valueOf(value); }

Target:
Why can't you just return value here?
Source:
public List<Concept> getPossibleValues() { try { return Context.getConceptService().getConceptsByName(""); } catch (Exception e) { logger.error("Error", e); } //pass return Collections.emptyList(); }

Target:
Change this to `log`
Source:
public String getIssuerName() { issuerName = StringUtils.isEmpty(x509Cert.getIssuerDN().getName()) ? EMPTY_FIELD : x509Cert.getIssuerDN().getName(); return issuerName; }

Target:
Do everything in the CertificateManagerServiceImpl . Use the certificate class just for sending to/from information on the View.
Source:
TestShardConsumerSubscriber(RecordsPublisher recordsPublisher, ExecutorService executorService, int bufferSize, ShardConsumer shardConsumer, int readTimeoutsToIgnoreBeforeWarning) { super(recordsPublisher, executorService, bufferSize, shardConsumer, readTimeoutsToIgnoreBeforeWarning); this.recordsPublisher = recordsPublisher; this.executorService = executorService; this.bufferSize = bufferSize; this.shardConsumer = shardConsumer; }

Target:
I am not able to see this constructor being used? There is no need to chain the constructors.
Source:
public String getText(final Object element) { Item item = (Item) element; String label = item.getLabel(); if (label == null || label.trim().length() == 0) { label = item.getViewpoint().getName(); } return label; }

Target:
This should be handled in item.getLabel()
Source:
public boolean flush () { final boolean[] success = {false}; ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (!nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); success[0] = true; } } }); return success[0]; }

Target:
Please recheck the condition here, having `success=true` and `log("..failed..")` in the same block seems wrong.
Source:
private void createFile(File parentDir, String name, String content) throws IOException { File file = new File(parentDir, name); file.createNewFile(); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(content.getBytes("UTF-8")); } finally { if (fos != null) fos.close(); } }

Target:
This isn't necessary, new FileOutputStream(file) will create the file if it doesn't exist yet.
Source:
public KomodoObject komodoServersNode(UnitOfWork transaction) throws KException { ArgCheck.isNotNull( transaction, "transaction" ); //$NON-NLS-1$ ArgCheck.isTrue( ( transaction.getState() == org.komodo.spi.repository.Repository.UnitOfWork.State.NOT_STARTED ), "transaction state is not NOT_STARTED" ); //$NON-NLS-1$ komodoEnvironment(transaction); return create(transaction, SERVERS_ROOT, Environment.SERVERS); }

Target:
The SERVERS_ROOT grouping node is defined as nt:unstructured in the cnd, so the third arg (tko:servers type) throws an exception when the create is attempted. Changing the third arg to null will create it without issue.
Source:
public DefaultEquivalenceResultBuilder( ScoreCombiner<T> combiner, EquivalenceFilter<T> filter, List<EquivalenceExtractor<T>> extractors ) { this.combiner = combiner; this.filter = filter; this.extractors = extractors; this.multipleCandidateExtractor = MultipleCandidateExtractor.create(); }

Target:
No longer used! rip this field out
Source:
public ParametersBuilder add(int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, 1970, 1, 1 ); }

Target:
Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?
Source:
public void setUp() { setting = new SettingImpl<>(Integer.class, SETTING_ID, 50, new RangedNumberValidator<>(0, 100, false, false)); eventResult = -1; setting.subscribe(propertyChangeEvent -> eventResult = (int) propertyChangeEvent.getNewValue()); }

Target:
@eviltak, you mentioned removing the need for the class parameter by checking on the type of the default value? Can you please do that?
Source:
private void check(Rule rule) { if (rule.att().contains("unblock")) return; resetVars(); gatherVars(rule.body()); gatherVars(rule.requires()); gatherVars(rule.ensures()); check(rule.body()); check(rule.requires()); check(rule.ensures()); }

Target:
Instead of `check(Rule...` and `check(Context...` (which may be enriched with others in the future, simply have a `DefinitionTransformer` pass that does nothing but this check, or use the `AbstractReflectiveVisitor`.
Source:
public void writeTo(ParticipantStatus participantStatus, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write(participantStatus.toString().getBytes()); }

Target:
It is better to use ``` java participantStatus.name() ``` since it cannot be overridden whereas toString() can.
Source:
public void stop(BundleContext context) throws Exception { shutdownActiveLaunches(); plugin = null; super.stop(context); fgBundleContext = null; if (fMemoryRetrievalFactory != null) { Platform.getAdapterManager().unregisterAdapters(fMemoryRetrievalFactory, IDMContext.class); } }

Target:
I'd move this above super.stop() for safety. but not the fgBundle... line
Source:
public void setEventList(List<ITimeEvent> eventList) { fEventList = eventList; }

Target:
It's unsafe to store lists directly (whoever has the reference can still modify the list afterwards). Perhaps it'd be worth making fEventList final, and have this method do a .clear() and shallow-copy the list contents over.
Source:
public static HostInfo fromBytes(byte[] bytes) throws JSONException { final JSONObject obj = new JSONObject(new String(bytes, StandardCharsets.UTF_8)); return new HostInfo(obj.getString(HOST_IP), obj.getString(GROUP), (int)obj.getLong(LOCAL_SITES_COUNT)); }

Target:
there is a `getInt` variant
Source:
public void addContent(HttpContent httpContent) throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } else { rawRequestContents.add(httpContent); ReferenceCountUtil.retain(httpContent); } }

Target:
it has to be otherway round
Source:
private String extractConnectionKey(final iOSVariant iOSVariant) { final StringBuilder sb = new StringBuilder() .append(iOSVariant.getVariantID()) .append(iOSVariant.isProduction() ? "-prod" : "-dev"); return sb.toString(); }

Target:
No need to assign to a temporary variable.
Source:
public void execute() { if (!hasLightGrenade) { if (hasPowerFailure) player.endTurn(); return; } // The square the player stepped on has a light grenade and should // always cause a decrease of at least three actions at this point. player.skipNumberOfActions(3 + (hasPowerFailure ? 1 : 0)); }

Target:
zeer matig geschreven methode maar bon ...
Source:
public String getName() { return this.name; }

Target:
[minor] I think we use `return name` (i.e. no `this`) elsewhere in jclouds?
Source:
public GetDeviceListQueryParameters() { privateStorageType = StorageType.UNKNOWN; checkStatus = false; }

Target:
This too should call this(...) somehow, it's becoming clunky
Source:
public void testImportWithoutPadding() throws IOException { if(failWithoutExtraArgs){ thrown.expect(IOException.class); thrown.expectMessage("Failure during job; return status 1"); NumericTypesTestUtils.configureJunitToExpectFailure(thrown); } ArgumentArrayBuilder builder = getArgsBuilder(); String[] args = builder.build(); runImport(args); if (!failWithoutExtraArgs) { verify(); } }

Target:
This method seems to be doing the same thing as the previous line.
Source:
void addReferencesToBlobs(PortAndAssignment pna, BlobChangingCallback cb) throws IOException, KeyNotFoundException, AuthorizationException { List<LocalResource> localResourceList = getLocalResources(pna); if (!localResourceList.isEmpty()) { getBlobs(localResourceList, pna, cb); } pna.complete(); }

Target:
just one more nit: put this outside of this method since the method `addReferencesToBlobs` doesn't indicate `complete`
Source:
public void visitFunctionDeclaration(FunctionDeclarationTree tree) { super.visitFunctionDeclaration(tree); checkFunction(tree); }

Target:
@ivandalbosco No need to change order if we don't rely on visitor for finding "try"
Source:
private boolean isBufferFilled() { int available = fileBuffer.size(); return available > 0 && available >= Math.min(MIN_BYTES_READ_IN, this.fileBytesLeft); }

Target:
Can we surround the return in parenthesis
Source:
public boolean consumeRetry() { return --remainingRetries >= 0; }

Target:
the previous code had pretty bad readability. The new one is better, but not much. Maybe we can be a little more expressive than `--remainingRetries >=0`?
Source:
public String getDisplayName(int tokenType) { if (tokenType >= Token.MIN_USER_TOKEN_TYPE && tokenType < displayNames.length) { String displayName = displayNames[tokenType]; if (displayName != null) { return displayName; } } String literalName = getLiteralName(tokenType); if (literalName != null) { return literalName; } String symbolicName = getSymbolicName(tokenType); if (symbolicName != null) { return symbolicName; } return Integer.toString(tokenType); }

Target:
❗️ This prevents a user from assigning a custom display name to `Token.INVALID_TYPE`. Adding this as a restriction doesn't seem to provide any benefit to the user.
Source:
private boolean hasPersistentPower() { final PackageManager pm = this.getPackageManager(); return (pm != null && (pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) || pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE))); }

Target:
Nit: while you're at it, this "this." is not necessary, I think.
Source:
public Boolean attachStdin() { return (attachStdin != null) ? attachStdin : Boolean.FALSE; }

Target:
if these Boolean methods can never be null why not have the return type be boolean instead of Boolean ?
Source:
private boolean validatePage() { if (dcc.getDirectory() == null || dcc.getDirectory().equals("")) { //$NON-NLS-1$ setErrorMessage("Destination not selected!"); return false; } if(0 == systemTree.getCheckedElements().length){ setErrorMessage("Nothing selected for FMU generation!"); return false; } if (!isSomeLibrarySelected()){ setErrorMessage("No libraries selected to include"); return false; } setErrorMessage(null); return true; }

Target:
by switching to "".eqauls(dcc.getDirectory()) you don't need the null check
Source:
public boolean StorageDomainRemoved(storage_domain_static storageDomain) { storage_server_connections connection = DbFacade.getInstance().getStorageServerConnectionDAO().get(storageDomain.getstorage()); if (connection != null) DbFacade.getInstance().getStorageServerConnectionDAO().remove(connection.getid()); return true; }

Target:
Please add
Source:
public void open() throws IOException { writer = CompressionFactory.getDoubleSerializer( ioPeon, String.format("%s.double_column", filenameBase), byteOrder, compression ); writer.open(); }

Target:
StringUtils
Source:
public LeaderElectorImp(Map conf, List<String> servers, CuratorFramework zk, String leaderlockPath, String id, AtomicReference<LeaderLatch> leaderLatch, AtomicReference<LeaderLatchListener> leaderLatchListener) { this.conf = conf; this.servers = servers; this.zk = zk; this.leaderLatch = leaderLatch; this.id = id; this.leaderLatch = leaderLatch; this.leaderLatchListener = leaderLatchListener; }

Target:
duplicately here
Source:
protected Class<?> loadRepositoryInterface(RepositoryConfiguration<?> configuration, ResourceLoader loader) { String repositoryInterface = configuration.getRepositoryInterface(); ClassLoader classLoader = loader.getClassLoader(); try { return org.springframework.util.ClassUtils.forName(repositoryInterface, classLoader); } catch (ClassNotFoundException | LinkageError e) { LOGGER.warn(String.format(CLASS_LOADING_ERROR, getModuleName(), repositoryInterface, classLoader), e); } return null; }

Target:
What's the reason we need to make this `protected`?
Source:
protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), "'outputChannel' or 'outputChannelName' is required"); }

Target:
Well, I think now this should be moved to the `onInit()` raise error ASAP.
Source:
protected DocumentModel createDocument(boolean withBlobContent) { DocumentModel documentModel = session.createDocumentModel("/", "MyFile", "File"); if (withBlobContent) { documentModel.setPropertyValue(FILE_CONTENT_PROPERTY, (Serializable) Blobs.createBlob(FILE_CONTENT)); } documentModel = session.createDocument(documentModel); return documentModel; }

Target:
``` return session.createDocument(documentModel); ```
Source:
private boolean checkPresentOrNullable(Invocation invocation, String paramKey, int argIndex, Object arg) { if (arg == null && !Reflection2.getInvokableParameters(invocation.getInvokable()).get(argIndex).isAnnotationPresent(Nullable.class)) throw new NullPointerException(format("param{%s} for invocation %s.%s", paramKey, invocation.getInvokable() .getOwnerType().getRawType().getSimpleName(), invocation.getInvokable().getName())); return true; }

Target:
Static import of `Reflection2.getInvokableParameters`?
Source:
public void optOutTracking() { getAnalyticsMessages().emptyTrackingQueues(new AnalyticsMessages.MixpanelDescription(mToken)); if (getPeople().isIdentified()) { getPeople().deleteUser(); getPeople().clearCharges(); } mPersistentIdentity.clearPreferences(); synchronized (mEventTimings) { mEventTimings.clear(); mPersistentIdentity.clearTimeEvents(); } mPersistentIdentity.clearReferrerProperties(); mPersistentIdentity.setOptOutTracking(true); }

Target:
is it allowed to flush the events on the device after the user opt out in gdpr?
Source:
protected org.robolectric.bytecode.ShadowMap createShadowMap() { return super.createShadowMap() .newBuilder() .addShadowClass(ShadowCrashlytics.class) .addShadowClass(ShadowMapView.class) .addShadowClass(ShadowGLMatrix.class) .build(); }

Target:
why the fully qualified package name here?
Source:
public static String serialize(ColumnStatisticMetadata value) { return value.getStatisticType().name() + ":" + value.getColumnName(); }

Target:
What does "column name" refer to? The plan IR shouldn't have any references to column names, but should be using column handles, instead.
Source:
private static void deleteFileIfExists(File to) throws IOException { boolean fileDoesNotExist = to.exists(); if (fileDoesNotExist) { return; } boolean deleteOk = to.delete(); if (deleteOk) { return; } throw new IOException("Unable to delete file: " + to.getAbsolutePath()); }

Target:
There seems to be a `!` missing.
Source:
public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); final K key = entry.getKey(); final Collection<V> value = entry.getValue(); return new UnmodifiableMapEntry<>(key, value); }

Target:
You can just inline `key` and `value` IMO.
Source:
public void basicInvocation(Runnable call) throws Exception { DistributedExecutorService des = createDES(getCache()); des.submit(call); }

Target:
I believe, we should call get on the future: ``` des.submit(call).get() ```
Source:
public void aggregate(ByteBuffer buf, int position) { final int oldPosition = buf.position(); buf.position(position); bufferAdd(buf); buf.position(oldPosition); }

Target:
The position adjustment and restore should be wrapped in a try/finally, because we don't want the buffer to be left in an invalid state if an exception is thrown.
Source:
public List<Put> getJobPuts() { if (jobHistoryListener != null) return jobHistoryListener.getJobPuts(); else return null; }

Target:
nit: add braces for each if/else statement
Source:
private boolean isTemplate(String expression) { return expression.startsWith(PARSER_CONTEXT.getExpressionPrefix()) && expression.endsWith(PARSER_CONTEXT.getExpressionSuffix()); }

Target:
This is not correct. The expression can be like this: `foo#{bar.value}.baz`. With meaning to evaluate a template part and concatenate it with the rest as strings. See `ParserContext` JavaDocs. Also that doesn't make sense to deprecate private method. The point was to log `warn` that templating is deprecated. Nothing more we can do from the context of variable.
Source:
public String toString() { return Objects.toStringHelper(this) .omitNullValues() .add("revision", revision.getName()) .add("oldRevision", oldRevision.getName()) .add("path", path) .toString(); }

Target:
can't these be null?
Source:
public void testListImages() { List<ImageSummary> listImages = api().listImages(); assertNotNull(listImages); ImageSummary taggedImage = Iterables.find(listImages, new Predicate<ImageSummary>() { @Override public boolean apply(ImageSummary input) { return input.repoTags().contains("jclouds:testTag"); } }); assertNotNull(taggedImage); }

Target:
The `find` method will throw an exception if not found, so the assertion below is redundant. Use `tryFind` if you want to be explicit or just remove the assertion.
Source:
private static void resetJsonReaderEscapeAnyChar() { client.alterSession(ExecConstants.JSON_READER_ESCAPE_ANY_CHAR, false); }

Target:
No need to have above methods as `static`. `private void` is fine.
Source:
private int getNumberOfPartitionsForTopic(final String topic) throws ExecutionException, InterruptedException { try (AdminClient adminClient = createAdminClient()) { final TopicDescription topicDescription = adminClient.describeTopics(Collections.singleton(topic)) .values() .get(topic) .get(); return topicDescription.partitions().size(); } }

Target:
Ah, yeah, there are some limitations to the linter. Thanks for taking care of it.
Source:
public List<String> getHeaders(String name) { MultivaluedMap<String, String> headers = requestContext.getMutableHeaders(); System.out.println(headers.get(name)); return headers.get(name); }

Target:
Need to remove this leftover debug output
Source:
public boolean startWork(String id) { synchronized (mLock) { return startWork(id, null); } }

Target:
Nit: You don't really need the synchronized here.
Source:
public WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request) { loggerContext.log("msg-in.txt", new UpdateLogCallback(updates)); final UpdateResponse updateResponse = updateRequestHandler.handle(new UpdateRequest(origin, keyword, updates), updateContext); return performUpdates(request, updateContext, updates); }

Target:
Add a TODO to use the response, if there aren't any side-effects?
Source:
private V computeInternal(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction, boolean computeIfPresent, Metadata metadata, long flags) { assertKeyNotNull(key); assertFunctionNotNull(remappingFunction); InvocationContext ctx = getInvocationContextWithImplicitTransaction(false, 1); ComputeCommand command = commandsFactory.buildComputeCommand(key, remappingFunction, computeIfPresent, metadata, flags); ctx.setLockOwner(command.getKeyLockOwner()); return (V) executeCommandAndCommitIfNeeded(ctx, command); }

Target:
This needs to be changed to support locked stream syntax now.
Source:
protected void addMappingsToConcepts(List<Object> explicitItems) { log("Adding mappings to Concepts"); if (MetadataSharing.getInstance().isAddLocalMappings()) { ConceptPubSubService pubsubService = Context.getService(ConceptPubSubService.class); for (Object explicitItem : explicitItems) { if (explicitItem instanceof Concept) { //MetadataSharing.getInstance().getConceptMapper().addSystemConceptMap((Concept) explicitItem); pubsubService.addLocalMappingToConcept((Concept) explicitItem); } } } }

Target:
Put it inside the if.
Source:
public Artifact getRequirementFromArtifactId(ArtifactId artId) { for (Artifact art : directRequirements) { if (art.getId().equals(artId.getId())) { return art; } } return null; }

Target:
Nit: You should be able to do "if (art.equals(artId))"