auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean shouldProcess(final Triple triple) { return triple != null && triple.getSubject().isURI() && triple.getSubject().toString() .startsWith(prefix == null ? "" : prefix) && TO_RESOLVE.contains(triple.getPredicate().toString()) & !(triple.getObject().isLiteral()); }

Target:
Bitwise `&` here?
Source:
public void onActivate(ActivateEvent event, EntityRef entity) { blockFactory = new BlockItemFactory(entityManager); inventoryManager = new InventoryAuthoritySystem(); EntityRef flagTaker = event.getInstigator(); // If the flag being taken is a red flag and the player is on the black team, let them take the flag if (!playerTeamMatchesFlagTeam(entity, flagTaker)) { giveFlagToPlayer(entity, flagTaker); attachParticleEmitterToPlayer(flagTaker); } }

Target:
I doubt if inventoryManager needs initialisation since it's being injected
Source:
public void initialise() { for (EntityRef entity : entityManager.getEntitiesWith(ScoreComponent.class)) { scoreEntity = entity; score = scoreEntity.getComponent(ScoreComponent.class); } if (!scoreEntity.equals(EntityRef.NULL)) { scoreArea = find("scoreArea", UIText.class); scoreArea.bindText(new ReadOnlyBinding<String>() { @Override public String get() { return String.valueOf(score.blackScore); } }); } // String scoreText = "Red Team: " + redScore + " " + // "Black Team: " + blackScore; // scoreArea.setText(String.format(scoreText)); }

Target:
Are you expecting one or more entities with `ScoreComponent.class`? If it is more than one, why store one of them (the last one) as `private EntityRef scoreEntity;` Currently, the variable is only accessed in the local scope of `initialise`.
Source:
public void initialize() { BlockManager blockManager = CoreRegistry.get(BlockManager.class); theme = BlockTheme.builder(blockManager) .register(DefaultBlockType.ROOF_FLAT, "LightAndShadowResources:MagicPlank") .register(DefaultBlockType.FENCE, "LightAndShadowResources:MagicGlass") .register(DefaultBlockType.BUILDING_WALL, "LightAndShadowResources:MagicStone") .build(); redDice = CoreRegistry.get(BlockManager.class).getBlock("LightAndShadowResources:redDice"); blackDice = CoreRegistry.get(BlockManager.class).getBlock("LightAndShadowResources:blackDice"); }

Target:
Convert "L&SResources:redDice" to a constant as well. Try to avoid hard coded strings as much as possible, everywhere.
Source:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class).extendBy(0, 8, 4); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }

Target:
Why do we need the extension? I removed and tested it with abnormally large bases and it seems to work.
Source:
public void process(GeneratingRegion region) { Border3D border = region.getBorderForFacet(BaseFacet.class).extendBy(0, 0, 0); BaseFacet facet = new BaseFacet(region.getRegion(), border); for (Base base : fixedBases) { facet.add(base); } region.setRegionFacet(BaseFacet.class, facet); }

Target:
This is unnecessary. Remove the extension altogether. `Border3D border = region.getBorderForFacet(BaseFacet.class);`
Source:
public void init() { startTime = new Date(); try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { } }

Target:
Looks like, once initialized, `startTime`'s value will never change. If so, you can remove setting its value in `init()`, and make it `final`: ``` private final Date startTime = new Date(); ```
Source:
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { if (entity instanceof Comment) { Comment comment = (Comment) entity; KafkaJsonOutput output = new KafkaJsonOutput(comment.getCommentUri(), KafkaEventType.DELETE); sendMessage("ambra-comment", output); } super.onDelete(entity, id, state, propertyNames, types); }

Target:
What do you think of moving the creation of `KafkaJsonOutput` inside `sendMessage`?
Source:
public JsonElement serialize(JsonSerializationContext context) { JsonObject serialized = context.serialize(flag).getAsJsonObject(); // Alias "comment" (the flag field containing the comment that the user submitted) to avoid ambiguity. // Should match the field name used for org.ambraproject.rhino.view.comment.CommentFlagInputView.body. serialized.add("body", serialized.remove("comment")); if (flag.getUserProfileId() != null) { serialized.remove("userProfileID"); serialized.add("creator", context.serialize(new UserIdView(flag.getUserProfileId()))); } serialized.add("flaggedComment", context.serialize(flaggedComment)); return serialized; }

Target:
I think this line serialized.remove("userProfileID") should be before if() block.
Source:
public String getCrepoKey() { return entry; }

Target:
shouldn't this be `key`?
Source:
public RelationshipView(String type, Doi doi, String title) { this.type = Objects.requireNonNull(type); this.doi = Objects.requireNonNull(doi).getName(); this.title = title; }

Target:
This can just be `doi.getName()`, which serves the same purpose as `Objects.requireNonNull`: throwing an NPE if `doi` is null.
Source:
public ResponseEntity<?> syndicate(HttpServletRequest request, @RequestParam(value = "revision", required = false) Integer revisionNumber) throws IOException { ArticleVersionIdentifier versionId = getArticleVersionIdentifier(request, revisionNumber); SyndicationInputView input = readJsonFromRequest(request, SyndicationInputView.class); Syndication created = syndicationCrudService.syndicate(versionId, input.getTarget()); return reportOk(created.toString()); }

Target:
you can use `ResponseEntity<Object>` instead of `?`.
Source:
private void assertArticleExistence(ArticleIdentity id, boolean expectedToExist) { boolean received404 = false; try { articleCrudService.readXml(id); } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException me) { received404 = true; } catch(NotFoundException nfe) { received404 = true; } catch (RestClientException e) { throw e; } assertEquals(received404, !expectedToExist, (expectedToExist ? "Article expected to exist but doesn't" : "Article expected not to exist but does")); }

