auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void updateSetting(String key, String value) { if (getServer().version().isGreaterThanOrEquals("6.1")) { <START> newAdminWsClient().settingsService().set(SetRequest.builder().setKey(key).setValue(value).build()); <END> } else { server.getAdminWsClient().update(new PropertyUpdateQuery(key, value)); } }</code><technical_language>discussed please server.getAdminWsClient().post() instead of a new client. Sharing a single client critical addressed soon</technical_language>

Target:
private void updateSetting(String key, String value) { if (getServer().version().isGreaterThanOrEquals("6.1")) { server.adminWsClient().post("api/settings/set", ImmutableMap.of("key", key, "value", value)); } else { server.getAdminWsClient().update(new PropertyUpdateQuery(key, value)); } }
Source:
<code>protected T getProxyInternal() { try { final InetSocketAddress rmAddress = rmProxy.getRMAddress(conf, protocol); return rmProxy.getProxy(conf, protocol, rmAddress); } catch (IOException ioe) { <START> LOG.error("Unable to create proxy to the ResourceManager ", ioe); <END> return null; } }</code><technical_language>remove space. In addition, enough show ioe.getMessage()</technical_language>

Target:
protected T getProxyInternal() { try { final InetSocketAddress rmAddress = rmProxy.getRMAddress(conf, protocol); return rmProxy.getProxy(conf, protocol, rmAddress); } catch (IOException ioe) { LOG.error("Unable to create proxy to the ResourceManager", ioe.getMessage()); return null; } }
Source:
<code>public ModelPlotConfig(StreamInput in) throws IOException { enabled = in.readBoolean(); terms = in.readOptionalString(); <START> if (in.getVersion().onOrAfter(Version.V_7_9_0)) { <END> annotationsEnabled = in.readBoolean(); } else { annotationsEnabled = enabled; } }</code><technical_language>I delete version check master. logic is simple clashes hard resolve in event of adding another field in lifetime of 7.x</technical_language>

Target:
public ModelPlotConfig(StreamInput in) throws IOException { enabled = in.readBoolean(); terms = in.readOptionalString(); annotationsEnabled = in.readBoolean(); }
Source:
<code>public String toString() { <START> if (dateUploaded != null) { <END> return "UploadResult{" + "errorCode='" + errorCode + '\'' + ", resultStatus='" + resultStatus + '\'' + ", dateUploaded='" + dateUploaded.toString() + '\'' + ", imageUrl='" + imageUrl + '\'' + ", canonicalFilename='" + canonicalFilename + '\'' + '}'; } return "Server is in read only mode"; }</code><technical_language>Do add check here. Add check for dateuploaded</technical_language>

Target:
public String toString() { return "UploadResult{" + "errorCode='" + errorCode + '\'' + ", resultStatus='" + resultStatus + '\'' + ", dateUploaded='" + (dateUploaded != null ? dateUploaded.toString() : "") + '\'' + ", imageUrl='" + imageUrl + '\'' + ", canonicalFilename='" + canonicalFilename + '\'' + '}'; }
Source:
<code>private ExecutableElement getValidationAppliesToMethod(Element annotation) { for ( Element e : annotation.getEnclosedElements() ) { ExecutableElement method = e.accept( new ElementKindVisitor6<ExecutableElement, Void>() { @Override public ExecutableElement visitExecutableAsMethod(ExecutableElement e, Void p) { if ( e.getSimpleName().contentEquals( "validationAppliesTo" ) ) { return e; } <START> return super.visitExecutableAsMethod( e, p ); <END> } }, null ); if ( method != null ) { return method; } } return null; }</code><technical_language>I call super method is needed</technical_language>

Target:
private ExecutableElement getValidationAppliesToMethod(Element annotation) { for ( Element e : annotation.getEnclosedElements() ) { ExecutableElement method = e.accept( new ElementKindVisitor6<ExecutableElement, Void>() { @Override public ExecutableElement visitExecutableAsMethod(ExecutableElement e, Void p) { if ( e.getSimpleName().contentEquals( "validationAppliesTo" ) ) { return e; } return null; } }, null ); if ( method != null ) { return method; } } return null; }
Source:
<code><START> public void setChannelTypeRegistry(ChannelTypeRegistry registry) { <END> this.channelTypeRegistry = registry; }</code><technical_language>default DS binding methods modifier protected instead of public. This prevents others accidentally "destroying" existing service. ProfileTypeResource is injected other services I suggest this approach. In test case able call methods a trick. Instantiate ProfileTypeResource this: ptr = new ProfileTypeResource() { { setChannelTypeRegistry(...); setProfileTypeRegistry(...); } };</technical_language>

Target:
protected void setChannelTypeRegistry(ChannelTypeRegistry registry) { this.channelTypeRegistry = registry; }
Source:
<code>public void testToCalendarWithDateNull() { <START> try { <END> DateUtils.toCalendar(null, zone); fail("Expected NullPointerException to be thrown when Date is null"); } catch(final NullPointerException npe) { } }</code><technical_language>need a try-catch here. simply @Test(expected=NullPointerException.class)</technical_language>

Target:
public void testToCalendarWithDateNull() { DateUtils.toCalendar(null, zone); }
Source:
<code>public void shouldReturnIdImmediatelyAfterRecordIdOnlyOnce() throws Exception { PrepareIdSequence idSequence = new SecondaryUnitPrepareIdSequence(); IdSequence actual = mock( IdSequence.class ); long recordId = 10; IdSequence prepared = idSequence.apply( actual ).apply( recordId ); long nextRecordId = prepared.nextId(); assertEquals( 10 + 1, nextRecordId ); verifyNoMoreInteractions( actual ); try { prepared.nextId(); <START> fail( "Shoul've failed" ); <END> } catch ( IllegalStateException e ) { } recordId = 20; prepared = idSequence.apply( actual ).apply( recordId ); nextRecordId = prepared.nextId(); assertEquals( 20 + 1, nextRecordId ); verifyNoMoreInteractions( actual ); }</code><technical_language>Shoud</technical_language>

