auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private <T> List<T> toListOfComplexType(DataTable dataTable, Class<T> itemType) { HierarchicalStreamReader reader = new ListOfComplexTypeReader(itemType, convertTopCellsToFieldNames(dataTable), dataTable.cells(1)); try { return Collections.unmodifiableList((List<T>) xStream.unmarshal(reader)); } catch (AbstractReflectionConverter.UnknownFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (AbstractReflectionConverter.DuplicateFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (ConversionException e) { if (e.getCause() instanceof NullPointerException) { throw new CucumberException(String.format("Can't assign null value to one of the primitive fields in %s. Please use boxed types.", e.get("class"))); } else { <START> throw e; <END> } } }</code><technical_language>e wrapped in a CucumberException in this case. construct throw new CucumberException(e); pretty common in code base</technical_language>

Target:
private <T> List<T> toListOfComplexType(DataTable dataTable, Class<T> itemType) { HierarchicalStreamReader reader = new ListOfComplexTypeReader(itemType, convertTopCellsToFieldNames(dataTable), dataTable.cells(1)); try { return Collections.unmodifiableList((List<T>) xStream.unmarshal(reader)); } catch (AbstractReflectionConverter.UnknownFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (AbstractReflectionConverter.DuplicateFieldException e) { throw new CucumberException(e.getShortMessage()); } catch (ConversionException e) { if (e.getCause() instanceof NullPointerException) { throw new CucumberException(String.format("Can't assign null value to one of the primitive fields in %s. Please use boxed types.", e.get("class"))); } else { throw new CucumberException(e); } } }
Source:
<code>public void setPrev(InternalResourceGroup prevNeighbour) { <START> prev = Optional.of(prevNeighbour); <END> }</code><technical_language>Do need synchronized</technical_language>

Target:
public void setPrev(InternalResourceGroup prevNeighbour) { synchronized (root) { if (prevNeighbour == null) { prev = Optional.empty(); } else { prev = Optional.of(prevNeighbour); } } }
Source:
<code>public ComparableTuple(final A a, final B b) { <START> super(a, b); <END> }</code><technical_language>This reject nulls want compareTo deal them</technical_language>

Target:
public ComparableTuple(final A a, final B b) { super(a, b); if (a == null || b == null) { throw new IllegalArgumentException("ComparableTuple's behavior is undefined when containing a null."); } }
Source:
<code>public int getTotalRevenueTimeForTrips (Collection<Trip> trips) { TIntList times = new TIntArrayList(); for (Trip trip : trips) { StopTime first; StopTime last; Spliterator<StopTime> interpolated = null; try { interpolated = feed.getInterpolatedStopTimesForTrip(trip.trip_id).spliterator(); } catch (GTFSFeed.FirstAndLastStopsDoNotHaveTimes firstAndLastStopsDoNotHaveTimes) { return -1; } first = StreamSupport.stream(interpolated, false) .findFirst() .orElse(null); last = StreamSupport.stream(interpolated, false) .reduce((a, b) -> b) .orElse(null); <START> int time = last.departure_time - first.arrival_time; <END> times.add(time); } return times.sum(); }</code><technical_language>this last.arrival_time - first.departure_time? I consider layover stops revenue time</technical_language>

Target:
public int getTotalRevenueTimeForTrips (Collection<Trip> trips) { TIntList times = new TIntArrayList(); for (Trip trip : trips) { StopTime first; StopTime last; Spliterator<StopTime> stopTimes = feed.getOrderedStopTimesForTrip(trip.trip_id).spliterator();; first = StreamSupport.stream(stopTimes, false) .findFirst() .orElse(null); last = StreamSupport.stream(stopTimes, false) .reduce((a, b) -> b) .orElse(null); int time = last.arrival_time - first.departure_time; times.add(time); } return times.sum(); }
Source:
<code>public void onLayoutEditorElementSelectEvent(@Observes LayoutEditorElementSelectEvent event) { <START> LayoutEditorElement element = event.getElement(); <END> if (element instanceof ComponentColumn) { ComponentColumn componentColumn = (ComponentColumn) element; LayoutComponent layoutComponent = componentColumn.getLayoutComponent(); LayoutDragComponent layoutDragComponent = componentColumn.getLayoutDragComponent(); if (layoutDragComponent instanceof EditorFieldLayoutComponent) { ((EditorFieldLayoutComponent) layoutDragComponent).addComponentParts(layoutComponent); } componentColumn.setupParts(); } }</code><technical_language>@jesuino more editor opened time, more editor get event time. Aparently this issue add a check right editor is porcessing layout component</technical_language>

Target:
public void onLayoutEditorElementSelectEvent(@Observes LayoutEditorElementSelectEvent event) { LayoutEditorElement element = event.getElement(); if (element instanceof ComponentColumn) { ComponentColumn componentColumn = (ComponentColumn) element; LayoutComponent layoutComponent = componentColumn.getLayoutComponent(); LayoutDragComponent layoutDragComponent = componentColumn.getLayoutDragComponent(); boolean containsElement = getFormDefinition().getLayoutTemplate().contains(layoutComponent); if (layoutDragComponent instanceof EditorFieldLayoutComponent && containsElement) { ((EditorFieldLayoutComponent) layoutDragComponent).addComponentParts(layoutComponent); } componentColumn.setupParts(); } }
Source:
<code>public static synchronized void reset(UserAccount account) { <START> if (account == null) { <END> account = SmartStoreSDKManager.getInstance().getUserAccountManager().getCurrentUser(); } if (account != null) { Set<String> keysToRemove = new HashSet<>(); for (String key : INSTANCES.keySet()) { if (key.startsWith(account.getUserId())) { keysToRemove.add(key); SyncManager syncManager = INSTANCES.get(key); syncManager.threadPool.shutdownNow(); } } INSTANCES.keySet().removeAll(keysToRemove); } }</code><technical_language>@narakim I do this. This API specifically expects a valid account instance. substituting currentUser if account passed in? null check though</technical_language>

Target:
public static synchronized void reset(UserAccount account) { if (account != null) { Set<String> keysToRemove = new HashSet<>(); for (String key : INSTANCES.keySet()) { if (key.startsWith(account.getUserId())) { keysToRemove.add(key); SyncManager syncManager = INSTANCES.get(key); syncManager.threadPool.shutdownNow(); } } INSTANCES.keySet().removeAll(keysToRemove); } }
Source:
<code>private void plugins(StringWriter w) { List<String> urls = Lists.newArrayList(); for (WebUiPlugin u : plugins) { <START> if (u.isExternalResource()) { <END> urls.add(u.getJavaScriptResourcePath()); } else { urls.add(String.format("plugins/%s/%s", u.getPluginName(), u.getJavaScriptResourcePath())); } } if (!urls.isEmpty()) { w.write(HPD_ID + ".plugins="); json(urls, w); w.write(";"); } }</code><technical_language>problem I this change is need plugins: * load jquery. do. * load code. work installing other plugin. I need permit plugin a list of additional external JavaScript source files loaded. added a List<String> getExternalJavaScriptUrls() iterated plugin's JS. Of some issues plugins load versions of JQuery a CDN. loading a CDN other loading private copy. namespaces collide, I guess protect that. Instead recommend plugins work Gerrit X.Y source JQuery CDN URL if need JQuery maybe</technical_language>

Target:
private void plugins(StringWriter w) { List<String> urls = Lists.newArrayList(); List<String> injectedDependencies = Lists.newArrayList(); for (WebUiPlugin u : plugins) { for(Map.Entry<String,String> dep : u.getJavaScriptDependencies().entrySet()) { String depName = dep.getKey(); if(injectedDependencies.contains(depName)) { log.info("Plugin dependency '" + depName + "' already injected. Skipping loading it a second time."); continue; } else { urls.add(dep.getValue()); injectedDependencies.add(depName); } } urls.add(String.format("plugins/%s/%s", u.getPluginName(), u.getJavaScriptResourcePath())); } if (!urls.isEmpty()) { w.write(HPD_ID + ".plugins="); json(urls, w); w.write(";"); } }
Source:
<code>public void createAndDropViewTest() throws DatabaseEngineException { test5Columns(); try { engine.dropView("VN"); } catch (final Throwable a) { <START> } <END> engine.executeUpdate( createView("VN").as(select(all()).from(table("TEST"))) ); engine.dropView("VN"); }</code><technical_language>I this this, is weird dropping view creating. If goal is assert throws exception, assert it, this is anything</technical_language>

Target:
public void createAndDropViewTest() throws DatabaseEngineException { test5Columns(); engine.executeUpdate( createView("VN").as(select(all()).from(table("TEST"))) ); engine.dropView("VN"); }
Source:
<code>public AbstractFindStoragePopupView(EventBus eventBus, boolean multiSelection) { super(eventBus); table = new EntityModelCellTable<>(multiSelection); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { return storage.getStorageName(); } }, constants.nameStorage()); table.addColumn(new AbstractEntityModelEnumColumn<StorageDomain, StorageDomainType>() { @Override protected StorageDomainType getEnum(StorageDomain storage) { return storage.getStorageDomainType(); } }, constants.typeStorage()); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { if (storage.getAvailableDiskSize() == null || storage.getAvailableDiskSize() < 1) { return messages.gigabytes("< 1"); } return <START> messages.gigabytes(storage.getAvailableDiskSize().toString()); <END> } }, constants.freeSpaceStorage()); }</code><technical_language>consider String.valueOf() circumvent NPE</technical_language>

