auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void handleResult( SourceResponse response, ExecutorService executorService, File dumpDir, AtomicLong resultCount) { if (StringUtils.isNotBlank(zipFileName)) { try { Optional<QueryResponseTransformer> zipCompressionTransformer = getZipCompression(); if (zipCompressionTransformer.isPresent()) { BinaryContent binaryContent = zipCompressionTransformer.get().transform(response, zipArgs); if (binaryContent != null) { IOUtils.closeQuietly(binaryContent.getInputStream()); } Long resultSize = (long) response.getResults().size(); printStatus(resultCount.addAndGet(resultSize)); } } catch (InvalidSyntaxException e) { LOGGER.info("No Zip Transformer found. Unable export metacards to a zip file."); } catch (CatalogTransformerException e) { LOGGER.info("zipCompression transform failed"); } } else if (multithreaded > 1) { final List<Result> results = new ArrayList<>(response.getResults()); <START> executorService.submit( <END> () -> { for (final Result result : results) { Metacard metacard = result.getMetacard(); try { exportMetacard(dumpDir, metacard, resultCount); } catch (IOException e) { LOGGER.debug("Failed to dump metacard {}", metacard.getId(), e); } } }); } else { for (final Result result : response.getResults()) { Metacard metacard = result.getMetacard(); try { exportMetacard(dumpDir, metacard, resultCount); } catch (IOException e) { LOGGER.debug( "Unable to export metacard: [{}]", metacard.getId(), metacard.getTitle(), e); } } } }</code><technical_language>Time this code a private method a method reference instead. more readable for code is identical in else, able refactor re-use code</technical_language>

Target:
private void handleResult( SourceResponse response, ExecutorService executorService, File dumpDir, AtomicLong resultCount) { final List<Result> results = response.getResults(); if (StringUtils.isNotBlank(zipFileName)) { try { Optional<QueryResponseTransformer> zipCompressionTransformer = getZipCompression(); if (zipCompressionTransformer.isPresent()) { BinaryContent binaryContent = zipCompressionTransformer.get().transform(response, zipArgs); if (binaryContent != null) { IOUtils.closeQuietly(binaryContent.getInputStream()); } Long resultSize = (long) results.size(); printStatus(resultCount.addAndGet(resultSize)); } } catch (InvalidSyntaxException e) { LOGGER.info("No Zip Transformer found. Unable export metacards to a zip file."); } catch (CatalogTransformerException e) { LOGGER.info("zipCompression transform failed"); } } else if (multithreaded > 1) { executorService.submit(() -> processResults(results, dumpDir, resultCount)); } else { processResults(results, dumpDir, resultCount); } }
Source:
<code>public static URLConnection openURLConnection(URL url) <START> throws IOException, ConnectException { <END> return openURLConnection(url,DEFAULT_CONNECTION_TIMEOUT); }</code><technical_language>ConnectException is thrown anything... declared in throws</technical_language>

Target:
public static URLConnection openURLConnection(URL url) throws IOException { return openURLConnection(url,DEFAULT_CONNECTION_TIMEOUT); }
Source:
<code>public MethodOutcome createFHIRDiagnosticReport(@ResourceParam DiagnosticReport diagnosticReport) { System.out.println("DiagnosticReport: createFHIRDiagnosticReport"); diagnosticReport = diagnosticReportResource.createFHIRDiagnosticReport(diagnosticReport); MethodOutcome retVal = new MethodOutcome(); <START> retVal.setId(new IdDt("DiagnosticReport", "2889127246021897")); <END> OperationOutcome outcome = new OperationOutcome(); outcome.addIssue().setDetails("Diagnostic Report is successfully created"); retVal.setOperationOutcome(outcome); return retVal; }</code><technical_language>is this id hard coding? is supposed represent UUID of newly created OpenMRS object (in this case, encounter?) if so, get actual returned? need hard code</technical_language>

Target:
public MethodOutcome createFHIRDiagnosticReport(@ResourceParam DiagnosticReport diagnosticReport) { System.out.println("DiagnosticReport: createFHIRDiagnosticReport"); diagnosticReport = diagnosticReportResource.createFHIRDiagnosticReport(diagnosticReport); MethodOutcome retVal = new MethodOutcome(); retVal.setId(new IdDt("DiagnosticReport", diagnosticReport.getId().getIdPart())); OperationOutcome outcome = new OperationOutcome(); outcome.addIssue().setDetails("Diagnostic Report is successfully created"); retVal.setOperationOutcome(outcome); return retVal; }
Source:
<code>public List<HTNode> selectNextChildren(CoreNode currentNode, long t) throws ClosedChannelException { assert (currentNode.getNbChildren() > 0); int potentialNextSeqNb = currentNode.getSequenceNumber(); <START> List<HTNode> nextChildren = new LinkedList<>(); <END> for (int i = 0; i < currentNode.getNbChildren(); i++) { if (t >= currentNode.getChildStart(i) && t <= currentNode.getChildEnd(i)) { potentialNextSeqNb = currentNode.getChild(i); if (currentNode.isOnDisk()) { nextChildren.add( fTreeIO.readNode(potentialNextSeqNb) ); }else{ nextChildren.add( readNode(potentialNextSeqNb) ); } } } return nextChildren; }</code><technical_language>ArrayList is sufficient (less overhead LinkedList). Is ordering important? a Set? return a Collection instead</technical_language>

Target:
public Collection<HTNode> selectNextChildren(CoreNode currentNode, long t) throws ClosedChannelException { assert (currentNode.getNbChildren() > 0); int potentialNextSeqNb = currentNode.getSequenceNumber(); List<HTNode> nextChildren = new ArrayList<>(); for (int i = 0; i < currentNode.getNbChildren(); i++) { if (t >= currentNode.getChildStart(i) && t <= currentNode.getChildEnd(i)) { potentialNextSeqNb = currentNode.getChild(i); if (currentNode.isOnDisk()) { nextChildren.add(fTreeIO.readNode(potentialNextSeqNb)); } else { nextChildren.add(readNode(potentialNextSeqNb)); } } } return nextChildren; }
Source:
<code>public CDPStructuredNotificationEvent(CDPOperationDetails operation, CDPStructuredNotificationDetails notificationDetails) { super(CDPStructuredNotificationEvent.class.getSimpleName(), operation); this.notificationDetails = notificationDetails; <START> ldapNotificationDetails = null; rdsNotificationDetails = null; <END> }</code><technical_language>null initializations required? for in other constructors</technical_language>

