auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void enqueueTask(NotificationContext changeContext) throws Exception { if (_batchModeEnabled && changeContext.getType() == NotificationContext.Type.CALLBACK) { logger.debug("Callbackhandler {}, Enqueuing callback", this._uid ); if (!isReady()) { logger.info("CallbackHandler is not ready, ignore change callback from path: {}, for " <START> + "listener: {}", this._uid, _path, _listener); <END> } else { synchronized (this) { if (_batchCallbackProcessor != null) { _batchCallbackProcessor.queueEvent(changeContext.getType(), changeContext); } else { throw new HelixException( "Failed to process callback in batch mode. Batch Callback Processor does not exist."); } } } } else { invoke(changeContext); } if (_monitor != null) { _monitor.increaseCallbackUnbatchedCounters(); } }</code><technical_language>nit, "this." in "this._uid" is necessary, right? places</technical_language>

Target:
public void enqueueTask(NotificationContext changeContext) throws Exception { if (_batchModeEnabled && changeContext.getType() == NotificationContext.Type.CALLBACK) { logger.debug("Callbackhandler {}, Enqueuing callback", _uid ); if (!isReady()) { logger.info("CallbackHandler is not ready, ignore change callback from path: {}, for " + "listener: {}", _uid, _path, _listener); } else { synchronized (this) { if (_batchCallbackProcessor != null) { _batchCallbackProcessor.queueEvent(changeContext.getType(), changeContext); } else { throw new HelixException( "Failed to process callback in batch mode. Batch Callback Processor does not exist."); } } } } else { invoke(changeContext); } if (_monitor != null) { _monitor.increaseCallbackUnbatchedCounters(); } }
Source:
<code>public void stopTask(boolean forceFinish) { if (getState() != AsyncTaskState.AttemptingEndAction && getState() != AsyncTaskState.Cleared && getState() != AsyncTaskState.ClearFailed && !getLastTaskStatus().getTaskIsInUnusualState()) { try { log.info("SPMAsyncTask::StopTask: Attempting to stop task '{}' (Parent Command '{}', Parameters" + " Type '{}').", getVdsmTaskId(), getParameters().getDbAsyncTask().getActionType(), getParameters().getClass().getName()); coco.stopTask(getStoragePoolID(), getVdsmTaskId()); } catch (RuntimeException e) { <START> log.error("SPMAsyncTask::StopTask: Stopping task '{}' threw an exception: {}", <END> getVdsmTaskId(), e.getMessage()); log.debug("Exception", e); } finally { if (forceFinish) { setState(AsyncTaskState.Ended); setLastTaskStatus(new AsyncTaskStatus(AsyncTaskStatusEnum.finished)); } else { setState(AsyncTaskState.Polling); } } } }</code><technical_language>Error during... remove threw excpetion</technical_language>

Target:
public void stopTask(boolean forceFinish) { if (getState() != AsyncTaskState.AttemptingEndAction && getState() != AsyncTaskState.Cleared && getState() != AsyncTaskState.ClearFailed && !getLastTaskStatus().getTaskIsInUnusualState()) { try { log.info("SPMAsyncTask::StopTask: Attempting to stop task '{}' (Parent Command '{}', Parameters" + " Type '{}').", getVdsmTaskId(), getParameters().getDbAsyncTask().getActionType(), getParameters().getClass().getName()); coco.stopTask(getStoragePoolID(), getVdsmTaskId()); } catch (RuntimeException e) { log.error("SPMAsyncTask::StopTask: Error during stopping task '{}': {}", getVdsmTaskId(), e.getMessage()); log.debug("Exception", e); } finally { if (forceFinish) { setState(AsyncTaskState.Ended); setLastTaskStatus(new AsyncTaskStatus(AsyncTaskStatusEnum.finished)); } else { setState(AsyncTaskState.Polling); } } } }
Source:
<code><START> public synchronized void tearDown() { <END> executorToShutdown.shutdown(); }</code><technical_language>synchronized</technical_language>

Target:
public void tearDown() { executorToShutdown.shutdown(); }
Source:
<code>private void setPlacementStrategy(EcsClientConfig clientConfig, RunTaskRequest runTaskRequest) throws ConfigException { if (clientConfig.getPlacementStrategyType().isPresent()) { final PlacementStrategyType placementStrategyType; try { placementStrategyType = PlacementStrategyType.fromValue(clientConfig.getPlacementStrategyType().get()); } <START> catch (IllegalArgumentException invalidReason) { <END> throw new ConfigException("PlacementStrategyType is invalid", invalidReason); } final PlacementStrategy placementStrategy = new PlacementStrategy(); placementStrategy.setType(placementStrategyType); if (clientConfig.getPlacementStrategyField().isPresent()) { placementStrategy.setField(clientConfig.getPlacementStrategyField().get()); } runTaskRequest.setPlacementStrategy(Arrays.asList(placementStrategy)); } }</code><technical_language>[minor] invalidReason sounds a bit weird this is a exception here. If extracted a pure reason-like object exception Reason invalidReason = ex.getReason(), good</technical_language>

Target:
private void setPlacementStrategy(EcsClientConfig clientConfig, RunTaskRequest runTaskRequest) throws ConfigException { if (clientConfig.getPlacementStrategyType().isPresent()) { final PlacementStrategyType placementStrategyType; try { placementStrategyType = PlacementStrategyType.fromValue(clientConfig.getPlacementStrategyType().get()); } catch (IllegalArgumentException validationError) { throw new ConfigException("PlacementStrategyType is invalid", validationError); } final PlacementStrategy placementStrategy = new PlacementStrategy(); placementStrategy.setType(placementStrategyType); if (clientConfig.getPlacementStrategyField().isPresent()) { placementStrategy.setField(clientConfig.getPlacementStrategyField().get()); } runTaskRequest.setPlacementStrategy(Arrays.asList(placementStrategy)); } }
Source:
<code>private static void invokeForEachKeyFactoryPair(KeyFactoryPairRunnable runnable) throws Exception { for (Provider provider1 : getKeyFactoryProviders()) { for (Provider provider2 : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider1), getKeyFactory(provider2)); <START> } catch (Exception e) { <END> throw new Exception("provider1: " + provider1.getName() + ", provider2: " + provider2.getName(), e); } } } }</code><technical_language>others catch Throwable if want fix one, fix</technical_language>

