auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private double getHeightAt(BufferedImage image, int x, int y) { int rgb = image.getRGB(x, y); int red = rgb >>> 16 & 0xFF; int green = rgb >>> 8 & 0xFF; int blue = rgb & 0xFF; <START> if (red == 0 && green == 0 && blue == 0) { <END> return 0; } double scale = (red + blue + green) / 3D / 255D; return scale * intensity; }</code><technical_language>Is a reason for this short circuit? I nit-picking here, I feel this "slower" it, due extra complexity preventing JVM optimisations</technical_language>

Target:
private double getHeightAt(BufferedImage image, int x, int y) { int rgb = image.getRGB(x, y); if (rgb == 0) { return 0; } int red = rgb >>> 16 & 0xFF; int green = rgb >>> 8 & 0xFF; int blue = rgb & 0xFF; double scale = (red + blue + green) / 3D / 255D; return scale * intensity; }
Source:
<code>public DroolsFilterUniConstraintStream(DroolsConstraintFactory<Solution_> constraintFactory, DroolsAbstractUniConstraintStream<Solution_, A> parent, Predicate<A> predicate) { <START> super(constraintFactory, parent.getAnchor().filter(predicate)); <END> this.parent = parent; }</code><technical_language>ow, this dangerous. need bluejeans discuss</technical_language>

Target:
public DroolsFilterUniConstraintStream(DroolsConstraintFactory<Solution_> constraintFactory, DroolsAbstractUniConstraintStream<Solution_, A> parent, Predicate<A> predicate) { super(constraintFactory); this.parent = parent; this.predicate = predicate; }
Source:
<code>public File getOutputFileToWrite(Obs obs) throws IOException { String title = obs.getComplexData().getTitle(); String extension = FilenameUtils.getExtension(title); File dir = OpenmrsUtil.getDirectoryInApplicationDataDirectory(Context.getAdministrationService().getGlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_COMPLEX_OBS_DIR)); File outputfile = null; String uuid = obs.getUuid(); if (null == title) { String now = longfmt.format(new Date()); outputfile = new File(dir, now + '_' + uuid); } else { <START> if (!(extension.equals(""))) { <END> extension = "." + extension; } String titleWithoutExtension = title.replace(extension, ""); outputfile = new File(dir, titleWithoutExtension + '_' + uuid + extension); } return outputfile; }</code><technical_language>I is safer do reverse (just hedge NPE): java if (!("".equals(extension))) simply java if (!StringUtils.isEmpty(extension))</technical_language>

Target:
public File getOutputFileToWrite(Obs obs) throws IOException { String title = obs.getComplexData().getTitle(); String titleWithoutExtension = FilenameUtils.removeExtension(title); String extension = "." + StringUtils.defaultIfEmpty(FilenameUtils.getExtension(title), "dat"); String uuid = obs.getUuid(); String filename; if (StringUtils.isNotBlank(titleWithoutExtension)) { filename = titleWithoutExtension + "_" + uuid + extension; } else { filename = uuid + extension; } File dir = OpenmrsUtil.getDirectoryInApplicationDataDirectory( Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_COMPLEX_OBS_DIR)); File outputfile = new File(dir, filename); return outputfile; }
Source:
<code>public Object[] getFiniteSupport() { checkHasParams(); <START> return null; <END> }</code><technical_language>@datang1992 another thought, do 0 x (where p(x) is close zero)</technical_language>

Target:
public Object[] getFiniteSupport() { if (finiteSupport == null) { checkHasParams(); int supportSize = 0; while (!Util.closeToZero(getProb(supportSize))) supportSize++; finiteSupport = new Object[supportSize]; for (int i = 0; i < supportSize; i++) finiteSupport[i] = i; } return finiteSupport; }
Source:
<code>public @NotNull Builder setTransportHeaders(Map<String, String> transportHeaders) { <START> if (transportHeaders == null) { <END> throw new NullPointerException("`transportHeaders` cannot be null"); } this.transportHeaders = transportHeaders; return this; }</code><technical_language>need for manual check (especially for unannotated parameter)</technical_language>

Target:
public @NotNull Builder setTransportHeaders(Map<String, String> transportHeaders) { this.transportHeaders = transportHeaders; return this; }
Source:
<code>public ServiceAccount store(String token, InputStream service) throws IOException { final Path path = rootLocation.resolve(token + JSON_EXTENSION); <START> ServiceAccount object = jsonSerialise.deserialiseQuietly(service, path); <END> jsonSerialise.serialise(path, object); return object; }</code><technical_language>Good point , I added a check in</technical_language>

Target:
public ServiceAccount store(String token, InputStream service) throws IOException { final Path path = rootLocation.resolve(token + JSON_EXTENSION); if (!Files.exists(path)) { ServiceAccount object = jsonSerialise.deserialiseQuietly(service, path); jsonSerialise.serialise(path, object); return object; } throw new FileAlreadyExistsException("The service token already exists : " + path); }
Source:
<code>public Collection<Permission> getAllPermissions() { Collection<Permission> result = new ArrayList<Permission>(permissions); for (Role role : nestedRoles) { if (role == this) { <START> throw new IllegalStateException("cyclic dependency detected"); <END> } result.addAll(role.getAllPermissions()); } return result; }</code><technical_language>do throw exception in case? a warn enough</technical_language>

Target:
public Collection<Permission> getAllPermissions() { Collection<Permission> result = new ArrayList<Permission>(permissions); for (Role role : nestedRoles) { if (role == this) { LOGGER.warn("cyclic dependency detected"); return Collections.emptyList(); } result.addAll(role.getAllPermissions()); } return result; }
Source:
<code>public BukkitBlockCommandSender(WorldEditPlugin plugin, BlockCommandSender sender) { checkNotNull(plugin); checkNotNull(sender); this.plugin = plugin; this.sender = sender; this.location = BukkitAdapter.adapt(sender.getBlock().getLocation()); <START> this.uuid = new UUID("COMMAND_BLOCK".hashCode(), sender.getName().hashCode()); <END> }</code><technical_language>I before, I prefer if a standard UUID generation scheme, UUIDv4 (Random) seeded name, UUIDv5 (namespaced)</technical_language>

