auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void preparePreviousAttemptWorkers() { <START> testingYarnAMRMClientAsyncBuilder.setRegisterApplicationMasterFunction((ignored1, ignored2, ignored3) -> RegisterApplicationMasterResponse.newInstance( <END> Resource.newInstance(0, 0), Resource.newInstance(Integer.MAX_VALUE, Integer.MAX_VALUE), Collections.emptyMap(), null, Collections.singletonList(testingContainer), null, Collections.emptyList())); }</code><technical_language>RegisterApplicationMasterResponse.newInstance is annotated private unstable. This compiling issues hadoop versions. I suggest create a testing class extending RegisterApplicationMasterResponsePBImpl. Similar do testing yarn clients</technical_language>

Target:
protected void preparePreviousAttemptWorkers() { testingYarnAMRMClientAsyncBuilder.setRegisterApplicationMasterFunction( (ignored1, ignored2, ignored3) -> new TestingRegisterApplicationMasterResponse(() -> Collections.singletonList(testingContainer))); }
Source:
<code>public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled()) { AbstractBuildContext config = AbstractBuildContext.createContextFromMap(taskDefinition.getConfiguration()); <START> if ((config != null) && config.releaseManagementContext.isReleaseMgmtEnabled()) { <END> return taskDefinition; } } } } return null; }</code><technical_language>Redundant parentheses (config != null). Also, this method is identical getTaskConfiguration method. I suggest reusing code</technical_language>

Target:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled() && isReleaseMgmtEnabled(taskDefinition)) { return taskDefinition; } } } return null; }
Source:
<code>private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { if (entry.enabled) { try { Extension extension = (Extension) lookupService( Extension.class, entry.getConfig().getProperty(CLASS), <START> loadModule(entry.getConfig().getProperty(MODULE)) <END> ).newInstance(); extension.setContext(entry.context); extension.init(); entry.setExtension(extension); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException ex ) { log.error(String.format("Error in activating extension %1$s. Exception message is " + entry.getName()), ex.getMessage()); if (log.isDebugEnabled()) { log.error("", ex); } } } } }</code><technical_language>loadModule done lookupService, interface plain strings</technical_language>

Target:
private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { if (entry.enabled) { try { Extension extension = (Extension) lookupService( Extension.class, entry.getConfig().getProperty(CLASS), entry.getConfig().getProperty(MODULE) ).newInstance(); extension.setContext(entry.context); extension.init(); entry.setExtension(extension); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException ex ) { log.error(String.format("Error in activating extension %1$s. Exception message is " + entry.getName()), ex.getMessage()); if (log.isDebugEnabled()) { log.error("", ex); } } } } }
Source:
<code>public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_SUBSCRIPTION_KEY")) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT")) .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.", "en"), new TextDocumentInput("2", "Mount Shasta has lenticular clouds.", "en") ); final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); final DocumentResultCollection<LinkedEntityResult> detectedBatchResult = client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); System.out.printf("Model version: %s", detectedBatchResult.getModelVersion()); final TextBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); detectedBatchResult.forEach(linkedEntityDocumentResult -> linkedEntityDocumentResult.getLinkedEntities().stream().forEach(linkedEntity -> <START> System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s", <END> linkedEntity.getName(), linkedEntity.getUri(), linkedEntity.getDataSource()))); }</code><technical_language>%n used</technical_language>

Target:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey("subscription-key") .endpoint("<LINK_0>") .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.", "en"), new TextDocumentInput("2", "Mount Shasta has lenticular clouds.", "en") ); final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); final DocumentResultCollection<RecognizeLinkedEntitiesResult> detectedBatchResult = client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (RecognizeLinkedEntitiesResult linkedEntityDocumentResult : detectedBatchResult) { for (LinkedEntity linkedEntity : linkedEntityDocumentResult.getLinkedEntities()) { System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s%n", linkedEntity.getName(), linkedEntity.getUrl(), linkedEntity.getDataSource()); } } }
Source:
<code>public ConfigurationClientBuilder connectionString(String connectionString) { <START> if (CoreUtils.isNullOrEmpty(connectionString)) { <END> throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be null or an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; }</code><technical_language>design spec, null throw NullPointerException isEmpty throw IllegalArgumentException. split this steps. <LINK_0></technical_language>

Target:
public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; }
Source:
<code>public void setUp() throws ComponentLookupException, IOException, SolrServerException, CacheException { MockitoAnnotations.initMocks(this); this.indexReturn = -1; SolrVocabularyResourceManager externalServicesAccess = this.mocker.getInstance(SolrVocabularyResourceManager.class); when(externalServicesAccess.getSolrConnection()).thenReturn(this.server); CacheManager cacheFactory = this.mocker.getInstance(CacheManager.class); <START> when(cacheFactory.createNewLocalCache(any(CacheConfiguration.class))).thenReturn((Cache) this.cache); <END> this.service = (HPOScriptService) this.mocker.getComponentUnderTest(); }</code><technical_language>Remove @SuppressWarnings("unchecked") in this file, this style of mocking objects whate prevent warning showing up: java // do when(cacheFactory.createNewLocalCache(any(CacheConfiguration.class))).thenReturn((Cache) this.cache); // do Mockito.doReturn(this.cache).when(cacheFactory).createNewLocalCache(any(CacheConfiguration.class));</technical_language>

