auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CrossesListDescriptionSheetParser(final T importedList, final UserDataManager userDataManager) { this.importedList = importedList; this.doParseDetails = true; this.doParseConditions = true; this.doParseFactors = true; this.doParseVariates = true; this.userDataManager = userDataManager; this.descriptionSheetIndex = 0; ; }

Target:
remove
Source:
public VolumeClassification getVolumeClassification() { if (volumeClassification == null) { if (active) { return VolumeClassification.Volume; } return VolumeClassification.Snapshot; } return volumeClassification; }

Target:
please change to ternary
Source:
public void registerSonarQubeVersion_publishes_version_on_first_call() { ClusterProperties clusterProperties = new ClusterProperties(newClusterSettings()); try (HazelcastCluster hzCluster = HazelcastCluster.builder(clusterProperties).build()) { hzCluster.registerSonarQubeVersion("1.0.0.0"); HazelcastInstance hzInstance = createHazelcastClient(hzCluster); assertThat(hzInstance.getAtomicReference(SONARQUBE_VERSION).get()) .isNotNull() .isInstanceOf(String.class) .isEqualTo("1.0.0.0"); } }

Target:
no need for isNotNull nor isInstanceOf(String.class). They are both implicit with .isEqualTo("1.0.0.0")
Source:
public String[] getColumnTexts(@NonNull ITimeGraphEntry entry) { String[] texts = new String[fColumns.length]; for (int i = 0; i < fColumns.length; i++) { texts[i] = fLabelProvider.getColumnText(entry, i); } return texts; }

Target:
Null pointer...
Source:
public TreeFillingConfigurationDialog(final Shell parentShell, final TreeFillingConfiguration treefillingConfiguration, final List<ILabelProviderConfiguration> existingLabelProvidersConfiguration, final List<PasteEObjectConfiguration> existingPasteConfigurations) { super(parentShell); this.modifiedTreefillingConfiguration = EcoreUtil.copy(treefillingConfiguration); this.existingLabelProviderConfigurations = existingLabelProvidersConfiguration; this.existingPasteConfigurations = existingPasteConfigurations; setTitle(org.eclipse.papyrus.customization.nattableconfiguration.messages.Messages.TreeFillingConfigurationDialog_treeFillingConfigurationDialogName); }

Target:
import the class Messages ?
Source:
public void execute(final Talks talks) throws IOException { int idx = this.index(talks); for (final Talk talk : talks.active()) { final int current = idx + 1; talk.modify( new Directives() .xpath("/talk/request") .attr("index", Integer.toString(current)) ); idx = current; } }

