auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public long appendFrom(ReadableByteChannel channel, long size) throws IOException { logger.trace("Log : currentWriteOffset capacityInBytes sizeToAppend {}", file.getAbsolutePath(), currentWriteOffset, capacityInBytes, size); if (currentWriteOffset.get() + size > capacityInBytes) { metrics.overflowWriteError.inc(1); throw new IllegalArgumentException("Log : " + file.getAbsolutePath() + " error trying to append to log " + "from channel since new data size " + size + "exceeds total log size " + capacityInBytes); } long bytesWritten = 0; while(bytesWritten < size) { bytesWritten += fileChannel.transferFrom(channel, currentWriteOffset.get() + bytesWritten, size - bytesWritten); } <START> if(bytesWritten != size) { <END> throw new IOException("Couldn't read entire bytes. Read only " + bytesWritten +", expected to be read " + size); } currentWriteOffset.addAndGet(bytesWritten); logger.trace("Log : bytes appended to the log from read channel bytesWritten: {}", file.getAbsolutePath(), bytesWritten); return bytesWritten; }</code><technical_language>this happen now, (assuming checking for bytesWritten < size)</technical_language>

Target:
public void appendFrom(ReadableByteChannel channel, long size) throws IOException { logger.trace("Log : currentWriteOffset capacityInBytes sizeToAppend {}", file.getAbsolutePath(), currentWriteOffset, capacityInBytes, size); if (currentWriteOffset.get() + size > capacityInBytes) { metrics.overflowWriteError.inc(1); throw new IllegalArgumentException("Log : " + file.getAbsolutePath() + " error trying to append to log " + "from channel since new data size " + size + "exceeds total log size " + capacityInBytes); } long bytesWritten = 0; while (bytesWritten < size) { bytesWritten += fileChannel.transferFrom(channel, currentWriteOffset.get() + bytesWritten, size - bytesWritten); } currentWriteOffset.addAndGet(bytesWritten); logger.trace("Log : bytes appended to the log from read channel bytesWritten: {}", file.getAbsolutePath(), bytesWritten); }
Source:
<code>public OrcLocalMemoryContext newOrcLocalMemoryContext(String allocationTag) { <START> return new NoopOrcLocalMemoryContext(); <END> }</code><technical_language>refer const</technical_language>

Target:
public OrcLocalMemoryContext newOrcLocalMemoryContext(String allocationTag) { return NOOP_ORC_LOCAL_MEMORY_CONTEXT; }
Source:
<code>public void didChange(DidChangeTextDocumentParams params) throws NullPointerException { String uri = params.getTextDocument().getUri(); TextDocumentContentChangeEvent contentChange = params.getContentChanges().get(0); if (contentChange == null) { throw new NullPointerException("Event change param cannot be null"); } String input = params.getContentChanges().get(0).getText(); fFiltersInputs.put(uri, input); try { List<Diagnostic> diagnostics = FilterValidation.validate(input); PublishDiagnosticsParams pd = new PublishDiagnosticsParams(uri, diagnostics); pd.setDiagnostics(diagnostics); LanguageClient client = fLSPServer.getClient(); if (client != null) { client.publishDiagnostics(pd); } <START> } catch (RecognitionException error) { <END> Activator.getInstance().logError(error.getMessage()); } catch (IOException error) { Activator.getInstance().logError(error.getMessage()); } }</code><technical_language>multi-catch</technical_language>

Target:
public void didChange(DidChangeTextDocumentParams params) throws NullPointerException { String uri = params.getTextDocument().getUri(); TextDocumentContentChangeEvent contentChange = params.getContentChanges().get(0); if (contentChange == null) { throw new NullPointerException("Event change param cannot be null"); } String input = params.getContentChanges().get(0).getText(); fFiltersInputs.put(uri, input); try { List<Diagnostic> diagnostics = FilterValidation.validate(input); PublishDiagnosticsParams pd = new PublishDiagnosticsParams(uri, diagnostics); pd.setDiagnostics(diagnostics); LanguageClient client = fLSPServer.getClient(); if (client != null) { client.publishDiagnostics(pd); } } catch (RecognitionException | IOException error) { Activator.getInstance().logError(error.getMessage()); } }
Source:
<code>private void updateLocalStorageRef(AgentResponse rsp, LocalStorageHostRefVO ref) { if (ref.getAvailablePhysicalCapacity() == rsp.getAvailableCapacity() && ref.getTotalPhysicalCapacity() == rsp.getTotalCapacity()) { return; } long originalPhysicalTotal = ref.getTotalPhysicalCapacity(); long originalPhysicalAvailable = ref.getAvailablePhysicalCapacity(); ref.setTotalPhysicalCapacity(rsp.getTotalCapacity()); ref.setAvailablePhysicalCapacity(rsp.getAvailableCapacity()); <START> dbf.updateAndRefresh(ref); <END> if (logger.isTraceEnabled()) { logger.trace(String.format("[Local Storage Capacity] changed the physical capacity of the host[uuid:%s] of " + "the local primary storage[uuid:%s] as:\n" + "physical total: %s --> %s\n" + "physical available: %s --> %s\n", ref.getHostUuid(), ref.getPrimaryStorageUuid(), originalPhysicalTotal, ref.getTotalPhysicalCapacity(), originalPhysicalAvailable, ref.getAvailablePhysicalCapacity())); } }</code><technical_language>dbf.getEntityManager().merge(ref);</technical_language>

