auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void serialize(ExtKey extKey, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { <START> jsonGenerator.writeFieldName(extKey.getUuid().getName() + ";" + extKey.getType().getName() + ";" + extKey.getUuid().getUuid()); <END> }</code><technical_language>user String.format() for that? jsonGenerator.writeFieldName("%s;%s;%s", extKey.getUuid().getName(), extKey.getType().getName(), extKey.getUuid().getUuid());</technical_language>

Target:
public void serialize(ExtKey extKey, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeFieldName( String.format("%s;%s;%s", extKey.getUuid().getName(), extKey.getType().getName(), extKey.getUuid().getUuid())); }
Source:
<code>public void testLegacyLogFunctionDisabled() { try (DistributedQueryRunner queryRunner = createQueryRunner(false)) { <START> MaterializedResult result = queryRunner.execute(QUERY); <END> fail("Expected exception"); } catch (Exception e) { assertContains(e.getMessage(), "Function log not registered"); } }</code><technical_language>result is unused</technical_language>

Target:
public void testLegacyLogFunctionDisabled() { try (QueryRunner runner = createQueryRunner(false)) { runner.execute(QUERY); } }
Source:
<code>public void handle(Exception exception) { if (exception instanceof IllegalArgumentException <START> || exception instanceof IllegalStateException) { <END> throw new InterceptionException(exception); } if (exception instanceof ReflectionProviderException) { throwIfNotValidationException(exception, exception.getCause()); } throwIfNotValidationException(exception, exception); }</code><technical_language>tending VRaptor specific exceptions for this case, instead of reusing IllegalArg IllegalState... this of validations, right? create a ValidationFailedException</technical_language>

Target:
public void handle(Exception exception) { if (exception instanceof ReflectionProviderException) { throwIfNotValidationException(exception, exception.getCause()); } throwIfNotValidationException(exception, exception); }
Source:
<code>public SinkRuntimeProvider getSinkRuntimeProvider(Context context) { final SerializationSchema<RowData> keySerialization = createSerialization(context, keyEncodingFormat, keyProjection, keyPrefix); final SerializationSchema<RowData> valueSerialization = createSerialization(context, valueEncodingFormat, valueProjection, null); final FlinkKafkaProducer<RowData> kafkaProducer = createKafkaProducer(keySerialization, valueSerialization); <START> return new SinkFunctionProvider() { <END> @Override public SinkFunction<RowData> createSinkFunction() { return kafkaProducer; } @Override public Optional<Integer> getParallelism() { return parallelism == null ? Optional.empty() : Optional.of(parallelism); } }; }</code><technical_language>add a new util method in SinkFunctionProvider? I of connector this new method. java /** * Helper method for creating a SinkFunction provider a provided sink parallelism. */ static SinkFunctionProvider of(SinkFunction<RowData> sinkFunction, Integer sinkParallelism) { return new SinkFunctionProvider() { @Override public SinkFunction<RowData> createSinkFunction() { return sinkFunction; } @Override public Optional<Integer> getParallelism() { return Optional.ofNullable(sinkParallelism); } }; }</technical_language>

Target:
public SinkRuntimeProvider getSinkRuntimeProvider(Context context) { final SerializationSchema<RowData> keySerialization = createSerialization(context, keyEncodingFormat, keyProjection, keyPrefix); final SerializationSchema<RowData> valueSerialization = createSerialization(context, valueEncodingFormat, valueProjection, null); final FlinkKafkaProducer<RowData> kafkaProducer = createKafkaProducer(keySerialization, valueSerialization); return SinkFunctionProvider.of(kafkaProducer, parallelism); }
Source:
<code>public SqlOptionNode(SqlParserPos pos, SqlIdentifier key, SqlLiteral literal) { super(pos); if (key.isSimple()) { familyName = ""; propertyName = key.getSimple(); } else { familyName = key.names.get(0); propertyName = key.names.get(1); } PhoenixRelImplementor <START> implementor = new PhoenixRelImplementorImpl(new RuntimeContextImpl()); <END> this.value = CalciteUtils.convertLiteral(literal, implementor); }</code><technical_language>need a "dummy" RuntimeContext for this kind of "dry run" implementor. do this part I commit it</technical_language>

Target:
public SqlOptionNode(SqlParserPos pos, SqlIdentifier key, SqlLiteral literal) { super(pos); if (key.isSimple()) { familyName = ""; propertyName = key.getSimple(); } else { familyName = key.names.get(0); propertyName = key.names.get(1); } PhoenixRelImplementor implementor = new PhoenixRelImplementorImpl(new RuntimeContextImpl()); this.value = CalciteUtils.convertSqlLiteral(literal, implementor); }
Source:
<code>public void timeout() { synchronized (runLock) { createSnapshot(ACTION_TIMEOUT); <START> requestBatchStart(); <END> _startTimeout(); requestBatchEnd(); ScoreBoardManager.gameSnapshot(); } }</code><technical_language>a batch for a single call starts a batch, in stopJamTO similar</technical_language>

Target:
public void timeout() { synchronized (runLock) { createSnapshot(ACTION_TIMEOUT); _startTimeout(); ScoreBoardManager.gameSnapshot(); } }
Source:
<code>public AuthFileCredential build() { <START> ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("filepath", filepath); }}); <END> return new AuthFileCredential(filepath, identityClientOptions); }</code><technical_language>simpler check if filePath is null instead of creating a new hashmap ValidationUtil for null check of a single field</technical_language>