Target:
public AbstractFindStoragePopupView(EventBus eventBus, boolean multiSelection) { super(eventBus); table = new EntityModelCellTable<>(multiSelection); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { return storage.getStorageName(); } }, constants.nameStorage()); table.addColumn(new AbstractEntityModelEnumColumn<StorageDomain, StorageDomainType>() { @Override protected StorageDomainType getEnum(StorageDomain storage) { return storage.getStorageDomainType(); } }, constants.typeStorage()); table.addColumn(new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { if (storage.getAvailableDiskSize() == null || storage.getAvailableDiskSize() < 1) { return messages.gigabytes("< 1"); } return messages.gigabytes(String.valueOf(storage.getAvailableDiskSize())); } }, constants.freeSpaceStorage()); }
Source:
<code>private void handleVdsLiveSnapshotFailure(VdcBLLException e) { <START> log.warn("Could not perform live snapshot due to error: {}. VM will still be configured to the new created snapshot", <END> ExceptionUtils.getMessage(e)); addCustomValue("SnapshotName", getSnapshotName()); addCustomValue("VmName", getVmName()); updateCallStackFromThrowable(e); AuditLogDirector.log(this, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }</code><technical_language>perform live snapshot due error, VM configured t new created snapshot: {}</technical_language>

Target:
private void handleVdsLiveSnapshotFailure(VdcBLLException e) { log.warn("Could not perform live snapshot due to error, VM will still be configured to the new created snapshot: {}", ExceptionUtils.getMessage(e)); addCustomValue("SnapshotName", getSnapshotName()); addCustomValue("VmName", getVmName()); updateCallStackFromThrowable(e); AuditLogDirector.log(this, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }
Source:
<code>public void start(final ServiceProvider serviceProvider) { <START> this.statisticsExecutor = serviceProvider.getService(ExecutionService.class).getScheduledExecutor(EhcacheStatisticsProvider.class.getSimpleName()); <END> this.cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); addManagementProvider(new EhcacheActionProvider(getConfiguration().getContext())); addManagementProvider(new EhcacheStatisticsProvider( getConfiguration().getContext(), getConfiguration().getConfigurationFor(EhcacheStatisticsProvider.class), statisticsExecutor)); addManagementProvider(new EhcacheStatisticCollectorProvider(getConfiguration().getContext())); this.cacheManager.registerListener(this); }</code><technical_language>Execution service usage wrong too</technical_language>

Target:
public void start(final ServiceProvider serviceProvider) { this.statisticsExecutor = serviceProvider.getService(ExecutionService.class).getScheduledExecutor(configuration.getStatisticsExecutorAlias()); this.cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); addManagementProvider(new EhcacheActionProvider(getConfiguration().getContext())); addManagementProvider(new EhcacheStatisticsProvider( getConfiguration().getContext(), getConfiguration().getConfigurationFor(EhcacheStatisticsProvider.class), statisticsExecutor)); addManagementProvider(new EhcacheStatisticCollectorProvider(getConfiguration().getContext())); this.cacheManager.registerListener(this); }
Source:
<code>public static Function<String, Integer> bits() { return new Function<String, Integer>() { @Override public Integer apply(String operatingSystemReferenceCode) { if (operatingSystemReferenceCode != null) { <START> return Integer.parseInt(getLast(Splitter.on("_").split(operatingSystemReferenceCode))); <END> } return null; } }; }</code><technical_language>If function is allowed return null, is Ints.tryParse instead of parseInt avoid throwing exception return null instead</technical_language>

