auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldReturnInternalServerError_ifGatewayErrors() { String externalChargeId = "external-charge-id"; GatewayError gatewayError = mock(GatewayError.class); GatewayResponse gatewayResponse = responseBuilder() .withGatewayError(gatewayError) .withSessionIdentifier("234") .build(); when(gatewayError.getErrorType()).thenReturn(GATEWAY_ERROR); when(gatewayError.getMessage()).thenReturn("oops"); when(mockedWalletAuthoriseService.doAuthorise(externalChargeId, googlePayAuthRequest)).thenReturn(gatewayResponse); Response authorisationResponse = googlePayService.authorise(externalChargeId, googlePayAuthRequest); verify(mockedWalletAuthoriseService).doAuthorise(externalChargeId, googlePayAuthRequest); assertThat(authorisationResponse.getStatus(), is(500)); ErrorResponse response = (ErrorResponse)authorisationResponse.getEntity(); <START> MatcherAssert.assertThat(response.getMessages(), contains("oops")); <END> }</code><technical_language>this</technical_language>

Target:
public void shouldReturnInternalServerError_ifGatewayErrors() { String externalChargeId = "external-charge-id"; GatewayError gatewayError = mock(GatewayError.class); GatewayResponse gatewayResponse = responseBuilder() .withGatewayError(gatewayError) .withSessionIdentifier("234") .build(); when(gatewayError.getErrorType()).thenReturn(GATEWAY_ERROR); when(gatewayError.getMessage()).thenReturn("oops"); when(mockedWalletAuthoriseService.doAuthorise(externalChargeId, googlePayAuthRequest)).thenReturn(gatewayResponse); Response authorisationResponse = googlePayService.authorise(externalChargeId, googlePayAuthRequest); verify(mockedWalletAuthoriseService).doAuthorise(externalChargeId, googlePayAuthRequest); assertThat(authorisationResponse.getStatus(), is(500)); ErrorResponse response = (ErrorResponse)authorisationResponse.getEntity(); assertThat(response.getMessages(), contains("oops")); }
Source:
<code>public Volume buildVolume(String volumeName) { return new VolumeBuilder() .withName(volumeName) <START> .withNewSecret().withSecretName(getSecretName()).withDefaultMode(Integer.parseInt(defaultMode)).endSecret() <END> .build(); }</code><technical_language>This Github's rendering, this line a tad bit long</technical_language>

Target:
public Volume buildVolume(String volumeName) { SecretVolumeSource secretVolumeSource = new SecretVolumeSource(); secretVolumeSource.setSecretName(getSecretName()); if (StringUtils.isNotBlank(defaultMode)) { secretVolumeSource.setDefaultMode(Integer.parseInt(getDefaultMode())); } return new VolumeBuilder() .withName(volumeName) .withNewSecretLike(secretVolumeSource) .endSecret() .build(); }
Source:
<code>public Brokers getKafkaBrokers() { <START> return kafkaBrokerList; <END> }</code><technical_language>Immutable copy of</technical_language>

Target:
public List<Broker> getKafkaBrokers() { return kafkaBrokerList; }
Source:
<code>private List<NetworkAttachment> getAttachmentsWithMissingUpdatedDefaultRoute() { NetworkCluster currentDefaultRouteNetworkCluster = findCurrentDefaultRouteNetworkForCluster(); NetworkAttachment currentDefaultRouteNetworkAttachment = findAttachmentByNetworkClusterId(currentDefaultRouteNetworkCluster); VdsNetworkInterface previousDefaultRouteNic = findPreviousDefaultRouteNic(); NetworkAttachment previousDefaultRouteNetworkAttachment = findNetworkAttachmentByNetworkName(previousDefaultRouteNic, getExistingAttachments()); if (currentDefaultRouteNetworkAttachment != null && previousDefaultRouteNetworkAttachment != null && currentDefaultRouteNetworkAttachment.getId().equals(previousDefaultRouteNetworkAttachment.getId())) { return getParameters().getNetworkAttachments(); } List<NetworkAttachment> extendedAttachments = getParameters().getNetworkAttachments(); NetworkAttachment potentialyMissingAttachment = getPotentialyMissingAttachment( currentDefaultRouteNetworkCluster == null ? null : currentDefaultRouteNetworkCluster.getNetworkId(), currentDefaultRouteNetworkAttachment, previousDefaultRouteNetworkAttachment); addAttachmentIfMissing(potentialyMissingAttachment, extendedAttachments); <START> removeIpv6GatewayFromPreviousDefaultRouteAttachment(previousDefaultRouteNic, extendedAttachments); <END> return extendedAttachments; }</code><technical_language>Putting this call creates a side-effect in a method is collecting attachments</technical_language>

Target:
private List<NetworkAttachment> getAttachmentsWithMissingUpdatedDefaultRoute() { NetworkCluster currentDefaultRouteNetworkCluster = findCurrentDefaultRouteNetworkForCluster(); NetworkAttachment previousDefaultRouteNetworkAttachment = findNetworkAttachmentByNetworkName( findPreviousDefaultRouteNic(), getExistingAttachments()); return getAttachmentsWithMissingUpdatedDefaultRoute(currentDefaultRouteNetworkCluster, findAttachmentByNetworkClusterId(currentDefaultRouteNetworkCluster), previousDefaultRouteNetworkAttachment); }
Source:
<code>void setComposedTaskRunnerConfigurationProperties(ComposedTaskRunnerConfigurationProperties composedTaskRunnerConfigurationProperties) { <START> this.composedTaskRunnerConfigurationProperties = composedTaskRunnerConfigurationProperties; <END> }</code><technical_language>check for null here, package private</technical_language>