Target:
public CDPStructuredNotificationEvent(CDPOperationDetails operation, CDPStructuredNotificationDetails notificationDetails) { super(CDPStructuredNotificationEvent.class.getSimpleName(), operation); this.notificationDetails = notificationDetails; }
Source:
<code>public void testQuerySerdeWithAlphaNumericTopNMetricSpec() throws IOException{ TopNQuery query = new TopNQueryBuilder() .dataSource(dataSource) .granularity(allGran) .dimension(marketDimension) .metric(new AlphaNumericTopNMetricSpec(null)) .threshold(2) .intervals(fullOnInterval) .aggregators(Lists.<AggregatorFactory>newArrayList(commonAggregators)) .build(); <START> String json = jsonMapper.writeValueAsString(query); <END> Query serdeQuery = jsonMapper.readValue(json, Query.class); Assert.assertEquals(query, serdeQuery); }</code><technical_language>for serde tests parse actual json. a round-trip test is enough, tells fields write parse correctly, write read fields</technical_language>

Target:
public void testQuerySerdeWithAlphaNumericTopNMetricSpec() throws IOException{ TopNQuery expectedQuery = new TopNQueryBuilder() .dataSource(dataSource) .granularity(allGran) .dimension(new LegacyDimensionSpec(marketDimension)) .metric(new AlphaNumericTopNMetricSpec(null)) .threshold(2) .intervals(fullOnInterval.getIntervals()) .aggregators(Lists.<AggregatorFactory>newArrayList(rowsCount)) .build(); String jsonQuery = "{\n" + " \"queryType\": \"topN\",\n" + " \"dataSource\": \"testing\",\n" + " \"dimension\": \"market\",\n" + " \"threshold\": 2,\n" + " \"metric\": {\n" + " \"type\": \"alphaNumeric\"\n" + " },\n" + " \"granularity\": \"all\",\n" + " \"aggregations\": [\n" + " {\n" + " \"type\": \"count\",\n" + " \"name\": \"rows\"\n" + " }\n" + " ],\n" + " \"intervals\": [\n" + " \"1970-01-01T00:00:00.000Z/2020-01-01T00:00:00.000Z\"\n" + " ]\n" + "}"; TopNQuery actualQuery = jsonMapper.readValue(jsonMapper.writeValueAsString(jsonMapper.readValue(jsonQuery, TopNQuery.class)), TopNQuery.class); Assert.assertEquals(expectedQuery, actualQuery); }
Source:
<code>private void processFile(File file) throws Exception { final ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); Log.d(TAG, "Processing entry: " + entry.getName()); String parts[] = entry.getName().split("/"); String filename = parts[parts.length - 1]; <START> String id = surveyIdGenerator.getSurveyIdFromFilePath(parts); <END> if (entry.isDirectory() || filename.startsWith(".") || ConstantUtil.BOOTSTRAP_ROLLBACK_FILE.equalsIgnoreCase(filename)) { continue; } if (filename.endsWith(ConstantUtil.BOOTSTRAP_DB_FILE)) { processDbInstructions(FileUtil.readText(zipFile.getInputStream(entry)), true); } else if (filename.endsWith(ConstantUtil.CASCADE_RES_SUFFIX)) { FileUtil.extract(new ZipInputStream(zipFile.getInputStream(entry)), FileUtil.getFilesDir(FileType.RES)); } else if (filename.endsWith(ConstantUtil.XML_SUFFIX)) { processSurveyFile(zipFile, entry, filename, id); } else { File helpDir = new File(FileUtil.getFilesDir(FileType.FORMS), id); if (!helpDir.exists()) { helpDir.mkdir(); } FileUtil.copy(zipFile.getInputStream(entry), new FileOutputStream(new File(helpDir, filename))); } } file.renameTo(new File(file.getAbsolutePath() + ConstantUtil.PROCESSED_OK_SUFFIX)); }</code><technical_language>I wondering if easier substring() entry.getName(). i.e. indexOf("/") is survey id lastIndexOf("/") is filename? ensure digits filename</technical_language>

Target:
private void processFile(File file) throws Exception { final ZipFile zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); Log.d(TAG, "Processing entry: " + entryName); int fileSeparatorPosition = entryName.lastIndexOf("/"); String filename = entryName.substring(fileSeparatorPosition + 1); String id = surveyIdGenerator .getSurveyIdFromFilePath(entryName.substring(0, fileSeparatorPosition)); if (entry.isDirectory() || filename.startsWith(".") || ConstantUtil.BOOTSTRAP_ROLLBACK_FILE.equalsIgnoreCase(filename)) { continue; } if (filename.endsWith(ConstantUtil.BOOTSTRAP_DB_FILE)) { processDbInstructions(FileUtil.readText(zipFile.getInputStream(entry)), true); } else if (filename.endsWith(ConstantUtil.CASCADE_RES_SUFFIX)) { FileUtil.extract(new ZipInputStream(zipFile.getInputStream(entry)), FileUtil.getFilesDir(FileType.RES)); } else if (filename.endsWith(ConstantUtil.XML_SUFFIX)) { processSurveyFile(zipFile, entry, filename, id); } else { File helpDir = new File(FileUtil.getFilesDir(FileType.FORMS), id); if (!helpDir.exists()) { helpDir.mkdir(); } FileUtil.copy(zipFile.getInputStream(entry), new FileOutputStream(new File(helpDir, filename))); } } file.renameTo(new File(file.getAbsolutePath() + ConstantUtil.PROCESSED_OK_SUFFIX)); }
Source:
<code>static JSONObject copyOperatorNewName(JSONObject op, String name){ try{ op = OrderedJSONObject.parse(op.serialize()); } catch(Exception e){ e.printStackTrace(); <START> System.exit(-1); <END> } JSONObject op_new=null; try { op_new = JSONObject.parse(op.serialize()); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } op_new.put("name", name); @SuppressWarnings("unchecked") Collection<JSONObject> inputs = (Collection<JSONObject>)op_new.get("inputs"); @SuppressWarnings("unchecked") Collection<JSONObject> outputs = (Collection<JSONObject>)op_new.get("outputs"); for(JSONObject input : inputs){ input.put("name", name + "_IN" + input.get("index").toString()); JSONArray conns = (JSONArray) input.get("connections"); conns.clear(); } for(JSONObject output : outputs){ output.put("name", name + "_OUT" + output.get("index").toString()); JSONArray conns = (JSONArray) output.get("connections"); conns.clear(); } return op_new; }</code><technical_language>call System.exit(), wrap Exception in a RuntimeException throw it</technical_language>

