auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testIdempotentReprocess() throws IOException { final IndexableAdapter adapter = new QueryableIndexIndexableAdapter(IndexIO.loadIndex(persistTmpDir)); Assert.assertEquals(events.size(), adapter.getNumRows()); reprocessAndValidate(persistTmpDir, tmpDir); <START> final File tmpDir2 = Files.createTempDir(); <END> try { final IndexableAdapter adapter2 = new QueryableIndexIndexableAdapter(IndexIO.loadIndex(tmpDir)); Assert.assertEquals(events.size(), adapter2.getNumRows()); reprocessAndValidate(tmpDir, tmpDir2); final File tmpDir3 = Files.createTempDir(); try { final IndexableAdapter adapter3 = new QueryableIndexIndexableAdapter(IndexIO.loadIndex(tmpDir2)); Assert.assertEquals(events.size(), adapter3.getNumRows()); reprocessAndValidate(tmpDir2, tmpDir3); } finally { FileUtils.deleteDirectory(tmpDir3); } } finally { FileUtils.deleteDirectory(tmpDir2); } }</code><technical_language>cleanup easier code more readable, reuse temp directory created part of setup, worry deleting stuff in test. fail test delete temp files</technical_language>

Target:
public void testIdempotentReprocess() throws IOException { final IndexableAdapter adapter = new QueryableIndexIndexableAdapter(IndexIO.loadIndex(persistTmpDir)); Assert.assertEquals(events.size(), adapter.getNumRows()); final File tmpDir1 = new File(tmpDir, "reprocessed1"); reprocessAndValidate(persistTmpDir, tmpDir1); final File tmpDir2 = new File(tmpDir, "reprocessed2"); final IndexableAdapter adapter2 = new QueryableIndexIndexableAdapter(IndexIO.loadIndex(tmpDir1)); Assert.assertEquals(events.size(), adapter2.getNumRows()); reprocessAndValidate(tmpDir1, tmpDir2); final File tmpDir3 = new File(tmpDir, "reprocessed3"); final IndexableAdapter adapter3 = new QueryableIndexIndexableAdapter(IndexIO.loadIndex(tmpDir2)); Assert.assertEquals(events.size(), adapter3.getNumRows()); reprocessAndValidate(tmpDir2, tmpDir3); }
Source:
<code>public void test() throws Exception { String txnAsString = null; tm.setTransactionTimeout(1); try { tm.begin(); txnAsString = tm.getTransaction().toString(); TxTestUtil.waitForTimeout(tm); tm.commit(); } catch (RollbackException e) { try { log.debugf("Rollbacking transaction '%s'", txnAsString); tm.rollback(); Assert.fail("Rollback should throw IllegalStateException: BaseTransaction.rollback - ARJUNA016074: no transaction!" + " as the original transaction should be aborted by transaction manager"); } catch (Exception rollbacke) { log.debugf(rollbacke, "Got expected transaction: %s'", rollbacke.getClass()); } } <START> tm.setTransactionTimeout(0); <END> tm.begin(); txnAsString = tm.getTransaction().toString(); TxTestUtil.waitForTimeout(tm); tm.commit(); }</code><technical_language>I this needs happen in a finally block</technical_language>

Target:
public void test() throws Exception { String txnAsString = null; tm.setTransactionTimeout(1); try { tm.begin(); txnAsString = tm.getTransaction().toString(); TxTestUtil.waitForTimeout(tm); tm.commit(); } catch (RollbackException e) { try { log.tracef("Rollbacking transaction '%s'", txnAsString); tm.rollback(); Assert.fail("Rollback should throw IllegalStateException: BaseTransaction.rollback - ARJUNA016074: no transaction!" + " as the original transaction should be aborted by transaction manager"); } catch (Exception rollbacke) { log.debugf(rollbacke, "Got expected transaction: %s'", rollbacke.getClass()); } } finally { tm.setTransactionTimeout(0); } tm.begin(); txnAsString = tm.getTransaction().toString(); TxTestUtil.waitForTimeout(tm); tm.commit(); }
Source:
<code>public void testArraysOfNulls() throws Exception { <START> for (Type type : ImmutableList.of(BOOLEAN, BIGINT, INTEGER, SMALLINT, TINYINT, DOUBLE, REAL, TIMESTAMP, DECIMAL_TYPE_PRECISION_19, DECIMAL_TYPE_PRECISION_4, VARCHAR, CharType.createCharType(10), VARBINARY, arrayType(INTEGER))) { <END> tester.testRoundTrip(arrayType(type), nCopies(30_000, nCopies(5, null)), ImmutableList.of( ImmutableMap.of(new Subfield("c[2]"), IS_NULL), ImmutableMap.of(new Subfield("c[2]"), IS_NOT_NULL))); } }</code><technical_language>CHAR_10 constant</technical_language>

Target:
public void testArraysOfNulls() throws Exception { for (Type type : ImmutableList.of(BOOLEAN, BIGINT, INTEGER, SMALLINT, TINYINT, DOUBLE, REAL, TIMESTAMP, DECIMAL_TYPE_PRECISION_19, DECIMAL_TYPE_PRECISION_4, VARCHAR, CHAR_10, VARBINARY, arrayType(INTEGER))) { tester.testRoundTrip(arrayType(type), nCopies(NUM_ROWS, nCopies(5, null)), ImmutableList.of( ImmutableMap.of(new Subfield("c[2]"), IS_NULL), ImmutableMap.of(new Subfield("c[2]"), IS_NOT_NULL))); } }
Source:
<code>protected boolean validateImageTransfer() { DiskImage diskImage = getDiskImage(); DiskValidator diskValidator = getDiskValidator(diskImage); DiskImagesValidator diskImagesValidator = getDiskImagesValidator(diskImage); StorageDomainValidator storageDomainValidator = getStorageDomainValidator( storageDomainDao.getForStoragePool(diskImage.getStorageIds().get(0), diskImage.getStoragePoolId())); return validate(diskValidator.isDiskExists()) && <START> validateActiveDiskPluggedToAnyNonDownVm(diskImage, diskValidator) <END> && validate(diskImagesValidator.diskImagesNotIllegal()) && validate(diskImagesValidator.diskImagesNotLocked()) && validate(storageDomainValidator.isDomainExistAndActive()); }</code><technical_language>In case of a disk in backup VM</technical_language>