Target:
You can use the "or version" of the catch block to make this more succinct: ``` } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException | NotFoundException ex) { received404 = true; } ```
Source:
private void checkFileExistence(AssetFileIdentity fileIdentity, boolean expectedToExist) throws IOException { try (InputStream stream = contentRepoService.getLatestRepoObject(fileIdentity.toString())) { assertNotNull(stream); assertTrue(expectedToExist); } catch (InMemoryContentRepoService.InMemoryContentRepoServiceException me) { assertFalse(expectedToExist); } catch (NotFoundException nfe) { assertFalse(expectedToExist); } catch (ContentRepoException e) { throw e; } }

Target:
Use a single catch block.
Source:
public List<String> getRawTerms(Document articleXml) throws IOException { ArrayList<String> rawTerms = new ArrayList<>(); rawTerms.add("dummy raw term"); return rawTerms; }

Target:
Guava's `ImmutableList.of(...)` can save you a little typing in cases like this.
Source:
String summaryString(Response response) { try { if (response.getExample() != null) return response.getFormulaAnswer(); if (response.getLines().size() > 0) return response.getLines().get(0); } catch (Exception e) { return null; } return null; }

Target:
Should return e.toString() or something? Silent failures are sometimes no fun to track down...
Source:
private void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException { for (final EC2AbstractSlave slave : slaves) { if (slave == null) { LOGGER.warning("Can't raise node for " + t); continue; } Computer c = slave.toComputer(); if (slave.getStopOnTerminate() && c != null) { c.connect(false); } jenkins.addNode(slave); } }

Target:
```suggestion private static void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException { ```
Source:
public SpotConfiguration(boolean useBidPrice) { this.useBidPrice = useBidPrice; this.spotMaxBidPrice = ""; this.fallbackToOndemand = false; this.spotBlockReservationDuration = 0; }

Target:
These are default for bool and int so no need to clarify. ```suggestion ```
Source:
private void fetchLiveInstanceData(boolean force) throws AmazonClientException { return fetchLiveInstanceData(force, 25); }

Target:
```suggestion fetchLiveInstanceData(force, 25); ```
Source:
public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { return Objects.requireNonNull(nodeProperties); }

Target:
Nit: it might make more sense to throw an `IllegalStateException` here instead of `NullPointerException`.
Source:
public static AmazonEC2Client createAmazonEC2Mock(@Nullable Answer defaultAnswer) { AmazonEC2Client mock; if (defaultAnswer != null) { mock = Mockito.mock(AmazonEC2Client.class, defaultAnswer); } else { mock = Mockito.mock(AmazonEC2Client.class); mockDescribeRegions(mock); mockDescribeInstances(mock); mockDescribeImages(mock); mockDescribeKeyPairs(mock); mockDescribeSecurityGroups(mock); mockDescribeSubnets(mock); mockRunInstances(mock); mockTerminateInstances(mock); } return mock; }

Target:
Nit: You can use static imports for `Mockito` methods.
Source:
public BurstableUnlimitedMode getBurstableUnlimitedMode() { if (burstableUnlimitedMode == null) { // For backward-compatibility. return t2Unlimited ? BurstableUnlimitedMode.ENABLED : BurstableUnlimitedMode.DEFAULT; } return burstableUnlimitedMode; }

Target:
Yous should resolve this bit in `readResolve`
Source:
public void testEmptyConfig() throws Exception { final AmazonEC2Cloud ec2Cloud = (AmazonEC2Cloud) Jenkins.get().getCloud("ec2-"); assertNotNull(ec2Cloud); assertEquals(ec2Cloud.getTemplates().size(), 0); }

Target:
```suggestion assertEquals(0, ec2Cloud.getTemplates().size()); ``` These assertions are usually ordered `assertEquals(expected, actual)`.
Source:
public WinConnection(String host, String username, String password) { this.host = host; this.username = username; this.password = password; this.smbclient = new SMBClient(); this.authentication = new AuthenticationContext(username, password.toCharArray(), null);; }

Target:
```suggestion this.authentication = new AuthenticationContext(username, password.toCharArray(), null); ```
Source:
private static void setLogStreamLevel(int level) { LogStream.level = 6; }

Target:
hardcoded value instead of argument? :)
Source:
public int getLaunchTimeout() { if( StringUtils.isEmpty(launchTimeout) || Integer.parseInt(launchTimeout) <= 0 ) launchTimeout = "" + Integer.MAX_VALUE; return Integer.parseInt(launchTimeout); }

Target:
using a toString() is probably better than building a string
Source:
public static Integer get(final String key) { if (key == null) { return R.drawable.acc_none; } return map.containsKey(key.toUpperCase(Locale.getDefault())) ? map.get(key.toUpperCase()) : R.drawable.acc_none; }

Target:
Can this key ever get null?
Source:
public void onBackPressed() { if (!shouldShowDualPane) { if (isDrawerOpen()) { toggleNavigationDrawer(false); } } if (navigationDrawer.fetchDefaultPosition() != navigationDrawer.getCheckedItemPosition()) { navigationDrawer.checkDefaultItemPosition(); return; } super.onBackPressed(); }

Target:
You can make single check out of this `if (!shouldShowDualPane && isDrawerOpen())` since you interested only in single outcome
Source:
public void onRefreshEvent(RefreshEvent event) { Log.d("YOLO", getClass().getSimpleName() + " is refrehshing!"); startLoadingData(); }

Target:
Rubbish
Source:
public Object getItem(int position) { return itemsList.get(position); }

Target:
This should return T.
Source:
public ERDatabaseAttachment _process(EOEditingContext editingContext, File uploadedFile, String recommendedFileName, String mimeType, String configurationName, String ownerID, boolean pendingDelete) throws IOException { NSData data = new NSData(uploadedFile.toURI().toURL()); ERDatabaseAttachment attachment = _process(editingContext, data, recommendedFileName, mimeType, configurationName); if (pendingDelete) { uploadedFile.delete(); } return attachment; }

Target:
If line 33 throws an error this line won't be reached. Prior this PR that delete would always be executed in a finally block.
Source:
private NSArray selectionsFromBindings() { if (canGetValueForBinding(Keys.Selections)) { NSArray result = (NSArray)valueForBinding(Keys.Selections); if (hasBinding(Keys.SortKey)) { String sortKey = stringValueForBinding(Keys.SortKey); result = ERXArrayUtilities.sortedArraySortedWithKey(result, sortKey); } if(result != null) { return result; } } return NSArray.EmptyArray; }

Target:
Should be moved down into the `if(result != null) {` block as sorting a non-existing result does not make sense and even will throw an exception in ERXArrayUtilities.
Source:
public Node apply(@Nonnull Node node) { for (Rule rule : rules) { if (!rule.matches(node)) { return rule.apply(node); } } for (Rule rule : rules) { node = rule.apply(node); if (isErrorResult(node)) return createNodeUsingFactory(node); } return createNodeUsingFactory(node); }

Target:
Why do you return a new node instead of the failing one?
Source:
public ObjectRule untitledRaml() { return super.untitledRaml() .with(annotationTypesField()) .with(annotationField()) .with(typesField()) .with(usesField()) .with(exclusiveKeys(BaseRamlGrammar.TYPES_KEY_NAME, BaseRamlGrammar.SCHEMAS_KEY_NAME)); }

Target:
use static imports
Source:
protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; for (int i = 0; i<incidents.length; i++) { incidentDtos[i] = fromIncident(incidents[0]); } return incidentDtos; }