Target:
private void updateLocalStorageRef(AgentResponse rsp, LocalStorageHostRefVO ref) { if (ref.getAvailablePhysicalCapacity() == rsp.getAvailableCapacity() && ref.getTotalPhysicalCapacity() == rsp.getTotalCapacity()) { return; } long originalPhysicalTotal = ref.getTotalPhysicalCapacity(); long originalPhysicalAvailable = ref.getAvailablePhysicalCapacity(); ref.setTotalPhysicalCapacity(rsp.getTotalCapacity()); ref.setAvailablePhysicalCapacity(rsp.getAvailableCapacity()); dbf.getEntityManager().merge(ref); if (logger.isTraceEnabled()) { logger.trace(String.format("[Local Storage Capacity] changed the physical capacity of the host[uuid:%s] of " + "the local primary storage[uuid:%s] as:\n" + "physical total: %s --> %s\n" + "physical available: %s --> %s\n", ref.getHostUuid(), ref.getPrimaryStorageUuid(), originalPhysicalTotal, ref.getTotalPhysicalCapacity(), originalPhysicalAvailable, ref.getAvailablePhysicalCapacity())); } }
Source:
<code>public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException { populateAttributes(session); Intent intent = request.getIntent(); if (HELP.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText("The OneBusAway skill will tell you upcoming transit arrivals " + "at a stop of your choice. You've already configured your region and stop, " + "so just open the skill or ask me for arrivals. " + "You can also ask me to change your city or stop."); return SpeechletResponse.newTellResponse(out); } else if (REPEAT.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText(getCachedResponse(session)); return SpeechletResponse.newTellResponse(out); } else if (SET_CITY.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_CITY.equals(intent.getName())) { return getCity(); <START> } else if (SET_STOP_NUMBER.equals(intent.getName()) || YES.equals(intent.getName()) || NO.equals(intent.getName())) { <END> return anonSpeechlet.onIntent(request, session); } else if (GET_STOP_NUMBER.equals(intent.getName())) { return getStopDetails(); } else if (GET_ARRIVALS.equals(intent.getName())) { return tellArrivals(); } else if (STOP.equals(intent.getName())) { return goodbye(); } else { throw new SpeechletException("Did not recognize intent name"); } }</code><technical_language>please split out intents else if block? } else if (YES.equals(intent.getName()) || NO.equals(intent.getName()) { For SET_STOP_NUMBER intent, more general in future, added code generalize them</technical_language>

Target:
public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException { populateAttributes(session); Intent intent = request.getIntent(); if (HELP.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText("The OneBusAway skill will tell you upcoming transit arrivals " + "at a stop of your choice. You've already configured your region and stop, " + "so just open the skill or ask me for arrivals. " + "You can also ask me to change your city or stop."); return SpeechletResponse.newTellResponse(out); } else if (REPEAT.equals(intent.getName())) { PlainTextOutputSpeech out = new PlainTextOutputSpeech(); out.setText(getCachedResponse(session)); return SpeechletResponse.newTellResponse(out); } else if (SET_CITY.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_CITY.equals(intent.getName())) { return getCity(); } else if (SET_STOP_NUMBER.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (YES.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (NO.equals(intent.getName())) { return anonSpeechlet.onIntent(request, session); } else if (GET_STOP_NUMBER.equals(intent.getName())) { return getStopDetails(); } else if (GET_ARRIVALS.equals(intent.getName())) { return tellArrivals(); } else if (STOP.equals(intent.getName())) { return goodbye(); } else { throw new SpeechletException("Did not recognize intent name"); } }
Source:
<code>public void testActionBeginOrJoinAndNoTx() throws Exception { MuleTransactionConfig config = new MuleTransactionConfig(TransactionConfig.ACTION_BEGIN_OR_JOIN); ExecutionTemplate executionTemplate = createExecutionTemplate(config); config.setFactory(new TestTransactionFactory(mockTransaction)); Object result = executionTemplate.execute(getEmptyTransactionCallback()); assertThat(result, is(RETURN_VALUE)); verify(mockTransaction).commit(); verify(mockTransaction, never()).rollback(); <START> assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.nullValue()); <END> }</code><technical_language>static import</technical_language>

Target:
public void testActionBeginOrJoinAndNoTx() throws Exception { MuleTransactionConfig config = new MuleTransactionConfig(ACTION_BEGIN_OR_JOIN); ExecutionTemplate executionTemplate = createExecutionTemplate(config); config.setFactory(new TestTransactionFactory(mockTransaction)); Object result = executionTemplate.execute(getEmptyTransactionCallback()); assertThat(result, is(RETURN_VALUE)); verify(mockTransaction).commit(); verify(mockTransaction, never()).rollback(); assertThat(getInstance().getTransaction(), nullValue()); }
Source:
<code>protected Validator getValidator(final TaskRepository repository) { return new org.eclipse.mylyn.tasks.ui.wizards.AbstractRepositorySettingsPage.Validator() { @Override public void run(IProgressMonitor monitor) throws CoreException { RepositoryInfo repositoryInfo = connector.validateRepository(repository, monitor); <START> setStatus(new Status(IStatus.OK, TasksUiPlugin.ID_PLUGIN, "Settings are valid (repository has version " <END> + repositoryInfo.getVersion() + ")")); } }; }</code><technical_language>NLS.bind() construct message</technical_language>

Target:
protected Validator getValidator(final TaskRepository repository) { return new org.eclipse.mylyn.tasks.ui.wizards.AbstractRepositorySettingsPage.Validator() { @Override public void run(IProgressMonitor monitor) throws CoreException { RepositoryInfo repositoryInfo = connector.validateRepository(repository, monitor); setStatus(new Status(IStatus.OK, TasksUiPlugin.ID_PLUGIN, NLS.bind( Messages.AbstractRepositorySettingsPage_Settings_are_valid_version, repositoryInfo.getVersion()))); } }; }
Source:
<code>public BasicAuthTestResourceConfig() { <START> super(); <END> register(AuthResource.class); }</code><technical_language>I believe, super() is redundant, Java compiler automatically inserts a call default constructor of a superclass</technical_language>

Target:
public BasicAuthTestResourceConfig() { register(AuthResource.class); }
Source:
<code>protected void reInitializeColumnsWidth() { final List<IAxis> notationColumnsAxisList = <START> tableManager.getTable().getCurrentColumnAxisProvider().getAxis(); <END> final DataLayer tableBodyLayer = tableManager.getBodyLayerStack().getBodyDataLayer(); for (int index = 0; index < notationColumnsAxisList.size(); index++) { final IAxis currentColumnAxis = notationColumnsAxisList.get(index); if (!tableManager.getTable().isInvertAxis()) { final int axisWidth = tableBodyLayer.getColumnWidthByPosition(index); final IntValueStyle value = (IntValueStyle) currentColumnAxis.getNamedStyle(NattablestylePackage.eINSTANCE.getIntValueStyle(), NamedStyleConstants.AXIS_WIDTH); if (null != value) { tableBodyLayer.setColumnWidthByPosition(index, value.getIntValue(), false); } else if (axisWidth != DefaultSizeUtils.getDefaultCellWidth()) { tableBodyLayer.setColumnWidthByPosition(index, DefaultSizeUtils.getDefaultCellWidth(), false); } } } }</code><technical_language>rows for tables filled users</technical_language>

Target:
protected void reInitializeColumnsWidth() { final List<IAxis> notationAxisList = ((isRowsReordering && !tableManager.getTable().isInvertAxis()) || (!isRowsReordering && tableManager.getTable().isInvertAxis())) ? tableManager.getTable().getCurrentRowAxisProvider().getAxis() : tableManager.getTable().getCurrentColumnAxisProvider().getAxis(); final DataLayer tableBodyLayer = tableManager.getBodyLayerStack().getBodyDataLayer(); for (int index = 0; index < notationAxisList.size(); index++) { final IAxis currentAxis = notationAxisList.get(index); if (!tableManager.getTable().isInvertAxis()) { if (isRowsReordering) { final int axisHeight = tableBodyLayer.getRowHeightByPosition(index); final IntValueStyle value = (IntValueStyle) currentAxis.getNamedStyle(NattablestylePackage.eINSTANCE.getIntValueStyle(), NamedStyleConstants.AXIS_HEIGHT); if (null != value) { tableBodyLayer.setRowHeightByPosition(index, value.getIntValue(), false); } else if (axisHeight != DefaultSizeUtils.getDefaultCellHeight()) { tableBodyLayer.setRowHeightByPosition(index, DefaultSizeUtils.getDefaultCellHeight(), false); } } else { final int axisWidth = tableBodyLayer.getColumnWidthByPosition(index); final IntValueStyle value = (IntValueStyle) currentAxis.getNamedStyle(NattablestylePackage.eINSTANCE.getIntValueStyle(), NamedStyleConstants.AXIS_WIDTH); if (null != value) { tableBodyLayer.setColumnWidthByPosition(index, value.getIntValue(), false); } else if (axisWidth != DefaultSizeUtils.getDefaultCellWidth()) { tableBodyLayer.setColumnWidthByPosition(index, DefaultSizeUtils.getDefaultCellWidth(), false); } } } } }
Source:
<code>public void apply() throws ConnectException { try { if (!storage.exists(logFile)) { return; } FileStatus[] statuses = storage.listStatus(logFile); if (statuses.length != 1) { throw new ConnectException("Expected only one WAL file: " + logFile); } if (statuses[0].getLen() == 0) { log.warn("Skip empty WAL file: " + logFile); <START> return; <END> } acquireLease(); if (reader == null) { reader = new WALFile.Reader(conf, Reader.file(new Path(logFile))); } Map<WALEntry, WALEntry> entries = new HashMap<>(); WALEntry key = new WALEntry(); WALEntry value = new WALEntry(); while (reader.next(key, value)) { String keyName = key.getName(); if (keyName.equals(beginMarker)) { entries.clear(); } else if (keyName.equals(endMarker)) { for (Map.Entry<WALEntry, WALEntry> entry: entries.entrySet()) { String tempFile = entry.getKey().getName(); String committedFile = entry.getValue().getName(); if (!storage.exists(committedFile)) { storage.commit(tempFile, committedFile); } } } else { WALEntry mapKey = new WALEntry(key.getName()); WALEntry mapValue = new WALEntry(value.getName()); entries.put(mapKey, mapValue); } } } catch (IOException e) { throw new ConnectException(e); } }</code><technical_language>want acquire lease here? acquiring if for other reason _can_ this point? Otherwise, if zero bytes now, else continue write entries WAL</technical_language>

Target:
public void apply() throws ConnectException { try { if (!storage.exists(logFile)) { return; } acquireLease(); FileStatus[] statuses = storage.listStatus(logFile); if (statuses.length != 1) { throw new ConnectException("Expect only one WAL file: " + logFile); } if (statuses[0].getLen() == 0) { log.warn("Skip empty WAL file: " + logFile); return; } if (reader == null) { reader = new WALFile.Reader(conf, Reader.file(new Path(logFile))); } Map<WALEntry, WALEntry> entries = new HashMap<>(); WALEntry key = new WALEntry(); WALEntry value = new WALEntry(); while (reader.next(key, value)) { String keyName = key.getName(); if (keyName.equals(beginMarker)) { entries.clear(); } else if (keyName.equals(endMarker)) { for (Map.Entry<WALEntry, WALEntry> entry: entries.entrySet()) { String tempFile = entry.getKey().getName(); String committedFile = entry.getValue().getName(); if (!storage.exists(committedFile)) { storage.commit(tempFile, committedFile); } } } else { WALEntry mapKey = new WALEntry(key.getName()); WALEntry mapValue = new WALEntry(value.getName()); entries.put(mapKey, mapValue); } } } catch (IOException e) { throw new ConnectException(e); } }
Source:
<code>protected void executeCommand() { List<String> macsToRemove = getVmNicDao().getAllMacsByDataCenter(getStoragePool().getId()); removeNetworks(); List<StorageDomain> storageDomains = getStorageDomainDAO().getAllForStoragePool(getStoragePool().getId()); Collections.sort(storageDomains, new Comparator<StorageDomain>() { @Override public int compare(StorageDomain o1, StorageDomain o2) { return o1.getStorageDomainType().compareTo(o2.getStorageDomainType()); } }); if (storageDomains.size() > 0) { if (!getParameters().getForceDelete() && getAllRunningVdssInPool().size() > 0) { if(!regularRemoveStorageDomains(storageDomains)) { setSucceeded(false); return; } } else if (getParameters().getForceDelete()) { forceRemoveStorageDomains(storageDomains); } else { return; } } removeDataCenter(); getMacPoolForDataCenter().freeMacs(macsToRemove); <START> MacPoolPerDc.getInstance().removePool(getStoragePoolId()); <END> setSucceeded(true); }</code><technical_language>this line sense..</technical_language>

Target:
protected void executeCommand() { List<String> macsToRemove = getVmNicDao().getAllMacsByDataCenter(getStoragePool().getId()); removeNetworks(); List<StorageDomain> storageDomains = getStorageDomainDAO().getAllForStoragePool(getStoragePool().getId()); Collections.sort(storageDomains, new Comparator<StorageDomain>() { @Override public int compare(StorageDomain o1, StorageDomain o2) { return o1.getStorageDomainType().compareTo(o2.getStorageDomainType()); } }); if (storageDomains.size() > 0) { if (!getParameters().getForceDelete() && getAllRunningVdssInPool().size() > 0) { if(!regularRemoveStorageDomains(storageDomains)) { setSucceeded(false); return; } } else if (getParameters().getForceDelete()) { forceRemoveStorageDomains(storageDomains); } else { return; } } removeDataCenter(); getMacPool().freeMacs(macsToRemove); setSucceeded(true); }
Source:
<code>private IgniteCheckedException closeEx(boolean cancel, IgniteCheckedException err) throws IgniteCheckedException { if (!closed.compareAndSet(false, true)) return null; busyLock.writeLock(); try { if (log.isDebugEnabled()) log.debug("Closing data streamer [ldr=" + this + ", cancel=" + cancel + ']'); try { if (cancel) { cancelled = true; <START> flushAllThreadsBufs(); <END> for (Buffer buf : bufMappings.values()) buf.cancelAll(err); } else doFlush(); ctx.event().removeLocalEventListener(discoLsnr); ctx.io().removeMessageListener(topic); } catch (IgniteCheckedException | IgniteDataStreamerTimeoutException e) { fut.onDone(e); throw e; } long failed = failCntr.longValue(); if (failed > 0 && err == null) err = new IgniteCheckedException("Some of DataStreamer operations failed [failedCount=" + failed + "]"); fut.onDone(err); return err; } finally { busyLock.writeUnlock(); } }</code><technical_language>start another flushes closing *cancelling* operations including flushes</technical_language>

Target:
private IgniteCheckedException closeEx(boolean cancel, IgniteCheckedException err) throws IgniteCheckedException { if (!closed.compareAndSet(false, true)) return null; busyLock.writeLock(); try { if (log.isDebugEnabled()) log.debug("Closing data streamer [ldr=" + this + ", cancel=" + cancel + ']'); try { if (cancel) { cancelled = true; IgniteCheckedException cancellationErr = err; if (cancellationErr == null) cancellationErr = new IgniteCheckedException("Data streamer has been cancelled: " + DataStreamerImpl.this); for (ThreadBuffer buf : threadBufMap.values()) { GridFutureAdapter internalFut = (GridFutureAdapter)buf.getFut().internalFuture(); internalFut.onDone(cancellationErr); } for (Buffer buf : bufMappings.values()) buf.cancelAll(cancellationErr); } else doFlush(); ctx.event().removeLocalEventListener(discoLsnr); ctx.io().removeMessageListener(topic); } catch (IgniteCheckedException | IgniteDataStreamerTimeoutException e) { fut.onDone(e); throw e; } long failed = failCntr.longValue(); if (failed > 0 && err == null) err = new IgniteCheckedException("Some of DataStreamer operations failed [failedCount=" + failed + "]"); fut.onDone(err); return err; } finally { busyLock.writeUnlock(); } }
Source:
<code>public void testLifeCycleResetOnCopy() throws OperationException { String initialLifeCycleState = source.getCurrentLifeCycleState(); source.followTransition("approve"); source = session.saveDocument(source); txFeature.nextTransaction(); Map<String, Serializable> params = new HashMap<>(); params.put(TARGET_PROPERTY_KEY, COPY_PATH); params.put(NAME_PROPERTY_KEY, COPY_DOC_NAME); <START> params.put(CoreEventConstants.RESET_LIFECYCLE, Boolean.FALSE); <END> context.setInput(source); DocumentModel result = (DocumentModel) service.run(context, CopyDocument.ID, params); txFeature.nextTransaction(); result = session.getDocument(result.getRef()); assertEquals("approved", result.getCurrentLifeCycleState()); params = new HashMap<>(); params.put(TARGET_PROPERTY_KEY, COPY_PATH); params.put(NAME_PROPERTY_KEY, COPY_DOC_NAME); params.put(CoreEventConstants.RESET_LIFECYCLE, Boolean.TRUE); context.setInput(source); result = (DocumentModel) service.run(context, CopyDocument.ID, params); txFeature.nextTransaction(); result = session.getDocument(result.getRef()); assertEquals(initialLifeCycleState, result.getCurrentLifeCycleState()); }</code><technical_language>jira ticket is for 11.1 i guess, in this case Java 11 Map.of... create immutable object Map<String, Serializable> params = Map.of(TARGET_PROPERTY_KEY, COPY_PATH, NAME_PROPERTY_KEY, COPY_DOC_NAME, RESET_LIFECYCLE, false);</technical_language>

Target:
public void testLifeCycleResetOnCopy() throws OperationException { DocumentModel source = session.createDocumentModel(ROOT, "Source", FILE); source = session.createDocument(source); String initialLifeCycleState = source.getCurrentLifeCycleState(); source.followTransition("approve"); source = session.getDocument(source.getRef()); Map<String, Serializable> params = Map.of(TARGET_PROPERTY_KEY, ROOT, NAME_PROPERTY_KEY, COPY_DOC_NAME); try (OperationContext context = new OperationContext(session)) { context.setInput(source); DocumentModel result = (DocumentModel) automationService.run(context, CopyDocument.ID, params); txFeature.nextTransaction(); result = session.getDocument(result.getRef()); assertEquals("approved", result.getCurrentLifeCycleState()); } params = Map.of(TARGET_PROPERTY_KEY, ROOT, NAME_PROPERTY_KEY, COPY_DOC_NAME, "resetLifeCycle", true); try (OperationContext context = new OperationContext(session)) { context.setInput(source); DocumentModel result = (DocumentModel) automationService.run(context, CopyDocument.ID, params); txFeature.nextTransaction(); result = session.getDocument(result.getRef()); assertEquals(initialLifeCycleState, result.getCurrentLifeCycleState()); } }
Source:
<code>public boolean canBeCraftedBy(ItemStack stack) { <START> if (stack == null) return false; <END> return input.stackSize <= stack.stackSize && Utils.areSame(stack, input); }</code><technical_language>logically, important check if empty if null. sure</technical_language>

Target:
public boolean canBeCraftedBy(ItemStack stack) { if (stack.isEmpty()) return false; return input.getCount() <= stack.getCount() && Utils.areSame(stack, input); }
Source:
<code>public Account getAccountByName(String accountName) { Account primaryResult = primaryAccountService.getAccountByName(accountName); Account secondaryResult = secondaryAccountService.getAccountByName(accountName); <START> if (++getAccountRequestCount % 100 < config.samplingPercentageForGetAccountConsistencyCheck && primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountName ={}", accountName); accountServiceMetrics.getAccountDataInconsistencyCount.inc(); } <END> return primaryResult; }</code><technical_language>compareAccountMetadata method exhaustive check periodically. specific reason do a sampling check</technical_language>

Target:
public Account getAccountByName(String accountName) { Account primaryResult = primaryAccountService.getAccountByName(accountName); if (shouldCompare()) { Account secondaryResult = secondaryAccountService.getAccountByName(accountName); if (primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountName ={}", accountName); accountServiceMetrics.accountDataInconsistencyCount.inc(); } } return primaryResult; }
Source:
<code>protected void verifyCannotAccess(String... params) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, params); ActionResult result = c.executeAndPostProcess(); String classNameOfRedirectResult = RedirectResult.class.getName(); assertEquals(classNameOfRedirectResult, result.getClass().getName()); } catch (Exception e) { ignoreExpectedException(); } <START> ; <END> }</code><technical_language>extra ;</technical_language>

Target:
protected void verifyCannotAccess(String... params) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, params); ActionResult result = c.executeAndPostProcess(); String classNameOfRedirectResult = RedirectResult.class.getName(); assertEquals(classNameOfRedirectResult, result.getClass().getName()); } catch (Exception e) { ignoreExpectedException(); } }
Source:
<code>public boolean synchronize(DocumentFile event) throws Exception { <START> OutputStream fout = null; <END> try { fout = event.getPath().out(); xstream.toXML(event.getBody(), fout); return true; } catch (IllegalStateException e) { if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) LOGGER.severe(e.getLocalizedMessage()); throw e; } finally { IOUtils.closeQuietly(fout); } }</code><technical_language>Please convert tabs spaces. this converted a Java 7 try-with-resources</technical_language>

Target:
public boolean synchronize(DocumentFile event) throws Exception { try (OutputStream fout = event.getPath().out()) { xstream.toXML(event.getBody(), fout); return true; } catch (IllegalStateException e) { if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) LOGGER.severe(e.getLocalizedMessage()); throw e; } }
Source:
<code>public RegistryResponseType processRequest(AdhocQueryRequest msg, AssertionType assertion) { LOG.debug("Running through AdapterDeferredResponseOptionProxyWebServiceSecuredImpl"); RegistryResponseType response = null; try { if (msg == null) { throw new IllegalArgumentException("Request Message must be provided"); } response = (RegistryResponseType) invokeClientPort(getRequest(msg), assertion); } catch (final Exception ex) { <START> response = AdapterResponseHelper.createRegistryResponseTypeWithXdsQueryFailure(ERROR_MSG); <END> throw new ErrorEventException(ex, response, ERROR_MSG); } return response; }</code><technical_language>existing helper method do this</technical_language>

