auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void delete_directory_parallel() throws Exception { GoogleCloudStorageFileSystemOptions gcsFsOptions = <START> newGcsFsOptions().setStatusParallelEnabled(true).build(); <END> TrackingHttpRequestInitializer gcsRequestsTracker = new TrackingHttpRequestInitializer(httpRequestsInitializer); GoogleCloudStorageFileSystem gcsFs = newGcsFs(gcsFsOptions, gcsRequestsTracker); String bucketName = gcsfsIHelper.sharedBucketName1; URI bucketUri = new URI("gs://" + bucketName + "/"); String dirObject = getTestResource(); gcsfsIHelper.createObjectsWithSubdirs(bucketName, dirObject + "/f1"); gcsFs.delete(bucketUri.resolve(dirObject + "/f1"), false); assertThat(gcsRequestsTracker.getAllRequestStrings()) .containsExactly( getRequestString(bucketName, dirObject + "/"), getRequestString(bucketName, dirObject + "/f1"), listRequestWithTrailingDelimiter( bucketName, dirObject + "/f1/", 1, null), deleteRequestString(bucketName, dirObject + "/f1", 1)); assertThat(gcsFs.exists(bucketUri.resolve(dirObject + "/f1"))).isFalse(); }</code><technical_language>is parallel=true reflected in verification? if set parallel=false, verification different</technical_language>

Target:
public void delete_directory_parallel() throws Exception { delete_directory( true); }
Source:
<code>public void start() { try { <START> restoreRestorableTasks(); <END> cleanupStaleAnnouncements(); registerRunListener(); registerLocationListener(); pathChildrenCache.start(); exec.submit( new Runnable() { @Override public void run() { mainLoop(); } } ); } catch (Exception e) { log.makeAlert(e, "Exception starting WorkerTaskMonitor") .emit(); throw Throwables.propagate(e); } }</code><technical_language>a lot here, suggest guarding start/stop a lock</technical_language>

Target:
public void start() { synchronized (lifecycleLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); started = true; try { restoreRestorableTasks(); cleanupStaleAnnouncements(); registerRunListener(); registerLocationListener(); pathChildrenCache.start(); exec.submit( new Runnable() { @Override public void run() { mainLoop(); } } ); log.info("Started WorkerTaskMonitor."); started = true; } catch (Exception e) { log.makeAlert(e, "Exception starting WorkerTaskMonitor") .emit(); throw Throwables.propagate(e); } } }
Source:
<code>public NumberValue divideBy( NumberValue numberValue ) { if ( numberValue instanceof IntegralValue ) { return dividedBy( numberValue.longValue() ); } else if ( numberValue instanceof FloatingPointValue ) { return dividedBy( numberValue.doubleValue() ); } else { <START> throw new IllegalArgumentException( "Cannot add " + numberValue ); <END> } }</code><technical_language>This error msg (and similar for times minus) copy paste artifacts</technical_language>

Target:
public NumberValue divideBy( NumberValue numberValue ) { if ( numberValue instanceof IntegralValue ) { return dividedBy( numberValue.longValue() ); } else if ( numberValue instanceof FloatingPointValue ) { return dividedBy( numberValue.doubleValue() ); } else { throw new IllegalArgumentException( "Cannot divide by " + numberValue ); } }
Source:
<code>public void sendMessage(){ String[] recipients = et_recipient.getText().toString().split(" "); for (int i=0; i<recipients.length; ++i){ recipients[i] = recipients[i].substring(1); } String subject = et_subject.getText().toString(); String content = et_message.getText().toString(); if(subject.length() == 0){ subject = getString(R.string.no_subject); } if(content.length() == 0){ subject = getString(R.string.no_content); } String content_type = Mail.PLAIN_TEXT; if (content.startsWith("<html>") && content.endsWith("</html>")) content_type = Mail.HTML_TEXT; SendMailData data = new SendMailData(recipients, subject, content, content_type); if (isAnswer){ <START> if (attachments.size()>0) <END> HandlerAPIConnect.answerMailWithAttachment(data, mail.handler_id, this, attachments); else HandlerAPIConnect.answerMail(data, mail.handler_id, this); } else { if (attachments.size()>0) HandlerAPIConnect.sendMailWithAttachment(data, this, attachments); else HandlerAPIConnect.sendMail(data, this); } finish(); }</code><technical_language>List Arraylist methods built in : if(!attachments.isEmpty())</technical_language>

Target:
public void sendMessage(){ String[] recipients = et_recipient.getText().toString().split(" "); for (int i=0; i<recipients.length; ++i){ recipients[i] = recipients[i].substring(1); } String subject = et_subject.getText().toString(); String content = et_message.getText().toString(); if(TextUtils.isEmpty(subject)){ subject = getString(R.string.no_subject); } if(TextUtils.isEmpty(content)){ subject = getString(R.string.no_content); } String content_type = Mail.PLAIN_TEXT; if (content.startsWith("<html>") && content.endsWith("</html>")) content_type = Mail.HTML_TEXT; SendMailData data = new SendMailData(recipients, subject, content, content_type); if (isAnswer){ if (!attachments.isEmpty()) HandlerAPIConnect.answerMailWithAttachment(data, mail.handler_id, this, attachments); else HandlerAPIConnect.answerMail(data, mail.handler_id, this); } else { if (!attachments.isEmpty()) HandlerAPIConnect.sendMailWithAttachment(data, this, attachments); else HandlerAPIConnect.sendMail(data, this); } finish(); }
Source:
<code>protected Connection tryConnectionInsideLock() throws JMSException { if (m_closing) { throw new ProcessingException("closed"); } if (m_impl != null) { return m_impl; } final Connection c = m_connectionFunction.create(); if (m_connectionRetryCount > 0) { c.setExceptionListener(new ExceptionListener() { @Override public void onException(JMSException e1) { if (m_connectionRetryCount > 0) { LOG.info("JMS connection dropped with <START> '{}'; starting <END> failover", e1); invalidate(e1); } else { BEANS.get(MomExceptionHandler.class).handle(e1); } } }); } m_impl = c; return m_impl; }</code><technical_language>This placeholder is is log argument in fact is exception. empty placeholder exception details (message, stacktrace) is logged end of log message</technical_language>

