auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> protected long[] sequentialTimestamps(int count, long firstValue) { <END> assert count > 0; long[] timestamps = new long[count]; timestamps[0] = firstValue; for (int i = 1; i < timestamps.length; ++i) { timestamps[i] = timestamps[0] + i; } return timestamps; }</code><technical_language>public</technical_language>

Target:
public long[] sequentialTimestamps(int count, long firstValue) { assert count > 0; long[] timestamps = new long[count]; timestamps[0] = firstValue; for (int i = 1; i < timestamps.length; ++i) { timestamps[i] = timestamps[0] + i; } return timestamps; }
Source:
<code>public void test() { JavaCheckVerifier.verify("src/test/files/checks/security/LDAPDeserializationCheck.java", new LDAPDeserializationCheck()); <START> JavaCheckVerifier.verifyNoIssueWithoutSemantic("src/test/files/checks/security/LDAPDeserializationCheck.java", new LDAPDeserializationCheck()); <END> }</code><technical_language>I required extending AbstractMethodDetection</technical_language>

Target:
public void test() { JavaCheckVerifier.verify("src/test/files/checks/security/LDAPDeserializationCheck.java", new LDAPDeserializationCheck()); }
Source:
<code>public static DataType projectRow(DataType dataType, int[][] indexPaths) { final List<RowField> updatedFields = new ArrayList<>(); final List<DataType> updatedChildren = new ArrayList<>(); Set<String> nameDomain = new HashSet<>(); int duplicateCount = 0; for (int[] indexPath : indexPaths) { DataType fieldType = dataType.getChildren().get(indexPath[0]); LogicalType fieldLogicalType = fieldType.getLogicalType(); StringBuilder builder = new StringBuilder(((RowType) dataType.getLogicalType()).getFieldNames().get(indexPath[0])); for (int index = 1; index < indexPath.length; index++) { Preconditions.checkArgument( hasRoot(fieldLogicalType, LogicalTypeRoot.ROW), "Row data type expected."); RowType rowtype = ((RowType) fieldLogicalType); builder.append("_").append(rowtype.getFieldNames().get(indexPath[index])); fieldLogicalType = rowtype.getFields().get(indexPath[index]).getType(); fieldType = fieldType.getChildren().get(indexPath[index]); } String path = builder.toString(); while (nameDomain.contains(path)) { <START> path = builder.append("$").append(duplicateCount++).toString(); <END> } updatedFields.add(new RowField(path, fieldLogicalType)); updatedChildren.add(fieldType); nameDomain.add(path); } return new FieldsDataType( new RowType(dataType.getLogicalType().isNullable(), updatedFields), dataType.getConversionClass(), updatedChildren); }</code><technical_language>nit: adding _ "$"</technical_language>

Target:
public static DataType projectRow(DataType dataType, int[][] indexPaths) { final List<RowField> updatedFields = new ArrayList<>(); final List<DataType> updatedChildren = new ArrayList<>(); Set<String> nameDomain = new HashSet<>(); int duplicateCount = 0; for (int[] indexPath : indexPaths) { DataType fieldType = dataType.getChildren().get(indexPath[0]); LogicalType fieldLogicalType = fieldType.getLogicalType(); StringBuilder builder = new StringBuilder(((RowType) dataType.getLogicalType()).getFieldNames().get(indexPath[0])); for (int index = 1; index < indexPath.length; index++) { Preconditions.checkArgument( hasRoot(fieldLogicalType, LogicalTypeRoot.ROW), "Row data type expected."); RowType rowtype = ((RowType) fieldLogicalType); builder.append("_").append(rowtype.getFieldNames().get(indexPath[index])); fieldLogicalType = rowtype.getFields().get(indexPath[index]).getType(); fieldType = fieldType.getChildren().get(indexPath[index]); } String path = builder.toString(); while (nameDomain.contains(path)) { path = builder.append("_$").append(duplicateCount++).toString(); } updatedFields.add(new RowField(path, fieldLogicalType)); updatedChildren.add(fieldType); nameDomain.add(path); } return new FieldsDataType( new RowType(dataType.getLogicalType().isNullable(), updatedFields), dataType.getConversionClass(), updatedChildren); }
Source:
<code>public final static String generateHash(String data) throws Exception { String hashedData = data; try { <START> byte[] bytes = data.getBytes(StandardCharsets.US_ASCII); <END> MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(bytes, 0, bytes.length); byte[] digestBytes = digest.digest(); hashedData = Base64.encodeToString(digestBytes, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); } catch (Exception e) { throw e; } return hashedData; }</code><technical_language>Unfortunately, this API introduced in API level 19. SDK supports platforms 19. revert this "US-ASCII" string? reviewing Base64 encoding change,</technical_language>

Target:
public final static String generateHash(String data) throws Exception { String hashedData = data; try { byte[] bytes = data.getBytes("US-ASCII"); MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(bytes, 0, bytes.length); byte[] digestBytes = digest.digest(); hashedData = Base64.encodeToString(digestBytes, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); } catch (Exception e) { throw e; } return hashedData; }
Source:
<code>public static void addDiskImage(DiskImage image) { addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getId(), <START> image.getstorage_ids().get(0))); <END> }</code><technical_language>getStorageId method here</technical_language>

Target:
public static void addDiskImage(DiskImage image) { addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getId(), getStorageDomainId(image))); }
Source:
<code>public boolean isIgnoreFolder(boolean withDeleted, Project project, Folder folder) { boolean ignoreFolder = super.isIgnoreFolder(withDeleted, project, folder); if (ignoreFolder) { return true; } boolean isBusinessRules = <START> folder.getLabel().equals(EResourceConstant.SYSTEM_INDICATORS_BUSINESS_RULES.getName()); <END> boolean isPhoneNumber = folder.getLabel().equals(EResourceConstant.SYSTEM_INDICATORS_PHONENUMBER_STATISTICS.getName()); if (isBusinessRules || isPhoneNumber) { return true; } return false; }</code><technical_language>is better: EResourceConstant.SYSTEM_INDICATORS_BUSINESS_RULES.getName(). equals(folder.getLabel())</technical_language>