Target:
public static Function<String, Integer> bits() { return new Function<String, Integer>() { @Override public Integer apply(String operatingSystemReferenceCode) { if (operatingSystemReferenceCode != null) { return Ints.tryParse(getLast(Splitter.on("_").split(operatingSystemReferenceCode))); } return null; } }; }
Source:
<code>protected static boolean checkForScheme( String[] initialSchemes, boolean relativeFilename, String vfsFilename, VariableSpace space, FileSystemOptions fsOptions ) throws IOException { for ( int i = 0; i < initialSchemes.length && relativeFilename; i++ ) { if ( vfsFilename.startsWith( initialSchemes[ i ] + ":" ) ) { relativeFilename = false; <START> fsOptions = buildFsOptions( space, fsOptions, vfsFilename, initialSchemes[ i ] ); <END> } } return relativeFilename; }</code><technical_language>I this for a couple minutes realize buildFsOptions is mutating fsOptions. .checkForScheme method return fsOptions do else it, a need assign</technical_language>

Target:
protected static boolean checkForScheme( String[] initialSchemes, boolean relativeFilename, String vfsFilename, VariableSpace space, FileSystemOptions fsOptions ) throws IOException { for ( int i = 0; i < initialSchemes.length && relativeFilename; i++ ) { if ( vfsFilename.startsWith( initialSchemes[ i ] + ":" ) ) { relativeFilename = false; fsOptionsForScheme = buildFsOptions( space, fsOptions, vfsFilename, initialSchemes[ i ] ); } } return relativeFilename; }
Source:
<code>public String getFamilyName() { <START> return "Delete range"; <END> }</code><technical_language>"Delete elements"</technical_language>

Target:
public String getFamilyName() { return "Delete elements"; }
Source:
<code>public void testExecuteSingleUploadBlobSizeTooLarge() { final long blobSize = ByteSizeUnit.GB.toBytes(randomIntBetween(6, 10)); final S3BlobStore blobStore = mock(S3BlobStore.class); final S3BlobContainer blobContainer = new S3BlobContainer(mock(BlobPath.class), blobStore); <START> final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> <END> blobContainer.executeSingleUpload(blobStore, randomAlphaOfLengthBetween(1, 10), null, blobSize)); assertEquals("Upload request size [" + blobSize + "] can't be larger than 5gb", e.getMessage()); }</code><technical_language>prefer increases readability imo</technical_language>

Target:
public void testExecuteSingleUploadBlobSizeTooLarge() throws IOException { final long blobSize = ByteSizeUnit.GB.toBytes(randomIntBetween(6, 10)); final S3BlobStore blobStore = mock(S3BlobStore.class); final S3BlobContainer blobContainer = new S3BlobContainer(mock(BlobPath.class), blobStore); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("can't be larger than 5gb")); blobContainer.executeSingleUpload(blobStore, randomAlphaOfLengthBetween(1, 10), null, blobSize); }
Source:
<code><START> public void run(final ThrowingRunnable<E> backgroundAction) { <END> Preconditions.checkNotNull(backgroundAction); final AtomicReference<Throwable> exceptionRef = new AtomicReference<>(); final WaitDialog waitDialog = new WaitDialog(null, waitDialogTitle); waitDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); final SwingWorker<Void, Void> worker = new SwingWorker<>() { @Override protected Void doInBackground() { try { backgroundAction.run(); } catch (final Throwable e) { exceptionRef.set(e); } return null; } @Override protected void done() { waitDialog.setVisible(false); waitDialog.dispose(); } }; SwingComponents.addWindowClosedListener(waitDialog, () -> worker.cancel(true)); worker.execute(); waitDialog.setVisible(true); try { @SuppressWarnings("unchecked") final @Nullable E exception = (E) exceptionRef.get(); if (exception != null) { exceptionHandler.accept(exception); } } catch (final ClassCastException e) { throw new AssertionError("unexpected checked exception", e); } }</code><technical_language>Method run 33 lines of code (exceeds 25 allowed). Consider refactoring</technical_language>