Target:
protected boolean validateImageTransfer() { DiskImage diskImage = getDiskImage(); DiskValidator diskValidator = getDiskValidator(diskImage); DiskImagesValidator diskImagesValidator = getDiskImagesValidator(diskImage); StorageDomainValidator storageDomainValidator = getStorageDomainValidator( storageDomainDao.getForStoragePool(diskImage.getStorageIds().get(0), diskImage.getStoragePoolId())); boolean isValid = validate(diskValidator.isDiskExists()) && validate(diskImagesValidator.diskImagesNotIllegal()) && validate(storageDomainValidator.isDomainExistAndActive()); if (getParameters().getBackupId() != null) { return isValid && validate(isVmBackupExists()); } return isValid && validateActiveDiskPluggedToAnyNonDownVm(diskImage, diskValidator) && validate(diskImagesValidator.diskImagesNotLocked()); }
Source:
<code>public Collection<ImmutableWorkerInfo> getBlackListedWorkers() { <START> return ImmutableList.copyOf( <END> Collections2.transform( blackListedWorkers, new Function<ZkWorker, ImmutableWorkerInfo>() { @Override public ImmutableWorkerInfo apply(ZkWorker input) { return input.toImmutable(); } } ) ); }</code><technical_language>Collections.unmodifiableSet() good enough</technical_language>

Target:
public Collection<ImmutableWorkerInfo> getBlackListedWorkers() { return getImmutableWorkerFromZK(blackListedWorkers); }
Source:
<code>public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { if (!(value instanceof Duration)) { return Optional.empty(); <START> } <END> Duration duration = (Duration)value; final boolean isNegative = duration.isNegative(); if (isNegative) { duration = duration.negated(); } final long days = duration.toDays(); if (days > Integer.MAX_VALUE) { throw new IllegalArgumentException( String.format("duration %s too large to be represented unambiguously as postgres interval", duration)); } duration = duration.minusDays(days); final int hours = (int)duration.toHours(); duration = duration.minusHours(hours); final int minutes = (int)duration.toMinutes(); duration = duration.minusMinutes(minutes); if (duration.getNano() % 1000 != 0) { throw new IllegalArgumentException( String.format("duration %s too precise to represented as postgres interval", duration)); } double seconds = duration.getSeconds() + duration.getNano() / 1e9; final PGInterval interval = new PGInterval(0, 0, (int)days, hours, minutes, seconds); if (isNegative) { interval.scale(-1); } return Optional.of((i, p, cx) -> p.setObject(i, interval, Types.OTHER)); }</code><technical_language>Typically match type value: java if (!(Duration.class.isAssignableFrom(GenericTypes.getErasedType(type)) || instanceof Duration)) { return Optional.empty(); } if (value == null) { return Optional.of(new NullArgument(Types.OTHER)); } // way, argument is null, a statically type of Duration (e.g. if passed null a Duration-typed parameter of a SQL Object), null bound correct SQL type. JDBC is picky this, meticulous capturing nulls right type</technical_language>

Target:
public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { if (Duration.class != type) { return Optional.empty(); } if (null == value) { return Optional.of(new NullArgument(Types.OTHER)); } Duration duration = (Duration)value; final boolean isNegative = duration.isNegative(); if (isNegative) { duration = duration.negated(); } final long days = duration.toDays(); if (days > Integer.MAX_VALUE) { throw new IllegalArgumentException( String.format("duration %s too large to be represented unambiguously as postgres interval", duration)); } duration = duration.minusDays(days); final int hours = (int)duration.toHours(); duration = duration.minusHours(hours); final int minutes = (int)duration.toMinutes(); duration = duration.minusMinutes(minutes); if (duration.getNano() % 1000 != 0) { throw new IllegalArgumentException( String.format("duration %s too precise to represented as postgres interval", duration)); } double seconds = duration.getSeconds() + duration.getNano() / 1e9; final PGInterval interval = new PGInterval(0, 0, (int)days, hours, minutes, seconds); if (isNegative) { interval.scale(-1); } return Optional.of((i, p, cx) -> p.setObject(i, interval, Types.OTHER)); }
Source:
<code>public boolean scaleIn() throws AvroRemoteException { final String removedTaskName = getMinimumLoadTask(); final boolean stopTaskSuccess = proxyToDriver.stopTask(removedTaskName); if (stopTaskSuccess) { <START> final ExecutorService singleThreadedExecutor = Executors.newSingleThreadExecutor(); <END> final TaskStats taskStats = taskStatsMap.removeTask(removedTaskName); singleThreadedExecutor .submit(new RecoveryStarter(taskStats.getGroupStatsMap(), recoveryScheduler)); return true; } else { return false; } }</code><technical_language>create singleThreadedExecutor a class variable? need implement close() method inScaleInManager</technical_language>

Target:
public boolean scaleIn() throws AvroRemoteException { final String removedTaskName = getMinimumLoadTask(); final boolean stopTaskSuccess = proxyToDriver.stopTask(removedTaskName); if (stopTaskSuccess) { final TaskStats taskStats = taskStatsMap.removeTask(removedTaskName); singleThreadedExecutor .submit(new RecoveryStarter(taskStats.getGroupStatsMap(), recoveryScheduler)); return true; } else { return false; } }
Source:
<code>public void getMeasurementSuccess() { final CountDownLatch signal = new CountDownLatch(1); <START> a.getApiClient().getMeasurement(EXISTING_REPORT_ID, null).enqueue(new GetMeasurementsCallback() { <END> @Override public void onSuccess(ApiMeasurement.Result result) { Assert.assertNotNull(result); signal.countDown(); } @Override public void onError(String msg) { Assert.fail(); signal.countDown(); } }); try { signal.await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } }</code><technical_language>I struggling understand is a declared</technical_language>