Target:
public boolean isIgnoreFolder(boolean withDeleted, Project project, Folder folder) { boolean ignoreFolder = super.isIgnoreFolder(withDeleted, project, folder); if (ignoreFolder) { return true; } boolean isBusinessRules = EResourceConstant.SYSTEM_INDICATORS_BUSINESS_RULES.getName().equals(folder.getLabel()); boolean isPhoneNumber = EResourceConstant.SYSTEM_INDICATORS_PHONENUMBER_STATISTICS.getName().equals(folder.getLabel()); if (isBusinessRules || isPhoneNumber) { return true; } return false; }
Source:
<code>public void getCasesTest() { TestCasesConfig config = mock(TestCasesConfig.class); expect(config.getTestCasesDirectory()).andReturn(new File("src/test/resources/cases/ok")); replay(config); <START> Assert.assertEquals(4, new TestCasesProvider(config).getCases().size()); <END> }</code><technical_language>verify mocks</technical_language>

Target:
public void getCasesTest() { TestCasesConfig config = mock(TestCasesConfig.class); expect(config.getTestCasesDirectory()).andReturn(new File("src/test/resources/cases/ok")); replay(config); Assert.assertEquals(4, new TestCasesProvider(config).getCases().size()); verify(config); }
Source:
<code>public void testTextWrapBoundariesUpdatesOnRefresh() { tested.refresh(); <START> verify(textDecorator).setTextBoundaries(any()); <END> }</code><technical_language>verify text boundaries correct? Verifying simply set boundaries text decorator is ascertain values set</technical_language>

Target:
public void testTextWrapBoundariesUpdatesOnRefresh() { tested.refresh(); verify(textDecorator).setTextBoundaries(PATH.getBoundingBox()); }
Source:
<code>public void testConsumedResultPartitionsProducers() { TestingInputsLocationsRetriever originalLocationRetriever = getOriginalLocationRetriever(); InputsLocationsRetriever availableInputsLocationsRetriever = new AvailableInputsLocationsRetriever(originalLocationRetriever); Collection<Collection<ExecutionVertexID>> producers = availableInputsLocationsRetriever.getConsumedResultPartitionsProducers(EV2); assertThat(producers.size(), is(1)); Collection<ExecutionVertexID> resultProducers = producers.iterator().next(); <START> assertThat(resultProducers.size(), is(1)); assertThat(resultProducers.iterator().next(), is(EV1)); <END> }</code><technical_language>2 asserts replaced assertThat(resultProducers, contains(EV1))</technical_language>

Target:
public void testConsumedResultPartitionsProducers() { TestingInputsLocationsRetriever originalLocationRetriever = getOriginalLocationRetriever(); InputsLocationsRetriever availableInputsLocationsRetriever = new AvailableInputsLocationsRetriever(originalLocationRetriever); Collection<Collection<ExecutionVertexID>> producers = availableInputsLocationsRetriever.getConsumedResultPartitionsProducers(EV2); assertThat(producers.size(), is(1)); Collection<ExecutionVertexID> resultProducers = producers.iterator().next(); assertThat(resultProducers, contains(EV1)); }
Source:
<code>public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { log.warn("no load balancer"); return null; } Server server = null; int count = 0; while (server == null && count++ < 10) { <START> List<Server> upList = lb.getServerList(availableOnlyServers); <END> List<Server> allList = lb.getServerList(allServers); int upCount = upList.size(); int serverCount = allList.size(); if ((upCount == 0) || (serverCount == 0)) { log.warn("No up servers available from load balancer: " + lb); return null; } server = allList.get(incrementAndGetModulo(serverCount)); if (server == null) { Thread.yield(); continue; } if (server.isAlive() && (server.isReadyToServe())) { return (server); } server = null; } if (count >= 10) { log.warn("No available alive servers after 10 tries from load balancer: " + lb); } return server; }</code><technical_language>A 'cleaner' more readable API create new methods in ILoadBalancer. getUpServerList() getServerList(). deprecated getServerList(boolean)</technical_language>

Target:
public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { log.warn("no load balancer"); return null; } Server server = null; int count = 0; while (server == null && count++ < 10) { List<Server> reachableServers = lb.getReachableServers(); List<Server> allServers = lb.getAllServers(); int upCount = reachableServers.size(); int serverCount = allServers.size(); if ((upCount == 0) || (serverCount == 0)) { log.warn("No up servers available from load balancer: " + lb); return null; } int nextServerIndex = incrementAndGetModulo(serverCount); server = allServers.get(nextServerIndex); if (server == null) { Thread.yield(); continue; } if (server.isAlive() && (server.isReadyToServe())) { return (server); } server = null; } if (count >= 10) { log.warn("No available alive servers after 10 tries from load balancer: " + lb); } return server; }
Source:
<code>private static byte[] transform(final InputStream body) throws IOException { final ByteArrayOutputStream result = new ByteArrayOutputStream(); final JsonReader reader = Json.createReader(body); final Map<String, ?> props = Collections.singletonMap( JsonGenerator.PRETTY_PRINTING, true ); <START> final JsonWriterFactory factory = Json.createWriterFactory(props); <END> final JsonWriter writer = factory.createWriter(result); try { final JsonObject obj = reader.readObject(); try { writer.writeObject(obj); } finally { writer.close(); } } catch (final JsonException ex) { throw new IOException(ex); } finally { reader.close(); } return result.toByteArray(); }</code><technical_language>@ekondrashev inline this variable</technical_language>