Target:
public void setUp() throws ComponentLookupException, IOException, SolrServerException, CacheException { MockitoAnnotations.initMocks(this); this.indexReturn = -1; SolrVocabularyResourceManager externalServicesAccess = this.mocker.getInstance(SolrVocabularyResourceManager.class); Mockito.doReturn(this.server).when(externalServicesAccess).getSolrConnection(); CacheManager cacheFactory = this.mocker.getInstance(CacheManager.class); Mockito.doReturn(this.cache).when(cacheFactory).createNewLocalCache(any(CacheConfiguration.class)); this.service = (HPOScriptService) this.mocker.getComponentUnderTest(); }
Source:
<code>private JButton getBtnReopen() { if (btnReopen == null) { btnReopen = new JButton(); btnReopen.setIcon(REOPEN_ICON); btnReopen.setEnabled(true); btnReopen.setToolTipText(Constant.messages.getString("websocket.manual_send.btn_reopen_hint")); btnReopen.addActionListener(e -> { isOnConnectingProgress(true); String newSecWebSocketKey = null; if(!wsUiHelper.isAlwaysGenerate()){ newSecWebSocketKey = wsUiHelper.getWebSocketKey(); } ReEstablishConnection reEstablishConnection = new ReEstablishConnection(newSecWebSocketKey); reEstablishConnection.addPropertyChangeListener(propertyChangeEvent -> { if((propertyChangeEvent.getNewValue() == SwingWorker.StateValue.DONE)){ isOnConnectingProgress(false); int channelId1; try { channelId1 = reEstablishConnection.get(); if(channelId1 < 0){ if(channelId1 == ReEstablishConnection.REQUEST_OUT_OF_SCOPE){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.out_of_scope")); }else if(channelId1 == ReEstablishConnection.IOEXCEPTION){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.unable_reopen")); } }else{ wsUiHelper.setSelectedChannelId(channelId1); wsUiHelper.requestFocusChannelComboBox(); } } catch (Exception e1) { <START> LOGGER.warn(e1.getStackTrace(), e1); <END> } } }); reEstablishConnection.execute(); }); } return btnReopen; }</code><technical_language>This method logs stacktrace, parameter message. - level error, this is issue in code</technical_language>