Target:
public void getMeasurementSuccess() { final CountDownLatch signal = new CountDownLatch(1); a.getApiClient().getMeasurement(EXISTING_REPORT_ID, null).enqueue(new GetMeasurementsCallback() { @Override public void onSuccess(ApiMeasurement.Result result) { Assert.assertNotNull(result); signal.countDown(); } @Override public void onError(String msg) { Assert.fail(); signal.countDown(); } }); try { signal.await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); Assert.fail(); } }
Source:
<code>public void afterPropertiesSet() throws Exception { if (this.mongoTemplate == null) { if (this.mappingMongoConverter == null) { this.mappingMongoConverter = new MappingMongoConverter(this.mongoDbFactory, new MongoMappingContext()); this.mappingMongoConverter.setApplicationContext(this.applicationContext); Assert.state(!(this.messageToDbConverter != null ^ this.dbToMessageConverter != null), "Both 'messageToDbConverter' and 'dbToMessageConverter' should be provided, or no one " + "in case of 'mongoDbFactory' is configured. " + "If these converters arn't provided 'MongoDbMessageBytesConverter' will be used by default"); List<Object> customConverters = new ArrayList<Object>(); customConverters.add(new MongoDbMessageBytesConverter()); this.mappingMongoConverter.setCustomConversions(new CustomConversions(customConverters)); this.mappingMongoConverter.afterPropertiesSet(); } else { Assert.state(this.messageToDbConverter != null | this.dbToMessageConverter != null, "'messageToDbConverter' and 'dbToMessageConverter' can't provided, if 'mappingMongoConverter' is configured." + <START> "All conversion will rely on provided 'dbToMessageConverter'."); <END> } this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mappingMongoConverter); this.mongoTemplate.setApplicationContext(this.applicationContext); } else { Assert.state(this.messageToDbConverter != null | this.dbToMessageConverter != null, "'messageToDbConverter' and 'dbToMessageConverter' can't provided, if 'mongoTemplate' is configured." + "All conversion will rely on provided 'mongoTemplate'."); } IndexOperations indexOperations = this.mongoTemplate.indexOps(this.collectionName); indexOperations.ensureIndex(new Index(MESSAGE_ID, Order.ASCENDING)); indexOperations.ensureIndex(new Index(GROUP_ID, Order.ASCENDING).on(LAST_MODIFIED_TIME, Order.DESCENDING)); }</code><technical_language>this is say, if condition is false, conversion</technical_language>

Target:
public void afterPropertiesSet() throws Exception { if (this.mongoTemplate == null) { if (this.mappingMongoConverter == null) { this.mappingMongoConverter = new MappingMongoConverter(this.mongoDbFactory, new MongoMappingContext()); this.mappingMongoConverter.setApplicationContext(this.applicationContext); List<Object> customConverters = new ArrayList<Object>(); customConverters.add(new MongoDbMessageBytesConverter()); this.mappingMongoConverter.setCustomConversions(new CustomConversions(customConverters)); this.mappingMongoConverter.afterPropertiesSet(); } this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mappingMongoConverter); if (this.applicationContext != null) { this.mongoTemplate.setApplicationContext(this.applicationContext); } } IndexOperations indexOperations = this.mongoTemplate.indexOps(this.collectionName); indexOperations.ensureIndex(new Index(MESSAGE_ID, Order.ASCENDING)); indexOperations.ensureIndex(new Index(GROUP_ID, Order.ASCENDING).on(LAST_MODIFIED_TIME, Order.DESCENDING)); }
Source:
<code>public Status insert(final String table, final String key, final Map<String, ByteIterator> values) { try { final Map<String, String> data = StringByteIterator.getStringMap(values); data.put(KEY, key); final Response response = restClient.performRequest( "POST", "/" + indexKey + "/" + table + "/", Collections.<String, String>emptyMap(), new NStringEntity(new ObjectMapper().writeValueAsString(data), ContentType.APPLICATION_JSON)); if (response.getStatusLine().getStatusCode() != 201) { return Status.ERROR; } if (!isRefreshNeeded) { synchronized (this) { isRefreshNeeded = true; } } return Status.OK; } catch (final Exception e) { <START> e.printStackTrace(); <END> return Status.ERROR; } }</code><technical_language>Exception#printStackTrace stderr default</technical_language>

Target:
public Status insert(final String table, final String key, final Map<String, ByteIterator> values) { try { final Map<String, String> data = StringByteIterator.getStringMap(values); data.put(KEY, key); final Response response = restClient.performRequest( "POST", "/" + indexKey + "/" + table + "/", Collections.<String, String>emptyMap(), new NStringEntity(new ObjectMapper().writeValueAsString(data), ContentType.APPLICATION_JSON)); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { return Status.ERROR; } if (!isRefreshNeeded) { synchronized (this) { isRefreshNeeded = true; } } return Status.OK; } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } }
Source:
<code>LocalClientConnection(ScheduledExecutorService executorService, HandlerRegistry handlers) { super(executorService); this.serverConnection = new LocalServerConnection(handlers); <START> serverConnection.setClientConnection(this); <END> }</code><technical_language>this set in constructor</technical_language>

Target:
LocalClientConnection(ScheduledExecutorService executorService, HandlerRegistry handlers) { super(executorService); this.serverConnection = new LocalServerConnection(handlers, this); }
Source:
<code>void modifyBindings() throws MigrationException { try { List<Binding> bindings = connector.readBindings(); for (Binding binding : bindings) { try { binding.setBindingDetails(modifier.modifyBinding(binding.getBindingDetails())); } catch (MigrationException e) { logger.error("Error modifying binding for queue: " + binding.getQueueName() + ". Incorrect " + <START> "binding info format: " + binding.getBindingDetails(), e); <END> } } connector.updateBindings(bindings); addDlcBindings(); } catch (SQLException e) { throw new MigrationException("Error while modifying bindings in the database", e); } }</code><technical_language>'+' sign beginning of a line</technical_language>