Target:
public void run(final ThrowingRunnable<E> backgroundAction) { Preconditions.checkNotNull(backgroundAction); final AtomicReference<Exception> exceptionRef = new AtomicReference<>(); final WaitDialog waitDialog = new WaitDialog(null, waitDialogTitle); waitDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); final SwingWorker<Void, Void> worker = buildBackgroundJobRunnerWithWaitDialog(backgroundAction, exceptionRef, waitDialog); SwingComponents.addWindowClosedListener(waitDialog, () -> worker.cancel(true)); worker.execute(); waitDialog.setVisible(true); try { @SuppressWarnings("unchecked") final @Nullable E exception = (E) exceptionRef.get(); if (exception != null) { exceptionHandler.accept(exception); } } catch (final ClassCastException e) { throw new IllegalStateException("Unexpected exception thrown", e); } }
Source:
<code>public void addAttachedArtifact( Artifact artifact ) throws DuplicateArtifactAttachmentException { <START> int index = attachedArtifacts.indexOf( artifact ); <END> if ( index > 0 ) { LOGGER.warn( "artifact already attached, remove previous instance and add again" ); attachedArtifacts.set( index, artifact ); } attachedArtifacts.add( artifact ); }</code><technical_language>This incur a complexity of O(n). sense work a set/map test</technical_language>

Target:
public void addAttachedArtifact( Artifact artifact ) throws DuplicateArtifactAttachmentException { int index = attachedArtifacts.indexOf( artifact ); if ( index >= 0 ) { LOGGER.warn( "artifact already attached, replace previous instance", artifact ); attachedArtifacts.set( index, artifact ); } else { attachedArtifacts.add( artifact ); } }
Source:
<code>public static String getQualifiedNameLabelWithSufficientDepth(final NamedElement namedElement, final Namespace model) { Assert.isNotNull(namedElement); StringBuffer label = new StringBuffer(); List<Package> importedPackages = null; if (null != model) { importedPackages = new ArrayList<Package>(model.getImportedPackages()); } List<Namespace> visitedNamespaces = new ArrayList<Namespace>(); Namespace currentNamespace = namedElement.getNamespace(); boolean rootFound = false; boolean modelIsTheRoot = false; while (currentNamespace != null && !rootFound) { visitedNamespaces.add(currentNamespace); <START> if (null != importedPackages || null != model) { <END> if (importedPackages.contains(currentNamespace) || currentNamespace == model) { rootFound = true; if (currentNamespace == model) { modelIsTheRoot = true; } } } Element owner = currentNamespace.getOwner(); while (null != owner && !(owner instanceof Namespace)) { owner = owner.getOwner(); } currentNamespace = owner != null ? (Namespace) owner : null; } int qualifiedNameDepht = visitedNamespaces.size() - 1 - (modelIsTheRoot ? 1 : 0); for (int i = qualifiedNameDepht; i >= 0; i--) { label.append(visitedNamespaces.get(i).getName()); label.append("::"); } label.append(namedElement.getName()); return label.toString(); }</code><technical_language>test 'null != importedPackages' (the manage 'importedPackages'</technical_language>

Target:
public static String getQualifiedNameLabelWithSufficientDepth(final NamedElement namedElement, final Namespace model) { Assert.isNotNull(namedElement); StringBuffer label = new StringBuffer(); List<Package> importedPackages = null; if (null != model) { importedPackages = new ArrayList<Package>(model.getImportedPackages()); } List<Namespace> visitedNamespaces = new ArrayList<Namespace>(); Namespace currentNamespace = namedElement.getNamespace(); boolean rootFound = false; boolean modelIsTheRoot = false; while (currentNamespace != null && !rootFound) { visitedNamespaces.add(currentNamespace); if (null != importedPackages && (importedPackages.contains(currentNamespace) || currentNamespace.equals(model))) { rootFound = true; if (currentNamespace.equals(model)) { modelIsTheRoot = true; } } Element owner = currentNamespace.getOwner(); while (null != owner && !(owner instanceof Namespace)) { owner = owner.getOwner(); } currentNamespace = owner != null ? (Namespace) owner : null; } int qualifiedNameDepht = visitedNamespaces.size() - 1 - (modelIsTheRoot ? 1 : 0); for (int i = qualifiedNameDepht; i >= 0; i--) { label.append(visitedNamespaces.get(i).getName()); label.append("::"); } label.append(namedElement.getName()); return label.toString(); }
Source:
<code>protected List<Dimension> getAllDimensions() { return getEntityDictionary().getAllFields(getEntityClass()).stream() .filter(field -> !AbstractMetric.isMetricField(field, getEntityClass(), getEntityDictionary())) <START> .filter(field -> getEntityDictionary().isRelation(getEntityClass(), field)) <END> .map(getEntityDictionary()::getEntityClass) .map(this::constructDimension) .collect( Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList ) ); }</code><technical_language>Dimensions restricted relationships. non-metric attributes</technical_language>

Target:
private Set<Dimension> getAllDimensions() { return getEntityDictionary().getAllFields(getEntityClass()).stream() .filter(field -> !isMetricField(field)) .map(field -> constructDimension(field, getEntityClass(), getEntityDictionary())) .collect( Collectors.collectingAndThen( Collectors.toSet(), Collections::unmodifiableSet ) ); }
Source:
<code>public void execute() { Long accountId = null; Account account = _accountService.getActiveAccountByName(accountName, domainId); if (account != null) { accountId = account.getAccountId(); } if (accountId == null) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "The account does not exists or has been removed/disabled"); } if (getValue() == null) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Please send a valid non-empty quota value"); } if (getQuotaEnforce() != null) { _quotaService.setLockAccount(accountId, getQuotaEnforce()); } if (getMinBalance() != null) { _quotaService.setMinBalance(accountId, getMinBalance()); } else { <START> _quotaService.setMinBalance(accountId, 0.2 * getValue()); <END> } final QuotaCreditsResponse response = _responseBuilder.addQuotaCredits(accountId, getDomainId(), getValue(), CallContext.current().getCallingUserId()); response.setResponseName(getCommandName()); response.setObjectName("quotacredits"); setResponseObject(response); }</code><technical_language>is multiplied 0.2</technical_language>