Target:
private static void invokeForEachKeyFactoryPair(KeyFactoryPairRunnable runnable) throws Exception { for (Provider provider1 : getKeyFactoryProviders()) { for (Provider provider2 : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider1), getKeyFactory(provider2)); } catch (Throwable e) { throw new Exception("provider1: " + provider1.getName() + ", provider2: " + provider2.getName(), e); } } } }
Source:
<code>public void internalStop() throws Exception { server.stop(); if (webContexts != null) { File tmpdir = null; for (WebAppContext context : webContexts) { tmpdir = context.getTempDirectory(); if (tmpdir != null && !context.isPersistTempDirectory()) { boolean fileDeleted = TimeUtils.waitOnBoolean(false, 5000, tmpdir::exists); if (!fileDeleted) { FileUtil.deleteDirectory(tmpdir); <START> ActiveMQWebLogger.LOGGER.tmpFileForceDelete(tmpdir); <END> if (tmpdir.exists()) { ActiveMQWebLogger.LOGGER.tmpFileNotDeleted(tmpdir); } } } } webContexts.clear(); } }</code><technical_language>ActiveMQWebLogger.LOGGER.debug("..."); work... I prefer actual logger debug trace</technical_language>

Target:
public void internalStop() throws Exception { server.stop(); if (webContexts != null) { File tmpdir = null; for (WebAppContext context : webContexts) { tmpdir = context.getTempDirectory(); if (tmpdir != null && !context.isPersistTempDirectory()) { boolean fileDeleted = TimeUtils.waitOnBoolean(false, 5000, tmpdir::exists); if (!fileDeleted) { FileUtil.deleteDirectory(tmpdir); logger.debug("Force to delete temporary file on shutdown: " + tmpdir.getAbsolutePath()); if (tmpdir.exists()) { ActiveMQWebLogger.LOGGER.tmpFileNotDeleted(tmpdir); } } } } webContexts.clear(); } }
Source:
<code>public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); validateNonEditableProperty(entity); List<FieldDto> entityFields = getEntityFields(entityRecord.getEntitySchemaId()); <START> List<FieldRecord> fieldRecords = entityRecord.getFields(); <END> for(FieldRecord field : fieldRecords) { if(field.getType().getTypeClass().equals(UUID.class.getName())) { field.setValue(UUID.randomUUID()); } } try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = newInstanceFromEntityRecord(entityClass, entityFields, entityRecord.getFields(), service); return service.create(instance); } else { instance = service.retrieve(ID_FIELD_NAME, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(entity.getName(), entityRecord.getId()); } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, true); return service.update(instance); } } catch (Exception e) { if (entityRecord.getId() == null) { throw new ObjectCreateException(entity.getName(), e); } else { throw new ObjectUpdateException(entity.getName(), entityRecord.getId(), e); } } }</code><technical_language>set this field here, is a setProperty method. Additionally support setting UUID field end user</technical_language>

Target:
public Object saveInstance(EntityRecord entityRecord, Long deleteValueFieldId) { EntityDto entity = getEntity(entityRecord.getEntitySchemaId()); validateCredentials(entity); validateNonEditableProperty(entity); List<FieldDto> entityFields = getEntityFields(entityRecord.getEntitySchemaId()); try { MotechDataService service = getServiceForEntity(entity); Class<?> entityClass = getEntityClass(entity); boolean newObject = entityRecord.getId() == null; Object instance; if (newObject) { instance = newInstanceFromEntityRecord(entityClass, entityFields, entityRecord.getFields(), service); return service.create(instance); } else { instance = service.retrieve(ID_FIELD_NAME, entityRecord.getId()); if (instance == null) { throw new ObjectNotFoundException(entity.getName(), entityRecord.getId()); } updateFields(instance, entityRecord.getFields(), service, deleteValueFieldId, true); return service.update(instance); } } catch (Exception e) { if (entityRecord.getId() == null) { throw new ObjectCreateException(entity.getName(), e); } else { throw new ObjectUpdateException(entity.getName(), entityRecord.getId(), e); } } }
Source:
<code>public void doDecryptSucceeds() throws Exception { final Path path = ddfHome.resolve(TEST_DIRECTORY); configurationMigrationManager = spy(getConfigurationMigrationManager()); configurationMigrationManager.doExport(path); expectImportDelegationIsSuccessful(); final MigrationReport report = configurationMigrationManager.doDecrypt(path); assertThat("Decrypt was not successful", report.wasSuccessful(), is(true)); reportHasInfoMessage( report.infos(), equalTo( "Successfully decrypted file [" <START> + path.resolve(TEST_BRANDING) <END> + "-" + TEST_VERSION + ".dar] to [" + path.resolve(TEST_BRANDING) + "-" + TEST_VERSION + ".zip].")); verify(configurationMigrationManager) .delegateToDecryptMigrationManager( any(MigrationReportImpl.class), any(MigrationZipFile.class), any(Path.class)); }</code><technical_language>private method(s) build .dar .zip file names code shorter/clearer</technical_language>