Target:
public RegistryResponseType processRequest(AdhocQueryRequest msg, AssertionType assertion) { LOG.debug("Running through AdapterDeferredResponseOptionProxyWebServiceSecuredImpl"); RegistryResponseType response = null; try { if (msg == null) { throw new IllegalArgumentException("Request Message must be provided"); } response = (RegistryResponseType) invokeClientPort(getRequest(msg), assertion); } catch (final Exception ex) { response = AdapterResponseHelper.createFailureWithMessage(ERROR_MSG); throw new ErrorEventException(ex, response, ERROR_MSG); } return response; }
Source:
<code>public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { stream.readLong(); } catch (IOException e) { <START> throw new InterruptedException("stream read error." + e); <END> } requestQueue.put(request); }</code><technical_language>nit: this a result of interrupt, I throwing a RuntimeException IllegalStateException a fit here</technical_language>

Target:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { stream.readLong(); } catch (IOException e) { throw new IllegalStateException("stream read error." + e); } requestQueue.put(request); }
Source:
<code>public boolean cancelOrder(String s) { <START> throw new UnsupportedOperationException("Orders Api Unnavailable at this time"); <END> }</code><technical_language>throw NotAvailableFromExchangeException</technical_language>

Target:
public boolean cancelOrder(String s) { throw new NotAvailableFromExchangeException(); }
Source:
<code>public void uncaughtException(Thread thread, Throwable ex) { try { String excInfo = ex.getMessage(); Tracker tracker = getTracker(); TrackHelper.track(mTrackMe).exception(ex).description(excInfo).fatal(true).with(tracker); <START> tracker.setOffline(); <END> tracker.dispatchBlocking(); } catch (Exception e) { Timber.tag(TAG).e(e, "Couldn't track uncaught exception"); } finally { if (getDefaultExceptionHandler() != null && getDefaultExceptionHandler() != this) { getDefaultExceptionHandler().uncaughtException(thread, ex); } } }</code><technical_language>This Tracker attempt transmission first? While calling setOffline track attempts taken, right</technical_language>

