auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Double visitLiteral(Literal literal, Stats stats) { Object value = literal.value(); if (value instanceof Boolean) { START Boolean val = (Boolean) literal.value(); END return (val == null || !val) ? 0.0 : 1.0; } return super.visitLiteral(literal, stats); } minor: could use `(Boolean) value` instead to avoid one call.

Target:
public Double visitLiteral(Literal literal, Stats stats) { Object value = literal.value(); if (value instanceof Boolean) { Boolean val = (Boolean) value; return (val == null || !val) ? 0.0 : 1.0; } return super.visitLiteral(literal, stats); }
Source:
public CompletableFuture<Integer> killAll() { for (KillAllListener killAllListener : killAllListeners) { try { killAllListener.killAllJobs(); } catch (Throwable t) { START LOGGER.error("Failed to call killAllJobs on listener={} error={}", t, killAllListener); END } } Collection<UUID> toKill = ImmutableList.copyOf(activeTasks.keySet()); if (toKill.isEmpty()) { return CompletableFuture.completedFuture(0); } return killTasks(toKill, null); } arguments in wrong order?

Target:
public CompletableFuture<Integer> killAll() { for (KillAllListener killAllListener : killAllListeners) { try { killAllListener.killAllJobs(); } catch (Throwable t) { LOGGER.error("Failed to call killAllJobs on listener={} error={}", killAllListener, t); } } Collection<UUID> toKill = ImmutableList.copyOf(activeTasks.keySet()); if (toKill.isEmpty()) { return CompletableFuture.completedFuture(0); } return killTasks(toKill, null); }
Source:
public CompletableFuture<Integer> killJobs(Collection<UUID> toKill, @Nullable String reason) { for (KillAllListener killAllListener : killAllListeners) { for (UUID job : toKill) { try { killAllListener.killJob(job); } catch (Throwable t) { START LOGGER.error("Failed to call killJob on listener={}, err={}", t, killAllListener); END } } } return killTasks(toKill, reason); } also here, wrong arguments order

Target:
public CompletableFuture<Integer> killJobs(Collection<UUID> toKill, @Nullable String reason) { for (KillAllListener killAllListener : killAllListeners) { for (UUID job : toKill) { try { killAllListener.killJob(job); } catch (Throwable t) { LOGGER.error("Failed to call killJob on listener={}, err={}", killAllListener, t); } } } return killTasks(toKill, reason); }
Source:
public AnalyzedKill analyze(KillStatement<Expression> killStatement, Function<ParameterExpression, Symbol> convertParamFunction, CoordinatorTxnCtx txnCtx) { START var exprAnalyzerWithoutFields = new ExpressionAnalyzer( END functions, txnCtx, convertParamFunction, FieldProvider.UNSUPPORTED, null); Symbol jobId; if (killStatement.jobId() != null) { jobId = exprAnalyzerWithoutFields.convert( killStatement.jobId(), new ExpressionAnalysisContext()); } else { jobId = null; } return new AnalyzedKill(jobId); } Could move this also into the `if` brach below, so that it is not created for `KILL ALL`

Target:
public AnalyzedKill analyze(KillStatement<Expression> killStatement, Function<ParameterExpression, Symbol> convertParamFunction, CoordinatorTxnCtx txnCtx) { Symbol jobId; if (killStatement.jobId() != null) { var exprAnalyzerWithoutFields = new ExpressionAnalyzer( functions, txnCtx, convertParamFunction, FieldProvider.UNSUPPORTED, null); jobId = exprAnalyzerWithoutFields.convert( killStatement.jobId(), new ExpressionAnalysisContext()); } else { jobId = null; } return new AnalyzedKill(jobId); }
Source:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { START AnalyzedStatement analyzedStatement = analyzer.unboundAnalyze(rewriteShowTransaction(), END analysis.sessionContext(), ParamTypeHints.EMPTY); analysis.rootRelation((AnalyzedRelation) analyzedStatement); return analyzedStatement; } could we use the `unboundAnalyze()` helper method here as well?

Target:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { return unboundAnalyze(rewriteShowTransaction(), analysis); }
Source:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { START return unboundAnalyze(rewriteShowTransaction(), analysis, ParamTypeHints.EMPTY); END } why not use `unboundAnalyze(query, analysis)` and thus use `analysis.paramTypeHints()` here as well?

Target:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { return unboundAnalyze(rewriteShowTransaction(), analysis); }
Source:
public void testSubSelectWhere() throws Exception { setup.setUpCharacters(); execute("select id, name " + "from (select * from characters where female = true) as ch " + "where name like 'Arthur'"); assertThat(printedTable(response.rows()), is("4| Arthur\n")); START assertThat(printedTable(response.rows()), END is("4| Arthur\n")); } This is redundant?