Target:
void modifyBindings() throws MigrationException { try { List<Binding> bindings = connector.readBindings(); for (Binding binding : bindings) { try { binding.setBindingDetails(modifier.modifyBinding(binding.getBindingDetails())); logger.info("Modified binding information in database"); } catch (MigrationException e) { logger.error("Error modifying binding for queue: " + binding.getQueueName() + ". Incorrect " + "binding info format: " + binding.getBindingDetails(), e); } } connector.updateBindings(bindings); addDlcBindings(); } catch (SQLException e) { throw new MigrationException("Error while modifying bindings in the database", e); } }
Source:
<code>private SimpleConsumer createConsumer(TopicPartition topicPartition) { HostAndPort leader = findLeader(topicPartition); LOG.debug("leader for topic partition is {}", topicPartition.getTopic(), topicPartition.getPartition(), leader); if (leader == null) { <START> return null; <END> } final String clientName = getClientName(topicPartition); return createConsumer(leader.getHostText(), leader.getPort(), clientName); }</code><technical_language>add a warning logging here</technical_language>

Target:
private SimpleConsumer createConsumer(TopicPartition topicPartition) { HostAndPort leader = findLeader(topicPartition); if (leader == null) { LOG.warn("no leader for topic partition {}", topicPartition.getTopic(), topicPartition.getPartition()); return null; } LOG.debug("leader for topic partition is {}", topicPartition.getTopic(), topicPartition.getPartition(), leader); final String clientName = getClientName(topicPartition); return createConsumer(leader.getHostText(), leader.getPort(), clientName); }
Source:
<code>public String toString() { return "LockToken [lockCreated=" + isCreated + ", link=" + <START> link.get().getFileName() + <END> "]"; }</code><technical_language>This fail if link.isPresent() is false</technical_language>

Target:
public String toString() { return "LockToken [lockCreated=" + isCreated + ", link=" + (link.isPresent() ? link.get().getFileName() + "]" : "<null>]"); }
Source:
<code>private static void testPidSorting(final SWTBotTree tree, final SWTBotTimeGraph timeGraph) { SWTBotTreeColumn column = tree.header(PID_COLUMN); String[] expected = { <START> LTTNG_CONSUMER_PROCESS_NAME, KTHREAD_PROCESS_NAME, SYSTEMD_PROCESS_NAME }; <END> SWTBotTestCondition condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected, timeGraph, false); clickColumn(tree, column, condition); String[] expected2 = { SYSTEMD_PROCESS_NAME, KTHREAD_PROCESS_NAME, LTTNG_CONSUMER_PROCESS_NAME }; condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected2, timeGraph, false); clickColumn(tree, column, condition); }</code><technical_language>If order of expected2 this order, successful</technical_language>

Target:
private static void testPidSorting(final SWTBotTree tree, final SWTBotTimeGraph timeGraph) { SWTBotTreeColumn column = tree.header(PID_COLUMN); String[] expected = { SYSTEMD_PROCESS_NAME, KTHREAD_PROCESS_NAME, LTTNG_CONSUMER_PROCESS_NAME }; SWTBotTestCondition condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected, timeGraph, false); clickColumn(tree, column, condition); String[] expected2 = { LTTNG_CONSUMER_PROCESS_NAME, KTHREAD_PROCESS_NAME, SYSTEMD_PROCESS_NAME }; condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected2, timeGraph, false); clickColumn(tree, column, condition); }
Source:
<code>protected void testStayLocalIfAllSegmentsPresentLocallyWithWriteBehindStore(boolean rehashAware) { Cache<Object, String> cache0 = cache(0, CACHE_NAME); ClusterStreamManager clusterStreamManager = replaceWithSpy(cache0); IntStream.rangeClosed(0, 499).boxed().forEach(i -> cache0.put(i, i.toString())); <START> <END> KeyPartitioner keyPartitioner = TestingUtil.extractComponent(cache0, KeyPartitioner.class); ConsistentHash ch = cache0.getAdvancedCache().getDistributionManager().getWriteConsistentHash(); Set<Integer> segmentsCache0 = ch.getSegmentsForOwner(address(0)); CacheStream<Map.Entry<Object, String>> stream = cache0.entrySet().stream(); if (!rehashAware) stream = stream.disableRehashAware(); Map<Object, String> entries = mapFromIterator(stream.filterKeySegments(segmentsCache0).iterator()); Map<Integer, Set<Map.Entry<Object, String>>> entriesPerSegment = generateEntriesPerSegment(keyPartitioner, entries.entrySet()); assertTrue(segmentsCache0.containsAll(entriesPerSegment.keySet())); verifyZeroInteractions(clusterStreamManager); assertTrue(cache0.getCacheConfiguration().persistence().stores().get(0).isWriteBehindShared()); }</code><technical_language>need 500 entries. 20, 40</technical_language>

Target:
protected void testStayLocalIfAllSegmentsPresentLocallyWithWriteBehindStore(boolean rehashAware) { Cache<Object, String> cache0 = cache(0, CACHE_NAME); ClusterStreamManager clusterStreamManager = replaceWithSpy(cache0); IntStream.rangeClosed(0, 499).boxed().forEach(i -> cache0.put(i, i.toString())); KeyPartitioner keyPartitioner = TestingUtil.extractComponent(cache0, KeyPartitioner.class); ConsistentHash ch = cache0.getAdvancedCache().getDistributionManager().getWriteConsistentHash(); Set<Integer> segmentsCache0 = ch.getSegmentsForOwner(address(0)); CacheStream<Map.Entry<Object, String>> stream = cache0.entrySet().stream(); if (!rehashAware) stream = stream.disableRehashAware(); Map<Object, String> entries = mapFromIterator(stream.filterKeySegments(segmentsCache0).iterator()); Map<Integer, Set<Map.Entry<Object, String>>> entriesPerSegment = generateEntriesPerSegment(keyPartitioner, entries.entrySet()); assertTrue(segmentsCache0.containsAll(entriesPerSegment.keySet())); verifyZeroInteractions(clusterStreamManager); assertTrue(new DistributedCacheStream(null).hasWriteBehindSharedStore(cache0.getCacheConfiguration().persistence())); }
Source:
<code>private void useCardKnight(GameUserBean gameUser, GameBean game) throws PlayException, GameException { cardUtil.validateUserDidNotUsedCardsInCurrentTurn(game); cardUtil.validateUserDidNotBoughtCardInCurrentTurn(gameUser, DevelopmentCard.KNIGHT); cardUtil.takeDevelopmentCardFromPlayer(gameUser, DevelopmentCard.KNIGHT); game.setRobberShouldBeMovedMandatory(true); game.setDevelopmentCardUsed(true); <START> gameUser.getAchievements().setTotalUsedKnights(gameUser.getAchievements().getTotalUsedKnights() + 1); <END> }</code><technical_language>i split this line for readability. gameUser.getAchievements() puted variable</technical_language>