Target:
We should update the index to point to the current iteration of the loop. This way we always convert the first incident only. ```suggestion incidentDtos[i] = fromIncident(incidents[i]); ```
Source:
public SetLicenseKeyCmd(final String licenseKey) { this.LicenseKey = licenseKey; }

Target:
```suggestion this.licenseKey = licenseKey; ```
Source:
public static Restaurant createFakeRestaurant(ParseUser u) throws ParseException { ParseUser restUser = new ParseUser(); restUser.setUsername("testRestUser"); restUser.setPassword("12345"); restUser.setObjectId("_marksrest"); return new Restaurant(restUser); }

Target:
shouldn't you set the object Id?
Source:
private void disableMenuItem(Menu menu, int rID) { MenuItem item = menu.findItem(rID); item.setEnabled(false); item.setVisible(false); }

Target:
We need to add a null check for safety. Because our layouts are going to be dynamic we need to be able handle the case where we try to disable a MenuItem that doesn't exist. I know in the previous example there wasn't a null check. Thats because that piece of code was in an optionsmenyoncreate call where we can assert the existence of certain items. In summary for disabling a menu item first check if its null. That means it already is gone.
Source:
private void enableMenuItem(Menu menu, int rID) { MenuItem item = menu.findItem(rID); item.setEnabled(true); item.setVisible(true); }

Target:
Add a null check, if it is null add a menu item or invalidate the menu. Find some way of adding the menu item back in the view
Source:
public static long[] copyFromIntArray(int[] source) { long[] dest = new long[source.length]; for (int i = 0; i < source.length; i++) { dest[i] = source[i]; } return dest; }

Target:
@fchauveau there is no null handling of source, is this intended ?
Source:
public QueryRegistrationHandler(final TSDB tsdb, final HttpHandler next) { this.tsdb = tsdb; this.next = next; closeTask = new Runnable() { @Override public void run() { LOG.info("Closing the query!"); } }; }

Target:
debug and log the hash of the query for tracking
Source:
public HashCode buildHashCode() { final HashCode hc = Const.HASH_FUNCTION().newHasher() .putString(Strings.nullToEmpty(filter), Const.UTF8_CHARSET) .putString(Strings.nullToEmpty(pattern.pattern()), Const.UTF8_CHARSET) .hash(); return hc; }

Target:
This (And other filters) need their type as well. The reason being we could have a `TagValueRegexp` with a filter like `.*` and a `FieldRegexp` filter with the same filter and want them to hash to something different. For this and other regex filters, you can omit the pattern from equals and hash as those are just compiled versions of the `filter` field. It's ok not to use the parsed version even if someone puts a space in front or back.
Source:
public void prefixKeyWithSalt(final byte[] row_key, final int bucket) { if (salt_width == 1) { row_key[0] = (byte) bucket; return; } int shift = 0; for (int i = 0; i <= salt_width; i++) { row_key[salt_width - i] = 0; row_key[salt_width - i] = (byte) (bucket >>> shift); shift += 8; } }

Target:
This will replace the first byte of the metric name when i = 0. Also, total iterations are salt_width + 1. Starting from i = 1 may fix it.
Source:
public final boolean getBoolean(final String property) { final String val = this.properties.getProperty(property).toUpperCase(); if (val == null) throw new NullPointerException(); if (val.equals("1")) return true; if (val.equals("TRUE")) return true; if (val.equals("YES")) return true; return false; }

