auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void validatePage() { String message = null; if (userText.getText().trim().length() == 0) message = Messages.CredentialsWizardPage_ErrorUser; START if (message == null && passwordText.getText().trim().length() == 0) END message = Messages.CredentialsWizardPage_ErrorPassword; setErrorMessage(message); setPageComplete(message == null); } Suggestion: Use an else-if for these two and provide the missing braces. And instead of length() == 0 I'd use isEmpty().

Target:
private void validatePage() { String message = null; if (userText.getText().trim().isEmpty()) { message = Messages.CredentialsWizardPage_ErrorUser; } else if (passwordText.getText().trim().isEmpty()) { message = Messages.CredentialsWizardPage_ErrorPassword; } setErrorMessage(message); setPageComplete(message == null); }
Source:
public boolean isSupporting(Capabilities capabilities) { return BrowserType.EDGE.equals(capabilities.getBrowserName()) || capabilities.getCapability("chromeOptions") != null || START capabilities.getCapability("goog:chromeOptions") != null; END } 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.

Target:
public boolean isSupporting(Capabilities capabilities) { return BrowserType.EDGE.equals(capabilities.getBrowserName()); }
Source:
public HistoryTreeStub getHistoryTree() { START return (HistoryTreeStub) NonNullUtils.checkNotNull(super.getSHT()); END } getSHT() can never actually be null, we should just annotate it.

Target:
public HistoryTreeStub getHistoryTree() { return (HistoryTreeStub) super.getSHT(); }
Source:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { return START Lists.newArrayList(Iterables.filter(Iterables.concat(trace.getEventAspects(), END EXTRA_ASPECTS), aspect -> aspectClass.isAssignableFrom(aspect.getClass()))); } why the newArrayList? Iterables.filter already returns an iterable.

Target:
public static Iterable<ITmfEventAspect<?>> getEventAspects(ITmfTrace trace, Class<? extends ITmfEventAspect<?>> aspectClass) { return Iterables.filter(Iterables.concat(trace.getEventAspects(), EXTRA_ASPECTS), aspect -> aspectClass.isAssignableFrom(aspect.getClass())); }
Source:
public PrestoSparkRow get() throws InterruptedException { PrestoSparkRow row; synchronized (monitor) { while (!finished && buffer.isEmpty()) { START monitor.wait(); END } if (finished) { return null; } row = buffer.poll(); } memoryManager.updateMemoryUsage(-row.getRetainedSize()); return row; } 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?

Target:
public PrestoSparkRow get() throws InterruptedException { PrestoSparkRow row = null; synchronized (monitor) { while (buffer.isEmpty() && !finished) { monitor.wait(); } if (!buffer.isEmpty()) { row = buffer.poll(); } } if (row != null) { memoryManager.updateMemoryUsage(-row.getRetainedSize()); } return row; }
Source:
private ByteBuffer parsePacketIDBAndNRB(int blockLength) throws IOException { ByteBuffer pcapPacketData; pcapPacketData = ByteBuffer.allocate(blockLength - PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); START pcapPacketData.position(PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); END pcapPacketData.clear(); SeekableByteChannel fFileChannel; try { fFileChannel = getFileChannel(); fFileChannel.read(pcapPacketData); } catch (BadPcapFileException e1) { /* Just ignore */ } pcapPacketData.flip(); return pcapPacketData; } This is useless since clear() below resets position to zero?

Target:
private ByteBuffer parsePacketIDBAndNRB(int blockLength) throws IOException { ByteBuffer pcapPacketData; pcapPacketData = ByteBuffer.allocate(blockLength - PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); pcapPacketData.clear(); SeekableByteChannel fFileChannel; try { fFileChannel = getFileChannel(); fFileChannel.read(pcapPacketData); } catch (BadPcapFileException e1) { /* Just ignore */ } pcapPacketData.flip(); return pcapPacketData; }
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)); START Actions actions = new Actions(driver); END actions.moveToElement(editButton).perform(); js.executeScript("arguments[0].querySelector(arguments[1]).click()", mostRecentComment, EDIT_BUTTON_SELECTOR); return new MiniEditorComponentObject(driver); } merge into one line