Target:
void setComposedTaskRunnerConfigurationProperties(ComposedTaskRunnerConfigurationProperties composedTaskRunnerConfigurationProperties) { if (composedTaskRunnerConfigurationProperties != null) { this.composedTaskRunnerConfigurationProperties = composedTaskRunnerConfigurationProperties; } }
Source:
<code>private static void deleteChunks(ShardWriterDao dao, long commitId, long tableId, Set<Long> chunkIds) { int rows = dao.deleteChunks(commitId, chunkIds); verifyMetadata(rows == chunkIds.size(), "Wrong row count %s for delete of %s chunks", rows, chunkIds.size()); rows = dao.deleteIndexChunks(chunkIndexTable(tableId), chunkIds); <START> verifyMetadata(rows == chunkIds.size(), "Wrong row count %s for delete of %s index chunks", rows, chunkIds.size()); <END> }</code><technical_language>delete all, instead of setting end_commit_id. 2 cases issues: 1 ChunkSupplier.java line 105, getBucketChunks. called RaptorSplitManager.getSplits(), place for presto get chunks. If called in a transaction, good. if called once, fine. 2 DatabaseMetadataWriter.recover line 205 dao.rollbackDeletedIndexChunks(chunkIndexTable(tableId), commitId); filters end_commit_id. rollback of delete, rollback chunks, index not, index is chunks</technical_language>

Target:
private static void deleteChunks(ShardWriterDao dao, long commitId, long tableId, Set<Long> chunkIds) { int rows = dao.deleteChunks(commitId, chunkIds); verifyMetadata(rows == chunkIds.size(), "Wrong row count %s for delete of %s chunks", rows, chunkIds.size()); rows = dao.deleteIndexChunks(chunkIndexTable(tableId), commitId, chunkIds); verifyMetadata(rows == chunkIds.size(), "Wrong row count %s for delete of %s index chunks", rows, chunkIds.size()); }
Source:
<code>public void run() { <START> final int loginterval = 1000; <END> int count = 0; while (!testContext.isStopped()) { final IMap map = targetInstance.getMap(basename); map.put(keyCounter.getAndAdd(1), "test value"); if (count % loginterval == 0) { log.info("Map size: " + map.size()); } } }</code><technical_language>please logInterval a public property, too</technical_language>

Target:
public void run() { IMap<Object, Object> map = targetInstance.getMap(basename); MapConfig mapConfig = targetInstance.getConfig().getMapConfig(basename); while (!testContext.isStopped()) { long keycounter = keyCounter.incrementAndGet(); map.put(keycounter, "test value"); if (keycounter % logInterval == 0) { log.info("Iteration: " + keycounter + ". Map size: " + map.size() + " max per node is: " + maxMapSize); } } }
Source:
<code>public static NIOKieMavenCompiler getCompiler(KieDecorator decorator) { <START> NIOKieMavenCompiler compiler = compilers.get(decorator); <END> if (compiler == null) { compiler = createAndAddNewCompiler(decorator); } return compiler; }</code><technical_language>decorator is of type KieDecorator, while map is Strings. missed decorator.name()</technical_language>

Target:
public static NIOKieMavenCompiler getCompiler(KieDecorator decorator) { NIOKieMavenCompiler compiler = compilers.get(decorator.name()); if (compiler == null) { compiler = createAndAddNewCompiler(decorator); } return compiler; }
Source:
<code>public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> resultList = new ArrayList<IPropertyDescriptor>(); PropertyDescriptor desc = new PropertyDescriptor( ConfigConstants.CONFIG_KEY_MERGE, "Upstream Branch"); <START> desc.setCategory("Upstream Configuration"); END> resultList.add(desc); desc = new PropertyDescriptor(ConfigConstants.CONFIG_KEY_REMOTE, "Remote"); desc.setCategory("Upstream Configuration"); resultList.add(desc); desc = new PropertyDescriptor(ConfigConstants.CONFIG_KEY_REBASE, "Rebase"); desc.setCategory("Upstream Configuration"); resultList.add(desc); return resultList.toArray(new IPropertyDescriptor[0]); }</code><technical_language>externalize strings</technical_language>

Target:
public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> resultList = new ArrayList<IPropertyDescriptor>(); PropertyDescriptor desc = new PropertyDescriptor( ConfigConstants.CONFIG_KEY_MERGE, UIText.BranchPropertySource_UpstreamBranchDescriptor); desc.setCategory(UIText.BranchPropertySource_UpstreamConfigurationCategory); resultList.add(desc); desc = new PropertyDescriptor(ConfigConstants.CONFIG_KEY_REMOTE, UIText.BranchPropertySource_RemoteDescriptor); desc.setCategory(UIText.BranchPropertySource_UpstreamConfigurationCategory); resultList.add(desc); desc = new PropertyDescriptor(ConfigConstants.CONFIG_KEY_REBASE, UIText.BranchPropertySource_RebaseDescriptor); desc.setCategory(UIText.BranchPropertySource_UpstreamConfigurationCategory); resultList.add(desc); return resultList.toArray(new IPropertyDescriptor[0]); }
Source:
<code>public void set(byte[] val, boolean delete) { if (buffer == null) { throw new IllegalStateException("Can not add to mutation after serializing it"); } <START> buffer.writeVLong(columnFamilyLength); <END> buffer.add(columnFamily, 0, columnFamilyLength); buffer.writeVLong(columnQualifierLength); buffer.add(columnQualifier, 0, columnQualifierLength); if (columnVisibility == null) { buffer.writeVLong(EMPTY_BYTES.length); buffer.add(EMPTY_BYTES, 0, EMPTY_BYTES.length); } else { buffer.writeVLong(columnVisibilityLength); buffer.add(columnVisibility, 0, columnVisibilityLength); } buffer.add(hasTs); if (hasTs) { buffer.writeVLong(timestamp); } buffer.add(delete); if (val.length < VALUE_SIZE_COPY_CUTOFF) { buffer.writeVLong(val.length); buffer.add(val, 0, val.length); } else { if (values == null) { values = new ArrayList<>(); } byte copy[] = new byte[val.length]; System.arraycopy(val, 0, copy, 0, val.length); values.add(copy); put(-1 * values.size()); } entries++; }</code><technical_language>private put(byte[], int) function called</technical_language>