Target:
public BukkitBlockCommandSender(WorldEditPlugin plugin, BlockCommandSender sender) { checkNotNull(plugin); checkNotNull(sender); this.plugin = plugin; this.sender = sender; this.location = BukkitAdapter.adapt(sender.getBlock().getLocation()); this.uuid = UUID.nameUUIDFromBytes((UUID_PREFIX + sender.getName()).getBytes(StandardCharsets.UTF_8)); }
Source:
<code>private void checkVdsMemoryThresholdPercentage(Cluster cluster, VdsStatistics stat) { <START> Integer maxUsedPercentageThreshold = <END> cluster.getLogMaxMemoryUsedThreshold(); if (stat.getUsageMemPercent() > maxUsedPercentageThreshold) { logMemoryAuditLog(vds, stat, AuditLogType.VDS_HIGH_MEM_USE, maxUsedPercentageThreshold); } }</code><technical_language>please merge lines</technical_language>

Target:
private void checkVdsMemoryThresholdPercentage(Cluster cluster, VdsStatistics stat) { Integer maxUsedPercentageThreshold = cluster.getLogMaxMemoryUsedThreshold(); if (stat.getUsageMemPercent() > maxUsedPercentageThreshold) { logMemoryAuditLog(vds, cluster, stat, AuditLogType.VDS_HIGH_MEM_USE, maxUsedPercentageThreshold); } }
Source:
<code>public void whenLightStatsOnActiveSubscriptionThenCorrectRespones() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventTypeFromBegin(et); publishEvents(et, 15, i -> "{\"foo\":\"bar\"}"); final TestStreamingClient client = TestStreamingClient .create(URL, s.getId(), "max_uncommitted_events=20") .start(); waitFor(() -> assertThat(client.getBatches(), hasSize(15))); final Response response = when().get("/subscriptions?show_status=true").thenReturn(); final ItemsWrapper<Subscription> subsItems = MAPPER.readValue(response.print(), new TypeReference<ItemsWrapper<Subscription>>(){}); for (final Subscription subscription: subsItems.getItems()) { if (subscription.getId().equals(s.getId())) { Assert.assertNotNull(subscription.getStats()); Assert.assertEquals("assigned", subscription.getStats().get(0).getPartitions().get(0).getState()); <START> Assert.assertNotEquals("", subscription.getStats().get(0).getPartitions().get(0).getStreamId()); <END> Assert.assertEquals(SubscriptionEventTypeStats.Partition.AssignmentType.AUTO, subscription.getStats().get(0).getPartitions().get(0).getAssignmentType()); return; } } Assert.assertTrue(false); }</code><technical_language>streamId TestStreamingClient for assertion</technical_language>

Target:
public void whenLightStatsOnActiveSubscriptionThenCorrectRespones() throws IOException { final String et = createEventType().getName(); final Subscription s = createSubscriptionForEventTypeFromBegin(et); final String owningApplication = s.getOwningApplication(); publishEvents(et, 15, i -> "{\"foo\":\"bar\"}"); final TestStreamingClient client = TestStreamingClient .create(URL, s.getId(), "max_uncommitted_events=20") .start(); waitFor(() -> assertThat(client.getBatches(), hasSize(15))); final Response response = when() .get("/subscriptions?show_status=true&owning_application=" + owningApplication) .thenReturn(); final ItemsWrapper<Subscription> subsItems = MAPPER.readValue(response.print(), new TypeReference<ItemsWrapper<Subscription>>(){}); for (final Subscription subscription: subsItems.getItems()) { if (subscription.getId().equals(s.getId())) { Assert.assertNotNull(subscription.getStatus()); Assert.assertEquals("assigned", subscription.getStatus().get(0).getPartitions().get(0).getState()); Assert.assertEquals(client.getSessionId(), subscription.getStatus().get(0).getPartitions().get(0).getStreamId()); Assert.assertEquals(SubscriptionEventTypeStats.Partition.AssignmentType.AUTO, subscription.getStatus().get(0).getPartitions().get(0).getAssignmentType()); return; } } Assert.assertTrue(false); }
Source:
<code><START> public boolean isPair(final SAMRecord record) { <END> return record != null && this.getMateAlignmentStart() == record.getAlignmentStart() && record.getMateAlignmentStart() == this.getAlignmentStart() && !NO_ALIGNMENT_REFERENCE_NAME.equals(this.getMateReferenceName()) && !NO_ALIGNMENT_REFERENCE_NAME.equals(record.getMateReferenceName()) && Objects.equals(this.getReferenceName(), record.getMateReferenceName()) && Objects.equals(record.getReferenceName(), this.getMateReferenceName()); }</code><technical_language>I suggest move this SamPairUtil, a lot of methods in SAMRecord utility class. Eventually, reads accessed interface (e.g., #985) this methods live in utility class is implementation-independent</technical_language>

Target:
public boolean isPair(final SAMRecord record) { return record != null && Objects.equals(this.getReadName(), record.getReadName()) && this.getMateAlignmentStart() == record.getAlignmentStart() && record.getMateAlignmentStart() == this.getAlignmentStart() && !NO_ALIGNMENT_REFERENCE_NAME.equals(this.getMateReferenceName()) && !NO_ALIGNMENT_REFERENCE_NAME.equals(record.getMateReferenceName()) && Objects.equals(this.getReferenceName(), record.getMateReferenceName()) && Objects.equals(record.getReferenceName(), this.getMateReferenceName()); }
Source:
<code>void addCleanupAddon(MApplication app, EModelService modelService) { final String contributionURI = "bundleclass://org.eclipse.e4.ui.workbench.addons.swt/org.eclipse.e4.ui.workbench.addons.cleanupaddon.CleanupAddon"; final String id = "CleanupAddon"; <START> addAddon(app, modelService, contributionURI, id); <END> }</code><technical_language>I convert a ProcessorUtil.addAddon call.. need introduce inheritance</technical_language>

Target:
void addCleanupAddon(MApplication app, EModelService modelService) { final String contributionURI = "bundleclass://org.eclipse.e4.ui.workbench.addons.swt/org.eclipse.e4.ui.workbench.addons.cleanupaddon.CleanupAddon"; final String id = "CleanupAddon"; ProcessorUtil.addAddon(app, modelService, contributionURI, id); }
Source:
<code>void findBySimpleProperty() { Airport vie = null; try { vie = new Airport("airports::vie", "vie", "loww"); airportRepository.save(vie).block(); List<Airport> airports1 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports1.size()); List<Airport> airports2 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports2.size()); vie = airportRepository.save(vie).block(); List<Airport> airports = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports.size()); <START> System.out.println("findAllByIata(0): " + airports.get(0)); <END> Airport airport1 = airportRepository.findById(airports.get(0).getId()).block(); assertEquals(airport1.getIata(), vie.getIata()); System.out.println("findById: " + airport1); Airport airport2 = airportRepository.findByIata(airports.get(0).getIata()).block(); assertEquals(airport1.getId(), vie.getId()); System.out.println("findByIata: " + airport2); } finally { airportRepository.delete(vie).block(); } }</code><technical_language>some debugging leftovers - recommend remove prints tests noisy in logfiles</technical_language>