Target:
protected Connection tryConnectionInsideLock() throws JMSException { if (m_closing) { throw new ProcessingException("closed"); } if (m_impl != null) { return m_impl; } final Connection c = m_connectionFunction.create(); if (m_connectionRetryCount > 0) { c.setExceptionListener(new ExceptionListener() { @Override public void onException(JMSException e1) { if (m_connectionRetryCount > 0) { LOG.info("JMS connection dropped with '{}'; starting failover", e1.getMessage()); invalidate(e1); } else { BEANS.get(MomExceptionHandler.class).handle(e1); } } }); } m_impl = c; return m_impl; }
Source:
<code>public void setupRoutes() { path(controllerBasePath(), () -> { before("", mimeType, this::setContentType); before("/*", mimeType, this::setContentType); before("", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", mimeType, this::index); get(Routes.Packages.SHOW, mimeType, this::show); post("", mimeType, this::create); put(Routes.Packages.SHOW, mimeType, this::update); <START> delete(Routes.Packages.SHOW, mimeType, this::remove); <END> }); }</code><technical_language>rename SHOW ID PACKAGE_ID something</technical_language>

Target:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", mimeType, this::setContentType); before("/*", mimeType, this::setContentType); before("", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", mimeType, this::index); get(Routes.Packages.PACKAGE_ID, mimeType, this::show); post("", mimeType, this::create); put(Routes.Packages.PACKAGE_ID, mimeType, this::update); delete(Routes.Packages.PACKAGE_ID, mimeType, this::remove); }); }
Source:
<code>public void insertCard(@NonNull Card card, int position) { cards.add(position, card); <START> removeHiddenCard(card); <END> if (updateListener != null) { updateListener.update(cards); } }</code><technical_language>remove hidden cards here</technical_language>

Target:
public void insertCard(@NonNull Card card, int position) { cards.add(position, card); unHideCard(card); if (updateListener != null) { updateListener.update(cards); } }
Source:
<code>private void recoverSortMenuState(Menu menu){ if(menu != null) { <START> menu.findItem(R.id.action_sort_descending).setChecked(!com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); <END> switch (com.owncloud.android.db.PreferenceManager.getSortOrder(this,FileStorageUtils.FILE_DISPLAY_SORT)) { case FileStorageUtils.SORT_NAME: menu.findItem(R.id.action_sort_by_name).setChecked(true); sortByName(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_SIZE: menu.findItem(R.id.action_sort_by_size).setChecked(true); sortBySize(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_DATE: menu.findItem(R.id.action_sort_by_date).setChecked(true); sortByDate(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; } } }</code><technical_language>This line is huge, remember a limit of 120 characters</technical_language>

Target:
private void recoverSortMenuState(Menu menu) { if (menu != null) { menu.findItem(R.id.action_sort_descending).setChecked( !PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); switch (PreferenceManager.getSortOrder(this, FileStorageUtils.FILE_DISPLAY_SORT)) { case FileStorageUtils.SORT_NAME: menu.findItem(R.id.action_sort_by_name).setChecked(true); sortByName(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_SIZE: menu.findItem(R.id.action_sort_by_size).setChecked(true); sortBySize(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_DATE: menu.findItem(R.id.action_sort_by_date).setChecked(true); sortByDate(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; } } }
Source:
<code>public ComplexMetricExtractor getExtractor() { return new ComplexMetricExtractor() { @Override public Class<HyperLogLogCollector> extractedClass() { return HyperLogLogCollector.class; } @Override public HyperLogLogCollector extractValue(InputRow inputRow, String metricName) { Object rawValue = inputRow.getRaw(metricName); if (rawValue instanceof HyperLogLogCollector) { return (HyperLogLogCollector) rawValue; } else { HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); List<String> dimValues = inputRow.getDimension(metricName); if (dimValues == null) { return collector; } for (String dimensionValue : dimValues) { <START> collector.add(dimensionValue); <END> } return collector; } } }; }</code><technical_language>motivation removing hashFn parameter of serde? collector is supposed hash-function agnostic, is serde applied handing hashedValue</technical_language>

Target:
public ComplexMetricExtractor getExtractor() { return new ComplexMetricExtractor() { @Override public Class<HyperLogLogCollector> extractedClass() { return HyperLogLogCollector.class; } @Override public HyperLogLogCollector extractValue(InputRow inputRow, String metricName) { Object rawValue = inputRow.getRaw(metricName); if (rawValue instanceof HyperLogLogCollector) { return (HyperLogLogCollector) rawValue; } else { HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); List<String> dimValues = inputRow.getDimension(metricName); if (dimValues == null) { return collector; } for (String dimensionValue : dimValues) { collector.add(hyperLogLogHash.hash(dimensionValue)); } return collector; } } }; }
Source:
<code>public List<SourceWithKeys> splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) throws Exception { List<SourceWithKeys> newSplits = split(estimatedSize, desiredBundleSizeBytes, startKey, stopKey); if (LOG.isDebugEnabled()) { <START> LOG.debug("Splitting split with into {}", this, newSplits); <END> } return newSplits; }</code><technical_language>Splitting split {}</technical_language>

Target:
public List<SourceWithKeys> splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) throws Exception { List<SourceWithKeys> newSplits = split(estimatedSize, desiredBundleSizeBytes, startKey, stopKey); if (LOG.isDebugEnabled()) { LOG.debug("Splitting split into {}", this, newSplits); } return newSplits; }
Source:
<code>public String getHref() { <START> return "/pools/" + getId(); <END> }</code><technical_language>For this value, do closer ProductDTO does. Leave building of URL actual entity implementations of floating around. update Pool nicer generating generate a valid URL (see Product for example)</technical_language>

Target:
public String getHref() { return this.getId() != null ? String.format("/pools/%s", this.getId()) : null; }
Source:
<code>public ItemsFilter(SearchPattern searchPattern) { patternMatcher = searchPattern; String stringPattern = ""; if (pattern != null && !pattern.getText().equals("*")) { stringPattern = pattern.getText(); } <START> if (stringPattern.indexOf("*") != 0) { END> stringPattern = "*" + stringPattern; } patternMatcher.setPattern(stringPattern); }</code><technical_language>original PDE bug report for correct of implementing this</technical_language>

Target:
public ItemsFilter(SearchPattern searchPattern) { patternMatcher = searchPattern; String stringPattern = ""; if (pattern != null && !pattern.getText().equals("*")) { stringPattern = pattern.getText(); } if (stringPattern.indexOf("*") != 0 && stringPattern.indexOf("?") != 0 && stringPattern.indexOf(".") != 0) { stringPattern = "*" + stringPattern; } patternMatcher.setPattern(stringPattern); }
Source:
<code>public Location createLocation(Location location) { org.openmrs.Location omrsLocation=null; List<String> errors = new ArrayList<String>(); omrsLocation = FHIRLocationUtil.generateOpenMRSLocation(location, errors); if (!errors.isEmpty()) { <START> StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to following issues \n"); <END> for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } omrsLocation=Context.getLocationService().saveLocation(omrsLocation); return FHIRLocationUtil.generateLocation(omrsLocation); }</code><technical_language>"The request processed due issues"</technical_language>

Target:
public Location createLocation(Location location) { org.openmrs.Location omrsLocation=null; List<String> errors = new ArrayList<String>(); omrsLocation = FHIRLocationUtil.generateOpenMRSLocation(location, errors); if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } omrsLocation=Context.getLocationService().saveLocation(omrsLocation); return FHIRLocationUtil.generateLocation(omrsLocation); }
Source:
<code>public GatewayNotification processNotification(final String notification, final String pluginName, final Iterable<PluginProperty> properties, final CallContext callContext) throws PaymentApiException { return dispatchWithExceptionHandling(null, pluginName, new Callable<PluginDispatcherReturnType<GatewayNotification>>() { @Override public PluginDispatcherReturnType<GatewayNotification> call() throws PaymentApiException { try { <START> final PaymentPluginApi plugin = getPaymentPluginApi(pluginName); <END> final GatewayNotification result = plugin.processNotification(notification, properties, callContext); return PluginDispatcher.createPluginDispatcherReturnType(result == null ? new DefaultNoOpGatewayNotification() : result); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_EXCEPTION, e.getErrorMessage()); } } }, paymentPluginNotificationDispatcher); }</code><technical_language>Nit: a reason move try block (considering this throws a PaymentApiException catch PaymentPluginApiException</technical_language>

Target:
public GatewayNotification processNotification(final String notification, final String pluginName, final Iterable<PluginProperty> properties, final CallContext callContext) throws PaymentApiException { return dispatchWithExceptionHandling(null, pluginName, new Callable<PluginDispatcherReturnType<GatewayNotification>>() { @Override public PluginDispatcherReturnType<GatewayNotification> call() throws PaymentApiException { final PaymentPluginApi plugin = getPaymentPluginApi(pluginName); try { final GatewayNotification result = plugin.processNotification(notification, properties, callContext); return PluginDispatcher.createPluginDispatcherReturnType(result == null ? new DefaultNoOpGatewayNotification() : result); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_EXCEPTION, e.getErrorMessage()); } } }, paymentPluginNotificationDispatcher); }
Source:
<code>protected void dealWithStringtoStringMap(U field) { Map<String, String> updateDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) updateDocument.getFieldValue(field)); Map<String, String> actualDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) actualDocument.getFieldValue(field)); if (updateDocumentMap.equals(actualDocumentMap)) { return; } Map<String,String> addedMap = updateDocumentMap; Map<String, String> deletedMap = actualDocumentMap; Set<String> commonKeys = Sets.intersection(updateDocumentMap.keySet(), actualDocumentMap.keySet()); for(String id : commonKeys) { String actual = actualDocumentMap.get(id); String update = updateDocumentMap.get(id); <START> if(! actual.equals(update)) { <END> addedMap.put(id, update); deletedMap.put(id, actual); } } documentAdditions.setFieldValue(field, addedMap); documentDeletions.setFieldValue(field, deletedMap); }</code><technical_language>a good candidate for a NullPointerException</technical_language>

Target:
protected void dealWithStringtoStringMap(U field) { Map<String, String> updateDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) updateDocument.getFieldValue(field)); Map<String, String> actualDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) actualDocument.getFieldValue(field)); if (updateDocumentMap.equals(actualDocumentMap)) { return; } Map<String,String> addedMap = updateDocumentMap; Map<String, String> deletedMap = actualDocumentMap; Set<String> commonKeys = Sets.intersection(updateDocumentMap.keySet(), actualDocumentMap.keySet()); for(String id : commonKeys) { String actual = actualDocumentMap.get(id); String update = updateDocumentMap.get(id); if(! Objects.equals(update, actual)) { addedMap.put(id, update); deletedMap.put(id, actual); } } documentAdditions.setFieldValue(field, addedMap); documentDeletions.setFieldValue(field, deletedMap); }
Source:
<code>public void setRatingChange(PlayerStats playerStats) { if (playerStats.getAfterMean() == null || playerStats.getAfterDeviation() == null) { return; } int newRating = RatingUtil.getRating(playerStats.getAfterMean(), playerStats.getAfterDeviation()); int oldRating = RatingUtil.getRating(playerStats.getBeforeMean(), playerStats.getBeforeDeviation()); int ratingChane = newRating - oldRating; ratingChangLabelRoot.setText(i18n.numberWithSign(ratingChane)); <START> ratingChangLabelRoot.pseudoClassStateChanged(ratingChane < 0 ? NEGATIVE : POSITIVE, true); <END> ratingChangLabelRoot.setVisible(true); }</code><technical_language>ratingChane -> ratingChange</technical_language>

Target:
public void setRatingChange(PlayerStats playerStats) { if (playerStats.getAfterMean() == null || playerStats.getAfterDeviation() == null) { return; } int newRating = RatingUtil.getRating(playerStats.getAfterMean(), playerStats.getAfterDeviation()); int oldRating = RatingUtil.getRating(playerStats.getBeforeMean(), playerStats.getBeforeDeviation()); int ratingChange = newRating - oldRating; ratingChangLabelRoot.setText(i18n.numberWithSign(ratingChange)); ratingChangLabelRoot.pseudoClassStateChanged(ratingChange < 0 ? NEGATIVE : POSITIVE, true); ratingChangLabelRoot.setVisible(true); }
Source:
<code>protected void populateProjects() { Util.PROJECT_SVC.visibleProjects( <START> new ScreenLoadCallback<List<Project>>(this) { <END> @Override protected void preDisplay(final List<Project> result) { projectsTab.display(result); if (firstPopupLoad) { firstPopupLoad = false; displayPopup(); } } }); }</code><technical_language>a GerritCallback a ScreenLoadCallback. need trigger displaying this screen display project list back, need capture result onSuccess continue popup display</technical_language>

Target:
protected void populateProjects() { Util.PROJECT_SVC.visibleProjects( new GerritCallback<List<Project>>() { @Override public void onSuccess(final List<Project> result) { projectsTab.display(result); if (firstPopupLoad) { firstPopupLoad = false; displayPopup(); } } }); }
Source:
<code>protected AbstractResourceWrapper<?, ?> createNewWrapper(Collection<IResource> resources, IResource r) { AbstractResourceWrapper<?, ?> newWrapper; if (r instanceof IService) { ServiceWrapper newService = new ServiceWrapper(ProjectWrapper.this, (IService) r); Collection<IResource> relatedResources = ServiceResourceMapper.computeRelatedResources((IService) r, resources); newService.initWithResources(relatedResources); newWrapper = newService; } else if ((ResourceKind.DEPLOYMENT_CONFIG.equals(r.getKind()) || (ResourceKind.REPLICATION_CONTROLLER.equals(r.getKind()) && !r.isAnnotatedWith(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME))) && ServiceResourceMapper.getServices((IReplicationController) r, resources).isEmpty()) { ReplicationControllerWrapper dcWrapper = new ReplicationControllerWrapper(this, (IReplicationController) r); <START> Collection<IResource> relatedResource = <END> ResourceKind.DEPLOYMENT_CONFIG.equals(r.getKind())?ServiceResourceMapper.computeRelatedResources((IDeploymentConfig) r, resources) :ServiceResourceMapper.computeRelatedResources((IReplicationController) r, resources); dcWrapper.initWithResources(relatedResource); newWrapper = dcWrapper; } else { newWrapper = new ResourceWrapper(ProjectWrapper.this, r); } return newWrapper; }</code><technical_language>Code lines [83](<LINK_1> [62](<LINK_0> separated in a method. please, format it, hard read</technical_language>

Target:
protected AbstractResourceWrapper<?, ?> createNewWrapper(Collection<IResource> resources, IResource r) { AbstractResourceWrapper<?, ?> newWrapper; if (r instanceof IService) { ServiceWrapper newService = new ServiceWrapper(ProjectWrapper.this, (IService) r); Collection<IResource> relatedResources = ServiceResourceMapper.computeRelatedResources((IService) r, resources); newService.initWithResources(relatedResources); newWrapper = newService; } else if ((ResourceKind.DEPLOYMENT_CONFIG.equals(r.getKind()) || (ResourceKind.REPLICATION_CONTROLLER.equals(r.getKind()) && !r.isAnnotatedWith(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME))) && ServiceResourceMapper.getServices((IReplicationController) r, resources).isEmpty()) { ReplicationControllerWrapper dcWrapper = new ReplicationControllerWrapper(this, (IReplicationController) r); Collection<IResource> relatedResource = getRelatedResources(resources, dcWrapper); dcWrapper.initWithResources(relatedResource); newWrapper = dcWrapper; } else { newWrapper = new ResourceWrapper(ProjectWrapper.this, r); } return newWrapper; }
Source:
<code>pathname -> pathname.isFile() && pathname.getName().startsWith(RESERVE_FILE_PREFIX); static final FileFilter FILE_SIZE_DIR_FILTER = pathname -> pathname.isDirectory() && getFileSizeForDirName(pathname.getName()) != null; private final boolean enablePooling; private final File reserveDir; private final File swapReserveDir; private final long requiredSwapSegmentsPerSize; private final StorageManagerMetrics metrics; private final Map<String, ReserveFileMap> storeReserveFiles = new HashMap<>(); private final ReserveFileMap swapReserveFiles = new ReserveFileMap(); private PoolState poolState = PoolState.NOT_INVENTORIED; private Exception inventoryException = null; DiskSpaceAllocator(boolean enablePooling, File reserveDir, long requiredSwapSegmentsPerSize, StorageManagerMetrics metrics) { this.enablePooling = enablePooling; this.reserveDir = reserveDir; swapReserveDir = new File(reserveDir, SWAP_DIR_NAME); <START> this.requiredSwapSegmentsPerSize = requiredSwapSegmentsPerSize; <END> this.metrics = metrics; try { if (enablePooling) { prepareDirectory(reserveDir); prepareDirectory(swapReserveDir); inventoryExistingReserveFiles(); poolState = PoolState.INVENTORIED; } } catch (Exception e) { inventoryException = e; logger.error("Could not inventory preexisting reserve directory", e); } }</code><technical_language>is rollout strategy for this? Is manually delete directories code detect format do automatically. automatically delete folders in reserveDir start "reserve_size_". This avoid a complicated deployment disable diskspaceallocator, delete files, redeploy new version</technical_language>

Target:
pathname -> pathname.isFile() && pathname.getName().startsWith(RESERVE_FILE_PREFIX); private static final FileFilter FILE_SIZE_DIR_FILTER = pathname -> pathname.isDirectory() && getFileSizeForDirName(pathname.getName()) != null; private static final Logger logger = LoggerFactory.getLogger(DiskSpaceAllocator.class); private final boolean enablePooling; private final File reserveDir; private final File swapReserveDir; private final long requiredSwapSegmentsPerSize; private final StorageManagerMetrics metrics; private final Map<String, ReserveFileMap> storeReserveFiles = new HashMap<>(); private final ReserveFileMap swapReserveFiles = new ReserveFileMap(); private PoolState poolState = PoolState.NOT_INVENTORIED; private Exception inventoryException = null; DiskSpaceAllocator(boolean enablePooling, File reserveDir, long requiredSwapSegmentsPerSize, StorageManagerMetrics metrics) { this.enablePooling = enablePooling; this.reserveDir = reserveDir; swapReserveDir = new File(reserveDir, SWAP_DIR_NAME); this.requiredSwapSegmentsPerSize = requiredSwapSegmentsPerSize; this.metrics = metrics; try { if (enablePooling) { prepareDirectory(reserveDir); prepareDirectory(swapReserveDir); inventoryExistingReserveFiles(); poolState = PoolState.INVENTORIED; } } catch (Exception e) { inventoryException = e; logger.error("Could not inventory preexisting reserve directory", e); } }
Source:
<code>public void updateHandler_queryParams() { final String oldValue = "foo"; <START> final String newValue = "foo bar"; <END> Response response = db.save(new Foo(null, oldValue)); Params params = new Params() .addParam("field", "title") .addParam("value", newValue); String output = db.invokeUpdateHandler("example/example_update", response.getId(), params); Foo foo = db.find(Foo.class, response.getId()); assertNotNull(output); assertEquals(foo.getTitle(), newValue); }</code><technical_language>Again, wrong version in update master</technical_language>

Target:
public void updateHandler_queryParams() { final String oldValue = "foo"; final String newValue = "foo bar+plus=equals&ampersand"; Response response = db.save(new Foo(null, oldValue)); Params params = new Params() .addParam("field", "title") .addParam("value", newValue); String output = db.invokeUpdateHandler("example/example_update", response.getId(), params); Foo foo = db.find(Foo.class, response.getId()); assertNotNull(output); assertEquals(foo.getTitle(), newValue); }
Source:
<code>public static @Nonnull Document parse(@Nonnull Reader stream) throws SAXException, IOException { DocumentBuilder docBuilder; try { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unexpected error creating DocumentBuilder.", e); } <START> return docBuilder.parse(new InputSource(stream)); <END> }</code><technical_language>susceptable XXE injections of it..</technical_language>

Target:
public static @Nonnull Document parse(@Nonnull Reader stream) throws SAXException, IOException { DocumentBuilder docBuilder; try { docBuilder = newDocumentBuilderFactory().newDocumentBuilder(); docBuilder.setEntityResolver(RestrictiveEntityResolver.INSTANCE); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unexpected error creating DocumentBuilder.", e); } return docBuilder.parse(new InputSource(stream)); }
Source:
<code>public void handle(LoginRequest loginRequest) throws Exception { Preconditions.checkState( thisState == State.USERNAME, "Not expecting USERNAME" ); this.loginRequest = loginRequest; if ( !Protocol.supportedVersions.contains( handshake.getProtocolVersion() ) ) { disconnect( bungee.getTranslation( "outdated_server" ) ); return; } if ( getName().contains( "." ) ) { disconnect( bungee.getTranslation( "name_invalid" ) ); return; } if ( getName().length() > 16 ) { disconnect( bungee.getTranslation( "name_too_long" ) ); return; } int limit = BungeeCord.getInstance().config.getPlayerLimit(); if ( limit > 0 && bungee.getOnlineCount() > limit ) { disconnect( bungee.getTranslation( "proxy_full" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getName() ) != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; <START> } <END> if ( !isOnlineMode() && bungee.getPlayer( getName() ).getUniqueId() != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; } Callback<PreLoginEvent> callback = new Callback<PreLoginEvent>() { @Override public void done(PreLoginEvent result, Throwable error) { if ( result.isCancelled() ) { disconnect( result.getCancelReason() ); return; } if ( ch.isClosed() ) { return; } if ( onlineMode ) { unsafe().sendPacket( request = EncryptionUtil.encryptRequest() ); } else { finish(); } thisState = State.ENCRYPT; } }; bungee.getPluginManager().callEvent( new PreLoginEvent( InitialHandler.this, callback ) ); }</code><technical_language>This line absolutely</technical_language>

Target:
public void handle(LoginRequest loginRequest) throws Exception { Preconditions.checkState( thisState == State.USERNAME, "Not expecting USERNAME" ); this.loginRequest = loginRequest; if ( !Protocol.supportedVersions.contains( handshake.getProtocolVersion() ) ) { disconnect( bungee.getTranslation( "outdated_server" ) ); return; } if ( getName().contains( "." ) ) { disconnect( bungee.getTranslation( "name_invalid" ) ); return; } if ( getName().length() > 16 ) { disconnect( bungee.getTranslation( "name_too_long" ) ); return; } int limit = BungeeCord.getInstance().config.getPlayerLimit(); if ( limit > 0 && bungee.getOnlineCount() > limit ) { disconnect( bungee.getTranslation( "proxy_full" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getName() ) != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; } if ( !isOnlineMode() && bungee.getPlayer( getUUID() ) != null ) { disconnect( bungee.getTranslation( "already_connected" ) ); return; } Callback<PreLoginEvent> callback = new Callback<PreLoginEvent>() { @Override public void done(PreLoginEvent result, Throwable error) { if ( result.isCancelled() ) { disconnect( result.getCancelReason() ); return; } if ( ch.isClosed() ) { return; } if ( onlineMode ) { unsafe().sendPacket( request = EncryptionUtil.encryptRequest() ); } else { finish(); } thisState = State.ENCRYPT; } }; bungee.getPluginManager().callEvent( new PreLoginEvent( InitialHandler.this, callback ) ); }
Source:
<code>public List<String> getExtendedLabelsForVSM() { List<String> labels = Lists.newArrayList(); for (IConfigurationElement configurationElement : extensions) { <START> labels.add(configurationElement.getAttribute(LABEL_ATTRIBUTE) + " - " + configurationElement.getNamespaceIdentifier()); END> } return labels; }</code><technical_language>Add a getExtendedLabelsForVSM(IConfigurationElement) method avoid duplication</technical_language>

Target:
public List<String> getExtendedLabelsForVSM() { List<String> labels = Lists.newArrayList(); for (IConfigurationElement configurationElement : extensions) { labels.add(getExtendedLabelForVSM(configurationElement)); } return labels; }
Source:
<code>public void init() { Properties properties = new Properties(); try { properties.load(new FileInputStream("config.properties")); PopulatorContext context = new PopulatorContext(); context.setURI(properties.getProperty("xcri.oxcap.populator.uri")); context.setUser(properties.getProperty("xcri.oxcap.populator.username")); context.setPassword(properties.getProperty("xcri.oxcap.populator.password")); context.setName(properties.getProperty("xcri.oxcap.populator.name")); populator.update(context); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>This exception in logs</technical_language>

Target:
public void init() { Properties properties = new Properties(); try { properties.load(new FileInputStream("config.properties")); PopulatorContext context = new PopulatorContext("xcri.oxcap.populator", properties); populator.update(context); } catch (IOException e) { log.error("IOException [config.properties]", e); } }
Source:
<code>public static ReplicationCache createCache(long expiration, TimeUnit unit) { ReplicationCache cache = new ReplicationCache(expiration, unit); if (!cache.initialize()) { <START> cache = new ReplicationCache(); <END> cache.initialize(); } return cache; }</code><technical_language>initialize() performs some logging, nice a trace logging decision path</technical_language>

Target:
public static ReplicationCache createCache(long expiration, TimeUnit unit) { ReplicationCache cache = new ReplicationCache(expiration, unit); if (!cache.initialize()) { logger.info("Initialized replication cache with default settings."); cache = new ReplicationCache(); cache.initialize(); } return cache; }
Source:
<code>public void onResponse(Call<List<Resource>> call, Response<List<Resource>> response) { <START> HashMap<String, String> hashMap = new HashMap<String, String>(); <END> if (!response.isSuccessful()) { Log.d("Error", response.errorBody().toString()); } else { List<Resource> resources = response.body(); String decoded = rebuildFromChunks(resources.get(0).getData()); try { JSONObject structure = (new JSONObject(decoded)).getJSONObject("inventoryStructure"); JSONObject data = structure.getJSONObject("data"); String type1 = data.getString("type"); metric1.getConfiguration().setType(type1); Log.d("Type", metric1.getConfiguration().getType()); Intent intent = Intents.Builder.of(getApplicationContext()).buildMetricIntent(metric1); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }</code><technical_language>this codacy warning easily resolved</technical_language>

Target:
public void onResponse(Call<List<Resource>> call, Response<List<Resource>> response) { if (!response.isSuccessful()) { Log.d("Error", response.errorBody().toString()); } else { List<Resource> resources = response.body(); String decoded = rebuildFromChunks(resources.get(0).getData()); try { JSONObject structure = (new JSONObject(decoded)).getJSONObject("inventoryStructure"); JSONObject data = structure.getJSONObject("data"); String type1 = data.getString("type"); metric1.getConfiguration().setType(type1); Intent intent = Intents.Builder.of(getApplicationContext()).buildMetricIntent(metric1); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }
Source:
<code>public void validateBadUUIDSFiltered() { Map<String, Object> innerMap = new HashMap<>(); innerMap.put(IMAGES_LIST, new Object[]{"28e983b9-c2f6-4a50-a5d5-7a38089797c7", "c3d75234-b360-4aed-8d78-413d7488bd9b", "_remove_me_2f17489c-285e-496d-bd86-0d63d1be2efe"}); ImagesListReturn imagesListReturn = new ImagesListReturn(innerMap); <START> assertEquals(2, imagesListReturn.getImageList().length); <END> }</code><technical_language>Personally I check list matches expect theoretically obvious bug get a list of UUIDs expected</technical_language>

Target:
public void validateBadUUIDSFiltered() { Map<String, Object> innerMap = new HashMap<>(); innerMap.put(IMAGES_LIST, new Object[]{"28e983b9-c2f6-4a50-a5d5-7a38089797c7", "c3d75234-b360-4aed-8d78-413d7488bd9b", "_remove_me_2f17489c-285e-496d-bd86-0d63d1be2efe"}); ImagesListReturn imagesListReturn = new ImagesListReturn(innerMap); String[] expectedUUIDList = new String[]{"28e983b9-c2f6-4a50-a5d5-7a38089797c7", "c3d75234-b360-4aed-8d78-413d7488bd9b"}; assertArrayEquals(expectedUUIDList, imagesListReturn.getImageList()); }
Source:
<code><START> public void setStatus(final StateStatus status) { <END> this.status = status; }</code><technical_language>explain protected field access expose public methods ? Do change access modifiers understanding purpose</technical_language>

Target:
protected void setStatus(final StateStatus status) { this.status = status; }
Source:
<code>public void onError(ObjectServerError error) { if (error.getErrorCode() == ErrorCode.TOKEN_EXPIRED) { session.getUser().removeAccessToken(session.getServerUrl()); session.stopNativeSession(); <START> session.createNativeSession(); <END> gotoNextState(SessionState.BINDING); } else { switch (error.getCategory()) { case FATAL: gotoNextState(SessionState.STOPPED); break; case RECOVERABLE: gotoNextState(SessionState.UNBOUND); break; } } }</code><technical_language>UNBOUND state in constructor call stopNativeSession createNativeSession, transit BINDING state there. @cmelchior</technical_language>

Target:
public void onError(ObjectServerError error) { if (error.getErrorCode() == ErrorCode.TOKEN_EXPIRED) { session.stopNativeSession(); session.removeAccessToken(); session.createNativeSession(); gotoNextState(SessionState.BINDING); } else { switch (error.getCategory()) { case FATAL: gotoNextState(SessionState.STOPPED); break; case RECOVERABLE: gotoNextState(SessionState.UNBOUND); break; } } }
Source:
<code>public boolean checkDistinguishedName(String userName) { Name name = null; try { name = new LdapName(userName); } catch (InvalidNameException ex) { <START> LOG.error("Invalid distinguished name {}", userName); <END> LOG.debug("Invalid distinguished name {}", userName, ex); } return name != null; }</code><technical_language>change debug warn error. need include</technical_language>

Target:
public boolean checkDistinguishedName(String userName) { Name name = null; try { name = new LdapName(userName); } catch (InvalidNameException ex) { LOG.error("Invalid distinguished name {}", userName, ex); } return name != null; }
Source:
<code>protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null || vm.getVmFQDN() == null) { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = (HostProviderProxy) ProviderProxyFactory.getInstance().create(provider); <START> getQueryReturnValue().setReturnValue(proxy.getErrataForHost(vm.getVmFQDN())); <END> } else { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); } }</code><technical_language>a "fallback" vmName in case FQDN is empty? thoughts this</technical_language>

Target:
protected void executeQueryCommand() { VM vm = vmDao.get(getParameters().getId()); if (vm == null || vm.getVmHost() == null) { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); return; } Provider<?> provider = providerDao.get(vm.getProviderId()); if (provider != null) { HostProviderProxy proxy = (HostProviderProxy) ProviderProxyFactory.getInstance().create(provider); getQueryReturnValue().setReturnValue(proxy.getErrataForHost(vm.getVmHost())); } else { getQueryReturnValue().setReturnValue(Collections.<Erratum> emptyList()); } }
Source:
<code>private static Result documentEntity(ImmutableMap<String, String> extIdentifiers) { Result result = minimalEntityBuilder(ID, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_ARTICLE, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_DATASET); addTitle(result, TITLE, null); addTitle(result, OTHER_TITLE, null); addDescription(result, ABSTRACT); if (result.getPid() == null) { result.setPid(new ArrayList<>()); } <START> for (Entry<String, String> entry : extIdentifiers.entrySet()) { <END> StructuredProperty structPid = new StructuredProperty(); structPid.setValue(entry.getValue()); Qualifier pidQualifier = new Qualifier(); pidQualifier.setClassid(entry.getKey()); structPid.setQualifier(pidQualifier); result.getPid().add(structPid); result.getPid().add(structPid); } Field<String> dateOfAcc = new Field<>(); dateOfAcc.setValue(String.format("%s-02-29", YEAR)); result.setDateofacceptance(dateOfAcc); Field<String> publisher = new Field<>(); publisher.setValue(PUBLISHER); result.setPublisher(publisher); Field<String> format = new Field<>(); format.setValue(FORMAT); if (result.getFormat() == null) { result.setFormat(new ArrayList<>()); } result.getFormat().add(format); result.setResulttype(buildQualifierWithClassId(RESULT_TYPE_CLASSID)); result.setResourcetype(buildQualifierWithClassId(RESOURCE_TYPE_CLASSID)); Author author = new Author(); author.setFullname(FULL_NAME); author.setRank(0); if (result.getAuthor() == null) { result.setAuthor(new ArrayList<>()); } result.getAuthor().add(author); return result; }</code><technical_language>I stream iteration :)</technical_language>

Target:
private static Result documentEntity(ImmutableMap<String, String> extIdentifiers) { Result result = minimalEntityBuilder(ID, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_ARTICLE, InfoSpaceConstants.SEMANTIC_CLASS_INSTANCE_TYPE_DATASET); addTitle(result, TITLE, null); addTitle(result, OTHER_TITLE, null); addDescription(result, ABSTRACT); if (result.getPid() == null) { result.setPid(new ArrayList<>()); } extIdentifiers.entrySet().stream().map(entry -> { StructuredProperty structPid = new StructuredProperty(); structPid.setValue(entry.getValue()); Qualifier pidQualifier = new Qualifier(); pidQualifier.setClassid(entry.getKey()); structPid.setQualifier(pidQualifier); return structPid; }).forEach(pid -> { result.getPid().add(pid); result.getPid().add(pid); }); Field<String> dateOfAcc = new Field<>(); dateOfAcc.setValue(String.format("%s-02-29", YEAR)); result.setDateofacceptance(dateOfAcc); Field<String> publisher = new Field<>(); publisher.setValue(PUBLISHER); result.setPublisher(publisher); Field<String> format = new Field<>(); format.setValue(FORMAT); if (result.getFormat() == null) { result.setFormat(new ArrayList<>()); } result.getFormat().add(format); result.setResulttype(buildQualifierWithClassId(RESULT_TYPE_CLASSID)); result.setResourcetype(buildQualifierWithClassId(RESOURCE_TYPE_CLASSID)); Author author = new Author(); author.setFullname(FULL_NAME); author.setRank(0); if (result.getAuthor() == null) { result.setAuthor(new ArrayList<>()); } result.getAuthor().add(author); return result; }
Source:
<code>public void testWithInvalidForcedQualifier() throws Exception { File basedir = getBasedir("projects/buildqualifier"); File pom = new File(basedir, "p001/pom.xml"); <START> MavenExecutionRequest request = newMavenExecutionRequest(pom); request.getProjectBuildingRequest().setProcessPlugins(false); MavenProject project = getProject(request); ArrayList<MavenProject> projects = new ArrayList<MavenProject>(); projects.add(project); MavenSession session = newMavenSession(projects.get(0), projects); BuildQualifierMojo mojo = getMojo(project, session); <END> setVariableValueToObject(mojo, "forceContextQualifier", "invalid:Qualifier"); try { mojo.execute(); fail(); } catch (MojoFailureException e) { assertEquals( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')", e.getMessage()); } }</code><technical_language>I this bulk is repeated. extract a method for this</technical_language>

Target:
public void testWithInvalidForcedQualifier() throws Exception { MavenProject project = getProject("projects/buildqualifier", "p001/pom.xml"); BuildQualifierMojo mojo = createMojoWithProject(project); setVariableValueToObject(mojo, "forceContextQualifier", "invalid:Qualifier"); try { mojo.execute(); fail(); } catch (MojoFailureException e) { assertEquals( "Invalid build qualifier, it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')", e.getMessage()); } }
Source:
<code>List<? extends Message> reactOn(RejectionEnvelope rejection) { final CommandClass commandClass = CommandClass.of(rejection.getCommandMessage() <START> .getClass()); <END> final RejectionReactorMethod method = thisClass().getReactor(rejection.getMessageClass(), commandClass); final List<? extends Message> messages = method.invoke(this, rejection.getMessage(), rejection.getRejectionContext()); return from(messages).filter(nonEmpty()).toList(); }</code><technical_language>remove getClass()call</technical_language>

Target:
List<? extends Message> reactOn(RejectionEnvelope rejection) { final CommandClass commandClass = CommandClass.of(rejection.getCommandMessage()); final RejectionReactorMethod method = thisClass().getReactor(rejection.getMessageClass(), commandClass); final List<? extends Message> messages = method.invoke(this, rejection.getMessage(), rejection.getRejectionContext()); return from(messages).filter(nonEmpty()).toList(); }
Source:
<code>public Object perform(InvocationContext ctx) throws Throwable { if (valueMatcher == ValueMatcher.MATCH_NEVER) { successful = false; return null; } MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); Object prevValue = e.getValue(hasFlag(Flag.COMMAND_RETRY)); if (prevValue == null) { nonExistent = true; <START> if (valueMatcher.matches(prevValue, value, null, valueEquivalence)) { <END> e.setChanged(true); e.setRemoved(true); e.setCreated(false); if (this instanceof EvictCommand) { e.setEvicted(true); } e.setValue(null); return isConditional() ? true : null; } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is null"); successful = false; return false; } } if (!valueMatcher.matches(prevValue, value, null, valueEquivalence)) { successful = false; return false; } if (this instanceof EvictCommand) { e.setEvicted(true); } return performRemove(e, prevValue, ctx); }</code><technical_language>prevValue replaced null</technical_language>

Target:
public Object perform(InvocationContext ctx) throws Throwable { if (valueMatcher == ValueMatcher.MATCH_NEVER) { successful = false; return null; } MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); Object prevValue = e.getValue(); if (prevValue == null) { nonExistent = true; if (valueMatcher.matches(null, value, null, valueEquivalence)) { e.setChanged(true); e.setRemoved(true); e.setCreated(false); if (this instanceof EvictCommand) { e.setEvicted(true); } e.setValue(null); return isConditional() ? true : null; } else { log.trace("Nothing to remove since the entry doesn't exist in the context or it is null"); successful = false; return false; } } if (!valueMatcher.matches(prevValue, value, null, valueEquivalence)) { successful = false; return false; } if (this instanceof EvictCommand) { e.setEvicted(true); } return performRemove(e, prevValue, ctx); }
Source:
<code>public BSONObject getReplicaSetConfig() { try { return client.getDB("local").getCollection("system.replset").findOne(); } catch (MongoException e) { <START> LOG.warn("Failed to get replica set config on {}: {}", client, e); <END> return null; } }</code><technical_language>log actual exception anywhere, toString? losing info underlying (e.g. this insufficient info send a mongodb-users list, I suspect)</technical_language>

Target:
public BSONObject getReplicaSetConfig() { try { return client.getDB("local").getCollection("system.replset").findOne(); } catch (MongoException e) { LOG.error("Failed to get replica set config on "+client, e); return null; } }