Target:
public void uncaughtException(Thread thread, Throwable ex) { try { String excInfo = ex.getMessage(); Tracker tracker = getTracker(); tracker.setDispatchMode(DispatchMode.EXCEPTION); TrackHelper.track(mTrackMe).exception(ex).description(excInfo).fatal(true).with(tracker); tracker.dispatchBlocking(); } catch (Exception e) { Timber.tag(TAG).e(e, "Couldn't track uncaught exception"); } finally { if (getDefaultExceptionHandler() != null && getDefaultExceptionHandler() != this) { getDefaultExceptionHandler().uncaughtException(thread, ex); } } }
Source:
<code>public Map<?, ListenableFuture<Void>> execute(final String group, final int count, final Template template, final Set<NodeMetadata> goodNodes, final Map<NodeMetadata, Exception> badNodes, final Multimap<NodeMetadata, CustomizationResponse> customizationResponses) { final DimensionDataCloudControlTemplateOptions templateOptions = template.getOptions() .as(DimensionDataCloudControlTemplateOptions.class); String networkDomainName = firstNonNull(templateOptions.getNetworkDomainName(), DEFAULT_NETWORK_DOMAIN_NAME); <START> String vlanName = firstNonNull(templateOptions.getVlanName(), DEFAULT_VLAN_NAME); <END> String datacenterId = template.getLocation().getId(); String networkDomainId = tryCreateOrGetExistingNetworkDomainId(datacenterId, networkDomainName); templateOptions.networkDomainId(networkDomainId); templateOptions.networkDomainName(networkDomainName); String vlanId = tryCreateOrGetExistingVlanId(templateOptions.getNetworkDomainId(), vlanName, templateOptions); templateOptions.vlanId(vlanId); templateOptions.vlanName(vlanName); return super.execute(group, count, template, goodNodes, badNodes, customizationResponses); }</code><technical_language>jclouds portable template options networks attribute (names, ids, sense for provider) users configure networks nodes connected to. Instead of providing options configure that, try accommodate current behavior networks option in a is understandable sense users</technical_language>