Target:
I believe this isn't necessary. If the property wasn't set, an NPE would have been thrown already when the code attempts to call `.toUpperCase()`. This line and the next may be removed.
Source:
private PrintLayer createMyPlacesPrintLayer(int categoryId, LayerProperties requestedLayer) { int opacity = requestedLayer.getOpacity() != null ? requestedLayer.getOpacity() : 100; if (opacity <= 0) { // Ignore fully transparent layers return null; } PrintLayer layer = new PrintLayer(); layer.setId(categoryId); layer.setType("myplaces"); layer.setVersion("1.3.0"); layer.setName("oskari:my_places_categories"); layer.setSrsName("EPSG:3067"); layer.setOpacity(opacity); return layer; }

Target:
You should take srs name from properties. There's something like oskari.native.srs that's used elsewhere in the codebase.
Source:
public boolean deleteIndicatorData(long indicator, long regionset, int year) { try (final SqlSession session = factory.openSession()) { int updated = getMapper(session).deleteData(indicator, regionset, year); if(updated != 1) { throw new ServiceRuntimeException("Delete wasn't successful"); } } return true; }

Target:
I wouldn't expect `public boolean delete()` to throw a RuntimeException in case there was nothing to delete. Instead I'd expect false to be returned, and an Exception to be thrown only in the case there was an actual Exception (like the DB connection unexpectedly error'd or something)
Source:
public void init() { super.init(); if(userLayerDbService == null) { userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); } }

Target:
No way to set the userLayerDbService so this will always be true
Source:
public void init() { super.init(); if(userLayerDbService == null) { setUserLayerDbService(OskariComponentManager.getComponentOfType(UserLayerDbService.class)); } }

Target:
Calling `super.init();` is unnecessary, since `ActionHandlers` implementation is empty.
Source:
private String getFileExt(String name) { int i = name.lastIndexOf('.'); if (i < 0 || i > name.length() - 1) { return null; } return name.substring(i + 1); }

Target:
True, I guess that would return an empty string instead of the null we now get on such a filename? Maybe i +1 == name.length() or name.endsWith(".") would be clearer? With "foo." isn't the i=3 and name.length() - 1 = 3 so the check wouldn't work properly now? Should check this in the morning, it's way too late for thinking this through :D
Source:
public void handleAction(ActionParameters params) throws ActionException { log.debug("Getting layer groups"); JSONArray json = getGroupJSON(-1,params, 0); log.debug("Got layer groups"); ResponseHelper.writeResponse(params, json); }

Target:
This file would read better if you have handleAction before getGroupJSON() since handleAction is the access point that uses getGroupJSON().
Source:
public ReferencedEnvelope getEnlargedEnvelope() { if(this.enlargedEnvelope == null) { log.warn("Enlarged envelope not created"); if(this.envelope == null) { this.getEnvelope(); } return this.envelope; } return this.enlargedEnvelope; }

Target:
I think this could be logged as just debug.
Source:
public boolean servesCoverage(String coverageId) { if (coverageId == null || coverageId.length() == 0) { return false; } return contents.getCoverageSummary().stream() .anyMatch(c -> coverageId.equals(c.getCoverageId())); }

Target:
String.isEmpty() is used in other places of Oskari. No biggie - just a heads up.
Source:
public boolean supportsFormat(String format) { if (format == null || format.length() == 0) { return false; } return serviceMetadata.getSupportedFormats().stream() .anyMatch(f -> format.equals(f)); }

Target:
Same here with length() == 0 -> isEmpty(). I'll stop mentioning for the rest of these :)
Source:
private List<Row> updateRows(List<Row> rows) { for (ListIterator<Row> it = rows.listIterator(); it.hasNext();) { final Row original = (Row) it.next(); validateUpdateType(original); final Row updated = update(original); it.set(updated); } return rows; }

Target:
Why add this here?
Source:
public static int getMajorVersion(String stringToParse){ String fullVersion = getVersion(stringToParse); if(fullVersion != null) { int firstDot = fullVersion.indexOf('.'); if(firstDot >= 0) { return Integer.valueOf(fullVersion.substring(0, firstDot)); } } return 0; }

Target:
`0` is a bad exception value I think, because versions might easily be 0-based. Better to go with `-1`.
Source:
private Set<String> getSchemaSQLServerNames(DatabaseMetaData metaData) throws SQLException { // Distinct schema names. metaData.getTables() is a denormalized // resultset Set<String> schemas = new HashSet<>(); ResultSet rs = metaData.getTables(_catalogName, null, null, JdbcUtils.getTableTypesAsStrings(_tableTypes)); while (rs.next()) { schemas.add(rs.getString("TABLE_SCHEM")); } FileHelper.safeClose(rs); return schemas; }

Target:
This should be in a finally block that you create once you have the ResultSet: ``` ResultSet rs = ... try { ... } finally { FileHelper.safeClose(rs); } ```
Source:
public RowInsertionBuilder value(final int columnIndex, final Object value) { values.set(columnIndex, value); return this; }

Target:
Wait ... So how would a user be able to pass in a column that's not already defined? I see that `HBaseTable` returns `HBaseColumn`s which represent that paths down into the column families as defined by the `SimpleTableDef`s. So it's kind of dynamic based on that `SimpleTableDef`. But is there some way that the columns will change after creating the simple table def? Or rather - in the middle of a update script? I don't see how that would be possible, but maybe it is, and then I think that deserves some clarification (since it's unusual for MetaModel).
Source:
private void appendRemarks(MutableColumn column, String remarks) { final String existingRemarks = column.getRemarks(); if (existingRemarks == null) { column.setRemarks(remarks); } else { column.setRemarks(existingRemarks + ", " + remarks); } }

Target:
Could be static, if I'm not blind
Source:
public WildcardPattern(String pattern, char wildcard) { _pattern = pattern; _wildcard = wildcard; _startsWithDelim = (_pattern.charAt(0) == _wildcard); _endsWithDelim = (_pattern.charAt(pattern.length() - 1) == _wildcard); }

Target:
This will throw IndexOutOfBoundsException if an empty string is passed as the pattern.
Source:
public CustomColumnNamingStrategy(String... columnNames) { this.columnNames = Arrays.asList(columnNames); }

Target:
No biggie, but I guess best practice would be to do `this(Arrays.asList(columnNames));`
Source:
private static void indexTweeterDocument(String indexType, int id, Date date) { try { client.prepareIndex(indexName, indexType).setSource(buildTweeterJson(id, date)) .setId("tweet_" + indexType + "_" + id).execute().actionGet(); } catch (Exception ex) { System.out.println("Exception indexing documents!!!!!"); } }

Target:
Wouldn't a rethrow be better?
Source:
public AggregateFunction getAggregateFunction() { if (_function instanceof AggregateFunction) return (AggregateFunction) _function; else return null; }

Target:
I'm also missing some brackets here to comply with our normal code style.
Source:
protected Schema getMainSchema() throws MetaModelException { if (schema == null) { MutableSchema theSchema = new MutableSchema(getMainSchemaName()); for (SimpleTableDef tableDef: tableDefs) { MutableTable table = tableDef.toTable().setSchema(theSchema); theSchema.addTable(table); } schema = theSchema; } return schema; }

Target:
No need to cache the schema here. The superclass will automatically cache the schema until "refreshSchemas" is called.
Source:
public int hashCode() { int bits = 1; bits = 31 * bits + this.type.ordinal(); bits = 31 * bits + getToX(); bits = 31 * bits + getToY(); bits = 31 * bits + getToZ(); return bits; }

Target:
Please replace by `bits ^ (bits >> 31)`
Source:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(getX1()); bits = 31 * bits + Double.doubleToLongBits(getY1()); bits = 31 * bits + Double.doubleToLongBits(getX2()); bits = 31 * bits + Double.doubleToLongBits(getY2()); final int b = (int) bits; return b; }

Target:
Please replace all you change by something similar to `b ^ (b >> 31)`.
Source:
public int hashCode() { int bits = 1; bits = 31 * bits + this.minx; bits = 31 * bits + this.miny; bits = 31 * bits + this.minz; bits = 31 * bits + this.maxx; bits = 31 * bits + this.maxy; bits = 31 * bits + this.maxz; return bits; }

Target:
`b ^ (b >> 31)` is missed here.
Source:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(this.scalar); bits = 31 * bits + ((this.vector == null) ? 0 : this.vector.hashCode()); final int b = (int) bits; return b; }