Target:
public void doDecryptSucceeds() throws Exception { expectZipWithChecksum(true); expectDecryptDelegationIsSuccessful(); final MigrationReport report = configurationMigrationManager.doDecrypt(path); assertThat("Decrypt was not successful", report.wasSuccessful(), is(true)); reportHasInfoMessage( report.infos(), equalTo( "Successfully decrypted file [" + encryptedFileName + "] to [" + decryptedFileName + "].")); verify(configurationMigrationManager) .delegateToDecryptMigrationManager( any(MigrationReportImpl.class), any(MigrationZipFile.class), eq(Paths.get(decryptedFileName))); verifyZipEncryptedFile(); }
Source:
<code>private void parseIncompleteRoot(CommonTree root) throws ParseException { List<CommonTree> children = root.getChildren(); if (fHasBeenParsed == false) { throw new ParseException("You need to run generate first"); } List<CommonTree> streams = new ArrayList<>(); List<CommonTree> events = new ArrayList<>(); List<CommonTree> declarations = new ArrayList<>(); List<CommonTree> environments = new ArrayList<>(); List<CommonTree> clocks = new ArrayList<>(); List<CommonTree> callsites = new ArrayList<>(); pushScope(); for (CommonTree child : children) { final int type = child.getType(); switch (type) { case CTFParser.DECLARATION: declarations.add(child); break; case CTFParser.TRACE: <START> throw new ParseException("Trace block defined here, please use generate and not generateFragment parse this chunk"); END> case CTFParser.STREAM: streams.add(child); break; case CTFParser.EVENT: events.add(child); break; case CTFParser.CLOCK: clocks.add(child); break; case CTFParser.ENV: environments.add(child); break; case CTFParser.CALLSITE: callsites.add(child); break; default: childTypeError(child); } } for (CommonTree decl : declarations) { parseRootDeclaration(decl); } for (CommonTree environment : environments) { parseEnvironment(environment); } for (CommonTree clock : clocks) { parseClock(clock); } for (CommonTree callsite : callsites) { parseCallsite(callsite); } for (CommonTree stream : streams) { parseStream(stream); } for (CommonTree event : events) { parseEvent(event); } popScope(); }</code><technical_language>"*to* parse this chunk"</technical_language>

Target:
private void parseIncompleteRoot(CommonTree root) throws ParseException { List<CommonTree> children = root.getChildren(); if (fHasBeenParsed == false) { throw new ParseException("You need to run generate first"); } List<CommonTree> streams = new ArrayList<>(); List<CommonTree> events = new ArrayList<>(); List<CommonTree> declarations = new ArrayList<>(); List<CommonTree> environments = new ArrayList<>(); List<CommonTree> clocks = new ArrayList<>(); List<CommonTree> callsites = new ArrayList<>(); pushScope(); for (CommonTree child : children) { final int type = child.getType(); switch (type) { case CTFParser.DECLARATION: declarations.add(child); break; case CTFParser.TRACE: throw new ParseException("Trace block defined here, please use generate and not generateFragment to parse this fragment"); case CTFParser.STREAM: streams.add(child); break; case CTFParser.EVENT: events.add(child); break; case CTFParser.CLOCK: clocks.add(child); break; case CTFParser.ENV: environments.add(child); break; case CTFParser.CALLSITE: callsites.add(child); break; default: childTypeError(child); } } for (CommonTree decl : declarations) { parseRootDeclaration(decl); } for (CommonTree environment : environments) { parseEnvironment(environment); } for (CommonTree clock : clocks) { parseClock(clock); } for (CommonTree callsite : callsites) { parseCallsite(callsite); } for (CommonTree stream : streams) { parseStream(stream); } for (CommonTree event : events) { parseEvent(event); } popScope(); }
Source:
<code>private void writeToFile(ZonedDateTime time) { try ( <START> FileOutputStream fos = new FileOutputStream(lastEventPollingPath.toFile()); <END> ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(time); } catch (Exception e) { } }</code><technical_language>try resources close stream</technical_language>

Target:
private void writeToFile(ZonedDateTime time) { try { Files.write(lastEventPollingPath, Long.toString(time.toInstant().toEpochMilli()).getBytes(Charset.defaultCharset())); } catch (IOException e) { } }
Source:
<code><START> public synchronized void updateCommittedTail(long newCommittedTail) { <END> committedTail.updateAndGet(curr -> { if (newCommittedTail <= curr) { return curr; } return newCommittedTail; }); }</code><technical_language>Is synchronized necessary here</technical_language>

Target:
public void updateCommittedTail(long newCommittedTail) { committedTail.updateAndGet(curr -> { if (newCommittedTail <= curr) { return curr; } return newCommittedTail; }); }
Source:
<code>public void testMessageConverterConfigurer() throws Exception { final CountDownLatch latch = new CountDownLatch(1); MessageHandler messageHandler = new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { latch.countDown(); } }; <START> testSink.input().subscribe(messageHandler); <END> testSink.input().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}").build()); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); testSink.input().unsubscribe(messageHandler); }</code><technical_language>assert message more</technical_language>

Target:
public void testMessageConverterConfigurer() throws Exception { final CountDownLatch latch = new CountDownLatch(1); MessageHandler messageHandler = new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { assertThat(message.getPayload()).isInstanceOf(byte[].class); assertThat(message.getPayload()).isEqualTo("{\"message\":\"Hi\"}".getBytes()); latch.countDown(); } }; testSink.input().subscribe(messageHandler); testSink.input().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}".getBytes()).build()); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); testSink.input().unsubscribe(messageHandler); }
Source:
<code>public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { <START> if (invocation.getAttachments() != null) { <END> long start = System.currentTimeMillis(); invocation.getAttachments().put(TIMEOUT_FILTER_START_TIME, String.valueOf(start)); } return invoker.invoke(invocation); }</code><technical_language>If is attachement for invocation, handle fix timeout care create a attachment set TIMEOUT_FILTER_START_TIME ? do say</technical_language>

Target:
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (invocation.getAttachments() != null) { long start = System.currentTimeMillis(); invocation.getAttachments().put(TIMEOUT_FILTER_START_TIME, String.valueOf(start)); } else { if (invocation instanceof RpcInvocation) { RpcInvocation invc = (RpcInvocation) invocation; long start = System.currentTimeMillis(); invc.setAttachment(TIMEOUT_FILTER_START_TIME, String.valueOf(start)); } } return invoker.invoke(invocation); }
Source:
<code><START> @BeforeClass public static void beforeClass() { <END> firefoxdriver().setup(); }</code><technical_language>tests for Firefox Chrome drivers</technical_language>