Target:
public void shouldReturnIdImmediatelyAfterRecordIdOnlyOnce() throws Exception { PrepareIdSequence idSequence = new SecondaryUnitPrepareIdSequence(); IdSequence actual = mock( IdSequence.class ); long recordId = 10; IdSequence prepared = idSequence.apply( actual ).apply( recordId ); long nextRecordId = prepared.nextId(); assertEquals( 10 + 1, nextRecordId ); verifyNoMoreInteractions( actual ); try { prepared.nextId(); fail( "Should've failed" ); } catch ( IllegalStateException e ) { } recordId = 20; prepared = idSequence.apply( actual ).apply( recordId ); nextRecordId = prepared.nextId(); assertEquals( 20 + 1, nextRecordId ); verifyNoMoreInteractions( actual ); }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(this) <START> .add("_name", _name) <END> .add("_alignSampling", _alignSampling) .add("_alignStartTime", _alignStartTime) .add("_alignEndTime", _alignEndTime) .add("_sampling", _sampling) .add("_otherArgs", _otherArgs) .toString(); }</code><technical_language>nit: (it's inconsistent but) preference is field names underscore prefix for name</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("name", _name) .add("alignSampling", _alignSampling) .add("alignStartTime", _alignStartTime) .add("alignEndTime", _alignEndTime) .add("sampling", _sampling) .add("otherArgs", _otherArgs) .toString(); }
Source:
<code>public SslContextBuilder trustManager(TrustManager trustManager) { trustCertCollection = null; try { this.trustManagerFactory = new TrustManagerFactoryWrapper(trustManager); } catch (Exception e) { <START> throw new Error(e.toString()); <END> } return this; }</code><technical_language>throw IllegalStateException wrap original Exception</technical_language>

Target:
public SslContextBuilder trustManager(TrustManager trustManager) { this.trustManagerFactory = new TrustManagerFactoryWrapper(trustManager); trustCertCollection = null; return this; }
Source:
<code>public void testDeleteRoot() throws Exception { Path srcDir = new Path("/"); fileSys = DFSTestUtil.getFileSystemAs(user1, conf); boolean result = fileSys.delete(srcDir, true); fileSys.close(); <START> assertTrue(result == false); <END> String aceDeletePattern = ".*allowed=false.*ugi=theDoctor.*cmd=delete.*"; verifyAuditLogs(aceDeletePattern); }</code><technical_language>CI reports, more simple here, assertFalse(result)</technical_language>

Target:
public void testDeleteRoot() throws Exception { Path srcDir = new Path("/"); fileSys = DFSTestUtil.getFileSystemAs(user1, conf); boolean result = fileSys.delete(srcDir, true); fileSys.close(); assertFalse(result); String aceDeletePattern = ".*allowed=false.*ugi=theDoctor.*cmd=delete.*"; verifyAuditLogs(aceDeletePattern); }
Source:
<code>public void shouldNotSendEventIfPasswordReminderIsDisabled() throws Exception { List<MotechUser> users = prepareMotechUsersOne(); when(settingService.isPasswordResetReminderEnabled()).thenReturn(false); when(allUsers.retrieveAll()).thenReturn(users); eventHandler.handleEvent(event); verify(allUsers, times(0)).retrieveAll(); verify(eventRelay, times(0)).sendEventMessage(any(MotechEvent.class)); verify(settingService, times(1)).isPasswordResetReminderEnabled(); <START> verify(settingService, times(0)).getNumberOfDaysForReminder(); <END> verify(settingService, times(0)).getNumberOfDaysToChangePassword(); }</code><technical_language>never() instead of times(0)</technical_language>

Target:
public void shouldNotSendEventIfPasswordReminderIsDisabled() throws Exception { List<MotechUser> users = prepareMotechUsersOne(); when(settingService.isPasswordResetReminderEnabled()).thenReturn(false); when(allUsers.retrieveAll()).thenReturn(users); eventHandler.handleEvent(event); verify(allUsers, never()).retrieveAll(); verify(eventRelay, never()).sendEventMessage(any(MotechEvent.class)); verify(settingService, times(1)).isPasswordResetReminderEnabled(); verify(settingService, never()).getNumberOfDaysForReminder(); verify(settingService, never()).getNumberOfDaysToChangePassword(); }
Source:
<code>public void run() { try { ConnectedChannel channel1 = connectionPool.checkOutConnection("localhost", 6667, 1000); channelCount.get("localhost" + 6667).incrementAndGet(); ConnectedChannel channel2 = connectionPool.checkOutConnection("localhost", 6668, 1000); channelCount.get("localhost" + 6668).incrementAndGet(); ConnectedChannel channel3 = connectionPool.checkOutConnection("localhost", 6669, 1000); channelCount.get("localhost" + 6669).incrementAndGet(); releaseConnection.await(); if (destroyConnection) { connectionPool.destroyConnection(channel1); } else { connectionPool.checkInConnection(channel1); } if (destroyConnection) { connectionPool.destroyConnection(channel2); } else { connectionPool.checkInConnection(channel2); } if (destroyConnection) { connectionPool.destroyConnection(channel3); } else { connectionPool.checkInConnection(channel3); } } catch (Exception e) { exception.set(e); e.printStackTrace(); <START> Assert.assertFalse(true); <END> } }</code><technical_language>I lines of (216 217). assertionError thrown junit</technical_language>

Target:
public void run() { try { ConnectedChannel channel1 = connectionPool.checkOutConnection("localhost", 6667, 1000); channelCount.get("localhost" + 6667).incrementAndGet(); ConnectedChannel channel2 = connectionPool.checkOutConnection("localhost", 6668, 1000); channelCount.get("localhost" + 6668).incrementAndGet(); ConnectedChannel channel3 = connectionPool.checkOutConnection("localhost", 6669, 1000); channelCount.get("localhost" + 6669).incrementAndGet(); releaseConnection.await(); if (destroyConnection) { connectionPool.destroyConnection(channel1); } else { connectionPool.checkInConnection(channel1); } if (destroyConnection) { connectionPool.destroyConnection(channel2); } else { connectionPool.checkInConnection(channel2); } if (destroyConnection) { connectionPool.destroyConnection(channel3); } else { connectionPool.checkInConnection(channel3); } } catch (Exception e) { exception.set(e); e.printStackTrace(); } }
Source:
<code>public Slice getStripeFooterSlice(OrcDataSource orcDataSource, StripeId stripeId, long footerOffset, int footerLength, HiveFileContext hiveFileContext) throws IOException { try { return footerSliceCache.get(stripeId, () -> delegate.getStripeFooterSlice(orcDataSource, stripeId, footerOffset, footerLength, hiveFileContext)); } catch (ExecutionException | UncheckedExecutionException e) { <START> throwIfInstanceOf(e.getCause(), IOException.class); <END> throw new IOException("Unexpected error in stripe footer reading after footerSliceCache miss", e.getCause()); } }</code><technical_language>Cache</technical_language>

Target:
public Slice getStripeFooterSlice(OrcDataSource orcDataSource, StripeId stripeId, long footerOffset, int footerLength, HiveFileContext hiveFileContext) throws IOException { try { if (!hiveFileContext.isCacheable()) { return delegate.getStripeFooterSlice(orcDataSource, stripeId, footerOffset, footerLength, hiveFileContext); } return footerSliceCache.get(stripeId, () -> delegate.getStripeFooterSlice(orcDataSource, stripeId, footerOffset, footerLength, hiveFileContext)); } catch (ExecutionException | UncheckedExecutionException e) { throwIfInstanceOf(e.getCause(), IOException.class); throw new IOException("Unexpected error in stripe footer reading after footerSliceCache miss", e.getCause()); } }
Source:
<code>public void testPrintXpathTwo() throws Exception { final String eol = System.lineSeparator(); final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final Path file = Files.createTempFile("", ""); Files.write(file, fileContent.getBytes(StandardCharsets.UTF_8)); final String expected = "CLASS_DEF -> CLASS_DEF [1:0]" + eol + "`--OBJBLOCK -> OBJBLOCK [1:11]" + eol + " |--METHOD_DEF -> METHOD_DEF [1:13]" + eol + " | `--SLIST -> { [1:34]" + eol + " | |--VARIABLE_DEF -> VARIABLE_DEF [1:35]" + eol + " | | |--IDENT -> a [1:39]" + eol + "---------" + eol + "CLASS_DEF -> CLASS_DEF [1:0]" + eol + "`--OBJBLOCK -> OBJBLOCK [1:11]" + eol + " |--METHOD_DEF -> METHOD_DEF [1:13]" + eol + " | `--SLIST -> { [1:34]" + eol + " | |--VARIABLE_DEF -> VARIABLE_DEF [1:46]" + eol + " | | |--IDENT -> b [1:50]" + eol; assertEquals("Branch string is different", expected, XpathUtil.printXpathBranch( " <START> file.toFile())); <END> }</code><technical_language>read ? String actualXpath = XpathUtil.printXpathBranch("//CLASS_DEF//METHOD_DEF//VARIABLE_DEF//IDENT", path.toFile()) assertEquals("Branch string is different", expected, actualXpath);</technical_language>

Target:
public void testPrintXpathTwo() throws Exception { final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final File file = tempFolder.newFile(); Files.write(file.toPath(), fileContent.getBytes(StandardCharsets.UTF_8)); final String expected = addEndOfLine( "CLASS_DEF -> CLASS_DEF [1:0]", "`--OBJBLOCK -> OBJBLOCK [1:11]", " |--METHOD_DEF -> METHOD_DEF [1:13]", " | `--SLIST -> { [1:34]", " | |--VARIABLE_DEF -> VARIABLE_DEF [1:35]", " | | |--IDENT -> a [1:39]", "---------", "CLASS_DEF -> CLASS_DEF [1:0]", "`--OBJBLOCK -> OBJBLOCK [1:11]", " |--METHOD_DEF -> METHOD_DEF [1:13]", " | `--SLIST -> { [1:34]", " | |--VARIABLE_DEF -> VARIABLE_DEF [1:46]", " | | |--IDENT -> b [1:50]"); final String result = XpathUtil.printXpathBranch( " assertThat("Branch string is different", result, is(expected)); }
Source:
<code>public AllelicCountReader(final File file) throws IOException { super(file); if (columns().containsAll(AllelicCountTableColumns.FULL_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableColumns.AllelicCountTableVerbosity.FULL; } else if (columns().containsAll(AllelicCountTableColumns.INTERMEDIATE_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableColumns.AllelicCountTableVerbosity.INTERMEDIATE; } else if (columns().containsAll(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableColumns.AllelicCountTableVerbosity.BASIC; } else { final Set<String> missingColumns = Sets.difference( new HashSet<>(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY), new HashSet<>(columns().names())); throw new UserException.BadInput("Bad header in AllelicCount file. Not all mandatory columns are present." + " Missing: " + StringUtils.join(missingColumns, ", ")); } <START> <END> }</code><technical_language>Extra blank line</technical_language>

Target:
public AllelicCountReader(final File file) throws IOException { super(file); if (columns().containsAll(AllelicCountTableColumns.FULL_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableVerbosity.FULL; } else if (columns().containsAll(AllelicCountTableColumns.INTERMEDIATE_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableVerbosity.INTERMEDIATE; } else if (columns().containsAll(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY)) { verbosity = AllelicCountTableVerbosity.BASIC; } else { final Set<String> missingColumns = Sets.difference( new HashSet<>(AllelicCountTableColumns.BASIC_COLUMN_NAME_ARRAY), new HashSet<>(columns().names())); throw new UserException.BadInput("Bad header in AllelicCount file. Not all mandatory columns are present." + " Missing: " + StringUtils.join(missingColumns, ", ")); } }
Source:
<code>protected Optional<PlanNode> pushDownProjectOff(PlanNodeIdAllocator idAllocator, JoinNode joinNode, Set<Symbol> referencedOutputs) { Optional<PlanNode> newLeft = restrictOutputs(idAllocator, joinNode.getLeft(), referencedOutputs); Optional<PlanNode> newRight = restrictOutputs(idAllocator, joinNode.getRight(), referencedOutputs); <START> if (!(newLeft.isPresent() || newRight.isPresent())) { <END> return Optional.empty(); } ImmutableList.Builder<Symbol> outputSymbolBuilder = ImmutableList.builder(); outputSymbolBuilder.addAll(newLeft.orElse(joinNode.getLeft()).getOutputSymbols()); outputSymbolBuilder.addAll(newRight.orElse(joinNode.getRight()).getOutputSymbols()); return Optional.of(new JoinNode( idAllocator.getNextId(), joinNode.getType(), newLeft.orElse(joinNode.getLeft()), newRight.orElse(joinNode.getRight()), joinNode.getCriteria(), outputSymbolBuilder.build(), joinNode.getFilter(), joinNode.getLeftHashSymbol(), joinNode.getRightHashSymbol(), joinNode.getDistributionType())); }</code><technical_language>change to: !newLeft.isPresent() && !newRight.isPresent()</technical_language>

Target:
protected Optional<PlanNode> pushDownProjectOff(PlanNodeIdAllocator idAllocator, JoinNode joinNode, Set<Symbol> referencedOutputs) { Optional<PlanNode> newLeft = restrictOutputs(idAllocator, joinNode.getLeft(), referencedOutputs); Optional<PlanNode> newRight = restrictOutputs(idAllocator, joinNode.getRight(), referencedOutputs); if (!newLeft.isPresent() && !newRight.isPresent()) { return Optional.empty(); } ImmutableList.Builder<Symbol> outputSymbolBuilder = ImmutableList.builder(); outputSymbolBuilder.addAll(newLeft.orElse(joinNode.getLeft()).getOutputSymbols()); outputSymbolBuilder.addAll(newRight.orElse(joinNode.getRight()).getOutputSymbols()); return Optional.of(new JoinNode( idAllocator.getNextId(), joinNode.getType(), newLeft.orElse(joinNode.getLeft()), newRight.orElse(joinNode.getRight()), joinNode.getCriteria(), outputSymbolBuilder.build(), joinNode.getFilter(), joinNode.getLeftHashSymbol(), joinNode.getRightHashSymbol(), joinNode.getDistributionType())); }
Source:
<code>private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AddVmStatic(); AddVmDynamic(); AddVmNetwork(); AddVmStatistics(); getCompensationContext().stateChanged(); return null; } <START> }); <END> TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AddVmImages(); MoveOrCopyAllImageGroups(); VmHandler.LockVm(getVm().getvm_guid()); return null; } }); }</code><technical_language>ligically addVmToDb ends here, is images handling</technical_language>

Target:
private void addVmToDb() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { AddVmStatic(); AddVmDynamic(); AddVmNetwork(); AddVmStatistics(); getCompensationContext().stateChanged(); return null; } }); }
Source:
<code>static Map<Partition, List<String>> obtainPartitionDescriptorMap(String stagingDirectory, String streamName) { if (StringUtils.isBlank(stagingDirectory)) { LOG.warn("Empty staging directory"); <START> return null; <END> } if (StringUtils.isBlank(streamName)) { throw new SamzaException("stream name is empty!"); } Path path = PartitionDescriptorUtil.getPartitionDescriptorPath(stagingDirectory, streamName); try (FileSystem fs = path.getFileSystem(new Configuration())) { if (!fs.exists(path)) { return null; } try (FSDataInputStream fis = fs.open(path)) { String json = IOUtils.toString(fis, StandardCharsets.UTF_8); return PartitionDescriptorUtil.getDescriptorMapFromJson(json); } } catch (IOException e) { throw new SamzaException("Failed to read partition description from: " + path); } }</code><technical_language>return Collections.emptyMap() instead of null</technical_language>

Target:
static Map<Partition, List<String>> obtainPartitionDescriptorMap(String stagingDirectory, String streamName) { if (StringUtils.isBlank(stagingDirectory)) { LOG.info("Empty or null staging directory: {}", stagingDirectory); return Collections.emptyMap(); } if (StringUtils.isBlank(streamName)) { throw new SamzaException(String.format("stream name (%s) is null or empty!", streamName)); } Path path = PartitionDescriptorUtil.getPartitionDescriptorPath(stagingDirectory, streamName); try (FileSystem fs = path.getFileSystem(new Configuration())) { if (!fs.exists(path)) { return Collections.emptyMap(); } try (FSDataInputStream fis = fs.open(path)) { String json = IOUtils.toString(fis, StandardCharsets.UTF_8); return PartitionDescriptorUtil.getDescriptorMapFromJson(json); } } catch (IOException e) { throw new SamzaException("Failed to read partition description from: " + path); } }
Source:
<code>public SimpleInterval(final String contig, final int start, final int end){ if(contig == null){ <START> throw new IllegalArgumentException("contig cannot be null"); <END> } if (start <= 0 ){ throw new IllegalArgumentException("SimpleInterval is 1 based, so start must be >= 1, start:%d" + start); } if (end < start){ throw new IllegalArgumentException( String.format("start must be <= end. start:%d end:%d", start, end)); } this.contig = contig; this.start = start; this.end = end; }</code><technical_language>current implementation of SimpleInterval represent unmapped interval? If so, how</technical_language>

Target:
public SimpleInterval(final String contig, final int start, final int end){ if(contig == null){ throw new IllegalArgumentException("contig cannot be null"); } if (start <= 0 ){ throw new IllegalArgumentException("SimpleInterval is 1 based, so start must be >= 1, start:%d" + start); } if (end < start -1){ throw new IllegalArgumentException( String.format("end must be >= start -1 . start:%d end:%d", start, end)); } this.contig = contig; this.start = start; this.end = end; }
Source:
<code>private void initActive() throws ExecutorManagerException { final Executor executor; try { final String host = requireNonNull(getHost()); final int port = props.getInt(ConfigurationKeys.EXECUTOR_PORT, -1); <START> checkState(port != -1); <END> executor = this.executionLoader.fetchExecutor(host, port); } catch (final ExecutorManagerException e) { logger.error("Error fetching executor entry from DB", e); throw e; } if (executor == null) { logger.info("This executor wasn't found in the DB. Setting active=false."); getFlowRunnerManager().setActiveInternal(false); } else { logger.info("This executor is already in the DB. Found active=" + executor.isActive()); getFlowRunnerManager().setActiveInternal(executor.isActive()); } }</code><technical_language>Fixed port is multiple executors host. A new deployment lets new executions place latest executor, however, existing continue executor started. executor instances shutdown drained out. elaborate if condition? condition</technical_language>

Target:
private void initActive() throws ExecutorManagerException { final Executor executor; final int port = this.props.getInt(ConfigurationKeys.EXECUTOR_PORT, -1); if (port != -1) { final String host = requireNonNull(getHost()); try { executor = this.executionLoader.fetchExecutor(host, port); } catch (final ExecutorManagerException e) { logger.error("Error fetching executor entry from DB", e); throw e; } if (executor == null) { logger.info("This executor wasn't found in the DB. Setting active=false."); getFlowRunnerManager().setActiveInternal(false); } else { logger.info("This executor is already in the DB. Found active=" + executor.isActive()); getFlowRunnerManager().setActiveInternal(executor.isActive()); } } else { logger.info(ConfigurationKeys.EXECUTOR_PORT + " wasn't set - free port will be picked automatically. Executor " + "is started with active=false and must be activated separately."); } }
Source:
<code>public static Version getCompatibilityVersion(VmBase vmBase) { return vmBase.getClusterId() != null ? getInstance().getClusterDao().get(vmBase.getClusterId()).getCompatibilityVersion() <START> : Version.v3_6; <END> }</code><technical_language>this 3.5</technical_language>

Target:
public static Version getCompatibilityVersion(VmBase vmBase) { return vmBase.getClusterId() != null ? getInstance().getClusterDao().get(vmBase.getClusterId()).getCompatibilityVersion() : Version.v3_5; }
Source:
<code>void updateBindings(List<Binding> bindings) throws SQLException { getConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { <START> preparedStatement = conn.prepareStatement(UPDATE_BINDING); <END> for (Binding binding : bindings) { preparedStatement.setString(1, binding.getBindingDetails()); preparedStatement.setString(2, binding.getQueueName()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); } catch (SQLException e) { e.printStackTrace(); } finally { close(conn, preparedStatement, resultSet); } }</code><technical_language>try-with-resources[1] here? need specifically close resources. [1] <LINK_0></technical_language>

Target:
void updateBindings(List<Binding> bindings) throws SQLException { try (Connection conn = getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(UPDATE_BINDING)) { for (Binding binding : bindings) { preparedStatement.setString(1, binding.getBindingDetails()); preparedStatement.setString(2, binding.getQueueName()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); } }
Source:
<code>public String getURI() { <START> return "/metadatamapping/metadatasource"; <END> }</code><technical_language>short /metadatamapping/source</technical_language>

Target:
public String getURI() { return "/metadatamapping/source"; }
Source:
<code>private String getHypervisor(String folder) { String[] validHypervisors = CDK3Server.getHypervisors(); String hyperV = validHypervisors[0]; File config = new File(folder, "config"); File configJson = new File(config, "config.json"); if (!configJson.exists() || !configJson.isFile()) { return hyperV; } String path = configJson.getAbsolutePath(); try { String content = new String(Files.readAllBytes(Paths.get(path))); ModelNode mn = ModelNode.fromJSONString(content); ModelNode o = mn.get("vm-driver"); String val = (o == null ? null : o.asString()); if (val != null && Arrays.asList(validHypervisors).contains(val)) { return val; } } catch (IOException e) { <START> IOException ioe2 = new IOException("Error parsing " + path, e); <END> CDKCoreActivator.pluginLog().logError(ioe2); } return hyperV; }</code><technical_language>Creating a new objects is expensive task, just: Java CDKCoreActivator.pluginLog().logError("Error parsing " + path, e);</technical_language>

Target:
private String getHypervisor(String folder) { String[] validHypervisors = CDK3Server.getHypervisors(); String hyperV = validHypervisors[0]; File config = new File(folder, "config"); File configJson = new File(config, "config.json"); if (!configJson.exists() || !configJson.isFile()) { return hyperV; } String path = configJson.getAbsolutePath(); try { String content = new String(Files.readAllBytes(Paths.get(path))); ModelNode mn = ModelNode.fromJSONString(content); ModelNode o = mn.get("vm-driver"); String val = (o == null ? null : o.asString()); if (val != null && Arrays.asList(validHypervisors).contains(val)) { return val; } } catch (IOException e) { CDKCoreActivator.pluginLog().logError("Error parsing " + path, e); } return hyperV; }
Source:
<code>public String showStatus() throws InterruptedException, ExecutionException { if (future.isDone()) { result = future.get(); if (result == null) <START> return "failure"; <END> return "success"; } return "status"; }</code><technical_language>tiles names specific for transformations; failure success</technical_language>

Target:
public String showStatus() throws InterruptedException, ExecutionException { if (future.isDone()) { result = future.get(); if (result == null) { return "auth/transformation/emptyTransformation"; } return "auth/transformation/successTransformation"; } return "auth/transformation/statusTransformation"; }
Source:
<code>public View getView(ViewModel model, HttpServletRequest request) { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, null, producesMediaTypes); <START> if (mediaType.equals(MediaType.APPLICATION_JSON) || "stormpathJsonView".equals(model.getViewName())) { <END> return jsonView; } if (mediaType.equals(MediaType.TEXT_HTML)) { return delegateViewResolver.getView(model, request); } } catch (UnresolvedMediaTypeException e) { } return null; }</code><technical_language>In AbstractStormpathWebMvcConfiguration name of json view is configured stormpath.web.json.view. please add a new variable called stormpathJsonView is obtained property change hardcoded "stormpathJsonView".equals(model.getViewName()) stormpathJsonView.equals(model.getViewName())</technical_language>

Target:
public View getView(ViewModel model, HttpServletRequest request) { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, null, producesMediaTypes); if (mediaType.equals(MediaType.APPLICATION_JSON) || STORMPATH_JSON_VIEW_NAME.equals(model.getViewName())) { return jsonView; } if (mediaType.equals(MediaType.TEXT_HTML)) { return delegateViewResolver.getView(model, request); } } catch (UnresolvedMediaTypeException e) { } return null; }
Source:
<code>protected VdcReturnValueBase attemptRollback(VdcActionType commandType, VdcActionParametersBase params, <START> CommandContext context) { <END> if (canPerformRollbackUsingCommand(commandType, params)) { params.setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); return Backend.getInstance().runInternalAction(commandType, params); } return new VdcReturnValueBase(); }</code><technical_language>do context</technical_language>