Target:
private void useCardKnight(GameUserBean gameUser, GameBean game) throws PlayException, GameException { cardUtil.validateUserDidNotUsedCardsInCurrentTurn(game); cardUtil.validateUserDidNotBoughtCardInCurrentTurn(gameUser, DevelopmentCard.KNIGHT); cardUtil.takeDevelopmentCardFromPlayer(gameUser, DevelopmentCard.KNIGHT); game.setRobberShouldBeMovedMandatory(true); game.setDevelopmentCardUsed(true); Achievements achievements = gameUser.getAchievements(); int totalUsedKnightsNew = achievements.getTotalUsedKnights() + 1; achievements.setTotalUsedKnights(totalUsedKnightsNew); }
Source:
<code>public static Comparator<EventCrf> getCompareByOrdinal() { if(compareByOrdinal != null) { return compareByOrdinal; }else { compareByOrdinal = new Comparator<EventCrf>() { @Override public int compare(EventCrf o1, EventCrf o2) { Integer o1ordinal,o2ordinal; o1ordinal = getOrdinal(o1); o2ordinal = getOrdinal(o2); return o1ordinal.compareTo(o1ordinal); }; private Integer getOrdinal(EventCrf ec) { Integer ecOrdinal = null; <START> List<EventDefinitionCrf> edfcList1 = ec.getFormLayout().getCrf().getEventDefinitionCrfs(); <END> for(EventDefinitionCrf edfc: edfcList1) { if(edfc.getCrf().getOcOid().equals(ec.getFormLayout().getCrf().getOcOid())){ ecOrdinal = edfc.getOrdinal(); return ecOrdinal; } } return ecOrdinal; } }; } return compareByOrdinal; }</code><technical_language>test this logic events, Event1 & Event2 forms 1, 2 & 3 ordering in Event1 Event2</technical_language>

Target:
public static Comparator<EventCrf> getCompareByOrdinal() { if(compareByOrdinal != null) { return compareByOrdinal; }else { compareByOrdinal = new Comparator<EventCrf>() { @Override public int compare(EventCrf o1, EventCrf o2) { Integer o1ordinal,o2ordinal; o1ordinal = getOrdinal(o1); o2ordinal = getOrdinal(o2); return o1ordinal.compareTo(o2ordinal); }; private Integer getOrdinal(EventCrf ec) { Integer ecOrdinal = null; StudyEventDefinition sed1 = ec.studyEvent.getStudyEventDefinition(); List<EventDefinitionCrf> edfcList1 = ec.getFormLayout().getCrf().getEventDefinitionCrfs(); for(EventDefinitionCrf edfc: edfcList1) { StudyEventDefinition sed2 = edfc.getStudyEventDefinition(); if(edfc.getCrf().getOcOid().equals(ec.getFormLayout().getCrf().getOcOid()) && sed1.getOc_oid().equals(sed2.getOc_oid())){ ecOrdinal = edfc.getOrdinal(); return ecOrdinal; } } return ecOrdinal; } }; } return compareByOrdinal; }
Source:
<code>public void add(String lookupName, LookupExtractorFactoryContainer lookupExtractorFactoryContainer) { assertStarted(); try { <START> if (!queue.offer(new LoadNotice(lookupName, lookupExtractorFactoryContainer), 1, TimeUnit.MILLISECONDS)) { <END> throw new ISE("notice queue add timedout to add [%s] lookup drop notice", lookupName); } } catch (InterruptedException ex) { throw new ISE(ex, "failed to add [%s] lookup load notice", lookupName); } }</code><technical_language>If this a GC fail? 1ms short</technical_language>

Target:
public void add(String lookupName, LookupExtractorFactoryContainer lookupExtractorFactoryContainer) { Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)); addNotice(new LoadNotice(lookupName, lookupExtractorFactoryContainer)); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_form_entry_patient_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } FormEntryPatientListFragment formEntryPatientListFragment = (FormEntryPatientListFragment) getSupportFragmentManager().findFragmentById(R.id.formEntryPatientListContentFrame); if (formEntryPatientListFragment == null) { formEntryPatientListFragment = FormEntryPatientListFragment.newInstance(); } <START> addFragmentToActivity(getSupportFragmentManager(), <END> formEntryPatientListFragment, R.id.formEntryPatientListContentFrame); mPresenter = new FormEntryPatientListPresenter (formEntryPatientListFragment); }</code><technical_language>@tmarzeion check if fragment is added</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_form_entry_patient_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } FormEntryPatientListFragment formEntryPatientListFragment = (FormEntryPatientListFragment) getSupportFragmentManager().findFragmentById(R.id.formEntryPatientListContentFrame); if (formEntryPatientListFragment == null) { formEntryPatientListFragment = FormEntryPatientListFragment.newInstance(); } if (!formEntryPatientListFragment.isActive()) { addFragmentToActivity(getSupportFragmentManager(), formEntryPatientListFragment, R.id.formEntryPatientListContentFrame); } mPresenter = new FormEntryPatientListPresenter (formEntryPatientListFragment); }
Source:
<code>private RebalanceMode normalizeRebalanceMode(IdealStateModeProperty mode) { RebalanceMode property; switch (mode) { case AUTO_REBALANCE: property = RebalanceMode.FULL_AUTO; break; case AUTO: property = RebalanceMode.SEMI_AUTO; break; case CUSTOMIZED: property = RebalanceMode.CUSTOMIZED; break; default: String rebalancerName = getRebalancerClassName(); if (rebalancerName != null) { if (rebalancerName.equals(JobRebalancer.class.getName()) <START> || rebalancerName.equals(WorkflowRebalancer.class.getName())) { <END> property = RebalanceMode.TASK; } else { property = RebalanceMode.USER_DEFINED; } } else { property = RebalanceMode.SEMI_AUTO; } break; } return property; }</code><technical_language>this break compatibility for existing long-running TF resources</technical_language>