Target:
void findBySimpleProperty() { Airport vie = null; try { vie = new Airport("airports::vie", "vie", "loww"); airportRepository.save(vie).block(); List<Airport> airports1 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports1.size()); List<Airport> airports2 = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports2.size()); vie = airportRepository.save(vie).block(); List<Airport> airports = airportRepository.findAllByIata("vie").collectList().block(); assertEquals(1, airports.size()); Airport airport1 = airportRepository.findById(airports.get(0).getId()).block(); assertEquals(airport1.getIata(), vie.getIata()); Airport airport2 = airportRepository.findByIata(airports.get(0).getIata()).block(); assertEquals(airport1.getId(), vie.getId()); } finally { airportRepository.delete(vie).block(); } }
Source:
<code>public void testBinaryStatsWithTruncation() { int defaultTruncLen = ParquetProperties.DEFAULT_STATISTICS_TRUNCATE_LENGTH; int[] validLengths = {1, 2, 16, 64, defaultTruncLen - 1, defaultTruncLen - 1}; for (int len : validLengths) { testBinaryStatsWithTruncation(len); } int[] invalidLengths = {-1, 0, defaultTruncLen + 1}; <START> for (int len : invalidLengths) { <END> try { testBinaryStatsWithTruncation(len); } catch (IllegalArgumentException e) { } } }</code><technical_language>do test defaultTruncLen -1 twice? I guess, defaultTrundLen tested</technical_language>

Target:
public void testBinaryStatsWithTruncation() { int defaultTruncLen = ParquetProperties.DEFAULT_STATISTICS_TRUNCATE_LENGTH; int[] validLengths = {1, 2, 16, 64, defaultTruncLen - 1}; for (int len : validLengths) { testBinaryStatsWithTruncation(len, 60, 70); testBinaryStatsWithTruncation(len, (int) ParquetMetadataConverter.MAX_STATS_SIZE, 190); testBinaryStatsWithTruncation(len, 280, (int) ParquetMetadataConverter.MAX_STATS_SIZE); testBinaryStatsWithTruncation(len, (int) ParquetMetadataConverter.MAX_STATS_SIZE, (int) ParquetMetadataConverter.MAX_STATS_SIZE); } int[] invalidLengths = {-1, 0, Integer.MAX_VALUE + 1}; for (int len : invalidLengths) { try { testBinaryStatsWithTruncation(len, 80, 20); Assert.fail("Expected IllegalArgumentException but didn't happen"); } catch (IllegalArgumentException e) { } } }
Source:
<code>private double getTotalSizeForDisksWithSnapshots(Collection<DiskImage> diskImages) { return getTotalSizeForDisksByMethod(diskImages, diskImage -> { double sizeForDisk = diskImage.getSize(); if ((storageDomain.getStorageType().isFileDomain() && diskImage.getVolumeType() == VolumeType.Sparse) || diskImage.getVolumeFormat() == VolumeFormat.COW) { if <START> (!VmEntityType.TEMPLATE.equals(diskImage.getVmEntityType())) <END> { sizeForDisk = diskImage.getActualDiskWithSnapshotsSizeInBytes(); } } if (diskImage.getVolumeFormat() == VolumeFormat.COW) { sizeForDisk = Math.ceil(StorageConstants.QCOW_OVERHEAD_FACTOR * sizeForDisk); } return sizeForDisk; }); }</code><technical_language>Preferred style, in line above: if (!diskImage.getVmEntityType() == VmEntityType.TEMPLATE) { ... }</technical_language>

Target:
private double getTotalSizeForDisksWithSnapshots(Collection<DiskImage> diskImages) { return getTotalSizeForDisksByMethod(diskImages, diskImage -> { double sizeForDisk = diskImage.getSize(); if ((storageDomain.getStorageType().isFileDomain() && diskImage.getVolumeType() == VolumeType.Sparse) || diskImage.getVolumeFormat() == VolumeFormat.COW) { sizeForDisk = diskImage.getActualDiskWithSnapshotsSizeInBytes(); } if (diskImage.getVolumeFormat() == VolumeFormat.COW) { sizeForDisk = Math.ceil(StorageConstants.QCOW_OVERHEAD_FACTOR * sizeForDisk); } return sizeForDisk; }); }
Source:
<code><START> public static boolean isEqualToDefault(EObject object, EStructuralFeature feature) { <END> final Object value = ReferenceUtil.safeEGet(object, feature); final Object defaultValue = feature.getDefaultValue(); if (value == null) { return defaultValue == null; } return value.equals(feature.getDefaultValue()) || "".equals(value); }</code><technical_language>need this public. leave renaming "is*" in though, a name :)</technical_language>