Target:
protected VdcReturnValueBase attemptRollback(VdcActionType commandType, VdcActionParametersBase params, CommandContext context) { if (canPerformRollbackUsingCommand(commandType, params)) { params.setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); return Backend.getInstance().runInternalAction(commandType, params, context); } return new VdcReturnValueBase(); }
Source:
<code>public synchronized void close() { if (!isOpen()) { LOGGER.info("jms transport already closed, returning"); return; } try { producer.close(); <START> session.close(); <END> } catch (JMSException e) { LOGGER.error("failed to close jms producer", e); } finally { producer = null; session = null; } }</code><technical_language>try-with-resource ensures is closed if closing fails: try (MessageProducer closeProducer = producer) { session.close(); } (Later Java supports try (producer) { session.close(); } dummy var.)</technical_language>

Target:
public synchronized void close() { if (!isOpen()) { LOGGER.info("jms transport already closed, returning"); return; } try (Session closeSession = session) { producer.close(); } catch (JMSException e) { LOGGER.error("failed to close jms producer", e); } finally { producer = null; session = null; } }
Source:
<code><START> public InvalidationTracker(RoomDatabase database, Map<String, String> shadowTablesMap, <END> String... tableNames) { mDatabase = database; mObservedTableTracker = new ObservedTableTracker(tableNames.length); mTableIdLookup = new ArrayMap<>(); mShadowTableLookup = new SparseArrayCompat<>(); final int size = tableNames.length; mTableNames = new String[size]; for (int id = 0; id < size; id++) { final String tableName = tableNames[id].toLowerCase(Locale.US); mTableIdLookup.put(tableName, id); mTableNames[id] = tableName; if (shadowTablesMap.containsKey(tableNames[id])) { final String shadowTableName = shadowTablesMap.get(tableNames[id]); mShadowTableLookup.append(id, shadowTableName.toLowerCase(Locale.US)); } } mTableVersions = new long[tableNames.length]; Arrays.fill(mTableVersions, 0); }</code><technical_language>need previous constructor, new runtime compatible codegen</technical_language>