Target:
private RebalanceMode normalizeRebalanceMode(IdealStateModeProperty mode) { RebalanceMode property; switch (mode) { case AUTO_REBALANCE: property = RebalanceMode.FULL_AUTO; break; case AUTO: property = RebalanceMode.SEMI_AUTO; break; case CUSTOMIZED: property = RebalanceMode.CUSTOMIZED; break; default: String rebalancerName = getRebalancerClassName(); if (rebalancerName != null) { if (rebalancerName.equals(JobRebalancer.class.getName()) || rebalancerName.equals(WorkflowRebalancer.class.getName())) { property = RebalanceMode.TASK; } else { if (LEGACY_TASK_REBALANCERS.contains(rebalancerName)) { logger.warn("The rebalancer is not supported anymore. Setting rebalance mode to USER_DEFINED.", rebalancerName); } property = RebalanceMode.USER_DEFINED; } } else { property = RebalanceMode.SEMI_AUTO; } break; } return property; }
Source:
<code>public void testFreetemplateFileNameValidity() { final TextTemplate textTemplate = new TextTemplate(); textTemplate.setFreemarkerParsingExtensions("nxftl"); final File testResouceDirectory = new File(getClass().getClassLoader().getResource("test-nxftl").getPath()); final File tmpdir = new File(System.getProperty("java.io.tmpdir")); try { textTemplate.processDirectory(new File(testResouceDirectory, "tutu.xml.nxftl"), tmpdir); textTemplate.processDirectory(new File(testResouceDirectory, "tutu.nxftl"), tmpdir); } catch (Exception e) { <START> Assert.fail("Unexpected exception: " + e.getMessage()); <END> } final File failingFile = new File(testResouceDirectory, ".nxftl"); IOException exceptedException = null; try { textTemplate.processDirectory(failingFile, tmpdir); } catch (IOException expected) { exceptedException = expected; } catch (TemplateException e) { } Assert.assertNotNull(exceptedException); Assert.assertEquals("Template file : '" + failingFile.getAbsolutePath() + "' cannot be parsed. Launcher had to stop, please fix this problem." + System.getProperty("line.separator") + "It may be caused by its output name '" + tmpdir.getAbsolutePath() + "'", exceptedException.getMessage()); }</code><technical_language>need explicity fail here, remove try/catch block test method throws Exception</technical_language>

Target:
public void testFreetemplateFileNameValidity() throws Exception { File tmpdir = temporary.newFolder(); TextTemplate textTemplate = new TextTemplate(); textTemplate.setFreemarkerParsingExtensions("nxftl"); File testResouceDirectory = FileUtils.getResourceFileFromContext("test-nxftl"); textTemplate.processDirectory(new File(testResouceDirectory, "tutu.xml.nxftl"), tmpdir); textTemplate.processDirectory(new File(testResouceDirectory, "tutu.nxftl"), tmpdir); File failingFile = new File(testResouceDirectory, ".nxftl"); try { textTemplate.processDirectory(failingFile, tmpdir); fail("File name is invalid the call should not success"); } catch (IOException expected) { String expectedMessage = "Extension only as a filename is not allowed: " + failingFile.getAbsolutePath(); assertEquals(expectedMessage, expected.getMessage()); } }
Source:
<code>public CreateGlusterVolumeGeoRepSessionCommand(GlusterVolumeGeoRepSessionParameters params) { super(params); setGlusterVolumeId(getParameters().getVolumeId()); <START> session = getDbFacade().getGlusterGeoRepDao().getById(getParameters().getGeoRepSessionId()); <END> }</code><technical_language>for create session geoRepSessionId exist in parameters? session in db, right</technical_language>

Target:
public CreateGlusterVolumeGeoRepSessionCommand(GlusterVolumeGeoRepSessionParameters params) { super(params); setGlusterVolumeId(getParameters().getVolumeId()); setVdsGroupId(getGlusterVolume().getClusterId()); }
Source:
<code>private void notifyThingAboutRemoval(final Thing thing) { <START> logger.debug("Asking handler of thing '{}' to handle its removal.", thing.getUID()); <END> ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() { @Override public void run() { try { thing.getHandler().handleRemoval(); logger.trace("Handler of thing '{}' returned from handling its removal.", thing.getUID()); } catch (Exception ex) { logger.error("The ThingHandler caused an exception while handling the removal of its thing", ex); } } }); }</code><technical_language>trace</technical_language>