Target:
private Mutation set(byte[] val, boolean delete) { if (buffer == null) { throw new IllegalStateException("Can not add to mutation after serializing it"); } put(columnFamily, columnFamilyLength); put(columnQualifier, columnQualifierLength); if (columnVisibility == null) { put(EMPTY_BYTES, EMPTY_BYTES.length); } else { put(columnVisibility, columnVisibilityLength); } put(hasTs); if (hasTs) { put(timestamp); } put(delete); if (val.length < VALUE_SIZE_COPY_CUTOFF) { put(val, val.length); } else { if (values == null) { values = new ArrayList<>(); } byte copy[] = new byte[val.length]; System.arraycopy(val, 0, copy, 0, val.length); values.add(copy); put(-1 * values.size()); } entries++; return Mutation.this; }
Source:
<code>public boolean contains(Module module, Flow flow) { <START> logger.info("Check contains: " + module + flow); <END> return this.cache.containsKey(module.getName()+flow.getName()); }</code><technical_language>debug</technical_language>

Target:
public boolean contains(Module module, Flow flow) { logger.debug("Check contains: " + module + flow); return this.cache.containsKey(module.getName()+flow.getName()); }
Source:
<code>protected DataStore<String, WebPage> createWebPageDataStore() throws IOException { <START> try { <END> return DataStoreFactory.getDataStore(String.class, WebPage.class, driver.getConfiguration()); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>This try/catch needed GoraException thrown getDataStore extends IOException :)</technical_language>

Target:
protected DataStore<String, WebPage> createWebPageDataStore() throws IOException { return DataStoreFactory.getDataStore(String.class, WebPage.class, driver.getConfiguration()); }
Source:
<code>public Collection<LocalIssuePointer> read(VirtualFile virtualFile) { <START> return cache.getOrDefault(virtualFile, loadToCache(virtualFile)); <END> }</code><technical_language>loadToCache(virtualFile) evaluated getOrDefault is called, defeating purpose</technical_language>

Target:
public synchronized Collection<LocalIssuePointer> read(VirtualFile virtualFile) { Collection<LocalIssuePointer> issues = cache.get(virtualFile); if (issues != null) { return issues; } return loadToCache(virtualFile); }
Source:
<code>public void testDateTimeChannelCalendarTimeZoneUpdate() { Configuration configuration = new Configuration(); configuration.put(NtpBindingConstants.PROPERTY_TIMEZONE, TEST_TIME_ZONE_ID); initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null); ZonedDateTime timeZoneIdFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME)) .getZonedDateTime(); ZoneOffset testZoneId; <START> <END> String timeZoneInConfiguration = (String) configuration.getProperties().get(NtpBindingConstants.PROPERTY_TIMEZONE); if (ZoneId.of(timeZoneInConfiguration).getRules().isDaylightSavings(timeZoneIdFromItemRegistry.toInstant())) { testZoneId = ZoneOffset.of("-07:00"); } else { testZoneId = ZoneOffset.of("-08:00"); } assertEquals(testZoneId, timeZoneIdFromItemRegistry.getOffset()); }</code><technical_language>@lpapazow need change DateTimeType UI interpretation of format, then? If ZoneId information of DateTimeType loss information, bugs other places sometime, too</technical_language>

Target:
public void testDateTimeChannelCalendarTimeZoneUpdate() { Configuration configuration = new Configuration(); configuration.put(NtpBindingConstants.PROPERTY_TIMEZONE, TEST_TIME_ZONE_ID); initialize(configuration, NtpBindingConstants.CHANNEL_DATE_TIME, ACCEPTED_ITEM_TYPE_DATE_TIME, null, null); ZonedDateTime timeZoneIdFromItemRegistry = ((DateTimeType) getItemState(ACCEPTED_ITEM_TYPE_DATE_TIME)) .getZonedDateTime(); ZoneOffset expectedOffset = ZoneId.of(TEST_TIME_ZONE_ID).getRules().getOffset(timeZoneIdFromItemRegistry.toInstant()); assertEquals(expectedOffset, timeZoneIdFromItemRegistry.getOffset()); }
Source:
<code>public RecordWriter<M, GenericWritable<M>> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException { Configuration conf = HadoopCompat.getConfiguration(job); String encoderClassName = conf.get(GENERIC_ENCODER_KEY); Class<?> typeRef = null; Class<?> encoderClazz = null; BinaryConverterProvider<?> converterProvider = null; try { String typeRefClass = conf.get(CLASS_CONF_KEY); typeRef = conf.getClassByName(typeRefClass); encoderClazz = conf.getClassByName(encoderClassName); <START> converterProvider = (BinaryConverterProvider<?>)encoderClazz.newInstance(); <END> } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException("failed to instantiate class '" + encoderClassName + "'", e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } BinaryConverter<?> converter = converterProvider.getConverter(conf); return new LzoBinaryBlockRecordWriter<M, GenericWritable<M>>(new BinaryBlockWriter( getOutputStream(job), typeRef, converter)); }</code><technical_language>ReflectionUtils.newInstance() (so if encoderClazz is configurable, called instantiation)</technical_language>