Target:
private static boolean isEqualToDefault(EObject object, EStructuralFeature feature) { final Object value = ReferenceUtil.safeEGet(object, feature); final Object defaultValue = feature.getDefaultValue(); if (value == null) { return defaultValue == null; } return value.equals(feature.getDefaultValue()) || "".equals(value); }
Source:
<code>public boolean refresh() throws Exception { <START> prepare(); <END> if (!isOk()) { return false; } repoImpl.refresh(); bridge = new BridgeRepository(repoImpl); for (RepositoryListenerPlugin listener : registry.getPlugins(RepositoryListenerPlugin.class)) { try { listener.repositoryRefreshed(this); } catch (Exception e) { reporter.exception(e, "Updating listener plugin %s", listener); } } return true; }</code><technical_language>prepare. Refresh is pom file settings. If setting sin bnd file change, a new plugin is created</technical_language>

Target:
public boolean refresh() throws Exception { if (!init()) { return false; } repoImpl.refresh(); bridge = new BridgeRepository(repoImpl); for (RepositoryListenerPlugin listener : registry.getPlugins(RepositoryListenerPlugin.class)) { try { listener.repositoryRefreshed(this); } catch (Exception e) { reporter.exception(e, "Updating listener plugin %s", listener); } } return true; }
Source:
<code>public CoordinatorServerView( ServerInventoryView baseView ) { this.baseView = baseView; this.selectors = Maps.newHashMap(); this.timelines = Maps.newHashMap(); <START> ExecutorService exec = Execs.singleThreaded("OverlordServerView-%s"); <END> baseView.registerSegmentCallback( exec, new ServerView.SegmentCallback() { @Override public ServerView.CallbackAction segmentAdded(DruidServerMetadata server, DataSegment segment) { serverAddedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentRemoved(final DruidServerMetadata server, DataSegment segment) { serverRemovedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentViewInitialized() { initialized = true; return ServerView.CallbackAction.CONTINUE; } } ); baseView.registerServerCallback( exec, new ServerView.ServerCallback() { @Override public ServerView.CallbackAction serverRemoved(DruidServer server) { removeServer(server); return ServerView.CallbackAction.CONTINUE; } } ); }</code><technical_language>CoordinatorServerView</technical_language>

Target:
public CoordinatorServerView( ServerInventoryView baseView ) { this.baseView = baseView; this.segmentLoadInfos = Maps.newHashMap(); this.timelines = Maps.newHashMap(); ExecutorService exec = Execs.singleThreaded("CoordinatorServerView-%s"); baseView.registerSegmentCallback( exec, new ServerView.SegmentCallback() { @Override public ServerView.CallbackAction segmentAdded(DruidServerMetadata server, DataSegment segment) { serverAddedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentRemoved(final DruidServerMetadata server, DataSegment segment) { serverRemovedSegment(server, segment); return ServerView.CallbackAction.CONTINUE; } @Override public ServerView.CallbackAction segmentViewInitialized() { initialized = true; return ServerView.CallbackAction.CONTINUE; } } ); baseView.registerServerCallback( exec, new ServerView.ServerCallback() { @Override public ServerView.CallbackAction serverRemoved(DruidServer server) { removeServer(server); return ServerView.CallbackAction.CONTINUE; } } ); }
Source:
<code>public List<String> getTimeZoneOptionsAsHtml() { <START> return getTimeZoneOptionsAsHtml(TimeHelper.convertToOffset(timeZone)); <END> }</code><technical_language>I change front end instead of double offset</technical_language>

Target:
public List<String> getTimeZoneOptionsAsHtml() { return getTimeZoneOptionsAsHtml(timeZone); }
Source:
<code>public void deleteFromSubject(String tenant, String subject) { String hql = "DELETE FROM Policy " + "WHERE subject = :subject_id"; Query query = this.currentSession().createQuery(hql); query.setParameter("subject_id", subject); int result = query.executeUpdate(); <START> System.out.println("The result of the delete subject is " + result); <END> }</code><technical_language>Remove statement</technical_language>

Target:
public void deleteFromSubject(String tenant, String subject) { String hql = "DELETE FROM Policy " + "WHERE subject = :subject_id"; Query query = this.currentSession().createQuery(hql); query.setParameter("subject_id", subject); int result = query.executeUpdate(); }
Source:
<code>public void testQueryExecution() { VmTemplate expected = new VmTemplate(); VmTemplateDao vmTemplateDaoMock = mock(VmTemplateDao.class); when(vmTemplateDaoMock.getTemplatesWithPermittedAction(getUser().getId(), getActionGroup())).thenReturn(Collections.singletonList(expected)); when(getDbFacadeMockInstance().getVmTemplateDao()).thenReturn(vmTemplateDaoMock); getQuery().executeQueryCommand(); @SuppressWarnings("unchecked") List<VmTemplate> actual = getQuery().getQueryReturnValue().getReturnValue(); <START> assertEquals("Wrong <END> number of VDS Groups", 1, actual.size()); assertEquals("Wrong VDS Groups", expected, actual.get(0)); }</code><technical_language>Message is wrong, wrong number of templates, in line</technical_language>

Target:
public void testQueryExecution() { VmTemplate expected = new VmTemplate(); VmTemplateDao vmTemplateDaoMock = mock(VmTemplateDao.class); when(vmTemplateDaoMock.getTemplatesWithPermittedAction(getUser().getId(), getActionGroup())).thenReturn(Collections.singletonList(expected)); when(getDbFacadeMockInstance().getVmTemplateDao()).thenReturn(vmTemplateDaoMock); getQuery().executeQueryCommand(); @SuppressWarnings("unchecked") List<VmTemplate> actual = getQuery().getQueryReturnValue().getReturnValue(); assertEquals("Wrong number of templates", 1, actual.size()); assertEquals("Wrong templates", expected, actual.get(0)); }
Source:
<code>public ProcessorConfig(final List<Evaluator> evaluators, final List<Action> actions, final List<StreamDefinition> streamDefinition, final List<StreamDefinition> writePermitedStreamDefinition, final Aphrodite aphrodite, final ExecutorService executorService, final String rootDirectory, final boolean write) { super(); <START> this.evaluators = evaluators; <END> this.actions = actions; this.aphrodite = aphrodite; this.executorService = executorService; this.streamDefinition = Collections.unmodifiableList(streamDefinition); if(writePermitedStreamDefinition != null){ this.writePermitedStreamDefinition = Collections.unmodifiableList(writePermitedStreamDefinition); } else { this.writePermitedStreamDefinition = this.streamDefinition; } this.rootDirectory = rootDirectory; this.write = write; }</code><technical_language>unwanted</technical_language>

Target:
public ProcessorConfig(final List<Evaluator> evaluators, final List<Action> actions, final List<StreamDefinition> streamDefinition, final List<StreamDefinition> writePermitedStreamDefinition, final Aphrodite aphrodite, final ExecutorService executorService, final String rootDirectory, final boolean write) { super(); this.evaluators = evaluators; this.actions = actions; this.aphrodite = aphrodite; this.executorService = executorService; this.streamDefinition = Collections.unmodifiableList(streamDefinition); if(writePermitedStreamDefinition != null){ this.writePermitedStreamDefinition = Collections.unmodifiableList(writePermitedStreamDefinition); } else { this.writePermitedStreamDefinition = this.streamDefinition; } this.rootDirectory = new File(rootDirectory); this.write = write; }
Source:
<code>public void writeTo(ObjectOutput output) throws IOException { MarshallUtil.marshallEnum(type, output); switch (type) { case START_STATE_TRANSFER: <START> output.writeBoolean(applyState); <END> case GET_TRANSACTIONS: case CANCEL_STATE_TRANSFER: output.writeObject(getOrigin()); MarshallUtil.marshallCollection(segments, output); return; case GET_CACHE_LISTENERS: return; default: throw new IllegalStateException("Unknown state request command type: " + type); } }</code><technical_language>I add new type a flag</technical_language>

Target:
public void writeTo(ObjectOutput output) throws IOException { MarshallUtil.marshallEnum(type, output); switch (type) { case START_CONSISTENCY_CHECK: case CANCEL_CONSISTENCY_CHECK: case START_STATE_TRANSFER: case GET_TRANSACTIONS: case CANCEL_STATE_TRANSFER: output.writeObject(getOrigin()); MarshallUtil.marshallCollection(segments, output); return; case GET_CACHE_LISTENERS: return; default: throw new IllegalStateException("Unknown state request command type: " + type); } }
Source:
<code><START> public final void setAggregates(GPOMutable aggregates) <END> { Preconditions.checkNotNull(aggregates); this.aggregates = aggregates; }</code><technical_language>this need public</technical_language>

Target:
protected final void setAggregates(GPOMutable aggregates) { Preconditions.checkNotNull(aggregates); this.aggregates = aggregates; }
Source:
<code>public void setup(TestContext testContext) throws Exception { this.testContext = testContext; targetInstance = testContext.getTargetInstance(); basename = testContext.getTestId(); if (TestUtils.isMemberNode(targetInstance)) { HazelcastServerCachingProvider hcp = new HazelcastServerCachingProvider(); cacheManager = new HazelcastServerCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } else { HazelcastClientCachingProvider hcp = new HazelcastClientCachingProvider(); cacheManager = new HazelcastClientCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } config = new CacheConfig(); config.setName(basename); config.setTypes(Object.class, Object.class); config.setReadThrough(true); config.setCacheLoaderFactory(FactoryBuilder.factoryOf( new RecordingCacheLoader() )); cacheManager.createCache(basename, config); cache = cacheManager.getCache(basename); config = cache.getConfiguration(CacheConfig.class); <START> for(int i=0; i< keyCount; i++){ <END> keySet.add(i); } }</code><technical_language>this done in warmup</technical_language>

Target:
public void setup(TestContext testContext) throws Exception { this.testContext = testContext; targetInstance = testContext.getTargetInstance(); basename = testContext.getTestId(); if (TestUtils.isMemberNode(targetInstance)) { HazelcastServerCachingProvider hcp = new HazelcastServerCachingProvider(); cacheManager = new HazelcastServerCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } else { HazelcastClientCachingProvider hcp = new HazelcastClientCachingProvider(); cacheManager = new HazelcastClientCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } config = new CacheConfig(); config.setName(basename); config.setReadThrough(true); RecordingCacheLoader recordingCacheLoader = new RecordingCacheLoader(); recordingCacheLoader.loadAllDelayMs = loadAllDelayMs; config.setCacheLoaderFactory(FactoryBuilder.factoryOf( recordingCacheLoader )); cacheManager.createCache(basename, config); cache = cacheManager.getCache(basename); config = cache.getConfiguration(CacheConfig.class); }
Source:
<code>public void stop() throws InterruptedException { final String container = containerId.or(containerName); stopAsync().awaitTerminated(); try { <START> log.info("container stats: {}", containerName, docker.stats(containerName).toString()); <END> docker.stopContainer(container, secondsToWaitBeforeKill); } catch (DockerException e) { if ((e instanceof ContainerNotFoundException) && !containerId.isPresent()) { } else { log.warn("Stopping container failed", container, e); } } }</code><technical_language>minor: need call .toString()</technical_language>

Target:
public void stop() throws InterruptedException { final String container = containerId.or(containerName); stopAsync().awaitTerminated(); if (System.getenv("CONTAINER_STATS") != null) { try { log.info("container stats: {}", containerName, docker.stats(containerName)); } catch (DockerException e) { log.warn("Could not log container stats. Exception was {}", e); } } try { docker.stopContainer(container, secondsToWaitBeforeKill); } catch (DockerException e) { if ((e instanceof ContainerNotFoundException) && !containerId.isPresent()) { } else { log.warn("Stopping container failed", container, e); } } }
Source:
<code><START> public void execCreateTestWithEnv() throws Exception { <END> String containerName = "generated_" + new SecureRandom().nextInt(); final String testVariable = "VARIABLE=success"; CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withUser("root").withCmd("top") .withName(containerName).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()) .withEnv(testVariable) .withCmd("/bin/sh", "-c", "\"env | grep BASE_DIR\"").exec(); assertThat(execCreateCmdResponse.getId(), not(isEmptyString())); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); dockerClient.execStartCmd(execCreateCmdResponse.getId()) .withDetach(false) .exec(new ExecStartResultCallback(stdout, System.err)) .awaitCompletion(); stdout.close(); assertEquals(stdout.toString(), testVariable); }</code><technical_language>please duplicate netty test class</technical_language>

Target:
public void execCreateTestWithEnv() throws Exception { String containerName = "generated_" + new SecureRandom().nextInt(); final List<String> testVariable = Arrays.asList("VARIABLE=dockerJavaTestSuccess"); CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withUser("root").withCmd("top") .withName(containerName).exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(container.getId()) .withEnv(testVariable) .withAttachStdout(true) .withAttachStderr(true) .withCmd("/bin/sh", "-c", "env | grep dockerJavaTestSuccess").exec(); assertThat(execCreateCmdResponse.getId(), not(isEmptyString())); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ExecStartResultCallback callback = new ExecStartResultCallback(stdout, stdout); dockerClient .execStartCmd(execCreateCmdResponse.getId()) .withDetach(false) .exec(callback) .awaitCompletion(); stdout.close(); assertTrue(stdout.toString().startsWith(testVariable.get(0))); }
Source:
<code>synchronized void notifyProgressListener(long listenerId, long transferredBytes, long transferableBytes) { Pair<ProgressListener, Progress> listener = listenerIdToProgressListenerMap.get(listenerId); if (listener != null) { Progress newProgressNotification = new Progress(transferredBytes, transferableBytes); if (!newProgressNotification.equals(listener.second)) { listener.first.onChange(newProgressNotification); <START> listener.second = newProgressNotification; <END> } } else { RealmLog.debug("Trying unknown listener failed: " + listenerId); } }</code><technical_language>assign newProgressNotification calling listener ensure listener.second is updated listener throws exception? handle exceptions listener</technical_language>

Target:
synchronized void notifyProgressListener(long listenerId, long transferredBytes, long transferableBytes) { Pair<ProgressListener, Progress> listener = listenerIdToProgressListenerMap.get(listenerId); if (listener != null) { Progress newProgressNotification = new Progress(transferredBytes, transferableBytes); if (!newProgressNotification.equals(listener.second)) { listener.second = newProgressNotification; listener.first.onChange(newProgressNotification); } } else { RealmLog.debug("Trying unknown listener failed: " + listenerId); } }
Source:
<code><START> public boolean create(final Identifier queryId, final Map<Identifier, OperatorState> queryState) { <END> if (queryStateMap.containsKey(queryId)) { return false; } else { queryStateMap.put(queryId, queryState); return true; } }</code><technical_language>need ConcurrentMap</technical_language>

Target:
public boolean create(final Identifier queryId, final Map<Identifier, OperatorState> queryState) { return queryStateMap.putIfAbsent(queryId, queryState) == null ? true : false; }
Source:
<code><START> protected String getLabelForFormsSent() { <END> int successfulSends = getSuccessfulSends(); String label = Localization.get("sync.success.sent", new String[]{String.valueOf(successfulSends)}); if (successfulSends == 1) { label = Localization.get("sync.success.sent.singular", new String[]{String.valueOf(successfulSends)}); } return label; }</code><technical_language>Ah I see, pulling out code for this previously in FormAndDataSyncer. in original implementation, mistake is reason pass a numeric parameter in case sync.success.sent.singular key. remove parameter in case, change key</technical_language>

Target:
protected String getLabelForFormsSent() { int successfulSends = getSuccessfulSends(); String label; switch (successfulSends) { case 0: label = Localization.get("sync.success.sent.none"); break; case 1: label = Localization.get("sync.success.sent.singular"); break; default: label = Localization.get("sync.success.sent", new String[]{String.valueOf(successfulSends)}); } return label; }
Source:
<code>private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { if (CachingConnectionFactory.this.active && CachingConnectionFactory.this.publisherConfirms) { ExecutorService executorService = (getExecutorService() != null ? getExecutorService() : Executors.newSingleThreadExecutor()); executorService.execute(new Runnable() { @Override public void run() { try { CachedChannelInvocationHandler.this.target.waitForConfirmsOrDie(getCloseTimeout()); CachedChannelInvocationHandler.this.target.close(); } catch (Exception e) { <START> Thread.currentThread().interrupt(); <END> } } }); } else { this.target.close(); } } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } finally { this.target = null; } }</code><technical_language>? interrupt InterruptedExeption. Also, waitForConfirmsOrDie() needs try block - throw exceptions (timeout etc), close() skipped</technical_language>

