auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String docsVersion() { if (Version.VERSION.matches("^\\d*\\.\\d*\\.\\d*$")) { //FIXME once we know how readthedocs handles version tags return Version.VERSION; } else { return "latest"; } }

Target:
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?
Source:
protected void applyChanges(IndexFamily to, IndexFamily from) throws IOException { to.setName(from.getName()); to.setFake(from.hasFakeSequence()); to.setUniqueDualIndex(from.isUniqueDualIndex()); to.setArchived(from.getArchived()); }

Target:
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.
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()); setBoolean(to::setArchived, from.isArchived(), true); return to; }

Target:
last parameter should be false (`TissuePieceType#archived` isn't nullable)
Source:
public static String truncate(String index, int shortestLength) { return index.substring(0, shortestLength); }

Target:
These 3 methods should be private, or if useful outside of this controller, they should be in a utilities class
Source:
public @ResponseBody List<ExperimentDto> list() throws IOException { Collection<Experiment> experiments = experimentService.list(); return experiments.stream().map(expt -> Dtos.asDto(expt)).collect(Collectors.toList()); }

Target:
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
Source:
public @ResponseBody BoxDto removeMultipleItems(@PathVariable long boxId, @RequestBody List<String> positions) throws IOException { Box box = getBox(boxId); for (String position : positions) { box.getBoxPositions().remove(position); } boxService.save(box); return getBoxDtoWithBoxables(boxId); }

Target:
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)
Source:
public String propertyForUserName(Criteria item, boolean creator) { item.createAlias("creator", "creator"); item.createAlias("lastModifier", "lastModifier"); return creator ? "creator.loginName" : "lastModifier.loginName"; }

Target:
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
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); dilution.setCreator(securityStore.getUserByFullName(dilutionDto.getDilutionUserName())); dilution.setId(dilutionId); dilutionService.update(dilution); return getDilution(dilutionId); }

Target:
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) ).
Source:
public String clickLinkButtonAndGetUrl(String linkText) { WebElement button = getDriver().findElement(By.linkText(linkText)); WebElement html = getHtmlElement(); button.click(); waitForPageRefresh(html); return getCurrentUrl(); }

Target:
Should be `protected`. Knowledge of link text belongs in Page model classes. A Page class should expose an `addDilution()` method rather than `clickLinkButtonAndGetUrl("Add")`.
Source:
protected void clickOk() { WebElement okButton = getDriver().findElement(By.id("ok")); if (okButton != null) { okButton.click(); } else { throw new IllegalArgumentException("Ok button is not available to click"); } }