Target:
public InvalidationTracker(RoomDatabase database, Map<String, String> shadowTablesMap, String... tableNames) { mDatabase = database; mObservedTableTracker = new ObservedTableTracker(tableNames.length); mTableIdLookup = new ArrayMap<>(); mShadowTableLookup = new SparseArrayCompat<>(shadowTablesMap.size()); final int size = tableNames.length; mTableNames = new String[size]; for (int id = 0; id < size; id++) { final String tableName = tableNames[id].toLowerCase(Locale.US); mTableIdLookup.put(tableName, id); mTableNames[id] = tableName; if (shadowTablesMap.containsKey(tableNames[id])) { final String shadowTableName = shadowTablesMap.get(tableNames[id]); mShadowTableLookup.append(id, shadowTableName.toLowerCase(Locale.US)); } } mTableVersions = new long[tableNames.length]; Arrays.fill(mTableVersions, 0); }
Source:
<code>public ReactorNettyClient(String url, String username, String password, ReactorNettyClientOptions options) { objectMapper = options.objectMapper() == null ? createDefaultObjectMapper() : options.objectMapper().get(); client = options.client() == null ? HttpClient.create().baseUrl(url) : options.client().get(); this.token = options.token() == null ? createBasicAuthenticationToken(username, password) : options.token(); if (options.onResponseCallback() == null) { this.onResponseCallback = (response, connection) -> { if (response.method() == HttpMethod.GET) { if (response.status().code() >= 500) { <START> throw new HttpServerException(response.status().code(), response.status().reasonPhrase()); <END> } else if (response.status().code() >= 400) { throw new HttpClientException(response.status().code(), response.status().reasonPhrase()); } } }; } else { this.onResponseCallback = (response, connection) -> options.onResponseCallback().accept(new HttpEndpoint(response.uri(), response.method().name()), toHttpResponse(response)); } }</code><technical_language>introduce extra API in HttpClient builder again. In general for generic REST cases want do issues payload dropped in past. I need double check if throw works expected (it should)</technical_language>