Target:
public AuthFileCredential build() { return new AuthFileCredential(filepath, identityClientOptions); }
Source:
<code>private <T> T withFollowingRedirect(WebTarget initialWebTarget, RequestWithFollowingRedirect<T> request) { WebApplicationException firstRedirectException = null; WebTarget webTarget = initialWebTarget; for (int i = 0; i < MAX_REDIRECT; i++) { try { return request.invoke(webTarget); } catch (WebApplicationException e) { <START> firstRedirectException = e; <END> Response response = checkNotNull(e.getResponse()); int status = response.getStatus(); if (status % 100 == 3 && response.getLocation() != null) { webTarget = client.target(UriBuilder.fromUri(response.getLocation())); continue; } throw e; } } throw firstRedirectException; }</code><technical_language>firstRedirectException exception? Then, this be: java if (firstRedirectException == null) { firstRedirectException = e; }</technical_language>

Target:
private <T> T withFollowingRedirect(WebTarget initialWebTarget, RequestWithFollowingRedirect<T> request) { WebApplicationException firstRedirectException = null; WebTarget webTarget = initialWebTarget; for (int i = 0; i < MAX_REDIRECT; i++) { try { return request.invoke(webTarget); } catch (WebApplicationException e) { if (firstRedirectException == null) { firstRedirectException = e; } Response response = checkNotNull(e.getResponse()); int status = response.getStatus(); if (status % 100 == 3 && response.getLocation() != null) { webTarget = client.target(UriBuilder.fromUri(response.getLocation())); continue; } throw e; } } throw firstRedirectException; }
Source:
<code>public void setUp() { <START> memoryPool = new MemoryPool(LocalMemoryManager.GENERAL_POOL, new DataSize(10, DataSize.Unit.BYTE)); <END> TaskExecutor taskExecutor = new TaskExecutor(8, 16); taskExecutor.start(); executor = newScheduledThreadPool(10, threadsNamed("task-notification-%s")); LocalExecutionPlanner planner = createTestingPlanner(); sqlTaskExecutionFactory = new SqlTaskExecutionFactory( executor, taskExecutor, planner, new QueryMonitor(new ObjectMapperProvider().get(), jsonCodec(StageInfo.class), new EventListenerManager(), new NodeInfo("test"), new NodeVersion("testVersion"), new QueryMonitorConfig()), new TaskManagerConfig()); allOperatorContexts = null; }</code><technical_language>Static import</technical_language>

Target:
public void setUp() { memoryPool = new MemoryPool(GENERAL_POOL, new DataSize(10, BYTE)); TaskExecutor taskExecutor = new TaskExecutor(8, 16); taskExecutor.start(); executor = newScheduledThreadPool(1, threadsNamed("task-notification-%s")); LocalExecutionPlanner planner = createTestingPlanner(); sqlTaskExecutionFactory = new SqlTaskExecutionFactory( executor, taskExecutor, planner, new QueryMonitor(new ObjectMapperProvider().get(), jsonCodec(StageInfo.class), new EventListenerManager(), new NodeInfo("test"), new NodeVersion("testVersion"), new QueryMonitorConfig()), new TaskManagerConfig()); allOperatorContexts = null; }
Source:
<code>public boolean delete( FileInfo fileInfo ) { File f = new File( baseDir, fileInfo.getFileStorage() ); <START> return f.delete(); <END> }</code><technical_language>worth Files.deleteIfExists(..) ? official doc said: > Note Files class defines delete method throw IOException a file deleted. This is useful for error reporting diagnose a file deleted</technical_language>

Target:
public boolean delete( FileInfo fileInfo ) { File f = new File( baseDir, fileInfo.getFileStorage() ); try { Files.deleteIfExists( Paths.get( f.getAbsolutePath() ) ); } catch ( IOException e ) { logger.error( "Failed to delete file: " + fileInfo, e ); return false; } return true; }
Source:
<code>public ColumnReader getColumnReader(ColumnDescriptor path) { PrimitiveConverter converter = getPrimitiveConverter(path); PageReader pageReader = pageReadStore.getPageReader(path); if (pageReadStore.isInPageFilteringMode()) { return new SynchronizingColumnReader(path, pageReader, converter, writerVersion, pageReadStore.getRowIndexes()); } else { <START> return new ColumnReaderImpl(path, pageReader, converter, writerVersion); <END> } }</code><technical_language>this newMemColumnReader? of function, I of inlined this, continue calling it</technical_language>

Target:
public ColumnReader getColumnReader(ColumnDescriptor path) { PrimitiveConverter converter = getPrimitiveConverter(path); PageReader pageReader = pageReadStore.getPageReader(path); Optional<PrimitiveIterator.OfLong> rowIndexes = pageReadStore.getRowIndexes(); if (rowIndexes.isPresent()) { return new SynchronizingColumnReader(path, pageReader, converter, writerVersion, rowIndexes.get()); } else { return new ColumnReaderImpl(path, pageReader, converter, writerVersion); } }
Source:
<code>public void createPdpFeedsFromRequestExtracts() { List<String> filesToProcess = getUnprocessedRequestExtractFiles(); if (filesToProcess.isEmpty()) { <START> LOG.error("No Request Extract files found to process."); <END> } else { for (String requestExtractFileName : filesToProcess) { createPdpFeedFromRequestExtract(requestExtractFileName); LOG.info("Request Extract File " + requestExtractFileName + " was processed."); } } }</code><technical_language>I this is necessarily error. this log info level</technical_language>

Target:
public void createPdpFeedsFromRequestExtracts() { List<String> filesToProcess = getUnprocessedRequestExtractFiles(); if (filesToProcess.isEmpty()) { LOG.info("No Request Extract files found to process."); } else { for (String requestExtractFileName : filesToProcess) { createPdpFeedFromRequestExtract(requestExtractFileName); LOG.info("Request Extract File " + requestExtractFileName + " was processed."); } } }
Source:
<code>public void execute(IProgressMonitor monitor) { IPluginModelBase[] plugins = PluginJavaSearchUtil.getPluginImports(fImportID); SubMonitor subMonitor = SubMonitor.convert(monitor, PDEUIMessages.DependencyExtentOperation_searching + " " + fImportID + "...", 10); checkForJavaDependencies(plugins, subMonitor.newChild(9)); for (int i = 0; i < plugins.length; i++) { <START> checkForExtensionPointsUsed(plugins[i]); <END> } }</code><technical_language>Ticks line up. If checkForExtensionPointsUsed is slow, consider reporting progress here</technical_language>