Target:
@BeforeClass public static void beforeClass() { chromedriver().setup(); }
Source:
<code><START> public int getUsageWidth() { <END> return usageWidth; }</code><technical_language>propose Java Bean convention full scale for getters all. else violates "Principle Of Astonishment". Hope point, thinking confused in some years. JavaBeans convention is ok, right in this point. BTW: getters package protected else need them. difficult change if protection is open</technical_language>

Target:
int getUsageWidth() { return usageWidth; }
Source:
<code>public static void updateApplicablePoolDomainsStatuses(Guid storagePoolId, <START> Set<StorageDomainStatus> applicableStatusesForUpdate, <END> StorageDomainStatus newStatus) { List<StoragePoolIsoMap> storagesStatusInPool = DbFacade.getInstance() .getStoragePoolIsoMapDao().getAllForStoragePool(storagePoolId); for (StoragePoolIsoMap storageStatusInPool : storagesStatusInPool) { if (storageStatusInPool.getStatus() != null && storageStatusInPool.getStatus() != newStatus && applicableStatusesForUpdate.contains(storageStatusInPool.getStatus())) { storageStatusInPool.setStatus(newStatus); DbFacade.getInstance() .getStoragePoolIsoMapDao() .updateStatus(storageStatusInPool.getId(), storageStatusInPool.getStatus()); } } }</code><technical_language>Suggestion: 1) storageDomainMonitoredStatus access modifier private 2) overload method applicableStatusesForUpdate parameter, variable internally, instead force client pass a variable method it</technical_language>

Target:
public static void updateApplicablePoolDomainsStatuses(Guid storagePoolId, Set<StorageDomainStatus> applicableStatusesForUpdate, StorageDomainStatus newStatus) { List<StoragePoolIsoMap> storagesStatusInPool = DbFacade.getInstance() .getStoragePoolIsoMapDao().getAllForStoragePool(storagePoolId); for (StoragePoolIsoMap storageStatusInPool : storagesStatusInPool) { if (storageStatusInPool.getStatus() != null && storageStatusInPool.getStatus() != newStatus && applicableStatusesForUpdate.contains(storageStatusInPool.getStatus())) { log.infoFormat("Updating Storage Domain status from %1s to %2s", storageStatusInPool.getStatus().name(), newStatus.name()); storageStatusInPool.setStatus(newStatus); DbFacade.getInstance() .getStoragePoolIsoMapDao() .updateStatus(storageStatusInPool.getId(), storageStatusInPool.getStatus()); } } }
Source:
<code>public static ProjectReadAccessType from( final String value ) { <START> if ( value.equalsIgnoreCase( PUBLIC.toString() ) ) <END> { return PUBLIC; } else if ( value.equalsIgnoreCase( PRIVATE.toString() ) ) { return PRIVATE; } else if ( value.equalsIgnoreCase( CUSTOM.toString() ) ) { return CUSTOM; } throw new IllegalArgumentException( "Cannot parse ProjectReadAccessType value: " + value ); }</code><technical_language>@vbradnitski NULL, PRIVATE.name().equals(value) Objects.equals(PRIVATE.name(), value). ProjectReadAccessType.valueOf(...)</technical_language>

Target:
public static ProjectReadAccessType from( final String value ) { if ( PUBLIC.value.equals( value ) ) { return PUBLIC; } else if ( PRIVATE.value.equals( value ) ) { return PRIVATE; } else if ( CUSTOM.value.equals( value ) ) { return CUSTOM; } throw new IllegalArgumentException( "Cannot parse ProjectReadAccessType value: " + value ); }
Source:
<code>public ASTNode visit(Module module, Void _) { newRules = new ArrayList<ModuleItem>(); Module newModule = (Module)super.visit(module, _); Module returnModule; if (newRules.isEmpty()) { returnModule = newModule; } else { returnModule = newModule.shallowCopy(); <START> returnModule = returnModule.setModuleItems(newRules); <END> } return returnModule; }</code><technical_language>Explain</technical_language>

Target:
public ASTNode visit(Module module, Void _) { newRules = new ArrayList<ModuleItem>(); Module newModule = (Module)super.visit(module, _); Module returnModule; if (newRules.isEmpty()) { returnModule = newModule; } else { returnModule = newModule.shallowCopy(); returnModule = returnModule.addModuleItems(newRules); } return returnModule; }
Source:
<code>public void testExpiry() throws Exception { String jobName = "Expiry"; long expiry = 1000L; Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(100)); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(commandConfig); <START> WorkflowConfig.Builder wfgBuilder = new WorkflowConfig.Builder().setJobPurgeInterval(-1); <END> WorkflowConfig wfg = wfgBuilder.build(); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName, jobBuilder) .setWorkflowConfig(wfg) .setExpiry(expiry).build(); _driver.start(flow); _driver.pollForWorkflowState(jobName, TaskState.IN_PROGRESS); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey workflowCfgKey = accessor.keyBuilder().resourceConfig(jobName); String workflowPropStoreKey = Joiner.on("/").join(TaskConstants.REBALANCER_CONTEXT_ROOT, jobName); Assert.assertTrue( _manager.getHelixPropertyStore().exists(workflowPropStoreKey, AccessOption.PERSISTENT)); Assert.assertNotSame(accessor.getProperty(workflowCfgKey), null); _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); long finishTime = _driver.getWorkflowContext(jobName).getFinishTime(); Assert.assertTrue(TestHelper.verify( () -> (!_manager.getHelixPropertyStore().exists(workflowPropStoreKey, AccessOption.PERSISTENT) && accessor.getProperty(workflowCfgKey) == null), TestHelper.WAIT_DURATION)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - finishTime >= expiry); }</code><technical_language>wfBuilder</technical_language>