Target:
public void testSubSelectWhere() throws Exception { setup.setUpCharacters(); execute("select id, name " + "from (select * from characters where female = true) as ch " + "where name like 'Arthur'"); assertThat(printedTable(response.rows()), is("4| Arthur\n")); }
Source:
public ColumnContext next() { if (!hasNext()) { throw new NoSuchElementException("Columns iterator exhausted"); } Reference ref = columns.next(); if (ref.column().isTopLevel() == false) { return new ColumnContext(tableInfo, ref, null); } // Tables created with CrateDB < 4.0 don't have any positional information stored inside the meta data so // we must fallback to old behaviour which uses a simple increased iterating based var. Integer position = ref.position(); if (position == null) { START position = ordinal.intValue(); END } ordinal++; return new ColumnContext(tableInfo, ref, position); } Maybe make `ordinal` a primitive int directly? `++` would cause boxing (although low values are cached, so it's a non issue). The memory footprint should also not increase, due to memory alignment I think a short takes up the same space as an int anyway.

Target:
public ColumnContext next() { if (!hasNext()) { throw new NoSuchElementException("Columns iterator exhausted"); } Reference ref = columns.next(); if (ref.column().isTopLevel() == false) { return new ColumnContext(tableInfo, ref, null); } // Tables created with CrateDB < 4.0 don't have any positional information stored inside the meta data so // we must fallback to old behaviour which uses a simple increased iterating based var. Integer position = ref.position(); if (position == null) { position = ordinal; } ordinal++; return new ColumnContext(tableInfo, ref, position); }
Source:
public boolean matchesSafely(Engine.Searcher searcher) { try { START this.count = (int) searcher.searcher().count(query); END return count == totalHits; } catch (IOException e) { return false; } } Redundant cast to int

Target:
public boolean matchesSafely(Engine.Searcher searcher) { try { this.count = searcher.searcher().count(query); return count == totalHits; } catch (IOException e) { return false; } }
Source:
START public static Matcher<Engine.Searcher> engineSearcherTotalHits(Query query, int totalHits) { END return new EngineSearcherTotalHitsMatcher(query, totalHits); } could be package private

Target:
static Matcher<Engine.Searcher> engineSearcherTotalHits(Query query, int totalHits) { return new EngineSearcherTotalHitsMatcher(query, totalHits); }
Source:
START public static Matcher<Engine.Searcher> engineSearcherTotalHits(int totalHits) { END return new EngineSearcherTotalHitsMatcher(Queries.newMatchAllQuery(), totalHits); } could be package private

Target:
static Matcher<Engine.Searcher> engineSearcherTotalHits(int totalHits) { return new EngineSearcherTotalHitsMatcher(Queries.newMatchAllQuery(), totalHits); }
Source:
public void test_psql_format_from_string() { Period period = PGIntervalParser.apply("@ 1 year 1 mon 1 day 1 hour 1 minute 1 secs"); START Assert.assertEquals(period, END new Period().withYears(1).withMonths(1).withDays(1).withHours(1).withMinutes(1).withSeconds(1)); } We generally prefer `assertThat(..., is(..))` for better error messages.

Target:
public void test_psql_format_from_string() { Period period = PGIntervalParser.apply("@ 1 year 1 mon 1 day 1 hour 1 minute 1 secs"); assertThat(period, is(new Period().withYears(1).withMonths(1).withDays(1).withHours(1).withMinutes(1).withSeconds(1))); }
Source:
public IntervalLiteral(String value, Sign sign, IntervalField startField, @Nullable IntervalField endField) { checkNotNull(value, "value is null"); checkNotNull(sign, "sign is null"); checkNotNull(startField, "startField is null"); START END this.value = value; this.sign = sign; this.startField = startField; this.endField = endField; } aren't these validations already handled by the parser?

Target:
public IntervalLiteral(String value, Sign sign, IntervalField startField, @Nullable IntervalField endField) { this.value = value; this.sign = sign; this.startField = startField; this.endField = endField; }
Source:
public LongObjectHashMap<Long> measureGroupingOnLongArray() { LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>(); for (long number : numbers) { sumByKey.compute(number, (key, oldValue) -> { if (oldValue == null) { START return 0L; END } else { return oldValue + number; } }); } return sumByKey; } should this be `number`? (adding the first value for a key right? )

Target:
public LongObjectHashMap<Long> measureGroupingOnLongArray() { LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>(); for (long number : numbers) { sumByKey.compute(number, (key, oldValue) -> { if (oldValue == null) { return number; } else { return oldValue + number; } }); } return sumByKey; }
Source:
private void processGeneratedExpressionColumn(Reference reference, Input<?> expressionInput) { toInject.put(reference, expressionInput); final ColumnIdent ident = reference.column(); if (!ident.isTopLevel()) { List<Reference> references = nestedReferenceByTopLevelColumnName.getOrDefault( ident.name(), START new ArrayList<>()); END references.add(reference); nestedReferenceByTopLevelColumnName.put(ident.name(), references); } } I think a manual `.get()` followed by an `if (.. null)` would be more efficient as right now the `new ArrayList<>()` is always evaluated, not just when there is no element found.

Target:
private void processGeneratedExpressionColumn(Reference reference, Input<?> expressionInput) { toInject.put(reference, expressionInput); final ColumnIdent ident = reference.column(); if (!ident.isTopLevel()) { List<Reference> references = nestedReferenceByTopLevelColumnName.get(ident.name()); if (references == null) { references = new ArrayList<>(); } references.add(reference); nestedReferenceByTopLevelColumnName.put(ident.name(), references); } }
Source:
public void testExecuteSingleUploadBlobSizeTooLarge() throws IOException { START expectedException.expect(IllegalArgumentException.class); END expectedException.expectMessage(containsString("can't be larger than 5gb")); final long blobSize = ByteSizeUnit.GB.toBytes(randomIntBetween(6, 10)); final S3BlobStore blobStore = mock(S3BlobStore.class); final S3BlobContainer blobContainer = new S3BlobContainer(mock(BlobPath.class), blobStore); blobContainer.executeSingleUpload(blobStore, randomAlphaOfLengthBetween(1, 10), null, blobSize); } this should be placed right before the expected exception ocurs so it won't catch any unexpected exceptions.

Target:
public void testExecuteSingleUploadBlobSizeTooLarge() throws IOException { final long blobSize = ByteSizeUnit.GB.toBytes(randomIntBetween(6, 10)); final S3BlobStore blobStore = mock(S3BlobStore.class); final S3BlobContainer blobContainer = new S3BlobContainer(mock(BlobPath.class), blobStore); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("can't be larger than 5gb")); blobContainer.executeSingleUpload(blobStore, randomAlphaOfLengthBetween(1, 10), null, blobSize); }
Source:
public Map<Object, Object> value(Object value) { Map<Object, Object> map = (Map<Object, Object>) value; if (map == null) { return map; } START return new HashMap<>(map); END } Why is the copy here necessary?

Target:
public Map<Object, Object> value(Object value) { return (Map<Object, Object>) value; }
Source:
public void testCreateColumnWithDefaultExpression() throws Exception { execute("create table test (col1 text default 'foo')"); START ensureYellow(); END String expectedMapping = "{\"default\":{" + "\"dynamic\":\"strict\",\"_meta\":{}," + "\"dynamic_templates\":[{\"strings\":{\"match_mapping_type\":\"string\",\"mapping\":{\"doc_values\":true,\"store\":false,\"type\":\"keyword\"}}}]," + "\"properties\":{\"col1\":{\"type\":\"keyword\",\"position\":1,\"default_expr\":\"'foo'\"}}}}"; assertEquals(expectedMapping, getIndexMapping("test")); } ```suggestion ensureYellow(); ``` Shouldn't be needed to retrieve the index mapping. The `create table` only returns when the cluster state has been updated (shard initialization is async, but that's not required here)