Target:
static JSONObject copyOperatorNewName(JSONObject op, String name){ JSONObject op_new=null; try { op_new = JSONObject.parse(op.serialize()); } catch (IOException e) { throw new RuntimeException("Error copying operator " + (String)op.get("name"), e); } op_new.put("name", name); @SuppressWarnings("unchecked") Collection<JSONObject> inputs = (Collection<JSONObject>)op_new.get("inputs"); @SuppressWarnings("unchecked") Collection<JSONObject> outputs = (Collection<JSONObject>)op_new.get("outputs"); for(JSONObject input : inputs){ input.put("name", name + "_IN" + input.get("index").toString()); JSONArray conns = (JSONArray) input.get("connections"); conns.clear(); } for(JSONObject output : outputs){ output.put("name", name + "_OUT" + output.get("index").toString()); JSONArray conns = (JSONArray) output.get("connections"); conns.clear(); } return op_new; }
Source:
<code>public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType())) { <START> if (providers.add(new ConfigurationProviderState<>(provider))) { <END> LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); forceReload = true; } } }</code><technical_language>Eliminate this if line 236 move condition if && line 235</technical_language>

Target:
public void providerRegistered(Registration registration, ConfigurationProvider provider) { if (clazz.equals(registration.getProvider(ConfigurationProvider.class).getType()) && providers.add(new ConfigurationProviderState<>(provider))) { LOG.debug("Registered configuration provider for {}.", provider, clazz.getCanonicalName()); forceReload = true; } }
Source:
<code>public BufferBuilder requestNewBufferBuilder(int targetChannel) throws IOException, InterruptedException { checkState(bufferBuilder == null || bufferBuilder.isFinished()); BufferBuilder builder = super.requestNewBufferBuilder(targetChannel); if (randomTriggered) { <START> addBufferConsumer(randomConsumer = builder.createBufferConsumer(), targetChannel); <END> } else { try (BufferConsumer bufferConsumer = builder.createBufferConsumer()) { for (int channel = 0; channel < numberOfChannels; channel++) { addBufferConsumer(bufferConsumer.copy(), channel); } } } bufferBuilder = builder; return builder; }</code><technical_language>I construct consumer filling BufferBuilder, random emitted latency marker is visible for other channels, breaks previous assumption</technical_language>

Target:
public BufferBuilder requestNewBufferBuilder(int targetChannel) throws IOException, InterruptedException { checkState(bufferBuilder == null || bufferBuilder.isFinished()); BufferBuilder builder = super.requestNewBufferBuilder(targetChannel); if (randomTriggered) { addBufferConsumer(randomTriggeredConsumer = builder.createBufferConsumer(), targetChannel); } else { try (BufferConsumer bufferConsumer = builder.createBufferConsumer()) { for (int channel = 0; channel < numberOfChannels; channel++) { addBufferConsumer(bufferConsumer.copy(), channel); } } } bufferBuilder = builder; return builder; }
Source:
<code>public void testIsEmpty() throws Exception { assertThat( Strings.isEmpty( null ) ).isTrue(); assertThat( Strings.isEmpty( "" ) ).isTrue(); assertThat( Strings.isEmpty( "not empty" ) ).isFalse(); <START> <END> }</code><technical_language>assertThat( Strings.isEmpty( " " ) ).isTrue();</technical_language>

Target:
public void testIsEmpty() throws Exception { assertThat( Strings.isEmpty( null ) ).isTrue(); assertThat( Strings.isEmpty( "" ) ).isTrue(); assertThat( Strings.isEmpty( " " ) ).isFalse(); assertThat( Strings.isEmpty( "not empty" ) ).isFalse(); }
Source:
<code>public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(GSE); } else { <START> logger.error("Unknown type of job seen"); <END> } } } }</code><technical_language>add task.getClass() log message</technical_language>

Target:
public void close() { if (enabled.compareAndSet(true, false)) { List<Runnable> pendingTasks = scheduler.shutdownNow(); for (Runnable task : pendingTasks) { if (task instanceof CryptoJob) { ((CryptoJob) task).closeJob(CLOSED_EXCEPTION); } else { logger.error("Unknown type of job seen : " + task.getClass()); } } } }
Source:
<code>protected synchronized void timerExpired(final Integer timerId) { if (m_kieSession == null) { <START> LOG.info("No valid session"); <END> return; } LOG.info("Begin correlation for Timer {}", timerId); TimerExpired expiration = new TimerExpired(timerId); m_kieSession.insert(expiration); try { if (!m_isStreaming) m_kieSession.fireAllRules(); } catch (Exception e) { LOG.error("Exception while firing rules ", e); } LOG.debug("Begin correlation for Timer {}", timerId); }</code><technical_language>suggestion LOG.info("No valid session exists. Timer id: added a fact.", timerId);</technical_language>