Target:
private static byte[] transform(final InputStream body) throws IOException { final ByteArrayOutputStream res = new ByteArrayOutputStream(); final JsonReader rdr = Json.createReader(body); try { final JsonObject obj = rdr.readObject(); final JsonWriter wrt = Json.createWriterFactory( Collections.singletonMap( JsonGenerator.PRETTY_PRINTING, true ) ).createWriter(res); try { wrt.writeObject(obj); } finally { wrt.close(); } } catch (final JsonException ex) { throw new IOException(ex); } finally { rdr.close(); } return res.toByteArray(); }
Source:
<code>public Map<String, ValidationReport> uploadProject(final Project project, final File archive, final String fileType, final User uploader, final Props additionalProps) throws ProjectManagerException, ExecutorManagerException { log.info("Uploading files to " + project.getName()); final Map<String, ValidationReport> reports; File folder = null; final FlowLoader loader; try { folder = unzipProject(archive, fileType); File startupDependencies = getStartupDependenciesFile(folder); reports = startupDependencies.exists() ? this.archiveUnthinner.validateThinProject(project, folder, startupDependencies, additionalProps) : this.validatorUtils.validateProject(project, folder, additionalProps); if (reports.values().stream().anyMatch(r -> !r.getModifiedFiles().isEmpty() || !r.getRemovedFiles().isEmpty())) { updateProjectZip(archive, folder); } loader = this.flowLoaderFactory.createFlowLoader(folder); reports.put(DIRECTORY_FLOW_REPORT_KEY, loader.loadProjectFlow(project, folder)); if (!isReportStatusValid(reports, project)) { FlowLoaderUtils.cleanUpDir(folder); return reports; } File startupDependenciesOrNull = startupDependencies.exists() ? startupDependencies : null; persistProject(project, loader, archive, folder, startupDependenciesOrNull, uploader); <START> if (startupDependencies.exists()) { <END> commonMetrics.markUploadThinProject(); } else { commonMetrics.markUploadFatProject(); } } finally { FlowLoaderUtils.cleanUpDir(folder); } cleanUpProjectOldInstallations(project); return reports; }</code><technical_language>nitpick : null check startupDependenciesOrNull</technical_language>

Target:
public Map<String, ValidationReport> uploadProject(final Project project, final File archive, final String fileType, final User uploader, final Props additionalProps) throws ProjectManagerException, ExecutorManagerException { log.info("Uploading files to " + project.getName()); final Map<String, ValidationReport> reports; File folder = null; final FlowLoader loader; try { folder = unzipProject(archive, fileType); final File startupDependencies = getStartupDependenciesFile(folder); final boolean isThinProject = startupDependencies.exists(); reports = isThinProject ? this.archiveUnthinner.validateThinProject(project, folder, startupDependencies, additionalProps) : this.validatorUtils.validateProject(project, folder, additionalProps); if (reports.values().stream().anyMatch(r -> !r.getModifiedFiles().isEmpty() || !r.getRemovedFiles().isEmpty())) { updateProjectZip(archive, folder); } loader = this.flowLoaderFactory.createFlowLoader(folder); reports.put(DIRECTORY_FLOW_REPORT_KEY, loader.loadProjectFlow(project, folder)); if (!isReportStatusValid(reports, project)) { FlowLoaderUtils.cleanUpDir(folder); return reports; } final File startupDependenciesOrNull = isThinProject ? startupDependencies : null; persistProject(project, loader, archive, folder, startupDependenciesOrNull, uploader); if (isThinProject) { commonMetrics.markUploadThinProject(); } else { commonMetrics.markUploadFatProject(); } } finally { FlowLoaderUtils.cleanUpDir(folder); } cleanUpProjectOldInstallations(project); return reports; }
Source:
<code><START> public Configuration load(File file) throws ConfigurationLoadingException { <END> LOG.debug("Start initializing loader with file: {}", file.getAbsolutePath()); Properties properties = new Properties(); InputStream is = null; try { is = new FileInputStream(file); properties.load(is); is.close(); LOG.debug("Loader successfully initialized with file: {}", file.getAbsolutePath()); } catch (IOException e) { LOG.error("Can not load properties: {}", e.getMessage()); throw new ConfigurationLoadingException(e.getMessage()); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { LOG.error("Can not close input stream for file {}: {}", file.getAbsolutePath(), e.getMessage()); } } return new ConfigurationImpl(properties); }</code><technical_language>this method static right ? , do ConfigurationLoaderImpl.load(); , name of class better</technical_language>

Target:
public Configuration load(File file) throws ConfigurationLoadingException { LOG.debug("Start initializing loader with file: {}", file.getAbsolutePath()); Properties properties = new Properties(); try { InputStream is = new FileInputStream(file); try { properties.load(is); LOG.debug("Loader successfully initialized with file: {}", file.getAbsolutePath()); } finally { Closeables.closeQuietly(is); } } catch (IOException e) { LOG.error("Cannot load properties", e); throw new ConfigurationLoadingException("Cannot load properties: " + e.getMessage()); } return new ConfigurationImpl(properties); }
Source:
<code>public final void setUpMuleContext() throws Exception { if (!logConfigured) { configureLoggingForTest(getClass()); logConfigured = true; } workingDirectory.create(); String workingDirectoryOldValue = System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectory.getRoot().getAbsolutePath()); try { doSetUpBeforeMuleContextCreation(); muleContext = createMuleContext(); if (doTestClassInjection()) { muleContext.getInjector().inject(this); } if (isStartContext() && muleContext != null && !muleContext.isStarted()) { startMuleContext(); } doSetUp(); } catch (LifecycleException e) { if (LIFECYCLE_EXCEPTION_COMPONENT_FIELD != null) { <START> LIFECYCLE_EXCEPTION_COMPONENT_FIELD.set(e, null); <END> } } finally { if (workingDirectoryOldValue != null) { System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectoryOldValue); } else { System.clearProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY); } } }</code><technical_language>I understand change PR title is wrong. This cleanup in case tests fails, prevent failing. fail repetetadly in place</technical_language>