Target:
public void execute(IProgressMonitor monitor) { IPluginModelBase[] plugins = PluginJavaSearchUtil.getPluginImports(fImportID); SubMonitor subMonitor = SubMonitor.convert(monitor, PDEUIMessages.DependencyExtentOperation_searching + " " + fImportID + "...", 10); checkForJavaDependencies(plugins, subMonitor.newChild(9)); subMonitor.setWorkRemaining(plugins.length); for (int i = 0; i < plugins.length; i++) { checkForExtensionPointsUsed(plugins[i]); subMonitor.worked(1); } }
Source:
<code>private void initKeyStore() throws CertificateManagerException { LOG.debug("SamlCallbackHandler.initKeyStore() -- Begin"); final Map<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_PASSWORD_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.warn(STORE_TYPE_ERROR, KEY_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (password != null) { if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("{} is not defined", KEY_STORE_TYPE_KEY); } else { keyStore = loadKeyStore(storeType, password, storeLoc); } } else { LOG.error("Please define {}", KEY_STORE_PASSWORD_KEY); } <START> LOG.debug("SamlCallbackHandler.initKeyStore() -- End"); <END> }</code><technical_language>This log message is completely</technical_language>

Target:
private void initKeyStore() throws CertificateManagerException { LOG.debug("initKeyStore() -- Begin"); final Map<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_PASSWORD_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.warn(STORE_TYPE_ERROR, KEY_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (password != null) { if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("{} is not defined", KEY_STORE_TYPE_KEY); } else { keyStore = loadKeyStore(storeType, password, storeLoc); } } else { LOG.error("Please define {}", KEY_STORE_PASSWORD_KEY); } LOG.debug("initKeyStore() -- End"); }
Source:
<code>public void helpSiteAddress(String url) { launchHelpshift(url, null, <START> HelpshiftHelper.chooseHelpshiftLoginTag(getLoginMode() == LoginMode.JETPACK_STATS, false)); <END> }</code><technical_language>getLoginMode() == LoginMode.JETPACK_STATS repeated 6 times, worth adding a helper for it</technical_language>

Target:
public void helpSiteAddress(String url) { launchHelpshift(url, null, false); }
Source:
<code>public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize(), <START> other.getMaxConcurrency() == null ? Integer.valueOf(Queues.SMALL_BUFFER_SIZE) : other.getMaxConcurrency()); <END> }</code><technical_language>want a parallelization is more idiomatic Storage service usage? I Queues.SMALL_BUFFER_SIZE aligns more Reactor's usage higher level of parallelization get issues</technical_language>

Target:
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null, null) : other; if (other.getBlockSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.blockSize", other.getBlockSize(), 1, MAX_APPEND_FILE_BYTES); } if (other.getMaxSingleUploadSize() != null) { StorageImplUtils.assertInBounds("ParallelTransferOptions.maxSingleUploadSize", other.getMaxSingleUploadSize(), 1, MAX_APPEND_FILE_BYTES); } return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(FILE_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getMaxConcurrency() == null ? Integer.valueOf(FILE_DEFAULT_NUMBER_OF_BUFFERS) : other.getMaxConcurrency(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(MAX_APPEND_FILE_BYTES) : other.getMaxSingleUploadSize()); }
Source:
<code>public void testCreateIncludesRequestValidatorInterceptorOutcome() throws IOException { RequestValidatingInterceptor interceptor = new RequestValidatingInterceptor(); assertTrue(interceptor.isAddValidationResultsToResponseOperationOutcome()); interceptor.setFailOnSeverity(null); ourRestServer.registerInterceptor(interceptor); try { Observation obs = new Observation(); obs.addIdentifier().setSystem("urn:foo").setValue("bar"); IBaseResource outcome = ourClient.create().resource(obs).execute().getOperationOutcome(); String encodedOo = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome); ourLog.info(encodedOo); <START> assertThat(encodedOo, containsString("The content of element 'Observation' is not complete")); <END> assertThat(encodedOo, containsString("Successfully created resource \\\"Observation/")); interceptor.setAddValidationResultsToResponseOperationOutcome(false); outcome = ourClient.create().resource(obs).execute().getOperationOutcome(); encodedOo = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome); ourLog.info(encodedOo); assertThat(encodedOo, not(containsString("The content of element 'Observation' is not complete"))); assertThat(encodedOo, containsString("Successfully created resource \\\"Observation/")); } finally { ourRestServer.unregisterInterceptor(interceptor); } }</code><technical_language>modify test assertion check for "cvc-complex-type.2.4.b" instead</technical_language>