Target:
protected synchronized void timerExpired(final Integer timerId) { if (m_kieSession == null) { LOG.info("No valid session, Timer with Id will not be added as a fact.", timerId); return; } LOG.info("Begin correlation for Timer {}", timerId); TimerExpired expiration = new TimerExpired(timerId); m_kieSession.insert(expiration); try { if (!m_isStreaming) m_kieSession.fireAllRules(); } catch (Exception e) { LOG.error("Exception while firing rules ", e); } LOG.debug("Begin correlation for Timer {}", timerId); }
Source:
<code>public void initialize(VM vm, List<Disk> disksToSparsify, ICommandTarget target) { this.disksToSparsify = disksToSparsify; UIConstants uiConstants = ConstantsManager.getInstance().getConstants(); setTitle(uiConstants.sparsifyDisksTitle()); setMessage(uiConstants.sparsifyConfirmationPopupMessage()); setHelpTag(HelpTag.sparsify_disk); setHashName("sparsify_disk"); <START> getLatch().setEntity(false); <END> List<DiskModel> items = new ArrayList<>(); for (Disk disk : disksToSparsify) { DiskModel diskModel = new DiskModel(); diskModel.setDisk(disk); diskModel.setVm(vm); items.add(diskModel); if (disk.getNumberOfVms() > 1) { getLatch().setIsChangeable(false); } } setItems(items); UICommand okCommand = UICommand.createDefaultOkUiCommand(ON_SPARSIFY, target); getCommands().add(okCommand); cancelCommand = UICommand.createCancelUiCommand(CANCEL_SPARSIFY, target); getCommands().add(cancelCommand); }</code><technical_language>so, I understand copy pasted this code RemoveDiskModel latch serves purpose of deciding if disk removed permanently detached. I latch meaning. add "are want sparsify"? removed</technical_language>

Target:
public void initialize(VM vm, List<Disk> disksToSparsify, ICommandTarget target) { this.disksToSparsify = disksToSparsify; UIConstants uiConstants = ConstantsManager.getInstance().getConstants(); setTitle(uiConstants.sparsifyDisksTitle()); setMessage(uiConstants.sparsifyConfirmationPopupMessage()); setHelpTag(HelpTag.sparsify_disk); setHashName("sparsify_disk"); List<DiskModel> items = new ArrayList<>(); for (Disk disk : disksToSparsify) { DiskModel diskModel = new DiskModel(); diskModel.setDisk(disk); diskModel.setVm(vm); items.add(diskModel); } setItems(items); UICommand okCommand = UICommand.createDefaultOkUiCommand(ON_SPARSIFY, target); getCommands().add(okCommand); cancelCommand = UICommand.createCancelUiCommand(CANCEL_SPARSIFY, target); getCommands().add(cancelCommand); }
Source:
<code>public Iterable<IEventDeclaration> getEventDeclarations() { <START> return ImmutableSet.copyOf(fStreamInput.getStream().getEventDeclarations()); <END> }</code><technical_language>this immutable. a list</technical_language>

Target:
public Iterable<IEventDeclaration> getEventDeclarations() { return ImmutableList.copyOf(fStreamInput.getStream().getEventDeclarations()); }
Source:
<code>protected void destroyVm() { boolean wasPaused = false; VmStatic vmStatic = getVm().getStaticData(); if (getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(new Guid(getVm().getMigratingToVds().toString()), getVmId(), true, false, 0)); } if (getVm().getStatus() == VMStatus.Paused && getVm().getVmPauseStatus() == VmPauseStatus.NOERR) { <START> wasPaused = true; <END> } setActionReturnValue(Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(getVdsId(), getVmId(), false, false, 0)).getReturnValue()); if (wasPaused) { VmHandler.decreasePendingVms(getVm().getRunOnVds(), vmStatic.getNumOfCpus(), vmStatic.getMinAllocatedMem(), vmStatic.getName()); } }</code><technical_language>1. this is a matter of style merge declaration of wasPaused assignment in #90 like: boolean wasPaused = getVm().getStatus()... IMO code shorter more readable 2. a suggestion, for sake of making code more easy understand, moving line 80 clear expect status changed a result of destroy command</technical_language>

Target:
protected void destroyVm() { boolean wasPaused = (getVm().getStatus() == VMStatus.Paused && getVm().getVmPauseStatus() == VmPauseStatus.NOERR); if (getVm().getStatus() == VMStatus.MigratingFrom && getVm().getMigratingToVds() != null) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(new Guid(getVm().getMigratingToVds().toString()), getVmId(), true, false, 0)); } setActionReturnValue(Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.DestroyVm, new DestroyVmVDSCommandParameters(getVdsId(), getVmId(), false, false, 0)).getReturnValue()); if (wasPaused) { VmHandler.decreasePendingVms(getVm(), getVdsId()); } }
Source:
<code>private void setTabIndex() { String tabIndexProperty = $selectElement.attr(TABINDEX_PROPERTY); if (options.isRemoveFromTabIndexWhenDisabled()) { if (isDisabled) { tabIndexProperty = "-1"; } else { <START> tabIndexProperty = "0"; <END> } } if (tabIndexProperty != null && tabIndexProperty.length() > 0) { $selectElement.attr(TABINDEX_PROPERTY, -1); if (isMultiple) { searchField.attr(TABINDEX_PROPERTY, tabIndexProperty); } else { selectedItem.attr(TABINDEX_PROPERTY, tabIndexProperty); searchField.attr(TABINDEX_PROPERTY, -1); } } }</code><technical_language>set tabIndex set disabled</technical_language>

Target:
private void setTabIndex() { final String selectElementOriginalTabIndexProperty = $selectElement.attr(TABINDEX_PROPERTY); String tabIndexProperty = selectElementOriginalTabIndexProperty; if (isDisabled) { tabIndexProperty = "-1"; } if (tabIndexProperty != null && tabIndexProperty.length() > 0) { if (isMultiple) { searchField.attr(TABINDEX_PROPERTY, tabIndexProperty); } else { selectedItem.attr(TABINDEX_PROPERTY, tabIndexProperty); searchField.attr(TABINDEX_PROPERTY, -1); } } }
Source:
<code>private static BlockBuilder createBlockBuilder(Type type, long count) { <START> checkCondition(count <= MAX_LENGTH, INVALID_FUNCTION_ARGUMENT, "repeat count should be no greater than " + MAX_LENGTH); <END> checkCondition(count >= 0, INVALID_FUNCTION_ARGUMENT, "repeat count must be no smaller than zero"); return type.createBlockBuilder(new BlockBuilderStatus(), toIntExact(count)); }</code><technical_language>count argument of repeat function equal MAX_LENGTH</technical_language>