Target:
public Map<?, ListenableFuture<Void>> execute(final String group, final int count, final Template template, final Set<NodeMetadata> goodNodes, final Map<NodeMetadata, Exception> badNodes, final Multimap<NodeMetadata, CustomizationResponse> customizationResponses) { final DimensionDataCloudControlTemplateOptions templateOptions = template.getOptions() .as(DimensionDataCloudControlTemplateOptions.class); String networkDomainName = firstNonNull(templateOptions.getNetworkDomainName(), DEFAULT_NETWORK_DOMAIN_NAME); String vlanName = firstNonNull( templateOptions.getNetworks().isEmpty() ? null : templateOptions.getNetworks().iterator().next(), DEFAULT_VLAN_NAME); templateOptions.networkDomainName(networkDomainName); String networkDomainId = tryCreateOrGetExistingNetworkDomainId(template.getLocation().getId(), networkDomainName); String vlanId = tryCreateOrGetExistingVlanId(networkDomainId, vlanName, templateOptions); templateOptions.networks(vlanName); return super .execute(group, count, new TemplateWithNetworkIds(template, networkDomainId, vlanId), goodNodes, badNodes, customizationResponses); }
Source:
<code>public void testFindDonorsWithDonationIdentificationNumber_shouldFindDonorByDonationIdentificationNumber() { String donationIdentificationNumber = "1000001"; Donor donor = aDonor().withId(UUID.randomUUID()).build(); <START> List<DonorSummaryViewModel> donorViewModels = Arrays.asList(aDonorSummaryViewModel().withId(UUID.randomUUID()).build()); <END> when(donorRepository.findDonorByDonationIdentificationNumber(donationIdentificationNumber)).thenReturn(donor); when(donorViewModelFactory.createDonorSummaryViewModels(Arrays.asList(donor))).thenReturn(donorViewModels); when(generalConfigAccessorService.getBooleanValue(GeneralConfigConstants.DONOR_REGISTRATION_OPEN_BATCH_REQUIRED)).thenReturn(false); Map<String, Object> result = donorController.findDonors("", "", null, false, donationIdentificationNumber); assertThat((List<DonorSummaryViewModel>) result.get("donors"), equalTo(donorViewModels)); }</code><technical_language>values reference Donor, extracted a single local global variable</technical_language>