Target:
`b ^ (b >> 31)` is missed here.
Source:
public double getY1() { return y1; }

Target:
This access to the attribute is forbidden by the coding rules. Compiler says: ``` return x1; ^^ Unqualified access to the field BasicPathShadow2afp.CoordinatesParam.x1 ``` You must add the `this.` prefix.
Source:
public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } final ListResponseModel lObj = (ListResponseModel) obj; if (delegate.equals(lObj.delegate)) { return delegate.equals(lObj.delegate); } return false; }

Target:
Should be: ``` java public boolean equals(Object obj) { return this.delegate.equals(obj); } ``` Indeed, this class is a delegation design pattern and does no have any attributes except the delegate.
Source:
public int hashCode() { int hash = 1; final int prime = 31; hash = hash * prime + (int) (delegate.hashCode()); return hash; }

Target:
Should be: ``` java public int hashCode() { return this.delegate.hashCode(); } ```
Source:
public D[] getAllUserData(D[] array) { if (this.data == null) { return (D[]) Array.newInstance(array.getClass(),0); } return this.data.toArray(array); }

Target:
Caution: array parameter could be null.
Source:
public double getProgressionFactor() { final double extent = this.max - (double) this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) / extent; }

Target:
here, extent must be an integer.
Source:
public double getPercent() { final double extent = this.max - (double) this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) * 100. / extent; }

Target:
here, extent must be an integer.
Source:
private void setAlpha(RoundedImageView view, float alpha) { if (Build.VERSION.SDK_INT < 11) { view.setAlpha((int) (255 * alpha)); } else { view.setAlpha(alpha); } }

Target:
I suggest to use positive case for more often scenarios when SDK >= 11
Source:
private TarArchive getApplicationContent(Owner owner, Libraries libraries) { File jarFile = getJarFile(); ImagePackager packager = getConfiguredPackager(() -> new ImagePackager(jarFile)); if (jarFile.exists()) { return TarArchive.fromZip(jarFile, owner); } return new PackagedTarArchive(owner, libraries, packager); }

Target:
The `packager` can be moved below the `if` as it doesn't seem to be used when the jar exists already, I guess.
Source:
private boolean isEnabled() { DataSourceInitializationMode mode = this.properties.getInitializationMode(); if (mode == DataSourceInitializationMode.NEVER) { return false; } return mode != DataSourceInitializationMode.EMBEDDED || isEmbedded(); }

Target:
We prefer multi if statements to stay separate for better readability.
Source:
private boolean isHelpShown(Command command) { return !(command instanceof HelpCommand) && !(command instanceof HintCommand); }

Target:
I find this harder to read
Source:
private List<Mojo> parseMojos(Node plugin) throws XPathExpressionException { List<Mojo> mojos = new ArrayList<>(); for (Node mojoNode : nodesAt("//plugin/mojos/mojo", plugin)) { mojos.add(new Mojo(textAt("goal", mojoNode), format(requireNonNull(textAt("description", mojoNode))), parseParameters(mojoNode))); } return mojos; }

Target:
I don't think an explicit check is needed.
Source:
default String getServletUrlMapping() { if ("".equals(getPath()) || "/".equals(getPath())) { return "/"; } if (getPath().contains("*")) { return getPath(); } if (getPath().endsWith("/")) { return getPath() + "*"; } return getPath() + "/*"; }

Target:
`getPath` does not return `null`.
Source:
default String getUrlMapping() { String path = getPath(); if (!path.startsWith("/")) { path = "/" + path; } if ("/".equals(path)) { return "/*"; } if (path.contains("*")) { return path; } if (path.endsWith("/")) { return path + "*"; } return path + "/*"; }

Target:
There is a usage of `path` right above so that change isn't necessary.
Source:
private void disableGrabResolvers(List<? extends AnnotatedNode> nodes) { for (AnnotatedNode classNode : nodes) { List<AnnotationNode> annotations = classNode.getAnnotations(); for (AnnotationNode node : new ArrayList<>(annotations)) { if ("GrabResolver".equals(node.getClassNode().getNameWithoutPackage())) { node.setMember("initClass", new ConstantExpression(false)); } } } }