Target:
private static BlockBuilder createBlockBuilder(Type type, long count) { checkCondition(count <= MAX_RESULT_ENTRIES, INVALID_FUNCTION_ARGUMENT, "count argument of repeat function must be less than or equal to 10000"); checkCondition(count >= 0, INVALID_FUNCTION_ARGUMENT, "count argument of repeat function must be greater than or equal to 0"); return type.createBlockBuilder(new BlockBuilderStatus(), toIntExact(count)); }
Source:
<code>public boolean dequeueOutGoingMessageQueue() { <START> if (null == messageClient) { <END> return false; } String message = outGoingMessageQueue.poll(); if (null == message) { return false; } try { Friend receiver = MessageFactory.buildMessageByJson(message).getReceiver(); messageClient.sendMsg(receiver.getIp(), receiver.getPort(), message); return true; } catch (JSONException ex) { ex.printStackTrace(); } catch (UnknownHostException ex) { ex.printStackTrace(); } return false; }</code><technical_language>unnecessary check</technical_language>

Target:
public boolean dequeueOutGoingMessageQueue() { String message = outGoingMessageQueue.poll(); if (null == message) { return false; } try { Friend receiver = MessageFactory.buildMessageByJson(message).getReceiver(); messageClient.sendMsg(receiver.getIp(), receiver.getPort(), message); return true; } catch (JSONException ex) { ex.printStackTrace(); } catch (UnknownHostException ex) { ex.printStackTrace(); } return false; }
Source:
<code>public void loadObjectsExceptionThrownTest() throws Exception { Mockito.reset(queryLogger); Object result = null; try { query = Query.builder().table(playerStatsTable).bypassingCache(true).build(); SQLQuery myQuery = SQLQuery.builder().clientQuery(query) .fromClause(query.getTable().getName()) .projectionClause(" ").build(); when(queryEngine.executeQuery(query, qeTransaction)).thenReturn(null); when(queryEngine.explain(query)).thenReturn(myQuery.toString()); AggregationDataStoreTransaction transaction = new MyAggregationDataStoreTransaction(queryEngine, cache, queryLogger); EntityProjection entityProjection = EntityProjection.builder().type(PlayerStats.class).build(); transaction.loadObjects(entityProjection, scope); } catch (Exception e) { result = e.getMessage(); } finally { <START> Object finalResult = result; <END> Mockito.verify(queryLogger, times(1)).acceptQuery( Mockito.eq(scope.getRequestId()), any(), any(), any(), any(), any()); Mockito.verify(queryLogger, times(1)).processQuery( Mockito.eq(scope.getRequestId()), any(), any(), Mockito.eq(false)); Mockito.verify(queryLogger, times(1)).completeQuery( Mockito.eq(scope.getRequestId()), any()); Mockito.verify(queryLogger).completeQuery(Mockito.eq(scope.getRequestId()), argThat((QueryResponse qResponse) -> qResponse.getErrorMessage() == finalResult)); } }</code><technical_language>I need this variable</technical_language>

Target:
public void loadObjectsExceptionThrownTest() throws Exception { Mockito.reset(queryLogger); String nullPointerExceptionMessage = "Cannot dereference an object with value Null"; try { query = Query.builder().table(playerStatsTable).bypassingCache(true).build(); doThrow(new NullPointerException(nullPointerExceptionMessage)) .when(queryEngine).executeQuery(query, qeTransaction); AggregationDataStoreTransaction transaction = new MyAggregationDataStoreTransaction(queryEngine, cache, queryLogger); EntityProjection entityProjection = EntityProjection.builder().type(PlayerStats.class).build(); transaction.loadObjects(entityProjection, scope); } catch (Exception e) { assertEquals(nullPointerExceptionMessage, e.getMessage()); Mockito.verify(queryLogger).completeQuery(Mockito.eq(scope.getRequestId()), argThat((QueryResponse qResponse) -> qResponse.getErrorMessage() == e.getMessage())); } Mockito.verify(queryLogger, times(1)).acceptQuery( Mockito.eq(scope.getRequestId()), any(), any(), any(), any(), any()); Mockito.verify(queryLogger, times(1)).processQuery( Mockito.eq(scope.getRequestId()), any(), any(), Mockito.eq(false)); Mockito.verify(queryLogger, times(1)).completeQuery( Mockito.eq(scope.getRequestId()), any()); }
Source:
<code>@Test public void failWhenWriteToParcelAlreadyDefinedTest() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", "" + "package test;\n" + "import android.os.Parcel;\n" + "import android.os.Parcelable;\n" + "import com.google.auto.value.AutoValue;\n" + "@AutoValue public abstract class Test implements Parcelable {\n" + " public abstract String name();\n" + " @Override\n" + " public void writeToParcel(Parcel dest, int flags) {\n" + " }\n" + "}" ); assertAbout(javaSources()) .that(Arrays.asList(parcel, parcelable, source)) .processedWith(new AutoValueProcessor()) <START> .failsToCompile(); <END> }</code><technical_language>assert error message is correct points right line</technical_language>

