auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SubversionSCMSource(String id, String remoteBase, String credentialsId, String includes, String excludes) { super(id); this.remoteBase = StringUtils.removeEnd(remoteBase, "/") + "/"; setCredentialsId(credentialsId); setIncludes(StringUtils.defaultIfEmpty(includes, DescriptorImpl.DEFAULT_INCLUDES)); setExcludes(StringUtils.defaultIfEmpty(excludes, DescriptorImpl.DEFAULT_EXCLUDES)); START this.additionalCredentials = new ArrayList<AdditionalCredentials>(); END } Usage of this collection is ineffective if you do not plan to modify it on the flight. Use `Collections.emptyList()` instead in the code

Target:
public SubversionSCMSource(String id, String remoteBase, String credentialsId, String includes, String excludes) { super(id); this.remoteBase = StringUtils.removeEnd(remoteBase, "/") + "/"; setCredentialsId(credentialsId); setIncludes(StringUtils.defaultIfEmpty(includes, DescriptorImpl.DEFAULT_INCLUDES)); setExcludes(StringUtils.defaultIfEmpty(excludes, DescriptorImpl.DEFAULT_EXCLUDES)); }
Source:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this.provider = START new RemotableSVNAuthenticationBuilderProvider(credentials, Collections.<String, Credentials>emptyMap(), /* TODO */ TaskListener.NULL); END } Better to use the `this()` invocation of the constructor below

Target:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this(credentials, null, /* TODO */ TaskListener.NULL); }
Source:
private static WebDriverElement createWebDriverElement(Hook hook, WebElement element, WebDriver driver) throws CandybeanException { try { if ("select".equals(element.getTagName())) { return new WebDriverSelector(hook, driver); } return new WebDriverElement(hook, 0, driver, element); } catch (CandybeanException e) { START throw e; END } } Why do we even need the catch if all it does is re-throw exactly the same exception?