Target:
public final void setUpMuleContext() throws Exception { if (!logConfigured) { configureLoggingForTest(getClass()); logConfigured = true; } workingDirectory.create(); String workingDirectoryOldValue = System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectory.getRoot().getAbsolutePath()); try { doSetUpBeforeMuleContextCreation(); muleContext = createMuleContext(); if (doTestClassInjection()) { muleContext.getInjector().inject(this); } if (isStartContext() && muleContext != null && !muleContext.isStarted()) { startMuleContext(); } doSetUp(); } catch (LifecycleException e) { if (LIFECYCLE_EXCEPTION_COMPONENT_FIELD != null) { LIFECYCLE_EXCEPTION_COMPONENT_FIELD.set(e, null); } throw e; } finally { if (workingDirectoryOldValue != null) { System.setProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY, workingDirectoryOldValue); } else { System.clearProperty(WORKING_DIRECTORY_SYSTEM_PROPERTY_KEY); } } }
Source:
<code>public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_travel_guide_activity, menu); MenuItem searchItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { <START> if (query != null) <END> query = query.trim().toLowerCase(); if (query == null || query.trim().equals("")) query = "Any"; city = query; Log.d("CITY", query); setContentFragment(TripPlanListFragment.newInstance(city, group, season)); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; }</code><technical_language>this method: <LINK_0></technical_language>

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_travel_guide_activity, menu); MenuItem searchItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (TextUtils.isEmpty(query)) query = "Any"; city = query.trim(); setContentFragment(TripPlanListFragment.newInstance(city, group, season)); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; }
Source:
<code>public boolean contains(Object o) { for (SoftReference<T> ref : buffer) { T item = getItem(ref); <START> if (item != null) { <END> return true; } } return false; }</code><technical_language>this point item is == null</technical_language>

Target:
public boolean contains(Object o) { checkQueue(); for (SoftReference<T> ref : buffer) { T item = getItem(ref); if (item.equals(o)) { return true; } } return false; }
Source:
<code>public DataSource lookup(SQLDataSetDef def) throws Exception { <START> InitialContext ctx = new InitialContext(); <END> return (DataSource) ctx.lookup(def.getDataSource()); }</code><technical_language>Consider instantiating InitialContext once, for example in PostConstruct</technical_language>

Target:
public DataSource lookup(SQLDataSetDef def) throws Exception { return InitialContext.doLookup(def.getDataSource()); }
Source:
<code>public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { if (String.class.equals(type)) { return Optional.empty(); } return Optional.of((rs, i, ctx) -> { ColumnMapper<String> jsonStringMapper = JdbiOptionals.findFirstPresent( () -> ctx.findColumnMapperFor(QualifiedType.of(String.class).with(Json.class)).map(JsonColumnMapperFactory::asStringMapper), () -> ctx.findColumnMapperFor(String.class)) <START> .orElseThrow(() -> new UnableToProduceResultException(JSON_NOT_RETRIEVABLE, ctx)); <END> String json = jsonStringMapper.map(rs, i, ctx); return json == null ? null : ctx.getConfig(JsonConfig.class).getJsonMapper().fromJson(type, json, ctx); }); }</code><technical_language>Instead of a fallback String mapper, register a default @Json String mapper in jdbi3-json plugin</technical_language>

Target:
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { if (String.class.equals(type)) { return Optional.empty(); } return Optional.of((rs, i, ctx) -> { ColumnMapper<String> jsonStringMapper = JdbiOptionals.findFirstPresent( () -> ctx.findColumnMapperFor(QualifiedType.of(String.class).with(Json.class)), () -> ctx.findColumnMapperFor(String.class)) .orElseThrow(() -> new UnableToProduceResultException(JSON_NOT_RETRIEVABLE, ctx)); String json = jsonStringMapper.map(rs, i, ctx); return json == null ? null : ctx.getConfig(JsonConfig.class).getJsonMapper().fromJson(type, json, ctx); }); }
Source:
<code>public void testPerformanceSpelVersusInvocable() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("messageAndHeader", Message.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); Message<String> message = MessageBuilder.withPayload("foo").setHeader("number", 42).build(); StopWatch stopWatch = new StopWatch("SpEL vs Invocable Performance"); stopWatch.start("SpEL"); int count = 10_000; for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); processor = new MethodInvokingMessageProcessor(service, method); stopWatch.start("Invocable"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); SpelParserConfiguration config = TestUtils.getPropertyValue(processor, "delegate.handlerMethod.EXPRESSION_PARSER.configuration", SpelParserConfiguration.class); <START> new DirectFieldAccessor(config).setPropertyValue("compilerMode", SpelCompilerMode.IMMEDIATE); <END> processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); stopWatch.start("Compiled SpEL"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); System.clearProperty("spring.expression.compiler.mode"); logger.warn(stopWatch.prettyPrint()); }</code><technical_language>OK. Merging hope @aclement relax exitTypeDescriptor for null type. I debug locally a problem in ArgumentResolvers for Message parameter</technical_language>