Target:
public void execute() { Long accountId = null; Account account = _accountService.getActiveAccountByName(accountName, domainId); if (account != null) { accountId = account.getAccountId(); } if (accountId == null) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "The account does not exists or has been removed/disabled"); } if (getValue() == null) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Please send a valid non-empty quota value"); } if (getQuotaEnforce() != null && getQuotaEnforce()) { _quotaService.setLockAccount(accountId, getQuotaEnforce()); } if (getMinBalance() != null) { _quotaService.setMinBalance(accountId, getMinBalance()); } else { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Please set a value for min balance"); } final QuotaCreditsResponse response = _responseBuilder.addQuotaCredits(accountId, getDomainId(), getValue(), CallContext.current().getCallingUserId()); response.setResponseName(getCommandName()); response.setObjectName("quotacredits"); setResponseObject(response); }
Source:
<code>public Path(Class<?> entityClass, EntityDictionary dictionary, String dotSeparatedPath) { pathElements = new ArrayList<>(); String[] fieldNames = dotSeparatedPath.split("\\."); Class<?> currentClass = entityClass; String currentClassName = dictionary.getJsonAliasFor(currentClass); for (String fieldName : fieldNames) { if (dictionary.isRelation(currentClass, fieldName)) { Class<?> relationClass = dictionary.getParameterizedType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, relationClass, fieldName)); currentClass = relationClass; currentClassName = fieldName; } else if (dictionary.isAttribute(currentClass, fieldName) || fieldName.equals(dictionary.getIdFieldName(entityClass))) { Class<?> attributeClass = dictionary.getType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, attributeClass, fieldName)); } else { <START> throw new InvalidValueException(entityClass.getSimpleName() <END> + " doesn't contain the field " + fieldName); } } }</code><technical_language>Is SimpleName want here? type name (which different)</technical_language>

Target:
public Path(Class<?> entityClass, EntityDictionary dictionary, String dotSeparatedPath) { pathElements = new ArrayList<>(); String[] fieldNames = dotSeparatedPath.split("\\."); Class<?> currentClass = entityClass; String currentClassName = dictionary.getJsonAliasFor(currentClass); for (String fieldName : fieldNames) { if (dictionary.isRelation(currentClass, fieldName)) { Class<?> relationClass = dictionary.getParameterizedType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, relationClass, fieldName)); currentClass = relationClass; currentClassName = fieldName; } else if (dictionary.isAttribute(currentClass, fieldName) || fieldName.equals(dictionary.getIdFieldName(entityClass))) { Class<?> attributeClass = dictionary.getType(currentClass, fieldName); pathElements.add(new PathElement(currentClass, currentClassName, attributeClass, fieldName)); } else { throw new InvalidValueException(dictionary.getJsonAliasFor(currentClass) + " doesn't contain the field " + fieldName); } } }
Source:
<code>public void delete(MessageWriteSet messageSetToDelete) throws StoreException { final Timer.Context context = metrics.deleteResponse.time(); checkStarted(); List<MessageInfo> infoList = messageSetToDelete.getMessageSetInfo(); for (MessageInfo info : infoList) { if (!index.exists(info.getStoreKey())) { throw new StoreException("Cannot delete id " + info.getStoreKey() + " since it is not present in the index.", StoreErrorCodes.ID_Not_Found); } } synchronized (lock) { try { messageSetToDelete.writeTo(log); logger.trace("Store : delete mark written to log", dataDir); for (MessageInfo info : infoList) { FileSpan fileSpan = new FileSpan(log.getLogEndOffset() - info.getSize(), log.getLogEndOffset()); index.markAsDeleted(info.getStoreKey(), fileSpan); } logger.trace("Store : delete has been marked in the index ", dataDir); } catch (IOException e) { <START> throw new StoreException("IO error while trying to delete blobs : " + e, StoreErrorCodes.IOError); <END> } finally { context.stop(); } } }</code><technical_language>pass exception e StoreException constructor</technical_language>

Target:
public void delete(MessageWriteSet messageSetToDelete) throws StoreException { final Timer.Context context = metrics.deleteResponse.time(); checkStarted(); List<MessageInfo> infoList = messageSetToDelete.getMessageSetInfo(); for (MessageInfo info : infoList) { if (!index.exists(info.getStoreKey())) { throw new StoreException("Cannot delete id " + info.getStoreKey() + " since it is not present in the index.", StoreErrorCodes.ID_Not_Found); } } synchronized (lock) { try { messageSetToDelete.writeTo(log); logger.trace("Store : delete mark written to log", dataDir); for (MessageInfo info : infoList) { FileSpan fileSpan = new FileSpan(log.getLogEndOffset() - info.getSize(), log.getLogEndOffset()); index.markAsDeleted(info.getStoreKey(), fileSpan); } logger.trace("Store : delete has been marked in the index ", dataDir); } catch (IOException e) { throw new StoreException("IO error while trying to delete blobs", e, StoreErrorCodes.IOError); } finally { context.stop(); } } }
Source:
<code>public Path getFilePath() { if(getFile() == null) { return null; } <START> return Paths.get(getFile().getAbsolutePath()); <END> }</code><technical_language>similary</technical_language>

Target:
public Path getFilePath() { if(getFile() == null) { return null; } return getFile().toPath(); }
Source:
<code>public String toString() <START> { <END> StringBuilder sb = new StringBuilder("ColumnarArray{"); sb.append("positionCount=").append(getPositionCount()).append(","); sb.append("offsetsOffset=").append(offsetsOffset).append(","); sb.append("nullCheckBlock=").append(nullCheckBlock.toString()).append(","); sb.append("elementsBlock=").append(elementsBlock.toString()).append(","); sb.append('}'); return sb.toString(); }</code><technical_language>@Override</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append("{"); sb.append("positionCount=").append(getPositionCount()).append(","); sb.append("offsetsOffset=").append(offsetsOffset).append(","); sb.append("nullCheckBlock=").append(nullCheckBlock.toString()).append(","); sb.append("elementsBlock=").append(elementsBlock.toString()).append(","); sb.append('}'); return sb.toString(); }
Source:
<code>public void actionPerformed(ActionEvent e) { boolean exists = false; for (ResourceAssignment ra: myAssignments) { <START> if (ra.getResource().equals(myHumanResource)){ <END> delete(ra); exists = true; break; } } if (!exists) { createAssignment(); myMutator.commit(); } }</code><technical_language>this checks if is delete create action. However, check created action. getValue(Action.SELECTED_KEY) return true if resource is assigned ( => this is delete action)</technical_language>