Target:
public ReactorNettyClient(String url, String username, String password, ReactorNettyClientOptions options) { objectMapper = options.objectMapper() == null ? createDefaultObjectMapper() : options.objectMapper().get(); client = options.client() == null ? HttpClient.create().baseUrl(url) : options.client().get(); this.token = options.token() == null ? createBasicAuthenticationToken(username, password) : options.token(); if (options.onResponseCallback() == null) { this.responseCallback = response -> { if (response.method() == HttpMethod.GET) { if (response.status().code() >= 500) { throw new HttpServerException(response.status().code(), response.status().reasonPhrase()); } else if (response.status().code() >= 400) { throw new HttpClientException(response.status().code(), response.status().reasonPhrase()); } } }; } else { this.responseCallback = response -> options.onResponseCallback().accept(new HttpEndpoint(response.uri(), response.method().name()), toHttpResponse(response)); } ByteBufAllocator byteBufAllocator = new PooledByteBufAllocator(); this.byteBufSupplier = () -> byteBufAllocator.buffer(); }
Source:
<code>public String getCommandDescription() { return "Merges multiple Parquet files into one. " + "The command doesn't merge row groups, just places one after the other. " + <START> "When used to merge many small files, the resulting file will still contain small row groups."; <END> }</code><technical_language>I add ", leads bad query performance."</technical_language>