Target:
public void testFindDonorsWithDonationIdentificationNumber_shouldFindDonorByDonationIdentificationNumber() { String donationIdentificationNumber = "1000001"; UUID donorId = UUID.randomUUID(); Donor donor = aDonor().withId(donorId).build(); List<DonorSummaryViewModel> donorViewModels = Arrays.asList(aDonorSummaryViewModel().withId(donorId).build()); when(donorRepository.findDonorByDonationIdentificationNumber(donationIdentificationNumber)).thenReturn(donor); when(donorViewModelFactory.createDonorSummaryViewModels(Arrays.asList(donor))).thenReturn(donorViewModels); when(generalConfigAccessorService.getBooleanValue(GeneralConfigConstants.DONOR_REGISTRATION_OPEN_BATCH_REQUIRED)).thenReturn(false); Map<String, Object> result = donorController.findDonors("", "", null, false, donationIdentificationNumber); assertThat((List<DonorSummaryViewModel>) result.get("donors"), equalTo(donorViewModels)); }
Source:
<code>public final BeanMetaData<T> getCurrentBeanMetaData() { <START> if ( currentBeanType != null && currentBeanMetaData == null ) { <END> currentBeanMetaData = beanMetaDataManager.getBeanMetaData( currentBeanType ); } return currentBeanMetaData; }</code><technical_language>is done lazily? need in case</technical_language>