Target:
public void testPerformanceSpelVersusInvocable() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); Message<Integer> message = MessageBuilder.withPayload(42).build(); StopWatch stopWatch = new StopWatch("SpEL vs Invocable Performance"); stopWatch.start("SpEL"); int count = 20_000; for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); processor = new MethodInvokingMessageProcessor(service, method); stopWatch.start("Invocable"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); SpelParserConfiguration config = TestUtils.getPropertyValue(processor, "delegate.handlerMethod.EXPRESSION_PARSER.configuration", SpelParserConfiguration.class); new DirectFieldAccessor(config).setPropertyValue("compilerMode", SpelCompilerMode.IMMEDIATE); processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); stopWatch.start("Compiled SpEL"); for (int i = 0; i < count; i++) { processor.processMessage(message); } stopWatch.stop(); logger.warn(stopWatch.prettyPrint()); }
Source:
<code>protected void executeCommand() { VmBackup vmBackup = getParameters().getVmBackup(); vmBackup.setDisks(getDisks()); log.info("Creating VmBackup entity for VM '{}'", vmBackup.getVmId()); Guid vmBackupId = createVmBackup(); log.info("Created VmBackup entity '{}'", vmBackupId); if (vmBackup.getFromCheckpointId() != null) { log.info("Redefine previous VM checkpoints for VM '{}'", vmBackup.getVmId()); if (!redefineVmCheckpoints()) { <START> <END> setCommandStatus(CommandStatus.FAILED); return; } log.info("Successfully redefined previous VM checkpoints for VM '{}'", vmBackup.getVmId()); } if (FeatureSupported.isIncrementalBackupSupported(getCluster().getCompatibilityVersion()) && !isBackupContainsRawDisksOnly()) { log.info("Creating VmCheckpoint entity for VM '{}'", vmBackup.getVmId()); Guid vmCheckpointId = createVmCheckpoint(); log.info("Created VmCheckpoint entity '{}'", vmCheckpointId); vmBackup.setToCheckpointId(vmCheckpointId); TransactionSupport.executeInNewTransaction(() -> { vmBackupDao.update(vmBackup); return null; }); } else { log.info("Skip checkpoint creation for VM '{}'", vmBackup.getVmId()); } updateVmBackupPhase(VmBackupPhase.STARTING); persistCommandIfNeeded(); setActionReturnValue(vmBackupId); setSucceeded(true); }</code><technical_language>extra space</technical_language>

Target:
protected void executeCommand() { VmBackup vmBackup = getParameters().getVmBackup(); vmBackup.setDisks(getDisks()); log.info("Creating VmBackup entity for VM '{}'", vmBackup.getVmId()); Guid vmBackupId = createVmBackup(); log.info("Created VmBackup entity '{}'", vmBackupId); if (vmBackup.getFromCheckpointId() != null) { log.info("Redefine previous VM checkpoints for VM '{}'", vmBackup.getVmId()); if (!redefineVmCheckpoints()) { setCommandStatus(CommandStatus.FAILED); return; } log.info("Successfully redefined previous VM checkpoints for VM '{}'", vmBackup.getVmId()); } if (FeatureSupported.isIncrementalBackupSupported(getCluster().getCompatibilityVersion()) && !isBackupContainsRawDisksOnly()) { log.info("Creating VmCheckpoint entity for VM '{}'", vmBackup.getVmId()); Guid vmCheckpointId = createVmCheckpoint(); log.info("Created VmCheckpoint entity '{}'", vmCheckpointId); getParameters().setToCheckpointId(vmCheckpointId); } else { log.info("Skip checkpoint creation for VM '{}'", vmBackup.getVmId()); } updateVmBackupPhase(VmBackupPhase.STARTING); persistCommandIfNeeded(); setActionReturnValue(vmBackupId); setSucceeded(true); }
Source:
<code>public void testPodServiceAccountName() { <START> assertEquals(SERVICE_ACCOUNT_NAME, this.resultPod.getSpec().getServiceAccountName()); <END> }</code><technical_language>suggestion assertThat(SERVICE_ACCOUNT_NAME, is(this.resultPod.getSpec().getServiceAccountName())) In Flink, prefer assertThat for assertion</technical_language>

Target:
public void testPodServiceAccountName() { assertThat(this.resultPod.getSpec().getServiceAccountName(), is(SERVICE_ACCOUNT_NAME)); }
Source:
<code>private void reload(final Reload<T> message) { final Optional<String> eTag = message.getETag(); final CachedJob<T> cachedJob; <START> _periodicMetrics.recordCounter("job_executor_actor_reloads", 1); <END> try { cachedJob = initializeOrEnsureRefMatch(unsafeJobRefCast(message.getJobRef())); if (eTag.isPresent()) { cachedJob.reloadIfOutdated(_injector, eTag.get()); } else { cachedJob.reload(_injector); } } catch (final NoSuchElementException error) { LOGGER.warn() .setMessage("tried to reload job, but job no longer exists in repository") .addData("ref", message.getJobRef()) .log(); killSelf(); return; } getSelf().tell(Tick.INSTANCE, getSelf()); }</code><technical_language>No, fine. remember changing metric names, definitions removing is effectively changing "operational interface" of service. Graphs, alerts runbooks depend these. Metrics clear intention, naming obvious meaning operators (the hallmarks of a good "interface"). suggesting this meet bar, figured point ask. Leaving is fine</technical_language>