Target:
public void testExpiry() throws Exception { String jobName = "Expiry"; long expiry = 1000L; Map<String, String> commandConfig = ImmutableMap.of(MockTask.JOB_DELAY, String.valueOf(100)); JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG); jobBuilder.setJobCommandConfigMap(commandConfig); Workflow flow = WorkflowGenerator.generateSingleJobWorkflowBuilder(jobName, jobBuilder) .setExpiry(expiry).build(); _driver.start(flow); _driver.pollForWorkflowState(jobName, TaskState.IN_PROGRESS); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey workflowCfgKey = accessor.keyBuilder().resourceConfig(jobName); String workflowPropStoreKey = Joiner.on("/").join(TaskConstants.REBALANCER_CONTEXT_ROOT, jobName); Assert.assertTrue( _manager.getHelixPropertyStore().exists(workflowPropStoreKey, AccessOption.PERSISTENT)); Assert.assertNotSame(accessor.getProperty(workflowCfgKey), null); _driver.pollForWorkflowState(jobName, TaskState.COMPLETED); long finishTime = _driver.getWorkflowContext(jobName).getFinishTime(); Assert.assertTrue(TestHelper.verify( () -> (!_manager.getHelixPropertyStore().exists(workflowPropStoreKey, AccessOption.PERSISTENT) && accessor.getProperty(workflowCfgKey) == null), TestHelper.WAIT_DURATION)); long cleanUpTime = System.currentTimeMillis(); Assert.assertTrue(cleanUpTime - finishTime >= expiry); }
Source:
<code>private void setNormalBackgroundColor() { if (noResults) { Color currentColor = patternField.getBackground(); patternField.setData(CCS_CLASS_KEY, null); patternField.reskin(SWT.ALL); <START> patternField.update(); <END> if (currentColor.equals(patternField.getBackground())) { patternField.setBackground(null); } noResults = false; } }</code><technical_language>Is this necessary? If I remove update line work</technical_language>

Target:
private void setNormalBackgroundColor() { if (noResults) { Color currentColor = patternField.getBackground(); patternField.setData(CCS_CLASS_KEY, null); patternField.reskin(SWT.ALL); if (currentColor.equals(patternField.getBackground())) { patternField.setBackground(null); } noResults = false; } }
Source:
<code>public DialogAnonymization(Shell shell, Model model) { super(shell); this.title = Resources.getMessage("DialogAnonymization.0"); this.message = Resources.getMessage("DialogAnonymization.1"); this.configuration = model.getAnonymizationConfiguration(); this.configurationValid = true; EDDifferentialPrivacy edp = model.getInputConfig().getCriterion(EDDifferentialPrivacy.class); if (edp != null) { this.optimalSearchAvailable = false; this.heuristicSearchStepLimitAvailable = edp.isDataDependent(); <START> this.heuristicSearchTimeLimitAvailable = false; <END> } else { this.optimalSearchAvailable = model.getSolutionSpaceSize() <= model.getHeuristicSearchThreshold(); this.heuristicSearchStepLimitAvailable = true; this.heuristicSearchTimeLimitAvailable = true; } this.localRecodingAvailable = true; for (PrivacyCriterion c : model.getInputConfig().getCriteria()) { if (!c.isLocalRecodingSupported()) { this.localRecodingAvailable = false; break; } } }</code><technical_language>PrivacyModel.isHeuristicSearchSupported(); defaults true PrivacyModel.isHeuristicSearchWithTimeLimitSupported(); defaults true -> Overwrite for EDP</technical_language>

Target:
public DialogAnonymization(Shell shell, Model model) { super(shell); this.title = Resources.getMessage("DialogAnonymization.0"); this.message = Resources.getMessage("DialogAnonymization.1"); this.configuration = model.getAnonymizationConfiguration(); this.configurationValid = true; this.localRecodingAvailable = true; this.heuristicSearchStepLimitAvailable = true; this.heuristicSearchTimeLimitAvailable = true; this.optimalSearchAvailable = model.getSolutionSpaceSize() <= model.getHeuristicSearchThreshold(); for (PrivacyCriterion c : model.getInputConfig().getCriteria()) { if (!c.isLocalRecodingSupported()) { this.localRecodingAvailable = false; } if (!c.isOptimalSearchSupported()) { this.optimalSearchAvailable = false; } if (!c.isHeuristicSearchSupported()) { this.heuristicSearchStepLimitAvailable = false; } if (!c.isHeuristicSearchWithTimeLimitSupported()) { this.heuristicSearchTimeLimitAvailable = false; } } }
Source:
<code>void move(byte[] encodedRegionName, ServerName destServerName) throws IOException; void assign(byte[] regionName) throws IOException; void unassign(byte[] regionName, boolean force) throws IOException; void offline(byte[] regionName) throws IOException; boolean balancerSwitch(boolean onOrOff, boolean synchronous) throws IOException; boolean balance() throws IOException; boolean balance(boolean force) throws IOException; boolean isBalancerEnabled() throws IOException; CacheEvictionStats clearBlockCache(final TableName tableName) throws IOException; <START> boolean normalize() throws IOException; <END> boolean normalize(NormalizeTableFilterParams ntfp) throws IOException; boolean isNormalizerEnabled() throws IOException; boolean normalizerSwitch(boolean on) throws IOException; boolean catalogJanitorSwitch(boolean onOrOff) throws IOException; int runCatalogJanitor() throws IOException; boolean isCatalogJanitorEnabled() throws IOException; boolean cleanerChoreSwitch(boolean onOrOff) throws IOException; boolean runCleanerChore() throws IOException; boolean isCleanerChoreEnabled() throws IOException; @Deprecated default Future<Void> mergeRegionsAsync(byte[] nameOfRegionA, byte[] nameOfRegionB, boolean forcible) throws IOException { byte[][] nameofRegionsToMerge = new byte[2][]; nameofRegionsToMerge[0] = nameOfRegionA; nameofRegionsToMerge[1] = nameOfRegionB; return mergeRegionsAsync(nameofRegionsToMerge, forcible); }</code><technical_language>nit: add a default method calls normalize(NormalizeTableFilterParams) empty set of NTFparams? clean some stuff in *Admin implementations RequestConverter</technical_language>