Target:
public final BeanMetaData<T> getCurrentBeanMetaData() { return currentBeanMetaData; }
Source:
<code>public Encounter createEncounter(String configName, DateTime encounterDatetime, String encounterType, String locationName, String patientUuid, String providerUuid, String visitUuid, Map<String, String> observations) { Location location = getLocationByName(configName, locationName); Patient patient = patientService.getPatientByUuid(configName, patientUuid); Provider provider = providerService.getProviderByUuid(configName, providerUuid); <START> Visit visit = visitService.getVisitByUuid(configName, visitUuid); <END> List<Observation> observationList = MapUtils.isNotEmpty(observations) ? convertObservationMapToList(observations, encounterDatetime) : null; EncounterType type = new EncounterType(encounterType); Encounter encounter = new Encounter(location, type, encounterDatetime.toDate(), patient, visit, Collections.singletonList(provider.getPerson()), observationList); return encounterService.createEncounter(configName, encounter); }</code><technical_language>visitUuid is optional field handle potential null</technical_language>

Target:
public Encounter createEncounter(String configName, DateTime encounterDatetime, String encounterType, String locationName, String patientUuid, String providerUuid, String visitUuid, Map<String, String> observations) { Location location = getLocationByName(configName, locationName); Patient patient = patientService.getPatientByUuid(configName, patientUuid); Provider provider = providerService.getProviderByUuid(configName, providerUuid); Visit visit = null; if (StringUtils.isNotEmpty(visitUuid)) { visit = visitService.getVisitByUuid(configName, visitUuid); } List<Observation> observationList = MapUtils.isNotEmpty(observations) ? convertObservationMapToList(observations, encounterDatetime) : null; EncounterType type = new EncounterType(encounterType); Encounter encounter = new Encounter(location, type, encounterDatetime.toDate(), patient, visit, Collections.singletonList(provider.getPerson()), observationList); return encounterService.createEncounter(configName, encounter); }
Source:
<code>public static Future<?> deleteFeedMediaOfItem(final Context context, final long mediaId) { if (UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItem(context, DBReader.getFeedMedia(mediaId).getItem(), false); } <START> return doDeleteFeedMediaOfItem(context, mediaId); <END> }</code><technical_language>main logic is run end: is counter-intuitive. More of a style issue: dodeleteFeedMediaOfItem() removeQueueItem() run asynchronously anyway</technical_language>

Target:
public static Future<?> deleteFeedMediaOfItem(final Context context, final long mediaId) { Future res = doDeleteFeedMediaOfItem(context, mediaId); if (UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItem(context, DBReader.getFeedMedia(mediaId).getItem(), false); } return res; }
Source:
<code>private Object nullInputEvaluator(final Collection<VariableReferenceExpression> nullVariables, Expression expression) { Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes( session, metadata, sqlParser, types, expression, emptyList(), WarningCollector.NOOP); return ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes) <START> .optimize(symbol -> nullVariables.stream() <END> .map(VariableReferenceExpression::getName) .collect(toImmutableSet()) .contains(symbol.getName()) ? null : symbol.toSymbolReference()); }</code><technical_language>Do want move conversion Collection<VariableReferenceExpression> lambda? need do conversion then</technical_language>

Target:
private Object nullInputEvaluator(final Collection<VariableReferenceExpression> nullVariables, Expression expression) { Set<String> nullVariableNames = nullVariables.stream() .map(VariableReferenceExpression::getName) .collect(toImmutableSet()); Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes( session, metadata, sqlParser, types, expression, emptyList(), WarningCollector.NOOP); return ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes) .optimize(symbol -> nullVariableNames.contains(symbol.getName()) ? null : symbol.toSymbolReference()); }
Source:
<code>public IarParser() { <START> super(Messages._Warnings_iar_ParserName(), <END> Messages._Warnings_iar_LinkName(), Messages._Warnings_iar_TrendName(), IAR_WARNING_PATTERN); }</code><technical_language>If remove true, method isLineInteresting is **not** invoked anymore</technical_language>

Target:
public IarParser() { super(Messages._Warnings_iar_ParserName(), Messages._Warnings_iar_LinkName(), Messages._Warnings_iar_TrendName(), IAR_WARNING_PATTERN, true); }
Source:
<code>public void setup() throws IOException, AuthenticationException { OzoneConfiguration conf = new OzoneConfiguration(); conf.setInt( ScmConfigKeys.OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT, <START> 1000); <END> storageDir = GenericTestUtils.getTempPath( TestDeadNodeHandler.class.getSimpleName() + UUID.randomUUID()); conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, storageDir); eventQueue = new EventQueue(); scm = HddsTestUtils.getScm(conf); nodeManager = (SCMNodeManager) scm.getScmNodeManager(); SCMPipelineManager manager = (SCMPipelineManager)scm.getPipelineManager(); PipelineProvider mockRatisProvider = new MockRatisPipelineProvider(nodeManager, manager.getStateManager(), conf); manager.setPipelineProvider(HddsProtos.ReplicationType.RATIS, mockRatisProvider); containerManager = scm.getContainerManager(); deadNodeHandler = new DeadNodeHandler(nodeManager, Mockito.mock(PipelineManager.class), containerManager); eventQueue.addHandler(SCMEvents.DEAD_NODE, deadNodeHandler); publisher = Mockito.mock(EventPublisher.class); nodeReportHandler = new NodeReportHandler(nodeManager); }</code><technical_language>0? Is able merge 3 lines 1 line exceed 80 chars line</technical_language>