Target:
This doesn't return null either.
Source:
private void addUrl(URL url) { if ("file".equals(url.getProtocol()) && url.getPath().endsWith("/")) { try { this.folders.add(ResourceUtils.getFile(url)); } catch (Exception ex) { logger.warn(LogMessage.format("Unable to get classpath URL %s", url)); logger.trace(LogMessage.format("Unable to get classpath URL %s", url), ex); } } }

Target:
The protocol is mandatory so this isn't necessary.
Source:
protected boolean isMain(Thread thread) { return "main".equals(thread.getName()) && thread.getContextClassLoader().getClass().getName().contains("AppClassLoader"); }

Target:
Thread name is mandatory.
Source:
public void execute() throws MojoExecutionException, MojoFailureException { if ("pom".equals(this.project.getPackaging())) { getLog().debug("repackage goal could not be applied to pom project."); return; } if (this.skip) { getLog().debug("skipping repackaging as per configuration."); return; } repackage(); }

Target:
packaging has a default so there is no need to do that.
Source:
private boolean isJava13OrLater() { for (Method method : String.class.getMethods()) { if ("stripIndent".equals(method.getName())) { return true; } } return false; }

Target:
No need to do this either.
Source:
private boolean isSet(ConfigurableEnvironment environment, String property) { String value = environment.getProperty(property); return (value != null && !"false".equals(value)); }

Target:
Can be replaced by `Boolean.parseBoolean`
Source:
public int getRequestedChannelMax() { return this.requestedChannelMax; }

Target:
Getter/Setter should be co-located.
Source:
public Object findFilterId(Annotated a) { Object id = super.findFilterId(a); return (id != null) ? id : CONFIGURATION_PROPERTIES_FILTER_ID; }

Target:
This is unrelated to the task at hand, please refrain from polishing code even if it's in the same class.
Source:
public void customDisableMaxHttpPostSize() { bind("server.tomcat.max-http-post-size=-1"); bind("server.tomcat.max-http-form-post-size=-1"); customizeAndRunServer((server) -> assertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1)); }

Target:
We should probably have two tests to make sure that the old property still works. As you've added `customDisableMaxHttpFormPostSize` below, this test should be left unchanged.
Source:
public String getHostHeader() { return this.remoteIpValve.getHostHeader() == null ? this.hostHeader : this.remoteIpValve.getHostHeader(); }