Target:
public String getCommandDescription() { return "Merges multiple Parquet files into one. " + "The command doesn't merge row groups, just places one after the other. " + "When used to merge many small files, the resulting file will still contain small row groups, " + "which usually leads to bad query performance."; }
Source:
<code>private void startCollectingLogs() throws IOException, InterruptedException { Preconditions.checkNotNull(currentLogCollector, "Collector should not be null"); <START> currentLogCollector.startCollecting(containersToStart.size() + containersStarted.size()); <END> }</code><technical_language>Afraid this is right - a container started, is removed containersToStart. if I Containers = new Containers(Blah.class).with(new Basket()); one.before(); // initializes executor 1 thread, basket is in started toStart this = one.with(new DrinkCan()); one.before(); // initializes executor 3 threads I is intention. want Sets.union(containersToStart, containersStarted).size()</technical_language>

Target:
private void startCollectingLogs() { currentLogCollector.initializeExecutor(Sets.union(containersToStart, containersStarted).size()); }
Source:
<code>public static List<URI> processScannedFilesAsURIs(List<String> classPathFiles) { List<URI> deps = new ArrayList<>(); for (String file : classPathFiles) { if (FilenameUtils.getName(file).startsWith(".")) { continue; } <START> if (file.endsWith(JAVA_ARCHIVE_RESOURCE_EXT)) { <END> if (file.startsWith(FILE_URI)) { deps.add(URI.create(file)); } else { deps.add(URI.create(FILE_URI + file)); } } } return deps; }</code><technical_language>This if is indented incorrectly - please reformat kie conventions</technical_language>