Target:
public void actionPerformed(ActionEvent e) { myUIFacade.getUndoManager().undoableEdit(getLocalizedDescription(), new Runnable() { @Override public void run() { if (getValue(Action.SELECTED_KEY) == Boolean.TRUE) { createAssignment(); } else { delete(myHumanResource); } } }); }
Source:
<code>private static Map<String, String> resourcesToOrderedMap(List<Resource> resources) { String cpus = null; String mem = null; String ports = null; for (Resource r : resources) { switch (r.getName()) { case "cpus": cpus = String.valueOf(r.getScalar().getValue()); break; <START> case "mem": <END> mem = String.valueOf(r.getScalar().getValue()); break; case "ports": ports = rangeListToString(r.getRanges().getRangeList()); break; default: new RuntimeException("Unrecognized resource " + r.getName()); break; } } Map<String, String> map = new LinkedHashMap<>(); if (cpus != null) { map.put("cpus", cpus); } if (mem != null) { map.put("mem", mem); } if (ports != null) { map.put("ports", ports); } return map; }</code><technical_language>wrong. implementation in storm-mesos is copying here. existing implementation is more generic. Please revert</technical_language>

Target:
private static Map<String, String> resourcesToOrderedMap(List<Resource> resources) { Map<String, String> map = new TreeMap<>(); for (Resource r : resources) { String name; String value = ""; if (r.hasRole()) { name = r.getName() + "(" + r.getRole() + ")"; } else { name = r.getName(); } switch (r.getType()) { case SCALAR: value = String.valueOf(r.getScalar().getValue()); break; case RANGES: value = rangesToString(r.getRanges()); break; case SET: value = setToString(r.getSet()); break; default: value = "Unrecognized Resource Type: `" + r.getType() + "'"; break; } map.put(name, value); } return map; }
Source:
<code>public void testGetAllOfTypeWithUnrepresentedType() { <START> List<VDS> result = dao.getAllOfType(VDSType.forValue(-1)); <END> assertIncorrectGetResult(result); }</code><technical_language>Sorry, null better: List<VDS> result = dao.getAllOfType(null);</technical_language>

Target:
public void testGetAllOfTypeWithUnrepresentedType() { List<VDS> result = dao.getAllOfType(null); assertIncorrectGetResult(result); }
Source:
<code>void applyTxMessage(TxMessage msg) throws Exception { verifyMetadata(msg.getMetadata()); if (msg.getMetadata().getSnapshotTimestamp() < srcGlobalSnapshot) { log.warn("Received message with snapshot is smaller than current snapshot {}.Ignore it", msg.getMetadata().getSnapshotTimestamp(), srcGlobalSnapshot); return; } <START> if (msg.getMetadata().getSnapshotTimestamp() > srcGlobalSnapshot) { <END> srcGlobalSnapshot = msg.getMetadata().getSnapshotTimestamp(); lastMsgTs = srcGlobalSnapshot; } if (msg.getMetadata().getEntryTimeStamp() <= lastMsgTs) { return; } if (msg.getMetadata().getPreviousEntryTimestamp() == lastMsgTs) { processMsg(msg); lastMsgTs = msg.getMetadata().getEntryTimeStamp(); processQue(); } if (msgQ.size() < MAX_MSG_QUE_SIZE) { msgQ.putIfAbsent(msg.getMetadata().getPreviousEntryTimestamp(), msg); } }</code><technical_language>this inequality work a NON_ADDRESS</technical_language>

Target:
void applyTxMessage(TxMessage msg) throws Exception { verifyMetadata(msg.getMetadata()); if (msg.getMetadata().getSnapshotTimestamp() < srcGlobalSnapshot) { log.warn("Received message with snapshot is smaller than current snapshot {}.Ignore it", msg.getMetadata().getSnapshotTimestamp(), srcGlobalSnapshot); return; } if (msg.getMetadata().getSnapshotTimestamp() > srcGlobalSnapshot) { srcGlobalSnapshot = msg.getMetadata().getSnapshotTimestamp(); lastMsgTs = srcGlobalSnapshot; cleanMsgQ(lastMsgTs); } if (msg.getMetadata().getEntryTimeStamp() <= lastMsgTs) { return; } if (msg.getMetadata().getPreviousEntryTimestamp() == lastMsgTs) { processMsg(msg); lastMsgTs = msg.getMetadata().getEntryTimeStamp(); processQueue(); } if (msgQ.size() < MAX_MSG_QUE_SIZE) { msgQ.putIfAbsent(msg.getMetadata().getPreviousEntryTimestamp(), msg); } else if (msgQ.get(msg.getMetadata().getPreviousEntryTimestamp()) != null) { log.warn("The message is out of order and the queue is full, will drop the message {}", msg.getMetadata()); } }
Source:
<code>private boolean validateCanAmendDisk() { DiskImage disk = (DiskImage) getNewDisk(); DiskValidator diskValidator = new DiskValidator(disk); <START> if (!validate(diskValidator.isDiskExists()) && <END> !validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, attachedVmsInfo))) { return false; } setStoragePoolId(disk.getStoragePoolId()); if (!validate(new StoragePoolValidator(getStoragePool()).isUp())) { return false; } if (!FeatureSupported.qcowCompatSupported(getStoragePool().getCompatibilityVersion())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_AMEND_NOT_SUPPORTED_BY_DC_VERSION, String.format("$dataCenterVersion %s", getStoragePool().getCompatibilityVersion().toString())); } if (disk.getVmEntityType().isTemplateType()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_AMEND_TEMPLATE_DISK); } setStorageDomainId(disk.getStorageIds().get(0)); StorageDomainValidator storageDomainValidator = new StorageDomainValidator(getStorageDomain()); if (!validate(storageDomainValidator.isDomainExistAndActive())) { return false; } DiskImagesValidator diskImagesValidator = new DiskImagesValidator(Collections.singletonList(disk)); return validate(diskImagesValidator.diskImagesNotIllegal()); }</code><technical_language>disk existence is validated, please remove</technical_language>