Target:
it should be just `return this.remoteIpValve.getHostHeader();`
Source:
public SpringApplicationAdminMXBeanRegistrar springApplicationAdminRegistrar( ObjectProvider<MBeanExporter> mbeanExporters, Environment environment) throws MalformedObjectNameException { String jmxName = environment.getProperty(JMX_NAME_PROPERTY, DEFAULT_JMX_NAME); if (mbeanExporters != null) { // Make sure to not register that MBean twice mbeanExporters.orderedStream().forEach(mbeanExporter -> { mbeanExporter.addExcludedBean(jmxName); }); } return new SpringApplicationAdminMXBeanRegistrar(jmxName); }

Target:
I don't think the ordering is important here.
Source:
void bindDataSourcesToRegistry(Map<String, DataSource> dataSources, MeterRegistry registry, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { List<DataSourcePoolMetadataProvider> metadataProvidersList = metadataProviders.orderedStream() .collect(Collectors.toList()); dataSources.forEach( (name, dataSource) -> bindDataSourceToRegistry(name, dataSource, metadataProvidersList, registry)); }

Target:
Does ordering matter here? The providers are used in a first wins manner. For the ordering to be important there would have to be overlap between providers.
Source:
void redisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) .withPropertyValues("spring.session.store-type=redis", "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", "spring.session.redis.save-mode=on-get-attribute", "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesRedis("foo:event:0:created:", FlushMode.IMMEDIATE, "0 0 12 * * *", SaveMode.ON_GET_ATTRIBUTE)); }

Target:
Can you please put the save-mode after the cron so that the order of properties are aligned with the assertion?
Source:
public Cluster couchbaseCluster() { CouchbaseCluster couchbaseCluster = CouchbaseCluster .create(couchbaseEnvironment(), determineBootstrapHosts()); if (this.properties.getUsername() != null && this.properties.getPassword() != null) { return couchbaseCluster.authenticate(this.properties.getUsername(), this.properties.getPassword()); } return couchbaseCluster; }

Target:
The `username` and `password` properties are initialized to empty string (`""`). Will they ever be null? A better check might be `.isEmpty()`.
Source:
public Bucket couchbaseClient() { if (this.properties.getUsername().isEmpty() || this.properties.getPassword().isEmpty()) { return couchbaseCluster().openBucket(this.properties.getBucket().getName()); } return couchbaseCluster().openBucket(this.properties.getBucket().getName(), this.properties.getBucket().getPassword()); }

Target:
This condition should be inverted. If RBAC `username` or `password` are empty we should call the openBucket method that takes a bucket password. Sorry if I missed this earlier.
Source:
void configure(MeterRegistry registry) { // Customizers must be applied before binders, as they may add custom // tags or alter timer or summary configuration. customize(registry); addFilters(registry); if (this.hasCompositeMeterRegistry) { if ((registry instanceof CompositeMeterRegistry)) { addBinders(registry); } } else { if (!(registry instanceof CompositeMeterRegistry)) { addBinders(registry); } } if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) { Metrics.addRegistry(registry); } }

Target:
Rather than `hasCompositeMeterRegistry` it might be better to be straightforward about what this controls. Something like `onlyBindToCompositeRegistry`.
Source:
private PushGateway getPushGateway(String url) { try { return new PushGateway(new URL(Objects.toString(url, ""))); } catch (MalformedURLException ex) { return new PushGateway(url); } }

Target:
I don't think we need to do `Objects.toString(url, "")` since the property has a default value of `localhost:9091`.
Source:
public TomcatConnectorCustomizer connectorCustomizer() { return (connector) -> connector.setPort(9001); }

Target:
This might cause a port clash if something else is used port 9001. It would be safer if the customizer didn't do anything to the connector.
Source:
public void tomcatContextCustomizerBeanIsAddedToFactory() { WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) .withConfiguration(AutoConfigurations .of(ServletWebServerFactoryAutoConfiguration.class)) .withUserConfiguration( TomcatContextCustomizerConfiguration.class); runner.run((context) -> { TomcatServletWebServerFactory factory = context .getBean(TomcatServletWebServerFactory.class); assertThat(factory.getTomcatContextCustomizers()).hasSize(1); }); }

Target:
If this test passes then this assertion isn't quite right as `TomcatContextCustomizerConfiguration` doesn't define a `TomcatContextCustomizer`. The assertions needs to be written such that if you remove `.withUserConfiguration(TomcatContextCustomizerConfiguration.class)` the test will fail.
Source:
public HierarchicalNameMapper graphiteHierarchicalNameMapper(GraphiteConfig config) { return new GraphiteHierarchicalNameMapper(config.tagsAsPrefix()); }

Target:
This should declare that `GraphiteHierarchicalNameMapper` is returned to provide as much type information to the bean factory as possible.
Source:
void shutdown() { this.executorService.shutdown(); if (this.pushgatewayProperties.isPushOnShutdown()) { push(); } if (this.pushgatewayProperties.isDeleteOnShutdown()) { try { this.pushGateway.delete(job(), this.pushgatewayProperties.getGroupingKeys()); } catch (Throwable throwable) { this.logger.error( "Unable to delete metrics from Prometheus Pushgateway", throwable); } } }

Target:
Perhaps extract a `delete()` method here?
Source:
protected List<String> getAndProcessPropertySourceProperties( MergedContextConfiguration mergedConfig) { List<String> propertySourceProperties = new ArrayList<>( Arrays.asList(mergedConfig.getPropertySourceProperties())); String differentiator = getDifferentiatorPropertySourceProperty(); if (differentiator != null) { propertySourceProperties.add(differentiator); } processPropertySourceProperties(mergedConfig, propertySourceProperties); return propertySourceProperties; }

Target:
If `org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getProperties(Class<?>)` was overridden instead, I think this method could continue to be `private`. Perhaps I have missed something?
Source:
public SpringBootConfigurationFinder() { this.scanner = new ClassPathScanningCandidateComponentProvider(false); this.scanner.addIncludeFilter( new AnnotationTypeFilter(SpringBootConfiguration.class)); this.scanner.setResourcePattern("*.class"); }

Target:
Rather than a copy/paste, this should call the other constructor you've created with `SpringBootConfiguration.class`
Source:
public void afterPropertiesSet() { this.embeddedDatabase = this.factory.getEmbeddedDatabase(); }

Target:
This change appears to be unrelated.
Source:
public DataSource getObject() { return this.embeddedDatabase; }

Target:
This change appears to be unrelated.
Source:
EmbeddedDatabase getEmbeddedDatabase() { EmbeddedDatabaseConnection connection = this.environment.getProperty( "spring.test.database.connection", EmbeddedDatabaseConnection.class, EmbeddedDatabaseConnection.NONE); if (EmbeddedDatabaseConnection.NONE.equals(connection)) { connection = EmbeddedDatabaseConnection.get(getClass().getClassLoader()); } Assert.state(connection != EmbeddedDatabaseConnection.NONE, "Failed to replace DataSource with an embedded database for tests. If " + "you want an embedded database please put a supported one " + "on the classpath or tune the replace attribute of " + "@AutoConfigureTestDatabase."); return new EmbeddedDatabaseBuilder().generateUniqueName(true) .setType(connection.getType()).build(); }

Target:
This change appears to be unrelated.
Source:
private static synchronized void disableCaching() { if (!cacheDisabled) { cacheDisabled = true; doDisableCaching(); } }

Target:
Why is this now `synchronized`?
Source:
public void setCurrentUrl( URL urlCurrent ) { oldFeedSource.setCurrentUrl( urlCurrent ); newFeedSource.setCurrentUrl( urlCurrent ); }

Target:
Hm... Migration feed is where it probably does not make sense to have Archive URLs. Maybe we can make these methods no-op?
Source:
public boolean hasRequiredProperties(MessageAddressingProperties map) { if (map.getAction() == null) { return false; } if ((map.getReplyTo() != null && !hasAnonymousAddress(map.getReplyTo()) && !hasNoneAddress(map.getReplyTo())) || (map.getFaultTo() != null && !hasAnonymousAddress(map.getFaultTo()) && !hasNoneAddress(map.getFaultTo()))){ return map.getMessageId() != null; } return true; }

Target:
Reading six boolean expressions chained together in collection of "ands", "ors" and "nots" takes me back to logical gate construction and makes me need a Venn diagram to grok. Could you extract some functions that embody the intent so its more readable?
Source:
private void logoutIfNeeded() throws InterruptedException { if (isViewDisplayed(getViewById(R.id.list_root)) == false) { return; } loadSettingsFromNotesList(); // Swipe to perform a scroll (because I couldn't get a reference to a scrollable view) // that will reveal the logout button. onView(withId(R.id.preferences_container)).perform(swipeUp()); // Logout selectSettingsOption(R.string.log_out, logoutPosition); // Give time to the logout to finish waitForViewMatching(withId(R.id.button_login), 1000); }

Target:
```suggestion if (!isViewDisplayed(getViewById(R.id.list_root))) { ``` We can simplify `!isViewDisplayed(getViewById(R.id.list_root))` to `isViewDisplayed(getViewById(R.id.list_root)) == false`.
Source:
private void enterThenDisablePasscodeIfNeeded() { if (isViewDisplayed(getViewById(R.id.button1)) == false) { return; } typeFullPasscode(); loadSettingsFromNotesList(); loadPasscodeUnsetterFromSettings(); typeFullPasscode(); dismissSettings(); }

Target:
```suggestion if (!isViewDisplayed(getViewById(R.id.button1))) { ``` We can simplify `isViewDisplayed(getViewById(R.id.button1)) == false` to `!isViewDisplayed(getViewById(R.id.button1))`.
Source:
public static void removePref(Context context, String prefKey){ SharedPreferences prefs = getPrefs(context); if (!prefs.contains(prefKey)){ return; } SharedPreferences.Editor editor = prefs.edit(); editor.remove(prefKey); editor.commit(); }

Target:
We can now use `apply()` instead of `commit()`, which will save the preference outside of the UI thread.
Source:
private HttpURLConnection openConnection(URL url) throws IOException { return (HttpURLConnection) url.openConnection(); }

Target:
```suggestion private static HttpURLConnection openConnection(URL url) throws IOException { ```
Source:
private InputStream openStream(String url) throws IOException { return new URL(url).openStream(); }

Target:
```suggestion private static InputStream openStream(String url) throws IOException { ```
Source:
public static ConfigurationLoader from(final Properties props) throws IOException { return new ConfigurationLoader(new Function<String, String>() { @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", justification = "False positive. I don't know what spotbugs is doing here.") public String apply(String from) { return props.getProperty(from); } }); }

Target:
BTW could convert to lambda
Source:
public void controller(FragmentModel model, @FragmentParam(required = true, value = "uuid") String uuid) throws Exception { PersonAttributeType personAttributeType = Context.getPersonService().getPersonAttributeTypeByUuid(uuid); if(personAttributeType.getFormat().contentEquals(Concept.class.getCanonicalName())){ int foreignKey = personAttributeType.getForeignKey(); model.put("foreignKey", foreignKey); model.put("codedPersonAttribute", true); } else{ model.put("codedPersonAttribute", false); } }

Target:
I think this should be `personAttributeType.getFormat().equals(Concept.class.getName())`
Source:
public void sendMessageSync(String destAddress, String message, boolean command) throws MessageException { Response response = getRequestBuilder().post(Entity.entity( preparePayload(destAddress, message.trim()), mediaType)); if (response.getStatus() / 100 != 2) { throw new MessageException(response.readEntity(String.class)); } }

Target:
I think we should do trim in the `preparePayload` method.
Source:
public void testDecode() throws Exception { GpsmtaProtocolDecoder decoder = new GpsmtaProtocolDecoder(new GpsmtaProtocol()); verifyPosition(decoder, text( "3085a94ef459 1446536867 49.81621 24.054207 1 0 22 0 10 12 24 0 0")); verifyPosition(decoder, text( "864528021249771 1446116686 49.85073 24.004438 0 217 6 338 00 59 27 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 49.85064 24.003979 1 0 40 0 10 110 26 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 -49.85064 24.003979 1 0 40 0 10 110 26 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 49.85064 -24.003979 1 0 40 0 10 110 26 0 0")); verifyPosition(decoder, text( "359144048138856 1442932957 -49.85064 -24.003979 1 0 40 0 10 110 26 0 0")); }

Target:
I don't think we need tests for all possible combinations. Just one would be enough.
Source:
public void sendMessageSync(String destAddress, String message, boolean command) throws InterruptedException, MessageException { Response response = getRequestBuilder().post(Entity.json(preparePayload(destAddress, message))); if (!response.getStatusInfo().equals(Response.Status.OK)) { String output = response.readEntity(String.class); throw new MessageException(new Exception(output)); } }

Target:
Please add `MessageException(String message)` constructor to `MessageException` class instead of creating proxy `Exception`
Source:
public static String formatShortMessage(long userId, Event event, Position position) { String templatePath = Context.getConfig().getString("message.short.templatesPath", "short"); return formatMessage(null, userId, event, position, templatePath); }

Target:
Not really related to this pull request, but I think we should just assume "full" and "short" sub-paths here. Base path can still be configurable.
Source:
public void testEncodePositionSingle() throws Exception { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_POSITION_SINGLE); Assert.assertEquals("(123456789012345AP00)", encoder.encodeCommand(command)); IdentityManager old = Context.getIdentityManager(); Context.init(t580wManager); try { Assert.assertEquals("[begin]sms2,*getposl*,[end]", encoder.encodeCommand(command)); } finally { Context.init(old); } }

Target:
This is just wrong.
Source:
public MultiPartEventForwarder() { payloadParamName = Context.getConfig().getString("event.forward.paramMode.payloadParamName", "payload"); additionalParams = Context.getConfig().getString("event.forward.paramMode.additionalParams", ""); }

Target:
Why empty string and not null?
Source:
protected String formatCommand(Command command, String format, String... keys) { return super.formatCommand(command, format, this, keys); }

Target:
Why `super`?
Source:
public OsmAndProtocolDecoder(OsmAndProtocol protocol) { super(protocol); speedUnits = Context.getConfig().getString("osmand.speedUnits", "kn"); }

Target:
Please make it consistent with other places: https://github.com/tananaev/traccar/blob/master/src/org/traccar/protocol/Tk103ProtocolDecoder.java#L256 Possibly updating TK103 decoder would be even better.
Source:
public User login(String email, String password) throws SQLException { User user = QueryBuilder.create(dataSource, getQuery("database.loginUser")) .setString("email", email.trim().toLowerCase()) .executeQuerySingle(User.class); if (user != null && user.isPasswordValid(password)) { return user; } else { return null; } }

Target:
I agree with trimming, but I don't understand why we need to lower-case it.