Target:
public RecordWriter<M, GenericWritable<M>> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException { Configuration conf = HadoopCompat.getConfiguration(job); String encoderClassName = conf.get(GENERIC_ENCODER_KEY); Class<?> valueClass = null; BinaryConverterProvider<?> converterProvider = null; try { String valueClassName = conf.get(CLASS_CONF_KEY); valueClass = conf.getClassByName(valueClassName); converterProvider = (BinaryConverterProvider<?>) ReflectionUtils.newInstance( conf.getClassByName(encoderClassName), conf); } catch (ClassNotFoundException e) { throw new RuntimeException("failed to instantiate class '" + encoderClassName + "'", e); } BinaryConverter<?> converter = converterProvider.getConverter(conf); return new LzoBinaryBlockRecordWriter<M, GenericWritable<M>>(new BinaryBlockWriter( getOutputStream(job), valueClass, converter)); }
Source:
<code>private void configureLockFileActions(File sandboxDir) { Task runIdeTask = project.getTasks().findByPath("runIde"); if (runIdeTask == null) throw new GradleException("Unable to find the task 'runIde' of the intellij plugin"); runIdeTask.doFirst( (Task t) -> { try { <START> sandboxDir.mkdirs(); <END> File lockFile = getLockFile(sandboxDir); boolean createdNewFile = lockFile.createNewFile(); if (!createdNewFile) throw new GradleException( "Lock file " + lockFile.getAbsolutePath() + " already exists!"); } catch (IOException e) { throw new GradleException("Unable to lock sandbox: " + sandboxDir.getAbsolutePath(), e); } }); runIdeTask.doLast( (Task t) -> { File lockFile = getLockFile(sandboxDir); boolean deleted = lockFile.delete(); if (!deleted) throw new GradleException("Failed to delete lock file: " + lockFile.getAbsolutePath()); }); }</code><technical_language>I this issue holds. mkdirs() method throw exception fails returns false. This case handled correctly rely parent directory existing for rest of logic</technical_language>

Target:
private void configureLockFileActions(File sandboxDir) { Task runIdeTask = project.getTasks().findByPath("runIde"); if (runIdeTask == null) throw new GradleException("Unable to find the task 'runIde' of the intellij plugin"); runIdeTask.doFirst( (Task t) -> { try { if (!sandboxDir.exists() && !sandboxDir.mkdirs()) { throw new GradleException( "Unable to create the sandbox directory: " + sandboxDir.getAbsolutePath()); } File lockFile = getLockFile(sandboxDir); boolean createdNewFile = lockFile.createNewFile(); if (!createdNewFile) throw new GradleException( "Lock file " + lockFile.getAbsolutePath() + " already exists!"); } catch (IOException e) { throw new GradleException("Unable to lock sandbox: " + sandboxDir.getAbsolutePath(), e); } }); runIdeTask.doLast( (Task t) -> { File lockFile = getLockFile(sandboxDir); if (!lockFile.delete()) throw new GradleException("Failed to delete lock file: " + lockFile.getAbsolutePath()); }); }
Source:
<code>public void monitor() throws Exception { File localStoreDir = new File(config.getLocalStoreBaseDir()); Preconditions.checkState(localStoreDir.isDirectory(), String.format("LocalStoreDir: %s is not a directory", localStoreDir.getAbsolutePath())); String localHostName = InetAddress.getLocalHost().getHostName(); for (JobInstance jobInstance : getHostAffinityEnabledJobs(localStoreDir)) { File jobDir = new File(localStoreDir, String.format("%s-%s", jobInstance.getJobName(), jobInstance.getJobId())); try { JobStatus jobStatus = jobsClient.getJobStatus(jobInstance); for (Task task : jobsClient.getTasks(jobInstance)) { for (String storeName : jobDir.list(DirectoryFileFilter.DIRECTORY)) { <START> LOG.info("Job: has the running status: with preferred host: {}", jobInstance, jobStatus, task.getPreferredHost()); <END> if (jobStatus.hasBeenStarted() && task.getStoreNames().contains(storeName) && task.getPreferredHost().equals(localHostName)) { LOG.info(String.format("Store %s is actively used by the task: %s.", storeName, task.getTaskName())); } else { LOG.info(String.format("Store %s not used by the task: %s.", storeName, task.getTaskName())); markSweepTaskStore(TaskStorageManager.getStorePartitionDir(jobDir, storeName, new TaskName(task.getTaskName()))); } } } } catch (Exception ex) { if (!config.getIgnoreFailures()) { throw ex; } LOG.warn("Local store cleanup for job: resulted in exception: {}. Config: turned on, failures are ignored.", new Object[]{jobInstance, ex, LocalStoreMonitorConfig.CONFIG_IGNORE_FAILURES}); } } }</code><technical_language>Nitpitck: Single space {}</technical_language>

Target:
public void monitor() throws Exception { File localStoreDir = new File(config.getLocalStoreBaseDir()); Preconditions.checkState(localStoreDir.isDirectory(), String.format("LocalStoreDir: %s is not a directory", localStoreDir.getAbsolutePath())); String localHostName = InetAddress.getLocalHost().getHostName(); for (JobInstance jobInstance : getHostAffinityEnabledJobs(localStoreDir)) { File jobDir = new File(localStoreDir, String.format("%s-%s", jobInstance.getJobName(), jobInstance.getJobId())); try { JobStatus jobStatus = jobsClient.getJobStatus(jobInstance); for (Task task : jobsClient.getTasks(jobInstance)) { for (String storeName : jobDir.list(DirectoryFileFilter.DIRECTORY)) { LOG.info("Job: has the running status: with preferred host: {}.", jobInstance, jobStatus, task.getPreferredHost()); if (jobStatus.hasBeenStarted() && task.getStoreNames().contains(storeName) && task.getPreferredHost().equals(localHostName)) { LOG.info(String.format("Store %s is actively used by the task: %s.", storeName, task.getTaskName())); } else { LOG.info(String.format("Store %s not used by the task: %s.", storeName, task.getTaskName())); markSweepTaskStore(TaskStorageManager.getStorePartitionDir(jobDir, storeName, new TaskName(task.getTaskName()))); } } } } catch (Exception ex) { if (!config.getIgnoreFailures()) { throw ex; } LOG.warn("Config: turned on, failures will be ignored. Local store cleanup for job: resulted in exception: {}.", new Object[]{LocalStoreMonitorConfig.CONFIG_IGNORE_FAILURES, jobInstance, ex}); } } }
Source:
<code>public Optional<T> cycleNext() { T[] constants = this.enumClass.getEnumConstants(); <START> if (constants.length == 0) { <END> return Optional.empty(); } int index; if (this.value == null) { index = 0; } else { index = this.value.ordinal() + 1; if (index >= constants.length) { index = 0; } } return Optional.of(constants[index]); }</code><technical_language>sense for setting options, this a precondition in object. means remove Optional return CycleableSettingValue#cycleNext. If cycle something, a valid setting option</technical_language>