Target:
public void testCreateColumnWithDefaultExpression() throws Exception { execute("create table test (col1 text default 'foo')"); String expectedMapping = "{\"default\":{" + "\"dynamic\":\"strict\",\"_meta\":{}," + "\"dynamic_templates\":[{\"strings\":{\"match_mapping_type\":\"string\",\"mapping\":{\"doc_values\":true,\"store\":false,\"type\":\"keyword\"}}}]," + "\"properties\":{\"col1\":{\"type\":\"keyword\",\"position\":1,\"default_expr\":\"'foo'\"}}}}"; assertEquals(expectedMapping, getIndexMapping("test")); }
Source:
public <T> int getStart(int pStart, int pEnd, int currentRowIdx, @Nullable Comparator<T> cmp, List<T> rows) { if (pStart == currentRowIdx) { return pStart; } else { if (cmp != null) { START return findFirstPreviousPeer(rows, currentRowIdx, cmp); END } else { return currentRowIdx; } } } Could this potentially go past the partition boundary?

Target:
public <T> int getStart(int pStart, int pEnd, int currentRowIdx, @Nullable Comparator<T> cmp, List<T> rows) { return pStart; }
Source:
START public void testQuerySysJobsLogReturnsLogEntriesRelevantToUser() { END executeAsSuperuser("select 2"); executeAsSuperuser("select 3"); execute("select 1", null, testUserSession()); String stmt = "select username, stmt " + "from sys.jobs_log " + "where stmt in ('select 1', 'select 2', 'select 3') " + "order by stmt"; executeAsSuperuser(stmt); assertThat(printedTable(response.rows()), is("privileges_test_user| select 1\n" + "crate| select 2\n" + "crate| select 3\n")); executeAsSuperuser("grant dql on table sys.jobs_log to " + TEST_USERNAME); execute(stmt, null, testUserSession()); assertThat(printedTable(response.rows()), is("privileges_test_user| select 1\n")); } I'm wondering if instead it would make sense to have a unit test for the concrete `StaticTableDefinition` ? Would be cheaper to execute and probably also more deterministic We've full integration tests already to make sure that the filtering works when everything is integrated.

Target:
public void testQuerySysJobsLogReturnsLogEntriesRelevantToUser() { executeAsSuperuser("grant dql on table sys.jobs_log to " + TEST_USERNAME); executeAsSuperuser("select 2"); executeAsSuperuser("select 3"); execute("select 1", null, testUserSession()); String stmt = "select username, stmt " + "from sys.jobs_log " + "where stmt in ('select 1', 'select 2', 'select 3') " + "order by stmt"; executeAsSuperuser(stmt); assertThat(printedTable(response.rows()), is("privileges_test_user| select 1\n" + "crate| select 2\n" + "crate| select 3\n")); execute(stmt, null, testUserSession()); assertThat(printedTable(response.rows()), is("privileges_test_user| select 1\n")); }
Source:
public Operation build() { return new Operation(method, summary, notes, responseModel, uniqueId, position, tags, produces, START consumes, protocol, securityReferences, parameters, responseMessages, deprecated, isHidden, nickname); END } @adrianbk I dont think we need to introduce an operation id generator concept. Thats what the plugin model is for, there is an operation builder plugin to enrich the operation model already. So l think the direction @who has taken would be the best approach. Just so we dont over engineer it, its probably fine to generate a operation id regardless. The extensibility mechanism allows folks to override the name if they wish.

Target:
public Operation build() { return new Operation(method, summary, notes, responseModel, uniqueId, position, tags, produces, consumes, protocol, securityReferences, parameters, responseMessages, deprecated, isHidden); }
Source:
public Jackson2Annotator(GenerationConfig generationConfig) { super(generationConfig); START this.generationConfig = generationConfig; END } This can be removed.

Target:
public Jackson2Annotator(GenerationConfig generationConfig) { super(generationConfig); }
Source:
private static String addFullDetailsParam(ParamsMap params, String urlParams) { START if (params != null && params.size() > 0 && params.get(FULL_DETAILS_QUERY_PARAM) != null) { END return urlParams + FULL_DETAILS_QUERY_PARAM + "="+ params.get(FULL_DETAILS_QUERY_PARAM); } return urlParams; } It looks like the second check (_params.size() > 0_) can be removed. If the params is not null, params.get() will not fail. After that, we have two cases. If params contain "fullDetails", we will have only two checks instead of three (params.size() is removed). If params does not contain "fullDetails", we will have also only two checks (as in the current implementation, with .size() in place), only that we replaced .size() with .get().