Target:
private JButton getBtnReopen() { if (btnReopen == null) { btnReopen = new JButton(); btnReopen.setIcon(REOPEN_ICON); btnReopen.setEnabled(true); btnReopen.setToolTipText(Constant.messages.getString("websocket.manual_send.btn_reopen_hint")); btnReopen.addActionListener((ActionEvent e) -> { isOnConnectingProgress(true); String newSecWebSocketKey = null; if(!wsUiHelper.isAlwaysGenerate()){ newSecWebSocketKey = wsUiHelper.getWebSocketKey(); } ReEstablishConnection reEstablishConnection = new ReEstablishConnection(newSecWebSocketKey); reEstablishConnection.addPropertyChangeListener(propertyChangeEvent -> { if((propertyChangeEvent.getNewValue() == SwingWorker.StateValue.DONE)){ isOnConnectingProgress(false); int channelId; try { channelId = reEstablishConnection.get(); if(channelId < 0){ if(channelId == ReEstablishConnection.RETRIVING_HANDSHAKE_ERROR){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.retrieve")); }else if(channelId == ReEstablishConnection.REQUEST_OUT_OF_SCOPE){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.out_of_scope")); }else if(channelId == ReEstablishConnection.IOEXCEPTION){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.unable_reopen")); } }else{ wsUiHelper.setSelectedChannelId(channelId); wsUiHelper.requestFocusChannelComboBox(); } } catch (Exception ex){ LOGGER.error("An error occurred when trying to re-establish a websocket connection",ex); } } }); reEstablishConnection.execute(); }); } return btnReopen; }
Source:
<code>public void merge_NullSafe() { <START> assertThat(new ReportFeatureAppendableMerger().merge(null)).isNotNull().isEmpty(); <END> }</code><technical_language>given, please this is clear testing</technical_language>

Target:
public void merge_NullSafe() { ReportFeatureAppendableMerger merger = new ReportFeatureAppendableMerger(); List<Feature> result = merger.merge(null); assertThat(result).isNotNull().isEmpty(); }
Source:
<code>protected void openDiagram(String name) { <START> editor = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), VIEWPOINT_NAME + " " + name, name, DDiagram.class); editor.setSnapToGrid(false); editor.zoom(ZoomLevel.ZOOM_100); <END> }</code><technical_language>replace openDiagram(name, ZoomLevel.ZOOM_100);</technical_language>

Target:
protected void openDiagram(String name) { openDiagram(name, ZoomLevel.ZOOM_100); }
Source:
<code>public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; <START> partitionedFileName = String.format(partitionedFileNameformat, outputFileName, physicalPartitionId); <END> }</code><technical_language>partitionedFileName is assigned in setup() is need do here; in fact, setters typically called operator is serialized, physicalPartitionId 0 here</technical_language>

Target:
public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; }
Source:
<code>public HealthThermometerServiceFragment() { mTemperatureMeasurementCharacteristic = new BluetoothGattCharacteristic(TEMPERATURE_MEASUREMENT_UUID, BluetoothGattCharacteristic.PROPERTY_INDICATE, 0); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getClientCharacteristicConfigurationDescriptor()); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(TEMPERATURE_MEASUREMENT_DESCRIPTION)); mMeasurementIntervalCharacteristic = new BluetoothGattCharacteristic(MEASUREMENT_INTERVAL_UUID, <START> (BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE), <END> (BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE)); mMeasurementIntervalCharacteristic.addDescriptor( Peripheral.getClientCharacteristicConfigurationDescriptor()); mMeasurementIntervalCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(MEASUREMENT_INTERVAL_DESCRIPTION)); mHealthThermometerService = new BluetoothGattService(HEALTH_THERMOMETER_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); mHealthThermometerService.addCharacteristic(mTemperatureMeasurementCharacteristic); mHealthThermometerService.addCharacteristic(mMeasurementIntervalCharacteristic); }</code><technical_language>I missing property here; adding CCC descriptor below</technical_language>

Target:
public HealthThermometerServiceFragment() { mTemperatureMeasurementCharacteristic = new BluetoothGattCharacteristic(TEMPERATURE_MEASUREMENT_UUID, BluetoothGattCharacteristic.PROPERTY_INDICATE, 0); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getClientCharacteristicConfigurationDescriptor()); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(TEMPERATURE_MEASUREMENT_DESCRIPTION)); mMeasurementIntervalCharacteristic = new BluetoothGattCharacteristic( MEASUREMENT_INTERVAL_UUID, (BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_INDICATE), (BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE)); mMeasurementIntervalCCCDescriptor = Peripheral.getClientCharacteristicConfigurationDescriptor(); mMeasurementIntervalCharacteristic.addDescriptor(mMeasurementIntervalCCCDescriptor); mMeasurementIntervalCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(MEASUREMENT_INTERVAL_DESCRIPTION)); mHealthThermometerService = new BluetoothGattService(HEALTH_THERMOMETER_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); mHealthThermometerService.addCharacteristic(mTemperatureMeasurementCharacteristic); mHealthThermometerService.addCharacteristic(mMeasurementIntervalCharacteristic); }
Source:
<code>protected void validate(long timeWindow) throws Exception { if (this.mergedFreeBusyInterval > timeWindow) { throw new IllegalArgumentException(String.format("%s,%s", <START> "MergedFreeBusyInterval must be smaller than the specified time window.", <END> "MergedFreeBusyInterval")); } EwsUtilities.validateParamAllowNull(this.detailedSuggestionsWindow, "DetailedSuggestionsWindow"); }</code><technical_language>is wrong indentation</technical_language>