Target:
void move(byte[] encodedRegionName, ServerName destServerName) throws IOException; void assign(byte[] regionName) throws IOException; void unassign(byte[] regionName, boolean force) throws IOException; void offline(byte[] regionName) throws IOException; boolean balancerSwitch(boolean onOrOff, boolean synchronous) throws IOException; boolean balance() throws IOException; boolean balance(boolean force) throws IOException; boolean isBalancerEnabled() throws IOException; CacheEvictionStats clearBlockCache(final TableName tableName) throws IOException; default boolean normalize() throws IOException { return normalize(new NormalizeTableFilterParams.Builder().build()); }
Source:
<code>public static void addIconToLabel(ViewGroup parent, Brick brick, Sprite sprite, Context context) { for (int i = 0; i < parent.getChildCount(); i++) { View child = parent.getChildAt(i); if (child instanceof LinearLayout || child instanceof RelativeLayout || child instanceof BrickLayout) { addIconToLabel((ViewGroup) child, brick, sprite, context); } if (child instanceof TextView) { TextView textView = (TextView) child; CategoryBricksFactory categoryBricksFactory = new CategoryBricksFactory(); String id = context.getResources().getResourceEntryName(textView.getId()); <START> String subString = id.subSequence(id.length() - LABEL_KEYWORD.length(), id.length()).toString(); <END> if (subString.equals(LABEL_KEYWORD)) { addIcon(context, textView, categoryBricksFactory.getBrickCategory(brick, sprite, context)); } } } }</code><technical_language>This is potentially subject IndexOutOfBoundsException if introduces a TextView a short id. Please add a check id size > LABEL_KEYWORD.length() ignore entries</technical_language>

Target:
public static boolean addIconToLabel(ViewGroup parent, Brick brick, Sprite sprite, Context context) { for (int i = 0; i < parent.getChildCount(); i++) { View child = parent.getChildAt(i); if (child instanceof ViewGroup) { boolean labelFound = addIconToLabel((ViewGroup) child, brick, sprite, context); if (labelFound) { return true; } } else if (child instanceof BrickTextView) { TextView textView = (TextView) child; CategoryBricksFactory categoryBricksFactory = new CategoryBricksFactory(); addIcon(context, textView, categoryBricksFactory.getBrickCategory(brick, sprite, context)); return true; } } return false; }
Source:
<code>public ImapFuture<ImapAsyncResponse> execute(@Nonnull final ImapRequest command) throws ImapAsyncClientException, IOException, SearchException { if (!requestsQueue.isEmpty()) { throw new ImapAsyncClientException(FailureType.COMMAND_NOT_ALLOWED); } final ImapFuture<ImapAsyncResponse> cmdFuture = new ImapFuture<ImapAsyncResponse>(); requestsQueue.add(new ImapCommandEntry(command, cmdFuture)); final String tag = getNextTag(); final StringBuilder sb = new StringBuilder(tag).append(ImapClientConstants.SPACE).append(command.getCommandLine()); if (isDebugEnabled()) { logger.debug(CLIENT_LOG_REC, sessionId, new StringBuilder(tag).append(ImapClientConstants.SPACE).append(command.getLogLine()).toString()); } <START> sendRequest(sb.toString()); <END> return cmdFuture; }</code><technical_language>logging sb.toString(), recreating sting logged? log actual data server, log in send request receive response</technical_language>

Target:
public ImapFuture<ImapAsyncResponse> execute(@Nonnull final ImapRequest command) throws ImapAsyncClientException, IOException, SearchException { if (!requestsQueue.isEmpty()) { throw new ImapAsyncClientException(FailureType.COMMAND_NOT_ALLOWED); } final ImapFuture<ImapAsyncResponse> cmdFuture = new ImapFuture<ImapAsyncResponse>(); requestsQueue.add(new ImapCommandEntry(command, cmdFuture)); final String tag = getNextTag(); final StringBuilder sb = new StringBuilder(tag).append(ImapClientConstants.SPACE).append(command.getCommandLine()); if (isDebugEnabled() && command.isCommandLineDataSensitive()) { logger.debug(CLIENT_LOG_REC, sessionId, command.getDebugData()); } sendRequest(sb.toString(), command.isCommandLineDataSensitive()); return cmdFuture; }
Source:
<code>public synchronized MemoryOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout) { long nextId = nextTableId.getAndIncrement(); Set<Node> nodes = nodeManager.getRequiredWorkerNodes(); checkState(!nodes.isEmpty(), "No Memory nodes available"); tableIds.put(tableMetadata.getTable().getTableName(), nextId); <START> MemoryTableHandle table = new MemoryTableHandle( <END> connectorId, nextId, tableMetadata); tables.put(table.getTableId(), table); hostsAndRowsPerTable.put(table.getTableId(), new HashMap<>()); return new MemoryOutputTableHandle(table, ImmutableSet.copyOf(tableIds.values())); }</code><technical_language>table name is unique? check state maybe</technical_language>

Target:
public synchronized MemoryOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout) { checkTableNotExists(tableMetadata.getTable()); long nextId = nextTableId.getAndIncrement(); Set<Node> nodes = nodeManager.getRequiredWorkerNodes(); checkState(!nodes.isEmpty(), "No Memory nodes available"); tableIds.put(tableMetadata.getTable(), nextId); MemoryTableHandle table = new MemoryTableHandle( connectorId, nextId, tableMetadata); tables.put(table.getTableId(), table); tableDataFragments.put(table.getTableId(), new HashMap<>()); return new MemoryOutputTableHandle(table, ImmutableSet.copyOf(tableIds.values())); }
Source:
<code>public String toString() { return "Response{" + "method='" + method + '\'' + ", uri=" + uri + ", status=" + status + <START> ", payload=" + Arrays.toString(payload) + <END> ", headers=" + headers + '}'; }</code><technical_language>If dealing character-based payloads (and aren't) logging decoded version of payload in a toString() more useful raw byte array</technical_language>

Target:
public String toString() { return "Response{" + "method='" + method + '\'' + ", uri=" + uri + ", status=" + status + ", payload='" + decode(payload) + '\'' + ", headers=" + headers + '}'; }
Source:
<code><START> @Override public Object call() { <END> return null; }</code><technical_language>nit: ~Square formatting</technical_language>

Target:
public Object call() { return null; }
Source:
<code>public NetworkException() { <START> super("Credentials not valid"); <END> }</code><technical_language>@xurxodev revise exception message? thanks</technical_language>

Target:
public NetworkException() { super("Network not available"); }
Source:
<code>public MongoDBQueryDescriptor(String collectionName, Operation operation, List<DBObject> pipeline) { this.collectionName = collectionName; this.operation = operation; this.criteria = null; this.projection = null; this.orderBy = null; this.options = null; this.updateOrInsert = null; this.unwinds = null; this.pipeline = pipeline == null ? Collections.<DBObject>emptyList() : pipeline; <START> this.fieldName = ""; <END> }</code><technical_language>other fields null initialized value, I stick :)</technical_language>