Target:
private static String addFullDetailsParam(ParamsMap params, String urlParams) { if (params != null && params.get(FULL_DETAILS_QUERY_PARAM) != null) { return urlParams + FULL_DETAILS_QUERY_PARAM + "="+ params.get(FULL_DETAILS_QUERY_PARAM); } return urlParams; }
Source:
public <R> R getOwnedEntities(MambuEntityType parentEntity, String parentId, MambuEntityType ownedEntity, String relatedEntityId, ParamsMap params, boolean requiresFullDetails) throws MambuApiException { if (parentEntity == null || ownedEntity == null) { throw new IllegalArgumentException("Parent Entity and Owned Entity cannot be null"); } Class<?> parentClass = parentEntity.getEntityClass(); Class<?> ownedClass = ownedEntity.getEntityClass(); START ApiDefinition apiDefinition ; END apiDefinition = createApiDefinitionForGetOwnedEntities(requiresFullDetails, parentClass, ownedClass); return execute(apiDefinition, parentId, relatedEntityId, params); } just curious, why this approach and not on a single line of code?

Target:
public <R> R getOwnedEntities(MambuEntityType parentEntity, String parentId, MambuEntityType ownedEntity, String relatedEntityId, ParamsMap params, boolean requiresFullDetails) throws MambuApiException { if (parentEntity == null || ownedEntity == null) { throw new IllegalArgumentException("Parent Entity and Owned Entity cannot be null"); } Class<?> parentClass = parentEntity.getEntityClass(); Class<?> ownedClass = ownedEntity.getEntityClass(); ApiDefinition apiDefinition = createApiDefinitionForGetOwnedEntities(requiresFullDetails, parentClass, ownedClass); return execute(apiDefinition, parentId, relatedEntityId, params); }
Source:
private ApiDefinition getApiDefinitionForPaginatedList(boolean requiresFullDetails, Class<?> clazz) { ApiDefinition apiDefinition; START if (requiresFullDetails == true) { END apiDefinition = new ApiDefinition(ApiType.GET_LIST_WITH_DETAILS, clazz); } else { apiDefinition = new ApiDefinition(ApiType.GET_LIST, clazz); } return apiDefinition; } can use without "== true"

Target:
private ApiDefinition getApiDefinitionForPaginatedList(boolean requiresFullDetails, Class<?> clazz) { ApiDefinition apiDefinition; if (requiresFullDetails) { apiDefinition = new ApiDefinition(ApiType.GET_LIST_WITH_DETAILS, clazz); } else { apiDefinition = new ApiDefinition(ApiType.GET_LIST, clazz); } return apiDefinition; }
Source:
private static void createAndAddDocumentIdsForClient(ClientExpanded clientExpanded) throws MambuApiException { // check if other document IDs are allowed boolean areOtherDocIdsAllowed = getOtherDocumentTemplateIdsEnabeled(); if (areOtherDocIdsAllowed) { // create and add doc IDs START List<IdentificationDocument> idDocs = new ArrayList<IdentificationDocument>(); END IdentificationDocument doc = new IdentificationDocument(); doc.setDocumentId("DFG1234"); doc.setDocumentType("Passport"); doc.setIssuingAuthority("Vancouver"); idDocs.add(doc); clientExpanded.setIdDocuments(idDocs); } } We can use the diamond operator here.

Target:
private static void createAndAddDocumentIdsForClient(ClientExpanded clientExpanded) throws MambuApiException { // check if other document IDs are allowed boolean areOtherDocIdsAllowed = getOtherDocumentTemplateIdsEnabeled(); if (areOtherDocIdsAllowed) { // create and add doc IDs List<IdentificationDocument> idDocs = new ArrayList<>(); IdentificationDocument doc = new IdentificationDocument(); doc.setDocumentId("DFG1234"); doc.setDocumentType("Passport"); doc.setIssuingAuthority("Vancouver"); idDocs.add(doc); clientExpanded.setIdDocuments(idDocs); } }
Source:
public Boolean deleteLoanRepayment(String accountId, String repaymentId) throws MambuApiException { // Example: GET endpoint "/api/loans/{LOAN_ID}/repayments/{REPAYMENT_ID} // Available since Mambu 4.3 START if (accountId == null && repaymentId == null) { END throw new IllegalArgumentException("Account ID and Repayment ID must not be null!"); } return serviceExecutor.deleteOwnedEntity(MambuEntityType.LOAN_ACCOUNT, accountId, MambuEntityType.REPAYMENTS, repaymentId); } Shouldn't we use the OR operator instead of AND?

Target:
public Boolean deleteLoanRepayment(String accountId, String repaymentId) throws MambuApiException { // Example: GET endpoint "/api/loans/{LOAN_ID}/repayments/{REPAYMENT_ID} // Available since Mambu 4.3 if (accountId == null || repaymentId == null) { throw new IllegalArgumentException("Account ID and Repayment ID must not be null!"); } return serviceExecutor.deleteOwnedEntity(MambuEntityType.LOAN_ACCOUNT, accountId, MambuEntityType.REPAYMENTS, repaymentId); }
Source:
private static void testDownloadLatestDbBackup() throws MambuApiException, IOException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); DatabaseService databaseService = MambuAPIFactory.getDatabaseService(); DatabaseBackup response = databaseService.downloadLatestDbBackup(); System.out.println("Backup was successfuly downloaded = " + (response.getContent().toByteArray() != null)); START END } Nice! You can optionally try/catch (and log) any IO exceptions in this method

Target:
private static void testDownloadLatestDbBackup() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); DatabaseService databaseService = MambuAPIFactory.getDatabaseService(); DatabaseBackup response = databaseService.downloadLatestDbBackup(); System.out.println("Backup was successfuly downloaded = " + (response.getContent().toByteArray() != null)); }
Source:
public MambuAPIModule(Protocol protocol, String domain, String username, String password) { this.domain = Preconditions.checkNotNull(domain, "domain cannot be null"); this.username = Preconditions.checkNotNull(username, "username cannot be null"); this.password = Preconditions.checkNotNull(password, "password cannot be null"); START this.protocol = Preconditions.checkNotNull(protocol, "protocol cannot be null").name(); END } may want to consider making the "protocol" to be the first line to match params order