Target:
`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
Source:
public PoolPickerResponse getPickersBySearch(@RequestParam("platform") String platform, @RequestParam("query") String query) throws IOException { PlatformType platformType = PlatformType.get(platform); return getPoolPickerWithFilters(100, PaginationFilter.platformType(platformType), PaginationFilter.query(query)); }

Target:
It might make sense to have this support the usual search using `PaginationFilter.parse`, but I'm indifferent.
Source:
public Long getId() { return boxId; }

Target:
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
Source:
public void setText(String input, WebElement element) { element.click(); element.clear(); element.sendKeys(input); element.sendKeys(Keys.ESCAPE); }

Target:
This and the below methods should be `protected` rather than `public` so that they can only be accessed by subclasses
Source:
public boolean shouldRerun() { return !dto.getHealthType().isDone() && Duration.between(created, Instant.now()).toMinutes() < 10; }

Target:
Is this necessary with the scheduler hard-coded to scan every 15 minutes? If so, should this be greater than instead of less than?
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 { throw new IOException("No boxStore available. Check that it has been declared in the Spring config."); } }

Target:
Could you please remove the checks for boxStore != null ? The lack of this particular cruft is one of my favourite parts of the services.
Source:
public Map<String, Integer> getColumnSizes() throws IOException { if (boxStore != null) { return boxStore.getBoxColumnSizes(); } else { throw new IOException("No boxStore available. Check that it has been declared in the Spring config."); } }

Target:
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
Source:
public PoolDto createPool(@RequestBody PoolDto pool, UriComponentsBuilder uriBuilder, HttpServletResponse response) throws IOException { Long id = poolService.savePool(Dtos.to(pool)); UriComponents uriComponents = uriBuilder.path("/{id}").buildAndExpand(id); response.setHeader("Location", uriComponents.toUri().toString()); return getPoolById(id); }

Target:
`"/pool/{id}"`?
Source:
public void testListAllLibraryTypes() throws Exception { List<LibraryType> libraryTypes = dao.listAllLibraryTypes(); assertTrue(libraryTypes.size() > 0); }

Target:
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
Source:
public void testListAllLibrarySelectionTypes() throws Exception { List<LibrarySelectionType> librarySelectionTypes = dao.listAllLibrarySelectionTypes(); assertTrue(librarySelectionTypes.size() > 0); }

Target:
missed one
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())); } setUrl(WritableUrls.buildUriPath(baseUri, "/rest/sample/{id}", getId())); }

Target:
setUrl already called above with different path
Source:
private void loadChildEntities(LibraryDilution dilution) throws IOException { if (dilution.getLibrary() != null) { dilution.setLibrary(libraryDao.get(dilution.getLibrary().getId())); } if (dilution.getTargetedSequencing() != null && dilution.getTargetedSequencing().getId() != null) { dilution.setTargetedSequencing(targetedSequencingDao.get(dilution.getTargetedSequencing().getId())); } }

Target:
Is there a reason the targeted sequencing is set and its id isn't? Seems like something an exception should be thrown for
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 if ("QuBit".equals(qc.getQcType().getName())) { managed.setInitialConcentration(qc.getResults()); } libraryQcDao.save(qc); libraryDao.save(library); }

Target:
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
Source:
public void setLibraryAliasGenerator(NameGenerator<Library> generator) { this.libraryAliasGenerator = (DefaultLibraryAliasGenerator) generator; }

Target:
Remove cast
Source:
public DetailedSampleBuilder(User user) { if (user != null) { securityProfile = new SecurityProfile(user); getSecurityProfile().getProfileId(); } }

Target:
remove line
Source:
public long save(LibraryDilution dilution) throws IOException { long id; if (dilution.getId() == AbstractLibrary.UNSAVED_ID) { id = (long) currentSession().save(dilution); } else { currentSession().update(dilution); id = dilution.getId(); } return id; }

Target:
It's probably the same, but shouldn't be comparing dilution's ID to AbstractLibrary's
Source:
public boolean isDeletable() { return printerId == UNSAVED_ID; }

Target:
It's only deletable if it's not saved?
Source:
public void setDefaultProjectDao() { HibernateProjectDao dao = new HibernateProjectDao(); dao.setJdbcTemplate(jdbcTemplate); dao.setSecurityManager(securityManager); dao.setSecurityProfileDAO(securityProfileDao); dao.setNamingScheme(getNamingScheme()); dao.setDataObjectFactory(dataObjectFactory); dao.setReferenceGenomeDao(referenceGenomeDao); setProjectDao(dao); }

Target:
Compilation errors here.
Source:
public SequencerReference get(long id) throws IOException { SequencerReference sr = (SequencerReference) currentSession().get(SequencerReferenceImpl.class, id); SequencerReference preUpgradeSR = getByUpgradedReference(id); if (preUpgradeSR != null) { sr.setPreUpgradeSequencerReference(preUpgradeSR); } return sr; }

Target:
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)
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); this.ip = null; } } }

Target:
rethrow as IllegalArgumentException
Source:
public int hashCode() { return new HashCodeBuilder(5, 35) .append(alias) .append(description) .append(progress) .append(referenceGenome.getId()) .append(shortName) .toHashCode(); }

Target:
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)
Source:
private void updateProjectDaoDependencies() { if (studyDao != null) studyDao.setProjectDAO(projectDao); if (sampleNumberPerProjectService != null) sampleNumberPerProjectService.setSqlProjectDAO(projectDao); if (referenceGenomeService != null) referenceGenomeService.setReferenceGenomeDao(referenceGenomeDao); }

Target:
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
Source:
private ReferenceGenome createReferenceGenome() { ReferenceGenome referenceGenome = new ReferenceGenomeImpl(); referenceGenome.setAlias("Human hg19"); referenceGenome.setId(1L); return referenceGenome; }

Target:
Shouldn't need to specify ID anymore
Source:
public Collection<String> populatePlatformTypes() throws IOException { Collection<PlatformType> platforms = requestManager.listActivePlatformTypes(); if (platforms.size() > 0) { return PlatformType.platformTypeNames(requestManager.listActivePlatformTypes()); } else { return requestManager.listDistinctPlatformNames(); } }

Target:
Can `return PlatformType.platformTypeNames(platforms);` instead of doing the same lookup twice
Source:
public Collection<Sample> listBySearch(String querystr) throws IOException { Criteria criteria = currentSession().createCriteria(Sample.class); criteria.add(Restrictions.or(Restrictions.ilike("identificationBarcode", querystr + "%"), Restrictions.ilike("name", querystr + "%"), Restrictions.ilike("alias", querystr + "%"))); @SuppressWarnings("unchecked") List<Sample> records = criteria.list(); return fetchSqlStore(records); }

Target:
Consider adding a wildcard to the front of the string as well. Right now searching for `KGMT` will match `KGMT_0015`, but searching for `0015` will not. Since the query string is not escaped, it's currently possible to use SQL wildcards in queries (this is not something a general user will do.) So searching for `%0015` will match against `KGMT_0015`.
Source:
private void updateTissueMaterialDaoDependencies() { if (sampleService != null) sampleService.setTissueMaterialDao(tissueMaterialDao); updateSamplePurposeDaoDependencies(); }

Target:
Wrong place. This should be done in the setSamplePurposeDao method, where it was originally
Source:
public Integer getCutsRemaining() { Integer cutsConsumed = 0; for (Sample child : getChildren()) { if (child instanceof SampleLCMTube && ((SampleLCMTube) child).getCutsConsumed() != null) { cutsConsumed += ((SampleLCMTube) child).getCutsConsumed(); } } return (getCuts() - getDiscards() - cutsConsumed); }

Target:
This should be `int`.
Source:
public String getBulkSamples(@RequestBody JSONObject json) throws IOException { JSONArray ids = JSONArray.fromObject(json.get("ids")); StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < ids.size(); ++i) { stringBuffer.append(ids.getLong(i)); if (i + 1 < ids.size()) { stringBuffer.append(","); } } return "redirect:/miso/sample/bulk/edit/" + stringBuffer.toString(); }

Target:
This is easier to read as: ``` for (int i = 0; i < ids.size(); ++i) { if (i>0) { stringBuffer.append(","); } stringBuffer.append(ids.getLong(i)); } ```
Source:
public static SampleAdditionalInfo to(SampleAdditionalInfoDto from) { SampleAdditionalInfo to = new SampleAdditionalInfoImpl(); to.setPassageNumber(from.getPassageNumber()); to.setTimesReceived(from.getTimesReceived()); to.setTubeNumber(from.getTubeNumber()); to.setVolume(from.getVolume()); to.setConcentration(from.getConcentration()); to.setTubeNumber(from.getTubeNumber()); return to; }

Target:
It is already set in this method, three lines up.
Source:
public String toString() { return "SampleTissueDto [bioBankId=" + bioBankId + ", cellularity=" + cellularity + ", createdById=" + createdById + ", createdByUrl=" + createdByUrl + ", creationDate=" + creationDate + ", id=" + id + ", labUrl=" + labUrl + ", instituteTissueName=" + instituteTissueName + ", lastUpdated=" + lastUpdated + ", updatedById=" + updatedById + ", updatedByUrl=" + updatedByUrl + ", url=" + url + "]"; }

Target:
labUrl needs to be taken out as well, and added in to SampleAdditionalInfoDto
Source:
private SampleNumberPerProject createSampleNumberPerProject(Project project, User user) { SampleNumberPerProject sampleNumberPerProject; sampleNumberPerProject = new SampleNumberPerProjectImpl(); sampleNumberPerProject.setProject(project); sampleNumberPerProject.setHighestSampleNumber(0); sampleNumberPerProject.setPadding(DEFAULT_PADDING); sampleNumberPerProject.setCreatedBy(user); sampleNumberPerProject.setUpdatedBy(user); sampleNumberPerProject.setLastUpdated(new Date()); sampleNumberPerProject.setCreationDate(new Date()); addSampleNumberPerProject(sampleNumberPerProject); return sampleNumberPerProject; }

Target:
Setting the dates is handled inside the addSampleNumberPerProject method, so is not required here.
Source:
public static String loadFile(String path) { String result = ""; Scanner sc = new Scanner(ResourcesUtil.class.getClassLoader().getResourceAsStream(path)); while (sc.hasNextLine()) { result += sc.nextLine(); } sc.close(); return result; }

Target:
try/finally?
Source:
private static Activity getActivity(final Context context) { if (context == null) { // TODO Mapsme API will do a hard cast. We could locally fix this by re-declaring all API methods return null; } else if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return getActivity(((ContextWrapper) context).getBaseContext()); } return null; }

Target:
The first if is superfluous. instanceof is always false for null, therefore a null value bypasses the instanceof checks and returns null from the end of the method already.
Source:
public static IConnector[] getActiveConnectors() { final List<IConnector> activeConnectors = new ArrayList<>(); for (final IConnector conn : CONNECTORS) { if (conn.isActive()) { activeConnectors.add(conn); } } return activeConnectors.toArray(new IConnector[activeConnectors.size()]); }

Target:
Why not return directly the `List<IConnector>`?
Source:
public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return false; }

Target:
Can be transformed into an `if` statement.
Source:
static List<TrackableInventoryEntry> getTrackableInventory() { final List<TrackableInventoryEntry> trackableInventoryEntries = new ArrayList<>(); int skip = 0; TrackableInventoryEntry[] entries = null; while (entries == null || entries.length == MAX_TAKE) { entries = getAPI("/trackables?inCollection=false&take=" + MAX_TAKE + "&skip=" + skip, TrackableInventoryEntry[].class).blockingGet(); trackableInventoryEntries.addAll(Arrays.asList(entries)); skip += MAX_TAKE; } return trackableInventoryEntries; }

Target:
We can get rid of the first condition (and the `null`-initialization of `entries`) by using a do-while loop.
Source:
public void increaseActualCachesFound() { if (actualCachesFound >= 0) { setActualCachesFound(actualCachesFound + 1); } }

Target:
That's actually `actualCachesFound++;`. Sorry, I though you already had this in mind when you proposed to reference the field directly.
Source:
public static CalcState fromJSON(final String json) throws JSONException { CalcState rv = null; if (json != null) { rv = new CalcState(new JSONObject(json)); } return rv; }

Target:
Your proposal is even better. Early returns make it easier to understand: Here it will return, (almost) nothing will be executed after this line. So please change this to ```java if (json == null) { return null; } return new CalcState(new JSONObject(json)); ```
Source:
public JSONObject toJASON() throws JSONException { JSONObject rv = new JSONObject(); rv.put("type", type.ordinal()); rv.put("inputVal", inputVal); rv.put("autoChar", autoChar); rv.put("customChar", customChar); return rv; }

Target:
Should be `final JSONObject rv = …`.
Source:
public void testShouldRemoveNoCache() throws Exception { // GIVEN lists1.add(LIST_ID1); lists2.add(LIST_ID3); lists3.add(LIST_ID3); final Set<Geocache> toBeRemoved = RemoveNotUniqueHelper.removeNonUniqueCaches(geoCaches); assertThat(toBeRemoved.size()).isEqualTo(0); assertThat(toBeRemoved.contains(gc1)).isFalse(); assertThat(toBeRemoved.contains(gc2)).isFalse(); assertThat(toBeRemoved.contains(gc3)).isFalse(); }

Target:
Please add an empty line between the two methods.
Source:
private void initializeFavoriteCheck() { if (ConnectorFactory.getConnector(cache).supportsAddToFavorite(cache, typeSelected)) { if (premFavPoints > 0) { favCheck.setVisibility(View.VISIBLE); favCheck.setText(getString(R.string.fav_points_remaining, String.valueOf(premFavPoints))); } } else { favCheck.setVisibility(View.GONE); } }

Target:
Why not either: - fix the string to use `%d` instead of `%s` - do nothing and let the implicit `.toString()` do the job rather than calling `String.valueOf` explicitly?
Source:
private void initializeCommonFields() { supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); AndroidBeam.disable(this); // initialize commonly used members res = this.getResources(); app = (CgeoApplication) this.getApplication(); // only needed in some activities, but implemented in super class nonetheless Cookies.restoreCookieStore(Settings.getCookieStore()); ActivityMixin.onCreate(this, keepScreenOn); }

Target:
If you re-purpose the method, you should change its name as well
Source:
protected InputStream getInputStream() throws IOException { try { return contentResolver.openInputStream(uri); } catch (final FileNotFoundException e) { // for http links, we may need to download the content ourself, if it has no mime type announced by the browser if (uri.toString().startsWith("http")) { return Network.getResponseStream(Network.getRequest(uri.toString())); } // only log error for non-http URI Log.e("GpxZip import cannot resolve " + uri); } return null; }

Target:
No, I mean take the `Log.e()` near the `return null;`.
Source:
public void addInventoryItem(final Trackable newTrackable) { if (inventory == null) { inventory = new ArrayList<Trackable>(); } Boolean foundTrackable = false; for (final Trackable trackable: inventory) { if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { // Trackable already present, merge data foundTrackable = true; trackable.mergeTrackable(newTrackable); break; } } if (!foundTrackable) { inventory.add(newTrackable); } inventoryItems = inventory.size(); }

Target:
please avoid boxed primitives
Source:
public DistanceComparator() { this.coords = null; this.list = null; }

Target:
What does it mean to have the `list` set to `null`? As soon as `compareCaches()` will be called, then `calculateAllDistances` will be called as well, and there will be a `NullPointerException` in the `for` loop. Does it mean that `compareCaches()` will never be called on the singleton? If this is the case, why not use `null` instead of this singleton? I'm not sure I follow the logic here.
Source:
public static List<Trackable> parse(final InputSource page) { try { // Create a new instance of the SAX parser SAXParserFactory saxPF = SAXParserFactory.newInstance(); SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // Create the Handler to handle each of the XML tags. final GeokretyHandler gkXMLHandler = new GeokretyHandler(); xmlR.setContentHandler(gkXMLHandler); xmlR.parse(page); return gkXMLHandler.getTrackables(); } catch (final Exception e) { Log.w("Cannot parse geokrety", e); } return null; }

Target:
Should be `final`.
Source:
public static boolean mergeFriendsLogs(final List<LogEntry> mergedLogs, List<LogEntry> logsToMerge) { if (logsToMerge != null && !logsToMerge.isEmpty()) { for (final LogEntry log : logsToMerge) { if (mergedLogs.contains(log)) { mergedLogs.get(mergedLogs.indexOf(log)).friend = true; } else { log.friend = true; mergedLogs.add(log); } } return true; } return false; }

Target:
Why public?
Source:
public SearchResult searchByGeocode(final String geocode, final String guid, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_loadpage); final Geocache cache = ECApi.searchByGeoCode(geocode); if (cache == null) { return null; } final SearchResult searchResult = new SearchResult(cache); return searchResult; }

Target:
This line and all the following ones can be replaced by the single line ``` java return cache != null ? new SearchResult(cache) : null; ```
Source:
public final LogResult postLog(final Geocache cache, final LogType logType, final Calendar date, final String log, final String logPassword, final List<TrackableLog> trackableLogs) { final LogResult result = ECApi.postLog(cache, logType, date, log); return result; }

Target:
Please do not create useless variables, it is more readable if you directly use: ``` java return ECApi.postLog(cache, logType, date, log); ```
Source:
public static String getResponseDataAlways(@Nullable final HttpResponse response) { if (response == null) { return null; } return getResponseDataNoError(response, false); }

Target:
You could use the shorter ``` java return response != null ? getResponseDataNoError(response, false) : null; ```
Source:
public void onLoadFinished(Loader<String> arg0, String page) { if (page == null) { hasLoaderError = true; } else { viewstates = Login.getViewstates(page); trackables = GCParser.parseTrackableLog(page); possibleLogTypes = GCParser.parseTypes(page); if (possibleLogTypes.isEmpty()) { hasLoaderError = true; } else { hasLoaderError = false; } } activity.onLoadFinished(); }

Target:
the if-else can be transformed to a simple assignment.
Source:
public static void clearVisitDate(String[] selected) { ArrayList<String> geocodes = new ArrayList<String>(); for (int i = 0; i < selected.length; i++) { geocodes.add(selected[i]); } setVisitDate(geocodes, 0); }

Target:
This method could be written as ``` java public static void clearVisitDate(String[] selected) { setVisitDate(Arrays.asList(selected), 0); } ```
Source:
public SearchResult loadInBackground() { loading = true; if (search == null) { search = runSearch(); } else { //Unless we make a new Search the Loader framework won't deliver results. It does't do equals only identity SearchResult newSearch = new SearchResult(search); newSearch.setUrl(search.getUrl()); newSearch.setViewstates(search.getViewstates()); search = GCParser.searchByNextPage(newSearch, Settings.isShowCaptcha(), this); } loading = false; return search; }

Target:
I'm confused by those. Those fields (as well as `geocodes`, `error` and `totalCnt`) would have been copied already by the `new SearchResult(search)` constructor, wouldn't they?
Source:
public boolean isMapDatabaseSwitchSupported() { return !getMapGenerator().requiresInternetConnection() && null != Settings.getMapFile(); //if no file is specified in settings then disable the switch map option }

Target:
This can be read easier by others by splitting the check using "guards style": http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html if (getMapGenerator.requiresInternetConnection()) { return false; } if (Settings.getMapFile() == null) { return false; } return true; And if you now want to ask: But isn't my original code much more compact and optimized? No, it is not. The compiler will create basically the same binary code for both versions. Besides that, even if there are differences in the binary, they don't matter. Code should always be optimized for readability and understandability, as that is the most severe problem in software development.
Source:
public boolean isEnabled(Geopoint geopoint) { if (geopoint == null) { return true; } return false; }

Target:
This should be ``` java return geopoint == null; ``` but as I wrote, the semantics of this are questionable…
Source:
public synchronized void stopIt() { stop = true; }

Target:
Why do you make this synchronized? IMHO it can be stopped as many times as you wish.
Source:
public cgeocoords(final AbstractActivity contextIn, cgSettings settingsIn, final Geopoint gpIn, final cgGeo geoIn) { super(contextIn); context = contextIn; settings = settingsIn; geo = geoIn; if (gpIn != null) { gp = gpIn; } else if (geo != null && geo.latitudeNow != null && geo.longitudeNow != null) { gp = new Geopoint(geo.latitudeNow, geo.longitudeNow); } else { gp = new Geopoint(); } }

Target:
I removed the empty constructor because (0|0) doesn't make sense here. So there are two possibilities: - set valid coordinates (preferred) - set gp to null and check it later
Source:
protected PreparedStatement getPreparedStatement(String query) throws SQLException { return (connection.prepareStatement(query)); }

Target:
Unnecessary parenthesis
Source:
public void failToFindNonExistentElement() { WebDriver d = getDriver(); d.get("http://www.google.com"); try { WebElement inputField = d.findElement(By.cssSelector("input[name='idontexist']")); fail(); } catch (NoSuchElementException e) { // expected } }

Target:
There is a better way to handle the exception in a more JUnit-y way. See for example: http://www.mkyong.com/unittest/junit-4-tutorial-2-expected-exception-test/ If you update with this, I'll merge straightaway: the code itself looks great. Thanks ;)
Source:
public void peopleMessage(final PeopleDescription peopleDescription) { try { peopleDescription.getMessage().toString(); final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); } catch (AssertionError e) { MPLog.e(LOGTAG, "Could not record people update (see https://github.com/mixpanel/mixpanel-android/issues/567)", e); } }

Target:
Shouldn't it be already normalized in `MixpanelMessageDescription` constructor?
Source:
public void testInvalidNotificationBadge() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_bdgcnt", "0"); mpPushSpy.createNotification(intent); verify(builderSpy, never()).setNumber(any(Integer.class)); }

Target:
it's unclear whether this is invalid because 0 is not valid or because it's a string. I'd recommend being a bit more specific here or potentially having two tests if both are invalid to make it clear what our expectations are.
Source:
public void testNoChannelId() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); Notification notification = mpPushSpy.createNotification(intent); verify(builderSpy).setChannelId(anyString()); assertEquals(notification.getChannelId(), MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID); }

Target:
can't we be more specific here and verify that `setChannelId(MixpanelPushNotification.NotificationData.DEFAULT_CHANNEL_ID)`?
Source:
protected Bitmap getBitmapFromUrl(String url) { ImageStore is = new ImageStore(context, "MixpanelPushNotification"); try { Bitmap bm = is.getImage(url); return bm; } catch (ImageStore.CantGetImageException e) { return null; } }

Target:
just return `is.getImage(url)` no need to create a local var
Source:
protected void maybeSetNotificationBadge(NotificationData data) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE && data.badgeCount > 0) { builder.setNumber(data.badgeCount); } }

Target:
just to repeat the question I had in the test code, what happens if you set badgeCount to 0?
Source:
protected Intent buildIntentForUri(Uri uri) { return new Intent(Intent.ACTION_VIEW, uri); }

Target:
```suggestion /* package */ Intent buildIntentForUri(Uri uri) { ```
Source:
public double eventElapsedTime(final String eventName) { final long currentTime = System.currentTimeMillis(); long startTime; synchronized (mEventTimings) { startTime = mEventTimings.get(eventName); } return (double)((currentTime - startTime) / 1000); }

Target:
We probably want to check if there is a timed event for the given name and return 0 in that case 👍
Source:
private boolean isInEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) || "google_sdk".equals(Build.PRODUCT); }

Target:
On the stackoverflow post there are 4 people suggesting `Build.MANUFACTURER.equals("unknown")`. Also, this library does it as well: https://github.com/gingo/android-emulator-detector/blob/master/EmulatorDetectorProject/EmulatorDetector/src/main/java/net/skoumal/emulatordetector/EmulatorDetector.java#L41 I think its worth to include it.
Source:
private void handleVariantsReceived(JSONArray variants) { final SharedPreferences preferences = getSharedPreferences(); final SharedPreferences.Editor editor = preferences.edit(); if(variants != null) { editor.putString(SHARED_PREF_CHANGES_KEY, variants.toString()); } else { editor.remove(SHARED_PREF_CHANGES_KEY); } editor.apply(); initializeChanges(); }

Target:
I am not a fan of using `null` as a meaningful value that will change the behavior/flow of the product. For instance, `variants` could be just an empty `JSONArray` if there are really no `variants`. The `SHARED_PREF_CHANGES_KEY` could always be in the device, just with empty variants.
Source:
public DecideMessages(String token, OnNewResultsListener listener, UpdatesFromMixpanel updatesFromMixpanel) { mToken = token; mListener = listener; mUpdatesFromMixpanel = updatesFromMixpanel; mDistinctId = null; mUnseenSurveys = new LinkedList<Survey>(); mUnseenNotifications = new LinkedList<InAppNotification>(); mSurveyIds = new HashSet<Integer>(); mNotificationIds = new HashSet<Integer>(); if(mVariants == null) { mVariants = new JSONArray(); } }

Target:
`mVariants` will always be `null` here.
Source:
public String getStringValue() { String ret = null; try { ret = (String) defaultValue; } catch (ClassCastException e2) { ; // ok } try { ret = (String) value; } catch (ClassCastException e) { ; // ok } return ret; }

Target:
should be `ClassCastException e`
Source:
public void run() { if (!mAlive) { return; } final View viewRoot = mViewRoot.get(); if (null == viewRoot || mDying) { cleanUp(); return; } // ELSE View is alive and we are alive try { mEdit.visit(viewRoot); } catch (ViewVisitor.LayoutUpdateException e) { cleanUp(); throw e; } mHandler.removeCallbacks(this); mHandler.postDelayed(this, 1000); }

Target:
I'm worried that this rethrow will crash the app. Perhaps LayoutUpdateException shouldn't be a runtime error?
Source:
public void visit(View rootView) { if (mAlive) { super.getPathfinder().findTargetsInRoot(rootView, super.getPath(), this); } }

Target:
Great!
Source:
public void onActivityCreated(Activity activity, Bundle savedInstanceState) { checkForDecideUpdates(activity); }

Target:
Is it okay to only checkForDecideUpdates() in onActivityResumed()? I think with the current logic, only one call is necessary now since we register the listeners.
Source:
public static MPMetrics getInstance(Context context, String token) { MPMetrics instance = mInstanceMap.get(token); if (instance == null) { instance = new MPMetrics(context.getApplicationContext(), token); mInstanceMap.put(token, instance); } instance.mPushPref.edit().putString("mp_token", token).commit(); return instance; }

Target:
I think the SharedPreferences will be shared across tokens, so if someone is using multiple tokens, this will overwrite the first token. And then you'll be writing device ids to the wrong project. Please check this.
Source:
public void setProperties(List<String> properties) { this.properties = properties; }

Target:
Could have `@VisibleForTesting` annotation. Also could `public` be removed?
Source:
private String stream2String(InputStream in) { try { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
Configuration files are relatively small. Will this stream ever be sufficiently large to warrant this bufferred reading approach, rather than simply reading the whole stream in? We're eventually reading the whole stream into memory anyway. Why not just readFully or similar?
Source:
private CompletableFuture<Void> rollbackLocks(CommitData cd) throws Exception { CommitStep firstStep = new RollbackOtherLocks(); firstStep.andThen(new RollbackPrimaryLock()); return firstStep.compose(cd) .thenRun(() -> cd.commitObserver.commitFailed(cd.getShortCollisionMessage())); }

Target:
I don't think this throws any checked exceptions, so could drop `throws Exception`.
Source:
public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) { dest.clear(); for (int i = 0; i < timeStamps.size(); i++) { long time = timeStamps.get(i); if (timestampTest.test(time)) { dest.add(new Key(key.getRow(), time), values.get(i)); } } }

Target:
It would be nice to avoid creating the key object. Since its the same class you can directly access private things in dest. Could directly add stuff to `dest.timeStamps` and `dest.values`. Alternatively, could create a private method like `private void add(long timestamp, Value v){...}` and call that method here. I think the private method is a little cleaner.
Source:
private synchronized void scheduleRetry() { schedExecutor.schedule(() -> updatePartitionInfo(), retrySleepTime, TimeUnit.MILLISECONDS); retrySleepTime = Math.min(maxSleepTime, (long) (1.5 * retrySleepTime) + (long) (retrySleepTime * Math.random())); }

Target:
IntelliJ is suggesting to method reference `this::updatePartitionInfo` rather than `() -> updatePartitionInfo()`
Source:
private synchronized void scheduleUpdate() { schedExecutor.schedule(() -> updatePartitionInfo(), 0, TimeUnit.MILLISECONDS); }

Target:
Could use `this::updatePartionInfo`
Source:
public void beginSecondCommitPhase(CommitData cd, Stamp commitStamp) throws Exception { if (startTs < commitStamp.getGcTimestamp()) { rollbackOtherLocks(cd); } else { // Notification are written here for the following reasons : // * At this point all columns are locked, this guarantees that anything triggering as a // result of this transaction will see all of this transactions changes. // * The transaction is not yet committed. If the process dies at this point whatever // was running this transaction should rerun and recreate all of the notifications. // The next transactions will rerun because this transaction will have to be rolled back. // * If notifications are written in the 2nd phase of commit, then when the 2nd phase // partially succeeds notifications may never be written. Because in the case of failure // notifications would not be written until a column is read and it may never be read. // See https://github.com/fluo-io/fluo/issues/642 // // Its very important the notifications which trigger an observer are deleted after the 2nd // phase of commit finishes. getStats().setCommitTs(commitStamp.getTxTimestamp()); writeNotificationsAsync(cd, commitStamp.getTxTimestamp()); } }

Target:
can be private
Source:
public ListenableFuture<Void> writeMutationsAsyncFuture(Collection<Mutation> ml) { if (ml.size() == 0) { return Futures.immediateFuture(null); } ListenableFutureTask<Void> lf = ListenableFutureTask.create(DO_NOTHING, null); try { MutationBatch mb = new MutationBatch(ml, lf); mutQueue.put(mb); return lf; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
Several methods in this class do not need to be public and can be package local
Source:
public FluoConfiguration setPositiveInt(String property, int value) { Preconditions.checkArgument(value > 0, property+" must be positive"); setProperty(property, value); return this; }

Target:
why make these public and part of the API? I was thinking of these methods as implementation. If we make them part of API then we have to support them.
Source:
public static String parseRoot(String zookeepers) { int slashIndex = zookeepers.indexOf("/"); if (slashIndex != -1) { return zookeepers.substring(slashIndex); } return "/"; }

Target:
could return `zookeepers.substring(slashIndex).trim()` to remove any trailing whitespace...
Source:
public MutationBuilder put(Column col, Bytes value) { Flutation.put(null, mutation, col, ColumnConstants.DATA_PREFIX | 0, value.toArray()); Flutation.put(null, mutation, col, ColumnConstants.WRITE_PREFIX | 1, WriteValue.encode(0, false, false)); return this; }

Target:
what about creating a separate put method with no Environment parameter to avoid using null?
Source:
public Long allocateTimestamp() { synchronized(status) { Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp Long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } // retrieve timestamp to return Long ts = getTimestamp(); timestamps.add(ts); status = TrackerStatus.BUSY; //System.out.println("allocated "+ts); return ts; } }

Target:
synchronizing on an object that changes in sync blocks is not good
Source:
public long allocateTimestamp() { // initialize zookeeper if idle and node does not exist synchronized(this) { Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp Long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } } // retrieve timestamp to return long ts = getTimestamp(); // update timestamp set and status synchronized(this) { timestamps.add(ts); status = TrackerStatus.BUSY; } return ts; }

Target:
thinking about this some more, its possible that the zknode could be deleted (and state is set to IDLE) while lock was not held. That can be detected here, but then what? retry? An alternative to retrying would be to increment an allocating counter in the first block and decrement it in the second sync block. Code that deletes node would not do so if allocating counter > 0. Another alternative would be to use a read-write lock.
Source:
public void done() throws CommitException { commit(); close(); }

Target:
nice maybe try finally?
Source:
public boolean checkExists(Long transactorId) { // once a transactor has timed out, act like it does not exist even if still in zookeeper if (timeoutCache.getIfPresent(transactorId) != null) return false; return cache.getCurrentData(TransactorID.getNodePath(config, transactorId)) != null; }

Target:
It might make sense to modify the usage of this cache. Transactors that have timed out should only "not exist" for all transactions before the startTime of the timeout. For any newer transactions, the timeout needs to occur again before the timeout cache is updated with a newer time. This will prevent rollbacks from continuing to occur on transactors that were slow but started to function correctly again.
Source:
public void stop() throws Exception { if (started) { server.stop(); serverThread.join(); started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderSelector.close(); curatorFramework.getConnectionStateListenable().removeListener(this); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }

Target:
this is unrelated to this issue, but this stop method should probably be synchronized.
Source:
public static String setupTestPath(final ConfigContext config, final MantaClient client, final String testName, final String testType) { if ("buckets".equals(testType)) { if (BooleanUtils.isTrue(verifyBucketsSupport(config, client))) { return setupBucketsPath(config, testName); } else { throw new SkipException("Bucket operations not supported by the server"); } } return IntegrationTestConfigContext.generateBasePath(config, testName); }

Target:
We want to make sure that the bucket name doesn't start with an upper case character, since it's one of the naming restrictions as mentioned [here](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html).
Source:
public void valueOfCodeCanFindByMatchingCode() { final MantaErrorCode expectedLimitError = MantaErrorCode.INVALID_LIMIT_ERROR; final MantaErrorCode expectedNoApiError = MantaErrorCode.NO_API_SERVERS_AVAILABLE; final MantaErrorCode expectedObjectNotFoundError = MantaErrorCode.OBJECT_NOT_FOUND_ERROR; final MantaErrorCode actualLimitError = MantaErrorCode.valueOfCode("InvalidLimit"); final MantaErrorCode actualNoApiError = MantaErrorCode.valueOfCode("NoApiServersAvailable"); final MantaErrorCode actualObjectNotFoundError = MantaErrorCode.valueOfCode("ObjectNotFoundError"); Assert.assertEquals(actualLimitError, expectedLimitError); Assert.assertEquals(actualNoApiError, expectedNoApiError); Assert.assertEquals(actualObjectNotFoundError, expectedObjectNotFoundError); }

Target:
I would just use the raw enum because that is simpler.
Source:
public void validateAllSupportedCiphers() throws IOException, DecoderException { /* Loop through each Supported Cipher for All Supported Providers*/ final Iterator<SupportedCipherDetails> i = CIPHERS_TO_TEST.iterator(); while (i.hasNext()) { final SupportedCipherDetails cipherDetails = i.next(); validateEncryptedFileWithHeaderValues(cipherDetails); } }

Target:
Use `for :` and not an iterator directly.
Source:
void delete(final String rawPath, final MantaHttpHeaders requestHeaders, final Integer pruneDepth) throws IOException { Validate.notBlank(rawPath, "rawPath must not be blank"); String path = formatPath(rawPath); if (pruneDepth == null) { LOG.debug("DELETE {}", path); httpHelper.httpDelete(path, requestHeaders); } else { PruneEmpytParentDirectoryStrategy.pruneParentDirectories(this, requestHeaders, path, pruneDepth); } }

Target:
It's good that you can handle the 0 case in `PruneEmpytParentDirectoryStrategy` but it's easier on the next maintainer if you make this check `pruneDepth == null || pruneDepth == 0` (since the fact that it isn't null means the unboxing will be safe)
Source:
private static long[] byteRangeAsNullSafe(final Long[] ranges, final SupportedCipherDetails cipherDetails) { final long plaintextMax = cipherDetails.getMaximumPlaintextSizeInBytes(); final long startPos; final long endPos; if (ranges[0] == null) { startPos = 0L; } else { startPos = ranges[0]; } if (ranges[1] == null) { endPos = plaintextMax; } else { endPos = ranges[1]; } return new long[] {startPos, endPos}; }

Target:
Can this be `@VisibleForTesting` (even if we are not using guava or whatever has the actual formal annotation)?
Source:
private void shuffleDataset() { Random random = new Random(); int iterator, shufflePosition; Object temp; for(iterator = dataset.length - 1; iterator > 0; iterator--) { shufflePosition = random.nextInt(iterator); temp = dataset[iterator]; dataset[iterator] = dataset[shufflePosition]; dataset[shufflePosition] = temp; } }

Target:
This could be declared inside his scope, the for loop.
Source:
public void randomBigDecimalUsingRange() { RandomFunction random = new RandomFunction(BigDecimal.class, new Range(1, 1000)); BigDecimal bigDecimal = random.generateValue(); assertNotNull("Generated BigDecimal must not be null", bigDecimal); assertTrue("Generated value must be a BigDecimal", bigDecimal instanceof BigDecimal); assertTrue(new BigDecimal("1").compareTo(bigDecimal) != 1); assertTrue(new BigDecimal("1000").compareTo(bigDecimal) != -1); }

Target:
Maybe here should be better to check if the generated value is in the range instead of checking if it's not the `limit values`. Something like: ``` assertTrue(new BigDecimal("1").compareTo(bigDecimal) >= 1); assertTrue(new BigDecimal("1000").compareTo(bigDecimal) <= 1000); ``` What do you think?