Target:
`current` is redundant, just use `idx`
Source:
public long getSafePointDrId() { // Acquire lock to avoid seeing bad data while another thread is in truncate() synchronized (m_map) { assert (!m_map.isEmpty()); return end(m_map.asRanges().iterator().next()); } }

Target:
Looks good to me, but worth to protect `getFirstDrId()` and `getLastDrId()` too, they'll throw `NoSuchElementException` also if `m_map` is empty.
Source:
public void setUp() throws Exception { createProjectWithNfcAndSetVariable(PROJECT_NAME); numDetectedTags.setValue(0); nfcBrickPosition = 0; setVariableIDPosition = 1; setVariableMessagePosition = 2; baseActivityTestRule.launchActivity(null); checkIfSpinnerOnBrickAtPositionShowsString(R.id.set_variable_spinner, setVariableIDPosition, READ_TAG_ID); checkIfSpinnerOnBrickAtPositionShowsString(R.id.set_variable_spinner, setVariableMessagePosition, READ_TAG_MESSAGE); }

Target:
is this necessary in the set up? wouldnt it be sufficient if this would be done once in the layout test?
Source:
public ListRequest list() { return new ListRequest() { @Override public List<ProjectInfo> get() throws RestApiException { return ProjectsImpl.this.list(this); } }; }

Target:
I don't think ProjectsImpl.this is necessary, it would only be necessary if the method call were get(this) which conflicts with the method name in the anonymous class.
Source:
public void validateEnums(WatchDog entity) { EnumValidator.validateEnum(WatchdogAction.class, entity.getAction(), true); EnumValidator.validateEnum(WatchdogModel.class, entity.getModel(), false); }

Target:
potential NPE, entity can be NULL
Source:
void error(ZuulException e) { RequestContext.getCurrentContext().setThrowable(e); zuulRunner.error(); LOG.error(e.getMessage(), e); }

Target:
My preference would be to remove `e.printStackTrace()` altogether and let the 'error' filters determine if they want to log the error.
Source:
private List<String> defaultIncludedModuleNamesForUnnamedModule() { if (fJavaElements != null) { List<IPackageFragmentRoot> roots= new ArrayList<>(); for (IJavaElement fJavaElement : fJavaElements) { if (fJavaElement instanceof IPackageFragmentRoot) { roots.add((IPackageFragmentRoot) fJavaElement); } } return JavaCore.defaultRootModules(roots); } return Collections.emptyList(); }

Target:
rename to element
Source:
public ResponseEntity<?> disable(@RequestBody List<Long> printerIds) throws IOException { return setState(printerIds, false); }

Target:
`@ResponseStatus(HttpStatus.NO_RESPONSE)`, void return type Same for `/enable`
Source:
public double getFilterMinSelectivityEstimateFactor() { return options.getOption(FILTER_MIN_SELECTIVITY_ESTIMATE_FACTOR.getOptionName()).float_val; }

Target:
Make the option validators above typed: `public static final FloatValidator FILTER_MIN_SELECTIVITY_ESTIMATE_FACTOR ...` and change this line to: `return options.getOption(FILTER_MIN_SELECTIVITY_ESTIMATE_FACTOR);` Same for the other option.
Source:
public JavaOutputProcessor(PrettyPrinter printer) { this.printer = printer; this.environment = printer.getEnvironment(); }

Target:
why did you need to copy the env? it is accessible via getFactory().getEnv().
Source:
public BucketFunction getBucketFunction( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle, List<Type> partitionChannelTypes, int bucketCount) { HivePartitioningHandle handle = (HivePartitioningHandle) partitioningHandle; BucketFunctionType bucketFunctionType = handle.getBucketFunctionType(); switch (bucketFunctionType) { case HIVE_COMPATIBLE: return createHiveCompatibleBucketFunction(bucketCount, handle.getHiveTypes().get()); case PRESTO_NATIVE: return createPrestoNativeBucketFunction(bucketCount, handle.getTypes().get()); default: throw new IllegalStateException("Unsupported bucket function type " + bucketFunctionType); } }

Target:
nit `IllegalArgumentException`
Source:
public void writePacketData(RailcraftOutputStream data) throws IOException { super.writePacketData(data); tankManager.writePacketData(data); data.writeBoolean(boiler.isBurning()); }

Target:
This is only required in things that render the FluidStack in a TESR.
Source:
protected void setValue(final int rowIndex, final int columnIndex, final Date value) { DTCellValue52 dtCellValue52 = table52.getData() .get(rowIndex) .get(columnIndex); dtCellValue52 .setDateValue(value); try { updateManager.update(table52, getUpdates(rowIndex, columnIndex)); } catch (UpdateException e) { e.printStackTrace(); } }

Target:
This _smells_ bad.. what was your reasoning to catch `UpdateException`?
Source:
private TreeMap<Event, List<EntryDTO>> buildEventEntryDTOMap(List<EntryDTO> entryDTOS) { return entryDTOS.stream().collect(Collectors.groupingBy(EntryDTO::getEvent, () -> new TreeMap<>(Comparator.comparing(Event::getExternalId).thenComparing(Event::getWhenOccured)), Collectors.toList())); }

Target:
```suggestion () -> new TreeMap<>(Comparator.comparing(Event::getWhenOccured).thenComparing(Event::getExternalId)), Collectors.toList())); ```
Source:
public void verifyTableProperty(String propertyName, int propertyValue) { waitForElementByElement(table); Assertion.assertEquals(table.getAttribute(propertyName), Integer.toString(propertyValue)); PageObjectLogging.log( "verifyTableProperty", "table has correct " + propertyName + " property", true ); }

Target:
1. set this method to private, 2. create helpers for each property
Source:
public ColumnMetadata_v4(String[] name, PrimitiveType.PrimitiveTypeName primitiveType, Object minValue, Object maxValue, Long nulls) { this.name = name; this.minValue = minValue; this.maxValue = maxValue; this.nulls = nulls; this.primitiveType = primitiveType; }

Target:
Please post the examples of content for new metadata cache files to the Jira description
Source:
@Override public ReflogEntry getReverseEntry(int number) throws IOException { lock.lock(); try { LogCursor cursor = reftable.seekLog(refname); while (true) { if (!cursor.next() || number < 0) { return null; } if (number == 0) { return cursor.getReflogEntry(); } number--; } } finally { lock.unlock(); } }

Target:
The @Override should go on a line on its own, like in getReverseEntries() and the same below.
Source:
public void testVersion0_98IsValid() throws Exception{ rootDir = Paths.get(getClass().getClassLoader().getResource("bags/v0_98/bag").toURI()); if (System.getProperty("os.name").contains("Windows")){ Path bagitDir = rootDir.resolve(".bagit"); Files.setAttribute(bagitDir, "dos:hidden", Boolean.TRUE); } Bag bag = reader.read(rootDir); sut.isValid(bag, true); }

Target:
the .bagit folder does not have to be hidden. .bagit is our incubating next version of the bagit spec; it solves a lot of problems from the originial spec.
Source:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { final AbstractStatementVisitor visitor = new PreStatementVisitor(context); syntaxNode.accept(visitor); return visitor.programState; }

Target:
remove `final` modifiers everywhere.
Source:
ParameterMap getQueryParams(MuleEvent event) { return resolveParams(event, HttpParamType.QUERY_PARAM); }

Target:
This breaks compatibility.
Source:
public Mutation(Mutation m) { m.serialize(); this.row = m.row; this.data = m.data; this.size = new MutationSize(m.size.entries, m.size.sizeInBytes); this.values = m.values; this.replicationSources = m.replicationSources; }

Target:
maybe make a copy constructor for this case?
Source:
public DecoratedCache(AdvancedCache<K, V> delegate, ClassLoader classLoader) { this(delegate, classLoader, null, null); }

Target:
The last `null` is interpreted as a null `Flag`, not as a null `Flag[]`, and is causing some NPEs in the test suite: http://ci.infinispan.org/viewLog.html?buildId=6702&buildTypeId=bt9
Source:
default Query getRemoveByQuery() { if (isVersionedEntity()) { return getQueryForVersion(); } return getByIdQuery(); }

Target:
Ternary ? true : false. ;)
Source:
public void addError(String errorMessage, Element element) { errors.add(new ProblemImpl(errorMessage, name, element)); }

Target:
There are still a lot of calls to this method, resulting in errors that will not reference any BPMN element. From a quick look, many of those do have an element id that we could reference.
Source:
private void validatePage() { String message = null; if (userText.getText().trim().length() == 0) message = Messages.CredentialsWizardPage_ErrorUser; if (message == null && passwordText.getText().trim().length() == 0) message = Messages.CredentialsWizardPage_ErrorPassword; setErrorMessage(message); setPageComplete(message == null); }

Target:
Suggestion: Use an else-if for these two and provide the missing braces. And instead of length() == 0 I'd use isEmpty().
Source:
public boolean isSupporting(Capabilities capabilities) { return BrowserType.EDGE.equals(capabilities.getBrowserName()) || capabilities.getCapability("chromeOptions") != null || capabilities.getCapability("goog:chromeOptions") != null; }

Target:
You probably don't want to pick this if `browserName` is also `chrome` or `chromium`, right? Otherwise this will match: `{"browserName": "chrome", "goog:chromeOptions": {}}`, which isn't what you want.
Source:
public HistoryTreeStub getHistoryTree() { return (HistoryTreeStub) NonNullUtils.checkNotNull(super.getSHT()); }