Target:
private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { if (CachingConnectionFactory.this.active && (CachingConnectionFactory.this.publisherConfirms || CachingConnectionFactory.this.publisherReturns)) { ExecutorService executorService = (getExecutorService() != null ? getExecutorService() : Executors.newSingleThreadExecutor()); final Channel channel = CachedChannelInvocationHandler.this.target; executorService.execute(new Runnable() { @Override public void run() { try { if (CachingConnectionFactory.this.publisherConfirms) { channel.waitForConfirmsOrDie(5000); } else { Thread.sleep(5000); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) finally { try { if (channel.isOpen()) { channel.close(); } } catch (IOException e) catch (AlreadyClosedException e) } } }); } else { this.target.close(); } } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } finally { this.target = null; } }
Source:
<code>public void run() { logger.info("Listening for messages using " + transformer); while (socket != null && socket.isConnected()) { try { transformer.read(in, mess -> incomingMess(mess)); } catch (CardshifterSerializationException e) { if(e.getCause() instanceof SocketException) { <START> logger.info("SocketException has happended, closing the socket"); <END> } else { logger.error(e.getMessage(), e); } this.close(); } if (Thread.interrupted()) { logger.info(this + " interrupted"); close(); break; } if (socket.isClosed()) { logger.info(this + " socket closed"); close(); break; } } logger.info("End of run method for " + this); }</code><technical_language>"SocketException occurred"</technical_language>