Target:
public static List<URI> processScannedFilesAsURIs(List<String> classPathFiles) { List<URI> deps = new ArrayList<>(); for (String file : classPathFiles) { if (FilenameUtils.getName(file).startsWith(".")) { continue; } if (file.endsWith(CommonConstants.JAVA_ARCHIVE_RESOURCE_EXT)) { if (file.startsWith(CommonConstants.FILE_URI)) { deps.add(URI.create(file)); } else { deps.add(URI.create(CommonConstants.FILE_URI + file)); } } } return deps; }
Source:
<code>private void captureOutput(Process process, String vepOutputPath) { writingOk = new AtomicBoolean(false); outputCapturer = new Thread(() -> { long writtenLines = 0; boolean skipComments = new File(vepOutputPath).exists(); try (OutputStreamWriter writer = getOutputStreamWriter(vepOutputPath); BufferedReader processStandardOutput = getBufferedReader(process) ) { writtenLines = copyVepOutput(processStandardOutput, writer, skipComments); writingOk.set(true); } catch (IOException e) { logger.error("Writing the VEP output to " + vepOutputPath + " failed. ", e); } logger.trace("Finished writing VEP output ({} lines written) to {}", writtenLines, vepOutputPath); }); logger.trace("Starting writing VEP output to {}", vepOutputPath); <START> outputCapturer.start(); <END> }</code><technical_language>outputCaptureThread easier identify this is exactly, "capturer" a meaning</technical_language>

Target:
private void captureOutput(Process process, String vepOutputPath) { writingOk = new AtomicBoolean(false); outputCaptureThread = new Thread(() -> { long writtenLines = 0; boolean skipComments = new File(vepOutputPath).exists(); try (OutputStreamWriter writer = getOutputStreamWriter(vepOutputPath); BufferedReader processStandardOutput = getBufferedReader(process) ) { writtenLines = copyVepOutput(processStandardOutput, writer, skipComments); writingOk.set(true); } catch (IOException e) { logger.error("Writing the VEP output to " + vepOutputPath + " failed. ", e); } logger.trace("Finished writing VEP output ({} lines written) to {}", writtenLines, vepOutputPath); }); logger.trace("Starting writing VEP output to {}", vepOutputPath); outputCaptureThread.start(); }
Source:
<code>@Override public void run() { try { Thread.currentThread().setName(Utils.THREAD_PREFIX + data.getName()); result = hunt(); if (result == null) { dispatcher.dispatchFailed(this); } else { dispatcher.dispatchComplete(this); } } catch (IOException e) { exception = e; dispatcher.dispatchRetry(this); } catch (OutOfMemoryError e) { result = null; dispatcher.dispatchFailed(this); <START> throw e; <END> } catch (Exception e) { exception = e; dispatcher.dispatchFailed(this); } finally { Thread.currentThread().setName(Utils.THREAD_IDLE_NAME); } }</code><technical_language>crash app</technical_language>

Target:
@Override public void run() { try { Thread.currentThread().setName(Utils.THREAD_PREFIX + data.getName()); result = hunt(); if (result == null) { dispatcher.dispatchFailed(this); } else { dispatcher.dispatchComplete(this); } } catch (IOException e) { exception = e; dispatcher.dispatchRetry(this); } catch (OutOfMemoryError e) { StringWriter writer = new StringWriter(); stats.createSnapshot().dump(new PrintWriter(writer)); exception = new RuntimeException(writer.toString(), e); dispatcher.dispatchFailed(this); } catch (Exception e) { exception = e; dispatcher.dispatchFailed(this); } finally { Thread.currentThread().setName(Utils.THREAD_IDLE_NAME); } }
Source:
<code>public void test() { final HelloWorld hello = new HelloWorld(); <START> assertTrue("Hello World".equals(hello.test())); <END> }</code><technical_language>assertEquals(...) instead for reports in case of failur</technical_language>