Target:
getSHT() can never actually be null, we should just annotate it.
Source:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { return Lists.newArrayList(Iterables.filter(Iterables.concat(trace.getEventAspects(), EXTRA_ASPECTS), aspect -> aspectClass.isAssignableFrom(aspect.getClass()))); }

Target:
why the newArrayList? Iterables.filter already returns an iterable.
Source:
public PrestoSparkRow get() throws InterruptedException { PrestoSparkRow row; synchronized (monitor) { while (!finished && buffer.isEmpty()) { monitor.wait(); } if (finished) { return null; } row = buffer.poll(); } memoryManager.updateMemoryUsage(-row.getRetainedSize()); return row; }

Target:
So `PrestoSparkRowBuffer#get` is a blocked call. Is there any reason for that -- I am asking this since the general convention in Presto seems to be using `ListenableFuture<PrestoSparkRow>` for such cases?
Source:
private ByteBuffer parsePacketIDBAndNRB(int blockLength) throws IOException { ByteBuffer pcapPacketData; pcapPacketData = ByteBuffer.allocate(blockLength - PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); pcapPacketData.position(PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); pcapPacketData.clear(); SeekableByteChannel fFileChannel; try { fFileChannel = getFileChannel(); fFileChannel.read(pcapPacketData); } catch (BadPcapFileException e1) { /* Just ignore */ } pcapPacketData.flip(); return pcapPacketData; }

Target:
This is useless since clear() below resets position to zero?
Source:
public MiniEditorComponentObject triggerEditCommentArea() { jsActions.scrollToElement(allCommentsArea); WebElement mostRecentComment = articleComments.get(0); PageObjectLogging.log("First check",mostRecentComment.getText(), true); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement editButton = mostRecentComment.findElement(By.cssSelector(EDIT_BUTTON_SELECTOR)); Actions actions = new Actions(driver); actions.moveToElement(editButton).perform(); js.executeScript("arguments[0].querySelector(arguments[1]).click()", mostRecentComment, EDIT_BUTTON_SELECTOR); return new MiniEditorComponentObject(driver); }

Target:
merge into one line
Source:
public String getContentAccessModeList() { String[] modeList = contentAccessModeList == null ? new String[0] : contentAccessModeList.split(","); String ammend = ""; if (!ArrayUtils.contains(modeList, ContentAccessCertServiceAdapter.DEFAULT_CONTENT_ACCESS_MODE)) { ammend = modeList.length > 0 ? "," : ""; ammend += ContentAccessCertServiceAdapter.DEFAULT_CONTENT_ACCESS_MODE; } return modeList.length > 0 ? this.contentAccessModeList + ammend : ammend; }

Target:
@wottop Would this mean that the "entitlement" mode is always included? Even if a mode list has been set on the owner that did not include it? If so, that does not seem right as it is valid to set the list to not contain entitlements as an option, just that if the list is empty that means it should be set to entitlement.
Source:
public void setUp() { System.setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); configuration = Configuration.DEFAULT; }

Target:
@timowest weird. I remembered it was failed with testing on querydls-sql module. but it's gone now.
Source:
public void onDestroyView() { mWebViewStateOnDestroyView = new Bundle(); try { storeWebView(mWebViewStateOnDestroyView); mWebViewBridge.destroy(); } catch (Exception exp) { Log.w(TAG, exp.getMessage() + "", exp); } super.onDestroyView(); }