Target:
public MongoDBQueryDescriptor(String collectionName, Operation operation, List<DBObject> pipeline) { this.collectionName = collectionName; this.operation = operation; this.criteria = null; this.projection = null; this.orderBy = null; this.options = null; this.updateOrInsert = null; this.unwinds = null; this.pipeline = pipeline == null ? Collections.<DBObject>emptyList() : pipeline; this.distinctFieldName = null; this.collation = null; }
Source:
<code>public final T executeInManualFlushMode() { <START> Session currentSession = HibernateSessionFactory.getSessionFactory().getHibernateSessionFactory().getCurrentSession(); <END> FlushMode previousFlushMode = currentSession.getFlushMode(); currentSession.setFlushMode(FlushMode.MANUAL); try { return task(); } finally { currentSession.setFlushMode(previousFlushMode); } }</code><technical_language>Please change this line to: DbSession currentSession = HibernateSessionFactory.getSessionFactory().getCurrentSession();</technical_language>

Target:
public final T executeInManualFlushMode() { DbSession currentSession = HibernateSessionFactory.getSessionFactory().getCurrentSession(); FlushMode previousFlushMode = currentSession.getFlushMode(); currentSession.setFlushMode(FlushMode.MANUAL); try { return task(); } finally { currentSession.setFlushMode(previousFlushMode); } }
Source:
<code>private boolean isFileEntryPackageable(ZipEntry entry) { <START> String entryName = entry.getName(); <END> return ApkBuilder.checkFileForPackaging(entry.getName()) && isValidMetaInfEntry(entryName); }</code><technical_language>need this. refer entry.getName() in places</technical_language>

Target:
private boolean isFileEntryPackageable(ZipEntry entry) { return ApkBuilder.checkFileForPackaging(entry.getName()) && isValidMetaInfEntry(entry.getName()); }
Source:
<code>public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof HAProxyMessage)) { super.write(ctx, msg, promise); return; } <START> ctx.writeAndFlush(msg, promise).addListener(new ChannelFutureListener() { <END> @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ctx.pipeline().remove(HAProxyMessageEncoder.INSTANCE); ctx.pipeline().remove(HAProxyHandler.this); } else { throw new HAProxyProtocolException("failed to write HAProxy message"); } } }); }</code><technical_language>imho write(...)...</technical_language>

Target:
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ChannelFuture future = ctx.write(msg, promise); if (msg instanceof HAProxyMessage) { future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ctx.pipeline().remove(HAProxyMessageEncoder.INSTANCE); ctx.pipeline().remove(HAProxyHandler.this); } else { ctx.close(); } } }); } }
Source:
<code>public CompletableFuture<Integer> killJobs(Collection<UUID> toKill, @Nullable String reason) { for (KillAllListener killAllListener : killAllListeners) { for (UUID job : toKill) { try { killAllListener.killJob(job); } catch (Throwable t) { <START> LOGGER.error("Failed to call killJob on listener={}, err={}", t, killAllListener); <END> } } } return killTasks(toKill, reason); }</code><technical_language>here, wrong arguments order</technical_language>