Target:
public void test() { final HelloWorld hello = new HelloWorld(); assertEquals("Hello World", hello.test()); }
Source:
<code>public synchronized CompletableFuture<Boolean> addToWaitList(String email) { <START> if (! enableWaitList || numberWaiting >= MAX_WAITING || ! VALID_EMAIL.matcher(email).matches()) <END> return Futures.of(false); try { Files.write(waitingList, (email + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); numberWaiting++; return Futures.of(true); } catch (IOException e) { e.printStackTrace(); return Futures.of(false); } }</code><technical_language>check email string length</technical_language>

Target:
public synchronized CompletableFuture<Boolean> addToWaitList(String email) { if (! enableWaitList || numberWaiting >= MAX_WAITING || ! VALID_EMAIL.matcher(email).matches() || email.length() > MAX_EMAIL_LENGTH) return Futures.of(false); try { Files.write(waitingList, (email + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); numberWaiting++; return Futures.of(true); } catch (IOException e) { e.printStackTrace(); return Futures.of(false); } }
Source:
<code>public BatchItem( final String rawEvent, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; try { this.event = StrictJsonParser.parseObject(rawEvent); } catch (final JSONException e) { LOG.debug("[STRICT_JSON_FAIL] Failed to parse event with strict parser: Error message: {}", <START> rawEvent, e.getMessage()); <END> throw e; } this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }</code><technical_language>@v-stepanov I this message logged in StrictJsonParser, top level exception</technical_language>

Target:
public BatchItem( final String rawEvent, final EmptyInjectionConfiguration emptyInjectionConfiguration, final InjectionConfiguration[] injections, final List<Integer> skipCharacters) { this.rawEvent = rawEvent; this.skipCharacters = skipCharacters; this.event = StrictJsonParser.parseObject(rawEvent); this.eventSize = rawEvent.getBytes(StandardCharsets.UTF_8).length; this.emptyInjectionConfiguration = emptyInjectionConfiguration; this.injections = injections; this.response = new BatchItemResponse(); Optional.ofNullable(this.event.optJSONObject("metadata")) .map(e -> e.optString("eid", null)) .ifPresent(this.response::setEid); }
Source:
<code>public Response countAssets(@Context UriInfo info, @Context SecurityContext sc) throws InvalidParameterException { if (logger.isLoggable(Level.FINE)) { logger.fine("countAssets called with query parameters: " + info.getRequestUri().getRawQuery()); } AssetQueryParameters params = AssetQueryParameters.create(info); Collection<AssetFilter> filters = params.getFilters(); if (!sc.isUserInRole(ADMIN_ROLE)) { <START> AssetFilter publishedFilter = new AssetFilter(Asset.STATE, Collections.<Condition> singletonList(new Condition(Operation.EQUALS, Asset.State.PUBLISHED.getValue()))); <END> filters.add(publishedFilter); } int count = assetService.countAllAssets(filters, params.getSearchTerm()); return Response.noContent().header("count", count).build(); }</code><technical_language>filter in places, factor out</technical_language>

Target:
public Response countAssets(@Context UriInfo info, @Context SecurityContext sc) throws InvalidParameterException { if (logger.isLoggable(Level.FINE)) { logger.fine("countAssets called with query parameters: " + info.getRequestUri().getRawQuery()); } AssetQueryParameters params = AssetQueryParameters.create(info); Collection<AssetFilter> filters = params.getFilters(); if (!sc.isUserInRole(ADMIN_ROLE)) { filters.add(ASSET_IS_PUBLISHED); } int count = assetService.countAllAssets(filters, params.getSearchTerm()); return Response.noContent().header("count", count).build(); }
Source:
<code>public void shouldScheduleZetesUpdateJob() { <START> ebodacScheduler.unscheduleZetesUpdateJob(); <END> verify(motechSchedulerService).safeUnscheduleAllJobs(EbodacConstants.ZETES_UPDATE_EVENT); Date startDate = DateTime.now().toDate(); String zetesUrl = "zetesUrl"; String zetesUsername = "username"; String zetesPassword = "password"; ebodacScheduler.scheduleZetesUpdateJob(startDate,zetesUrl,zetesUsername,zetesPassword); Map<String, Object> eventParameters = new HashMap<>(); eventParameters.put(EbodacConstants.ZETES_URL, zetesUrl); eventParameters.put(EbodacConstants.ZETES_USERNAME, zetesUsername); eventParameters.put(EbodacConstants.ZETES_PASSWORD, zetesPassword); MotechEvent event = new MotechEvent(EbodacConstants.ZETES_UPDATE_EVENT, eventParameters); Period period = Period.days(1); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate, null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }</code><technical_language>move new test - named shouldUnscheduleZetesUpdateJob</technical_language>

Target:
public void shouldScheduleZetesUpdateJob() { Date startDate = DateTime.now().toDate(); String zetesUrl = "zetesUrl"; String zetesUsername = "username"; String zetesPassword = "password"; ebodacScheduler.scheduleZetesUpdateJob(startDate,zetesUrl,zetesUsername,zetesPassword); Map<String, Object> eventParameters = new HashMap<>(); eventParameters.put(EbodacConstants.ZETES_URL, zetesUrl); eventParameters.put(EbodacConstants.ZETES_USERNAME, zetesUsername); eventParameters.put(EbodacConstants.ZETES_PASSWORD, zetesPassword); MotechEvent event = new MotechEvent(EbodacConstants.ZETES_UPDATE_EVENT, eventParameters); Period period = Period.days(1); RepeatingPeriodSchedulableJob job = new RepeatingPeriodSchedulableJob(event, startDate, null, period, true); verify(motechSchedulerService).safeScheduleRepeatingPeriodJob(job); }
Source:
<code>public DefaultLoadBalancingPolicy(DriverContext context, String profileName) { <START> this( <END> getLocalDcFromConfig(context, profileName), getFilterFromConfig(context, profileName), context); }</code><technical_language>Small slightly unrelated issue DefaultLoadBalancingPolicy, logic line 113 assumes if contact points provided localDC inferred 127.0.0.1. get rid of logic if localDC is explicitly set. In case I a default profile dc1, another profile dc2, in cases dc1 chosen contact points provided</technical_language>

Target:
public DefaultLoadBalancingPolicy(DriverContext context, String profileName) { this( getLocalDcFromConfig(context, profileName), getFilterFromConfig(context, profileName), context, profileName.equals(DriverConfigProfile.DEFAULT_NAME)); }