Target:
private static WebDriverElement createWebDriverElement(Hook hook, WebElement element, WebDriver driver) throws CandybeanException { if ("select".equals(element.getTagName())) { return new WebDriverSelector(hook, driver); } return new WebDriverElement(hook, 0, driver, element); }
Source:
private static WebElement findElement(Hook hook, WebDriver driver) throws CandybeanException { try { return driver.findElement(getBy(hook)); START } catch (NoSuchElementException e) { END throw e; } catch (WebDriverException e) { throw e; } } Since these catch blocks have the same body and we're using Java 7, let's user the multi-catch syntax: } catch(NoSuchElementException|WebDriverException e {

Target:
private static WebElement findElement(Hook hook, WebDriver driver) throws CandybeanException { try { return driver.findElement(getBy(hook)); } catch (WebDriverException e) { throw e; } }
Source:
public static ExpectedCondition<WebDriverElement> present(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return createWebDriverElement(hook, element, driver); START } catch (CandybeanException e) { END return null; } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; } Let's use multi-catch here.

Target:
public static ExpectedCondition<WebDriverElement> present(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return createWebDriverElement(hook, element, driver); } catch (CandybeanException | StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }
Source:
public static void first() throws Exception { String candybeanConfigStr = System.getProperty("candybean_config"); START if (candybeanConfigStr == null) candybeanConfigStr = AbstractTest.CONFIG_DIR.getCanonicalPath() + File.separator + "candybean.config"; END System.out.println("candybeanConfigPath: " + candybeanConfigStr); Configuration candybeanConfig = new Configuration(new File(Utils.adjustPath(candybeanConfigStr))); candybean = Candybean.getInstance(candybeanConfig); iface = candybean.getInterface(); iface.start(); } The reason it was named CB was so it'd be short when statically referenced. But, either way -- no biggie...

Target:
public static void first() throws Exception { String candybeanConfigStr = System.getProperty("candybean_config"); if (candybeanConfigStr == null) candybeanConfigStr = Candybean.CONFIG_DIR.getCanonicalPath() + File.separator + "candybean.config"; System.out.println("candybeanConfigPath: " + candybeanConfigStr); Configuration candybeanConfig = new Configuration(new File(Utils.adjustPath(candybeanConfigStr))); candybean = Candybean.getInstance(candybeanConfig); iface = candybean.getInterface(); iface.start(); }
Source:
public List<Player> getNonreadyPlayers() { List<Player> result = new LinkedList<>(); result.addAll(lobbyPlayers); result.removeAll(readyPlayers); START result.sort(Comparator.comparing(Player:: getName)); END return result; } I'm not sure the sorting should be in `ArenaImpl`. The reason `getNonreadyPlayers()` returns a List rather than a Set is likely because of its original call site in the `notready` command, where it is fed to a utility method that stringifies a List. So it's probably past laziness more than anything :P I think it makes more sense to do the sorting at the caller site rather than in here. If nothing else, it reduces the blast radius of the pull request and keeps the changes "collected" in the signs/rendering code.

Target:
public List<Player> getNonreadyPlayers() { List<Player> result = new LinkedList<>(); result.addAll(lobbyPlayers); result.removeAll(readyPlayers); return result; }
Source:
public RosActivity(String notificationTicker, String notificationTitle) { START super(); END rosActivityComponent = new RosActivityComponent(this, notificationTicker, notificationTitle, new RosActivityEventsHandler()); } I don't think this is necessary.

Target:
public RosActivity(String notificationTicker, String notificationTitle) { rosActivityComponent = new RosActivityComponent(this, notificationTicker, notificationTitle, new RosActivityEventsHandler()); }
Source:
public Vector3 toCameraFrame(int pixelX, int pixelY) { START double centeredX = pixelX - viewport.getWidth() / 2.0d; END double centeredY = viewport.getHeight() / 2.0d - pixelY; return getCameraToScreenTransform().invert().apply(new Vector3(centeredX, centeredY, 0)); } can both be final.

Target:
public Vector3 toCameraFrame(int pixelX, int pixelY) { final double centeredX = pixelX - viewport.getWidth() / 2.0d; final double centeredY = viewport.getHeight() / 2.0d - pixelY; return getCameraToScreenTransform().invert().apply(new Vector3(centeredX, centeredY, 0)); }
Source:
public void jumpToFrame(GraphName frame) { synchronized (mutex) { this.frame = frame; START double scale = cameraToRosTransform.getScale(); END resetTransform(); cameraToRosTransform = cameraToRosTransform.scale(scale / cameraToRosTransform.getScale()); } } final?

Target:
public void jumpToFrame(GraphName frame) { synchronized (mutex) { this.frame = frame; final double scale = cameraToRosTransform.getScale(); resetTransform(); cameraToRosTransform = cameraToRosTransform.scale(scale / cameraToRosTransform.getScale()); } }
Source:
public static long crc32(String data) { if (data == null) { return -1; } try { // get bytes from string byte bytes[] = data.getBytes("UTF-8"); Checksum checksum = new CRC32(); // update the current checksum with the specified array of bytes checksum.update(bytes, 0, bytes.length); // get the current checksum value return checksum.getValue(); } catch (UnsupportedEncodingException e) { START return -1; END } } Should we catch that exception here ? or pass it along ? I am sure there is a very thin chance this will happen. But in any case. Also, can we just do a default data.getBytes() if UTF-8 fails on UnsupportedEncodingException ?

Target:
public static long crc32(String data) { if (data == null) { return -1; } try { // get bytes from string byte bytes[] = data.getBytes("UTF-8"); Checksum checksum = new CRC32(); // update the current checksum with the specified array of bytes checksum.update(bytes, 0, bytes.length); // get the current checksum value return checksum.getValue(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
private void mergeProperties(Properties properties, Map<String, String> configurationMap) { if (properties != null) { START for (final String name : properties.stringPropertyNames()) END if (!configurationMap.containsKey(name)) { configurationMap.put(name, properties.getProperty(name)); } } } Please add braces surrounding the for loop block. Otherwise this is confusing to read.

Target:
private static void mergeProperties(Properties properties, Map<String, String> configurationMap) { if (properties != null) { for (final String name : properties.stringPropertyNames()) { if (!configurationMap.containsKey(name)) { configurationMap.put(name, properties.getProperty(name)); } } } }
Source:
public String getAccessToken() throws PayPalRESTException { START if (accessToken == null) { END accessToken = generateAccessToken(); } else if ((accessToken != null) && (expiresIn() <= 0)) { accessToken = generateAccessToken(); } return accessToken; } Can we refactor both of this if else if into one condition ? ``` java if (!accessToken || (accessToken && expiresIn() <= 0)) { accessToken = generateAccessToken(); } ```

Target:
public String getAccessToken() throws PayPalRESTException { if (accessToken == null || expiresIn() <= 0) { accessToken = generateAccessToken(); } return accessToken; }
Source:
private double[] getPercentages(List<Double> tBreaks, List<Bucket> buckets, int nvalues, int numClasses) { Map<Double, Integer> values = new HashMap<>(); for (Bucket b : buckets) { values.put(b.getMin(), b.getCount()); } ClassPercentagesManager percentagesManager = new ClassPercentagesManager(); START return percentagesManager.getPercentages(values, tBreaks, nvalues, numClasses); END } Both histogram based natural breaks and quantiles percentage calculation require counting portions of buckets in a given set of ranges, that do not necessarily match the buckets limits. So why are the two using two different methods to compute the results?

Target:
private double[] getPercentages(List<Double> tBreaks, List<Bucket> buckets, int nvalues, int numClasses) { ClassPercentagesManager percentagesManager = new ClassPercentagesManager(); return percentagesManager.getPercentages(buckets, tBreaks, numClasses); }
Source:
private Double getOverlappingPercentages(double cMin, double cMax, double bMin, double bMax) { if (cMin > bMax || cMax < bMin) { return 0.0; } double regionMin = Math.max(cMin, bMin); double regionMax = Math.min(cMax, bMax); double dividend = regionMax - regionMin; double divider = bMax - bMin; START if (dividend == divider) END return 1.0; else return dividend / divider; } But why not check explicitly for zero? This is opaque, it seems like you're trying to optimize away a division.

Target:
private Double getOverlappingPercentages(double cMin, double cMax, double bMin, double bMax) { if (cMin > bMax || cMax < bMin) { return 0.0; } double regionMin = Math.max(cMin, bMin); double regionMax = Math.min(cMax, bMax); double dividend = regionMax - regionMin; double divider = bMax - bMin; if (divider == 0.0) { // bucket min and max are equal, handling 0 divider case if (dividend == 0.0) { return 1.0; } else return 0.0; } else return dividend / divider; }
Source:
public boolean getOnlyCreateReportWithDifferentName() { START return this.onlyCreateReportWithDifferentName; END } This will need a null check done to make sure the default is returned if the field isn't set (i.e. is null). See `getEscapeUnderscores` for an example although obviously the default return will be different :)

Target:
public boolean getOnlyCreateReportWithDifferentName() { if (this.onlyCreateReportWithDifferentName == null) { return false; } else { return this.onlyCreateReportWithDifferentName; } }
Source:
START public final Object getAbstractBuildOwner(Run build, Class targetClass) { END return build instanceof AbstractBuild ? (AbstractBuild) build : null; } It can/should be private (and remove `@Restricted(NoExternalUse.class)`).

Target:
private final Object getAbstractBuildOwner(Run build, Class targetClass) { return build instanceof AbstractBuild ? (AbstractBuild) build : null; }
Source:
START protected static WebDriver getCurrentBrowser() { END return b.getCurrentWebDriver(); } Are you sure that "protected static" is ok? To me it doesn't make sense as you can't override static methods.

Target:
protected WebDriver getCurrentBrowser() { return b.getCurrentWebDriver(); }
Source:
public Batch getNextEmptyBatch() throws InterruptedException { synchronized(availableBatches) { if (availableBatches.isEmpty()) { START availableBatches.wait(); END Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } } https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28%29 synchronization error

Target:
public Batch getNextEmptyBatch() throws InterruptedException { synchronized(availableBatches) { while (availableBatches.isEmpty()) { availableBatches.wait(); } Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } }
Source:
public int read() throws IOException { streamPos++; START return 0; END } Seems a bit harsh, I'm guessing the TIFF reader never does a single byte read call?

Target:
public int read() throws IOException { byte[] b = new byte[1]; read(b, 0, 1); return b[0]; }
Source:
public static String printCommentTree(List<CommentTreeElement> cs) { START String buffer = ""; END for (CommentTreeElement c : cs) { buffer += printCommentTree(c, 0); } return buffer; } can you use instead of string concatenation a StringBuilder?

Target:
public static String printCommentTree(List<CommentTreeElement> cs) { StringBuilder builder = new StringBuilder(); for (CommentTreeElement c : cs) { builder.append(printCommentTree(c, 0)); } return builder.toString(); }
Source:
public UserInfo about(String username) throws ActionFailedException { // Send GET request to get the account overview START if(username == "[deleted]") END throw new ActionFailedException("There is no information associated with the username [deleted]"); JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null).getResponseObject(); JSONObject data = (JSONObject) object.get("data"); // Init account info wrapper return data != null ? new UserInfo(data) : null; } can you add curly brackets to the if statement? it good practice so you don't end up with weird bugs in the future

Target:
public UserInfo about(String username) throws ActionFailedException { // Send GET request to get the account overview if(username.equals("[deleted]")) { throw new ActionFailedException("There is no information associated with the username [deleted]"); } JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null).getResponseObject(); JSONObject data = (JSONObject) object.get("data"); // Init account info wrapper return data != null ? new UserInfo(data) : null; }
Source:
public FlairActions(RestClient restClient) { this.restClient = restClient; START this.user = null; END } if you don't specify the **this.user = null**, it will be null when the class is instantianciated, so this line is redundant

Target:
public FlairActions(RestClient restClient) { this.restClient = restClient; }
Source:
public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (!player.hasPlayedBefore()) { START for (Object map : kits.getKits().keySet()) { END Kit kit = kits.getKits().get(map); if (CommandBook.inst().hasPermission(player, "commandbook.kits.onfirstlogin."+map)) { kit.distribute(player); } } } } Do an EntrySet, iterating through Map.Entry<String, Kit>

Target:
public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (!player.hasPlayedBefore()) { for (Entry<String, Kit> map : kits.getKits().entrySet()) { if (CommandBook.inst().hasPermission(player, "commandbook.kits.onfirstlogin." + map)) { map.getValue().distribute(player); } } } }
Source:
START protected boolean isTokenRequest(final HttpServletRequest request) { END return CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.artifactParameterName, this.safeParameters)); } this class is final so these should be private

Target:
private boolean isTokenRequest(final HttpServletRequest request) { return CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.artifactParameterName, this.safeParameters)); }
Source:
START protected boolean isBackChannelLogoutRequest(final HttpServletRequest request) { END return "POST".equals(request.getMethod()) && !isMultipartRequest(request) && CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters)); } this should be private also

Target:
private boolean isBackChannelLogoutRequest(final HttpServletRequest request) { return "POST".equals(request.getMethod()) && !isMultipartRequest(request) && CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters)); }
Source:
private String retrieveParameterValueFromServletContextConfiguration(final FilterConfig filterConfig, final String propertyName) { START final String value2 = filterConfig.getServletContext().getInitParameter(propertyName); END if (CommonUtils.isNotBlank(value2)) { logger.info("Property loaded from ServletContext.getInitParameter with value [{}]", propertyName, value2); return value2; } return null; } This could be `value` instead of `value2` here...