Target:
public void run() { logger.info("Listening for messages using " + transformer); while (socket != null && socket.isConnected()) { try { transformer.read(in, mess -> incomingMess(mess)); } catch (CardshifterSerializationException e) { if(e.getCause() instanceof SocketException) { logger.info("SocketException has occurred, closing the socket"); } else { logger.error(e.getMessage(), e); } this.close(); } if (Thread.interrupted()) { logger.info(this + " interrupted"); close(); break; } if (socket.isClosed()) { logger.info(this + " socket closed"); close(); break; } } logger.info("End of run method for " + this); }
Source:
<code>public void reportNotJenkins() throws Exception { home = tempHome(); grabCliJar(); for (String transport: Arrays.asList("-remoting", "-http", "-ssh")) { <START> String url = "<LINK_0>"; <END> ByteArrayOutputStream baos = new ByteArrayOutputStream(); int ret = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds( "java", "-Duser.home=" + home, "-jar", jar.getAbsolutePath(), "-s", url, transport, "-user", "asdf", "who-am-i" ).stdout(baos).stderr(baos).join(); assertThat(baos.toString(), containsString("There's no Jenkins running at")); assertNotEquals(0, ret); } }</code><technical_language>consider declaring string final for loop</technical_language>

Target:
public void reportNotJenkins() throws Exception { home = tempHome(); grabCliJar(); String url = r.getURL().toExternalForm() + "not-jenkins/"; for (String transport : Arrays.asList("-remoting", "-http", "-ssh")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int ret = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds( "java", "-Duser.home=" + home, "-jar", jar.getAbsolutePath(), "-s", url, transport, "-user", "asdf", "who-am-i" ).stdout(baos).stderr(baos).join(); assertThat(baos.toString(), containsString("There's no Jenkins running at")); assertNotEquals(0, ret); } }
Source:
<code>public void start(RoutingTable routingTable) { try { NettyJaxrsServer netty = new NettyJaxrsServer(); ResteasyDeployment deployment = new ResteasyDeployment(); netty.setDeployment(deployment); nettyServer = Optional.of(netty); netty.setHostname(configuration.getIp().getHostName()); netty.setPort(configuration.getPort()); netty.setRootResourcePath(""); netty.setSecurityDomain(null); netty.start(); addDeployments(netty, routingTable); this.ip = Optional.of(configuration.getIp()); this.port = Optional.of(configuration.getPort()); <START> logger.restRouterStarted(ip + ":" + port); <END> } catch (Exception e) { throw logger.restRouterStartFailed(e); } }</code><technical_language>arguments logger method instead of a concatenated string</technical_language>