Target:
private boolean validateCanAmendDisk() { DiskImage disk = (DiskImage) getNewDisk(); setStoragePoolId(disk.getStoragePoolId()); if (!validate(new StoragePoolValidator(getStoragePool()).isUp())) { return false; } if (!FeatureSupported.qcowCompatSupported(getStoragePool().getCompatibilityVersion())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_AMEND_NOT_SUPPORTED_BY_DC_VERSION, String.format("$dataCenterVersion %s", getStoragePool().getCompatibilityVersion().toString())); } DiskImagesValidator diskImagesValidator = new DiskImagesValidator(Collections.singletonList(disk)); return validate(diskImagesValidator.diskImagesNotIllegal()); }
Source:
<code>@Test public void currentTraceContextIsVisibleInCallbackThread() throws Exception { Tracer tracer = httpTracing.tracing().tracer(); AtomicBoolean callbackHasTraceCtx = new AtomicBoolean(false); AtomicBoolean callbackCompleted = new AtomicBoolean(false); server.enqueue(new MockResponse()); closeClient(client); client = TracingHttpAsyncClientBuilder.create(httpTracing).build(); client.start(); ScopedSpan span = tracer.startScopedSpan("test"); <START> TraceContext expectedTraceCtx = span.context(); <END> try { getAsyncWithCallback(client, "/foo", new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse result) { callbackHasTraceCtx.set(expectedTraceCtx == currentTraceContext.get()); callbackCompleted.set(true); } @Override public void failed(Exception ex) { callbackCompleted.set(true); } @Override public void cancelled() { callbackCompleted.set(true); } }); } finally { span.finish(); } server.takeRequest(); waitForCallbackCompletion(callbackCompleted); takeSpan(); takeSpan(); assertTrue("Callback thread did not have expected trace ctx", callbackHasTraceCtx.get()); }</code><technical_language>I left (besides formatting) is simplify code remove wait loop. For example, if a countdownlatch instead of AtomicBoolean for callbackCompleted. search for references CountdownLatch in brave for similar examples. next, assertion in 117 occur main thread, is saving a boolean there. I is a bit cleaner atomic reference of TraceContext, do assertThat(callbackTraceContext.get()).isSameAs(expected) right countdown latch is done</technical_language>

Target:
@Test public void currentTraceContextIsVisibleInCallbackThread() throws Exception { CountDownLatch callbackCompleted = new CountDownLatch(1); AtomicReference callbackTraceContext = new AtomicReference(); Tracer tracer = httpTracing.tracing().tracer(); server.enqueue(new MockResponse()); ScopedSpan span = tracer.startScopedSpan("test"); TraceContext expectedTraceContext = span.context(); try { getAsyncWithCallback(client, "/foo", new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse result) { callbackTraceContext.set(currentTraceContext.get()); callbackCompleted.countDown(); } @Override public void failed(Exception ex) { callbackCompleted.countDown(); } @Override public void cancelled() { callbackCompleted.countDown(); } }); } finally { span.finish(); } server.takeRequest(); callbackCompleted.await(1, TimeUnit.SECONDS); assertThat(callbackTraceContext.get()).isSameAs(expectedTraceContext); takeSpan(); takeSpan(); }
Source:
<code>public void returnsEvents() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_OK, "{ \"id\": 1, \"events\": [ \"push\", \"pull_request\" ] }" ) ).start(this.resource.port()); try { MatcherAssert.assertThat( new RtHook( new ApacheRequest(container.home()), repo(), 1 ).json().getJsonArray("events") .stream() .map(JsonValue::toString) .map(event -> event.replace("\"", "")) .collect(Collectors.toList()), <START> Matchers.containsInAnyOrder("push", "pull_request") <END> ); } finally { container.stop(); } }</code><technical_language>@llorllale IsIterableContainingInAnyOrder</technical_language>

Target:
public void returnsEvents() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_OK, "{ \"id\": 1, \"events\": [ \"push\", \"pull_request\" ] }" ) ).start(this.resource.port()); try { MatcherAssert.assertThat( new RtHook( new ApacheRequest(container.home()), repo(), 1 ).json().getJsonArray("events") .stream() .map(JsonValue::toString) .map(event -> event.replace("\"", "")) .collect(Collectors.toList()), new IsIterableContainingInAnyOrder<>( Arrays.asList( new IsEqual<>("push"), new IsEqual<>("pull_request") ) ) ); } finally { container.stop(); } }
Source:
<code><START> public PublisherPack get(PublisherClient client) throws IOException, <END> ServiceNotAuthorizedException, ServiceNotEnabledException { if (closed) throw new IOException("Push already closed"); PublisherSession session = client.getSession(); Collection<SubscribeSpec> specs = session.getSubscriptions( repositoryName); if (specs.size() == 0) return null; Repository r = client.openRepository(repositoryName); try { synchronized (this) { for (PublisherPack p : packs) { if (p.match(specs)) return p; } PublisherPack newPack = generate( r, commands, specs, pushId + "-" + packs.size()); packs.add(newPack); return newPack; } } finally { r.close(); } }</code><technical_language>i need PublisherClient.... I a RepositoryFactory a PublisherSession here, RepositoryFactory a method open repository. is case RepositoryFactory PublisherSession itself</technical_language>