Target:
mWebViewStateOnDestroyViewを追加せずに mWebViewBridge.destroy(); のあとにmWebViewBridge =null; で解決すると思います
Source:
private static void deleteDir(HdfsContext context, HdfsEnvironment hdfsEnvironment, Path path, boolean recursive) { try { hdfsEnvironment.getFileSystem(context, path).delete(path, recursive); } catch (Exception e) { // don't fail if unable to delete path Logger.get(GlueHiveMetastore.class).warn(e, "Failed to delete path: " + path.toString()); } }

Target:
Declare the logger at the top of the class: ```java private static final Logger log = Logger.get(GlueHiveMetastore.class); ``` (you might see the inline `Logger.get()` pattern in some tests, but it's not the normal way)
Source:
private boolean isNakedTD1Key(String s) { return NAKED_TD1_KEY_PATTERN.matcher(s).matches(); }

Target:
`private static`
Source:
public long skip(long n) throws IOException { if (n <= 0) { return 0; } if (n > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } else { ((Seekable) in).seek(mPos + n); } mPos += n; return n; }

Target:
nit: for readability i prefer a method called `isSequentialReadMode` to determine whether to seek or not
Source:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartNoneEvent emptySubprocess = getStartNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, StartNoneEvent.class); assertGeneralSet(emptySubprocess.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertStartEventSlaDueDate(emptySubprocess.getExecutionSet(), EMPTY_VALUE); }

Target:
Missing assertNotNull for executionSet here.
Source:
private List<Window> fetchWindowsInQueue() { List<Window> windows = Lists.newArrayList(getWindows()); return ImmutableList.copyOf(Lists.reverse(windows)); }

Target:
Remove the reversal here, and let the JDK 8 implementation return it in reverse, and the JDK 9 implementation *not* reversed.
Source:
protected void executeCommand(IDeviceManagementInteractor executor) throws DeploymentException { try { executor.startFB(resource, new FBDeploymentData("", resFB)); //$NON-NLS-1$ //TODO correctly determine prefix } catch (DeploymentException e) { throw e; } }

Target:
what is the point of catching the exception here?
Source:
void setReaderBudget() { reader.setResultSizeBudget(ariaBatchRows <= MIN_BATCH_ROWS ? UNLIMITED_BUDGET : targetResultBytes); }

Target:
Make this method private.
Source:
default <T> Flux<SearchHit<T>> find(Query query, Class<T> entityType) { return find(query, entityType, entityType); }

Target:
Same as with the imperative template: Shouldn't we just deprecate these methods and introduce `Flux<SearchHit<T>> search(…)`?
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { RepositorySearchWizard wizard = new RepositorySearchWizard( util.getConfiguredRepositories(), false); WizardDialog dialog = new WizardDialog(getShell(event), wizard); if (dialog.open() == Window.OK) { for (String dir : wizard.getDirectories()) { File repositoryDir = FileUtils.canonicalize(new File(dir)); addRepository(repositoryDir); } } return null; }

Target:
True, now.
Source:
public Map<String, String> load() { final Map<String, String> preferences = new HashMap<String, String>(); final String property = System.getProperty( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED ); log.info( "Setting preference '" + GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED + "' to '" + property + "'." ); preferences.put( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED, property ); return preferences; }

Target:
We normally check if this is `null` and only set if non-null... IDK if your code handles `null` differently?
Source:
protected int getParallelHostCount(UpgradeContext ctx, int defaultValue) { if (m_grouping.parallelScheduler != null) { int taskParallelism = m_grouping.parallelScheduler.maxDegreeOfParallelism; if (taskParallelism == ParallelScheduler.DEFAULT_MAX_DEGREE_OF_PARALLELISM) { taskParallelism = ctx.getDefaultMaxDegreeOfParallelism(); } } return defaultValue; }

Target:
I think you need to return `taskParallelism` here b/c if the value specified as the max degree != `DEFAULT_MAX_DEGREE_OF_PARALLELISM`, then we return `1`, not, say `40`
Source:
public static boolean stopIfIsPlaying(@Nullable AudioSlide slide) { if (playing.isPresent() && playing.get().getAudioSlide().equals(slide)) { playing.get().stop(); return true; } else { return false; } }

Target:
think this has to be synchronized
Source:
public List<AggregatorFactory> getRequiredColumns() { return fields.stream() .map( input -> new CardinalityAggregatorFactory( input.getOutputName(), null, Collections.singletonList(input), byRow, round ) ).collect(Collectors.toList()); }

Target:
Line should be breaked after `)`
Source:
public Optional getRequestAttribute(final String name) { return Optional.ofNullable(this.request.getAttribute(name)); }

Target:
add the type parameter even if it's object
Source:
public static String reflogComments(List<ReflogEntry> entries) { StringBuffer b = new StringBuffer(); for (ReflogEntry e : entries) { b.append(e.getComment()).append(";"); } return b.toString(); }

Target:
this method doesn't need to be public
Source:
private static boolean validateName(String value) throws WSSecurityException { Name name; try { name = new LdapName(value); } catch (Exception e) { LOG.info("Validation of X509 Subject Name failed: {}", e.getLocalizedMessage(), e); throw new WSSecurityException(ErrorCode.FAILURE, "Not a valid X509 Subject Name."); } return name != null; }

Target:
The return value is never used.
Source:
private static SimpleFeatureCollection parseGeoJSON(InputStream in, CoordinateReferenceSystem crs) throws IOException { Map<String, Object> geojson = OM.readValue(in, TYPE_REF); in.close(); SimpleFeatureType schema = GeoJSONSchemaDetector.getSchema(geojson, crs); return GeoJSONReader2.toFeatureCollection(geojson, schema); }

Target:
Move close() to a finally-block?
Source:
private void refreshHostStorage(Guid hostId) { getBackendCollection(VdcQueryType.GetDeviceList, new GetDeviceListQueryParameters(hostId, StorageType.ISCSI, Boolean.FALSE)); }

Target:
Worth checking if we really need this method at all, although probably not in THIS patch. Regardless, why use Boolean.FALSE and not a primitive false?
Source:
public void openTestShells() { Display.syncExec(() -> { for (int i = 1; i <= TEST_SHELLS_COUNT; i++) { String shellTitle = "shell" + i; ShellTestUtils.createShell(shellTitle); shells.add(new DefaultShell(shellTitle)); } }); }

Target:
do not create new DefaultShell inside syncexec
Source:
public RangeColumnStatistics( Optional<Object> lowValue, Optional<Object> highValue, Estimate fraction, Estimate dataSize, Estimate distinctValuesCount) { this.lowValue = requireNonNull(lowValue, "lowValue can not be null"); this.highValue = requireNonNull(highValue, "highValue can not be null"); requireNonNull(fraction, "fraction can not be null"); requireNonNull(dataSize, "dataSize can not be null"); requireNonNull(distinctValuesCount, "distinctValuesCount can not be null"); this.statistics = createStatisticsMap(dataSize, fraction, distinctValuesCount); }

Target:
I do not think it should be public. IMO it should only called from `Builder`.
Source:
public void close() { log.debug("Closing record collector"); if (eosEnabled) { streamsProducer.abortTransaction(); } streamsProducer.flush(); checkForException(); }

Target:
Sounds reasonable to me
Source:
public static FileSystemContext create(ClientContext clientContext) { FileSystemContext ctx = new FileSystemContext(); ctx.init(clientContext, MasterInquireClient.Factory.create(clientContext.getClusterConf())); ctx.mUriValidationEnabled = clientContext.getUriValidationEnabled(); return ctx; }

Target:
set this in `initContext` instead?
Source:
private synchronized URI createNextResultsUri(String scheme, UriInfo uriInfo) { return uriInfo.getBaseUriBuilder().replacePath("/v1/statement").path(queryId.toString()).path(String.valueOf(resultId.incrementAndGet())).replaceQuery("").scheme(scheme).build(); }

Target:
Replace scheme first since it's first in the URL. Let's also wrap this since it's getting long: ```java return uriInfo.getBaseUriBuilder() .scheme(scheme) .replacePath("/v1/statement") .path(queryId.toString()) .path(String.valueOf(resultId.incrementAndGet())) .replaceQuery("") .build();
Source:
public void commitToFile() throws Exception { // Given afw.write(expectedContent, 0, expectedContent.length()); // When afw.commit(); // Then assertTrue(Files.size(af.toPath()) == expectedContent.length()); }

Target:
``` java assertEquals(expectedContent.length(), Files.size(af.toPath())); ```
Source:
public void setColumnWidthPercentageByPosition(int columnPosition, int width, boolean fireEvent) { this.columnWidthConfig.setPercentage(columnPosition, width); if (fireEvent) fireLayerEvent(new ColumnResizeEvent(this, columnPosition)); }

Target:
add { and }
Source:
protected void connect() throws IOException { // note that we are not connecting via JMX for testing mbeanServerConn = null; jmxc = null; ssProxy = StorageService.instance; msProxy = MessagingService.instance(); streamProxy = StreamManager.instance; compactionProxy = CompactionManager.instance; fdProxy = (FailureDetectorMBean) FailureDetector.instance; cacheService = CacheService.instance; spProxy = StorageProxy.instance; hhProxy = HintedHandOffManager.instance; gcProxy = new GCInspector(); gossProxy = Gossiper.instance; memProxy = ManagementFactory.getMemoryMXBean(); runtimeProxy = ManagementFactory.getRuntimeMXBean(); }

Target:
Don't think any method is going to throw an `IOException`. We can get rid of this.
Source:
private void sortPositions(int arrayLength, Comparator<Integer> comparator) { List<Integer> list = positions.subList(0, arrayLength); try { list.sort(comparator); } catch (IllegalArgumentException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Lambda comparator violates the comparator contract"); } }

Target:
To clarify, this does not catch the `PrestoException` thrown from comparatorResult? Do you wan to include the thrown `e` in the new `PrestoException` created here?
Source:
public void deactivate() { try { httpService.unregister(WEBAPP_ALIAS + SERVLET_NAME); } catch(IllegalArgumentException e) { logger.info("LgTv Servlet '{}' was not registered. Nothing to deactivate.", WEBAPP_ALIAS + SERVLET_NAME); } finally { logger.info("Stopped LgTv Servlet"); } }

Target:
debug
Source:
public void freeTicketWhenExists(TicketsInteractor mockedTicketsInteractor) throws RecordNotFoundException, UpdateTicketStateUnauthorizedException { long ticketId = 1; ObjectNode json = Json.newObject(); ArrayNode node = json.putArray(ConstantsManager.TICKET_IDS_FIELD_NAME); node.add(ticketId); when(mockedBody.asJson()).thenReturn(json); Result result = ticketsController.free(); assertEquals(Helpers.OK, Helpers.status(result)); verify(mockedTicketsInteractor, times(1)).freeATicket(ticketId); }

Target:
times(1) is by default in verify
Source:
private static <E> View<E> load(JobContext jobContext) { Configuration conf = Hadoop.JobContext.getConfiguration.invoke(jobContext); Class<E> type = getType(jobContext); String outputUri = conf.get(KITE_OUTPUT_URI); DefaultConfiguration.set(conf); return Datasets.<E, View<E>>load(outputUri, type); }

Target:
Should this be done in `OutputCommitter#setupTask` instead of here? This method could be called more than once, but we want to ensure we set up the environment config just one time per task. The `setupTask` methods seems like a good place, unless you have a reason to do it here?
Source:
public boolean validate(Map<String, String> optionsMap) { if (shouldSkip()) { return true; } if (!super.validate(optionsMap)) { return false; } if (!validatePrincipalLogin()) { System.err.format("Principal login test failed.%n"); return false; } return true; }

Target:
if the principal login test will already print the root cause, do we still need to print this here?
Source:
public void createEdit() { Button button = createButton(buttonparent, buttonEdit_ID, buttonEdit_caption, true); buttonBar.pack(); }

Target:
Done
Source:
public E read(String line) { try { return builder.makeRecord(parser.parseLine(line), null); } catch (IOException e) { throw new DatasetIOException("Cannot parse line: " + line, e); } }

Target:
This should probably just call `read(String line, E reuse)` and pass in `null` for `reuse` rather than duplicate the method.
Source:
public void centerOnCurrentLocation() { followMe = true; if (getMapController().getLocation() != null) { findMe(); } }

Target:
Why would this not be a part of findMe method? instead of the a wrapper? Like here where the call to getLocation happens: https://github.com/mapzen/mapzen-android-demo/blob/peter/noMoToast/src/main/java/com/mapzen/fragment/MapFragment.java#L245
Source:
public void serialize(final DoublesSketch sketch, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { generator.writeBinary(sketch.toByteArray(true)); }

Target:
JsonProcessingException is not necessary.
Source:
public String toString() { StringBuilder builder = new StringBuilder(StringUtil.simpleClassName(this)).append('['); for (MqttTopicSubscription subscription : topicSubscriptions) { builder.append(subscription).append(", "); } if (!topicSubscriptions.isEmpty()) { builder.setLength(builder.length() - 2); } return builder.append(']').toString(); }

Target:
please keep old "for loop" style to reduce GC.
Source:
private Field[] getFields(Class<?> currentClass) { final List<Field> fields = new ArrayList<>(); if (currentClass != null) { do { fields.addAll(Arrays.asList(currentClass.getDeclaredFields())); currentClass = currentClass.getSuperclass(); } while (currentClass.getSuperclass() != null); } return fields.toArray(new Field[0]); }

Target:
if you change to while (currentClass != null) you can avoid the outer if clause
Source:
public void setDecoderResult(DecoderResult decoderResult) { ObjectUtil.checkNotNull(decoderResult, "decoderResult"); this.decoderResult = decoderResult; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
protected String contentFrom(FitNesseContext context, Request request, WikiPage requestedPage) { requestData= request; return prepareResponseDocument(context).html(); }

Target:
```suggestion requestData = request; ```
Source:
public void start() { for (int i = 0; i < numProcessingQueues; i++) { processingExecutor.scheduleAtFixedRate( new SegmentChangeProcessor(segmentProcessingQueues[i]), 0, config.getCuratorCreateZkNodesRepeatDelay().getMillis(), TimeUnit.MILLISECONDS ); } }

Target:
Just wonder how high requests rate we are discussing, 1mln/s? The Coordinator balancing process will choke to halt from such amount long before the discussed queue will show a mere slight latency. I'm sure a single queue will manage the current request rate of Coordinator, besides threads don't need to call *drainTo()* as they can perfectly consume calling *queue.take()*.
Source:
protected void doc(Class c) throws IOException { open("tr class='TableRowColor'"); open("td"); around("span class='modifiers'",getModifiers(c)); close("td"); open("td"); link(c.getType()); tag("br"); around("span class='doc'", getDoc(c)); close("td"); close("tr"); }

Target:
Indentation here looks crazy! I'm thinking this might be some mismatch (between your IDE and github) in the number of spaces a tab is worth.
Source:
public ArrayList<Pair<AbstractIngredient[], Float>> lookupShapedRecipes(Item i) { if (shapedReverseLookupTable.get(i) != null) return shapedReverseLookupTable.get(i); return new ArrayList<Pair<AbstractIngredient[], Float>>(); }

Target:
internal cache, or just return null from this.
Source:
public boolean exists() { OverriddenBooleanValue overriden = null; if ( decorator != null ) { overriden = decorator.decorateExists( this, new EventMetadata( ) ); } if ( ( overriden != null ) && overriden.overrides() ) { return overriden.getResult(); } else { return provider.exists( resource ); } }

Target:
At some point we will probably need a variant of exists() that accepts an EventMetadata parameter, in case the existence decorator needs to know if a path has special properties within the scope of some package type. Not critical now.
Source:
public void startIndexPopulation( IndexPopulationJob job ) { populationJobs.add( job ); scheduler.schedule( indexPopulation, new IndexPopulationJobWrapper( job, this ) ); }

Target:
I think there is a race in `IndexingService` between `createIndexes` and `shutdown` where population jobs can be added after `IndexPopulationJobController.stop` is called. Result will be that we can leak population jobs. It might be that this is guarded for higher up in the stack. But I think this should be guarded for explicitly. Either here or in `IndexingService`.
Source:
public static int getOptionAsInteger(Map<String, String> options, String option, int defaultValue) { String value = options.get(option); return value == null ? defaultValue : Integer.valueOf(value); }

Target:
`Integer.parseInt`
Source:
public void releaseBuffer() { if (serializedCache != null) { serializedCache.release(); if (serializedCache.refCnt() == 0) { serializedCache = null; } } }

Target:
should this be thread safe ?
Source:
public Credentials.IdentityProvider getProvider() { String nativeProvider = nativeGetProvider(nativePtr); String id = identityProvider.getId(); // Sanity check - ensure nothing changed in the OS if (nativeProvider.equals(id)) { return identityProvider; } else { throw new AssertionError("The provider from the Object Store differs from the one in Realm."); } }

Target:
Good idea 👍 , but this checking should IMO be moved to `AppCredentials`. The `Os<X>` classes should generally just expose the Os interface and then we do the mapping on the "upper" layer, i.e. `AppCredentials`
Source:
private static Set<SymbolicValue> computedFrom(@Nullable SymbolicValue symbolicValue) { if (symbolicValue == null) { return Collections.emptySet(); } HashSet<SymbolicValue> result = new HashSet<>(); result.add(symbolicValue); symbolicValue.computedFrom().forEach(sv -> result.addAll(computedFrom(sv))); return result; }

Target:
minor: rely on interface rather that full type.
Source:
public ClassLoader getClassLoader() { return this.getClassLoader(); }

Target:
This method recursively calls itself, which will result in stackoverflow. Is that ok?
Source:
public Integer add(Stream<E> entities) { return delegate().add(entities.filter(entity -> { boolean permitted = isOperationPermitted(entity, Action.CREATE); if (permitted) { createAcl(entity); } return permitted; })); }

Target:
Shouldn't this throw an exception instead?
Source:
public void canIgnoreInvocationsWithJunit() throws InterruptedException { // given DelayedExecution delayedExecution = createZeroMillisDelayedExecution(); DelayedExecution twentyMillisDelayedExecution = createTwentyMillisDelayedExecution(); // when delayedExecution.allAsyncCallsStarted(); twentyMillisDelayedExecution.allAsyncCallsStarted(); // then verify(mock, timeout(50)).oneArg('1'); verify(mock, timeout(50)).oneArg('2'); }

Target:
@lukasz-szewc I'd rather propose ``` java delayedExecution.allAsyncCallsStarted(); verify(mock, timeout(50)).oneArg('1'); twentyMillisDelayedExecution.allAsyncCallsStarted(); verify(mock, timeout(50)).oneArg('2'); ``` I agree with you however the name of this test is wrong...
Source:
public final boolean isExtendedLifetimeValid() { //extended lifetime is only valid if it contains an access token if (mExtendedExpiresOn != null && !StringExtensions.IsNullOrBlank(mAccessToken)) { return !isTokenExpired(mExtendedExpiresOn); } else { return false; } }

Target:
> else { [](start = 10, length = 6) you don't need this else block.
Source:
public void sendDocumentFinalizedMessage(IWantDocument iWantDocument) { BodyMailMessage message = buildDocumentFinalizedMessage(iWantDocument); try { emailService.sendMessage(message, false); } catch (Exception e) { String errorMessage = new String("sendDocumentFinalizedMessage, Email could not be sent for IWNT edoc# " + iWantDocument.getDocumentNumber()); LOG.error(errorMessage, e); } }

Target:
Redundant String constructor.
Source:
public void addStore(PartitionId partitionId, ReplicationTest.StoreEventListener listener) { storesByPartition.computeIfAbsent(partitionId, partitionId1 -> new InMemoryStore(partitionId, infosByPartition.computeIfAbsent(partitionId1, (Function<PartitionId, List<MessageInfo>>) partitionId2 -> new ArrayList<>()), buffersByPartition.computeIfAbsent(partitionId1, (Function<PartitionId, List<ByteBuffer>>) partitionId22 -> new ArrayList<>()), listener)); }

Target:
minor: can be package private
Source:
private static long doubleToSortableLong(double value) { long bits = Double.doubleToLongBits(value); return bits ^ (bits >> 63) & Long.MAX_VALUE; }

Target:
Add clarifying parenthesis. It's easy to forget the precedence rules for `^` and `&` so that will make the code easier to reason about.
Source:
default int getGroupedJobInitializerCacheSize() { return 10; }

Target:
It's probably a bit low. I doubt GroupedJobInitializer use much memory so we could easily increase it a bit by default (like 100 maybe). Would need to check how many nodes are created after a few jobs are run in XWiki Standard. On extension side there is the root "extension" node and then 1 per namespace (so in practice 1 par wiki). It's potentially a lot more for the refactoring module since you have the root "refactoring" node and then one node for each element of each EntityReference which is manipulated.
Source:
public DefaultCompactionPolicyTest() throws InterruptedException { Pair<MockBlobStore, StoreConfig> initState = CompactionPolicyTest.initializeBlobStore(properties, time, -1, -1, DEFAULT_MAX_BLOB_SIZE); this.config = initState.getSecond(); this.blobStore = initState.getFirst(); this.mockBlobStoreStats = blobStore.getBlobStoreStats(); this.messageRetentionTimeInMs = config.storeDeletedMessageRetentionDays * Time.HoursPerDay * Time.SecsPerHour * Time.MsPerSec; this.compactionPolicy = new DefaultCompactionPolicy(config, time); }

Target:
minor: `this` qualifiers not required.
Source:
private boolean containtsOnlyValidXMLChars(String stringToValidate) { String pattern = "[^" + "\u0009\r\n" + "\u0020-\uD7FF" + "\uE000-\uFFFD" + "\ud800\udc00-\udbff\udfff" + "]"; String resultString = stringToValidate.replaceAll(pattern, ""); if (resultString.equals(stringToValidate)) { return true; } return false; }

Target:
Why not simply iterate over the array of chars and not check if `stringToValidate.contains(character)`.
Source:
public CloseableLiquibase(String changeLogFile, ResourceAccessor resourceAccessor, Database database, ManagedDataSource dataSource) throws LiquibaseException, SQLException { super(changeLogFile, resourceAccessor, database); this.dataSource = dataSource; }

Target:
It's a pity we have to change the public API, but I guess it's reasonable in this case. Let's hope not so many folks wrote custom migrations commands.
Source:
public CtfTmfLightweightContext(ArrayList<CtfIterator> iters, ListIterator<CtfIterator> pos) { fIteratorPool = iters; fCurrentIterator = pos; fTrace = iters.get(0).getCtfTmfTrace(); curLocation = new CtfLocation((Long)null); collisions = 0; }

Target:
Might as well remove these fields if they are not used. Perhaps just call the other constructor with: this(iters.get(0).getCtfTmfTrace());
Source:
public void testIsAdHocAutostart_true() throws Exception { String id = UUID.randomUUID().toString(); AdHocSubProcess adHocSubProcess = bpmn2.createAdHocSubProcess(); adHocSubProcess.setId(id); CustomElement.autoStart.of(adHocSubProcess).set(Boolean.TRUE); tested = new AdHocSubProcessPropertyReader(adHocSubProcess, definitionResolverReal.getDiagram(), definitionResolverReal); assertTrue(tested.isAdHocAutostart()); }

Target:
The Exception is never thrown.
Source:
private BroadcastTrimmer broadcastTrimmer() { return new ScheduleResolverBroadcastTrimmer( null, scheduleResolver, contentResolver, contentWriter ); }

Target:
Remove the parameter completely, the other constructor will initiate the publisher as null.
Source:
public void disconnect() throws IOException { if (forwarders != null) { for (LocalPortForwarder forwarder : forwarders) { try { forwarder.close(); } catch (IOException e) { log.warn("Error closing forwarder", e); } } } trans.disconnect(); super.disconnect(); }

Target:
clear the forwarders list after the loop?
Source:
public void close() { super.close(); if (mRefCount != null) { mRefCount.decrementAndGet(); } }

Target:
NIT: is there just a plain `decrement()`?
Source:
public static String getParameter(String key) { try { return getConfig().getString(key); } catch (NoSuchElementException e) { e.printStackTrace(); throw new NoSuchElementException("No configuration found in " + CONFIG_FILE + " for key " + key + "!"); } }

Target:
Use logger instead of `printStackTrace()` calls.
Source:
public List<Option> getOptions() { return unmodifiableList(options); }

Target:
This class should be immutable anyway so why not wrap the collection in the constructor once rather than every time it is returned to caller?
Source:
public DataInputNavigableJsonAdapter(BufferObjectDataInput input, int initialOffset) { this.input = input; this.initialOffset = initialOffset; }

Target:
Do we need to set the input position to the initial offset?
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree argument = mit.arguments().get(1); Type type = argument.symbolType(); if (type.isUnknown()) { return; } if (ExpressionsHelper.isNotSerializable(argument)) { String andParameters = JUtils.isParametrized(type) ? " and its parameters" : ""; reportIssue(argument, "Make \"" + type + "\"" + andParameters + " serializable or don't store it in the session."); } }

Target:
So it means that an argument with unknown type is considered as not serializable? Should we consider making the unknown check inside `isNotSerializable` and provide the same behavior for all rules using it? I'm saying this since the other rule (S2118) using `isNotSerializable` is also reporting an arguable issue with a similar message if we run it against an unknown type. > Make the "!Unknown!" class "Serializable" or don't write it.
Source:
public Predicate createPredicateAndJoin(String filterString, Root<T> root) { LogicalOperatorRulesLexer lexer = new LogicalOperatorRulesLexer(new ANTLRInputStream(filterString)); LogicalOperatorRulesParser parser = new LogicalOperatorRulesParser(new CommonTokenStream(lexer)); parser.addErrorListener(new OsiamAntlrErrorListener()); ParseTree tree = parser.parse(); EvalVisitor<T> visitor = new EvalVisitor<>(this, root); return (Predicate) visitor.visit(tree); }

Target:
Is this cast still necessary?
Source:
public Privilege[] getSupportedPrivileges(String path) throws PathNotFoundException, RepositoryException { return privileges.listOfSupported(); }

Target:
Remove the exceptions, since they're never thrown from the method.
Source:
protected AbstractSessionPresenter(final SessionManager sessionManager, final SessionPresenter.View view, final Optional<? extends ToolbarFactory<S>> toolbarFactory, final Optional<PaletteWidgetFactory<DefinitionSetPalette, ?>> paletteFactory, final NotificationsObserver notificationsObserver) { this.sessionManager = sessionManager; this.toolbarFactory = toolbarFactory.orElse(null); this.paletteFactory = paletteFactory.orElse(null); this.notificationsObserver = notificationsObserver; this.view = view; this.hasToolbar = true; this.hasPalette = true; }

Target:
I'd have thought preserving the use of ```Optional``` in the class's implementation would be nicer than just using ```Optional``` on the constructor and then reverting to ```null``` _inside_ the class.
Source:
public void prepareToNewMarker() { drawerLayout.closeDrawers(); setLongClickListener(true); setToastMarkerInfo(); }

Target:
czy to musi byc publiczne?
Source:
private MVCCEntry wrapMvccEntryForPut(InvocationContext ctx, Object key, CacheEntry cacheEntry, Metadata providedMetadata, boolean skipRead) { if (cacheEntry instanceof MVCCEntry) { MVCCEntry mvccEntry = (MVCCEntry) cacheEntry; updateMetadata(mvccEntry, providedMetadata); return mvccEntry; } return wrapInternalCacheEntryForPut(ctx, key, (InternalCacheEntry) cacheEntry, providedMetadata, true); }

Target:
The skipRead parameter isn't used.
Source:
public SERVICE_FAILURE_ACTIONS getFailureActions() { Pointer buffer = queryServiceConfig2(Winsvc.SERVICE_CONFIG_FAILURE_ACTIONS); SERVICE_FAILURE_ACTIONS result = new SERVICE_FAILURE_ACTIONS(buffer); result.read(); return result; }

Target:
You should make the `read()` call part of the `SERVICE_FAILURE_ACTIONS(Pointer)` constructor.
Source:
void fun(String strPath, String StrParent, String StrChild, String prefix, String suffix, java.net.URI uri) throws Exception { // Questionable: check what is done with this file new File(strPath); // Noncompliant new File(StrParent, StrChild); // Noncompliant {{Make sure this file handling is safe here.}} File parent = new File(uri); // Noncompliant new File(parent, StrChild); // compliant we rely on the fact that parent should be highlighted File.createTempFile(prefix, suffix); // Noncompliant }

Target:
I would add the other createTempFile method to enforce the fact that we explicitly target this one only.
Source:
public ValidationResult vmNotHavingPciPassthroughDevices() { for (VM vm : vms) { if (getHostDeviceManager().checkVmNeedsPciDevices(vm.getId())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_HAS_ATTACHED_PCI_HOST_DEVICES, String.format("$VmName %s", vm.getName())); } } return ValidationResult.VALID; }

Target:
I see that VmName in not included in the error message.. not sure if the right thing to do is to include it in the message or not to set it here
Source:
public void onError(Throwable e) { e.printStackTrace(); try { FileLfsServlet.sendError(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage()); context.complete(); in.close(); } catch (IOException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } }

Target:
did you want to log this exception ?
Source:
public String pop() { String value = lines.remove(lines.lastKey()); return value; }

Target:
Return could be simplified: `return lines.remove(lines.lastKey());` :)
Source:
public void onDestroyView() { mapView.onDestroy(); mapboxMap = null; unbinder.unbind(); unbinder = null; WikipediaApp.getInstance().getRefWatcher().watch(this); super.onDestroyView(); }

Target:
Shouldn't this be in onDestroy?
Source:
private static SampleTissueProcessingDto asTissueProcessingSampleDto(SampleTissueProcessing from) { SampleTissueProcessingDto dto = null; if (from.getClass() == SampleCVSlideImpl.class) { dto = asCVSlideSampleDto((SampleCVSlide) from); } else if (from.getClass() == SampleLCMTubeImpl.class) { dto = asLCMTubeSampleDto((SampleLCMTube) from); } else { dto = new SampleTissueProcessingDto(); } return dto; }

Target:
getClass comparison is required for Dtos because of the way their inheritance works (analyte is also a tissue and an identity for the purpose of including parent data), but instanceof should be used here (and typically for the non-dto models), and check vs. interfaces for flexibility. e.g. we could add another implementation of SampleCVSlide that this method should still work for, or we could subclass SampleCVSlideImpl (however unlikely)
Source:
public void testMakeTimeZone_NoOffsets() throws IOException { int[][] times = {}; int[][] offsets = {}; try { createZoneInfo(times, offsets); fail("Did not detect no transitions"); } catch (IllegalStateException expected) { // Expected this to happen } }

Target:
Unnecessary new line here and below: why leave the first line blank? (unless there's a wrap in the signature, in which case it can help to differentiate between the signature and the body).
Source:
DeploymentToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations, GroupNamingConvention.Factory namingConvention, OSImageToImage osImageToImage, RoleSizeToHardware roleSizeToHardware, Map<String, Credentials> credentialStore) { this.nodeNamingConvention = checkNotNull(namingConvention, "namingConvention").createWithoutPrefix(); this.locations = checkNotNull(locations, "locations"); this.osImageToImage = checkNotNull(osImageToImage, "osImageToImage"); this.roleSizeToHardware = checkNotNull(roleSizeToHardware, "roleSizeToHardware"); this.credentialStore = checkNotNull(credentialStore, "credentialStore cannot be null"); }

Target:
Since the constructor is package private and only the Guice injector will be able to call it, you can remove all the null checks. The injector will already fail if any parameter is missing.
Source:
public AsyncContext startAsync() throws IllegalStateException { if (_asyncNotSupportedSource != null) throw new IllegalStateException("!asyncSupported: " + _asyncNotSupportedSource); HttpChannelState state = getHttpChannelState(); if (_async == null) _async = new AsyncContextState(state); AsyncContextEvent event = new AsyncContextEvent(_context, _async, state, this, this, getResponse(), false); state.startAsync(event); return _async; }

Target:
I wonder if you shouldn't keep the old constructor here, and not use an extra boolean argument.