Target:
private String retrieveParameterValueFromServletContextConfiguration(final FilterConfig filterConfig, final String propertyName) { final String value = filterConfig.getServletContext().getInitParameter(propertyName); if (CommonUtils.isNotBlank(value)) { logger.info("Property loaded from ServletContext.getInitParameter with value [{}]", propertyName, value); return value; } return null; }
Source:
public CifsTelnetConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); START ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); END ConnectionValidator.assertNotNewStyleWindowsDomain(username, CIFS_PROTOCOL, cifsConnectionType); // Make sure that we're properly cleaned up by setting the connected state. connected(); } static imports

Target:
public CifsTelnetConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper); }
Source:
public CifsWinRmConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); START ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); END ConnectionValidator.assertNotOldStyleWindowsDomain(username, CIFS_PROTOCOL, cifsConnectionType); } static imports

Target:
public CifsWinRmConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper); }
Source:
public CifsWinrsConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); START ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); END ConnectionValidator.assetNotThroughJumpstation(mapper, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assertNoSingleQuoteInPassword(password, CIFS_PROTOCOL, cifsConnectionType); this.options = options; } static imports

Target:
public CifsWinrsConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper); }
Source:
public void connect() { connection = new WinrsConnection(options, mapper, workingDirectory); connection.connectToWinrsProxy(options); START if (connection.getWinrsProxyConnection().getHostOperatingSystem() != WINDOWS) { END connection.disconnectFromWinrsProxy(); throw new IllegalArgumentException(format("Cannot create a " + CIFS_PROTOCOL + ":%s connection with a winrs proxy that is not running Windows", cifsConnectionType.toString().toLowerCase())); } connected(); } Why first the connect, then the check and disconnect?