Target:
public T cycleNext() { T[] constants = this.enumClass.getEnumConstants(); int index; if (this.value == null) { index = 0; } else { index = this.value.ordinal() + 1; if (index >= constants.length) { index = 0; } } return constants[index]; }
Source:
<code>public static synchronized FlurryAgentWrapper getInstance() { if (sWrapper == null) { <START> sWrapper = new FlurryAgentWrapper(); <END> } return sWrapper; }</code><technical_language>sWrapper volatile, method is synchronized, sWrapper thread-local</technical_language>

Target:
public static FlurryAgentWrapper getInstance() { return FlurryAgentLoader.INSTANCE; }
Source:
<code>public Object[] transform(final String value) { switch (_removedMatches) { case LIST: return transform2(value); default: <START> return transformDefault(value); <END> } }</code><technical_language>logic for (value dictionary matches) is duplicated code. a shared codebase handle a match-list differently. branch out top level of transform-method (maybe more) ways of dealing "Removed matches"</technical_language>

Target:
public Object[] transform(final String value) { final List<String> removedParts = new ArrayList<>(2); final StringBuilder survivorString = new StringBuilder(); if (!Strings.isNullOrEmpty(value)) { final Iterable<String> tokens = SPLITTER.split(value); for (String token : tokens) { if (!dictionaryConnection.containsValue(token)) { if (survivorString.length() != 0) { survivorString.append(' '); } survivorString.append(token); } else { removedParts.add(token); } } } switch (_removedMatchesType) { case STRING: final String removedPartsString = Joiner.on(' ').join(removedParts); return new String[] { survivorString.toString(), removedPartsString }; case LIST: return new Object[] { survivorString.toString(), removedParts }; default: throw new UnsupportedOperationException("Unsupported output type: " + _removedMatchesType); } }
Source:
<code>public static void main(String[] args) throws Exception { <START> System.out.println("Camel is started. Ready to run Any23 example!"); <END> CamelContext context = new DefaultCamelContext(); context.start(); context.addRoutes(new Any23RouteBuilder()); context.addStartupListener(new Any23StartupMessage()); }</code><technical_language>is a bit nitpicking, Camel is started time of this message :-)</technical_language>

Target:
public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); context.addRoutes(new Any23RouteBuilder()); context.start(); context.addStartupListener(new Any23StartupMessage()); }
Source:
<code>public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; initialSize = 0; } else { sizeCalculator = i -> offHeapEntryFactory.getSize(i); <START> initialSize = memoryAddressCount * 8; <END> currentSize = initialSize; } this.lruLock = new ReentrantLock(); firstAddress = 0; }</code><technical_language><< 3 match MemoryAddressHash</technical_language>

Target:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; initialSize = 0; } else { sizeCalculator = i -> offHeapEntryFactory.getSize(i); initialSize = UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(memoryAddressCount << 3); currentSize = initialSize; } this.lruLock = new ReentrantLock(); firstAddress = 0; }
Source:
<code>public DefaultOCFLObjectSessionFactory( @Value("#{ocflPropsConfig.fedoraOcflStaging}") final Path ocflStagingDir) { <START> LOGGER.info("Fedora OCFL persistence staging directory:\n- {}", <END> ocflStagingDir); try { this.ocflStagingDir = Files.createDirectories(ocflStagingDir); } catch (IOException e) { throw new UncheckedIOException(e); } }</code><technical_language>reduce this logging debug, in favor of cleaner output of OcflPropsConfig</technical_language>

Target:
public DefaultOCFLObjectSessionFactory( @Value("#{ocflPropsConfig.fedoraOcflStaging}") final Path ocflStagingDir) { LOGGER.debug("Fedora OCFL persistence staging directory:\n- {}", ocflStagingDir); try { this.ocflStagingDir = Files.createDirectories(ocflStagingDir); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
<code><START> public File captureWebElement(String path, WebElement element, WebDriver driver) { <END> File screen = ((TakesScreenshot) driver) .getScreenshotAs(OutputType.FILE); Point p = element.getLocation(); int width = element.getSize().getWidth(); int height = element.getSize().getHeight(); Rectangle rect = new Rectangle(width, height); BufferedImage img = null; File subImg = new File(path); try { img = ImageIO.read(screen); } catch (IOException e){ throw new RuntimeException(e); } BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height); try { ImageIO.write(dest, "png", subImg); } catch (IOException e) { throw new RuntimeException(e); } return subImg; }</code><technical_language>please describe method does, i get name</technical_language>

Target:
public File captureWebElement(String path, WebElement element, WebDriver driver) { File screen = capturePage(driver); Point p = element.getLocation(); int width = element.getSize().getWidth(); int height = element.getSize().getHeight(); Rectangle rect = new Rectangle(width, height); BufferedImage img = null; File subImg = new File(path); try { img = ImageIO.read(screen); } catch (IOException e){ throw new RuntimeException(e); } BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height); try { ImageIO.write(dest, "png", subImg); } catch (IOException e) { throw new RuntimeException(e); } return subImg; }
Source:
<code>private static boolean checkImagesLocked(VM vm, List<String> messages, List<DiskImage> images) { boolean returnValue = true; List<String> lockedDisksAliases = new ArrayList<String>(); for (DiskImage diskImage : images) { if (diskImage.getimageStatus() == ImageStatus.LOCKED) { lockedDisksAliases.add(diskImage.getDiskAlias()); returnValue = false; } } <START> <END> ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED.toString()); messages.add(String.format("$%1$s %2$s", "diskAliases", StringUtils.join(lockedDisksAliases, ", "))); if (returnValue && vm.getstatus() == VMStatus.ImageLocked) { ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_LOCKED.toString()); returnValue = false; } return returnValue; }</code><technical_language>this message added in case</technical_language>