Target:
public void testCreateIncludesRequestValidatorInterceptorOutcome() throws IOException { RequestValidatingInterceptor interceptor = new RequestValidatingInterceptor(); assertTrue(interceptor.isAddValidationResultsToResponseOperationOutcome()); interceptor.setFailOnSeverity(null); ourRestServer.registerInterceptor(interceptor); try { Observation obs = new Observation(); obs.addIdentifier().setSystem("urn:foo").setValue("bar"); IBaseResource outcome = ourClient.create().resource(obs).execute().getOperationOutcome(); String encodedOo = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome); ourLog.info(encodedOo); assertThat(encodedOo, containsString("cvc-complex-type.2.4.b")); assertThat(encodedOo, containsString("Successfully created resource \\\"Observation/")); interceptor.setAddValidationResultsToResponseOperationOutcome(false); outcome = ourClient.create().resource(obs).execute().getOperationOutcome(); encodedOo = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome); ourLog.info(encodedOo); assertThat(encodedOo, not(containsString("cvc-complex-type.2.4.b"))); assertThat(encodedOo, containsString("Successfully created resource \\\"Observation/")); } finally { ourRestServer.unregisterInterceptor(interceptor); } }
Source:
<code>public static SortedMap<String, Object> allDefaults(){ final SortedMap<String, Object> result = new TreeMap<>(); result.put("CREATE_INDEX", CREATE_INDEX); result.put("CREATE_MD5", CREATE_MD5); result.put("USE_ASYNC_IO_READ_FOR_SAMTOOLS", USE_ASYNC_IO_READ_FOR_SAMTOOLS); result.put("USE_ASYNC_IO_WRITE_FOR_SAMTOOLS", USE_ASYNC_IO_WRITE_FOR_SAMTOOLS); <START> result.put("USE_ASYNC_IO_WRTIE_FOR_TRIBBLE", USE_ASYNC_IO_WRITE_FOR_TRIBBLE); <END> result.put("COMPRESSION_LEVEL", COMPRESSION_LEVEL); result.put("BUFFER_SIZE", BUFFER_SIZE); result.put("NON_ZERO_BUFFER_SIZE", NON_ZERO_BUFFER_SIZE); result.put("REFERENCE_FASTA", REFERENCE_FASTA); result.put("USE_CRAM_REF_DOWNLOAD", USE_CRAM_REF_DOWNLOAD); result.put("EBI_REFERENCE_SERVICE_URL_MASK", EBI_REFERENCE_SERVICE_URL_MASK); result.put("CUSTOM_READER_FACTORY", CUSTOM_READER_FACTORY); result.put("SAM_FLAG_FIELD_FORMAT", SAM_FLAG_FIELD_FORMAT); return Collections.unmodifiableSortedMap(result); }</code><technical_language>WRTIE -> WRITE</technical_language>

Target:
public static SortedMap<String, Object> allDefaults(){ final SortedMap<String, Object> result = new TreeMap<>(); result.put("CREATE_INDEX", CREATE_INDEX); result.put("CREATE_MD5", CREATE_MD5); result.put("USE_ASYNC_IO_READ_FOR_SAMTOOLS", USE_ASYNC_IO_READ_FOR_SAMTOOLS); result.put("USE_ASYNC_IO_WRITE_FOR_SAMTOOLS", USE_ASYNC_IO_WRITE_FOR_SAMTOOLS); result.put("USE_ASYNC_IO_WRITE_FOR_TRIBBLE", USE_ASYNC_IO_WRITE_FOR_TRIBBLE); result.put("COMPRESSION_LEVEL", COMPRESSION_LEVEL); result.put("BUFFER_SIZE", BUFFER_SIZE); result.put("NON_ZERO_BUFFER_SIZE", NON_ZERO_BUFFER_SIZE); result.put("REFERENCE_FASTA", REFERENCE_FASTA); result.put("USE_CRAM_REF_DOWNLOAD", USE_CRAM_REF_DOWNLOAD); result.put("EBI_REFERENCE_SERVICE_URL_MASK", EBI_REFERENCE_SERVICE_URL_MASK); result.put("CUSTOM_READER_FACTORY", CUSTOM_READER_FACTORY); result.put("SAM_FLAG_FIELD_FORMAT", SAM_FLAG_FIELD_FORMAT); return Collections.unmodifiableSortedMap(result); }
Source:
<code>public int hashCode() { <START> return Objects.hashCode(value); <END> }</code><technical_language>HashUtil.combineHashCodes</technical_language>

Target:
public int hashCode() { return HashUtil.combineHashCodes(Objects.hashCode(value)); }
Source:
<code>public String toString() { if(sb == null) sb = new StringBuilder(length()); else <START> sb.delete(0, sb.length()); <END> for (String cb : bufferList) { sb.append(cb); } return sb.toString(); }</code><technical_language>I reusing StringBuilder a big difference, if want reuse call sb.setLength(0) sb.delete() clear it, ends calling a native method</technical_language>

Target:
public String toString() { if(sb == null) sb = new StringBuilder(length()); else sb.setLength(0); for (String cb : bufferList) { sb.append(cb); } return sb.toString(); }
Source:
<code>public void shutdown() { <START> log.info("Shutting down TableMonitorThread"); <END> shutdownLatch.countDown(); }</code><technical_language>this is INFO level, about: suggestion log.info("Shutting thread monitoring tables.");</technical_language>

Target:
public void shutdown() { log.info("Shutting down thread monitoring tables."); shutdownLatch.countDown(); }
Source:
<code>static String getFieldWithPrimaryKeyAnnotation(Class<?> cls) { Field[] fs = cls.getDeclaredFields(); for (Field f : fs) { if (f.isAnnotationPresent(PrimaryKey.class)) { return f.getName(); } } <START> return ""; <END> }</code><technical_language>I this example I gave, this assertion failure instead? e.g. java Assumption.fail("There a field annotated @PrimaryKey"); Add: do more ensure field annotated @PrimaryKey, this is important</technical_language>

Target:
protected static String getFieldWithPrimaryKeyAnnotation(Class<?> cls) { Field[] fs = cls.getDeclaredFields(); for (Field f : fs) { if (f.isAnnotationPresent(PrimaryKey.class)) { return f.getName(); } } Assumption.fail("There should be a field annotated with @PrimaryKey"); return null; }
Source:
<code>protected List<NuxeoOAuth2Token> findTokens(QueryBuilder queryBuilder) { return Framework.doPrivileged(() -> { DirectoryService ds = Framework.getService(DirectoryService.class); try (Session session = ds.open(TOKEN_DIR)) { List<DocumentModel> documents = session.query(queryBuilder, false); <START> return documents.stream().distinct().map(NuxeoOAuth2Token::new).collect(Collectors.toList()); <END> } }); }</code><technical_language>distinct()</technical_language>