Target:
private void reload(final Reload<T> message) { final Optional<String> eTag = message.getETag(); final CachedJob<T> cachedJob; _periodicMetrics.recordCounter("job_executor_actor_reloads", 1); try { cachedJob = initializeOrEnsureRefMatch(unsafeJobRefCast(message.getJobRef())); if (eTag.isPresent()) { cachedJob.reloadIfOutdated(_injector, eTag.get()); } else { cachedJob.reload(_injector); } } catch (final NoSuchJobException error) { LOGGER.warn() .setMessage("tried to reload job, but job no longer exists in repository") .addData("ref", message.getJobRef()) .log(); killSelf(); return; } timers().startPeriodicTimer(PERIODIC_TICK_TIMER_NAME, Tick.INSTANCE, TICK_INTERVAL); getSelf().tell(Tick.INSTANCE, getSelf()); }
Source:
<code>protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + BUFFER_MESSAGES_TO_REMOVE); removedMessage.stream().forEach(receivedMessage -> { <START> System.out.println("Removed Message sequence : " + receivedMessage.getSequenceNumber()); <END> }); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } if (messagesDeferred.get().size() > 0) { try { List<Long> listOfDeferredMessages = messagesDeferred.get(); for (Long seqNumber : listOfDeferredMessages) { ServiceBusReceivedMessage deferredMessages = receiver.receiveDeferredMessage(seqNumber); receiver.complete(deferredMessages); } } catch (Exception e) { logger.warning("Error occurred when draining deferred messages Entity : " + receiver.getEntityPath(), e); } messagesDeferred.set(new ArrayList<>()); } dispose(receiver, sender, receiveAndDeleteReceiver); }</code><technical_language>logger</technical_language>

Target:
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + BUFFER_MESSAGES_TO_REMOVE); removedMessage.stream().forEach(receivedMessage -> { logger.info("Removed Message Seq: ", receivedMessage.getSequenceNumber()); }); } catch (Exception e) { logger.warning("Error occurred when draining queue.", e); } } if (messagesDeferred.get().size() > 0) { try { List<Long> listOfDeferredMessages = messagesDeferred.get(); for (Long seqNumber : listOfDeferredMessages) { ServiceBusReceivedMessage deferredMessages = receiver.receiveDeferredMessage(seqNumber); receiver.complete(deferredMessages); } } catch (Exception e) { logger.warning("Error occurred when draining deferred messages Entity: ", receiver.getEntityPath(), e); } } dispose(receiver, sender, receiveAndDeleteReceiver); }
Source:
<code>public boolean checkout() throws IOException { toBeDeleted.clear(); if (headCommitTree != null) preScanTwoTrees(); else prescanOneTree(); if (!conflicts.isEmpty()) { if (failOnConflict) { dc.unlock(); throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()])); } else cleanUpConflicts(); } builder.finish(); File file=null; String last = ""; for (int i = removed.size() - 1; i >= 0; i--) { String r = removed.get(i); file = new File(repo.getWorkTree(), r); if (!file.delete() && file.exists()) toBeDeleted.add(r); else { if (!isSamePrefix(r, last)) removeEmptyParents(file); last = r; } } if (file != null) removeEmptyParents(file); for (String path : updated.keySet()) { file = new File(repo.getWorkTree(), path); <START> FileUtils.mkdirs(file.getParentFile(), true); <END> file.createNewFile(); DirCacheEntry entry = dc.getEntry(path); checkoutEntry(repo, file, entry); } if (!builder.commit()) { dc.unlock(); throw new IndexWriteException(); } return toBeDeleted.size() == 0; }</code><technical_language>I completely that. I intentionally checked return code mkdirs. If mkdirs fails a directory is created subsequent createNewFile fail. detect error situation want spend extra stats() check for file-existance file-type is done in FileUtils</technical_language>

Target:
public boolean checkout() throws IOException { toBeDeleted.clear(); if (headCommitTree != null) preScanTwoTrees(); else prescanOneTree(); if (!conflicts.isEmpty()) { if (failOnConflict) { dc.unlock(); throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()])); } else cleanUpConflicts(); } builder.finish(); File file=null; String last = ""; for (int i = removed.size() - 1; i >= 0; i--) { String r = removed.get(i); file = new File(repo.getWorkTree(), r); if (!file.delete() && file.exists()) toBeDeleted.add(r); else { if (!isSamePrefix(r, last)) removeEmptyParents(file); last = r; } } if (file != null) removeEmptyParents(file); for (String path : updated.keySet()) { file = new File(repo.getWorkTree(), path); if (!file.getParentFile().mkdirs()) { } file.createNewFile(); DirCacheEntry entry = dc.getEntry(path); checkoutEntry(repo, file, entry); } if (!builder.commit()) { dc.unlock(); throw new IndexWriteException(); } return toBeDeleted.size() == 0; }
Source:
<code>private void insertIntoChannel() { this.manager.channel().config().setAutoRead(false); <START> this.manager.channel().pipeline().addBefore("packet_handler", "fml:packet_handler", this); <END> ChannelPipeline cp = this.manager.channel().pipeline().addBefore("packet_handler", "fml:packet_handler", this); cp.context(this).executor().execute(() -> { if (this.state != null) { FMLLog.log.info("Opening channel which already seems to have a state set. This is a vanilla connection. Handshake handler will stop now"); this.manager.channel().config().setAutoRead(true); return; } FMLLog.log.trace("Handshake channel activating"); this.state = ConnectionState.OPENING; this.handshakeChannel.pipeline().fireUserEventTriggered(this); this.manager.channel().config().setAutoRead(true); }); }</code><technical_language>This is called twice, issue</technical_language>