Target:
private void notifyThingAboutRemoval(final Thing thing) { logger.trace("Asking handler of thing '{}' to handle its removal.", thing.getUID()); ThreadPoolManager.getPool(THING_MANAGER_THREADPOOL_NAME).execute(new Runnable() { @Override public void run() { try { thing.getHandler().handleRemoval(); logger.trace("Handler of thing '{}' returned from handling its removal.", thing.getUID()); } catch (Exception ex) { logger.error("The ThingHandler caused an exception while handling the removal of its thing", ex); } } }); }
Source:
<code>public Response execute(Command command) throws WebDriverException, IOException { if (DriverCommand.NEW_SESSION.equals(command.getName())) { serviceOptional.ifPresent(driverService -> { try { driverService.start(); } catch (IOException e) { throw new WebDriverException(e.getMessage(), e); } }); } Response response; try { <START> if (!NEW_SESSION.equals(command.getName())) { <END> response = super.execute(command); } else { response = createSession(command); } } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")) { throw serviceOptional.map(service -> { if (service.isRunning()) { return new WebDriverException("The session is closed!", rootCause); } return new WebDriverException("The appium server has accidentally died!", rootCause); }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause)); } throwIfUnchecked(t); throw new WebDriverException(t); } finally { if (DriverCommand.QUIT.equals(command.getName())) { serviceOptional.ifPresent(DriverService::stop); } } if (DriverCommand.NEW_SESSION.equals(command.getName()) && getCommandCodec() instanceof W3CHttpCommandCodec) { setCommandCodec(new AppiumW3CHttpCommandCodec()); getAdditionalCommands().forEach(this::defineCommand); } return response; }</code><technical_language>ternary operator: response = NEW_SESSION.equals(command.getName()) ? createSession(command) : super.execute(command)</technical_language>

Target:
public Response execute(Command command) throws WebDriverException { if (DriverCommand.NEW_SESSION.equals(command.getName())) { serviceOptional.ifPresent(driverService -> { try { driverService.start(); } catch (IOException e) { throw new WebDriverException(e.getMessage(), e); } }); } Response response; try { response = NEW_SESSION.equals(command.getName()) ? createSession(command) : super.execute(command); } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); if (rootCause instanceof ConnectException && rootCause.getMessage().contains("Connection refused")) { throw serviceOptional.map(service -> { if (service.isRunning()) { return new WebDriverException("The session is closed!", rootCause); } return new WebDriverException("The appium server has accidentally died!", rootCause); }).orElseGet((Supplier<WebDriverException>) () -> new WebDriverException(rootCause.getMessage(), rootCause)); } throwIfUnchecked(t); throw new WebDriverException(t); } finally { if (DriverCommand.QUIT.equals(command.getName())) { serviceOptional.ifPresent(DriverService::stop); } } if (DriverCommand.NEW_SESSION.equals(command.getName()) && getCommandCodec() instanceof W3CHttpCommandCodec) { setCommandCodec(new AppiumW3CHttpCommandCodec()); getAdditionalCommands().forEach(this::defineCommand); } return response; }
Source:
<code>public void setValue(Object target, String fieldName, Object value) { Type<?> targetClass = getType(target); String targetType = getJsonAliasFor(targetClass); String fieldAlias = fieldName; try { Type<?> fieldClass = getType(targetClass, fieldName); String realName = getNameFromAlias(target, fieldName); fieldAlias = (realName != null) ? realName : fieldName; String setMethod = "set" + StringUtils.capitalize(fieldAlias); Method method = EntityDictionary.findMethod(targetClass, setMethod, fieldClass); method.invoke(target, coerce(target, value, fieldAlias, fieldClass)); } catch (IllegalAccessException e) { throw new InvalidAttributeException(fieldAlias, targetType, e); } catch (InvocationTargetException e) { throw handleInvocationTargetException(e); } catch (IllegalArgumentException | NoSuchMethodException noMethod) { AccessibleObject accessor = getAccessibleObject(target, fieldAlias); if (accessor != null && accessor instanceof Field) { Field field = (Field) accessor; try { <START> field.getField().set(target, coerce(target, value, fieldAlias, field.getType())); <END> } catch (IllegalAccessException noField) { throw new InvalidAttributeException(fieldAlias, targetType, noField); } } else { throw new InvalidAttributeException(fieldAlias, targetType); } } }</code><technical_language>this changed? want expose underlying types here. new Field class a set method</technical_language>

Target:
public void setValue(Object target, String fieldName, Object value) { Type<?> targetClass = getType(target); String targetType = getJsonAliasFor(targetClass); String fieldAlias = fieldName; try { Type<?> fieldClass = getType(targetClass, fieldName); String realName = getNameFromAlias(target, fieldName); fieldAlias = (realName != null) ? realName : fieldName; String setMethod = "set" + StringUtils.capitalize(fieldAlias); Method method = EntityDictionary.findMethod(targetClass, setMethod, fieldClass); method.invoke(target, coerce(target, value, fieldAlias, fieldClass)); } catch (IllegalAccessException e) { throw new InvalidAttributeException(fieldAlias, targetType, e); } catch (InvocationTargetException e) { throw handleInvocationTargetException(e); } catch (IllegalArgumentException | NoSuchMethodException noMethod) { AccessibleObject accessor = getAccessibleObject(target, fieldAlias); if (accessor != null && accessor instanceof Field) { Field field = (Field) accessor; try { field.set(target, coerce(target, value, fieldAlias, field.getType())); } catch (IllegalAccessException noField) { throw new InvalidAttributeException(fieldAlias, targetType, noField); } } else { throw new InvalidAttributeException(fieldAlias, targetType); } } }
Source:
<code>public <T> ParamConverter<T> getConverter( final Class<T> rawType, final Type genericType, final Annotation[] annotations) { if (Optional.class.equals(rawType)) { final List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(genericType); final ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null; if (ctp == null || ctp.rawClass() == String.class) { return new ParamConverter<T>() { @Override public T fromString(final String value) { return rawType.cast(Optional.ofNullable(value)); } @Override public String toString(final T value) { return value.toString(); } }; } for (ParamConverterProvider provider : Providers.getProviders(injectionManager, ParamConverterProvider.class)) { final ParamConverter<?> converter = provider.getConverter(ctp.rawClass(), ctp.type(), annotations); if (converter != null) { return new ParamConverter<T>() { @Override public T fromString(final String value) { <START> return rawType.cast(Optional.ofNullable(value).map(_s -> converter.fromString(value))); <END> } @Override public String toString(final T value) { return value.toString(); } }; } } } return null; }</code><technical_language>This is a fun</technical_language>