Target:
public void start(RoutingTable routingTable) { try { NettyJaxrsServer netty = new NettyJaxrsServer(); ResteasyDeployment deployment = new ResteasyDeployment(); netty.setDeployment(deployment); nettyServer = Optional.of(netty); netty.setHostname(configuration.getIp().getHostName()); netty.setPort(configuration.getPort()); netty.setRootResourcePath(""); netty.setSecurityDomain(null); netty.start(); addDeployments(netty, routingTable); this.ip = Optional.of(configuration.getIp()); this.port = Optional.of(configuration.getPort()); logger.restRouterStarted(ip, port); } catch (Exception e) { throw logger.restRouterStartFailed(e); } }
Source:
<code>private static int getNumberOfBlankLines(List<Token> tokens) { <START> List<Token> tkns = tokens; <END> if (tkns == null || tkns.size() <= 1) { return 0; } int firstNewlineOrCommentIndex = -1; for (int i = 0; i < tkns.size(); i++) { Token token = tkns.get(i); if (ListenerUtil.isComment(token) || ListenerUtil.isNewline(token)) { firstNewlineOrCommentIndex = i; break; } } tkns = tkns.subList(firstNewlineOrCommentIndex + 1, tokens.size()); return (int) tkns.stream().filter(ListenerUtil::isNewline).count(); }</code><technical_language>this rule is weird</technical_language>