Target:
protected void validate(long timeWindow) throws Exception { if (this.mergedFreeBusyInterval > timeWindow) { throw new IllegalArgumentException( "MergedFreeBusyInterval must be smaller than the specified time window."); } EwsUtilities.validateParamAllowNull(this.detailedSuggestionsWindow, "DetailedSuggestionsWindow"); }
Source:
<code>public void close() throws IOException { this.executor.shutdown(); final long begin = System.currentTimeMillis(); int attempt = 0; try { while (true) { <START> if (this.executor.awaitTermination(2, TimeUnit.SECONDS) <END> || attempt >= MethodScheduler.SHUTDOWN_ATTEMPTS) { break; } final long age = System.currentTimeMillis() - begin; if (age > this.limit) { this.executor.shutdownNow(); attempt += 1; } Logger.info( this, "waiting %[ms]s for threads termination", age ); TimeUnit.SECONDS.sleep(1); } if (!this.executor.isTerminated()) { throw new IllegalStateException( Logger.format( "failed to shutdown %[type]s of %[type]s", this.executor, this.object ) ); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } Logger.info( this.object, "execution stopped after %[ms]s and %d tick(s)", System.currentTimeMillis() - this.start, this.counter.get() ); }</code><technical_language>if limit set 100 milliseconds? waiting for seconds,</technical_language>

Target:
public void close() throws IOException { this.executor.shutdown(); final long begin = System.currentTimeMillis(); try { while (true) { if (this.executor.awaitTermination(1, TimeUnit.SECONDS)) { break; } final long age = System.currentTimeMillis() - begin; if (age > this.await) { break; } Logger.info( this, "waiting %[ms]s for threads termination", age ); } for (int attempt = 0; attempt < this.attempts; ++attempt) { this.executor.shutdownNow(); this.executor.awaitTermination(1, TimeUnit.SECONDS); } if (!this.executor.isTerminated()) { throw new IllegalStateException( Logger.format( "failed to shutdown %[type]s of %[type]s", this.executor, this.object ) ); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } Logger.info( this.object, "execution stopped after %[ms]s and %d tick(s)", System.currentTimeMillis() - this.start, this.counter.get() ); }
Source:
<code>public Response toResponse(QosException exception) { log.debug("Possible quality-of-service intervention", exception); if (exception instanceof QosException.Retry) { QosException.Retry retry = (QosException.Retry) exception; if (!retry.getBackoff().isPresent() && !retry.getRedirectTo().isPresent()) { return retryAnyNow(); <START> } else { <END> if (retry.getBackoff().isPresent()) { return retryAnyLater(retry.getBackoff().get()); } else if (retry.getRedirectTo().isPresent()) { return retryThisHostNow(retry.getRedirectTo().get()); } else { throw new RuntimeException("Unexpected internal state: expected either backoff or redirectTo"); } } } else if (exception instanceof QosException.Unavailable) { return unavailable(); } else { throw new RuntimeException( "Internal error, unknown QosException subclass: " + exception.getClass().getSimpleName()); } }</code><technical_language>support signalling redirect this location this time</technical_language>

Target:
public Response toResponse(QosException exception) { log.debug("Possible quality-of-service intervention", exception); if (exception instanceof QosException.Retry) { return retry(); } else if (exception instanceof QosException.RetryOther) { QosException.RetryOther retry = (QosException.RetryOther) exception; return retryOther(retry.getRedirectTo()); } else if (exception instanceof QosException.Unavailable) { return unavailable(); } else { throw new RuntimeException( "Internal error, unknown QosException subclass: " + exception.getClass().getSimpleName()); } }
Source:
<code>public static void downloadCustomDockerImage() throws IOException { <START> Utilities.executeCommand("docker pull ubuntu:latest", System.out, System.err); <END> Utilities.executeCommand("docker tag ubuntu:latest " + FAKE_IMAGE_NAME, System.out, System.err); docker_images = Files.createTempDirectory("docker_images").toAbsolutePath().toString(); Utilities.executeCommand("docker save -o " + docker_images + "/fakeImage " + FAKE_IMAGE_NAME, System.out, System.err); }</code><technical_language>Create a Dockerfile container add a symbolic link</technical_language>

Target:
public static void downloadCustomDockerImage() throws IOException { Utilities.executeCommand("docker build -f " + DOCKERFILE + " . -t " + FAKE_IMAGE_NAME, System.out, System.err); DOCKER_IMAGE_DIRECTORY = Files.createTempDirectory("docker_images").toAbsolutePath().toString(); Utilities.executeCommand("docker save -o " + DOCKER_IMAGE_DIRECTORY + "/fakeImage " + FAKE_IMAGE_NAME, System.out, System.err); }
Source:
<code>public void expansionPath() { CartFixtures.withCart(client(), cart -> { withCustomObjectAndCustomClasses(client(), cart, existingCustomObject -> { final String id = existingCustomObject.getId(); final CustomObjectByIdGet<MyCustomClass> fetch = CustomObjectByIdGet.of(id, MyCustomClass.class); CustomObject<MyCustomClass> customObject = client().executeBlocking(fetch); <START> assertThat(customObject).isEqualTo(existingCustomObject); <END> final ExpansionPath<CustomObject<MyCustomClass>> expansionPath = ExpansionPath.of("value.cartReference"); CustomObjectByIdGet<MyCustomClass> expandedFetch = fetch.withExpansionPaths(expansionPath); customObject = client().executeBlocking(expandedFetch); assertThat(customObject).isNotNull(); assertThat(customObject.getValue().getCartReference().getObj()).isNotNull(); }); return cart; }); }</code><technical_language>add a check custom object is expanded</technical_language>

Target:
public void expansionPath() { CartFixtures.withCart(client(), cart -> { withCustomObjectAndCustomClasses(client(), cart, existingCustomObject -> { final String id = existingCustomObject.getId(); final CustomObjectByIdGet<MyCustomClass> fetch = CustomObjectByIdGet.of(id, MyCustomClass.class); CustomObject<MyCustomClass> customObject = client().executeBlocking(fetch); assertThat(customObject).isEqualTo(existingCustomObject); assertThat(customObject.getValue().getCartReference().getObj()).isNull(); final ExpansionPath<CustomObject<MyCustomClass>> expansionPath = ExpansionPath.of("value.cartReference"); CustomObjectByIdGet<MyCustomClass> expandedFetch = fetch.withExpansionPaths(expansionPath); customObject = client().executeBlocking(expandedFetch); assertThat(customObject).isNotNull(); assertThat(customObject.getValue().getCartReference().getObj()).isNotNull(); }); return cart; }); }
Source:
<code>public void aggregation() { aggregatedApplicationContext = new AggregateApplicationBuilder( <START> FooConfig.class, "--server.port=0", "--debug=true", <END> "--spring.cloud.stream.default-binder=mock") .web(false).from(TestSource.class).to(TestProcessor.class).run(); SharedBindingTargetRegistry sharedBindingTargetRegistry = aggregatedApplicationContext .getBean(SharedBindingTargetRegistry.class); BindingTargetFactory channelFactory = aggregatedApplicationContext .getBean(SubscribableChannelBindingTargetFactory.class); assertThat(channelFactory).isNotNull(); assertThat(sharedBindingTargetRegistry.getAll().keySet()).hasSize(2); aggregatedApplicationContext.close(); }</code><technical_language>a .web(false). is point of out of --server.port=0? I need --debug=true. determine reason of failure in this test</technical_language>

Target:
public void aggregation() { aggregatedApplicationContext = new AggregateApplicationBuilder( AggregationAppConfig.class, "--spring.cloud.stream.default-binder=mock") .web(false).from(TestSource.class).to(TestProcessor.class).run(); SharedBindingTargetRegistry sharedBindingTargetRegistry = aggregatedApplicationContext .getBean(SharedBindingTargetRegistry.class); BindingTargetFactory channelFactory = aggregatedApplicationContext .getBean(SubscribableChannelBindingTargetFactory.class); assertThat(channelFactory).isNotNull(); assertThat(sharedBindingTargetRegistry.getAll().keySet()).hasSize(2); aggregatedApplicationContext.close(); }
Source:
<code>public void close() throws IOException { if (lineIterator != null) { lineIterator.close(); } if (closer != null) { <START> closer.close(); <END> } }</code><technical_language>close this if lineIterator fails close</technical_language>

Target:
public void close() throws IOException { try { if (lineIterator != null) { lineIterator.close(); } } catch (Throwable t) { try { if (closer != null) { closer.close(); } } catch (Exception e) { t.addSuppressed(e); } throw t; } if (closer != null) { closer.close(); } }
Source:
<code>public RestRequestHandler getRequestHandler() throws RestServiceException { RestRequestHandler requestHandler; int index = currIndex.getAndIncrement(); try { requestHandler = requestHandlers.get(index % requestHandlers.size()); } catch (Exception e) { logger.error("Exception during selection of a RestRequestHandler to return", e); restServerMetrics.requestHandlerControllerHandlerSelectionError.inc(); throw new RestServiceException("Exception during selection of a RestRequestHandler to return", e, RestServiceErrorCode.RequestHandlerSelectionError); } if (requestHandler.isRunning()) { logger.debug("Monotonically increasing value was used to pick request handler at index {}", index, index % requestHandlers.size()); } else { logger.debug("Request handler at index is dead. Substitute request handler selection will be attempted", index % requestHandlers.size()); <START> requestHandler = pickSubstituteRequestHandler(); <END> } return requestHandler; }</code><technical_language>avoid thread crashing...and remove this code</technical_language>

Target:
public RestRequestHandler getRequestHandler() throws RestServiceException { RestRequestHandler requestHandler; int index = currIndex.getAndIncrement(); try { requestHandler = requestHandlers.get(index % requestHandlers.size()); logger.trace("Monotonically increasing value was used to pick request handler at index {}", index, index % requestHandlers.size()); } catch (Exception e) { restServerMetrics.requestHandlerSelectionError.inc(); throw new RestServiceException("Exception during selection of a RestRequestHandler to return", e, RestServiceErrorCode.RequestHandlerSelectionError); } return requestHandler; }
Source:
<code>public static byte[] macToBytes(String mac) throws KuraException { if (mac == null) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } String[] items = mac.split("\\:"); if (items.length != 6) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } byte[] bytes = new byte[6]; for (int i = 0; i < 6; i++) { String item = items[i]; if (item.isEmpty() || (item.length() > 2)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); <START> } <END> try { bytes[i] = (byte) Integer.parseInt(items[i], 16); } catch (NumberFormatException e) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } } return bytes; }</code><technical_language>Runtime Exception</technical_language>