Target:
public MambuAPIModule(Protocol protocol, String domain, String username, String password) { this.protocol = Preconditions.checkNotNull(protocol, "protocol cannot be null").name(); this.domain = Preconditions.checkNotNull(domain, "domain cannot be null"); this.username = Preconditions.checkNotNull(username, "username cannot be null"); this.password = Preconditions.checkNotNull(password, "password cannot be null"); }
Source:
START public boolean updateClientCustomField(String clientId, String customFieldId, String fieldValue) END throws MambuApiException { // Execute request for PATCH API to update custom field value for a client. See MBU-6661 // e.g. PATCH "{ "value": "10" }" /host/api/clients/clientId/custominformation/customFieldId // Make ParamsMap with JSON request for Update API ParamsMap params = ServiceHelper.makeParamsForUpdateCustomField(clientId, customFieldId, fieldValue); return serviceExecutor.execute(updateClientCustomField, clientId, customFieldId, params); } Maybe on the next refactoring you can use inheritance or the composition pattern to extract these updateCustomField and deleteCustomField methods to e.g. an abstract class so that they don't have to be implemented in almost every service.

Target:
public boolean updateClientCustomField(String clientId, String customFieldId, String fieldValue) throws MambuApiException { // Execute request for PATCH API to update custom field value for a client. See MBU-6661 // e.g. PATCH "{ "value": "10" }" /host/api/clients/clientId/custominformation/customFieldId // Make ParamsMap with JSON request for Update API ParamsMap params = ServiceHelper.makeParamsForUpdateCustomField(customFieldId, fieldValue); return serviceExecutor.execute(updateClientCustomField, clientId, customFieldId, params); }
Source:
public static TransactionChannel getDemoTransactionChannel() throws MambuApiException { OrganizationService organizationService = MambuAPIFactory.getOrganizationService(); List<TransactionChannel> transactionChannels = organizationService.getTransactionChannels(); if (transactionChannels == null) { return null; } int randomIndex = (int) Math.round(Math.random() * (transactionChannels.size() - 1)); START randomIndex = 1; END return transactionChannels.get(randomIndex); } Not it's not random anymore ;)

Target:
public static TransactionChannel getDemoTransactionChannel() throws MambuApiException { OrganizationService organizationService = MambuAPIFactory.getOrganizationService(); List<TransactionChannel> transactionChannels = organizationService.getTransactionChannels(); if (transactionChannels == null) { return null; } int randomIndex = (int) Math.round(Math.random() * (transactionChannels.size() - 1)); return transactionChannels.get(randomIndex); }
Source:
public boolean deleteTasks(String taskId) throws MambuApiException { // create the api call String urlString = new String(mambuAPIService.createUrl(TASKS + "/" + taskId)); String jsonResponse = mambuAPIService.executeRequest(urlString, Method.DELETE); // On success the response is: returnCode: 0
returnStatus: SUCCESS // An exception can be thrown: E.g, ({"returnCode":980,"returnStatus":"INVALID_TASK_ID"}) // Parse the response. (Though, as no exception was thrown here, must be a "SUCCESS" response) boolean deletionStatus = false; MambuApiResponseMessage response = new MambuApiResponseMessage(jsonResponse); START if (response.getReturnCode() == 0) END deletionStatus = true; return deletionStatus; } Please add {..}.

Target:
public boolean deleteTasks(String taskId) throws MambuApiException { // create the api call String urlString = new String(mambuAPIService.createUrl(TASKS + "/" + taskId)); String jsonResponse = mambuAPIService.executeRequest(urlString, Method.DELETE); // On success the response is: returnCode: 0
returnStatus: SUCCESS // An exception can be thrown: E.g. ({"returnCode":980,"returnStatus":"INVALID_TASK_ID"}) // Parse the response. (Though, as no exception was thrown here, must be a "SUCCESS" response) boolean deletionStatus = false; MambuApiResponseMessage response = new MambuApiResponseMessage(jsonResponse); if (response.getReturnCode() == 0) { deletionStatus = true; } return deletionStatus; }
Source:
private EVCacheClient selectClient(List<EVCacheClient> clients) { if (clients == null) { if (log.isDebugEnabled()) log.debug("clients is null returning null!!!"); return null; } if (clients.size() == 1) { return clients.get(0); // Frequently used scenario } // Get absolute value of current val to ensure correctness even at 9 quintillion+ requests START final long currentVal = Math.abs(numberOfModOps.incrementAndGet()); END // make sure to truncate after the mod. This allows up to 2^31 clients. final int index = (int) (currentVal % clients.size()); return clients.get(index); } can you move the Math.abs to the next line for index.

Target:
private EVCacheClient selectClient(List<EVCacheClient> clients) { if (clients == null) { if (log.isDebugEnabled()) log.debug("clients is null returning null!!!"); return null; } if (clients.size() == 1) { return clients.get(0); // Frequently used scenario } final long currentVal = numberOfModOps.incrementAndGet(); // Get absolute value of current val to ensure correctness even at 9 quintillion+ requests // make sure to truncate after the mod. This allows up to 2^31 clients. final int index = Math.abs((int) (currentVal % clients.size())); return clients.get(index); }
Source:
void setApp(@NonNull AppWithState app) { START impl.app = app; END } Is there reason behind how you access this wrt to property or accessor function? Perhaps we should change all these uses to getters/setters?

Target:
void setApp(@NonNull AppWithState app) { impl.setApp(app); }
Source:
public static Map<String, Object> getMetadata() { START return new HashMap<>(getClient().getMetadataState().getMetadata().toMap()); END } Can this call `Client.getMetadata` rather than require a separate method to retrieve `MetadataState`?

Target:
public static Map<String, Object> getMetadata() { return getClient().getMetadata(); }
Source:
public static List<Breadcrumb> getBreadcrumbs() { START Queue<Breadcrumb> store = getClient().getBreadcrumbState().getStore(); END return new ArrayList<>(store); } Can this call `Client.getBreadcrumbs` rather than require a separate method to retrieve `BreadcrumbState`?

Target:
public static List<Breadcrumb> getBreadcrumbs() { return getClient().getBreadcrumbs(); }
Source:
public static Client init(@NonNull Context androidContext) { START synchronized (lock) { END if (client == null) { client = new Client(androidContext); NativeInterface.configureClientObservers(client); } else { logClientInitWarning(); } } return client; } why did you choose to make a `synchronized (lock) {}` block rather than label the entire static method `public static synchronized Client init()`?

Target:
public static Client init(@NonNull Context androidContext) { return init(androidContext, null, true); }
Source:
public static Map<String,Object> getAppData() { HashMap<String,Object> data = new HashMap<>(); AppData source = getClient().getAppData(); data.putAll(source.getAppData()); data.putAll(source.getAppDataMetaData()); START data.putAll(source.getAppDataSummary()); END return data; } `getAppDataSummary` can be removed here as its contents are included in `getAppData` (same for device metadata)

Target:
public static Map<String,Object> getAppData() { HashMap<String,Object> data = new HashMap<>(); AppData source = getClient().getAppData(); data.putAll(source.getAppData()); data.putAll(source.getAppDataMetaData()); return data; }
Source:
void sendNativeSetupNotification() { setChanged(); super.notifyObservers(new Message(NativeInterface.MessageType.INSTALL, config)); START final Client client = this; END try { Async.run(new Runnable() { @Override public void run() { enqueuePendingNativeReports(); } }); } catch (RejectedExecutionException ex) { Logger.warn("Failed to enqueue native reports, will retry next launch: ", ex); } } this variable is unused

Target:
void sendNativeSetupNotification() { setChanged(); super.notifyObservers(new Message(NativeInterface.MessageType.INSTALL, config)); try { Async.run(new Runnable() { @Override public void run() { enqueuePendingNativeReports(); } }); } catch (RejectedExecutionException ex) { Logger.warn("Failed to enqueue native reports, will retry next launch: ", ex); } }
Source:
START void enqueuePendingNativeReports() { END setChanged(); notifyObservers(new Message( NativeInterface.MessageType.DELIVER_PENDING, null)); } The visibility of this method can be private

Target:
private void enqueuePendingNativeReports() { setChanged(); notifyObservers(new Message( NativeInterface.MessageType.DELIVER_PENDING, null)); }
Source:
public void value(@NonNull File file) throws IOException { super.flush(); beforeValue(false); // add comma if in array // Copy the file contents onto the stream Reader input = null; try { FileInputStream fis = new FileInputStream(file); START input = new BufferedReader(new InputStreamReader(fis, "UTF-8")); END IOUtils.copy(input, out); } finally { IOUtils.closeQuietly(input); } out.flush(); } do any of these objects also need closing?

Target:
public void value(@NonNull File file) throws IOException { if (file == null || file.length() <= 0) { return; } super.flush(); beforeValue(false); // add comma if in array // Copy the file contents onto the stream Reader input = null; try { FileInputStream fis = new FileInputStream(file); input = new BufferedReader(new InputStreamReader(fis, "UTF-8")); IOUtils.copy(input, out); } finally { IOUtils.closeQuietly(input); } out.flush(); }
Source:
private void trackSessionIfNeeded(boolean autoCaptured, Session session) { String releaseStage = getReleaseStage(); START boolean notifyForRelease = client != null && configuration.shouldNotifyForReleaseStage(releaseStage); END if ((configuration.shouldAutoCaptureSessions() || !autoCaptured) && notifyForRelease) { sessionQueue.add(session); sessionStore.write(session); // store session for sending trackedFirstSession = true; } } why does this check if the client is not null here? shouldn't you always put a session in the queue/store even if the client is not initialized yet?

Target:
private void trackSessionIfNeeded(boolean autoCaptured, Session session) { String releaseStage = getReleaseStage(); boolean notifyForRelease = configuration.shouldNotifyForReleaseStage(releaseStage); if ((configuration.shouldAutoCaptureSessions() || !autoCaptured) && notifyForRelease) { sessionQueue.add(session); sessionStore.write(session); // store session for sending trackedFirstSession = true; } }
Source:
private static String getCpuAbi() { String cpuAbi = Build.CPU_ABI; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cpuAbi = SupportedAbiWrapper.getSupportedAbis(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { cpuAbi = Abi2Wrapper.getAbi1andAbi2(); } START return cpuAbi; END } This method can be simplified to ``` java if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return SupportedAbiWrapper.getSupportedAbis(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { return Abi2Wrapper.getAbi1andAbi2(); } return Build.CPU_ABI; ``` Also is it worth wrapping `Build.CPU_ABI` in an array so that the output format is always consistent regardless of API level?

Target:
private static String[] getCpuAbi() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return SupportedAbiWrapper.getSupportedAbis(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { return Abi2Wrapper.getAbi1andAbi2(); } return new String[]{Build.CPU_ABI}; }
Source:
protected String streamableToString(JsonStream.Streamable streamable) { StringWriter writer = new StringWriter(); JsonStream jsonStream = new JsonStream(writer); try { streamable.toStream(jsonStream); START } catch(java.io.IOException e) END return writer.toString(); } nit: import?

Target:
protected String streamableToString(JsonStream.Streamable streamable) throws IOException { StringWriter writer = new StringWriter(); JsonStream jsonStream = new JsonStream(writer); streamable.toStream(jsonStream); return writer.toString(); }
Source:
public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { // use the english locale to avoid the infamous turkish locale bug START final String upperCaseIsolationLevelName = Optional.of(transactionIsolationName.toUpperCase(Locale.ENGLISH)) END .orElseThrow(IllegalArgumentException::new); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; } Why `Optional` is used here? It's absolutely redundant

Target:
public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { // use the english locale to avoid the infamous turkish locale bug final String upperCaseIsolationLevelName = transactionIsolationName.toUpperCase(Locale.ENGLISH); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; }
Source:
START public HikariCPCollector add(String name, PoolStats poolStats) { END poolStatsMap.put(name, poolStats); return this; } I am not a Prometheus user, but I want to understand why this is ``public``. It appears to only be used by ``/PrometheusMetricsTracker`` in the same package.

Target:
protected HikariCPCollector add(String name, PoolStats poolStats) { poolStatsMap.put(name, poolStats); return this; }
Source:
public void setAutoCommit(boolean autoCommit) throws SQLException { delegate.setAutoCommit(autoCommit); isAutoCommit = autoCommit; START isCommitStateDirty = false; END dirtyBits |= DIRTY_BIT_AUTOCOMMIT; } This is not a valid change. The JavaDoc says: > If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed > If setAutoCommit is called and the auto-commit mode is not changed, the call is a no-op. If auto-commit started as `false` and the user performed some SQL, then `isCommitStateDirty` is `true`. If the user calls `setAutoCommit(false)` during the transaction, it is a no-op (auto-commit is still _false_). Which means that `isCommitStateDirty` should _still_ be `true` also. This change would set it to `false` unconditionally.

Target:
public void setAutoCommit(boolean autoCommit) throws SQLException { delegate.setAutoCommit(autoCommit); if (isAutoCommit != autoCommit) { isCommitStateDirty = false; } isAutoCommit = autoCommit; dirtyBits |= DIRTY_BIT_AUTOCOMMIT; }
Source:
final void markCommitStateDirty() { START if (isAutoCommit || isReadOnly) { END lastAccess = clockSource.currentTime(); } else { isCommitStateDirty = true; } } This is more expensive. `markCommitStateDirty()` may be called dozens or hundreds of times in a single connection use, so `isReadOnly` is evaluated many times. However, `close()` is only called once per connection use, and therefore checking the `isReadOnly` flag there (where it is currently), is more efficient.

Target:
final void markCommitStateDirty() { isCommitStateDirty = true; }
Source:
public Boolean call() throws Exception { long sleepBackoff = 200L; do { final PoolEntry poolEntry = createPoolEntry(); START if (poolEntry == PoolEntry.MAXED_POOL_MARKER) { END return Boolean.FALSE; } else if (poolEntry != null) { connectionBag.add(poolEntry); return Boolean.TRUE; } // addConnection() failed, so we sleep and retry quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 2, (long) (sleepBackoff * 1.3)); } while (true); } I prefer to keep the static import.

Target:
public Boolean call() throws Exception { long sleepBackoff = 200L; do { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry == MAXED_POOL_MARKER) { return Boolean.FALSE; } else if (poolEntry != null) { connectionBag.add(poolEntry); return Boolean.TRUE; } // addConnection() failed, so we sleep and retry quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 2, (long) (sleepBackoff * 1.3)); } while (true); }
Source:
private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout) { if (connectionTimeout != Integer.MAX_VALUE) { try { dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout))); } catch (SQLException e) { LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } START catch (UnsupportedOperationException e) { END LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } } } As this is a pull request against _dev_, and _dev_ is Java 7/8 only, please combine this catch with the above using a multi-catch statement.

Target:
private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout) { if (connectionTimeout != Integer.MAX_VALUE) { try { dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout))); } catch (SQLException | UnsupportedOperationException e) { LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } } }
Source:
public CohortDefinition getPersonWithAttribute() { PersonAttributeCohortDefinition cd = new PersonAttributeCohortDefinition(); cd.addParameter(new Parameter("attributeType", "reporting.parameter.attributeType", PersonAttributeType.class)); cd.addParameter(new Parameter("values", "reporting.parameter.values", String.class, List.class, null)); START return new MappedParametersCohortDefinition(cd, "attributeType", "attributeType", "values", "values"); END } I don't think this line is adding any value. Can't you just return "cd" if you aren't changing the names or mappings of any of the parameters?

Target:
public CohortDefinition getPersonWithAttribute() { PersonAttributeCohortDefinition cd = new PersonAttributeCohortDefinition(); cd.addParameter(new Parameter("attributeType", "reporting.parameter.attributeType", PersonAttributeType.class)); cd.addParameter(new Parameter("values", "reporting.parameter.values", String.class, List.class, null)); return cd; }
Source:
public Map<String, Mapped<PatientDataDefinition>> getContainedDataDefinitions() { START return containedDataDefinitions; END } Per above, can you change this to "if (containedDataDefinitions == null) { containedDataDefinitions = new HashMap... }; return containedDataDefinitions;

Target:
public Map<String, Mapped<PatientDataDefinition>> getContainedDataDefinitions() { if (containedDataDefinitions == null) { containedDataDefinitions = new HashMap<String, Mapped<PatientDataDefinition>>(); } return containedDataDefinitions; }
Source:
public Settings getState() { START System.out.println(pathToProjectContainer); END return this; } You can probably remove this

Target:
public Settings getState() { return this; }
Source:
public Stream(byte[] key) { this.key = key; START checkLength(key, NaCl.Sodium.AES_128_CTR_KEYBYTES); END } Make use of import static, please. Into this way we just leave the constant into the code.

Target:
public Stream(byte[] key) { this.key = key; checkLength(key, AES_128_CTR_KEYBYTES); }
Source:
public Collection<GrantedAuthority> getAuthorities() { List<GrantedAuthority> roles = new ArrayList<>(1); START roles.add(new SimpleGrantedAuthority(getUser().getRole().getShortName())); END return roles; } return List.of(new SimpleGrantedAuthority(getUser().getRole().getShortName()))

Target:
public Collection<GrantedAuthority> getAuthorities() { return ImmutableList.of(new SimpleGrantedAuthority(getUser().getRole().getShortName())); }
Source:
public AgentInfo approve(Long id, boolean approve) { Optional<AgentInfo> found = agentManagerRepository.findOne(idEqual(id)); AgentInfo agentInfo = null; if (found.isPresent()) { agentInfo = found.get(); agentInfo.setApproved(approve); START agentManagerRepository.save(agentInfo); END expireLocalCache(); } return agentInfo; } check if explicit ```save``` is necessary .

Target:
public AgentInfo approve(Long id, boolean approve) { Optional<AgentInfo> found = agentManagerRepository.findOne(idEqual(id)); AgentInfo agentInfo = null; if (found.isPresent()) { agentInfo = found.get(); agentInfo.setApproved(approve); expireLocalCache(); } return agentInfo; }
Source:
public ConsoleProperties createConsoleProperties(PerfTest perfTest) { ConsoleProperties consoleProperties = ConsolePropertiesFactory.createEmptyConsoleProperties(); try { START removePerftestResultDistributedFolderIfExist(perfTest); END consoleProperties.setAndSaveDistributionDirectory(new Directory(getDistributionPath(perfTest))); consoleProperties.setConsoleHost(config.getCurrentIP()); consoleProperties.setIgnoreSampleCount(getSafe(perfTest.getIgnoreSampleCount())); consoleProperties.setSampleInterval(1000 * getSafe(perfTest.getSamplingInterval())); } catch (Exception e) { throw processException("Error while setting console properties", e); } return consoleProperties; } I think this should not be called here.. it has the different behavior from createConsoleProperties()

Target:
public ConsoleProperties createConsoleProperties(PerfTest perfTest) { ConsoleProperties consoleProperties = ConsolePropertiesFactory.createEmptyConsoleProperties(); try { consoleProperties.setAndSaveDistributionDirectory(new Directory(getDistributionPath(perfTest))); consoleProperties.setConsoleHost(config.getCurrentIP()); consoleProperties.setIgnoreSampleCount(getSafe(perfTest.getIgnoreSampleCount())); consoleProperties.setSampleInterval(1000 * getSafe(perfTest.getSamplingInterval())); } catch (Exception e) { throw processException("Error while setting console properties", e); } return consoleProperties; }
Source:
public void addFileToPackage(TarArchiveOutputStream tarArchiveOutputStream, File file, String path) throws IOException { START CompressionUtils.addFileToTar(tarArchiveOutputStream, file, getLibPath() + path); END } Please use static import for CompressionUtils. likewise addFolderToTar above.

Target:
public void addFileToPackage(TarArchiveOutputStream tarArchiveOutputStream, File file, String path) throws IOException { addFileToTar(tarArchiveOutputStream, file, getLibPath() + path); }
Source:
void init() { ngrinderContext = System.getProperty("ngrinder.context", "agent"); START workDirectory = System.getProperty("ngrinder.base.path", System.getProperty("user.dir")); END if (isControllerContext()) { controllerHomeDir = resolveControllerHomeDir(); controllerHomeTmpDir = (controllerHomeDir + File.separator + NGRINDER_CONTROLLER_TEMP_FOLDER); } this.initAccessOfDirectories(); this.initAccessOfHosts(); } Isn't it better to use ngrinder.user.dir ?

Target:
void init() { ngrinderContext = System.getProperty("ngrinder.context", "agent"); if (isControllerContext()) { controllerHomeDir = resolveControllerHomeDir(); controllerHomeTmpDir = (controllerHomeDir + File.separator + NGRINDER_CONTROLLER_TEMP_FOLDER); } this.initAccessOfDirectories(); this.initAccessOfHosts(); }
Source:
public <M> List<M> getEnabledModulesByClass(Class<M> moduleClass, M defaultPlugin) { ArrayList<M> pluginClasses = new ArrayList<M>(); if (defaultPlugin != null) { pluginClasses.add(defaultPlugin); } START if (manager.getExtensions(moduleClass).size() > 0) { END pluginClasses.addAll(manager.getExtensions(moduleClass)); } return pluginClasses; } size 체크 없이 바로 `.addAll`해도 문제 없을 것 같아요.

Target:
public <M> List<M> getEnabledModulesByClass(Class<M> moduleClass, M defaultPlugin) { ArrayList<M> pluginClasses = new ArrayList<M>(); if (defaultPlugin != null) { pluginClasses.add(defaultPlugin); } pluginClasses.addAll(manager.getExtensions(moduleClass)); return pluginClasses; }
Source:
public Map<String, Set<String>> readClasspathStorages() { START Map<String, Set<String>> result = new LinkedHashMap<String, Set<String>>(); END return result; } 따로 result 변수없이 바로 `return new LinkedHashMap<...>();`가 좋을 것 같습니다.

Target:
public Map<String, Set<String>> readClasspathStorages() { return new LinkedHashMap<String, Set<String>>(); }
Source:
protected PluginClasspath createPluginClasspath() { START if (RuntimeMode.DEVELOPMENT.equals(getRuntimeMode())) { END return new DevelopmentPluginClasspath(); } return new NGrinderPluginClasspath(); } Development Runtime 모드를 판별하는 기준이 뭐죠? Config에는 isDevMode 라는 메소드가 있는데, 이걸로 판별하는 편이 나을 듯.

Target:
protected PluginClasspath createPluginClasspath() { return new NGrinderPluginClasspath(); }
Source:
START static public Set<String> parseProtocolRequestHeader(String value) { END if (StringUtils.isEmpty(value)) { return null; } Set<String> subprotocols = new LinkedHashSet<>(); if (!StringUtils.isEmpty(value)) { String[] values = value.split(","); for (String v : values) { subprotocols.add(v.trim()); } } return subprotocols; } Just an observation... might it be more cool to return Collections.emptySet()?... if we have the option to reduce null usage we should do so... imho helps in the long run... but - I may be wrong...

Target:
static public Set<String> parseProtocolRequestHeader(String value) { Set<String> subprotocols = new LinkedHashSet<>(); if (!StringUtils.isEmpty(value)) { String[] values = value.split(","); for (String v : values) { subprotocols.add(v.trim()); } } return subprotocols; }