Target:
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)); new Actions(driver).moveToElement(editButton).perform(); js.executeScript("arguments[0].querySelector(arguments[1]).click()", mostRecentComment, EDIT_BUTTON_SELECTOR); return new MiniEditorComponentObject(driver); }
Source:
public String getContentAccessModeList() { String[] modeList = contentAccessModeList == null ? new String[0] : contentAccessModeList.split(","); String ammend = ""; START if (!ArrayUtils.contains(modeList, ContentAccessCertServiceAdapter.DEFAULT_CONTENT_ACCESS_MODE)) { END ammend = modeList.length > 0 ? "," : ""; ammend += ContentAccessCertServiceAdapter.DEFAULT_CONTENT_ACCESS_MODE; } return modeList.length > 0 ? this.contentAccessModeList + ammend : ammend; } @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.

Target:
public String getContentAccessModeList() { return this.contentAccessModeList; }
Source:
public void setUp() { START System.setProperty("user.timezone", "UTC"); END TimeZone.setDefault(null); configuration = Configuration.DEFAULT; } @timowest weird. I remembered it was failed with testing on querydls-sql module. but it's gone now.

Target:
public void setUp() { configuration = Configuration.DEFAULT; }
Source:
public void onDestroyView() { mWebViewStateOnDestroyView = new Bundle(); try { storeWebView(mWebViewStateOnDestroyView); START mWebViewBridge.destroy(); END } catch (Exception exp) { Log.w(TAG, exp.getMessage() + "", exp); } super.onDestroyView(); } mWebViewStateOnDestroyViewを追加せずに mWebViewBridge.destroy(); のあとにmWebViewBridge =null; で解決すると思います

Target:
public void onDestroyView() { try { mWebViewBridge.destroy(); } catch (Exception exp) { Log.w(TAG, exp.getMessage() + "", exp); } mWebViewBridge = null; super.onDestroyView(); }
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 START Logger.get(GlueHiveMetastore.class).warn(e, "Failed to delete path: " + path.toString()); END } } 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)

Target:
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 log.warn(e, "Failed to delete path: " + path.toString()); } }
Source:
START private boolean isNakedTD1Key(String s) END { return NAKED_TD1_KEY_PATTERN.matcher(s).matches(); } `private static`

Target:
private static boolean isNakedTD1Key(String s) { return NAKED_TD1_KEY_PATTERN.matcher(s).matches(); }
Source:
public long skip(long n) throws IOException { if (n <= 0) { return 0; } if (n > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } else { START ((Seekable) in).seek(mPos + n); END } mPos += n; return n; } nit: for readability i prefer a method called `isSequentialReadMode` to determine whether to seek or not

Target:
public long skip(long n) throws IOException { if (n <= 0) { return 0; } if (n > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } mPos += n; return n; }
Source:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { START Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); END 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); } Missing assertNotNull for executionSet here.

Target:
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); assertNotNull(emptySubprocess.getExecutionSet()); assertStartEventSlaDueDate(emptySubprocess.getExecutionSet(), EMPTY_VALUE); }
Source:
private List<Window> fetchWindowsInQueue() { List<Window> windows = Lists.newArrayList(getWindows()); START return ImmutableList.copyOf(Lists.reverse(windows)); END } Remove the reversal here, and let the JDK 8 implementation return it in reverse, and the JDK 9 implementation *not* reversed.