Target:
public void setup() throws IOException, AuthenticationException { OzoneConfiguration conf = new OzoneConfiguration(); storageDir = GenericTestUtils.getTempPath( TestDeadNodeHandler.class.getSimpleName() + UUID.randomUUID()); conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, storageDir); conf.setInt(OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT, 0); eventQueue = new EventQueue(); scm = HddsTestUtils.getScm(conf); nodeManager = (SCMNodeManager) scm.getScmNodeManager(); SCMPipelineManager manager = (SCMPipelineManager)scm.getPipelineManager(); PipelineProvider mockRatisProvider = new MockRatisPipelineProvider(nodeManager, manager.getStateManager(), conf); manager.setPipelineProvider(HddsProtos.ReplicationType.RATIS, mockRatisProvider); containerManager = scm.getContainerManager(); deadNodeHandler = new DeadNodeHandler(nodeManager, Mockito.mock(PipelineManager.class), containerManager); eventQueue.addHandler(SCMEvents.DEAD_NODE, deadNodeHandler); publisher = Mockito.mock(EventPublisher.class); nodeReportHandler = new NodeReportHandler(nodeManager); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Descriptor that = (Descriptor) o; <START> return fullName.equals(that.fullName) && name.equals(that.name); <END> }</code><technical_language>include name in comparison? fullName enough</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Descriptor that = (Descriptor) o; return fullName.equals(that.fullName); }
Source:
<code>public AppPage clickAndConfirmWithoutWaitingForModalDisappearance(WebElement elementToClick) { click(elementToClick); waitForModalPresence(); WebElement okayButton = browser.driver.findElement(By.className("modal-btn-ok")); waitForElementToBeClickable(okayButton); click(okayButton); waitForPageToLoad(); <START> return this; <END> }</code><technical_language>Is necessary return page object</technical_language>

Target:
public void clickAndConfirmWithoutWaitingForModalDisappearance(WebElement elementToClick) { click(elementToClick); waitForModalPresence(); WebElement okayButton = browser.driver.findElement(By.className("modal-btn-ok")); waitForElementToBeClickable(okayButton); click(okayButton); }
Source:
<code>public void testValidateCustomPropertiesWhenCustomPropertiesFeatureIsNotSupported() throws Exception { Network networkA = createNetworkWithName("networkA"); NetworkAttachment networkAttachment = createNetworkAttachment(networkA); Map<String, String> customProperties = new HashMap<>(); customProperties.put("a", "b"); networkAttachment.setProperties(customProperties); VDS host = new VDS(); host.setVdsGroupCompatibilityVersion(Version.v3_4); HostSetupNetworksParameters params = new HostSetupNetworksParameters(host.getId()); params.setNetworkAttachments(Collections.singletonList(networkAttachment)); HostSetupNetworksValidator validator = spy(new HostSetupNetworksValidatorBuilder() .setHost(host) .setParams(params) .setNetworkBusinessEntityMap(new BusinessEntityMap<>(Collections.singletonList(networkA))) .build()); <START> doReturn(Collections.emptyList()).when(validator).translateErrorMessages(any(List.class)); <END> assertThat(validator.validateCustomProperties(null, Collections.<String, String> emptyMap(), Collections.<String, String> emptyMap()), failsWith(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_CUSTOM_PROPERTIES_NOT_SUPPORTED)); }</code><technical_language>this is redundant, code get point calls 'translateErrorMessages'</technical_language>

Target:
public void testValidateCustomPropertiesWhenCustomPropertiesFeatureIsNotSupported() throws Exception { Network networkA = createNetworkWithName("networkA"); NetworkAttachment networkAttachment = createNetworkAttachment(networkA); Map<String, String> customProperties = new HashMap<>(); customProperties.put("a", "b"); networkAttachment.setProperties(customProperties); VDS host = new VDS(); host.setVdsGroupCompatibilityVersion(Version.v3_4); HostSetupNetworksParameters params = new HostSetupNetworksParameters(host.getId()); params.setNetworkAttachments(Collections.singletonList(networkAttachment)); HostSetupNetworksValidator validator = spy(new HostSetupNetworksValidatorBuilder() .setHost(host) .setParams(params) .setNetworkBusinessEntityMap(new BusinessEntityMap<>(Collections.singletonList(networkA))) .build()); doReturn(Collections.emptyList()).when(validator).translateErrorMessages(any(List.class)); assertThat(validator.validateCustomProperties(null, Collections.<String, String> emptyMap(), Collections.<String, String> emptyMap()), failsWith(EngineMessage.ACTION_TYPE_FAILED_NETWORK_CUSTOM_PROPERTIES_NOT_SUPPORTED)); }
Source:
<code>public void testspaces() { StringBuffer buffer = new StringBuffer(); OracleDialect dialect = new OracleDialect(null); dialect.encodeColumnName("name with space",buffer); <START> assertEquals("NAME WITH SPACE", buffer.toString()); <END> }</code><technical_language>check for "\"NAME SPACE\""</technical_language>

Target:
public void testspaces() { StringBuffer buffer = new StringBuffer(); OracleDialect dialect = new OracleDialect(null); dialect.encodeColumnName("name with space",buffer); assertEquals("\"NAME WITH SPACE\"", buffer.toString()); }
Source:
<code>public void putAll(Map<? extends K, ? extends V> m) { <START> authzManager.checkPermission(CachePermission.WRITE); <END> delegate.putAll(m); }</code><technical_language>Guessing bulk again</technical_language>

Target:
public void putAll(Map<? extends K, ? extends V> m) { authzManager.checkPermission(AuthorizationPermission.WRITE); delegate.putAll(m); }
Source:
<code>public void onUpdate(U update) { synchronized (scheduleLock) { lastUpdate = update; if (schedule != null) { <START> schedule.cancel(false); <END> } schedule = getScheduledExecutorService().schedule(() -> getOriginal().onUpdate(lastUpdate), getPeriod(), getUnit()); } }</code><technical_language>Nit: typically a named (constant) variable instead of a 'magic boolean' this. parameter providing is mayInterruptIfRunning, a constant named DO_NOT_INTERRUPT_IF_RUNNING preference</technical_language>

Target:
public void onUpdate(U update) { lastUpdate = update; ScheduledFuture<?> schedule = scheduleRef.get(); if (schedule != null) { schedule.cancel(INTERRUPT_RUNNING_UPDATE); } scheduleRef.compareAndSet(schedule, getScheduledExecutorService().schedule( () -> getDelegateUpdateHandler().onUpdate(lastUpdate), getPeriod(), getUnit())); }