Target:
private static boolean checkImagesLocked(VM vm, List<String> messages, List<DiskImage> images) { boolean returnValue = true; List<String> lockedDisksAliases = new ArrayList<String>(); for (DiskImage diskImage : images) { if (diskImage.getimageStatus() == ImageStatus.LOCKED) { lockedDisksAliases.add(diskImage.getDiskAlias()); returnValue = false; } } if (lockedDisksAliases.size() > 0) { ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED.toString()); messages.add(String.format("$%1$s %2$s", "diskAliases", StringUtils.join(lockedDisksAliases, ", "))); } if (returnValue && vm.getstatus() == VMStatus.ImageLocked) { ListUtils.nullSafeAdd(messages, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_LOCKED.toString()); returnValue = false; } return returnValue; }
Source:
<code>EJBReceiver getEJBReceiver(final Collection<String> excludedNodeNames, final String appName, final String moduleName, final String distinctName) { final Iterator<EJBReceiver> iterator = getEJBReceivers(appName, moduleName, distinctName).iterator(); if (!iterator.hasNext()) { return null; } final Map<String, EJBReceiver> eligibleReceivers = new HashMap<String, EJBReceiver>(); while (iterator.hasNext()) { final EJBReceiver receiver = iterator.next(); final String nodeName = receiver.getNodeName(); if (excludedNodeNames != null && excludedNodeNames.contains(nodeName)) { <START> logger.debug(nodeName + " has been asked to be excluded from handling appname=" + appName + ",modulename=" + moduleName + <END> ",distinctname=" + distinctName); continue; } eligibleReceivers.put(receiver.getNodeName(), receiver); } if (eligibleReceivers.isEmpty()) { return null; } final String selectedNode = this.deploymentNodeSelector.selectNode(eligibleReceivers.keySet().toArray(new String[eligibleReceivers.size()]), appName, moduleName, distinctName); logger.debug(this.deploymentNodeSelector + " deployment node selector selected " + selectedNode + " node for appname=" + appName + ",modulename=" + moduleName + ",distinctname=" + distinctName); if (selectedNode == null || selectedNode.trim().isEmpty() || !eligibleReceivers.containsKey(selectedNode)) { logger.debug("Selected node " + selectedNode + " doesn't belong to eligible receivers. Continuing with a random eligible receiver"); return iterator.next(); } return eligibleReceivers.get(selectedNode); }</code><technical_language>debugf avoid string concat cost in non-debug case</technical_language>

Target:
EJBReceiver getEJBReceiver(final Collection<String> excludedNodeNames, final String appName, final String moduleName, final String distinctName) { final Iterator<EJBReceiver> iterator = getEJBReceivers(appName, moduleName, distinctName).iterator(); if (!iterator.hasNext()) { return null; } final Map<String, EJBReceiver> eligibleReceivers = new HashMap<String, EJBReceiver>(); while (iterator.hasNext()) { final EJBReceiver receiver = iterator.next(); final String nodeName = receiver.getNodeName(); if (excludedNodeNames != null && excludedNodeNames.contains(nodeName)) { logger.debugf("%s has been asked to be excluded from handling appName=%s, moduleName=%s=, distinctName=%s", nodeName, appName, moduleName, distinctName); continue; } eligibleReceivers.put(receiver.getNodeName(), receiver); } if (eligibleReceivers.isEmpty()) { return null; } final String selectedNode = this.deploymentNodeSelector.selectNode(eligibleReceivers.keySet().toArray(new String[eligibleReceivers.size()]), appName, moduleName, distinctName); logger.debugf("%s deployment node selector selected %s node for appname=%s, modulename=%s, distinctName=%s", this.deploymentNodeSelector, selectedNode, appName, moduleName, distinctName); if (selectedNode == null || selectedNode.trim().isEmpty() || !eligibleReceivers.containsKey(selectedNode)) { logger.debugf("Selected node %s doesn't belong to eligible receivers. Continuing with a random eligible receiver", selectedNode); return iterator.next(); } return eligibleReceivers.get(selectedNode); }
Source:
<code>public static boolean hasColorFromNBT(ItemStack stack) { return !stack.hasTagCompound() || !stack.getTagCompound().hasKey(ITEM_DISPLAY) || !stack.getTagCompound().getCompoundTag(ITEM_DISPLAY).hasKey(ITEM_COLOR); <START> } <END></code><technical_language>remove ! replace || && else a color if stack a tagCompound</technical_language>

Target:
public static boolean hasColorFromNBT(ItemStack stack) { return stack.hasTagCompound() && stack.getTagCompound().hasKey(ITEM_DISPLAY) && stack.getTagCompound().getCompoundTag(ITEM_DISPLAY).hasKey(ITEM_COLOR); }
Source:
<code>private boolean isInputStreamValid() throws IOException { <START> if (in.available()>0) <END> return true; else return false; }</code><technical_language>Please, braces, for one-liners. please change this pull</technical_language>

Target:
private boolean isInputStreamValid() throws IOException { if (in.available() > 0) { return true; } else { return false; } }
Source:
<code>public ValidationResult validate(Object value) { Long <START> longValue = <END> tryParseLong(value); if (longValue == 0) { return ValidationResult.ok(); } if (getMaximum() <= 0) { String msg = ConstantsManager.getInstance().getConstants().diskMaxSizeReached(); return ValidationResult.fail(msg); } return super.validate(value); }</code><technical_language>nan</technical_language>