Target:
public PublisherPack get(PublisherClient client) throws IOException, ServiceNotAuthorizedException, ServiceNotEnabledException { if (closed) throw new IOException("Push already closed"); PublisherSession session = client.getSession(); Set<SubscribeSpec> specs = session.getSubscriptions(repositoryName); if (specs.size() == 0) return null; Repository r = client.openRepository(repositoryName); try { Generator packGenerator = null; synchronized (this) { for (Generator p : packs) { if (p.match(specs)) packGenerator = p; } if (packGenerator == null) { Set<ReceiveCommand> matchedUpdates = new HashSet< ReceiveCommand>(); for (ReceiveCommand rc : commands) { for (SubscribeSpec f : specs) { if (f.isMatch(rc.getRefName())) { matchedUpdates.add(rc); break; } } } if (matchedUpdates.size() == 0) return null; packGenerator = new Generator(r, matchedUpdates, specs, pushId + "-" + packs.size()); packs.add(packGenerator); } } return packGenerator.get(); } finally { r.close(); } }
Source:
<code><START> public String getSelinuxEnforceMode() { <END> if (selinuxEnforceMode == null) { } else if (selinuxEnforceMode.equals(SELinuxMode.DISABLED)) { return constants.disabled(); } else if (selinuxEnforceMode.equals(SELinuxMode.PERMISSIVE)) { return constants.permissive(); } else if (selinuxEnforceMode .equals(SELinuxMode.ENFORCING)) { return constants.enforcing(); } return constants.notAvailableLabel(); }</code><technical_language>This done EnumTranslator. For example, VmGeneralModel - > updateProperties(). In addition, add values LocalizedEnums.java LocalizedEnums.properties</technical_language>

Target:
public String getSelinuxEnforceMode() { return selinuxEnforceMode; }
Source:
<code>public static void main(String... args) throws IOException { try { final CommandLine commandLine = parseCli(args); if (commandLine.getArgList().size() == 1) { writePropertiesFile(commandLine.getArgList().get(0), commandLine.getOptionValue(OPTION_DEST_FILE)); } else { printUsage(); } } catch (ParseException ex) { <START> System.out.println(ex.getMessage()); <END> printUsage(); } catch (ANTLRException ex) { ex.printStackTrace(); } }</code><technical_language>exception passed up? need a build failure happen if exception occurs. console for a stack trace is a build failure</technical_language>

Target:
public static void main(String... args) throws CheckstyleException, ParseException { final CommandLine commandLine = parseCli(args); if (commandLine.getArgList().size() == 1) { try { writePropertiesFile(commandLine.getArgList().get(0), commandLine.getOptionValue(OPTION_DEST_FILE)); } catch (IOException ex) { throw new CheckstyleException("Failed to write properties file", ex); } } else { printUsage(); } }
Source:
<code>public static long getBaseSize(byte[] delta) { int p = 0; long baseLen = 0; int c, shift = 0; do { c = delta[p++] & 0xff; <START> baseLen |= ((c & 0x7f) << shift); <END> shift += 7; } while ((c & 0x80) != 0); return baseLen; }</code><technical_language>this explicit cast done prevent overflow, I if is safe remove this cast question for other occurrences</technical_language>

Target:
public static long getBaseSize(byte[] delta) { int p = 0; long baseLen = 0; int c, shift = 0; do { c = delta[p++] & 0xff; baseLen |= ((long) (c & 0x7f)) << shift; shift += 7; } while ((c & 0x80) != 0); return baseLen; }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) { Objects.requireNonNull(data); Objects.requireNonNull(data.getData()); Uri uri = data.getData(); try { Bitmap image = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); if (image != null) { displayMessage("Group image changed"); } else { <START> displayMessage("Could not retrieve image"); <END> } } catch (IOException e) { displayMessage("Could not retrieve image"); } } else if (requestCode == REQUEST_ADD_USERS && resultCode == RESULT_OK){ ArrayList<String> emailList = data.getStringArrayListExtra( AddUsersFromEntourageActivity.EMAIL_LIST_KEY); int count = 0; List<User> entourage = mUser.getEntourage(); for (int i = 0; i < emailList.size(); i++){ for (int j = 0; j < entourage.size(); j++){ if (entourage.get(j).getEmail().equals(emailList.get(i)) && !mGroup.containsUser(entourage.get(j))){ count++; } } } String text = count + " user(s) added to group"; displayMessage(text); } }</code><technical_language>Log</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) { Objects.requireNonNull(data); Objects.requireNonNull(data.getData()); Uri uri = data.getData(); try { Bitmap image = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); if (image != null) { String message = "Group image changed"; YieldsApplication.showToast(getApplicationContext(), message); } else { String message = "Could not retrieve image"; YieldsApplication.showToast(getApplicationContext(), message); } } catch (IOException e) { String message = "Could not retrieve image"; YieldsApplication.showToast(getApplicationContext(), message); Log.d(TAG, message); } } else if (requestCode == REQUEST_ADD_USERS && resultCode == RESULT_OK){ ArrayList<String> emailList = data.getStringArrayListExtra( AddUsersFromEntourageActivity.EMAIL_LIST_KEY); int count = 0; List<User> entourage = mUser.getEntourage(); for (int i = 0; i < emailList.size(); i++){ for (int j = 0; j < entourage.size(); j++){ if (entourage.get(j).getEmail().equals(emailList.get(i)) && !mGroup.containsUser(entourage.get(j))){ count++; } } } String message = count + " user(s) added to group"; YieldsApplication.showToast(getApplicationContext(), message); } }
Source:
<code>public String tensorflowName() { <START> return "MergeZZZ"; <END> }</code><technical_language>Is a solution this? throw a new NoOpNameFoundException? auto skips in place do that</technical_language>

Target:
public String tensorflowName() { throw new NoOpNameFoundException("This operation has no TF counterpart"); }