Target:
public void connect() { super.connect(); }
Source:
private synchronized void drainQueueForRequests() { START final PrefetchRecordsRetrieved recordsToDeliver = (PrefetchRecordsRetrieved) peekNextResult(); END // If there is an event available to drain and if there is at least one demand, // then schedule it for delivery if (publisherSession.hasDemandToPublish() && canDispatchRecord(recordsToDeliver)) { subscriber.onNext(recordsToDeliver.prepareForPublish()); recordsToDeliver.dispatched(); lastEventDeliveryTime = Instant.now(); } } let's update peekNextResult() to return PrefetchRecordsRetrieved type, so no need to typecast here.

Target:
synchronized void drainQueueForRequests() { final PrefetchRecordsRetrieved recordsToDeliver = peekNextResult(); // If there is an event available to drain and if there is at least one demand, // then schedule it for delivery if (publisherSession.hasDemandToPublish() && canDispatchRecord(recordsToDeliver)) { subscriber.onNext(recordsToDeliver.prepareForPublish()); recordsToDeliver.dispatched(); lastEventDeliveryTime = Instant.now(); } }
Source:
START LeaseCoordinator(ILeaseManager<T> leaseManager, END String workerIdentifier, long leaseDurationMillis, long epsilonMillis, int maxLeasesForWorker, int maxLeasesToStealAtOneTime, int maxLeaseRenewerThreadCount, IMetricsFactory metricsFactory) { this(leaseManager, getDefaultLeaseSelector(), workerIdentifier, leaseDurationMillis, epsilonMillis, maxLeasesForWorker, maxLeasesToStealAtOneTime, maxLeaseRenewerThreadCount, metricsFactory); } The `public` can't be removed. This class is a public class, this would be a breaking change.

Target:
public LeaseCoordinator(ILeaseManager<T> leaseManager, String workerIdentifier, long leaseDurationMillis, long epsilonMillis, int maxLeasesForWorker, int maxLeasesToStealAtOneTime, int maxLeaseRenewerThreadCount, IMetricsFactory metricsFactory) { this(leaseManager, getDefaultLeaseSelector(), workerIdentifier, leaseDurationMillis, epsilonMillis, maxLeasesForWorker, maxLeasesToStealAtOneTime, maxLeaseRenewerThreadCount, metricsFactory); }
Source:
START @Override public synchronized Boolean isLeader(String workerId) { END // if no leaders yet, synchronously get leaders. This will happen at first Shard Sync. if (executeConditionCheckWithReadLock(() -> CollectionUtils.isNullOrEmpty(leaders))) { electLeaders(); // start a scheduled executor that will periodically update leaders. // The first run will be after a minute. // We don't need jitter since it is scheduled with a fixed delay and time taken to scan leases // will be different at different times and on different hosts/workers. leaderElectionThreadPool.scheduleWithFixedDelay(this::electLeaders, ELECTION_INITIAL_DELAY_MILLIS, ELECTION_SCHEDULING_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); } return executeConditionCheckWithReadLock(() -> isWorkerLeaderForShardSync(workerId)); } Nit: could you make sure `@Override` is in the line above the method. And also could you make sure all annotations in the PR are in the line above.

Target:
public synchronized Boolean isLeader(String workerId) { // if no leaders yet, synchronously get leaders. This will happen at first Shard Sync. if (executeConditionCheckWithReadLock(() -> CollectionUtils.isNullOrEmpty(leaders))) { electLeaders(); // start a scheduled executor that will periodically update leaders. // The first run will be after a minute. // We don't need jitter since it is scheduled with a fixed delay and time taken to scan leases // will be different at different times and on different hosts/workers. leaderElectionThreadPool.scheduleWithFixedDelay(this::electLeaders, ELECTION_INITIAL_DELAY_MILLIS, ELECTION_SCHEDULING_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); } return executeConditionCheckWithReadLock(() -> isWorkerLeaderForShardSync(workerId)); }
Source:
public final void testExecutorStateEventWithCustomHandler() { ExecutorStateEvent event = new ExecutorStateEvent(executor, leaseCoordinator); event.accept(customHandler); assertTrue(wasCustomHandlerInvoked); START wasCustomHandlerInvoked = false; END } Not sure why this statement is the last statement. It doesn't seem to do anything.

Target:
public void testExecutorStateEventWithCustomHandler() { ExecutorStateEvent event = new ExecutorStateEvent(executor, leaseCoordinator); event.accept(customHandler); assertTrue(wasCustomHandlerInvoked); }
Source:
public ShardConsumer(RecordsPublisher recordsPublisher, ExecutorService executorService, ShardInfo shardInfo, Optional<Long> logWarningForTaskAfterMillis, ShardConsumerArgument shardConsumerArgument, TaskExecutionListener taskExecutionListener) { this(recordsPublisher, executorService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, START taskExecutionListener, ConsumerStates.INITIAL_STATE, END ShardConsumer.metricsWrappingFunction(shardConsumerArgument.metricsFactory()), 8); } Is there a reason for changing the order for the chained constructor? If not could you add the new parameter to the end of the list.

Target:
public ShardConsumer(RecordsPublisher recordsPublisher, ExecutorService executorService, ShardInfo shardInfo, Optional<Long> logWarningForTaskAfterMillis, ShardConsumerArgument shardConsumerArgument, TaskExecutionListener taskExecutionListener) { this(recordsPublisher, executorService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, ConsumerStates.INITIAL_STATE, ShardConsumer.metricsWrappingFunction(shardConsumerArgument.metricsFactory()), 8, taskExecutionListener); }
Source:
private void callShutdownOnStrategy() { if (!getRecordsRetrievalStrategy.isShutdown()) { getRecordsRetrievalStrategy.shutdown(); } START isShutdown = true; END } Where is this changed to true to trigger shutdown.

Target:
private void callShutdownOnStrategy() { if (!getRecordsRetrievalStrategy.isShutdown()) { getRecordsRetrievalStrategy.shutdown(); } }
Source:
public NSDictionary searchTargetNSDict(NSDictionary rootDict, CoffeeName targetName) { final NSArray itemNSArray = (NSArray) (rootDict .objectForKey(ITEM_ARRAY)); NSDictionary resultDict = null; for (NSObject item : itemNSArray.getArray()) { final NSDictionary dict = (NSDictionary) item; final String itemName = NSDictionaryHelper.stringForKey(dict, CoffeeName.ITEM_NAME); START if (!TextUtils.equals(targetName.getCoffeeName(), itemName)) { END // mCoffeeNameと異なる場合は次へ continue; } resultDict = dict; } return resultDict; } ``` if (TextUtils.equals(targetName.getCoffeeName(), itemName)) { return dict; } ``` で良さそうな気がする！ TextUtilsってクラスは知らなかった！！便利そうだね。

Target:
public NSDictionary searchTargetNSDict(NSDictionary rootDict, CoffeeName targetName) { final NSArray itemNSArray = (NSArray) (rootDict .objectForKey(ITEM_ARRAY)); NSDictionary resultDict = null; for (NSObject item : itemNSArray.getArray()) { final NSDictionary dict = (NSDictionary) item; final String itemName = NSDictionaryHelper.stringForKey(dict, CoffeeName.ITEM_NAME); if (TextUtils.equals(targetName.getCoffeeName(), itemName)) { return dict; } } return resultDict; }
Source:
START public PrinterDto create(@RequestBody PrinterDto dto) throws Exception { END Printer printer = Dtos.to(dto); return get(printerService.create(printer)); } It looks like this should still only throw `IOException`?

Target:
public PrinterDto create(@RequestBody PrinterDto dto) throws IOException { Printer printer = Dtos.to(dto); return get(printerService.create(printer)); }
Source:
public static String docsVersion() { if (Version.VERSION.matches("^\\d*\\.\\d*\\.\\d*$")) { //FIXME once we know how readthedocs handles version tags START return Version.VERSION; END } else { return "latest"; } } It seems like it'll build versions that match our tag names, like "v0.2.190" and create a "stable" version for our most recent release, and "latest" pointing to current develop branch. Probably safest to just return "latest" for now so we know it won't be a broken link in the next release though?

Target:
public static String docsVersion() { //FIXME once we know how readthedocs handles version tags // if (Version.VERSION.matches("^\\d*\\.\\d*\\.\\d*$")) { // return Version.VERSION; // } else { return "latest"; // } }
Source:
protected void applyChanges(IndexFamily to, IndexFamily from) throws IOException { to.setName(from.getName()); START to.setFake(from.hasFakeSequence()); END to.setUniqueDualIndex(from.isUniqueDualIndex()); to.setArchived(from.getArchived()); } I'm not sure it's safe to change between fake and non-fake sequences. I'm having trouble working through it in my mind.

Target:
protected void applyChanges(IndexFamily to, IndexFamily from) throws IOException { to.setName(from.getName()); to.setUniqueDualIndex(from.isUniqueDualIndex()); to.setArchived(from.getArchived()); }
Source:
public static TissuePieceType to(@Nonnull TissuePieceTypeDto from) { TissuePieceType to = new TissuePieceType(); if (from.getId() != null) to.setId(from.getId()); setString(to::setName, from.getName()); setString(to::setAbbreviation, from.getAbbreviation()); START setBoolean(to::setArchived, from.isArchived(), true); END return to; } last parameter should be false (`TissuePieceType#archived` isn't nullable)

Target:
public static TissuePieceType to(@Nonnull TissuePieceTypeDto from) { TissuePieceType to = new TissuePieceType(); if (from.getId() != null) to.setId(from.getId()); setString(to::setName, from.getName()); setString(to::setAbbreviation, from.getAbbreviation()); setBoolean(to::setArchived, from.isArchived(), false); return to; }
Source:
START public static String truncate(String index, int shortestLength) { END return index.substring(0, shortestLength); } These 3 methods should be private, or if useful outside of this controller, they should be in a utilities class

Target:
private static String truncate(String index, int shortestLength) { return index.substring(0, shortestLength); }
Source:
public @ResponseBody List<ExperimentDto> list() throws IOException { Collection<Experiment> experiments = experimentService.list(); START return experiments.stream().map(expt -> Dtos.asDto(expt)).collect(Collectors.toList()); END } You've made changes similar to this in a few places... If your compiler was complaining, you might want to update your Java version. I was previously using a version that had a similar bug too

Target:
public @ResponseBody List<ExperimentDto> list() throws IOException { Collection<Experiment> experiments = experimentService.list(); return experiments.stream().map(Dtos::asDto).collect(Collectors.toList()); }
Source:
public @ResponseBody BoxDto removeMultipleItems(@PathVariable long boxId, @RequestBody List<String> positions) throws IOException { Box box = getBox(boxId); for (String position : positions) { START box.getBoxPositions().remove(position); END } boxService.save(box); return getBoxDtoWithBoxables(boxId); } Could you add a check that there is an item in the position before removing it? (I selected a column that had a few blank positions and clicked "discard selected" and it returned `Internal Server Error: No item in the specified box position` and when I closed the dialog the page didn't refresh so it looked like nothing had happened, but when I manually refreshed the page it turned out that the selected items had actually been discarded)

Target:
public @ResponseBody BoxDto removeMultipleItems(@PathVariable long boxId, @RequestBody List<String> positions) throws IOException { Box box = getBox(boxId); for (String position : positions) { if (box.getBoxPositions().containsKey(position)) { box.getBoxPositions().remove(position); } } boxService.save(box); return getBoxDtoWithBoxables(boxId); }
Source:
public String propertyForUserName(Criteria item, boolean creator) { item.createAlias("creator", "creator"); START item.createAlias("lastModifier", "lastModifier"); END return creator ? "creator.loginName" : "lastModifier.loginName"; } Add "creator" and "lastModifier" to the `STANDARD_ALIASES` list at the top of this class. These get added to all the criteria used in PaginatedDataSource

Target:
public String propertyForUserName(Criteria item, boolean creator) { return creator ? "creator.loginName" : "lastModifier.loginName"; }
Source:
public DilutionDto updateDilution(@PathVariable Long dilutionId, @RequestBody DilutionDto dilutionDto) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } LibraryDilution dilution = Dtos.to(dilutionDto); START dilution.setCreator(securityStore.getUserByFullName(dilutionDto.getDilutionUserName())); END dilution.setId(dilutionId); dilutionService.update(dilution); return getDilution(dilutionId); } Since the creator isn't modifiable, it doesn't need to be loaded from the database for an `update`. (It'll already be fully loaded in the `managed` dilution [here](https://github.com/TGAC/miso-lims/blob/a14d30993b704f603a5ebc27cb0d6fc07d6d3000/miso-service/src/main/java/uk/ac/bbsrc/tgac/miso/service/impl/DefaultLibraryDilutionService.java#L166) ).

Target:
public DilutionDto updateDilution(@PathVariable Long dilutionId, @RequestBody DilutionDto dilutionDto) throws IOException { if (dilutionDto == null) { log.error( "Received null dilutionDto from front end; cannot convert to Dilution. Something likely went wrong in the JS DTO conversion."); throw new RestException("Cannot convert null to Dilution", Status.BAD_REQUEST); } LibraryDilution dilution = Dtos.to(dilutionDto); dilution.setId(dilutionId); dilutionService.update(dilution); return getDilution(dilutionId); }
Source:
START public String clickLinkButtonAndGetUrl(String linkText) { END WebElement button = getDriver().findElement(By.linkText(linkText)); WebElement html = getHtmlElement(); button.click(); waitForPageRefresh(html); return getCurrentUrl(); } Should be `protected`. Knowledge of link text belongs in Page model classes. A Page class should expose an `addDilution()` method rather than `clickLinkButtonAndGetUrl("Add")`.

Target:
protected String clickLinkButtonAndGetUrl(String linkText) { WebElement button = getDriver().findElement(By.linkText(linkText)); WebElement html = getHtmlElement(); button.click(); waitForPageRefresh(html); return getCurrentUrl(); }
Source:
protected void clickOk() { WebElement okButton = getDriver().findElement(By.id("ok")); START if (okButton != null) { END okButton.click(); } else { throw new IllegalArgumentException("Ok button is not available to click"); } } `WebDriver#findElement` will throw `NoSuchElementException` if the element doesn't exist, so it will never be null here. You could use `AbstractElement#findElementIfExists` to get the element or null, but it makes more sense to remove the null check and allow `NoSuchElementException` to be thrown Same in `clickCancel` below

Target:
protected void clickOk() { WebElement okButton = getDriver().findElement(By.id("ok")); okButton.click(); }
Source:
public PoolPickerResponse getPickersBySearch(@RequestParam("platform") String platform, @RequestParam("query") String query) throws IOException { PlatformType platformType = PlatformType.get(platform); return getPoolPickerWithFilters(100, START PaginationFilter.platformType(platformType), END PaginationFilter.query(query)); } It might make sense to have this support the usual search using `PaginationFilter.parse`, but I'm indifferent.

Target:
public PoolPickerResponse getPickersBySearch(@RequestParam("platform") String platform, @RequestParam("query") String query) throws IOException { return getPoolPickerWithFilters(100, PaginationFilter.platformType(PlatformType.valueOf(platform)), PaginationFilter.query(query)); }
Source:
START public Long getId() { END return boxId; } I get changing all the `UNSAVED_ID` constants to primitive, but why change getters to `Long` object when the field is still a primitive? It just necessitates a lot of boxing/unboxing

Target:
public long getId() { return boxId; }
Source:
START public void setText(String input, WebElement element) { END element.click(); element.clear(); element.sendKeys(input); element.sendKeys(Keys.ESCAPE); } This and the below methods should be `protected` rather than `public` so that they can only be accessed by subclasses

Target:
protected void setText(String input, WebElement element) { element.click(); element.clear(); element.sendKeys(input); element.sendKeys(Keys.ESCAPE); }
Source:
public boolean shouldRerun() { START return !dto.getHealthType().isDone() && Duration.between(created, Instant.now()).toMinutes() < 10; END } Is this necessary with the scheduler hard-coded to scan every 15 minutes? If so, should this be greater than instead of less than?

Target:
public boolean shouldRerun() { return !dto.getHealthType().isDone() && Duration.between(created, Instant.now()).toMinutes() > 10; }
Source:
public void deleteBox(Box box) throws IOException { authorizationManager.throwIfNotWritable(box); if (boxStore != null) { if (!boxStore.remove(box)) { throw new IOException("Unable to delete box."); } } else { START throw new IOException("No boxStore available. Check that it has been declared in the Spring config."); END } } Could you please remove the checks for boxStore != null ? The lack of this particular cruft is one of my favourite parts of the services.

Target:
public void deleteBox(Box box) throws IOException { authorizationManager.throwIfNotWritable(box); if (!boxStore.remove(box)) { throw new IOException("Unable to delete box."); } }
Source:
public Map<String, Integer> getColumnSizes() throws IOException { if (boxStore != null) { return boxStore.getBoxColumnSizes(); } else { START throw new IOException("No boxStore available. Check that it has been declared in the Spring config."); END } } Sacre bleu, what is thees? How on earth could you mees such a sweet little succulent RequestManager holdover? https://giphy.com/gifs/hannibal-nbc-su-zakana-3m29WMD6BNss

Target:
public Map<String, Integer> getColumnSizes() throws IOException { return boxStore.getBoxColumnSizes(); }
Source:
public PoolDto createPool(@RequestBody PoolDto pool, UriComponentsBuilder uriBuilder, HttpServletResponse response) throws IOException { Long id = poolService.savePool(Dtos.to(pool)); START UriComponents uriComponents = uriBuilder.path("/{id}").buildAndExpand(id); END response.setHeader("Location", uriComponents.toUri().toString()); return getPoolById(id); } `"/pool/{id}"`?

Target:
public PoolDto createPool(@RequestBody PoolDto pool, UriComponentsBuilder uriBuilder, HttpServletResponse response) throws IOException { Long id = poolService.savePool(Dtos.to(pool)); return getPoolById(id); }
Source:
public void testListAllLibraryTypes() throws Exception { List<LibraryType> libraryTypes = dao.listAllLibraryTypes(); START assertTrue(libraryTypes.size() > 0); END } It would be ideal to clear and repopulate the LibraryType table in the V9000 test data migration. Then it's easier to test against an exact controlled number of LibraryTypes, rather than making the tests more lenient. Same with LibrarySelectionType below

Target:
public void testListAllLibraryTypes() throws Exception { List<LibraryType> libraryTypes = dao.listAllLibraryTypes(); assertEquals(10, libraryTypes.size()); }
Source:
public void testListAllLibrarySelectionTypes() throws Exception { List<LibrarySelectionType> librarySelectionTypes = dao.listAllLibrarySelectionTypes(); START assertTrue(librarySelectionTypes.size() > 0); END } missed one

Target:
public void testListAllLibrarySelectionTypes() throws Exception { List<LibrarySelectionType> librarySelectionTypes = dao.listAllLibrarySelectionTypes(); assertEquals(2, librarySelectionTypes.size()); }
Source:
public void writeUrls(URI baseUri) { setUrl(WritableUrls.buildUriPath(baseUri, "/rest/tree/sample/{id}", getId())); setUpdatedByUrl(WritableUrls.buildUriPath(baseUri, "/rest/user/{id}", getUpdatedById())); if (getRootSampleClassId() != null) { setRootSampleClassUrl(WritableUrls.buildUriPath(baseUri, "/rest/sampleclass/{id}", getRootSampleClassId())); } START setUrl(WritableUrls.buildUriPath(baseUri, "/rest/sample/{id}", getId())); END } setUrl already called above with different path

Target:
public void writeUrls(URI baseUri) { setUrl(WritableUrls.buildUriPath(baseUri, "/rest/tree/sample/{id}", getId())); setUpdatedByUrl(WritableUrls.buildUriPath(baseUri, "/rest/user/{id}", getUpdatedById())); if (getRootSampleClassId() != null) { setRootSampleClassUrl(WritableUrls.buildUriPath(baseUri, "/rest/sampleclass/{id}", getRootSampleClassId())); } }
Source:
private void loadChildEntities(LibraryDilution dilution) throws IOException { if (dilution.getLibrary() != null) { dilution.setLibrary(libraryDao.get(dilution.getLibrary().getId())); } START if (dilution.getTargetedSequencing() != null && dilution.getTargetedSequencing().getId() != null) { END dilution.setTargetedSequencing(targetedSequencingDao.get(dilution.getTargetedSequencing().getId())); } } Is there a reason the targeted sequencing is set and its id isn't? Seems like something an exception should be thrown for

Target:
private void loadChildEntities(LibraryDilution dilution) throws IOException { if (dilution.getLibrary() != null) { dilution.setLibrary(libraryDao.get(dilution.getLibrary().getId())); } if (dilution.getTargetedSequencing() != null) { dilution.setTargetedSequencing(targetedSequencingDao.get(dilution.getTargetedSequencing().getId())); } }
Source:
public void addQc(Library library, LibraryQC qc) throws IOException { Library managed = libraryDao.get(library.getId()); authorizationManager.throwIfNotWritable(managed); qc.setQcCreator(authorizationManager.getCurrentUsername()); // update concentration if QC is of relevant type START if ("QuBit".equals(qc.getQcType().getName())) { END managed.setInitialConcentration(qc.getResults()); } libraryQcDao.save(qc); libraryDao.save(library); } Would be better if there were a field in the QcType table to indicate purpose=concentration rather than hard-coding something that may or may not exist in the DB. Maybe this is okay temporarily

Target:
public void addQc(Library library, LibraryQC qc) throws IOException { Library managed = libraryDao.get(library.getId()); authorizationManager.throwIfNotWritable(managed); qc.setQcCreator(authorizationManager.getCurrentUsername()); // TODO: update concentration if QC is of relevant type libraryQcDao.save(qc); libraryDao.save(library); }
Source:
public void setLibraryAliasGenerator(NameGenerator<Library> generator) { START this.libraryAliasGenerator = (DefaultLibraryAliasGenerator) generator; END } Remove cast

Target:
public void setLibraryAliasGenerator(NameGenerator<Library> generator) { this.libraryAliasGenerator = generator; }
Source:
public DetailedSampleBuilder(User user) { if (user != null) { securityProfile = new SecurityProfile(user); START getSecurityProfile().getProfileId(); END } } remove line

Target:
public DetailedSampleBuilder(User user) { if (user != null) { securityProfile = new SecurityProfile(user); } }
Source:
public long save(LibraryDilution dilution) throws IOException { long id; START if (dilution.getId() == AbstractLibrary.UNSAVED_ID) { END id = (long) currentSession().save(dilution); } else { currentSession().update(dilution); id = dilution.getId(); } return id; } It's probably the same, but shouldn't be comparing dilution's ID to AbstractLibrary's

Target:
public long save(LibraryDilution dilution) throws IOException { long id; if (dilution.getId() == LibraryDilution.UNSAVED_ID) { id = (long) currentSession().save(dilution); } else { currentSession().update(dilution); id = dilution.getId(); } return id; }
Source:
public boolean isDeletable() { START return printerId == UNSAVED_ID; END } It's only deletable if it's not saved?

Target:
public boolean isDeletable() { return printerId != UNSAVED_ID; }
Source:
public void setDefaultProjectDao() { HibernateProjectDao dao = new HibernateProjectDao(); dao.setJdbcTemplate(jdbcTemplate); dao.setSecurityManager(securityManager); START dao.setSecurityProfileDAO(securityProfileDao); END dao.setNamingScheme(getNamingScheme()); dao.setDataObjectFactory(dataObjectFactory); dao.setReferenceGenomeDao(referenceGenomeDao); setProjectDao(dao); } Compilation errors here.

Target:
public void setDefaultProjectDao() { HibernateProjectDao dao = new HibernateProjectDao(); dao.setJdbcTemplate(jdbcTemplate); setProjectDao(dao); }
Source:
public SequencerReference get(long id) throws IOException { SequencerReference sr = (SequencerReference) currentSession().get(SequencerReferenceImpl.class, id); SequencerReference preUpgradeSR = getByUpgradedReference(id); if (preUpgradeSR != null) { START sr.setPreUpgradeSequencerReference(preUpgradeSR); END } return sr; } Consider making this relationship unidirectional instead of having to look up the preUpgradeSequencerReference. It is usually not useful anyway (only on edit sequencer page I'd think)

Target:
public SequencerReference get(long id) throws IOException { return (SequencerReference) currentSession().get(SequencerReferenceImpl.class, id); }
Source:
public void setIpAddress(String ip) { if (ip == null) { this.ip = null; } else { try { InetAddress inet = InetAddress.getByName(ip); this.ip = (inet != null ? inet.getHostAddress() : null); } catch (IOException e) { log.error("Error getting InetAddress from given ip " + ip, e); START this.ip = null; END } } } rethrow as IllegalArgumentException

Target:
public void setIpAddress(String ip) { if (ip == null) { this.ip = null; } else { try { InetAddress inet = InetAddress.getByName(ip); this.ip = (inet != null ? inet.getHostAddress() : null); } catch (IOException e) { log.error("Error getting InetAddress from given ip " + ip, e); throw new IllegalArgumentException("Error getting InetAddress from given ip " + ip, e); } } }
Source:
public int hashCode() { return new HashCodeBuilder(5, 35) .append(alias) .append(description) .append(progress) START .append(referenceGenome.getId()) END .append(shortName) .toHashCode(); } Potential NPE. Also won't be useful when the ID is not set (such as during migration). Could just append the ReferenceGenome object here, and then base ReferenceGenome's hashCode on the alias (which is a unique key also)

Target:
public int hashCode() { return new HashCodeBuilder(5, 35) .append(alias) .append(description) .append(progress) .append(referenceGenome) .append(shortName) .toHashCode(); }
Source:
private void updateProjectDaoDependencies() { if (studyDao != null) studyDao.setProjectDAO(projectDao); if (sampleNumberPerProjectService != null) sampleNumberPerProjectService.setSqlProjectDAO(projectDao); START if (referenceGenomeService != null) referenceGenomeService.setReferenceGenomeDao(referenceGenomeDao); END } This method is for updating other objects' dependencies on the Project DAO, so this doesn't belong here. There should be an `updateReferenceGenomeDaoDependencies` method which sets the referenceGenomeDao for projectDao and referenceGenomeService

Target:
private void updateProjectDaoDependencies() { if (studyDao != null) studyDao.setProjectDAO(projectDao); if (sampleNumberPerProjectService != null) sampleNumberPerProjectService.setSqlProjectDAO(projectDao); }
Source:
private ReferenceGenome createReferenceGenome() { ReferenceGenome referenceGenome = new ReferenceGenomeImpl(); referenceGenome.setAlias("Human hg19"); START referenceGenome.setId(1L); END return referenceGenome; } Shouldn't need to specify ID anymore

Target:
private ReferenceGenome createReferenceGenome() { ReferenceGenome referenceGenome = new ReferenceGenomeImpl(); referenceGenome.setAlias("Human hg19"); return referenceGenome; }