Target:
public ValidationResult validate(Object value) { Integer intValue = Integer.valueOf((String) value); if (intValue == 0) { return ValidationResult.ok(); } if (getMaximum() <= 0) { String msg = ConstantsManager.getInstance().getConstants().diskMaxSizeReached(); return ValidationResult.fail(msg); } return super.validate(value); }
Source:
<code>private Method matchMethod(Method invokedMethod) { if (invokedMethod.getDeclaringClass().isInterface()) { for (Method beanMethod : proxyFactory.getCachedMethods()) { if (MethodIdentifier.getIdentifierForMethod(beanMethod).equals(MethodIdentifier.getIdentifierForMethod(invokedMethod))) { return beanMethod; } <START> } <END> throw Assert.unreachableCode(); } else { return invokedMethod; } }</code><technical_language>This is request path optimized a single map lookup</technical_language>

Target:
private Method matchMethod(Method invokedMethod) { if (invokedMethod.getDeclaringClass().isInterface()) { return invokedMethodToCached.computeIfAbsent(invokedMethod, method -> { for (Method m : proxyFactory.getCachedMethods()) { if (MethodIdentifier.getIdentifierForMethod(m).equals(MethodIdentifier.getIdentifierForMethod(method))) { return m; } } throw Assert.unreachableCode(); }); } else { return invokedMethod; } }
Source:
<code>public JobModel getJobModel() { SystemAdmins systemAdmins = new SystemAdmins(config); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 5000, SystemClock.instance()); systemAdmins.start(); try { String containerId = Integer.toString(config.getInt(JobConfig.PROCESSOR_ID())); <START> GrouperContext grouperContext = new GrouperContext(ImmutableMap.of(String.valueOf(containerId), locationId), new HashMap<>(), new HashMap<>(), new HashMap<>()); <END> return JobModelManager.readJobModel(this.config, Collections.emptyMap(), streamMetadataCache, grouperContext); } finally { systemAdmins.stop(); } }</code><technical_language>Collections.emptyMap() (to consistent)</technical_language>

Target:
public JobModel getJobModel() { SystemAdmins systemAdmins = new SystemAdmins(config); StreamMetadataCache streamMetadataCache = new StreamMetadataCache(systemAdmins, 5000, SystemClock.instance()); systemAdmins.start(); try { String containerId = Integer.toString(config.getInt(JobConfig.PROCESSOR_ID())); GrouperMetadata grouperMetadata = new GrouperMetadataImpl(ImmutableMap.of(String.valueOf(containerId), locationId), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap()); return JobModelManager.readJobModel(this.config, Collections.emptyMap(), streamMetadataCache, grouperMetadata); } finally { systemAdmins.stop(); } }
Source:
<code>public void deleteSubscription(final String subscriptionId) throws DbWriteOperationsBlockedException, NoSuchSubscriptionException, NoSuchEventTypeException, ServiceTemporarilyUnavailableException { if (featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.DISABLE_DB_WRITE_OPERATIONS)) { throw new DbWriteOperationsBlockedException("Cannot delete subscription: write operations on DB " + "are blocked by feature flag."); } try { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); authorizationValidator.authorizeSubscriptionAdmin(subscription); subscriptionRepository.deleteSubscription(subscriptionId); final ZkSubscriptionClient zkSubscriptionClient = subscriptionClientFactory.createClient( subscription, LogPathBuilder.build(subscriptionId, "delete_subscription")); zkSubscriptionClient.deleteSubscription(); nakadiKpiPublisher.publish(subLogEventType, () -> new JSONObject() .put("subscription_id", subscriptionId) .put("status", "deleted")); return; } catch (final InternalNakadiException e) { LOG.error("Exception can not occur", e); <START> throw e; <END> } }</code><technical_language>do need this catch block</technical_language>

Target:
public void deleteSubscription(final String subscriptionId) throws DbWriteOperationsBlockedException, NoSuchSubscriptionException, NoSuchEventTypeException, ServiceTemporarilyUnavailableException, InternalNakadiException { if (featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.DISABLE_DB_WRITE_OPERATIONS)) { throw new DbWriteOperationsBlockedException("Cannot delete subscription: write operations on DB " + "are blocked by feature flag."); } final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); authorizationValidator.authorizeSubscriptionAdmin(subscription); subscriptionRepository.deleteSubscription(subscriptionId); final ZkSubscriptionClient zkSubscriptionClient = subscriptionClientFactory.createClient( subscription, LogPathBuilder.build(subscriptionId, "delete_subscription")); zkSubscriptionClient.deleteSubscription(); nakadiKpiPublisher.publish(subLogEventType, () -> new JSONObject() .put("subscription_id", subscriptionId) .put("status", "deleted")); }
Source:
<code>@Override public boolean canHandleRequest(@NonNull Request data) { final Uri uri = data.uri; <START> if (uri == null) return false; <END> return (SCHEME_CONTENT.equals(uri.getScheme()) && MediaStore.AUTHORITY.equals(uri.getAuthority())); }</code><technical_language>Merge return</technical_language>

Target:
@Override public boolean canHandleRequest(@NonNull Request data) { final Uri uri = data.uri; return uri != null && SCHEME_CONTENT.equals(uri.getScheme()) && MediaStore.AUTHORITY.equals(uri.getAuthority()); }
Source:
<code>private static Set<Type> thrownExceptionsFromBody(MethodTree methodTree) { BlockTree block = methodTree.block(); if (block != null) { MethodInvocationVisitor visitor = new MethodInvocationVisitor(); block.accept(visitor); Set<Type> thrownExceptions = visitor.thrownExceptions(); <START> if (thrownExceptions != null && methodTree.is(Tree.Kind.CONSTRUCTOR) && !visitor.visitedSuper) { <END> Optional<Symbol.MethodSymbol> constructor = getImplicitlyCalledConstructor(methodTree); constructor.ifPresent(c -> thrownExceptions.addAll(c.thrownTypes())); } return thrownExceptions; } return null; }</code><technical_language>need this. II prefer logic of collecting exceptions hidden in visitor. handling this case in MethodInvocationVisitor then? perfectly give symbol of current methodTree parameter of MethodInvocationVisitor constructor, lose info calling. end of visit, simply add thrown exception default super constructor, if super called a constructor</technical_language>