Target:
@Test public void failWhenWriteToParcelAlreadyDefinedTest() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", "" + "package test;\n" + "import android.os.Parcel;\n" + "import android.os.Parcelable;\n" + "import com.google.auto.value.AutoValue;\n" + "@AutoValue public abstract class Test implements Parcelable {\n" + " public abstract String name();\n" + " @Override\n" + " public void writeToParcel(Parcel dest, int flags) {\n" + " }\n" + "}" ); assertAbout(javaSources()) .that(Arrays.asList(parcel, parcelable, source)) .processedWith(new AutoValueProcessor()) .failsToCompile() .withErrorContaining("Manual implementation of Parcelable#writeToParcel(Parcel,int) found when " + "processing test.Test. Remove this so auto-value-parcel can automatically " + "generate the implementation for you.") .in(source) .onLine(8); }
Source:
<code>public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final EventAuthField that = (EventAuthField) o; <START> return (this.type.equals(that.type) && this.path.equals(that.path)); <END> }</code><technical_language>I is annotation @NotNull, still, is write Objects.equals(this.type, that.type) && Objects.equals(this.path, that.path) hash code - Objects.hash(this.path)</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final EventAuthField that = (EventAuthField) o; return Objects.equals(this.type, that.type) && Objects.equals(this.path, that.path); }
Source:
<code><START> Multimap<String, String> buildMultiMapHeaders(Map<String, String> headers) <END> { Multimap<String, String> multimap = ArrayListMultimap.create(); for (Map.Entry<String, String> entry : headers.entrySet()) { multimap.put(entry.getKey(), entry.getValue()); } return multimap; }</code><technical_language>minor, is method scope for Visible For Testing? If please change private</technical_language>

Target:
private Multimap<String, String> buildMultiMapHeaders(Map<String, String> headers) { Multimap<String, String> multimap = ArrayListMultimap.create(); for (Map.Entry<String, String> entry : headers.entrySet()) { multimap.put(entry.getKey(), entry.getValue()); } return multimap; }
Source:
<code>public Object getAdapter(Class adapter) { <START> if (adapter == IResource.class) { <END> return resource; } return null; }</code><technical_language>style nit: curly braces single line blocks</technical_language>

Target:
public Object getAdapter(Class adapter) { if (adapter == IResource.class) return resource; return null; }
Source:
<code>public AddUnseenToBitmapFilter(BitmapBuilder seen, BitmapBuilder bitmap) { this.seen = seen; this.bitmap = <START> bitmapResult; <END> }</code><technical_language>bitmap</technical_language>

Target:
public AddUnseenToBitmapFilter(BitmapBuilder seen, BitmapBuilder bitmap) { this.seen = seen; this.bitmap = bitmap; }
Source:
<code>private Group drawStackContainer(final StackedMutationContainer stack, final double width) { Group root = new Group(); int stacks = stack.getStack().size(); for (int index = 0; index < stacks; index++) { StackView stackView = new StackView(stack.getStack().get(index), <START> width / stacks, stack.getMaxMutations()); <END> stackView.setLayoutX(index * width / stacks); root.getChildren().add(stackView); } return root; }</code><technical_language>duplicate width / stacks</technical_language>

Target:
private Group drawStackContainer(final StackedMutationContainer stack, final double width) { Group root = new Group(); int stacks = stack.getStack().size(); double stackWidth = width / stacks; for (int index = 0; index < stacks; index++) { StackView stackView = new StackView(stack.getStack().get(index), stackWidth, stack.getMaxMutations()); stackView.setLayoutX(index * stackWidth); root.getChildren().add(stackView); } return root; }
Source:
<code>public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; if (state.walk != null) { DirCacheIterator i = state.walk.getTree(state.dirCacheTree, DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null <START> && compareMetadata(ent) == MetadataDiff.DIFFER_BY_TIMESTAMP) <END> return i.idBuffer(); } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_SYMLINK: return zeroid; case FileMode.TYPE_GITLINK: return zeroid; } return zeroid; }</code><technical_language>return buffer if compareMetadata returns EQUAL? I is update index, git status/diff does. place</technical_language>

Target:
public byte[] idBuffer() { if (contentIdFromPtr == ptr) return contentId; if (state.walk != null) { DirCacheIterator i = state.walk.getTree(state.dirCacheTree, DirCacheIterator.class); if (i != null) { DirCacheEntry ent = i.getDirCacheEntry(); if (ent != null && compareMetadata(ent) == MetadataDiff.EQUAL) return i.idBuffer(); } } switch (mode & FileMode.TYPE_MASK) { case FileMode.TYPE_FILE: contentIdFromPtr = ptr; return contentId = idBufferBlob(entries[ptr]); case FileMode.TYPE_SYMLINK: return zeroid; case FileMode.TYPE_GITLINK: return zeroid; } return zeroid; }
Source:
<code><START> @Test public void destinationIsAFileExecutorTest() throws IOException { <END> TestUtils.createFile(SAMPLE_TEXT_FILE); executeConversion(TestConstants.SAMPLE_JAR_FILE, SAMPLE_TEXT_FILE); if (Files.exists(SAMPLE_TEXT_FILE)) { BundleGeneratorUtils.delete(SAMPLE_TEXT_FILE); } Path jarFilePath = TestConstants.SAMPLE_JAR_FILE.getFileName(); if (jarFilePath != null) { String jarFileName = getBundleSymbolicName(jarFilePath); String bundleName = jarFileName + "_1.0.0.jar"; Path bundlePath = Paths.get(SAMPLE_TEXT_FILE.toString(), bundleName); Assert.assertFalse(Files.exists(bundlePath)); } else { assert false; } }</code><technical_language>check formatting</technical_language>

Target:
public void destinationIsAFileExecutorTest() throws IOException { TestUtils.createFile(SAMPLE_TEXT_FILE); executeConversion(TestConstants.SAMPLE_JAR_FILE, SAMPLE_TEXT_FILE); if (Files.exists(SAMPLE_TEXT_FILE)) { BundleGeneratorUtils.delete(SAMPLE_TEXT_FILE); } Path jarFilePath = TestConstants.SAMPLE_JAR_FILE.getFileName(); if (jarFilePath != null) { String jarFileName = getBundleSymbolicName(jarFilePath); String bundleName = jarFileName + "_1.0.0.jar"; Path bundlePath = Paths.get(SAMPLE_TEXT_FILE.toString(), bundleName); Assert.assertFalse(Files.exists(bundlePath)); } else { assert false; } }
Source:
<code>private KubernetesList unmarshal(Tool tool, String recipeContent) throws DevfileRecipeFormatException { try { return Serialization.unmarshal(recipeContent, KubernetesList.class); } catch (KubernetesClientException e) { throw new DevfileRecipeFormatException( format( <START> "Error occurred during parsing list from file %s for tool '%s'", <END> tool.getLocal(), tool.getName())); } }</code><technical_language>Please consider adding original error message thrown exception</technical_language>