Target:
private List<Window> fetchWindowsInQueue() { return ImmutableList.copyOf(getWindows()); }
Source:
protected void executeCommand(IDeviceManagementInteractor executor) throws DeploymentException { START try { executor.startFB(resource, new FBDeploymentData("", resFB)); //$NON-NLS-1$ //TODO correctly determine prefix } catch (DeploymentException e) { throw e; } END } what is the point of catching the exception here?

Target:
protected void executeCommand(IDeviceManagementInteractor executor) throws DeploymentException { executor.startFB(resource, new FBDeploymentData("", resFB)); //$NON-NLS-1$ //TODO correctly determine prefix }
Source:
START void setReaderBudget() END { reader.setResultSizeBudget(ariaBatchRows <= MIN_BATCH_ROWS ? UNLIMITED_BUDGET : targetResultBytes); } Make this method private.

Target:
private void setReaderBudget() { reader.setResultSizeBudget(ariaBatchRows <= MIN_BATCH_ROWS ? UNLIMITED_BUDGET : targetResultBytes); }
Source:
START default <T> Flux<SearchHit<T>> find(Query query, Class<T> entityType) { END return find(query, entityType, entityType); } Same as with the imperative template: Shouldn't we just deprecate these methods and introduce `Flux<SearchHit<T>> search(…)`?

Target:
default <T> Flux<T> find(Query query, Class<T> entityType) { return find(query, entityType, entityType); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { RepositorySearchWizard wizard = new RepositorySearchWizard( util.getConfiguredRepositories(), START false); END 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; } True, now.

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { RepositorySearchWizard wizard = new RepositorySearchWizard( util.getConfiguredRepositories(), true); 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; }
Source:
public Map<String, String> load() { final Map<String, String> preferences = new HashMap<String, String>(); START final String property = System.getProperty( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED ); END log.info( "Setting preference '" + GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED + "' to '" + property + "'." ); preferences.put( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED, property ); return preferences; } We normally check if this is `null` and only set if non-null... IDK if your code handles `null` differently?

Target:
public Map<String, String> load() { final Map<String, String> preferences = new HashMap<String, String>(); final String property = getProperty(); log.info( "Setting preference '" + GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED + "' to '" + property + "'." ); preferences.put( GuidedDecisionTableEditorService.DTABLE_VERIFICATION_ENABLED, property ); return preferences; }
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) { START taskParallelism = ctx.getDefaultMaxDegreeOfParallelism(); END } } return defaultValue; } 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`

Target:
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 taskParallelism; } return defaultValue; }
Source:
START public static boolean stopIfIsPlaying(@Nullable AudioSlide slide) { END if (playing.isPresent() && playing.get().getAudioSlide().equals(slide)) { playing.get().stop(); return true; } else { return false; } } think this has to be synchronized

Target:
public synchronized static boolean stopIfIsPlaying(@Nullable AudioSlide slide) { if (playing.isPresent() && playing.get().getAudioSlide().equals(slide)) { playing.get().stop(); return true; } else { return false; } }
Source:
public List<AggregatorFactory> getRequiredColumns() { return fields.stream() .map( input -> new CardinalityAggregatorFactory( input.getOutputName(), null, Collections.singletonList(input), byRow, round ) START ).collect(Collectors.toList()); END } Line should be breaked after `)`

Target:
public List<AggregatorFactory> getRequiredColumns() { return fields.stream() .map( field -> new CardinalityAggregatorFactory( field.getOutputName(), null, Collections.singletonList(field), byRow, round ) ) .collect(Collectors.toList()); }
Source:
START public Optional getRequestAttribute(final String name) { END return Optional.ofNullable(this.request.getAttribute(name)); } add the type parameter even if it's object

Target:
public Optional<Object> getRequestAttribute(final String name) { return Optional.ofNullable(this.request.getAttribute(name)); }
Source:
START public static String reflogComments(List<ReflogEntry> entries) { END StringBuffer b = new StringBuffer(); for (ReflogEntry e : entries) { b.append(e.getComment()).append(";"); } return b.toString(); } this method doesn't need to be public

Target:
private static String reflogComments(List<ReflogEntry> entries) { StringBuffer b = new StringBuffer(); for (ReflogEntry e : entries) { b.append(e.getComment()).append(";"); } return b.toString(); }
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."); } START return name != null; END } The return value is never used.

Target:
private static void 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."); } }
Source:
private static SimpleFeatureCollection parseGeoJSON(InputStream in, CoordinateReferenceSystem crs) throws IOException { Map<String, Object> geojson = OM.readValue(in, TYPE_REF); START in.close(); END SimpleFeatureType schema = GeoJSONSchemaDetector.getSchema(geojson, crs); return GeoJSONReader2.toFeatureCollection(geojson, schema); } Move close() to a finally-block?

Target:
private static SimpleFeatureCollection parseGeoJSON(InputStream in, CoordinateReferenceSystem crs) throws IOException { Map<String, Object> geojson = OM.readValue(in, TYPE_REF); SimpleFeatureType schema = GeoJSONSchemaDetector.getSchema(geojson, crs); return GeoJSONReader2.toFeatureCollection(geojson, schema); }
Source:
private void refreshHostStorage(Guid hostId) { getBackendCollection(VdcQueryType.GetDeviceList, new GetDeviceListQueryParameters(hostId, StorageType.ISCSI, Boolean.FALSE)); START } END 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?

Target:
private void refreshHostStorage(Guid hostId) { getBackendCollection(VdcQueryType.GetDeviceList, new GetDeviceListQueryParameters(hostId, StorageType.ISCSI, false, null)); }
Source:
public void openTestShells() { Display.syncExec(() -> { for (int i = 1; i <= TEST_SHELLS_COUNT; i++) { String shellTitle = "shell" + i; ShellTestUtils.createShell(shellTitle); START shells.add(new DefaultShell(shellTitle)); END } }); } do not create new DefaultShell inside syncexec

Target:
public void openTestShells() { for (int i = 1; i <= TEST_SHELLS_COUNT; i++) { String shellTitle = "shell" + i; Display.syncExec(() -> { ShellTestUtils.createShell(shellTitle); }); shells.add(new DefaultShell(shellTitle)); } }
Source:
START public RangeColumnStatistics( END 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); } I do not think it should be public. IMO it should only called from `Builder`.

Target:
private 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"); this.fraction = requireNonNull(fraction, "fraction can not be null"); this.dataSize = requireNonNull(dataSize, "dataSize can not be null"); this.distinctValuesCount = requireNonNull(distinctValuesCount, "distinctValuesCount can not be null"); }
Source:
public void close() { log.debug("Closing record collector"); if (eosEnabled) { streamsProducer.abortTransaction(); } START streamsProducer.flush(); END checkForException(); } Sounds reasonable to me

Target:
public void close() { log.debug("Closing record collector"); if (eosEnabled) { streamsProducer.abortTransaction(); } checkForException(); }
Source:
public static FileSystemContext create(ClientContext clientContext) { FileSystemContext ctx = new FileSystemContext(); ctx.init(clientContext, MasterInquireClient.Factory.create(clientContext.getClusterConf())); START ctx.mUriValidationEnabled = clientContext.getUriValidationEnabled(); END return ctx; } set this in `initContext` instead?

Target:
public static FileSystemContext create(ClientContext clientContext) { FileSystemContext ctx = new FileSystemContext(); ctx.init(clientContext, MasterInquireClient.Factory.create(clientContext.getClusterConf())); return ctx; }
Source:
private synchronized URI createNextResultsUri(String scheme, UriInfo uriInfo) { START return uriInfo.getBaseUriBuilder().replacePath("/v1/statement").path(queryId.toString()).path(String.valueOf(resultId.incrementAndGet())).replaceQuery("").scheme(scheme).build(); END } 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();

Target:
private synchronized URI createNextResultsUri(String scheme, UriInfo uriInfo) { 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 START assertTrue(Files.size(af.toPath()) == expectedContent.length()); END } ``` java assertEquals(expectedContent.length(), Files.size(af.toPath())); ```

Target:
public void commitToFile() throws Exception { // Given afw.write(expectedContent, 0, expectedContent.length()); // When afw.commit(); // Then assertEquals(expectedContent.length(), Files.size(af.toPath())); }
Source:
public void setColumnWidthPercentageByPosition(int columnPosition, int width, boolean fireEvent) { this.columnWidthConfig.setPercentage(columnPosition, width); if START (fireEvent) END fireLayerEvent(new ColumnResizeEvent(this, columnPosition)); } add { and }

Target:
public void setColumnWidthPercentageByPosition(int columnPosition, int width, boolean fireEvent) { this.columnWidthConfig.setPercentage(columnPosition, width); if (fireEvent){ fireLayerEvent(new ColumnResizeEvent(this, columnPosition)); } }
Source:
START protected void connect() throws IOException END { // 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(); } Don't think any method is going to throw an `IOException`. We can get rid of this.

Target:
protected void connect() { // 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(); }
Source:
private void sortPositions(int arrayLength, Comparator<Integer> comparator) { List<Integer> list = positions.subList(0, arrayLength); try { list.sort(comparator); } catch (IllegalArgumentException e) { START throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Lambda comparator violates the comparator contract"); END } } 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?

Target:
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", e); } }
Source:
public void deactivate() { try { httpService.unregister(WEBAPP_ALIAS + SERVLET_NAME); } catch(IllegalArgumentException e) { START logger.info("LgTv Servlet '{}' was not registered. Nothing to deactivate.", WEBAPP_ALIAS + SERVLET_NAME); END } finally { logger.info("Stopped LgTv Servlet"); } } debug

Target:
public void deactivate() { try { httpService.unregister(WEBAPP_ALIAS + SERVLET_NAME); } catch(IllegalArgumentException e) { logger.debug("LgTv Servlet '{}' was not registered. Nothing to deactivate.", WEBAPP_ALIAS + SERVLET_NAME); } finally { logger.info("Stopped LgTv Servlet"); } }
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)); START verify(mockedTicketsInteractor, times(1)).freeATicket(ticketId); END } times(1) is by default in verify

Target:
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).freeATicket(ticketId); }
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); START DefaultConfiguration.set(conf); END return Datasets.<E, View<E>>load(outputUri, type); } 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?

Target:
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); return Datasets.<E, View<E>>load(outputUri, type); }
Source:
public boolean validate(Map<String, String> optionsMap) { if (shouldSkip()) { return true; } if (!super.validate(optionsMap)) { return false; } if (!validatePrincipalLogin()) { START System.err.format("Principal login test failed.%n"); END return false; } return true; } if the principal login test will already print the root cause, do we still need to print this here?

Target:
public boolean validate(Map<String, String> optionsMap) { if (!super.validate(optionsMap)) { return false; } if (!validatePrincipalLogin()) { return false; } return true; }
Source:
START public void createEdit() { END Button button = createButton(buttonparent, buttonEdit_ID, buttonEdit_caption, true); buttonBar.pack(); } Done

Target:
private void createEdit() { Button button = createButton(buttonparent, buttonEdit_ID, buttonEdit_caption, true); buttonBar.pack(); }
Source:
START public E read(String line) { END try { return builder.makeRecord(parser.parseLine(line), null); } catch (IOException e) { throw new DatasetIOException("Cannot parse line: " + line, e); } } This should probably just call `read(String line, E reuse)` and pass in `null` for `reuse` rather than duplicate the method.

Target:
public E read(String line) { return read(line, null); }
Source:
public void centerOnCurrentLocation() { followMe = true; START if (getMapController().getLocation() != null) { END findMe(); } } 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

Target:
public void centerOnCurrentLocation() { followMe = true; findMe(); }
Source:
public void serialize(final DoublesSketch sketch, final JsonGenerator generator, final SerializerProvider provider) START throws IOException, JsonProcessingException END { generator.writeBinary(sketch.toByteArray(true)); } JsonProcessingException is not necessary.

Target:
public void serialize(final DoublesSketch sketch, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeBinary(sketch.toByteArray(true)); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(StringUtil.simpleClassName(this)).append('['); START for (MqttTopicSubscription subscription : topicSubscriptions) { END builder.append(subscription).append(", "); } if (!topicSubscriptions.isEmpty()) { builder.setLength(builder.length() - 2); } return builder.append(']').toString(); } please keep old "for loop" style to reduce GC.

Target:
public String toString() { StringBuilder builder = new StringBuilder(StringUtil.simpleClassName(this)).append('['); for (int i = 0; i < topicSubscriptions.size(); i++) { builder.append(topicSubscriptions.get(i)).append(", "); } if (!topicSubscriptions.isEmpty()) { builder.setLength(builder.length() - 2); } return builder.append(']').toString(); }
Source:
private Field[] getFields(Class<?> currentClass) { final List<Field> fields = new ArrayList<>(); START if (currentClass != null) { do { END fields.addAll(Arrays.asList(currentClass.getDeclaredFields())); currentClass = currentClass.getSuperclass(); } while (currentClass.getSuperclass() != null); } return fields.toArray(new Field[0]); } if you change to while (currentClass != null) you can avoid the outer if clause

Target:
private Field[] getFields(Class<?> currentClass) { final List<Field> fields = new ArrayList<>(); while (currentClass != null) { fields.addAll(Arrays.asList(currentClass.getDeclaredFields())); currentClass = currentClass.getSuperclass(); } return fields.toArray(new Field[0]); }
Source:
public void setDecoderResult(DecoderResult decoderResult) { ObjectUtil.checkNotNull(decoderResult, "decoderResult"); START this.decoderResult = decoderResult; END } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public void setDecoderResult(DecoderResult decoderResult) { this.decoderResult = ObjectUtil.checkNotNull(decoderResult, "decoderResult"); }
Source:
protected String contentFrom(FitNesseContext context, Request request, WikiPage requestedPage) { START requestData= request; END return prepareResponseDocument(context).html(); } ```suggestion requestData = request; ```

Target:
protected String contentFrom(FitNesseContext context, Request request, WikiPage requestedPage) { return prepareResponseDocument(context).html(request); }
Source:
public void start() { for (int i = 0; i < numProcessingQueues; i++) { processingExecutor.scheduleAtFixedRate( new SegmentChangeProcessor(segmentProcessingQueues[i]), 0, START config.getCuratorCreateZkNodesRepeatDelay().getMillis(), END TimeUnit.MILLISECONDS ); } } 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()*.

Target:
public void start() { }
Source:
START protected void doc(Class c) throws IOException { END 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"); } 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.

Target:
private 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"); }
Source:
public ArrayList<Pair<AbstractIngredient[], Float>> lookupShapedRecipes(Item i) { if (shapedReverseLookupTable.get(i) != null) return shapedReverseLookupTable.get(i); START return new ArrayList<Pair<AbstractIngredient[], Float>>(); END } internal cache, or just return null from this.

Target:
public List<Pair<AbstractIngredient[], Float>> lookupShapedRecipes(Item i) { return shapedReverseLookupTable.get(i); }
Source:
public boolean exists() { OverriddenBooleanValue overriden = null; if ( decorator != null ) { START overriden = decorator.decorateExists( this, new EventMetadata( ) ); END } if ( ( overriden != null ) && overriden.overrides() ) { return overriden.getResult(); } else { return provider.exists( resource ); } } 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.

Target:
public boolean exists() { return exists( new EventMetadata() ); }
Source:
public void startIndexPopulation( IndexPopulationJob job ) { populationJobs.add( job ); START scheduler.schedule( indexPopulation, new IndexPopulationJobWrapper( job, this ) ); END } 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`.