Target:
private void insertIntoChannel() { this.manager.channel().config().setAutoRead(false); this.manager.channel().pipeline().addBefore("packet_handler", "fml:packet_handler", this); if (this.state != null) { FMLLog.log.info("Opening channel which already seems to have a state set. This is a vanilla connection. Handshake handler will stop now"); this.manager.channel().config().setAutoRead(true); return; } FMLLog.log.trace("Handshake channel activating"); this.state = ConnectionState.OPENING; this.handshakeChannel.pipeline().fireUserEventTriggered(this); this.manager.channel().config().setAutoRead(true); }
Source:
<code>public ActionsCategory handleMultipleNodes(ActionsCategory category, ActionsManager manager, List<Element> elements) { final List<Classifier> classifiers = new ArrayList<Classifier>(); final List<InstanceSpecification> instances = new ArrayList<InstanceSpecification>(); final List<Element> validatableElements = new ArrayList<Element>(); boolean hasUneditable = false; for (Element element : elements) { if (element != null) { if (element instanceof Classifier) { classifiers.add((Classifier) element); validatableElements.add(element); } else if (element instanceof InstanceSpecification) { instances.add((InstanceSpecification) element); validatableElements.add(element); } if (!hasUneditable && !element.isEditable()) { hasUneditable = true; } } } if (validatableElements.isEmpty()) { return null; } validateAction = new ValidateAction(validatableElements); category.addAction(validateAction); <START> if (!classifiers.isEmpty()) { <END> } if (!instances.isEmpty()) { instance2BSTAction = new Instance2BSTAction(instances); } return category; }</code><technical_language>Remove unused loop</technical_language>

Target:
public ActionsCategory handleMultipleNodes(ActionsCategory category, ActionsManager manager, List<Element> elements) { final List<Classifier> classifiers = new ArrayList<Classifier>(); final List<InstanceSpecification> instances = new ArrayList<InstanceSpecification>(); final List<Element> validatableElements = new ArrayList<Element>(); boolean hasUneditable = false; for (Element element : elements) { if (element != null) { if (element instanceof Classifier) { classifiers.add((Classifier) element); validatableElements.add(element); } else if (element instanceof InstanceSpecification) { instances.add((InstanceSpecification) element); validatableElements.add(element); } if (!hasUneditable && !element.isEditable()) { hasUneditable = true; } } } if (validatableElements.isEmpty()) { return null; } validateAction = new ValidateAction(validatableElements); category.addAction(validateAction); if (!instances.isEmpty()) { instance2BSTAction = new Instance2BSTAction(instances); } return category; }
Source:
<code>public void dropContentsOfInventory(DoDestroyEvent event, EntityRef entity) { Vector3f position = entity.getComponent(LocationComponent.class).getWorldPosition(); int slotCount = inventoryManager.getNumSlots(entity); for (int i=0; i<slotCount; i++) { EntityRef itemInSlot = inventoryManager.getItemInSlot(entity, 0); if (itemInSlot.exists()) { inventoryManager.removeItem(entity, itemInSlot); <START> pickupBuilder.createPickupFor(itemInSlot, position, 60); <END> } } }</code><technical_language>createPickupFor do 1 item a time. If want stack dropped, repeat this for stack count, monkey pickup entity. (I repetition method). Also, do need do ImpulseEvent</technical_language>