Target:
protected List<NuxeoOAuth2Token> findTokens(QueryBuilder queryBuilder) { return findTokens(queryBuilder, null); }
Source:
<code><START> public int numberOfUsers() { <END> try (Connection conn = getConnection(); PreparedStatement select = conn.prepareStatement(GET_ALL_QUOTAS)) { ResultSet rs = select.executeQuery(); int count = 0; while (rs.next()) { count++; } return count; } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new IllegalStateException(sqe); } }</code><technical_language>select count() is general do in SQL</technical_language>

Target:
public int numberOfUsers() { try (Connection conn = getConnection(); PreparedStatement select = conn.prepareStatement(COUNT_USERS)) { ResultSet rs = select.executeQuery(); rs.next(); return rs.getInt(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new IllegalStateException(sqe); } }
Source:
<code>private void fetchAndDisplayCaption(DisplayableContribution contribution) { if ((contribution.getState() != Contribution.STATE_COMPLETED)) { titleView.setText(contribution.getDisplayTitle()); } else { Timber.d("Fetching caption for %s", contribution.getFilename()); compositeDisposable.add(mediaClient.getCaptionByFilename(contribution.getFilename()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .subscribe(subscriber -> { <START> if (!subscriber.trim().equals("No caption")) { <END> titleView.setText(subscriber); } else titleView.setText(contribution.getDisplayTitle()); })); } }</code><technical_language>Please "No caption" a final static constant</technical_language>

Target:
private void fetchAndDisplayCaption(DisplayableContribution contribution) { if ((contribution.getState() != Contribution.STATE_COMPLETED)) { titleView.setText(contribution.getDisplayTitle()); } else { Timber.d("Fetching caption for %s", contribution.getFilename()); String wikibaseMediaId = "M"+contribution.getPageId(); compositeDisposable.add(mediaClient.getCaptionByWikibaseIdentifier(wikibaseMediaId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) .subscribe(subscriber -> { if (!subscriber.trim().equals(NO_CAPTION)) { titleView.setText(subscriber); } else titleView.setText(contribution.getDisplayTitle()); })); } }
Source:
<code>public void serialize(SliceOutput out) { out.appendInt(bucketCount); out.appendDouble(min); out.appendDouble(max); out.appendInt(indices.length); int i = 0; <START> for (i = 0; i < bucketCount; ++i) { <END> out.appendDouble(indices[i]); } for (i = 0; i < bucketCount; ++i) { out.appendDouble(weights[i]); } for (i = 0; i < bucketCount; ++i) { out.appendDouble(counts[i]); } }</code><technical_language>nit: suggestion for (int i = 0; i < bucketCount; ++i) {</technical_language>

Target:
public void serialize(SliceOutput out) { out.appendInt(bucketCount); out.appendDouble(min); out.appendDouble(max); out.appendInt(indices.length); IntStream.range(0, indices.length).forEach(i -> out.appendInt(indices[i])); IntStream.range(0, indices.length).forEach(i -> out.appendDouble(weights[i])); IntStream.range(0, indices.length).forEach(i -> out.appendLong(counts[i])); }
Source:
<code>public static CompositeType camelRoutePropertiesCompositeType() throws OpenDataException { return new CompositeType("routeProperties", "Route Properties", <START> new String[]{"name", "value"}, <END> new String[]{"Name", "Value"}, new OpenType[]{SimpleType.STRING, SimpleType.STRING}); }</code><technical_language>key instead of name a key/value pair</technical_language>

Target:
public static CompositeType camelRoutePropertiesCompositeType() throws OpenDataException { return new CompositeType("routeProperties", "Route Properties", new String[]{"key", "value"}, new String[]{"Key", "Value"}, new OpenType[]{SimpleType.STRING, SimpleType.STRING}); }
Source:
<code>protected EObject getTargetEObject() { View view = getTargetView(); <START> return view.getElement(); <END> }</code><technical_language>nullpointer exceoption getTargetView return null</technical_language>

Target:
protected Optional<EObject> getTargetEObject() { Optional<View> view = getTargetView(); if (view.isPresent()) { EObject element = view.get().getElement(); if (element != null) return Optional.of(element); } return Optional.empty(); }
Source:
<code>public void testRegisterAction_IllegalArgument() { CompositeViewAction viewAction = new CompositeViewAction(1, TriggerType.CLICK); ViewAction action1 = mock(ViewAction.class); ViewAction action2 = mock(ViewAction.class); when(action1.getViewId()).thenReturn(2); when(action2.getViewId()).thenReturn(1); when(action1.getTriggerType()).thenReturn(TriggerType.CLICK); when(action2.getTriggerType()).thenReturn(TriggerType.TOUCH); try { viewAction.registerAction(action1); viewAction.registerAction(action2); <START> } catch (IllegalArgumentException e) { <END> Log.d(TAG,"Exception thrown..."); } when(action1.getViewId()).thenReturn(1); try { viewAction.registerAction(action1); viewAction.registerAction(action2); } catch (IllegalArgumentException e) { } Mockito.verify(action1, Mockito.times(3)).getViewId(); Mockito.verify(action2, Mockito.times(2)).getViewId(); }</code><technical_language>need put a fail try block pass properly type of error checking error message. Simply logging assert fact IllegalArgument throw</technical_language>

Target:
public void testRegisterAction_IllegalArgument() { CompositeViewAction viewAction = new CompositeViewAction(1, TriggerType.CLICK); ViewAction clickActionView2 = createAction(2, TriggerType.CLICK); ViewAction touchActionView1 = createAction(1, TriggerType.TOUCH); try { viewAction.registerAction(clickActionView2); viewAction.registerAction(touchActionView1); } catch (IllegalArgumentException e) { } catch (Exception e) { fail("Exception other than expected IllegalArgumentException thrown"); e.printStackTrace(); } Mockito.verify(clickActionView2, Mockito.times(2)).getViewId(); Mockito.verifyZeroInteractions(touchActionView1); ViewAction clickActionView1 = createAction(1, TriggerType.CLICK); try { viewAction.registerAction(clickActionView1); viewAction.registerAction(touchActionView1); } catch (IllegalArgumentException e) { } catch (Exception e) { fail("Exception other than expected IllegalArgumentException thrown"); e.printStackTrace(); } Mockito.verify(clickActionView1, Mockito.times(1)).getViewId(); Mockito.verify(touchActionView1, Mockito.times(2)).getViewId(); }
Source:
<code>public CatalogContext( long transactionId, long uniqueId, Catalog catalog, DbSettings settings, byte[] catalogBytes, byte[] catalogBytesHash, byte[] deploymentBytes, int version, HostMessenger messenger) { this(transactionId, uniqueId, catalog, settings, catalogBytes, catalogBytesHash, deploymentBytes, <START> version, messenger, true, null, null, -1L); <END> }</code><technical_language>is this -1</technical_language>

Target:
public CatalogContext( long transactionId, long uniqueId, Catalog catalog, DbSettings settings, byte[] catalogBytes, byte[] catalogBytesHash, byte[] deploymentBytes, int version, HostMessenger messenger) { this(transactionId, uniqueId, catalog, settings, catalogBytes, catalogBytesHash, deploymentBytes, version, messenger, true, null, null, uniqueId); }
Source:
<code>private FileResource createResource(String filenamePrefix, String extension) { final File directory = _userPreferences.getSaveDatastoreDirectory(); int attempt = 0; while (true) { final String filename; if (attempt == 0) { filename = filenamePrefix + extension; } else { filename = filenamePrefix + "_" + attempt + extension; } final File file = new File(directory, filename); <START> FileResource resourceCandidate = new FileResource(file); <END> if (!resourceCandidate.isExists()) { return resourceCandidate; } attempt++; } }</code><technical_language>final :)</technical_language>

Target:
private FileResource createResource(String filenamePrefix, String extension) { final File directory = _userPreferences.getSaveDatastoreDirectory(); int attempt = 0; while (true) { final String filename; if (attempt == 0) { filename = filenamePrefix + extension; } else { filename = filenamePrefix + "_" + attempt + extension; } final File file = new File(directory, filename); final FileResource resourceCandidate = new FileResource(file); if (!resourceCandidate.isExists()) { return resourceCandidate; } attempt++; } }
Source:
<code>public UUID execute(BranchContext context) { try { File file = doExport(toExportModel(context)); UUID fileId = UUID.randomUUID(); context.service(FileRegistry.class).upload(fileId, new FileInputStream(file)); <START> return fileId; <END> } catch (Exception e) { throw new RuntimeException("Error occurred during DSV export.", e); } }</code><technical_language>this point, export file deleted avoid filling server's tmp directory</technical_language>

Target:
public UUID execute(BranchContext context) { File file = null; try { file = doExport(toExportModel(context)); UUID fileId = UUID.randomUUID(); context.service(FileRegistry.class).upload(fileId, new FileInputStream(file)); return fileId; } catch (Exception e) { throw new RuntimeException("Error occurred during DSV export.", e); } finally { if (file != null) { file.delete(); } } }
Source:
<code>public void close() { final State state = this.state; if (State.CLOSED != state) { final AeronArchive.Context context = archive.context(); final Aeron aeron = context.aeron(); if (!aeron.isClosed()) { final ErrorHandler errorHandler = context.errorHandler(); if (State.MERGED != state && State.STOP_REPLAY != state) { <START> AeronCloseHelper.close(errorHandler, () -> subscription.removeDestination(replayDestination)); <END> } if (isReplayActive) { isReplayActive = false; final long correlationId = aeron.nextCorrelationId(); AeronCloseHelper.close(errorHandler, () -> archive.archiveProxy() .stopReplay(replaySessionId, correlationId, archive.controlSessionId())); } } state(State.CLOSED); } }</code><technical_language>This asyncRemoveDestination need a close helper</technical_language>

Target:
public void close() { final State state = this.state; if (State.CLOSED != state) { if (!archive.context().aeron().isClosed()) { if (State.MERGED != state) { subscription.asyncRemoveDestination(replayDestination); } if (isReplayActive && archive.archiveProxy().publication().isConnected()) { stopReplay(); } } state(State.CLOSED); } }
Source:
<code>public XDOM getXDOM() { if (!this.stack.isEmpty()) { throw new IllegalStateException("Unbalanced begin/end Block events, missing " + this.stack.size() + " calls to endBlockList()."); } <START> List<Block> blocks = endBlockList(); <END> if (!blocks.isEmpty() && blocks.get(0) instanceof XDOM) { return (XDOM) blocks.get(0); } else { return new XDOM(blocks); } }</code><technical_language>hmm this is effect endBlockList() calls this.stack.pop() , this.stack.isEmpty() is a result value</technical_language>

Target:
public XDOM getXDOM() { if (!this.stack.size()==1) { throw new IllegalStateException("Unbalanced begin/end Block events, missing " + this.stack.size() + " calls to endBlockList()."); } List<Block> blocks = endBlockList(); if (!blocks.isEmpty() && blocks.get(0) instanceof XDOM) { return (XDOM) blocks.get(0); } else { return new XDOM(blocks); } }
Source:
<code>public void testRenameSymref() throws IOException { ObjectId <START> id = <END> db.resolve("HEAD"); RefRename r = db.renameRef("HEAD", "KOPF"); assertEquals(IO_FAILURE, r.rename()); }</code><technical_language>unused</technical_language>

Target:
public void testRenameSymref() throws IOException { db.resolve("HEAD"); RefRename r = db.renameRef("HEAD", "KOPF"); assertEquals(IO_FAILURE, r.rename()); }
Source:
<code><START> public static Object charValue(Object obj) { <END> if (obj instanceof Character) { return obj; } if (obj instanceof Integer) { int value = (Integer) obj; return (char) value; } if (obj instanceof Long) { long value = (Long) obj; return (char) value; } if (obj instanceof Double) { double value = (Double) obj; return (char) value; } if (obj instanceof Float) { float value = (Float) obj; return (char) value; } if (obj instanceof String) { return ((String) obj).charAt(0); } throw new IllegalArgumentException("Expected a number or a string, but got: " + obj); }</code><technical_language>removing throws declarations</technical_language>

Target:
public static Object charValue(Object obj) throws IllegalArgumentException { if (obj instanceof Character) { return obj; } if (obj instanceof Integer) { int value = (Integer) obj; return (char) value; } if (obj instanceof Long) { long value = (Long) obj; return (char) value; } if (obj instanceof Double) { double value = (Double) obj; return (char) value; } if (obj instanceof Float) { float value = (Float) obj; return (char) value; } if (obj instanceof String) { return ((String) obj).charAt(0); } throw new IllegalArgumentException("Expected a number or a string, but got: " + obj); }
Source:
<code>private IStatus getStatus(IEvaluationResult evaluationResult) { Object result = evaluationResult.getValue(); <START> String defaultMessage = this.getDefaultMessage(result); String message = defaultMessage; <END> Diagnostic diagnostic = evaluationResult.getDiagnostic(); int statusCode = this.getStatusCodeFromDiagnostic(diagnostic); IStatus status = new Status(statusCode, Activator.PLUGIN_ID, message); if (Diagnostic.OK != diagnostic.getSeverity() && diagnostic.getChildren().size() > 0) { MultiStatus multiStatus = new MultiStatus(Activator.PLUGIN_ID, statusCode, message, null); List<Diagnostic> children = diagnostic.getChildren(); for (Diagnostic childDiagnostic : children) { int childStatusCode = this.getStatusCodeFromDiagnostic(childDiagnostic); String childMessage = childDiagnostic.getMessage(); IStatus childStatus = new Status(childStatusCode, Activator.PLUGIN_ID, childMessage); multiStatus.add(childStatus); } status = multiStatus; } return status; }</code><technical_language>replace String message = this.getDefaultMessage(result);</technical_language>

Target:
private IStatus getStatus(IEvaluationResult evaluationResult) { Object result = evaluationResult.getValue(); String message = this.getDefaultMessage(result); Diagnostic diagnostic = evaluationResult.getDiagnostic(); int statusCode = this.getStatusCodeFromDiagnostic(diagnostic); IStatus status = new Status(statusCode, InterpreterViewPlugin.PLUGIN_ID, message); if (Diagnostic.OK != diagnostic.getSeverity() && diagnostic.getChildren().size() > 0) { MultiStatus multiStatus = new MultiStatus(InterpreterViewPlugin.PLUGIN_ID, statusCode, message, null); List<Diagnostic> children = diagnostic.getChildren(); for (Diagnostic childDiagnostic : children) { int childStatusCode = this.getStatusCodeFromDiagnostic(childDiagnostic); String childMessage = childDiagnostic.getMessage(); IStatus childStatus = new Status(childStatusCode, InterpreterViewPlugin.PLUGIN_ID, childMessage); multiStatus.add(childStatus); } status = multiStatus; } return status; }
Source:
<code>public void conceptListHelper_shouldReturnListOfConceptsWithGivenNameInDescriptor() { List<Concept> helperList = OpenmrsUtil.conceptListHelper("name:YES|name:NO|name:DIED|set:25|set:26"); List<Concept> serviceList = new ArrayList<>(); List<Concept> aux; <START> Concept con; <END> ConceptService cs = Context.getConceptService(); serviceList.add(cs.getConceptByName("YES")); serviceList.add(cs.getConceptByName("NO")); serviceList.add(cs.getConceptByName("DIED")); con = cs.getConcept(25); aux = cs.getConceptsByConceptSet(con); serviceList.addAll(aux); con = cs.getConcept(26); aux = cs.getConceptsByConceptSet(con); serviceList.addAll(aux); assertTrue("List should be same size to be equal",helperList.size() == serviceList.size()); Set<Concept> serviceSet = new HashSet<>(serviceList); helperList.stream() .forEach(concept -> { serviceSet.remove(concept); }); assertTrue("The set should be empty" ,serviceSet.size() == 0); }</code><technical_language>case this one. More descriptive names needed</technical_language>

Target:
public void conceptListHelper_shouldReturnListOfConceptsWithGivenNameInDescriptor() { List<Concept> helperList = OpenmrsUtil.conceptListHelper("name:YES|name:NO|name:DIED|set:25|set:26"); List<Concept> serviceList = new ArrayList<>(); Concept concept_auxiliar; serviceList.add(cs.getConceptByName("YES")); serviceList.add(cs.getConceptByName("NO")); serviceList.add(cs.getConceptByName("DIED")); concept_auxiliar = cs.getConcept(25); serviceList.addAll(cs.getConceptsByConceptSet(concept_auxiliar)); concept_auxiliar = cs.getConcept(26); serviceList.addAll(cs.getConceptsByConceptSet(concept_auxiliar)); assertTrue("List should be same size to be equal",helperList.size() == serviceList.size()); Set<Concept> serviceSet = new HashSet<>(serviceList); helperList.stream() .forEach(concept -> { serviceSet.remove(concept); }); assertTrue("The set should be empty" ,serviceSet.isEmpty()); }
Source:
<code>public void calculatorReturnsNonMaximumForPriorityTable_thenProviderStillSelectsIt() { givenPriority(table("table1"), 1.0); givenPriority(table("table2"), 10_000.0); <START> whenGettingNextTableToSweepWithOverrides(ImmutableSweepPriorityOverrideConfig.builder() <END> .addPriorityTables(table("table1").getQualifiedName()) .build()); thenTableChosenIs(table("table1")); }</code><technical_language>Small style note: BDD-style tests I this as: givenPriority(table("table1"), 1.0); givenPriority(table("table2"), 10_000.0); givenPriorityOverride(table("table1")); whenGettingNextTableToSweep(); ... This test easier read (the state is in 'given' phase) if change overrides change givenPriorityOverride givenBlacklisted methods. essential change though</technical_language>

Target:
public void calculatorReturnsNonMaximumForPriorityTable_thenProviderStillSelectsIt() { givenPriority(table("table1"), 1.0); givenPriority(table("table2"), 10_000.0); givenPriorityOverride(table("table1")); whenGettingNextTableToSweep(); thenTableChosenIs(table("table1")); }
Source:
<code>public void addTableColumnReferences(AccessControl accessControl, Identity identity, Multimap<QualifiedObjectName, String> tableColumnMap) { AccessControlInfo accessControlInfo = new AccessControlInfo(accessControl, identity); <START> Map<QualifiedObjectName, Set<String>> references = tableColumnReferences.computeIfAbsent(accessControlInfo, (k) -> new LinkedHashMap<>()); <END> tableColumnMap.asMap() .forEach((key, value) -> references.computeIfAbsent(key, k -> new HashSet<>()).addAll(value)); }</code><technical_language>Nit: need for parens lambda parameter. Also, I replaced LinkedHashMap::new</technical_language>

Target:
public void addTableColumnReferences(AccessControl accessControl, Identity identity, Multimap<QualifiedObjectName, String> tableColumnMap) { AccessControlInfo accessControlInfo = new AccessControlInfo(accessControl, identity); Map<QualifiedObjectName, Set<String>> references = tableColumnReferences.computeIfAbsent(accessControlInfo, k -> new LinkedHashMap<>()); tableColumnMap.asMap() .forEach((key, value) -> references.computeIfAbsent(key, k -> new HashSet<>()).addAll(value)); }
Source:
<code>public Object evaluate(final Object knowledgeBase, Map<String, Object> requestData) { <START> logger.trace("evaluate {}", knowledgeBase, requestData); <END> if (!(knowledgeBase instanceof KieBase)) { throw new KiePMMLException(String.format("Expecting KieBase, received %s", knowledgeBase.getClass().getName())); } final PMML4Result toReturn = getPMML4Result(targetField); KiePMMLSessionUtils.Builder builder = KiePMMLSessionUtils.builder((InternalKnowledgeBase)knowledgeBase, name, toReturn) .withObjectsInSession(requestData, fieldTypeMap) .withOutputFieldsMap(outputFieldsMap); if (logger.isDebugEnabled()) { builder = builder.withAgendaEventListener(agendaEventListener); } final KiePMMLSessionUtils kiePMMLSessionUtils = builder.build(); kiePMMLSessionUtils.fireAllRules(); return toReturn; }</code><technical_language>please add isTraceEnabled check</technical_language>

Target:
public Object evaluate(final Object knowledgeBase, Map<String, Object> requestData) { logger.trace("evaluate {}", knowledgeBase, requestData); if (!(knowledgeBase instanceof KieBase)) { throw new KiePMMLException(String.format("Expecting KieBase, received %s", knowledgeBase.getClass().getName())); } final PMML4Result toReturn = getPMML4Result(targetField); KiePMMLSessionUtils.Builder builder = KiePMMLSessionUtils.builder((KieBase)knowledgeBase, name, toReturn) .withObjectsInSession(requestData, fieldTypeMap) .withOutputFieldsMap(outputFieldsMap); if (logger.isDebugEnabled()) { builder = builder.withAgendaEventListener(agendaEventListener); } final KiePMMLSessionUtils kiePMMLSessionUtils = builder.build(); kiePMMLSessionUtils.fireAllRules(); return toReturn; }
Source:
<code>public Variable(String name, VariableType variableType, int positionScore, char[] triggerChars, ImageDescriptor descriptor) { this.name = name; this.variableType = variableType; this.positionScore = positionScore; this.triggerChars = triggerChars; this.descriptor = descriptor; this.alreadyMatched = <START> false; <END> }</code><technical_language>Redundant initialization</technical_language>

Target:
public Variable(String name, VariableType variableType, int positionScore, char[] triggerChars, ImageDescriptor descriptor) { this.name = name; this.variableType = variableType; this.positionScore = positionScore; this.triggerChars = triggerChars; this.descriptor = descriptor; }
Source:
<code>public boolean loadUrl(final String url, final int timeout) { <START> browser.getShell().open(); <END> this.state = ReadyState.LOADING; browser.addProgressListener(readyStateListener); this.syncExec( () -> { browser.setUrl(url); }); boolean successful = waitForPageLoaded(timeout); browser.removeProgressListener(readyStateListener); return successful; }</code><technical_language>wondering if is call this a thread EDT ? If is syncCall line 82 is necessary</technical_language>

Target:
public boolean loadUrl(final String url, final int timeout) { syncExec(() -> browser.getShell().open()); state = ReadyState.LOADING; syncExec( () -> { browser.addProgressListener(readyStateListener); browser.setUrl(url); }); boolean successful = waitForPageLoaded(timeout); syncExec(() -> browser.removeProgressListener(readyStateListener)); return successful; }