Target:
private KubernetesList unmarshal(Tool tool, String recipeContent) throws DevfileRecipeFormatException { try { return Serialization.unmarshal(recipeContent, KubernetesList.class); } catch (KubernetesClientException e) { throw new DevfileRecipeFormatException( format( "Error occurred during parsing list from file %s for tool '%s': %s", tool.getLocal(), tool.getName(), e.getMessage())); } }
Source:
<code>private Response validateCacheWithServer(final Request req, final String home, final String method, final Collection<Map.Entry<String, String>> headers, final InputStream content, final int connect, final int read) throws IOException { final Response rspCached = this.cache.get(req); final Collection<Map.Entry<String, String>> hdrs = this.enrich( headers, rspCached ); Response rsp = this.origin.send( req, home, method, hdrs, content, connect, read ); if (rsp.status() == HttpURLConnection.HTTP_NOT_MODIFIED) { rsp = rspCached; } else { <START> this.updateCache(req, rsp); <END> } return rsp; }</code><technical_language>In this case, if new response turns out Last-Modified, entry evicted cache, IMO</technical_language>

Target:
private Response validateCacheWithServer(final Request req, final String home, final String method, final Collection<Map.Entry<String, String>> headers, final InputStream content, final int connect, final int read) throws IOException { final Response rsp = this.cache.get(req); final Collection<Map.Entry<String, String>> hdrs = this.enrich( headers, rsp ); Response result = this.origin.send( req, home, method, hdrs, content, connect, read ); if (result.status() == HttpURLConnection.HTTP_NOT_MODIFIED) { result = rsp; } else { this.updateCache(req, result); } return result; }
Source:
<code>protected void run(Date lastRun) { WikipediaApp app = (WikipediaApp) context.getApplicationContext(); try { for (String[] styleSpec : STYLE_SPECS) { String url = getRemoteURLFor(styleSpec[1]); OutputStream fo = context.openFileOutput(styleSpec[0], Context.MODE_PRIVATE); Utils.copyStreams(HttpRequest.get(url).userAgent(app.getUserAgent()).stream(), fo); fo.close(); Log.d("Wikipedia", String.format("Downloaded %s into %s", url, context.getFileStreamPath(styleSpec[0]).getAbsolutePath())); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { <START> e.printStackTrace(); <END> } catch (HttpRequest.HttpRequestException e) { e.printStackTrace(); } }</code><technical_language>Log.d "Wikipedia" tag</technical_language>

Target:
protected void run(Date lastRun) { WikipediaApp app = (WikipediaApp) context.getApplicationContext(); try { for (String[] styleSpec : STYLE_SPECS) { String url = getRemoteURLFor(styleSpec[1]); OutputStream fo = context.openFileOutput(styleSpec[0], Context.MODE_PRIVATE); Utils.copyStreams(HttpRequest.get(url).userAgent(app.getUserAgent()).stream(), fo); fo.close(); Log.d("Wikipedia", String.format("Downloaded %s into %s", url, context.getFileStreamPath(styleSpec[0]).getAbsolutePath())); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putString(WikipediaApp.PREFERENCE_STYLES_LAST_UPDATED, Utils.formatISO8601(new Date())).commit(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { Log.d("StyleFetcherTask", e.getMessage()); e.printStackTrace(); } catch (HttpRequest.HttpRequestException e) { Log.d("StyleFetcherTask", e.getMessage()); e.printStackTrace(); } }
Source:
<code><START> public static String unescape(String text) { <END> return StringEscapeUtils.unescapeHtml(text); }</code><technical_language>public static method is a good idea</technical_language>

Target:
private String unescape(String text) { return StringEscapeUtils.unescapeHtml(text); }
Source:
<code>public void setupTest() { this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.hypervisorType = new ConsumerType(ConsumerTypeEnum.HYPERVISOR); ConsumerBindUtil consumerBindUtil = new ConsumerBindUtil( <START> null, null, null, null, mockedServiceLevelValidator); <END> this.consumerResource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, null, this.idCertService, null, this.i18n, this.sink, this.eventFactory, null, null, this.userService, null, null, null, this.ownerCurator, this.activationKeyCurator, null, this.complianceRules, this.deletedConsumerCurator, null, null, new CandlepinCommonTestConfig(), null, null, null, consumerBindUtil); hypervisorResource = new HypervisorResource(consumerResource, consumerCurator, i18n, ownerCurator); when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class))) .thenReturn(new ComplianceStatus(new Date())); when(ownerCurator.lookupByKey(any(String.class))).thenReturn(new Owner()); when(eventFactory.getEventBuilder(any(Target.class), any(Type.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setNewEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setOldEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); }</code><technical_language>This is a layer deeper mocks necessary, consumerBindUtil a mock, returns a correct result for service level method used? a good idea layers deep this</technical_language>

Target:
public void setupTest() { this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.hypervisorType = new ConsumerType(ConsumerTypeEnum.HYPERVISOR); this.consumerResource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, null, this.idCertService, null, this.i18n, this.sink, this.eventFactory, null, null, this.userService, null, null, null, this.ownerCurator, this.activationKeyCurator, null, this.complianceRules, this.deletedConsumerCurator, null, null, new CandlepinCommonTestConfig(), null, null, null, this.consumerBindUtil); hypervisorResource = new HypervisorResource(consumerResource, consumerCurator, i18n, ownerCurator); when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class))) .thenReturn(new ComplianceStatus(new Date())); when(ownerCurator.lookupByKey(any(String.class))).thenReturn(new Owner()); when(eventFactory.getEventBuilder(any(Target.class), any(Type.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setNewEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); when(consumerEventBuilder.setOldEntity(any(Consumer.class))) .thenReturn(consumerEventBuilder); }
Source:
<code>protected static int isReadme(String name) { boolean isDoc = name.startsWith(DOC_PREFIX); boolean isParentDoc = name.startsWith(PARENT_DOC_PREFIX); if (isDoc || isParentDoc) { String filename = new Path(name).lastSegment(); <START> if (filename.length() >= 6 && filename.substring(0, 6).equalsIgnoreCase("readme")) { <END> return isDoc ? 1 : 2; } } return 0; }</code><technical_language>This test a bit optimist; starting readme matches. readme-test.md, readme-sample.ascidoc, etc</technical_language>

Target:
public static int isReadme(String name) { if (name == null) { return 0; } boolean isDoc = name.startsWith(DOC_PREFIX); boolean isParentDoc = name.startsWith(PARENT_DOC_PREFIX); if (isDoc || isParentDoc) { Path path = new Path(name); String filename = path.lastSegment(); if ("md".equals(path.getFileExtension()) && filename.length() >= 6 && filename.substring(0, 6).equalsIgnoreCase("readme")) { return isDoc ? 1 : 2; } } return 0; }
Source:
<code>public void testGlobalOutstandingRequestThrottlingWithRequestThrottlerDisabled() throws Exception { System.setProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT, GLOBAL_OUTSTANDING_LIMIT); ServerMetrics.getMetrics().resetAll(); RequestThrottler.setMaxRequests(0); resumeProcess = new CountDownLatch(1); int totalRequests = 10; submitted = new CountDownLatch(totalRequests); for (int i = 0; i < totalRequests; i++) { zk.create("/request_throttle_test- " + i, ("/request_throttle_test- " + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { }, null); } submitted.await(5, TimeUnit.SECONDS); resumeProcess.countDown(); assertEquals(Integer.parseInt(GLOBAL_OUTSTANDING_LIMIT) + 2, (long) MetricsUtils.currentServerMetrics().get("prep_processor_request_queued")); <START> System.clearProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT); <END> }</code><technical_language>clear property in a finally block</technical_language>