Target:
public <T> ParamConverter<T> getConverter( final Class<T> rawType, final Type genericType, final Annotation[] annotations) { if (Optional.class.equals(rawType)) { final List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(genericType); final ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null; if (ctp == null || ctp.rawClass() == String.class) { return new ParamConverter<T>() { @Override public T fromString(final String value) { return rawType.cast(Optional.ofNullable(value)); } @Override public String toString(final T value) { return value.toString(); } }; } for (ParamConverterProvider provider : Providers.getProviders(injectionManager, ParamConverterProvider.class)) { final ParamConverter<?> converter = provider.getConverter(ctp.rawClass(), ctp.type(), annotations); if (converter != null) { return new ParamConverter<T>() { @Override public T fromString(final String value) { return rawType.cast(Optional.ofNullable(value).map(converter::fromString)); } @Override public String toString(final T value) { return value.toString(); } }; } } } return null; }
Source:
<code><START> public void doUpdateCacheMembers(int viewId, Throwable throwable) throws Throwable { <END> if (throwable instanceof SuspectException) { log.tracef("Node %s left while updating cache members", ((SuspectException) throwable).getSuspect()); } else if (throwable != null) { throw throwable; } int newViewId = transport.getViewId(); if (newViewId != viewId) { log.debugf("Skipping cache members update for view %d after receiving view %d", viewId, newViewId); return; } for (ClusterCacheStatus cacheStatus : cacheStatusMap.values()) { cacheStatus.doHandleClusterView(viewId); } }</code><technical_language>Method a bit superfluous - Do if consolidated a bit nicer? I personally a big fan of exceptions for flow control catch in class ignore it</technical_language>

Target:
private void doUpdateCacheMembers(int viewId, Throwable throwable) { try { if (throwable == null) { int newViewId = transport.getViewId(); if (newViewId != viewId) { log.debugf("Skipping cache members update for view %d, newer view received: %d", viewId, newViewId); return; } for (ClusterCacheStatus cacheStatus : cacheStatusMap.values()) { cacheStatus.doHandleClusterView(viewId); } } else if (throwable instanceof SuspectException) { Address leaver = ((SuspectException) throwable).getSuspect(); log.debugf("Skipping cache members update for view %d, node %s left", viewId, leaver); return; } } catch (Throwable t) { throwable = t; } if (clusterManagerStatus.isRunning()) { log.errorUpdatingMembersList(viewId, throwable); } }
Source:
<code>private Element createRootElement(Document doc, LookupTransactionManagerProviderConfiguration lookupTransactionManagerProviderConfiguration) { <START> Element rootElement = doc.createElement(TRANSACTION_NAMESPACE_PREFIX + COLON + TRANSACTION_ELEMENT_NAME); <END> rootElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + TRANSACTION_NAMESPACE_PREFIX, NAMESPACE.toString()); rootElement.setAttribute(TRANSACTION_LOOKUP_CLASS, lookupTransactionManagerProviderConfiguration.getTransactionManagerLookup() .getName()); return rootElement; }</code><technical_language>createElementNS(...)</technical_language>

Target:
protected Element createRootElement(Document doc, LookupTransactionManagerProviderConfiguration lookupTransactionManagerProviderConfiguration) { Element rootElement = doc.createElementNS(NAMESPACE.toString(), TRANSACTION_NAMESPACE_PREFIX + COLON + TRANSACTION_ELEMENT_NAME); rootElement.setAttribute(TRANSACTION_LOOKUP_CLASS, lookupTransactionManagerProviderConfiguration.getTransactionManagerLookup() .getName()); return rootElement; }
Source:
<code>private static Stream<ExpressionTree> findStringArg(MethodInvocationTree mit) { return mit.arguments().stream() <START> .filter(arg -> arg.symbolType().is(String.class.getCanonicalName())); <END> }</code><technical_language>Reuse STRING constant</technical_language>

Target:
private static Stream<ExpressionTree> findStringArg(MethodInvocationTree mit) { return mit.arguments().stream() .filter(arg -> arg.symbolType().is("java.lang.String")); }
Source:
<code>public void run() { running = true; LOG.debug("RootCache Started"); final long rootPartitionId = INode.calculatePartitionId(HdfsConstantsClient.GRANDFATHER_INODE_ID, INodeDirectory.ROOT_NAME, INodeDirectory.ROOT_DIR_DEPTH); LightWeightRequestHandler getRootINode = new LightWeightRequestHandler(HDFSOperationType.GET_ROOT) { @Override public Object performTask() throws IOException { INodeDataAccess da = (INodeDataAccess) HdfsStorageFactory .getDataAccess(INodeDataAccess.class); INode rootINode = (INode) da.findInodeByNameParentIdAndPartitionIdPK(INodeDirectory.ROOT_NAME, HdfsConstantsClient.GRANDFATHER_INODE_ID, rootPartitionId); return rootINode; } }; while (running) { try { Thread.sleep(UPDATE_TIMER); INode rootInodeRet = (INode) getRootINode.handle(); if (rootInodeRet != null) { synchronized (rootCacheUpdater) { rootINode = rootInodeRet; } } else { LOG.debug("RootCache: root does not exist."); } } catch (InterruptedException e) { <START> LOG.warn(e); <END> } catch (IOException e) { LOG.warn(e); } } }</code><technical_language>interrupt current thread if received InterruptedException</technical_language>

Target:
public void run() { running = true; LOG.debug("RootCache Started"); final long rootPartitionId = INode.calculatePartitionId(HdfsConstantsClient.GRANDFATHER_INODE_ID, INodeDirectory.ROOT_NAME, INodeDirectory.ROOT_DIR_DEPTH); LightWeightRequestHandler getRootINode = new LightWeightRequestHandler(HDFSOperationType.GET_ROOT) { @Override public Object performTask() throws IOException { INodeDataAccess da = (INodeDataAccess) HdfsStorageFactory .getDataAccess(INodeDataAccess.class); INode rootINode = (INode) da.findInodeByNameParentIdAndPartitionIdPK(INodeDirectory.ROOT_NAME, HdfsConstantsClient.GRANDFATHER_INODE_ID, rootPartitionId); return rootINode; } }; while (running) { try { Thread.sleep(UPDATE_TIMER); INode rootInodeRet = (INode) getRootINode.handle(); if (rootInodeRet != null) { synchronized (rootCacheUpdater) { rootINode = rootInodeRet; } } else { LOG.debug("RootCache: root does not exist."); } } catch (InterruptedException e) { LOG.warn(e); Thread.currentThread().interrupt(); } catch (IOException e) { LOG.warn(e); } } }