auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testNotAllOutputsReferenced() { tester().assertThat(new PruneIndexSourceColumns()) .on(p -> buildProjectedIndexSource(p, symbol -> symbol.getName().equals("orderkey"))) .matches( strictProject( ImmutableMap.of("x", PlanMatchPattern.expression("orderkey")), constrainedIndexSource( "orders", ImmutableMap.of("totalprice", Domain.onlyNull(DOUBLE)), ImmutableMap.of( "orderkey", "orderkey", "totalprice", "totalprice")))); }

Target:
static imort?
Source:
public void close() { if (httpClient != null) { httpClient.close(); } }

Target:
you don't need to check for null since this gets set in the constructor
Source:
public static Slice crc32(@SqlType(StandardTypes.VARBINARY) Slice slice) { Slice hash = Slices.allocate(Long.BYTES); CRC32 crc32 = new CRC32(); crc32.update(slice.toByteBuffer()); // The expectation is that CRC32 is unsigned, so this won't fit // correctly in a 32 signed integer, therefore this uses a long. long crc32Value = crc32.getValue(); hash.setLong(0, Long.reverseBytes(crc32Value)); return hash; }

Target:
I did a bunch of investigation and had quite a discussion with @martint. We decide that crc32 will return a number (instead of binary). I'm sorry for the change. Please change accordingly. I looked into PHP, java (java.util.zip), Java (Guava), C++ Boost, Python (binascii), and Ruby (zlib). It turns out there is no general consensus on byte order for representation of the result.
Source:
public Class<? extends ConnectorTableHandle> getTableHandleClass() { return TestingMetadata.TestingTableHandle.class; }

Target:
static import
Source:
private static PlanFragment createTableScanPlanFragment(String name) { Symbol symbol = new Symbol("column"); PlanNode planNode = new TableScanNode( new PlanNodeId(name), new TableHandle(new ConnectorId("test"), new TestingMetadata.TestingTableHandle()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column")), Optional.empty(), TupleDomain.all(), null); return createFragment(planNode); }

Target:
static import
Source:
public TableScanNode tableScan(List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments) { TableHandle tableHandle = new TableHandle(new ConnectorId("testConnector"), new TestingMetadata.TestingTableHandle()); return tableScan(tableHandle, symbols, assignments); }

Target:
static import
Source:
private void avroAssertColumnTypes(QueryResult queryResult) { Connection connection = defaultQueryExecutor().getConnection(); if (usingPrestoJdbcDriver(connection)) { assertThat(queryResult).hasColumns( BIGINT, DOUBLE, BIGINT ); } else if (usingTeradataJdbcDriver(connection)) { assertThat(queryResult).hasColumns( BIGINT, DOUBLE, BIGINT ); } else { throw new IllegalStateException(); } }

Target:
these conditions are the same. you should combine them
Source:
public void setNoMorePages() { checkState(!Thread.holdsLock(this), "Can not set no more pages while holding a lock on this"); state.compareAndSet(OPEN, NO_MORE_PAGES); state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); memoryManager.setNoBlockOnFull(); masterBuffer.setNoMorePages(); // process any pending reads from the client buffers for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { if (masterBuffer.isEmpty()) { clientBuffer.setNoMorePages(); } else { clientBuffer.loadPagesIfNecessary(masterBuffer); } } checkFlushComplete(); }

Target:
I'm not sure this is correct. The `ClientBuffer` has a push and a pull mode. The push mode uses `enueuPages` and `setNoMorePages` and the pull mode uses `loadPagesIfNecessary`. I'm not confident that using `setNoMorePages` in a pull mode would do what we want. Instead, I suggest we simply call `loadPagesIfNecessary` on every `ClientBuffer` and then modify `loadPagesIfNecessary` to properly handle being called with a `!pagesSupplier.mayHaveMorePages()`.
Source:
private void reset() { probeIndexBuilder.reset(); buildPageBuilder.reset(); // Reset source page when probe reached the end. if (reachedProbeEnd) { probe = null; } }

Target:
Isn't that if `reset` is called we know we reached end of the probe?
Source:
private static ListenableFuture<?> getBlockedFuture(Operator operator) { ListenableFuture<?> blocked = operator.isBlocked(); if (blocked.isDone()) { blocked = operator.getOperatorContext().isWaitingForMemory(); } return blocked; }

Target:
It looks like what you really want is to say, "I'm blocked" until both of these conditions are satisfied. If so, you can simple replace the original method with: ```java return Futures.allAsList(operator.isBlocked(), operator.getOperatorContext().isWaitingForMemory()); ```
Source:
public void addEventListenerFactory(EventListenerFactory eventListenerFactory) { configuredEventListener.set(Optional.of(eventListenerFactory.create(ImmutableMap.of(), new EventListenerContext() { private final MBeanServer mBeanServer = getMBeanNamespaceManager().createMBeanServer("TestEventListener"); @Override public MBeanServer getMBeanServer() { return mBeanServer; } }))); }

Target:
Declare outside
Source:
public void init() throws Exception { queryRunner = queryRunner != null ? queryRunner : queryRunnerSupplier.get(); h2QueryRunner = new H2QueryRunner(); sqlParser = new SqlParser(); costCalculator = new CoefficientBasedCostCalculator(queryRunner.getMetadata()); }

Target:
This seems wrong. The `@BeforeClass` method should never be called more than once.
Source:
public StatusPrinter(StatementClient client, PrintStream out) { this.client = client; this.out = out; this.console = new ConsolePrinter(out); this.debug = client.isDebug(); this.mappingPreviousStageStatuses = new HashMap<>(); }

Target:
inline to its declaration.
Source:
public double next() throws IOException { input.readFully(buffer, 0, (int) SIZE_OF_DOUBLE); return slice.getDouble(0); }

Target:
This cast is not necessary (same with the others)
Source:
public synchronized Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments) { requireNonNull(insertHandle, "insertHandle is null"); checkArgument(insertHandle instanceof MemoryInsertTableHandle); MemoryInsertTableHandle memoryInsertHandle = (MemoryInsertTableHandle) insertHandle; updateRowsOnHosts(memoryInsertHandle.getTable(), fragments); return Optional.empty(); }

Target:
Remove instanceof checks - doesn't add any value. Look at other implementations of ConnectorMetadata
Source:
private static long getSliceArrayRetainedSizeInBytes(Slice[] values) { long sizeInBytes = SizeOf.sizeOf(values); Map<Object, Boolean> uniqueRetained = new IdentityHashMap<>(values.length); for (Slice value : values) { if (value != null && value.getBase() != null && uniqueRetained.put(value.getBase(), true) == null) { sizeInBytes += value.getRetainedSize(); } } return sizeInBytes; }

Target:
Replace `SizeOf.sizeOf`. You statically imported it.
Source:
public Optional<Decorrelated> decorrelate(PlanNode reference) { checkArgument(reference instanceof GroupReference); return lookup.resolve(reference).accept(this, reference); }

Target:
If this has to be a GroupReference, just take that as an argument.
Source:
public Optional<Decorrelated> visitFilter(FilterNode node, PlanNode reference) { Optional<Decorrelated> result = decorrelate(node.getSource()); return result.map(decorrelated -> { return new Decorrelated( ImmutableList.<Expression>builder() .addAll(decorrelated.getCorrelatedPredicates()) // No need to retain uncorrelated conditions, predicate push down will push them back .add(node.getPredicate()) .build(), decorrelated.getDecorrelatedNode() ); }); }

Target:
No need for `{ ... }` and `return`. It's a single expression.
Source:
public int hashCode() { return Objects.hash(message, sqlState, errorCode, errorName, errorType, errorLocation, failureInfo); }

Target:
please order the same as in equals so it's obvious whether all are here (why is equals required?)
Source:
protected Boolean visitBetweenPredicate(BetweenPredicate actual, Expression expectedExpression) { if (expectedExpression instanceof BetweenPredicate) { BetweenPredicate expected = (BetweenPredicate) expectedExpression; return process(actual.getMin(), expected.getMin()) && process(actual.getMax(), expected.getMax()); } return false; }

Target:
It needs to process the "value" from the between predicate, too.
Source:
public String idFromValueAndType(Object value, Class<?> suggestedType) { requireNonNull(value, "value is null"); if(value instanceof TupleExpression) { TupleExpression expression = (TupleExpression)value; if(expression instanceof DomainExpression) { return expression.getName() + "@@" + nameResolver.apply((ColumnHandle) ((DomainExpression) expression).getColumn()) ; } return expression.getName(); } else return null; }

Target:
Missing brackets.
Source:
public void testHexNoHashSign() { assertThat(faker.color().hex(true), matchesRegularExpression("^[0-9A-F]{6}$")); }

Target:
technically you should have a test that tests passing in a false... so `testHexWithHashSign()`
Source:
public final String toString() { return this.joinpoint.toString(); }

Target:
@shelan so no need to declare every method as final
Source:
private Callable<Throwable> callable(final ProceedingJoinPoint point, final CountDownLatch start) { return new Callable<Throwable>() { @Override public Throwable call() { try { start.await(); point.proceed(); // @checkstyle IllegalCatchCheck (1 line) } catch (Throwable ex) { return ex; } return null; } }; }

Target:
I don't like this multiple returning in one method. Better declare `Throwable result` and assign it twice, and return once.
Source:
protected void removeAllAnnotations() { // clear normal markers for (int i = 0; i < timarkers.size(); i++) { TiMarker timarker = timarkers.get(i); if (timarker.getMarker() != null) { timarker.getMarker().remove(); timarker.release(); } } timarkers.clear(); // clear cluster markers if (mClusterManager != null) { mClusterManager.clearItems(); mClusterManager.cluster(); } }

Target:
```Java if (timarker.getMarker() != null) { timarker.getMarker().remove(); } timarker.release(); ```
Source:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { try { testExecutor.configure() .init(defaultArguments()); } catch (WebDriverException ex) { // should happen } JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions.build(), (JavascriptStateValidator) (driver, output, events) -> { assertThat(jsDriver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }

Target:
Hopefully, it is understandable and I don't just confuse you more. I like our JS tests, but lots of people are struggling with them. It is almost done though, just some nitpicks to fix
Source:
public JavascriptTestExecutor login() { return login((JSObjectBuilder)null, null); }

Target:
```suggestion return login((String)null, null); ```
Source:
public JavascriptTestExecutor login(JavascriptStateValidator validator) { return login((JSObjectBuilder)null, validator); }

Target:
```suggestion return login((String)null, validator); ```
Source:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { try { testExecutor.configure() .init(defaultArguments()); } catch (WebDriverException ex) { // should happen } JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }

Target:
This `try-catch` block is not necessary. It is necessary only when you are using `onLoad: login-required`.
Source:
public boolean correspondsTo(AttributeType attribute) { return Objects.equals(this.uri, attribute.getName()) || Objects.equals(this.friendlyName, attribute.getFriendlyName()); }

Target:
ensure that attribute is not null to prevent NPE
Source:
private SAMLAttributeParser() { super(SAMLAssertionQNames.ATTRIBUTE); Set<String> localAttributeNames = new HashSet<>(); for (SAMLAssertionQNames name : Arrays.asList(SAMLAssertionQNames.ATTR_NAME, SAMLAssertionQNames.ATTR_FRIENDLY_NAME, SAMLAssertionQNames.ATTR_NAME_FORMAT)) { localAttributeNames.add(name.getQName().getLocalPart()); } DEFAULT_KNOWN_LOCAL_ATTRIBUTE_NAMES = localAttributeNames; }

Target:
Remove this whole block (l49-54) since this has moved to static initialization above.
Source:
public void setAttribute(String name, List<String> values) { // Remove all existing removeAttribute(name); List<String> nonNullValues = values.stream().filter(Objects::nonNull).collect(Collectors.toList()); // Put all new nonNull values for (String value : nonNullValues) { persistAttributeValue(name, value); } }

Target:
No need to realize this list into memory via `.collect`. you can either obtain a stream `iterator()` or use `Stream.forEach()`.
Source:
public void init(Config.Scope config) { Integer maxDetail = config.getInt("max-detail-length", 0); maxDetailLength = (maxDetail == null) ? 0 : maxDetail; }

Target:
maxDetail won't be null, so you can just do: `maxDetailLength = config.getInt("max-detail-length", 0);`
Source:
private String trimToMaxLength(String detail) { if (detail != null && detail.length() > maxDetailLength) { String result = detail.substring(0, maxDetailLength).concat("..."); logger.warn("Detail was truncated to " + result); return result; } else { return detail; } }

Target:
It should take `...` into account in the max-length, so the string with `...` should be max maxDetailLength long
Source:
public static ProviderConfigurationBuilder configurationBuilder() { return ProviderConfigurationBuilder.create() .property(Attributes.PRIORITY_PROPERTY) .property(Attributes.ENABLED_PROPERTY) .property(Attributes.ACTIVE_PROPERTY); }

Target:
If "final" is removed it would make it possible to override from subclass, so this change should be reverted
Source:
public static OAuth2Code deserializeCode(Map<String, String> data) { return new OAuth2Code(data); }

Target:
See above. Final prevents overriding.
Source:
public boolean supportsCredentialType(String credentialType) { return credentialType == null || credentialType.equals(CredentialModel.PASSWORD); }

Target:
I'm not a reviewer but FYI ` CredentialModel.PASSWORD.equals(credentialType)` in that order can't throw a null pointer exception, usually always the constants first because equals accept "null" but null don't have equals function.
Source:
public List<ClientModel> getClients() { return cacheSession.getClients(this, 0, cacheSession.getClientsCount(this).intValue()); }

Target:
Realm should have an overloaded method getClients(this), that just calls getClients(this, null, null). This approach will result in extra query to get the client counts first, to then list all clients.
Source:
public VaultRawSecret getRawSecret(final String value) { String entryId = this.getVaultEntryKey(value); if (entryId != null) { if (this.provider == null) { throw new IllegalStateException("Required VaultProvider not found - check vault configuration"); } // we have a valid ${vault.<KEY>} string, use the provider to retrieve the entry. return this.provider.obtainSecret(entryId); } else { // this should be avoided by calling isVaultEntry with the value before attempting to use this method. ByteBuffer buffer = value != null ? ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)) : null; return DefaultVaultRawSecret.forBuffer(Optional.ofNullable(buffer)); } }

Target:
Not here. If the value is not found, `VaultProvider` should write it to the log.
Source:
public PlainTextVaultProvider(@Nonnull Path path, @Nonnull String realmName) { vaultPath = path; secretMappingFunction = (vaultDirectory, secretId) -> vaultDirectory.resolve(realmName + "__" + secretId); logger.debugf("PlainTextVaultProvider will operate in %s directory", vaultPath.toAbsolutePath().toString()); }

Target:
`vaultPath.toAbsolutePath().toString()` would be evaluated always which is redundant if debug is not enabled. ` if (logger.isDebugEnabled()) {` ```suggestion logger.debugf("PlainTextVaultProvider will operate in %s directory", vaultPath.toAbsolutePath()); ``` }
Source:
public List<GroupModel> getGroups() { List<GroupModel> ldapGroupMappings = getLDAPGroupMappingsConverted(); if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) { // Use just group mappings from LDAP return ldapGroupMappings; } else { // Merge mappings from both DB and LDAP List<GroupModel> modelGroupMappings = super.getGroups(); ldapGroupMappings.addAll(modelGroupMappings); return ldapGroupMappings; } }

Target:
Revert to a `Set`, `List` would negatively impact performance
Source:
protected List<GroupModel> getLDAPGroupMappingsConverted() { if (cachedLDAPGroupMappings != null) { return new ArrayList<>(cachedLDAPGroupMappings); } List<LDAPObject> ldapGroups = getLDAPGroupMappings(ldapUser); List<GroupModel> result = new ArrayList<>(); for (LDAPObject ldapGroup : ldapGroups) { GroupModel kcGroup = findKcGroupOrSyncFromLDAP(realm, ldapGroup, this); if (kcGroup != null) { result.add(kcGroup); } } cachedLDAPGroupMappings = new HashSet<>(result); return result; }

Target:
Use `LinkedHashSet` instead of `ArrayList`.
Source:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; // KEYCLOAK-8460 client signed signature verification SignatureVerifierContext verifier(ClientModel client, JWSInput input) throws VerificationException; @Override default void close() { }

Target:
Verifying signatures for clients should not be added to the SignatureProvider. Instead a new ClientSignatureVerifierProvider should be introduced. This will also enable listing supported algorithms properly rather than hard-coding the lists.
Source:
public void isActiveReturnFalseWhenBeforeTimeInFuture() { int currentTime = Time.currentTime(); int futureTime = currentTime + 1; JsonWebToken jsonWebToken = new JsonWebToken(); jsonWebToken.notBefore(futureTime); assertFalse(jsonWebToken.isActive()); }

Target:
If I understand correctly, when the line 70 with "jsonWebToken.isActive()" is executed, the system time may be already increased during the time when lines 66-70 were executed and "Time.currentTime()" called from "jsonWebToken.isActive()" will return 1 second ahead of value of "currentTime" variable. If this happen, the test would fail IMO. Could it be changed to be less fragile? Instead of using 1 second interval, use 10 seconds intervals or something?
Source:
protected void commenceLoginRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { if (request.getSession(false) == null && KeycloakCookieBasedRedirect.getRedirectUrlFromCookie(request) == null) { // If no session exists yet at this point, then apparently the redirect URL is not // stored in a session. We'll store it in a cookie instead. response.addCookie(KeycloakCookieBasedRedirect.createCookieFromRedirectUrl(request.getRequestURI())); } String contextAwareLoginUri = request.getContextPath() + loginUri; log.debug("Redirecting to login URI {}", contextAwareLoginUri); response.sendRedirect(contextAwareLoginUri); }

Target:
This does not preserve query parameters of the original request. Is this intentional? Is there any (e.g. security related) reason to not include the query?
Source:
public Response update(final ClientRepresentation rep) { auth.requireManage(); try { RepresentationToModel.updateClient(rep, client); adminEvent.realm(realm).operation(OperationType.UPDATE).resourcePath(client).representation(rep).success(); return Response.noContent().build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Client " + rep.getClientId() + " already exists"); } }

Target:
Set realm in RealmAdminResource, then you don't have to do it everywhere
Source:
public String getSrcRecord() { return srcRecord; }

Target:
Thou hast a typo :)
Source:
public AbstractSequence<NucleotideCompound> getSequence() throws CompoundNotFoundException { try { DNASequenceCreator creator = new DNASequenceCreator(ABITracerCompoundSet.getABITracerCompoundSet()); return creator.getSequence(sequence, 0); } catch (Exception e) { // this should be impossible! throw new CompoundNotFoundException(e.toString()); } }

Target:
No need to catch, just let the `CompoundNotFoundException` go through. Catching a general `Exception` here could cause undesired side effects in the error handling. If you think the `CompoundNotFoundException` can't happen (other than because of a bug), then it's valid to catch it (but only that exception), log a warning and not throw it.
Source:
public void testCryst1Parsing() throws Exception { String cryst1Line = "CRYST1 11.111 11.111 111.111 70.00 80.00 60.00 P 1"; Structure s; PDBFileParser pdbPars = new PDBFileParser(); try(InputStream is = new ByteArrayInputStream(cryst1Line.getBytes()) ) { s = pdbPars.parsePDBFile(is); } assertEquals("P 1", s.getPDBHeader().getCrystallographicInfo().getSpaceGroup().getShortSymbol()); }

Target:
This can be specified to "throws IOException" only.
Source:
public static final void translate(Group group, Vector3d v) { for (Atom atom : group.getAtoms()) { translate(atom, v); } for (Group altG : group.getAltLocs()) { for (Atom atom : altG.getAtoms()) { translate(atom, v); } } }

Target:
Why not using `translate(g, v)`? It would be a recursive call to this function, nicer solution.
Source:
public static String complement(String sequence, boolean RNA) { String result = ""; for (int i = sequence.length() - 1; i >= 0; i--) { result += complementBase(sequence.charAt(i), RNA); } return result; }

Target:
Isn't this already present elsewhere in biojava?
Source:
public void setUp(){ Dataset ds = new Dataset(); String f = Dataset.ACETYLATION; File localFile = getLocalFileName(f); try { if (!localFile.exists()) { ds.downloadFile(new URL(f), localFile); } } catch (IOException e) { e.printStackTrace(); } }

Target:
It'd be better to throw the exception here. If there's a problem with the download, a stack trace will be printed but junit won't know anything about it. The failure would come later when the file is not found. With the exception thrown, the junit report will be a lot clearer and a naive user that knows nothing about this test will understand better what went wrong.
Source:
public void testAcetylation() { try { File localFile = getLocalFileName(Dataset.ACETYLATION); List<Site> sites = Site.parseSites(localFile); assertTrue(sites.size() > 0); for (Site s : sites) { assertTrue(s.getResidue() != null); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }

Target:
It would be better to throw the exception here. Like this an exception will be reported as a test failure by junit. Junit reports either errors or failures, and both are different: failures indicate that an assertion did not work, errors indicate that some unexpected exception occurred (see http://stackoverflow.com/questions/3425995/whats-the-difference-between-failure-and-error-in-junit)
Source:
public static List<Range> getCDSExonRanges(GeneChromosomePosition chromPos){ if ( chromPos.getOrientation() == '+') return getCDSExonRangesForward(chromPos,CDS); return getCDSExonRangesReverse(chromPos,CDS); }

Target:
Range should be parameterised, the compiler gives warnings for it. Same for all other occurrences below
Source:
private List<Step> getAlignmentsSteps(String gappedSequenceString){ List<Step> returnList = new ArrayList(); for (char c: gappedSequenceString.toCharArray()){ if (c=='-') returnList.add(Step.GAP); else returnList.add(Step.COMPOUND); } return returnList; }

Target:
You are missing the type in ArrayList
Source:
public List<String> getFileExtensions(){ ArrayList<String> extensions = new ArrayList(1); extensions.add("blastxml"); return extensions; }

Target:
Missing type
Source:
public UniprotProxySequenceReader(String accession, CompoundSet<C> compoundSet) throws CompoundNotFoundException, IOException { if (!UP_AC_PATTERN.matcher(accession.toUpperCase()).matches()) { throw new CompoundNotFoundException("Accession provided " + accession + " doesn't comply with the uniprot acession pattern."); } setCompoundSet(compoundSet); uniprotDoc = this.getUniprotXML(accession); String seq = this.getSequence(uniprotDoc); setContents(seq); }

Target:
CompoundNotFoundException was intended for cases when a particular symbol in a sequence (nucleotide or aminoacid) is not recognised. Should we have a different exception for this case? what do people think?
Source:
public void setCommodity(@NonNull String currencyCode){ mCommodity = Commodity.getInstance(currencyCode); }

Target:
Was just going through the pr and this caught my eye. `Money` objects are meant to be immutable, just like Java Strings. Could you change this back to private and use `Money.withCurrency()` at the relevant places instead?
Source:
private void checkNumColumns(String location, int[] baseColumnMap, Dataset<Row> table) throws StandardException { if( baseColumnMap.length > table.schema().fields().length) { throw StandardException.newException(SQLState.INCONSISTENT_NUMBER_OF_ATTRIBUTE, baseColumnMap.length, table.schema().fields().length, location, ExternalTableUtils.getSuggestedSchema(table.schema())); } }

Target:
nice! 👍 could be made `static` I guess?
Source:
public static byte[] getRowKey(long txnId) { long beginTS = txnId & SIConstants.TRANSANCTION_ID_MASK; byte[] rowKey = new byte[9]; rowKey[0] = (byte)((beginTS / SIConstants.TRASANCTION_INCREMENT) & (TRANSACTION_TABLE_BUCKET_COUNT-1)); rowKey[0] = (byte)(2); Bytes.longToBytes(beginTS, rowKey, 1); return rowKey; }

Target:
Remove
Source:
private String getClassName(String niceIndexName) throws StandardException { String cName = ""; if(niceIndexName!=null){ cName = "IndexScan["+niceIndexName+"]"; }else{ cName = "TableScan["+getPrettyTableName(); if(pastTxId >= 0){ cName += " timeTravelTx(" + pastTxId + ")"; } cName += "]"; } if(isMultiProbing()) cName = "MultiProbe"+cName; if (isDistinctScan()) cName = "Distinct" + cName; if (specialMaxScan) cName = "LastKey" + cName; return cName; }

Target:
We need to remove the closing bracket "]" for IndexScan here also
Source:
public void stopSpooling() { doSpool = false; this.out.flush(); this.out = new LocalizedOutput(System.out); }

Target:
We should close the FileOutputStream, relying on finalizers is very finicky
Source:
public void setReplicationRoleLocal(String role) { SIDriver.driver().lifecycleManager().setReplicationRole(role); Collection<Context> allContexts= ContextService.getFactory().getAllContexts(LanguageConnectionContext.CONTEXT_ID); for(Context context : allContexts){ ((LanguageConnectionContext)context).setReplicationRole(role); } SpliceLogUtils.info(LOG, "Set replication role to %s", role); }

Target:
I think it is a good idea to throw an exception is `role` doesn't match (or at least add an assert)
Source:
public RunningOperation(SpliceOperation operation, Thread thread, Date submittedTime, DataSetProcessor.Type engine, UUID uuid, String rdbIntTkn) { this.operation = operation; this.thread =thread; this.submittedTime = (Date)submittedTime.clone(); this.engine = engine; this.uuid = uuid; this.rdbIntTkn = rdbIntTkn; }

Target:
I would rather remove this clone, it shouldn't be too costly but for OLTP queries it could add up since it's in the hot path.
Source:
public void testCurrentServer() throws Exception { String sqlText = "values current server"; String sqlTextAlt = "values current_server"; String expected = "1 |\n" + "----------\n" + "splicedb |"; ResultSet rs = methodWatcher.executeQuery(sqlText); assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); rs.close(); rs = methodWatcher.executeQuery(sqlTextAlt); assertEquals("\n" + sqlTextAlt + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); }

Target:
You can use "try-with-resources" to ensure resultsets get closed: try(ResultSet rs = methodWatcher.executeQuery(sqlText)) { assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); }
Source:
public DirectPipelineWriter(long destConglomerate, TxnView txn, byte[] token, OperationContext opCtx, boolean skipIndex, String tableVersion){ this.destConglomerate=destConglomerate; this.txn=txn; this.token=token; this.opCtx=opCtx; this.skipIndex=skipIndex; }

Target:
`this.tableVersion = tableVersion` is probably missing
Source:
protected SocketConfig buildSocketConfig() { return SocketConfig.custom() .setSoTimeout(readTimeout == -1 ? 0 : readTimeout) .build(); }

Target:
I think this can return null if there is no timeout. From what I see, a null SocketConfig is supported and what occurs normally (if you have no customizations).
Source:
public static String getDefaultBeanName(String className){ int lastDotPosition = className.lastIndexOf("."); //$NON-NLS-1$ if(lastDotPosition >= 0 && className.length() > lastDotPosition){ className = className.substring(+1); } if(className.length() > 0) { className = className.substring(0, 1).toLowerCase() + className.substring(1); } return className; }

Target:
Please add JavaDoc to this util method.
Source:
private static void initializeUserHomeRuntimes(IProgressMonitor monitor) { String userHome = System.getProperty(USER_HOME); if (userHome != null) { File directory = new File(userHome, JBOSS_RUNTIMES); RuntimeInitializerUtil.initializeRuntimesFromFolder(directory, monitor); if (directory != null && directory.isDirectory()) { RuntimePath path = new RuntimePath(directory.getAbsolutePath()); path.setScanOnEveryStartup(true); RuntimeUIActivator.getDefault().getModel().addRuntimePath(path); } } }

Target:
Why would you call RuntimeInitializerUtil.initializeRuntimesFromFolder if directory is null or not a directory? i.e. why not put that down in the if block below?
Source:
public void start(BundleContext bundleContext) throws Exception { StacksCoreActivator.context = bundleContext; DEFAULT = this; new StacksManager().getStacks(new NullProgressMonitor()); }

Target:
This has nothing to do here. You're invoking blocking code during plugin activation and wasting this instance
Source:
private DelayDays(String value) { this.value = value; }

Target:
Can you update the generator to remove the modifier so that the constructor stays at the package-private level?
Source:
public SubscriptionScheduleCollection list(Map<String, Object> params) throws StripeException { return list(params, (RequestOptions) null); }

Target:
@ob-stripe totally random but do we really need those duplicate collection classes? (nothing to do with autogen, just realizing I haven't asked in a while)
Source:
public void setOnBehalfOf(String onBehalfOfID) { this.onBehalfOf = APIResource.setExpandableFieldID(onBehalfOfID, this.destination); }

Target:
I don't understand why `this.destination` is used here, can you clarify?
Source:
public static IssuerFraudRecord retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { String url = instanceURL(IssuerFraudRecord.class, id); return request(RequestMethod.GET, url, null, IssuerFraudRecord.class, null); }

Target:
Could you add a variant for `retrieve` that takes a `RequestOptions` like you have for `list` below? Thanks!
Source:
protected static String subresourceURL(Class<?> clazz, String id, Class<?> subClazz, String apiBase) throws InvalidRequestException { try { return String.format("%s/%s/%ss", classURL(clazz, apiBase), urlEncode(id), className(subClazz)); } catch (UnsupportedEncodingException e) { throw new InvalidRequestException("Unable to encode parameters to " + CHARSET + ". Please contact support@stripe.com for assistance.", null, null, null, 0, e); } }

Target:
Hm, I'm not too crazy about adding a couple new global helpers like this and then using them in just the one place. It feels like we should either just re-use the template found elsewhere (see transfer reversals for example), or convert everything over to use these. What do you think @ob-stripe?
Source:
public static Topup retrieve(String id, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.GET, instanceURL(Topup.class, id), null, Topup.class, options); }

Target:
Can this one be implemented using the below method: <pre> public static Topup retrieve(String id, Map<String, Object> params, RequestOptions options); </pre> ?
Source:
public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("plan", "plan_123"); params.put("subscription", "cus_123"); params.put("quantity", 99); SubscriptionItem subscriptionItem = SubscriptionItem.create(params); assertNotNull(subscriptionItem); verifyRequest( APIResource.RequestMethod.POST, "/v1/subscription_items", params ); }

Target:
should be called `resource`
Source:
public String get(String name) { List<String> valuesList = values(name); String requestId = null; if (valuesList != null && valuesList.size() > 0) { requestId = valuesList.get(0); } return requestId; }

Target:
Sorry to be such a bother, but mind giving a generic name to this variable too?
Source:
public DeletedAccount delete(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.DELETE, instanceURL(Account.class, this.id), null, DeletedAccount.class, options); }

Target:
IMO they should both call the other methods. They shouldn't make the request themselves so that there's only one path to a call to `request`
Source:
public static String getClassURL() { return String.format("%s/v1/%s", Stripe.getApiBase(), "apple_pay/domains"); }

Target:
I notice that most of the other models with this method don't use `static`. Would you mind making it an instance method for consistency? Also, can you see if you can change it to private visibility? I don't think there's any reason to leak this interface out of the package.
Source:
public void testDisputeList() throws StripeException, InterruptedException { createDisputedCharge(100).getDispute(); createDisputedCharge(150).getDispute(); createDisputedCharge(300).getDispute(); Map<String, Object> listParams = new HashMap<String, Object>(); listParams.put("count", 3); List<Dispute> disputes = Dispute.all(listParams).getData(); assertEquals(3, disputes.size()); }

Target:
I think it's safe to remove these
Source:
public static RequestOptions getDefault() { return new RequestOptions(Stripe.apiKey, Stripe.apiVersion, Stripe.getApiBase()); }

Target:
Per IRL, I meant to say `uploadApiBase`. This is fine too, but unrelated.
Source:
public String getInstanceURL() { if (this.getCustomer() != null) { return String.format("%s/%s/cards/%s", classURL(Customer.class), this.getCustomer(), this.getId()); } else { return String.format("%s/%s/cards/%s", classURL(Recipient.class), this.getRecipient(), this.getId()); } }

Target:
I realize that it wasn't smart enough to do this before, but ideally this method would return `null` when both `getCustomer()` and `getRecipient()` return `null`.
Source:
ListKeysOperation(Builder builder) { super(RiakMessageCodes.MSG_TsListKeysReq, RiakMessageCodes.MSG_TsListKeysResp, builder.reqBuilder, RiakTsPB.TsListKeysResp.PARSER); this.builder = builder; }

Target:
Suspicious package visibility, do we need it?
Source:
private List<Row> getKeyHeads() { List<Row> keyHeads = new ArrayList<Row>(rows.size()); for (Row row : rows) { final List<Cell> cells = row.getCellsCopy(); // Hack: replace timestamp cell with sint64 cell. keyHeads.add(new Row(cells.get(0), cells.get(1), new Cell(cells.get(2).getTimestamp()))); } return keyHeads; }

Target:
Better to make it static
Source:
public static ArrayList<RiakKvPB.TsCell> convertCellsToPb(Collection<Cell> cells) { final ArrayList<RiakKvPB.TsCell> pbCells = new ArrayList<RiakKvPB.TsCell>(cells.size()); for (Cell cell : cells) { pbCells.add(convertCellToPb(cell)); } return pbCells; }

Target:
it is better to return more generic List rather than return a concrete ArrayList
Source:
public SetOp add(ByteArrayWrapper element) { this.adds.add(element); this.removes.remove(element); return this; }

Target:
This is something I struggled with. The semantics of observed-remove make it not-so-obvious what the user _means_ by an add shipped in the same operation as a remove. In the Erlang client, we decided that sending _all_ recorded operations was the least surprising solution, with the caveat that removes are applied before adds.
Source:
public boolean isClientHealthy(RawClient client) { try { //-- First check to see if client is up client.ping(); //-- Check to see if client has joined ring by check to see if it has any buckets return !client.listBuckets().isEmpty(); } catch (IOException ioe) { return false; } }

Target:
The listBuckets() operation will kill the cluster in production as it needs to go trough all the keys. Maybe there is a better way to check for health?
Source:
public NodeStats stats() { NodeStats nodeStats = null; for(RawClient rc : cluster) { if (nodeStats == null) nodeStats = rc.stats(); else nodeStats.add(rc.stats()); } return nodeStats; }

Target:
Style points as before. In this case the class has existing code in a certain style.
Source:
Integer safeGet(String key) { if (containsKey(key)) { return get(key); } else { System.out.println(key + " unknown"); return get("UNK"); } }

Target:
Is that a leftover from debugging or on purpose?
Source:
void activate() { try { Central.bndCall(() -> { process(); list = memoize(this::list0); return null; }); } catch (Exception e) { logger.error("Could not activate {}", getName(), e); } }

Target:
This does not do what you want. It just creates the memoize object. You need to wrap the supplier. So move the bndCall invocation into list0.
Source:
public void partClosed(IWorkbenchPart part) { IDragAndDropService dndService = part.getSite() .getService(IDragAndDropService.class); IAdaptable adapter = part; Control control = adapter.getAdapter(Control.class); if (control != null && dndService != null) { dndService.removeMergedDropTarget(control); } }

Target:
BndEditor would need to add `getAdapter` support for Control.class for this to properly unmerge the dropTarget.
Source:
public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) { try { if (!init()) { return Collections.emptyMap(); } } catch (RuntimeException re) { throw re; } catch (Exception e) { throw Exceptions.duck(e); } return repoImpl.findProviders(requirements); }

Target:
if you use duck, no need to do this extra Runtime check
Source:
public IContextInformation getContextInformation() { return new IContextInformation() { @Override public String getContextDisplayString() { return "Added " + bundle + " to build path"; } @Override public Image getImage() { return Icons.image("bundle"); } @Override public String getInformationDisplayString() { return "Added " + bundle + " to build path - info"; } }; }

Target:
For the quick fix processor, I could never figure out when this was used. It is possible they are not used for quick fixes, but for completion proposals (which are different to quick fixes). However they are used, the strings should probably use `displayString` (eg, with these new changes, sometimes we're adding to the test path and not the build path).
Source:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof IJavaProject) { element = ((IJavaProject) element).getProject(); } return !Optional.ofNullable(element) .filter(IProject.class::isInstance) .map(IProject.class::cast) .filter(Objects::nonNull) .filter(p -> TemporaryProject.PROJECT_NAME.equals(p.getName())) .isPresent(); }

Target:
Why do you need the non-null filter? The `Class.isInstance` will already filter out null values.
Source:
public Container(Project project, String message) { this.project = project; this.bsn = "<unknown>"; this.version = "<unknown>"; this.warning = message; this.type = TYPE.ERROR; this.path = "unknown"; }

Target:
Can we make this private and just have people use the static method?
Source:
public BundleDTO install(String location, byte[] data) throws Exception { if (data == null) { return null; } Bundle installedBundle = null; try (InputStream stream = new ByteArrayInputStream(data)) { installedBundle = context.getBundle(location); if (installedBundle == null) { installedBundle = context.installBundle(location, stream); } else { installedBundle.update(stream); refresh(true); } } return toDTO(installedBundle); }

Target:
the data cannot be null
Source:
public static boolean isNotResolved(Bundle bundle) { return bundle.getState() == Bundle.INSTALLED || bundle.getState() == Bundle.UNINSTALLED; }

Target:
```java return (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) != 0; ```
Source:
default BundleSpecBuilder addResourceWithCopy(Class<?> class1) { String className = class1.getName(); String path = className.replace('.', '/') + ".class"; URL url = BundleSpecBuilder.class.getClassLoader() .getResource(path); if (url == null) { throw new IllegalArgumentException( "Couldn't find class file for " + class1.getName() + ", possibly a synthetic class"); } addResource(path, url); return this; }

Target:
Shouldn't this use the specified class' class loader to load the resource? For example, `URL url = class1.getClassLoader().getResource(path);`? Or even `URL url = class1.getResource(class1.getSimpleName()+".class");` since the class file resource is in the package of the class.
Source:
static Discover parse(String s) { if (s == null || s.isEmpty()) return Discover.none; return Discover.valueOf(s); }

Target:
You may want to do: https://github.com/bndtools/bnd/blob/57a70d6a05d77289e2f4702246ece22984b89070/aQute.libg/src/aQute/lib/strings/Strings.java#L147 since it also trims the string in case the input value has leading or trailing whitespace.
Source:
public void testGetWithSource() throws Exception { config(null); File jar = repo.get("org.osgi.dto", new Version("1.0.0.201505202023"), null); assertThat(jar.isFile()).isTrue(); File sources = repo.get("org.osgi.dto.source", new Version("1.0.0.201505202023"), null); assertThat(sources.isFile()).isTrue(); }

Target:
This should be better written as `assertThat(jar).isFile();`
Source:
boolean isInnerClass() { String binary = type.getBinary(); return attributes(InnerClassesAttribute.class).flatMap(a -> Arrays.stream(a.classes)) .filter(inner -> Objects.nonNull(inner.inner_name)) .anyMatch(inner -> !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); }

Target:
Instead of adding a filter operation, could we just AND the non-null check into the anyMatch test? ```java .anyMatch(inner -> (inner.inner_name != null) && !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); ```
Source:
public void testFinalFieldReference() throws Exception { Builder b = new Builder(); b.setProperty(Constants.DSANNOTATIONS, "test.component.*FinalClassNonFinalField*"); b.setProperty("Private-Package", "test.component"); b.addClasspath(new File("bin_test")); b.build(); assertOk(b); }

Target:
To clean up properly, please place the Builder in a try-with-resource block ```java try (Builder b = new Builder()) { // test } ```
Source:
default BundleSpecBuilder extension(Extension extension) { requireNonNull(extension, "Extension cannot be null"); directive("extension", extension.value); return this; }

Target:
extension.toString()
Source:
private void verifyDirectives(String header, String directives, Pattern namePattern, String type) throws Exception { verifyDirectives(header, directives, namePattern, type, (namespace, pattern) -> pattern); }

Target:
```java private void verifyDirectives(String header, String directives, Pattern namePattern, String type) throws Exception { verifyDirectives(header, namespace -> directives, namePattern, type); } private void verifyDirectives(String header, Function<String, String> directives, Pattern namePattern, String type) throws Exception { ```
Source:
protected void refreshServiceTaskList(ServiceTaskSummary serviceTaskSummary) { serviceTaskService.call((String serviceTaskName) -> { notificationEvent.fire(new NotificationEvent(getRemoveTaskSuccess() + serviceTaskName)); refreshData(); }).removeServiceTask(serviceTaskSummary); }

Target:
```suggestion notificationEvent.fire(new NotificationEvent(constants.RemoveTaskSuccess(serviceTaskName))); ```
Source:
public String removeServiceTask(ServiceTaskSummary serviceTaskSummary) { repoService.removeServiceTask(serviceTaskSummary.getId(), serviceTaskSummary.getInstalledOn().size() > 0 ? false : true); return serviceTaskSummary.getName(); }

Target:
@mswiderski is the logic correct here? Should we disable the ST only when it is used by no project? ....
Source:
public void onDeselectAllItemsEvent(@Observes DeselectAllItemsEvent event) { if (getListView().getListGrid() != null) { getListView().getListGrid().deselectAllItems(); } refreshGrid(); }

Target:
just not sure if we always want to refresh the grid when deselectall is executed.
Source:
public void bulkClaim(List<TaskSummary> taskSummaries) { if (taskSummaries == null || taskSummaries.isEmpty()) { return; } taskSummaries.parallelStream().forEach(taskSummary -> { if (getClaimActionCondition().test(taskSummary)) { claimTask(taskSummary); } else { view.displayNotification( constants.ClaimNotAllowedOn(String.valueOf(taskSummary.getId()), taskSummary.getName())); } }); }

Target:
Although using parallelStream could be more efficient, I would suggest using a plain _forEach_ to keep the behaviour more consistent.
Source:
public void init() { filterSettingsManager.getDefaultActiveFilterKey(defaultFilter -> loadSavedFilters(defaultFilter)); }

Target:
in here I think default filter is an attribute of the filter itself. You should continue using just _loadSavedFilters_ and that would set the default filter automatically.
Source:
public String toString() { return "TaskSelectionEvent{" + "forAdmin=" + forAdmin + ", forLog=" + forLog + ", description='" + description + '\'' + ", expirationTime=" + expirationTime + ", actualOwner='" + actualOwner + '\'' + ", status='" + status + '\'' + ", slaCompliance='" + slaCompliance + '\'' + ", priority=" + priority + ", processInstanceId=" + processInstanceId + ", processId='" + processId + '\'' + ", workItemId=" + workItemId + ", slaCompliance=" + slaCompliance + "} " + super.toString(); }

Target:
slaCompliance is twice here
Source:
public void testControlBulkOperationsEnabled() { boolean enabled = false; List a = Collections.singletonList(mockButton); when(rightActionsToolbar.spliterator()) .thenReturn(Spliterators.spliteratorUnknownSize(a.iterator(), 0)); when(extendedPagedTable.hasSelectedItems()).thenReturn(enabled); getView().controlBulkOperations(extendedPagedTable); verify(mockButton).setEnabled(enabled); }

Target:
@nmirasch one more thing, I would change the List from raw type to `List<Button>`, and move all these three lines into setupMocks methods.
Source:
public void refreshLogs() { currentPage = 1; loadTaskLogs(); displayVisibleLogs(); }

Target:
shouldn't this be executed in the callback from _getTaskEvents_ ?
Source:
private List<ColumnMeta<T>> renameDomainSpecifColumns(ExtendedPagedTable<T> extendedPagedTable, Set<String> columns) { return (List<ColumnMeta<T>>) extendedPagedTable.getColumnMetaList().stream() .filter(cm -> !cm.isExtraColumn() && columns.contains(cm.getCaption())) .map(colMet -> { return newColumnMeta(colMet.getCaption(), true); }).collect(Collectors.toList()); }

Target:
```suggestion .map(colMet -> newColumnMeta(colMet.getCaption(), true)) ```
Source:
public Predicate<String> getFilterEventPredicate() { return dataSetId -> getDataSetQueryHelper() != null && getDataSetQueryHelper() != null && getDataSetQueryHelper().getCurrentTableSettings() != null && dataSetId != null && dataSetId.equals(getDataSetQueryHelper().getCurrentTableSettings().getUUID()); }

Target:
I guess _getDataSetQueryHelper_ is duplicated here?
Source:
public void onEditButtonClicked(final ClickEvent ignore) { presenter.openEditModal(name.textContent, value.textContent);; }

Target:
No need to pass values back to the presenter.