Target:
public static byte[] macToBytes(String mac) { if (mac == null) { throw new IllegalArgumentException("mac is null"); } String[] items = mac.split("\\:"); if (items.length != 6) { throw new IllegalArgumentException("mac is invalid: " + mac); } byte[] bytes = new byte[6]; for (int i = 0; i < 6; i++) { String item = items[i]; if (item.isEmpty() || (item.length() > 2)) { throw new IllegalArgumentException("mac is invalid: " + mac); } try { bytes[i] = (byte) Integer.parseInt(items[i], 16); } catch (NumberFormatException e) { throw new IllegalArgumentException("mac is invalid: " + mac, e); } } return bytes; }
Source:
<code>public void testZkAdminTimeout() { boolean exceptionThrown = false; <START> ZKHelixAdmin admin = null; <END> try { admin = new ZKHelixAdmin("localhost:27999"); } catch (Exception e) { exceptionThrown = true; } finally { if (admin != null) { admin.close(); } } Assert.assertTrue(exceptionThrown); System.setProperty(ZKHelixAdmin.CONNECTION_TIMEOUT, "3"); exceptionThrown = false; long time = System.currentTimeMillis(); try { admin = new ZKHelixAdmin("localhost:27999"); } catch (Exception e) { exceptionThrown = true; } finally { if (admin != null) { admin.close(); } } Assert.assertTrue(exceptionThrown); Assert.assertTrue(System.currentTimeMillis() - time < 5000); }</code><technical_language>nit, want extract a private method for this section reduce duplication</technical_language>