Target:
public void dropContentsOfInventory(DoDestroyEvent event, EntityRef entity) { Vector3f position = entity.getComponent(LocationComponent.class).getWorldPosition(); FastRandom random = new FastRandom(); int slotCount = inventoryManager.getNumSlots(entity); for (int i = 0; i < slotCount; i++) { EntityRef itemInSlot = inventoryManager.getItemInSlot(entity, i); if (itemInSlot.exists()) { EntityRef pickup = pickupBuilder.createPickupFor(itemInSlot, position, 60, true); pickup.send(new ImpulseEvent(random.nextVector3f(30.0f))); } } }
Source:
<code>public Response getConfiguration( @PathParam("serviceId") @ApiParam(value = "service ID", required = true) String serviceId) { try { Configuration configuration = configurationService.get(serviceId); return configuration != null ? Response.ok(configuration.getProperties()).build() : Response.ok(Collections.emptyMap()).build(); } catch (IOException ex) { <START> logger.error("Cannot get configuration for service {}: {}", serviceId, ex.getMessage(), ex); <END> return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }</code><technical_language>again, ex is logged drop ex.getMessage() placeholder here</technical_language>

Target:
public Response getConfiguration( @PathParam("serviceId") @ApiParam(value = "service ID", required = true) String serviceId) { try { Configuration configuration = configurationService.get(serviceId); return configuration != null ? Response.ok(configuration.getProperties()).build() : Response.ok(Collections.emptyMap()).build(); } catch (IOException ex) { logger.error("Cannot get configuration for service {}: ", serviceId, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }
Source:
<code>private AuthenticationRequest getAuthenticationRequest(final String authority, final String resource, final String clientId, final boolean isExtendedLifetimeEnabled) { final AuthenticationRequest authRequest = new AuthenticationRequest(authority, resource, clientId, isExtendedLifetimeEnabled); <START> return authRequest; <END> }</code><technical_language>a warning collapsing 2 lines? #Closed</technical_language>

Target:
private AuthenticationRequest getAuthenticationRequest(final String authority, final String resource, final String clientId, final boolean isExtendedLifetimeEnabled) { return new AuthenticationRequest(authority, resource, clientId, isExtendedLifetimeEnabled); }
Source:
<code>public void onPlayerSlotChange(final PlayerItemHeldEvent event) { final Player player = event.getPlayer(); final int slot = event.getNewSlot() + 1; GeneralMethods.displayMovePreview(player, slot); <START> if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Water.WaterArms.DisplayBoundMsg")) { <END> final WaterArms waterArms = CoreAbility.getAbility(player, WaterArms.class); if (waterArms != null) { waterArms.displayBoundMsg(event.getNewSlot() + 1); return; } } }</code><technical_language>this, instead create a nested if statement for waterarms logic. In addition move [L1586](<LINK_0> if statement config option for bending preview something</technical_language>

Target:
public void onPlayerSlotChange(final PlayerItemHeldEvent event) { final Player player = event.getPlayer(); final int slot = event.getNewSlot() + 1; if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingPreview")) { GeneralMethods.displayMovePreview(player, slot); } if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Water.WaterArms.DisplayBoundMsg")) { final WaterArms waterArms = CoreAbility.getAbility(player, WaterArms.class); if (waterArms != null) { waterArms.displayBoundMsg(event.getNewSlot() + 1); return; } } }
Source:
<code>public void connect() throws ZkInterruptedException { boolean isConnected = zkClient.waitUntilConnected(connectionTimeoutMs, TimeUnit.MILLISECONDS); <START> if (!isConnected && metrics != null) { <END> metrics.zkConnectionError.inc(); throw new RuntimeException("Unable to connect to Zookeeper within connectionTimeout " + connectionTimeoutMs + "ms. Shutting down!"); } }</code><technical_language>fail RuntimeException if metrics = null(which solely dependent isConnected). move check (metrics != null) if block. java if (!isConnected) { if (metrics != null) metrics.zkConnectionError.inc() }</technical_language>

Target:
public void connect() throws ZkInterruptedException { boolean isConnected = zkClient.waitUntilConnected(connectionTimeoutMs, TimeUnit.MILLISECONDS); if (!isConnected) { if (metrics != null) { metrics.zkConnectionError.inc(); } throw new RuntimeException("Unable to connect to Zookeeper within connectionTimeout " + connectionTimeoutMs + "ms. Shutting down!"); } }
Source:
<code><START> private static boolean isAloneLambda(Details details) { <END> final DetailAST lcurly = details.lcurly; final DetailAST rcurly = details.rcurly; final DetailAST previousSibling = rcurly.getPreviousSibling(); final int lcurlyNo = lcurly.getLineNo(); final int rcurlyNo = rcurly.getLineNo(); boolean result = false; if (lcurlyNo != rcurlyNo) { result = previousSibling == null || rcurlyNo != previousSibling.getLineNo(); } return result; }</code><technical_language>@MaksimP , please explain this method is specific LAMBDA ? if specific, name of general, "Lambda"</technical_language>

Target:
private static boolean isAloneLambda(Details details) { final DetailAST lcurly = details.lcurly; final DetailAST rcurly = details.rcurly; final int lcurlyNo = lcurly.getLineNo(); final int rcurlyNo = rcurly.getLineNo(); boolean result = false; if (lcurlyNo != rcurlyNo) { result = rcurly.getPreviousSibling() == null || rcurlyNo != rcurly.getPreviousSibling().getLineNo(); } return result; }
Source:
<code>public CertificationBodyDTO getByCode(String code) { Query query = entityManager.createQuery( <START> "SELECT acb from CertificationBodyEntity acb " <END> + "LEFT OUTER JOIN FETCH acb.address " + "WHERE (acb.deleted = false) " + "AND (UPPER(acb.acbCode) = :code) ", CertificationBodyEntity.class); query.setParameter("code", code.toUpperCase()); List<CertificationBodyEntity> result = query.getResultList(); if (result != null && result.size() > 0) { return new CertificationBodyDTO(result.get(0)); } return null; }</code><technical_language>"FROM" - consistent capitalizing HQL keyword</technical_language>

Target:
public CertificationBodyDTO getByCode(String code) { Query query = entityManager.createQuery("SELECT acb " + "FROM CertificationBodyEntity acb " + "LEFT OUTER JOIN FETCH acb.address " + "WHERE (acb.deleted = false) " + "AND (UPPER(acb.acbCode) = :code) ", CertificationBodyEntity.class); query.setParameter("code", code.toUpperCase()); List<CertificationBodyEntity> result = query.getResultList(); if (result != null && result.size() > 0) { return new CertificationBodyDTO(result.get(0)); } return null; }
Source:
<code>public Response getProvider(@PathParam("providerId") String providerId, @Context HttpServletRequest request) throws IOException, RestOperationException { <START> OAuth2ServiceProvider provider = Framework.getLocalService(OAuth2ServiceProviderRegistry.class) <END> .getProvider(providerId); if (provider == null || !(provider instanceof NuxeoOAuth2ServiceProvider)) { RestOperationException err = new RestOperationException("Invalid provider: " + providerId); err.setStatus(HttpServletResponse.SC_BAD_REQUEST); throw err; } Map<String,Object> result = new HashMap<>(); result.put("serviceName", provider.getServiceName()); result.put("enabled", provider.isEnabled()); result.put("clientId", provider.getClientId()); result.put("scopes", provider.getScopes()); result.put("authorizationURL", provider.getClientId() == null ? null : provider.getAuthorizationUrl(request)); result.put("authorizationServerURL", provider.getAuthorizationServerURL()); result.put("tokenServerURL", provider.getTokenServerURL()); String username = request.getUserPrincipal().getName(); NuxeoOAuth2Token token = getToken((NuxeoOAuth2ServiceProvider)provider, username); boolean hasToken = (token != null); String login = hasToken ? token.getServiceLogin() : null; result.put("hasToken", hasToken); result.put("userId", login); return buildResponse(Status.OK, result); }</code><technical_language>move this a getProvider(providerId) for DRY</technical_language>

Target:
public Response getProvider(@PathParam("providerId") String providerId, @Context HttpServletRequest request) throws IOException, RestOperationException { NuxeoOAuth2ServiceProvider provider = getProvider(providerId); Map<String,Object> result = new HashMap<>(); result.put("serviceName", provider.getServiceName()); result.put("isAvailable", provider.isProviderAvailable()); result.put("clientId", provider.getClientId()); result.put("authorizationURL", provider.getClientId() == null ? null : provider.getAuthorizationUrl(request)); String username = request.getUserPrincipal().getName(); NuxeoOAuth2Token token = getToken(provider, username); boolean isAuthorized = (token != null); String login = isAuthorized ? token.getServiceLogin() : null; result.put("isAuthorized", isAuthorized); result.put("userId", login); return buildResponse(Status.OK, result); }