Target:
private static int getNumberOfBlankLines(List<Token> tokens) { if (tokens == null || tokens.size() <= 1) { return 0; } int firstNewlineOrCommentIndex = -1; for (int i = 0; i < tokens.size(); i++) { Token token = tokens.get(i); if (ListenerUtil.isComment(token) || ListenerUtil.isNewline(token)) { firstNewlineOrCommentIndex = i; break; } } tokens = tokens.subList(firstNewlineOrCommentIndex + 1, tokens.size()); return (int) tokens.stream().filter(ListenerUtil::isNewline).count(); }
Source:
<code>private void openNewSurvey(Activity activity) { ProgramDB programDB = ProgramDB.findById(PreferencesEReferral.getUserProgramId()); <START> SurveyDB surveyDB = new SurveyDB(null, programDB, Session.getUserDB()); <END> UserAccount userAccount = new UserAccount(Session.getUserDB().getName(), Session.getUserDB().getUid(), PreferencesState.getCredentialsFromPreferences().isDemoCredentials()); surveyDB.save(); Session.setMalariaSurveyDB(surveyDB); prepareLocationListener(activity, surveyDB); Program program = new Program(programDB.getUid(), programDB.getUid()); Survey survey = new Survey(surveyDB.getId_survey(), program, userAccount , Constants.SURVEY_IN_PROGRESS); saveValuesFromIntent(activity, survey); if(!DashboardActivity.dashboardActivity.isPreLoadSurveyOpenning()) { mDashboardActivity.initSurvey(); } }</code><technical_language>this method SurveyDB Survey domain entities used, refactor for domain entity</technical_language>

Target:
private void openNewSurvey(Activity activity) { ProgramDB programDB = ProgramDB.findById(PreferencesEReferral.getUserProgramId()); SurveyDB survey = new SurveyDB(null, programDB, Session.getUserDB()); survey.save(); Session.setMalariaSurveyDB(survey); prepareLocationListener(activity, survey); mDashboardActivity.initSurvey(); }
Source:
<code>public DeleteColumnManagementAnchorWidget() { super(); setText(GuidedDecisionTableConstants.INSTANCE.Delete()); setTitle(GuidedDecisionTableConstants.INSTANCE.DeleteThisColumn()); addClickHandler((clickEvent) -> { deletePopUpPresenter.getToggleCommentPresenter().getViewElement().setAttribute("hidden", "true"); deletePopUpPresenter.show((comment) -> afterDeleteConfirmedCommand.execute()); <START> }); <END> }</code><technical_language>DeletePopupPresenter.View shows a "Are want delete this **Asset**" prompt. need able this "Are want delete this **column**?". ways able do this; investigate a DeletePopupPresenter.setPrompt(String) method (that calls View.setPrompt(String) calls modal.setTitle( prompt )) implementation of DeletePopupPresenter injects a View sets "Are want delete this **column**?" a lot of leg work). you</technical_language>

Target:
public DeleteColumnManagementAnchorWidget() { }
Source:
<code>private LinkedHashMap<String, LinkedHashMap<String, String>> getAdditionalInformationAsMapOfMap(NodeSource ns) { String allNewAdditionalInformationAsString = ""; LinkedHashMap<String, LinkedHashMap<String, String>> additionalInformationMap = new LinkedHashMap<>(); for (Map.Entry<String, String> categoryAndKeyAndValue : ns.getAdditionalInformation().entrySet()) { <START> String[] categoryAndKeyArr = categoryAndKeyAndValue.getKey().split("\\|"); <END> String category = categoryAndKeyArr[0]; String key = categoryAndKeyArr[1]; String value = categoryAndKeyAndValue.getValue(); if (!additionalInformationMap.containsKey(category)) { additionalInformationMap.put(category, new LinkedHashMap<>()); } additionalInformationMap.get(category).put(key, value); allNewAdditionalInformationAsString += category + key + value; } if (!this.allAdditionalInformationAsString.equals(allNewAdditionalInformationAsString)) { this.allAdditionalInformationAsString = allNewAdditionalInformationAsString; return additionalInformationMap; } return null; }</code><technical_language>call "continue" categoryAndKeyArr is length = 2</technical_language>

Target:
private LinkedHashMap<String, LinkedHashMap<String, String>> getAdditionalInformationAsMapOfMap(NodeSource ns) { String allNewAdditionalInformationAsString = ""; LinkedHashMap<String, LinkedHashMap<String, String>> additionalInformationMap = new LinkedHashMap<>(); for (Map.Entry<String, String> categoryAndKeyAndValue : ns.getAdditionalInformation().entrySet()) { String[] categoryAndKeyArr = categoryAndKeyAndValue.getKey().split("\\|"); if (categoryAndKeyArr.length != 2) continue; String category = categoryAndKeyArr[0]; String key = categoryAndKeyArr[1]; String value = categoryAndKeyAndValue.getValue(); if (!additionalInformationMap.containsKey(category)) { additionalInformationMap.put(category, new LinkedHashMap<>()); } additionalInformationMap.get(category).put(key, value); allNewAdditionalInformationAsString += category + key + value; } if (!this.allAdditionalInformationAsString.equals(allNewAdditionalInformationAsString)) { this.allAdditionalInformationAsString = allNewAdditionalInformationAsString; return additionalInformationMap; } return null; }
Source:
<code>private static void editTree(TreeOperation op, Repository repo, RevWalk rw, RevCommit base, DirCacheEditor dce, ObjectInserter ins, String path, byte[] content) throws IOException, InvalidChangeOperationException { switch (op) { case DELETE_ENTRY: dce.add(new DeletePath(path)); break; case CHANGE_ENTRY: case RESTORE_ENTRY: <START> dce.add(getPathEdit(op, repo, rw, base, path, ins, content)); <END> } dce.finish(); }</code><technical_language>Break this line</technical_language>

Target:
private static void editTree(TreeOperation op, Repository repo, RevWalk rw, RevCommit base, DirCacheEditor dce, ObjectInserter ins, String path, byte[] content) throws IOException, InvalidChangeOperationException { switch (op) { case DELETE_ENTRY: dce.add(new DeletePath(path)); break; case CHANGE_ENTRY: case RESTORE_ENTRY: dce.add(getPathEdit(op, repo, rw, base, path, ins, content)); break; } dce.finish(); }