Target:
public void testZkAdminTimeout() { boolean exceptionThrown = testZkAdminTimeoutHelper(); Assert.assertTrue(exceptionThrown); System.setProperty(ZKHelixAdmin.CONNECTION_TIMEOUT, "3"); exceptionThrown = testZkAdminTimeoutHelper(); long time = System.currentTimeMillis(); Assert.assertTrue(exceptionThrown); Assert.assertTrue(System.currentTimeMillis() - time < 5000); }
Source:
<code><START> protected BinaryMetadataProcessor(String baseBinaryPath) { <END> this.baseBinaryPath = baseBinaryPath; if (!baseBinaryPath.endsWith("/")) { this.baseBinaryPath += "/"; } }</code><technical_language>this constructor protected access? other processors public constructors</technical_language>

Target:
public BinaryMetadataProcessor(String baseBinaryPath) { this.baseBinaryPath = baseBinaryPath; if (!baseBinaryPath.endsWith("/")) { this.baseBinaryPath += "/"; } }
Source:
<code>private String generator() { <START> String[] sentences = new String[] {"the cow jumped over the moon", "an apple a day keeps the doctor away", <END> "four score and seven years ago", "snow white and the seven dwarfs", "i am at two with nature" }; String sentence = sentences[rand.nextInt(sentences.length)]; return sentence; }</code><technical_language>final</technical_language>

Target:
private String generator() { final String[] sentences = new String[] {"the cow jumped over the moon", "an apple a day keeps the doctor away", "four score and seven years ago", "snow white and the seven dwarfs", "i am at two with nature" }; final String sentence = sentences[rand.nextInt(sentences.length)]; return sentence; }
Source:
<code>private String executeDiscoveryScript(File discoveryScript, long gpuAmount, String args) throws Exception { final String cmd = discoveryScript.getAbsolutePath() + " " + gpuAmount + " " + args; final Process process = Runtime.getRuntime().exec(cmd); final BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); <START> final int exitVal = process.waitFor(); <END> if (exitVal != 0) { final String stdout = stdoutReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); final String stderr = stderrReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); LOG.error("Discovery script exit with {}. With output {}", exitVal, stdout, stderr); throw new FlinkException("Discovery script exit with non-zero."); } return stdoutReader.readLine(); }</code><technical_language>This blocks thread. I noticed this method is indirectly called ExternalResourceUtils#getExternalResourceInfoInternal, in a loop. Ideally, this executed concurrently drivers, asynchronously if needed. drivers ATM, GPU discovery script time manually tested, fine making this a follow-up issue. For this PR, I a timeout for waitFor, in case script is stuck takes long</technical_language>

Target:
private String executeDiscoveryScript(File discoveryScript, long gpuAmount, String args) throws Exception { final String cmd = discoveryScript.getAbsolutePath() + " " + gpuAmount + " " + args; final Process process = Runtime.getRuntime().exec(cmd); try (final BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { final boolean hasProcessTerminated = process.waitFor(DISCOVERY_SCRIPT_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (!hasProcessTerminated) { throw new TimeoutException(String.format("The discovery script executed for over %d ms.", DISCOVERY_SCRIPT_TIMEOUT_MS)); } final int exitVal = process.exitValue(); if (exitVal != 0) { final String stdout = stdoutReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); final String stderr = stderrReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); LOG.warn("Discovery script exit with {}.\\nSTDOUT: {}\\nSTDERR: {}", exitVal, stdout, stderr); throw new FlinkException(String.format("Discovery script exit with non-zero return code: %s.", exitVal)); } Object[] stdout = stdoutReader.lines().toArray(); if (stdout.length > 1) { LOG.warn( "The output of the discovery script should only contain one single line. Finding lines with content: {}. Will only keep the first line.", stdout.length, Arrays.toString(stdout)); } if (stdout.length == 0) { return ""; } return (String) stdout[0]; } finally { process.destroyForcibly(); } }
Source:
<code>public String getDisplayName() { <START> return "Transform and archive various test result formats"; <END> }</code><technical_language>externalize message properties description of xunit pulisher</technical_language>

Target:
public String getDisplayName() { return Messages.xUnit_PublisherName(); }
Source:
<code>private static <T> Stream<T> unwrap(CompletableFuture<Stream<T>> fut) { try { <START> return fut.get(); <END> } catch (InterruptedException | ExecutionException e) { return Stream.empty(); } }</code><technical_language>get() freezes chain of computation, is worse a synchronized list</technical_language>

Target:
private static <T> Stream<T> unwrap(CompletableFuture<Stream<T>> fut) { Stream<T> empty = Stream.empty(); try { return fut.getNow(empty); } catch (CompletionException | CancellationException e) { return empty; } }
Source:
<code>public synchronized CompletableFuture<Void> addListener(String topic, LeadershipEventListener<byte[]> listener) { boolean empty = leadershipChangeListeners.isEmpty(); leadershipChangeListeners.compute(topic, (t, s) -> { if (s == null) { s = Sets.newCopyOnWriteArraySet(Collections.singleton(listener)); } else { s.add(listener); } return s; }); <START> if (empty) { <END> return proxy.invoke(ADD_LISTENER); } return CompletableFuture.completedFuture(null); }</code><technical_language>order of listeners invocation of proxy changed, matter</technical_language>