Target:
public CompletableFuture<Integer> killJobs(Collection<UUID> toKill, @Nullable String reason) { for (KillAllListener killAllListener : killAllListeners) { for (UUID job : toKill) { try { killAllListener.killJob(job); } catch (Throwable t) { LOGGER.error("Failed to call killJob on listener={}, err={}", killAllListener, t); } } } return killTasks(toKill, reason); }
Source:
<code>public ActionForward prepare(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { final Student student = getUserView(request).getPerson().getStudent(); final List<Registration> toEnrol = new ArrayList<Registration>(); <START> toEnrol.addAll(student.getAllRegistrations()); <END> if (toEnrol.size() == 1) { request.setAttribute("registrationOID", toEnrol.iterator().next().getExternalId()); return prepareStartViewWarning(mapping, form, request, response); } else { request.setAttribute("toEnrol", toEnrol); return mapping.findForward("chooseRegistration"); } }</code><technical_language>Avoid calling getAllRegistrations() method. poor performance</technical_language>

Target:
public ActionForward prepare(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { final Student student = getUserView(request).getPerson().getStudent(); final List<Registration> toEnrol = student.getRegistrationStream().collect(Collectors.toList()); if (toEnrol.size() == 1) { request.setAttribute("registrationOID", toEnrol.iterator().next().getExternalId()); return prepareStartViewWarning(mapping, form, request, response); } else { request.setAttribute("toEnrol", toEnrol); return mapping.findForward("chooseRegistration"); } }
Source:
<code>public void close() { Throwable exception = null; try { dataFileChannel.close(); } catch (Throwable throwable) { exception = throwable; } try { <START> dataFileChannel.close(); <END> } catch (Throwable throwable) { exception = throwable; } if (exception != null) { ExceptionUtils.rethrow(exception); } }</code><technical_language>is a copy/paste error here, this indexFileChannel</technical_language>

Target:
public void close() throws IOException { if (isClosed) { return; } isClosed = true; IOException exception = null; try { dataFileChannel.close(); } catch (IOException ioException) { exception = ioException; } try { indexFileChannel.close(); } catch (IOException ioException) { exception = ExceptionUtils.firstOrSuppressed(ioException, exception); } if (exception != null) { throw exception; } }
Source:
<code>private static boolean isHashTokenEmpty() { <START> return StringUtils.isBlank(getHashTokenFromSession()) ? true : false; <END> }</code><technical_language>remove "?true:false". is unnecessary</technical_language>

Target:
private static boolean isHashTokenEmpty() { return StringUtils.isBlank(getHashTokenFromSession()); }
Source:
<code>public void createUserAttributes() throws Throwable { AtomicInteger c = new AtomicInteger(); UsersResource users = testRealm().users(); UserRepresentation u = UserBuilder.create().username("attributes").build(); Response response = users.create(u); String userId = ApiUtil.getCreatedId(response); UserResource user = users.get(userId); concurrentTest((threadIndex, keycloak, realm) -> { UserRepresentation rep = user.toRepresentation(); rep.singleAttribute("a-" + c.getAndIncrement(), "value"); user.update(rep); }); UserRepresentation rep = user.toRepresentation(); assertTrue(rep.getAttributes().size() <= c.get()); <START> <END> for (Map.Entry<String, List<String>> e : rep.getAttributes().entrySet()) { assertEquals(1, e.getValue().size()); } }</code><technical_language>assertThat(rep.getAttributes(), Matchers.hasSize(lessThanOrEqualTo(c.get()) error reporting</technical_language>

Target:
public void createUserAttributes() throws Throwable { AtomicInteger c = new AtomicInteger(); UsersResource users = testRealm().users(); UserRepresentation u = UserBuilder.create().username("attributes").build(); Response response = users.create(u); String userId = ApiUtil.getCreatedId(response); response.close(); UserResource user = users.get(userId); concurrentTest((threadIndex, keycloak, realm) -> { UserRepresentation rep = user.toRepresentation(); rep.singleAttribute("a-" + c.getAndIncrement(), "value"); user.update(rep); }); UserRepresentation rep = user.toRepresentation(); assertTrue(rep.getAttributes().size() <= c.get()); for (Map.Entry<String, List<String>> e : rep.getAttributes().entrySet()) { assertEquals(1, e.getValue().size()); } }
Source:
<code>public static BlockType asBlockType(Material material) { checkNotNull(material); <START> if (!material.isBlock()) { <END> throw new IllegalArgumentException(material.getKey().toString() + " is not a block!"); } return materialBlockTypeCache.computeIfAbsent(material, new Function<Material, BlockType>() { @Nullable @Override public BlockType apply(@Nullable Material input) { return BlockTypes.get(material.getKey().toString()); } }); }</code><technical_language>able skip this (and isItem below) EnumMap stores a null object for skip Material's switches</technical_language>

Target:
public static BlockType asBlockType(Material material) { checkNotNull(material); return materialBlockTypeCache.computeIfAbsent(material, input -> BlockTypes.get(material.getKey().toString())); }
Source:
<code><START> public static void cleanUpData() throws Exception { <END> ContentletAPI contentletAPI = APILocator.getContentletAPI(); User user = APILocator.systemUser(); if(keyValueContentlet != null){ APILocator.getWorkflowAPI().deleteWorkflowTaskByWebAsset(keyValueContentlet.getIdentifier(), APILocator.systemUser()); contentletAPI.archive(keyValueContentlet,user, false); contentletAPI.delete(keyValueContentlet,user, false); } if(keyValueContentlet1 != null) { APILocator.getWorkflowAPI().deleteWorkflowTaskByWebAsset(keyValueContentlet1.getIdentifier(), APILocator.systemUser()); contentletAPI.archive(keyValueContentlet1,user, false); contentletAPI.delete(keyValueContentlet1,user, false); } if(keyValueContentlet2 != null){ APILocator.getWorkflowAPI().deleteWorkflowTaskByWebAsset(keyValueContentlet2.getIdentifier(), APILocator.systemUser()); contentletAPI.archive(keyValueContentlet2,user, false); contentletAPI.delete(keyValueContentlet2,user, false); } APILocator.getLanguageAPI().deleteLanguage(spanishNoCountryLanguage); APILocator.getLanguageAPI().deleteLanguage(spanishCostaRicaLanguage); }</code><technical_language>need clean data in tests - assume data thrown out</technical_language>

Target:
public static void cleanUpData() throws Exception { ContentletAPI contentletAPI = APILocator.getContentletAPI(); User user = APILocator.systemUser(); if(keyValueContentlet != null){ APILocator.getWorkflowAPI().deleteWorkflowTaskByContentletIdAnyLanguage(keyValueContentlet.getIdentifier(), APILocator.systemUser()); contentletAPI.archive(keyValueContentlet,user, false); contentletAPI.delete(keyValueContentlet,user, false); } if(keyValueContentlet1 != null) { APILocator.getWorkflowAPI().deleteWorkflowTaskByContentletIdAnyLanguage(keyValueContentlet1.getIdentifier(), APILocator.systemUser()); contentletAPI.archive(keyValueContentlet1,user, false); contentletAPI.delete(keyValueContentlet1,user, false); } if(keyValueContentlet2 != null){ APILocator.getWorkflowAPI().deleteWorkflowTaskByContentletIdAnyLanguage(keyValueContentlet2.getIdentifier(), APILocator.systemUser()); contentletAPI.archive(keyValueContentlet2,user, false); contentletAPI.delete(keyValueContentlet2,user, false); } APILocator.getLanguageAPI().deleteLanguage(spanishNoCountryLanguage); APILocator.getLanguageAPI().deleteLanguage(spanishCostaRicaLanguage); }
Source:
<code>protected Ref findBranch(String branchName) throws IOException { return <START> repository.findRef(R_HEADS <END> + branchName); }</code><technical_language>this exactRef</technical_language>

Target:
protected Ref findBranch(String branchName) throws IOException { return repository.exactRef(R_HEADS + branchName); }