Target:
public void testGlobalOutstandingRequestThrottlingWithRequestThrottlerDisabled() throws Exception { try { System.setProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT, GLOBAL_OUTSTANDING_LIMIT); ServerMetrics.getMetrics().resetAll(); RequestThrottler.setMaxRequests(0); resumeProcess = new CountDownLatch(1); int totalRequests = 10; submitted = new CountDownLatch(totalRequests); for (int i = 0; i < totalRequests; i++) { zk.create("/request_throttle_test- " + i, ("/request_throttle_test- " + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { }, null); } submitted.await(5, TimeUnit.SECONDS); resumeProcess.countDown(); assertEquals(Integer.parseInt(GLOBAL_OUTSTANDING_LIMIT) + 2, (long) MetricsUtils.currentServerMetrics().get("prep_processor_request_queued")); } catch (Exception e) { throw e; } finally { System.clearProperty(ZooKeeperServer.GLOBAL_OUTSTANDING_LIMIT); } }
Source:
<code>private void addBootProtocol(Map<String, String> opts, VdsNetworkInterface iface) { <START> if (iface.getBootProtocol() != null) { <END> switch (iface.getBootProtocol()) { case DHCP: opts.put(BOOT_PROTOCOL, DHCP_BOOT_PROTOCOL); break; case STATIC_IP: putIfNotEmpty(opts, "ipaddr", iface.getAddress()); putIfNotEmpty(opts, "netmask", iface.getSubnet()); putIfNotEmpty(opts, "gateway", iface.getGateway()); break; } } }</code><technical_language>perform this condition prior calling this method - adheres 'for loop' behavior. user is aware in cases this method (when is a real boot protocol)</technical_language>

Target:
private void addBootProtocol(Map<String, String> opts, VdsNetworkInterface iface) { switch (iface.getBootProtocol()) { case DHCP: opts.put(BOOT_PROTOCOL, DHCP_BOOT_PROTOCOL); break; case STATIC_IP: putIfNotEmpty(opts, "ipaddr", iface.getAddress()); putIfNotEmpty(opts, "netmask", iface.getSubnet()); putIfNotEmpty(opts, "gateway", iface.getGateway()); break; default: break; } }
Source:
<code>public void validateSessions() { <START> Byte[] fake = null; <END> fake[0].toString(); }</code><technical_language>throw exception this more clear</technical_language>

Target:
public void validateSessions() throws RuntimeException { throw new RuntimeException("Session test exception"); }
Source:
<code>public void testFilePollHdfsJob() { String data = UUID.randomUUID().toString(); String sourceFileName = UUID.randomUUID().toString(); <START> SimpleFileSource fileSource = sources.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName + ".out").reference( <END> true); job(jobs.filePollHdfsJob(DEFAULT_NAMES).toDSL()); waitForXD(); stream(fileSource + XD_TAP_DELIMETER + " queue:job:" + JOB_NAME); waitForXD(); stream("DataReceiver", sources.http() + XD_DELIMETER + sinks.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName).toDSL("REPLACE", "true"), WAIT_TIME); waitForXD(); sources.http().postData(data); assertValidHdfs(data, FilePollHdfsJob.DEFAULT_DIRECTORY + "/" + FilePollHdfsJob.DEFAULT_FILE_NAME + "-0.csv"); }</code><technical_language>I overload toDSL(String, String) method, setters set --mode --binary options toDSL pick options</technical_language>

Target:
public void testFilePollHdfsJob() { String data = UUID.randomUUID().toString(); String sourceFileName = UUID.randomUUID().toString(); SimpleFileSource fileSource = sources.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName + ".out").reference( true); waitForXD(); job(jobs.filePollHdfsJob(DEFAULT_NAMES).toDSL()); waitForXD(); stream(fileSource + XD_TAP_DELIMETER + " queue:job:" + JOB_NAME); waitForXD(); stream("DataReceiver", sources.http() + XD_DELIMETER + sinks.file(FilePollHdfsJob.DEFAULT_FILE_NAME, sourceFileName), WAIT_TIME); waitForXD(); sources.http().postData(data); assertValidHdfs(data, FilePollHdfsJob.DEFAULT_DIRECTORY + "/" + FilePollHdfsJob.DEFAULT_FILE_NAME + "-0.csv"); }