Target:
public synchronized CompletableFuture<Void> addListener(String topic, LeadershipEventListener<byte[]> listener) { boolean empty = leadershipChangeListeners.isEmpty(); leadershipChangeListeners.compute(topic, (t, s) -> { if (s == null) { s = Sets.newCopyOnWriteArraySet(); } s.add(listener); return s; }); if (empty) { return proxy.invoke(ADD_LISTENER); } return CompletableFuture.completedFuture(null); }
Source:
<code>private PhpCfgBlock createLabelBlock(LabelTree tree, PhpCfgBlock currentBlock) { String label = tree.label().text(); labelledBlocks.put(label, currentBlock); currentBlock.addElement(tree); PhpCfgBlock gotoWithoutTarget = gotosWithoutTarget.get(label); if (gotoWithoutTarget != null) { <START> gotoWithoutTarget.replaceSuccessor(end, currentBlock); <END> } return createSimpleBlock(currentBlock); }</code><technical_language>remove this goto map, right</technical_language>

Target:
private PhpCfgBlock createLabelBlock(LabelTree tree, PhpCfgBlock currentBlock) { String label = tree.label().text(); labelledBlocks.put(label, currentBlock); currentBlock.addElement(tree); List<PhpCfgBlock> gotoBlocks = gotosWithoutTarget.get(label); if (gotoBlocks != null) { gotoBlocks.forEach(gotoBlock -> gotoBlock.replaceSuccessor(end, currentBlock)); gotosWithoutTarget.remove(label); } return createSimpleBlock(currentBlock); }
Source:
<code>private String _encode(String strVal) { try { return URLEncoder.encode(strVal, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { <START> return e.getMessage(); <END> } }</code><technical_language>message returned original value</technical_language>

Target:
private String _encode(String strVal) { try { return URLEncoder.encode(strVal, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
<code>public static Set<URL> collectUrlFromRelease(final ImportConfiguration configuration) { final ReleaseFileSet releaseFileSet = configuration.getReleaseFileSet(); if (releaseFileSet == null) { return Collections.<URL>emptySet(); } final List<String> refSetsRelativePaths = releaseFileSet.getRefSetPaths(); final String relativeRoot = releaseFileSet.getRelativeRoot(); final Set<URL> collectedUrlSet = Sets.newHashSet(); for(final String refSetPath : refSetsRelativePaths) { Set<URL> parsedRefSetUrl = Sets.newHashSet(); if (configuration.getSourceKind().equals(ImportSourceKind.ARCHIVE)) { parsedRefSetUrl = parseZip(configuration.getArchiveFile(), relativeRoot, refSetPath); } else if (configuration.getSourceKind().equals(ImportSourceKind.ROOT_DIRECTORY)) { parsedRefSetUrl = parseDirectory(configuration.getRootFile(), relativeRoot, refSetPath); } collectedUrlSet.addAll(parsedRefSetUrl); } try { for (File langFiles : configuration.getLanguageRefSetFiles()) { collectedUrlSet.add(configuration.toURL(langFiles)); } <START> <END> if (null != configuration.getDescriptionType()) { collectedUrlSet.add(configuration.toURL(configuration.getDescriptionType())); } } catch (final IOException e) { e.printStackTrace(); } return collectedUrlSet; }</code><technical_language>Extra line</technical_language>

Target:
public static Set<URL> collectUrlFromRelease(final ImportConfiguration configuration) { final ReleaseFileSet releaseFileSet = configuration.getReleaseFileSet(); if (releaseFileSet == null) { return Collections.<URL>emptySet(); } final Set<URL> collectedUrlSet = Sets.newHashSet(); if (configuration.getSourceKind().equals(ImportSourceKind.ARCHIVE)) { final List<String> refSetsRelativePaths = releaseFileSet.getRefSetPaths(); final String relativeRoot = releaseFileSet.getRelativeRoot(); for (final String refSetPath : refSetsRelativePaths) { collectedUrlSet.addAll(parseZip(configuration.getArchiveFile(), relativeRoot, refSetPath)); } } return collectedUrlSet; }
Source:
<code>public SeRandomizationDTO getRandomizationDTOObject(String studyOid) { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String randomizationUrl = CoreResources.getField("moduleManager") + "/app/rest/oc/se_randomizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setReadTimeout(RANDOMIZATION_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { SeRandomizationDTO response = rest.getForObject(randomizationUrl, SeRandomizationDTO.class); if (response.getStudyOid() != null) { return response; } else { return null; } } catch (Exception e) { <START> logger.error("Response in not getting generated properly: ",e.getMessage(),e); <END> } return null; }</code><technical_language>do: logger.error("Response in generated properly", e);</technical_language>

Target:
public SeRandomizationDTO getRandomizationDTOObject(String studyOid) { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String randomizationUrl = CoreResources.getField("moduleManager") + "/app/rest/oc/se_randomizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setReadTimeout(RANDOMIZATION_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { SeRandomizationDTO response = rest.getForObject(randomizationUrl, SeRandomizationDTO.class); if (response.getStudyOid() != null) { return response; } else { return null; } } catch (Exception e) { logger.error("Response in not getting generated properly: ", e); } return null; }
Source:
<code>void tostring() { <START> assertThat(new AttributeWithValue("data-id", "expected").toString()).isEqualTo("attribute data-id=\"expected\""); <END> }</code><technical_language>hasToString assert</technical_language>

Target:
void tostring() { assertThat(new AttributeWithValue("data-id", "expected")).hasToString("attribute data-id=\"expected\""); }
Source:
<code>public String docs() { return "boolean {name} Adds a new team to the scoreboard, returning true if successful." <START> + " Returns false if a team already exists with the given name."; <END> }</code><technical_language>Lets throw exception (and return void) instead</technical_language>

Target:
public String docs() { return "void {name} Adds a new team to the scoreboard," + " throws an exception if a team already exists with the given name."; }
Source:
<code>public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener((ITestNGListener)new MyListener()); tng.run(); <START> Assertions.assertThat(TestClassSample.messages).containsExactly("afterInvocation", "retry","afterInvocation"); <END> }</code><technical_language>Typo: missing space ","</technical_language>

Target:
public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener((ITestNGListener)new MyListener()); tng.run(); assertThat(TestClassSample.messages).containsExactly("afterInvocation", "retry", "afterInvocation"); }
Source:
<code>int getFirstRowIndexOfMergedBlock(final GridData model, final int rowIndex) { int currentIndex = rowIndex; GridCell<?> cell = model.getCell(rowIndex, getHighlightCellColumnIndex()); <START> while (cell.getMergedCellCount() == 0) { <END> currentIndex--; cell = model.getCell(currentIndex, getHighlightCellColumnIndex()); } return currentIndex; }</code><technical_language>I condition in getMergedCellsCount: java cell.getMergedCellCount() == 0 && currentIndex >= 0</technical_language>

Target:
int getFirstRowIndexOfMergedBlock(final GridData model, final int rowIndex) { int currentIndex = rowIndex; GridCell<?> cell = model.getCell(rowIndex, getHighlightCellColumnIndex()); while (cell.getMergedCellCount() == 0 && currentIndex >= 0) { currentIndex--; cell = model.getCell(currentIndex, getHighlightCellColumnIndex()); } return currentIndex; }
Source:
<code>public static synchronized OVirtNodeInfo getInstance() { if (instance == null) { <START> instance = new OVirtNodeInfo(); <END> } return instance; }</code><technical_language>please add sync protection, EngineLocalConfig</technical_language>

Target:
public static synchronized OVirtNodeInfo getInstance() { if (instance == null) { instance = new OVirtNodeInfo(); } else { if (instance == null) { synchronized(OVirtNodeInfo.class) { if (instance == null) { instance = new OVirtNodeInfo(); } } } } return instance; }
Source:
<code>protected void populateReservoirInputPortMap() { for (Entry<String,Operators.PortContextPair<InputPort<?>>> entry : descriptor.inputPorts.entrySet()) { <START> if (entry.getValue().component instanceof InputPort) { <END> if (inputs.containsKey(entry.getKey())) { reservoirPortMap.put(inputs.get(entry.getKey()), entry.getValue().component.getSink()); } } } }</code><technical_language>component instance of InputPort default component is null</technical_language>

Target:
protected void populateReservoirInputPortMap() { for (Entry<String,Operators.PortContextPair<InputPort<?>>> entry : descriptor.inputPorts.entrySet()) { if (entry.getValue().component != null && entry.getValue().component instanceof InputPort) { if (inputs.containsKey(entry.getKey())) { reservoirPortMap.put(inputs.get(entry.getKey()), entry.getValue().component.getSink()); } } } }
Source:
<code>public Response getPurchaseOrder(@PathParam(PurapPropertyConstants.PURAP_DOC_ID) String purapDocumentIdentifier, @Context HttpHeaders headers) { try { HashMap<String, String> map = new HashMap<>(); map.put(PurapPropertyConstants.PURAP_DOC_ID, purapDocumentIdentifier); PurchaseOrderDocument poDoc = getLookupDao().findObjectByMap(PurchaseOrderDocument.class.newInstance(), map); if (ObjectUtils.isNull(poDoc)) { return respondNotFound(); } String responseBody = serializePoDocumentToJson(poDoc); return Response.ok(responseBody).build(); } catch (Exception ex) { <START> LOG.error(ex); <END> return respondInternalServerError(ex); } }</code><technical_language>more log statement needs function</technical_language>

Target:
public Response getPurchaseOrder(@PathParam(PurapPropertyConstants.PURAP_DOC_ID) String purapDocumentIdentifier, @Context HttpHeaders headers) { try { HashMap<String, String> map = new HashMap<>(); map.put(PurapPropertyConstants.PURAP_DOC_ID, purapDocumentIdentifier); PurchaseOrderDocument poDoc = getLookupDao().findObjectByMap(PurchaseOrderDocument.class.newInstance(), map); if (ObjectUtils.isNull(poDoc)) { return respondNotFound(); } String responseBody = serializePoDocumentToJson(poDoc); return Response.ok(responseBody).build(); } catch (Exception ex) { LOG.error("getPurchaseOrder", ex); return respondInternalServerError(ex); } }