Target:
void startIndexPopulation( IndexPopulationJob job ) { populationJobs.add( job ); scheduler.schedule( indexPopulation, new IndexPopulationJobWrapper( job, this ) ); }
Source:
public static int getOptionAsInteger(Map<String, String> options, String option, int defaultValue) { String value = options.get(option); START return value == null ? defaultValue : Integer.valueOf(value); END } `Integer.parseInt`

Target:
public static int getOptionAsInteger(Map<String, String> options, String option, int defaultValue) { String value = options.get(option); return value == null ? defaultValue : Integer.parseInt(value); }
Source:
public void releaseBuffer() { if (serializedCache != null) { serializedCache.release(); START if (serializedCache.refCnt() == 0) { END serializedCache = null; } } } should this be thread safe ?

Target:
public synchronized void releaseBuffer() { if (serializedCache != null) { serializedCache.release(); if (serializedCache.refCnt() == 0) { serializedCache = null; } } }
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 { START throw new AssertionError("The provider from the Object Store differs from the one in Realm."); END } } 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`

Target:
public String getProvider() { return nativeGetProvider(nativePtr); }
Source:
private static Set<SymbolicValue> computedFrom(@Nullable SymbolicValue symbolicValue) { if (symbolicValue == null) { return Collections.emptySet(); } START HashSet<SymbolicValue> result = new HashSet<>(); END result.add(symbolicValue); symbolicValue.computedFrom().forEach(sv -> result.addAll(computedFrom(sv))); return result; } minor: rely on interface rather that full type.

Target:
private static Set<SymbolicValue> computedFrom(@Nullable SymbolicValue symbolicValue) { if (symbolicValue == null) { return Collections.emptySet(); } Set<SymbolicValue> result = new HashSet<>(); result.add(symbolicValue); symbolicValue.computedFrom().forEach(sv -> result.addAll(computedFrom(sv))); return result; }
Source:
public ClassLoader getClassLoader() { START return this.getClassLoader(); END } This method recursively calls itself, which will result in stackoverflow. Is that ok?

Target:
public ClassLoader getClassLoader() { return this.getClass().getClassLoader(); }
Source:
public Integer add(Stream<E> entities) { return delegate().add(entities.filter(entity -> { START boolean permitted = isOperationPermitted(entity, Action.CREATE); END if (permitted) { createAcl(entity); } return permitted; })); } Shouldn't this throw an exception instead?

Target:
public Integer add(Stream<E> entities) { return delegate().add(entities.filter(entity -> { //throws exception if no permission on the containing package isOperationPermitted(entity, Action.CREATE); createAcl(entity); return true; })); }
Source:
public void canIgnoreInvocationsWithJunit() throws InterruptedException { // given DelayedExecution delayedExecution = createZeroMillisDelayedExecution(); DelayedExecution twentyMillisDelayedExecution = createTwentyMillisDelayedExecution(); // when delayedExecution.allAsyncCallsStarted(); START twentyMillisDelayedExecution.allAsyncCallsStarted(); END // then verify(mock, timeout(50)).oneArg('1'); verify(mock, timeout(50)).oneArg('2'); } @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...

Target:
public void canIgnoreInvocationsWithJunit() throws InterruptedException { // given DelayedExecution delayedExecution = createZeroMillisDelayedExecution(); DelayedExecution twentyMillisDelayedExecution = createTwentyMillisDelayedExecution(); // when delayedExecution.allAsyncCallsStarted(); // then verify(mock, timeout(50)).oneArg('1'); // when twentyMillisDelayedExecution.allAsyncCallsStarted(); // then verify(mock, timeout(50)).oneArg('2'); }
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); START } else { END return false; } } > else { [](start = 10, length = 6) you don't need this else block.

Target:
public final boolean isExtendedLifetimeValid() { //extended lifetime is only valid if it contains an access token if (mExtendedExpiresOn != null && !StringExtensions.IsNullOrBlank(mAccessToken)) { return !isTokenExpired(mExtendedExpiresOn); } return false; }
Source:
public void sendDocumentFinalizedMessage(IWantDocument iWantDocument) { BodyMailMessage message = buildDocumentFinalizedMessage(iWantDocument); try { emailService.sendMessage(message, false); } catch (Exception e) { START String errorMessage = new String("sendDocumentFinalizedMessage, Email could not be sent for IWNT edoc# " + iWantDocument.getDocumentNumber()); END LOG.error(errorMessage, e); } } Redundant String constructor.

Target:
public void sendDocumentFinalizedMessage(IWantDocument iWantDocument) { BodyMailMessage message = buildDocumentFinalizedMessage(iWantDocument); try { emailService.sendMessage(message, false); } catch (Exception e) { LOG.error(("sendDocumentFinalizedMessage, Email could not be sent for IWNT edoc# " + iWantDocument.getDocumentNumber()), e); } }
Source:
START public void addStore(PartitionId partitionId, ReplicationTest.StoreEventListener listener) { END 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)); } minor: can be package private

Target:
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)); }
Source:
private static long doubleToSortableLong(double value) { long bits = Double.doubleToLongBits(value); START return bits ^ (bits >> 63) & Long.MAX_VALUE; END } Add clarifying parenthesis. It's easy to forget the precedence rules for `^` and `&` so that will make the code easier to reason about.

Target:
private static long doubleToSortableLong(double value) { long bits = Double.doubleToLongBits(value); return bits ^ ((bits >> 63) & Long.MAX_VALUE); }
Source:
default int getGroupedJobInitializerCacheSize() { START return 10; END } 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.

Target:
default int getGroupedJobInitializerCacheSize() { return 100; }
Source:
public DefaultCompactionPolicyTest() throws InterruptedException { Pair<MockBlobStore, StoreConfig> initState = CompactionPolicyTest.initializeBlobStore(properties, time, -1, -1, DEFAULT_MAX_BLOB_SIZE); START this.config = initState.getSecond(); END this.blobStore = initState.getFirst(); this.mockBlobStoreStats = blobStore.getBlobStoreStats(); this.messageRetentionTimeInMs = config.storeDeletedMessageRetentionDays * Time.HoursPerDay * Time.SecsPerHour * Time.MsPerSec; this.compactionPolicy = new DefaultCompactionPolicy(config, time); } minor: `this` qualifiers not required.

Target:
public DefaultCompactionPolicyTest() throws InterruptedException { Pair<MockBlobStore, StoreConfig> initState = CompactionPolicyTest.initializeBlobStore(properties, time, -1, -1, DEFAULT_MAX_BLOB_SIZE); config = initState.getSecond(); blobStore = initState.getFirst(); mockBlobStoreStats = blobStore.getBlobStoreStats(); messageRetentionTimeInMs = config.storeDeletedMessageRetentionDays * Time.HoursPerDay * Time.SecsPerHour * Time.MsPerSec; compactionPolicy = new DefaultCompactionPolicy(config, time); }
Source:
private boolean containtsOnlyValidXMLChars(String stringToValidate) { START String pattern = "[^" END + "\u0009\r\n" + "\u0020-\uD7FF" + "\uE000-\uFFFD" + "\ud800\udc00-\udbff\udfff" + "]"; String resultString = stringToValidate.replaceAll(pattern, ""); if (resultString.equals(stringToValidate)) { return true; } return false; } Why not simply iterate over the array of chars and not check if `stringToValidate.contains(character)`.

Target:
private boolean containtsOnlyValidXMLChars(String stringToValidate) { String pattern = "[^" + "\u0009\r\n" + "\u0020-\uD7FF" + "\uE000-\uFFFD" + "\ud800\udc00-\udbff\udfff" + "]"; String resultString = stringToValidate.replaceAll(pattern, ""); return resultString.equals(stringToValidate); }
Source:
START public CloseableLiquibase(String changeLogFile, ResourceAccessor resourceAccessor, Database database, ManagedDataSource dataSource) throws LiquibaseException, SQLException { END super(changeLogFile, resourceAccessor, database); this.dataSource = dataSource; } 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.

Target:
CloseableLiquibase( String changeLogFile, ResourceAccessor resourceAccessor, Database database, ManagedDataSource dataSource ) throws LiquibaseException, SQLException { super(changeLogFile, resourceAccessor, database); this.dataSource = dataSource; }
Source:
public CtfTmfLightweightContext(ArrayList<CtfIterator> iters, ListIterator<CtfIterator> pos) { fIteratorPool = iters; START fCurrentIterator = pos; END fTrace = iters.get(0).getCtfTmfTrace(); curLocation = new CtfLocation((Long)null); collisions = 0; } Might as well remove these fields if they are not used. Perhaps just call the other constructor with: this(iters.get(0).getCtfTmfTrace());

Target:
public CtfTmfLightweightContext(ArrayList<CtfIterator> iters, ListIterator<CtfIterator> pos) { fTrace = iters.get(0).getCtfTmfTrace(); curLocation = new CtfLocation((Long) null); }
Source:
START public void testIsAdHocAutostart_true() throws Exception { END 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()); } The Exception is never thrown.

Target:
public void testIsAdHocAutostart_true() { 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()); }
Source:
private BroadcastTrimmer broadcastTrimmer() { return new ScheduleResolverBroadcastTrimmer( START null, END scheduleResolver, contentResolver, contentWriter ); } Remove the parameter completely, the other constructor will initiate the publisher as null.

Target:
private BroadcastTrimmer broadcastTrimmer() { return new ScheduleResolverBroadcastTrimmer( scheduleResolver, contentResolver, contentWriter ); }
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); } START } END } trans.disconnect(); super.disconnect(); } clear the forwarders list after the loop?

Target:
public void disconnect() throws IOException { for (LocalPortForwarder forwarder : forwarders) { try { forwarder.close(); } catch (IOException e) { log.warn("Error closing forwarder", e); } } forwarders.clear(); trans.disconnect(); super.disconnect(); }
Source:
public void close() { super.close(); if (mRefCount != null) { START mRefCount.decrementAndGet(); END } } NIT: is there just a plain `decrement()`?

Target:
public void close() { super.close(); mRefCount.decrementAndGet(); }
Source:
public static String getParameter(String key) { try { return getConfig().getString(key); } catch (NoSuchElementException e) { START e.printStackTrace(); END throw new NoSuchElementException("No configuration found in " + CONFIG_FILE + " for key " + key + "!"); } } Use logger instead of `printStackTrace()` calls.

Target:
public static String getParameter(String key) { try { return getConfig().getString(key); } catch (NoSuchElementException e) { throw new NoSuchElementException("No configuration found in " + CONFIG_FILE + " for key " + key + "!"); } }
Source:
public List<Option> getOptions() { START return unmodifiableList(options); END } 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?

Target:
public List<Option> getOptions() { return options; }