Target:
private static Set<Type> thrownExceptionsFromBody(MethodTree methodTree) { BlockTree block = methodTree.block(); if (block != null) { MethodInvocationVisitor visitor = new MethodInvocationVisitor(methodTree); block.accept(visitor); return visitor.thrownExceptions(); } return null; }
Source:
<code>public Mail retrieve(String key) throws MessagingException { try { Mail mc; try { mc = (Mail) objectRepository.get(key); } catch (RuntimeException re) { StringBuilder exceptionBuffer = new StringBuilder(128); if (re.getCause() instanceof Error) { exceptionBuffer.append("Error when retrieving mail, not deleting: ").append(re.toString()); } else { exceptionBuffer.append("Exception retrieving mail: ").append(re.toString()).append(", so we're deleting it."); remove(key); } final String errorMessage = exceptionBuffer.toString(); LOGGER.warn(errorMessage, re); return null; } MimeMessageStreamRepositorySource source = new MimeMessageStreamRepositorySource(streamRepository, destination, key); mc.setMessage(new MimeMessageCopyOnWriteProxy(source)); return mc; } catch (Exception me) { <START> LOGGER.error("Exception retrieving mail: {}", me.toString()); <END> throw new MessagingException("Exception while retrieving mail: " + me.getMessage(), me); } }</code><technical_language>LOGGER.error("Exception retrieving mail", me); Overwize swallow stacktrace</technical_language>

Target:
public Mail retrieve(String key) throws MessagingException { try { Mail mc; try { mc = (Mail) objectRepository.get(key); } catch (RuntimeException re) { if (re.getCause() instanceof Error) { LOGGER.warn("Error when retrieving mail, not deleting: {}", re, re); } else { LOGGER.warn("Exception retrieving mail: {}, so we're deleting it.", re, re); remove(key); } return null; } MimeMessageStreamRepositorySource source = new MimeMessageStreamRepositorySource(streamRepository, destination, key); mc.setMessage(new MimeMessageCopyOnWriteProxy(source)); return mc; } catch (Exception me) { LOGGER.error("Exception retrieving mail", me); throw new MessagingException("Exception while retrieving mail: " + me.getMessage(), me); } }
Source:
<code>private void adjustBound(SyncPoint[] line, LinkedList<SyncPoint> otherBoundList, int inversionFactor) { int i = 0; SyncPoint minPoint = null, nextPoint; boolean finishedSearch = false; <START> i = Math.max(0, otherBoundList.indexOf(line[0])); <END> while ((i < otherBoundList.size() - 1) && !finishedSearch) { minPoint = otherBoundList.get(i); nextPoint = otherBoundList.get(i + 1); if (minPoint.crossProduct(nextPoint, line[1]) * inversionFactor > 0) { if (nextPoint.getTimeX() < line[1].getTimeX()) { i++; } else { line[0] = null; finishedSearch = true; } } else { line[0] = minPoint; finishedSearch = true; } } if (line[0] == null) { line[0] = minPoint; } if ((line[0] != null) && (line[0].getTimeX() > line[1].getTimeX())) { line[0] = null; } }</code><technical_language>do int i this line</technical_language>

Target:
private void adjustBound(SyncPoint[] line, LinkedList<SyncPoint> otherBoundList, int inversionFactor) { SyncPoint minPoint = null, nextPoint; boolean finishedSearch = false; int i = Math.max(0, otherBoundList.indexOf(line[0])); while ((i < otherBoundList.size() - 1) && !finishedSearch) { minPoint = otherBoundList.get(i); nextPoint = otherBoundList.get(i + 1); if (minPoint.crossProduct(nextPoint, line[1]) * inversionFactor > 0) { if (nextPoint.getTimeX() < line[1].getTimeX()) { i++; } else { line[0] = null; finishedSearch = true; } } else { line[0] = minPoint; finishedSearch = true; } } if (line[0] == null) { line[0] = minPoint; } if ((line[0] != null) && (line[0].getTimeX() > line[1].getTimeX())) { line[0] = null; } }
Source:
<code>public static Map<String, String> getDefaultHeaders(String serviceName, String serviceVersion, String operationId) { Map<String, String> headers = new HashMap<>(); String sdkAnalyticsHeaderValue = String.format( "service_name=%s;service_version=%s;operation_id=%s", serviceName, serviceVersion, operationId ); headers.put(HttpHeaders.X_IBMCLOUD_SDK_ANALYTICS, sdkAnalyticsHeaderValue); <START> headers.put(HttpHeaders.USER_AGENT, getUserAgent()); <END> return headers; }</code><technical_language>technically speaking... :) user agent header stored in a static field computed time getDefaultHeaders() is called. performance difference is negligible, I stop mentioning :)</technical_language>

Target:
public static Map<String, String> getDefaultHeaders(String serviceName, String serviceVersion, String operationId) { Map<String, String> headers = new HashMap<>(); String sdkAnalyticsHeaderValue = String.format( "service_name=%s;service_version=%s;operation_id=%s", serviceName, serviceVersion, operationId ); headers.put(WatsonHttpHeaders.X_IBMCLOUD_SDK_ANALYTICS, sdkAnalyticsHeaderValue); headers.put(HttpHeaders.USER_AGENT, getUserAgent()); return headers; }
Source:
<code>protected AdditionalInitialization createAdditionalInitialization() { <START> return UndertowSubsystem100TestCase.DEFAULT; <END> }</code><technical_language>Access static fields directly, e.g. AbstractUndertowSubsystemTestCase.DEFAULT</technical_language>

Target:
protected AdditionalInitialization createAdditionalInitialization() { return AbstractUndertowSubsystemTestCase.DEFAULT; }