auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Context context) { sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch()) .setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch()); URL url; try { url = new URL(copySource); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalArgumentException(ex)); } return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync( null, null, url, null, metadata, tier, null, sourceConditions, destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(), context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId())); }

Target:
Mono<Response<String>> copyFromURLWithResponse(String copySource, Map<String, String> metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Context context) { sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch()) .setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch()); URL url; try { url = new URL(copySource); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalArgumentException("'copySource' is not a valid url.")); } return this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync( null, null, url, null, metadata, tier, null, sourceConditions, destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(), context).map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId())); }
Source:
public Firmware(final DeviceModel deviceModel, final int firmwareVersion, final String description) { super(); this.deviceModel = deviceModel; this.firmwareVersion = firmwareVersion; this.description = description; }

Target:
public Firmware(final DeviceModel deviceModel, final int firmwareVersion, final String description) { this.deviceModel = deviceModel; this.firmwareVersion = firmwareVersion; this.description = description; }
Source:
private int findPointer (UITouch touch) { long ptr = touch.getHandle(); for (int i = 0; i < touchDown.length; i++) { if (touchDown[i] == ptr) return i; } StringBuffer buf = new StringBuffer(); for (int i = 0; i < touchDown.length; i++) { buf.append(i + ":" + touchDown[i] + " "); } Gdx.app.error("IOSInput", "Pointer ID lookup failed: " + ptr + ", " + buf.toString()); return POINTER_NOT_FOUND; }

Target:
private int findPointer (UITouch touch) { long ptr = touch.getHandle(); for (int i = 0; i < touchDown.length; i++) { if (touchDown[i] == ptr) return i; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < touchDown.length; i++) { sb.append(i + ":" + touchDown[i] + " "); } Gdx.app.error("IOSInput", "Pointer ID lookup failed: " + ptr + ", " + sb.toString()); return POINTER_NOT_FOUND; }
Source:
private static void printStartupMsg(ServerConfiguration conf) { printLogo(); println("Welcome to CORFU SERVER"); println("Version (" + GitRepositoryState.getRepositoryState().commitIdAbbrev + ")"); println("Serving on port " + conf.getHostAddress()); println("Data location: " + (conf.getInMemoryMode() ? "MEMORY mode" : conf.getServerDir())); }

Target:
private static void printStartupMsg(ServerConfiguration conf) { printLogo(); println("Welcome to CORFU SERVER"); println("Version (" + GitRepositoryState.getRepositoryState().commitIdAbbrev + ")"); println("Serving on " + conf.getLocalServerEndpoint()); println("Data location: " + (conf.isInMemoryMode() ? "MEMORY mode" : conf.getServerDir())); }
Source:
public static AudioFormat getBestMatch(Set<AudioFormat> inputs, Set<AudioFormat> outputs) { AudioFormat preferredFormat = getPreferredFormat(inputs); for (AudioFormat output : outputs) { if (output.isCompatible(preferredFormat)) { return preferredFormat; } else { for (AudioFormat input : inputs) { if (output.isCompatible(input)) { return input; } } } } return null; }

Target:
public static AudioFormat getBestMatch(Set<AudioFormat> inputs, Set<AudioFormat> outputs) { AudioFormat preferredFormat = getPreferredFormat(inputs); if (preferredFormat != null) { for (AudioFormat output : outputs) { if (output.isCompatible(preferredFormat)) { return preferredFormat; } else { for (AudioFormat input : inputs) { if (output.isCompatible(input)) { return input; } } } } } return null; }
Source:
protected long generateActorId() { long result = (threadId << 56) | nextActorId; nextActorId++; return result; }

Target:
protected long generateActorId() { long result = (threadId << THREAD_ID_SHIFT) | nextActorId; nextActorId++; return result; }
Source:
private Set<Account.Id> getSubscribers() throws EmailException { watchers = new HashSet<Account.Id>(); Set<Account.Id> subscribers = new HashSet<Account.Id>(); try { for (AccountProjectWatch p : args.db.get().accountProjectWatches() .byProject(project.getNameKey())) { watchers.add(p.getAccountId()); switch (type) { case CREATE: case DELETE: String filter = p.getFilter(); if (filter.equals("*")) { subscribers.add(p.getAccountId()); } else if (branchMatchWithFilter(branchName, filter)) { subscribers.add(p.getAccountId()); } break; default: break; } } } catch (OrmException e) { log.error("Invalid watcher is set", e); } return subscribers; }

Target:
private Set<Account.Id> getSubscribers() throws EmailException { Set<Account.Id> subscribers = new HashSet<Account.Id>(); try { for (AccountProjectWatch p : args.db.get().accountProjectWatches() .byProject(project.getNameKey())) { switch (type) { case CREATE: case DELETE: String filter = p.getFilter(); if (branchMatchWithFilter(branchName, filter)) { subscribers.add(p.getAccountId()); } } } } catch (OrmException e) { log.error("Invalid watcher is set", e); } return subscribers; }
Source:
public void createsFork() throws Exception { final String organization = RandomStringUtils.randomNumeric(10); final MkAnswer answer = new MkAnswer.Simple( HttpURLConnection.HTTP_OK, fork(organization).toString() ); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_ACCEPTED, fork(organization).toString() ) ).next(answer).start(); final Repo owner = Mockito.mock(Repo.class); final Coordinates coordinates = Mockito.mock(Coordinates.class); Mockito.doReturn(coordinates).when(owner).coordinates(); Mockito.doReturn("test_user").when(coordinates).user(); Mockito.doReturn("test_repo").when(coordinates).repo(); final RtForks forks = new RtForks( new JdkRequest(container.home()), owner ); final Fork fork = forks.create(organization); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( fork.json().getString(ORGANIZATION), Matchers.equalTo(organization) ); container.stop(); }

Target:
public void createsFork() throws Exception { final String organization = RandomStringUtils.randomNumeric(10); final MkAnswer answer = new MkAnswer.Simple( HttpURLConnection.HTTP_OK, fork(organization).toString() ); final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_ACCEPTED, fork(organization).toString() ) ).next(answer).start(); final Repo owner = Mockito.mock(Repo.class); final Coordinates coordinates = new Coordinates.Simple( "test_user", "test_repo" ); Mockito.doReturn(coordinates).when(owner).coordinates(); final RtForks forks = new RtForks( new JdkRequest(container.home()), owner ); final Fork fork = forks.create(organization); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); MatcherAssert.assertThat( fork.json().getString(ORGANIZATION), Matchers.equalTo(organization) ); container.stop(); }
Source:
public String[] listFiles(URI fileUri, boolean recursive) throws IOException { try { ImmutableList.Builder<String> builder = ImmutableList.builder(); String prefix = normalizeToDirectoryPrefix(fileUri); ListObjectsV2Response listObjectsV2Response; ListObjectsV2Request.Builder listObjectsV2RequestBuilder = ListObjectsV2Request.builder() .bucket(fileUri.getHost()) .prefix(prefix); if (recursive) { ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.build(); listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request); } else { ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.delimiter(DELIMITER).build(); listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request); } listObjectsV2Response.contents().stream() .forEach(object -> { if (!object.key().equals(fileUri.getPath()) && !object.key().endsWith(DELIMITER)) { builder.add(object.key()); } }); return builder.build().toArray(new String[0]); } catch (Throwable t) { throw new IOException(t); } }

Target:
public String[] listFiles(URI fileUri, boolean recursive) throws IOException { try { ImmutableList.Builder<String> builder = ImmutableList.builder(); String prefix = normalizeToDirectoryPrefix(fileUri); ListObjectsV2Response listObjectsV2Response; ListObjectsV2Request.Builder listObjectsV2RequestBuilder = ListObjectsV2Request.builder().bucket(fileUri.getHost()); if (!prefix.equals(DELIMITER)) { listObjectsV2RequestBuilder = listObjectsV2RequestBuilder.prefix(prefix); } if (!recursive) { listObjectsV2RequestBuilder = listObjectsV2RequestBuilder.delimiter(DELIMITER); } ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.build(); listObjectsV2Response = _s3Client.listObjectsV2(listObjectsV2Request); listObjectsV2Response.contents().stream().forEach(object -> { if (!object.key().equals(fileUri.getPath()) && !object.key().endsWith(DELIMITER)) { builder.add(object.key()); } }); return builder.build().toArray(new String[0]); } catch (Throwable t) { throw new IOException(t); } }
Source:
private boolean useResizingImageView() { return !CommCarePreferences.isSmartInflationEnabled() && (ResizingImageView.resizeMethod != null && (ResizingImageView.resizeMethod.equals("full") || ResizingImageView.resizeMethod.equals("half") || ResizingImageView.resizeMethod.equals("width"))); }

Target:
private boolean useResizingImageView() { return !CommCarePreferences.isSmartInflationEnabled() && ("full".equals(ResizingImageView.resizeMethod) || "half".equals(ResizingImageView.resizeMethod) || "width".equals(ResizingImageView.resizeMethod)); }
Source:
private static <BE> void preUpdate(TraversalContext<BE, ?> context, BE entity, MetricType.Update update) { MetricType mt = context.backend.convert(entity, MetricType.class); if (mt.getUnit() == update.getUnit()) { return; } if (isInMetadataPack(context, entity)) { throw new IllegalArgumentException("Cannot delete a metric type that is a part of metadata pack."); } }

Target:
private static <BE> void preUpdate(TraversalContext<BE, ?> context, BE entity, MetricType.Update update) { MetricType mt = context.backend.convert(entity, MetricType.class); if (mt.getUnit() == update.getUnit()) { return; } if (isInMetadataPack(context, entity)) { throw new IllegalArgumentException("Cannot update a metric type that is a part of metadata pack."); } }
Source:
private void readProperties(Map<String, Object> properties) { if (properties.get(PROPERTY_PING_INTERVAL) != null) { this.pingInterval = (Integer) properties.get(PROPERTY_PING_INTERVAL); } if (properties.get(PROPERTY_WD_DEVICE) != null && !((String) properties.get(PROPERTY_WD_DEVICE)).isEmpty()) { this.watchdogDevice = (String) properties.get(PROPERTY_WD_DEVICE); } if (properties.get(PROPERTY_ENABLED) != null) { this.configEnabled = (Boolean) properties.get(PROPERTY_ENABLED); if (this.configEnabled) { PrintWriter wdWriter = null; try { wdWriter = new PrintWriter(WD_FILE); wdWriter.write(this.watchdogDevice); } catch (IOException e) { logger.error("Unable to write watchdog config file", e); } finally { if (wdWriter != null) wdWriter.close(); } logger.debug("activating WatchdogService with watchdog enabled"); } else { logger.debug("activating WatchdogService with watchdog disabled"); } } }

Target:
private void readProperties(Map<String, Object> properties) { this.pingInterval = (Integer) properties.get(PROPERTY_PING_INTERVAL); if (!((String) properties.get(PROPERTY_WD_DEVICE)).isEmpty()) { this.watchdogDevice = (String) properties.get(PROPERTY_WD_DEVICE); } this.configEnabled = (Boolean) properties.get(PROPERTY_ENABLED); if (this.configEnabled) { try (PrintWriter wdWriter = new PrintWriter(WD_FILE);) { wdWriter.write(this.watchdogDevice); } catch (IOException e) { logger.error("Unable to write watchdog config file", e); } logger.debug("activating WatchdogService with watchdog enabled"); } else { logger.debug("activating WatchdogService with watchdog disabled"); } }
Source:
public Command execute() throws RollBackCommandException { try { Session sess = this.getSecAdvisor().getReadOnlyHibernateSession(this.getUsername()); if(idDataTrack != null) { DataTrack dataTrack = (DataTrack) (sess.load(DataTrack.class, idDataTrack)); if (!this.getSecAdvisor().canRead(dataTrack)) { this.addInvalidField("perm", "Insufficient permission to access this data track"); } } else { this.addInvalidField("dataTrackNumber", "dataTrackNumber is either invalid or not provided"); } if (isValid()) { this.xmlResult = "<SUCCESS/>"; setResponsePage(this.SUCCESS_JSP); } else { setResponsePage(this.ERROR_JSP); } } catch (NamingException e){ LOG.error("An exception has occurred in CheckDataTrackPermission ", e); e.printStackTrace(System.out); throw new RollBackCommandException(e.getMessage()); } catch (SQLException e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); e.printStackTrace(System.out); throw new RollBackCommandException(e.getMessage()); } catch (Exception e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); e.printStackTrace(System.out); throw new RollBackCommandException(e.getMessage()); } finally { try { this.getSecAdvisor().closeReadOnlyHibernateSession(); } catch(Exception e) { } } return this; }

Target:
public Command execute() throws RollBackCommandException { try { Session sess = this.getSecAdvisor().getReadOnlyHibernateSession(this.getUsername()); if(idDataTrack != null) { DataTrack dataTrack = (DataTrack) (sess.load(DataTrack.class, idDataTrack)); if (!this.getSecAdvisor().canRead(dataTrack)) { this.addInvalidField("perm", "Insufficient permission to access this data track"); } } else { this.addInvalidField("dataTrackNumber", "dataTrackNumber is either invalid or not provided"); } if (isValid()) { this.xmlResult = "<SUCCESS/>"; setResponsePage(this.SUCCESS_JSP); } else { setResponsePage(this.ERROR_JSP); } } catch (Exception e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); throw new RollBackCommandException(e.getMessage()); } finally { try { this.getSecAdvisor().closeReadOnlyHibernateSession(); } catch(Exception e) { LOG.error("An exception has occurred in CheckDataTrackPermission ", e); } } return this; }
Source:
public void clearFinishedDownloads(boolean delete) { if (delete && mIterator.hasFinishedMissions() && mHidden.isEmpty()) { for (int i = 0; i < mIterator.getOldListSize(); i++) { FinishedMission mission = mIterator.getItem(i).mission instanceof FinishedMission ? (FinishedMission) mIterator.getItem(i).mission : null; if (mission != null) { mIterator.hide(mission); mHidden.add(mission); } } applyChanges(); String msg = String.format(mContext.getString(R.string.deleted_downloads), String.valueOf(mHidden.size())); mSnackbar = Snackbar.make(mView, msg, Snackbar.LENGTH_INDEFINITE); mSnackbar.setAction(R.string.undo, s -> { Iterator<Mission> i = mHidden.iterator(); while (i.hasNext()) { mIterator.unHide(i.next()); i.remove(); } applyChanges(); mHandler.removeCallbacks(rDelete); }); mSnackbar.setActionTextColor(Color.YELLOW); mSnackbar.show(); mHandler.postDelayed(rDelete, TIMEOUT); } else if (!delete) { mDownloadManager.forgetFinishedDownloads(); applyChanges(); } }

Target:
public void clearFinishedDownloads(boolean delete) { if (delete && mIterator.hasFinishedMissions() && mHidden.isEmpty()) { for (int i = 0; i < mIterator.getOldListSize(); i++) { FinishedMission mission = mIterator.getItem(i).mission instanceof FinishedMission ? (FinishedMission) mIterator.getItem(i).mission : null; if (mission != null) { mIterator.hide(mission); mHidden.add(mission); } } applyChanges(); String msg = String.format(mContext.getString(R.string.deleted_downloads), mHidden.size()); mSnackbar = Snackbar.make(mView, msg, Snackbar.LENGTH_INDEFINITE); mSnackbar.setAction(R.string.undo, s -> { Iterator<Mission> i = mHidden.iterator(); while (i.hasNext()) { mIterator.unHide(i.next()); i.remove(); } applyChanges(); mHandler.removeCallbacks(rDelete); }); mSnackbar.setActionTextColor(Color.YELLOW); mSnackbar.show(); mHandler.postDelayed(rDelete, 5000); } else if (!delete) { mDownloadManager.forgetFinishedDownloads(); applyChanges(); } }
Source:
protected void auditRequestMessage(RetrieveDocumentSetRequestType request, String direction, String connectInterface, AssertionType assertion, String requestCommunityID) { gov.hhs.fha.nhinc.common.auditlog.DocRetrieveMessageType message = new gov.hhs.fha.nhinc.common.auditlog.DocRetrieveMessageType(); message.setRetrieveDocumentSetRequest(request); message.setAssertion(assertion); AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logDocRetrieve(message, direction, connectInterface, requestCommunityID); if (auditLogMsg != null) { auditMessage(auditLogMsg, assertion); } }

Target:
protected void auditRequestMessage(RetrieveDocumentSetRequestType request, String direction, String connectInterface, AssertionType assertion, String requestCommunityID) { DocRetrieveMessageType message = new DocRetrieveMessageType(); message.setRetrieveDocumentSetRequest(request); message.setAssertion(assertion); AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logDocRetrieve(message, direction, connectInterface, requestCommunityID); if (auditLogMsg != null) { auditMessage(auditLogMsg, assertion); } }
Source:
private void orderListByProgramName(List<TrialSummary> trialSummaryList, final String sortOrder) { if (StringUtil.isEmpty(sortOrder) || TrialResourceBrapi.DESCENDING.equalsIgnoreCase(sortOrder)) { Comparator desc = Collections.reverseOrder(getComparatorProgramName()); Collections.sort(trialSummaryList, desc); }else { Collections.sort(trialSummaryList, getComparatorProgramName()); } }

Target:
private void orderListByProgramName(List<TrialSummary> trialSummaryList, final String sortOrder) { if (StringUtil.isEmpty(sortOrder) || TrialResourceBrapi.ORDER_BY_DESCENDING.equalsIgnoreCase(sortOrder)) { Comparator desc = Collections.reverseOrder(TrialResourceBrapi.getComparatorProgramName()); Collections.sort(trialSummaryList, desc); } else { Collections.sort(trialSummaryList, TrialResourceBrapi.getComparatorProgramName()); } }
Source:
public JSONPathSpec( @JsonProperty("useFieldDiscovery") Boolean useFieldDiscovery, @JsonProperty("fields") List<JSONPathFieldSpec> fields ) { this.useFieldDiscovery = useFieldDiscovery == null ? true : useFieldDiscovery; this.fields = fields == null ? new ArrayList<JSONPathFieldSpec>() : fields; }

Target:
public JSONPathSpec( @JsonProperty("useFieldDiscovery") Boolean useFieldDiscovery, @JsonProperty("fields") List<JSONPathFieldSpec> fields ) { this.useFieldDiscovery = useFieldDiscovery == null ? true : useFieldDiscovery; this.fields = fields == null ? ImmutableList.<JSONPathFieldSpec>of() : fields; }
Source:
private String trimUrlWebdav(String url){ if(url.toLowerCase().endsWith(WEBDAV_PATH)){ url = url.substring(0, url.length() - WEBDAV_PATH.length()); } return (url != null ? url : ""); }

Target:
private String trimUrlWebdav(String url){ if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){ url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length()); } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){ url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length()); } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){ url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length()); } return (url != null ? url : ""); }
Source:
public static SQLException unwrapSqlException(SQLException root){ Exception e = root; while(e.getCause() != null){ e = (Exception) e.getCause(); if(e instanceof SQLException){ root = (SQLException) e; } } return root; }

Target:
public static SQLException unwrapSqlException(SQLException root){ Exception e = root; while(e.getCause() != null){ e = (Exception) e.getCause(); if(e instanceof RuntimeException && e.getCause() instanceof SQLException) { return (SQLException) e.getCause(); } if(e instanceof SQLException){ return (SQLException) e; } } return root; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Shell activeShell= HandlerUtil.getActiveShell(event); Object newNameValue= HandlerUtil.getVariable(event, LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY); String newName= null; if (newNameValue instanceof String) { newName= (String) newNameValue; } else if (newNameValue != null) { RefactoringUIPlugin.logErrorMessage(NLS.bind(RefactoringUIMessages.RenameResourceHandler_ERROR_EXPECTED_STRING, newNameValue.getClass().getName())); } ISelection sel= HandlerUtil.getCurrentSelection(event); if (sel instanceof IStructuredSelection) { IResource resource= getCurrentResource((IStructuredSelection) sel); if (resource != null) { RenameResourceWizard refactoringWizard; if (newName != null) { refactoringWizard= new RenameResourceWizard(resource, newName); } else { refactoringWizard= new RenameResourceWizard(resource); } RefactoringProcessor processor= ((ProcessorBasedRefactoring) refactoringWizard.getRefactoring()).getProcessor(); Change change= getChange(refactoringWizard); RefactoringWizardOpenOperation op= new RefactoringWizardOpenOperation(refactoringWizard); try { if (isCompositeChange(change) || !(processor instanceof RenameResourceProcessor)) { op.run(activeShell, RefactoringUIMessages.RenameResourceHandler_title); } else { change.perform(new NullProgressMonitor()); } } catch (InterruptedException | CoreException e) { RefactoringUIPlugin.log(e); } } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Shell activeShell= HandlerUtil.getActiveShell(event); Object newNameValue= HandlerUtil.getVariable(event, LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY); String newName= null; if (newNameValue instanceof String) { newName= (String) newNameValue; } else if (newNameValue != null) { RefactoringUIPlugin.logErrorMessage(NLS.bind(RefactoringUIMessages.RenameResourceHandler_ERROR_EXPECTED_STRING, newNameValue.getClass().getName())); } ISelection sel= HandlerUtil.getCurrentSelection(event); if (sel instanceof IStructuredSelection) { IResource resource= getCurrentResource((IStructuredSelection) sel); if (resource != null) { RenameResourceWizard refactoringWizard; if (newName != null) { refactoringWizard= new RenameResourceWizard(resource, newName); } else { refactoringWizard= new RenameResourceWizard(resource); } RefactoringProcessor processor= ((ProcessorBasedRefactoring) refactoringWizard.getRefactoring()).getProcessor(); Change change= getChange(refactoringWizard); try { if (isCompositeChange(change) || !(processor instanceof RenameResourceProcessor)) { refactoringWizard= newName == null ? new RenameResourceWizard(resource) : new RenameResourceWizard(resource, newName); RefactoringWizardOpenOperation op= new RefactoringWizardOpenOperation(refactoringWizard); op.run(activeShell, RefactoringUIMessages.RenameResourceHandler_title); } else { change.perform(new NullProgressMonitor()); } } catch (InterruptedException | CoreException e) { RefactoringUIPlugin.log(e); } } } return null; }
Source:
public void setResize(int resize) { for(int i=1;i<10;i++) { if(resize == i*100) { this.resize = resize; return; } } throw new IllegalArgumentException("Invalid resize value"); }

Target:
public void setResize(int resize) { for(int i=1;i<10;i++) { if(resize == i*100) { this.resize = resize; return; } } throw new IllegalArgumentException("Invalid resize value. Valid range of values is 100-900."); }
Source:
public DefaultPlanPhase(final DefaultPlan parentPlan, final DefaultPlanPhase in, @Nullable final PlanPhasePriceOverride override) { this.type = in.getPhaseType(); this.duration = (DefaultDuration) in.getDuration(); this.fixed = override != null && override.getFixedPrice() != null ? new DefaultFixed((DefaultFixed) in.getFixed(), override) : (DefaultFixed) in.getFixed(); this.recurring = override != null && override.getRecurringPrice() != null ? new DefaultRecurring((DefaultRecurring) in.getRecurring(), override) : (DefaultRecurring) in.getRecurring(); this.usages = new DefaultUsage[in.getUsages().length]; for (int i = 0; i < in.getUsages().length; i++) { if(override != null && override.getUsagePriceOverrides().get(i)!= null) { usages[i] = new DefaultUsage(in.getUsages()[i], override.getUsagePriceOverrides().get(i), override.getCurrency()); } else { usages[i] = (DefaultUsage) in.getUsages()[i]; } } this.plan = parentPlan; }

Target:
public DefaultPlanPhase(final DefaultPlan parentPlan, final DefaultPlanPhase in, @Nullable final PlanPhasePriceOverride override) { this.type = in.getPhaseType(); this.duration = (DefaultDuration) in.getDuration(); this.fixed = override != null && override.getFixedPrice() != null ? new DefaultFixed((DefaultFixed) in.getFixed(), override) : (DefaultFixed) in.getFixed(); this.recurring = override != null && override.getRecurringPrice() != null ? new DefaultRecurring((DefaultRecurring) in.getRecurring(), override) : (DefaultRecurring) in.getRecurring(); this.usages = new DefaultUsage[in.getUsages().length]; for (int i = 0; i < in.getUsages().length; i++) { final Usage curUsage = in.getUsages()[i]; if(override != null && override.getUsagePriceOverrides()!= null) { final UsagePriceOverride usagePriceOverride = Iterables.tryFind(override.getUsagePriceOverrides(), new Predicate<UsagePriceOverride>() { @Override public boolean apply(final UsagePriceOverride input) { return input !=null && input.getName().equals(curUsage.getName()); } }).orNull(); usages[i] = (usagePriceOverride !=null) ? new DefaultUsage(in.getUsages()[i], usagePriceOverride, override.getCurrency()) : (DefaultUsage)curUsage; } else { usages[i] = (DefaultUsage)curUsage; } } this.plan = parentPlan; }
Source:
public synchronized MBeanInfo getMBeanInfo() { return _mBeanInfo; }

Target:
public MBeanInfo getMBeanInfo() { return _mBeanInfo; }
Source:
private void createNewWalk(Repository db, AnyObjectId headId) { currentHeadId = headId; if (currentWalk != null) currentWalk.release(); if (getFollowRenames()) { currentWalk = new FollowingSWTWalk(db); } else { currentWalk = new SWTWalk(db); } try { currentWalk.addAdditionalRefs(db.getRefDatabase().getAdditionalRefs()); currentWalk.addAdditionalRefs(db.getRefDatabase(). getRefs(Constants.R_NOTES).values()); } catch (IOException e) { throw new IllegalStateException(NLS.bind( UIText.GitHistoryPage_errorReadingAdditionalRefs, Activator .getDefault().getRepositoryUtil() .getRepositoryName(db)), e); } currentWalk.sort(RevSort.COMMIT_TIME_DESC, true); currentWalk.sort(RevSort.BOUNDARY, true); highlightFlag = currentWalk.newFlag("highlight"); }

Target:
private void createNewWalk(Repository db, AnyObjectId headId) { currentHeadId = headId; if (currentWalk != null) currentWalk.release(); if (getFollowRenames()) currentWalk = new FollowingSWTWalk(db); else currentWalk = new SWTWalk(db); try { currentWalk.addAdditionalRefs(db.getRefDatabase().getAdditionalRefs()); currentWalk.addAdditionalRefs(db.getRefDatabase(). getRefs(Constants.R_NOTES).values()); } catch (IOException e) { throw new IllegalStateException(NLS.bind( UIText.GitHistoryPage_errorReadingAdditionalRefs, Activator .getDefault().getRepositoryUtil() .getRepositoryName(db)), e); } currentWalk.sort(RevSort.COMMIT_TIME_DESC, true); currentWalk.sort(RevSort.BOUNDARY, true); highlightFlag = currentWalk.newFlag("highlight"); }
Source:
public ForwardToContainer(Collection<InetAddressAndPort> targets, int[] messageIds) { this.targets = targets; this.messageIds = messageIds; }

Target:
public ForwardToContainer(Collection<InetAddressAndPort> targets, int[] messageIds) { Preconditions.checkArgument(targets.size() == messageIds.length); this.targets = targets; this.messageIds = messageIds; }
Source:
private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) { if (state == null || state.networkInfo == null || state.linkProperties == null) return; if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) { state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null); } if (mLockdownTracker != null) { mLockdownTracker.augmentNetworkInfo(state.networkInfo); } final long token = Binder.clearCallingIdentity(); try { state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state)); } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(token); } }

Target:
private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) { if (state == null || state.networkInfo == null || state.linkProperties == null) return; if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) { state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null); } synchronized (mVpns) { if (mLockdownTracker != null) { mLockdownTracker.augmentNetworkInfo(state.networkInfo); } } final long token = Binder.clearCallingIdentity(); try { state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state)); } catch (RemoteException e) { } finally { Binder.restoreCallingIdentity(token); } }
Source:
protected List<String> getOptionalStringList(String... optionPath) { try { return getRequiredStringList(optionPath); } catch (InvalidConfigurationException e) { return Lists.newArrayList(); } }

Target:
protected List<String> getOptionalStringList(String... optionPath) { try { return getRequiredStringList(optionPath); } catch (InvalidConfigurationException e) { return Collections.emptyList(); } }
Source:
public String format(String projectName, String revision, ConfigSection cfg, String raw) throws IOException { File tmpFile = new File(baseDir, "tmp/asciidoctor-" + System.currentTimeMillis() + ".tmp"); try { Asciidoctor.Factory.create(AsciidoctorFormatter.class.getClassLoader()) .render(raw, createOptions(cfg, revision, tmpFile)); try (FileInputStream input = new FileInputStream(tmpFile)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteStreams.copy(input, out); return insertCss(out.toString(UTF_8.name())); } } finally { if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } }

Target:
public String format(String projectName, String revision, ConfigSection cfg, String raw) throws IOException { File tmpFile = new File(baseDir, "tmp/asciidoctor-" + TimeUtil.nowTs().getNanos() + ".tmp"); try { Asciidoctor.Factory.create(AsciidoctorFormatter.class.getClassLoader()) .render(raw, createOptions(cfg, revision, tmpFile)); try (FileInputStream input = new FileInputStream(tmpFile)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteStreams.copy(input, out); return insertCss(out.toString(UTF_8.name())); } } finally { if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((inboundAverage == null) ? 0 : inboundAverage.hashCode()); result = prime * result + ((inboundPeak == null) ? 0 : inboundPeak.hashCode()); result = prime * result + ((inboundBurst == null) ? 0 : inboundBurst.hashCode()); result = prime * result + ((outboundAverage == null) ? 0 : outboundAverage.hashCode()); result = prime * result + ((outboundPeak == null) ? 0 : outboundPeak.hashCode()); result = prime * result + ((outboundBurst == null) ? 0 : outboundBurst.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((inboundAverage == null) ? 0 : inboundAverage.hashCode()); result = prime * result + ((inboundPeak == null) ? 0 : inboundPeak.hashCode()); result = prime * result + ((inboundBurst == null) ? 0 : inboundBurst.hashCode()); result = prime * result + ((outboundAverage == null) ? 0 : outboundAverage.hashCode()); result = prime * result + ((outboundPeak == null) ? 0 : outboundPeak.hashCode()); result = prime * result + ((outboundBurst == null) ? 0 : outboundBurst.hashCode()); return result; }
Source:
private Query applyEntityGraphConfiguration(Query query, JpaQueryMethod method) { JpaEntityGraph entityGraph = method.getEntityGraph(); if (entityGraph != null) { List<QueryHintValue> hints = Jpa21Utils.tryGetFetchGraphHints(em, method.getEntityGraph(), getQueryMethod().getEntityInformation().getJavaType()); for (QueryHintValue hint : hints) { query.setHint(hint.name, hint.value); } } return query; }

Target:
private Query applyEntityGraphConfiguration(Query query, JpaQueryMethod method) { JpaEntityGraph entityGraph = method.getEntityGraph(); if (entityGraph != null) { SimpleQueryHints hints = Jpa21Utils.getFetchGraphHint(em, method.getEntityGraph(), getQueryMethod().getEntityInformation().getJavaType()); hints.forEach(query::setHint); } return query; }
Source:
private UniqueEntityLoader getLoaderByLockMode(LockMode lockMode) { if ( LockMode.NONE.equals( lockMode ) ) { return noneLockLoader; } else if ( LockMode.READ.equals( lockMode ) ) { return readLockLoader; } return loaders.computeIfAbsent( lockMode, this::createLazyLoadedEntityLoader ); }

Target:
private UniqueEntityLoader getLoaderByLockMode(LockMode lockMode) { if ( LockMode.NONE == lockMode ) { return noneLockLoader; } else if ( LockMode.READ == lockMode ) { return readLockLoader; } return loaders.computeIfAbsent( lockMode, this::createLazyLoadedEntityLoader ); }
Source:
public boolean add(SelectionKey key) { if (key == null) { return false; } if (pos >= (keys.length - 1)) { SelectionKey[] keys = new SelectionKey[this.keys.length << 1]; System.arraycopy(this.keys, 0, keys, 0, this.keys.length); this.keys = keys; } keys[pos++] = key; return true; }

Target:
public boolean add(SelectionKey key) { if (key == null) { return false; } if (pos >= keys.length) { SelectionKey[] keys = new SelectionKey[this.keys.length << 1]; System.arraycopy(this.keys, 0, keys, 0, this.keys.length); this.keys = keys; } keys[pos++] = key; return true; }
Source:
private static void findScrambleOptions( final PlayerId player, final Map<Territory, ProTerritory> moveMap) { final GameData data = ProData.getData(); if (!Properties.getScrambleRulesInEffect(data)) { return; } final var scrambleLogic = new ScrambleLogic(data, player, moveMap.keySet()); for (final var territoryToScramblersEntry : scrambleLogic.getUnitsThatCanScrambleByDestination().entrySet()) { final Territory to = territoryToScramblersEntry.getKey(); for (final var fromToScrambers : territoryToScramblersEntry.getValue().entrySet()) { final Territory from = fromToScrambers.getKey(); final Collection<Unit> airbases = fromToScrambers.getValue().getFirst(); final Collection<Unit> scramblers = fromToScrambers.getValue().getSecond(); final int maxCanScramble = ScrambleLogic.getMaxScrambleCount(airbases); final List<Unit> addTo = moveMap.get(to).getMaxScrambleUnits(); if (scramblers.size() <= maxCanScramble) { addTo.addAll(scramblers); } else { scramblers.stream() .sorted( Comparator.<Unit>comparingDouble( unit -> ProBattleUtils.estimateStrength(to, List.of(unit), List.of(), false)) .reversed()) .limit(maxCanScramble) .forEachOrdered(addTo::add); } } } }

Target:
private static void findScrambleOptions( final PlayerId player, final Map<Territory, ProTerritory> moveMap) { final GameData data = ProData.getData(); if (!Properties.getScrambleRulesInEffect(data)) { return; } final var scrambleLogic = new ScrambleLogic(data, player, moveMap.keySet()); for (final var territoryToScramblersEntry : scrambleLogic.getUnitsThatCanScrambleByDestination().entrySet()) { final Territory to = territoryToScramblersEntry.getKey(); for (final Tuple<Collection<Unit>, Collection<Unit>> airbasesAndScramblers : territoryToScramblersEntry.getValue().values()) { final Collection<Unit> airbases = airbasesAndScramblers.getFirst(); final Collection<Unit> scramblers = airbasesAndScramblers.getSecond(); final int maxCanScramble = ScrambleLogic.getMaxScrambleCount(airbases); final List<Unit> addTo = moveMap.get(to).getMaxScrambleUnits(); if (scramblers.size() <= maxCanScramble) { addTo.addAll(scramblers); } else { scramblers.stream() .sorted( Comparator.<Unit>comparingDouble( unit -> ProBattleUtils.estimateStrength(to, List.of(unit), List.of(), false)) .reversed()) .limit(maxCanScramble) .forEachOrdered(addTo::add); } } } }
Source:
public PojoWithCollections(Collection fieldCollection, List fieldList, Set fieldSet) { super(); this.fieldCollection = fieldCollection; this.fieldList = fieldList; this.fieldSet = fieldSet; }

Target:
public PojoWithCollections(Collection fieldCollection, List fieldList, Set fieldSet) { this.fieldCollection = fieldCollection; this.fieldList = fieldList; this.fieldSet = fieldSet; }
Source:
private static boolean isDuplicatedByStarImport(FullIdent starImp, FullIdent imp) { final String importSplitRegexp = "\\."; final String[] impSplitted = imp.getText().split(importSplitRegexp); final String[] starImpSplited = starImp.getText().split(importSplitRegexp); boolean isEquals = true; if (impSplitted.length == starImpSplited.length) { for (int i = 0; i < impSplitted.length - 1 && isEquals; i++) { isEquals = impSplitted[i].equals(starImpSplited[i]); } } else { isEquals = false; } return isEquals; }

Target:
private static boolean isDuplicatedByStarImport(FullIdent starImp, FullIdent imp) { final String impText = imp.getText(); final String starImpText = starImp.getText(); final int impLastDotIndex = impText.lastIndexOf('.'); final int starImpLastDotIndex = starImpText.lastIndexOf('.'); return impLastDotIndex == starImpLastDotIndex && impText.regionMatches(0, starImpText, 0, impLastDotIndex); }
Source:
default void testEmptyMetadata() { ConnectorSession session = new TestingConnectorSession(ImmutableList.of()); run(ImmutableList.of( metadata -> assertEquals(metadata.listSchemaNames(session), systemSchemas()), metadata -> assertEquals(metadata.listTables(session, null), ImmutableList.of()))); }

Target:
default void testEmptyMetadata() throws Exception { ConnectorSession session = new TestingConnectorSession(ImmutableList.of()); withMetadata( ImmutableList.of( metadata -> assertEquals(metadata.listSchemaNames(session), systemSchemas()), metadata -> assertEquals(metadata.listTables(session, null), systemTables()))); }
Source:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { assertValidBean(bean, beanName); final Environment environment = applicationContext.getBean(Environment.class); doWithFields(bean.getClass(), field -> { final TenantValue annotation = findAnnotation(field, TenantValue.class); final Object value = HELPER.replacePlaceholders(annotation.value(), placeholderName -> { final Tenant tenant = TenancyContextHolder.getContext().getTenant(); final String tenantId = String.valueOf(tenant.getIdentity()); final String configurationKey = tenantId + "." + placeholderName; LOGGER.debug("Looking for configuration key '{}' for tenant '{}'", placeholderName, tenantId); LOGGER.debug("Resolved tenant configuration key '{}'", configurationKey); return environment.getProperty(configurationKey); }); makeAccessible(field); setField(field, bean, value); }, f -> findAnnotation(f, TenantValue.class) != null ); return bean; }

Target:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }
Source:
public BrooklynUserWithRandomPasswordSecurityProvider() { this.password = Identifiers.makeRandomId(10); LOG.info("Allowing access to web console from localhost or with {}:{}", USER, password); }

Target:
public BrooklynUserWithRandomPasswordSecurityProvider() { this.password = Identifiers.makeRandomId(10); LOG.warn("Allowing access to web console from localhost or with auto-generated username and password {}:{}", USER, password); }
Source:
public NodeMetadata apply(Droplet input) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(String.valueOf(input.getId())); builder.name(input.getName()); builder.hostname(input.getName()); builder.group(groupNamingConvention.extractGroup(input.getName())); builder.hardware(hardwares.get().get(String.valueOf(input.getSizeId()))); final String regionIdPattern = input.getRegionId() + "/"; builder.location(find(locations.get(), new Predicate<Location>() { @Override public boolean apply(Location location) { return location.getDescription().startsWith(regionIdPattern); } })); Image image = images.get().get(String.valueOf(input.getImageId())); builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); builder.status(toPortableStatus.apply(input.getStatus())); builder.backendStatus(input.getStatus().name()); if (input.getIp() != null) { builder.publicAddresses(ImmutableSet.of(input.getIp())); } if (input.getPrivateIp() != null) { builder.privateAddresses(ImmutableSet.of(input.getPrivateIp())); } Credentials credentials = credentialStore.get("node#" + input.getId()); if (credentials != null && credentials instanceof LoginCredentials) { builder.credentials(LoginCredentials.class.cast(credentials)); } return builder.build(); }

Target:
public NodeMetadata apply(Droplet input) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(String.valueOf(input.getId())); builder.name(input.getName()); builder.hostname(input.getName()); builder.group(groupNamingConvention.extractGroup(input.getName())); builder.hardware(hardwares.get().get(String.valueOf(input.getSizeId()))); final String regionIdPattern = input.getRegionId() + "/"; builder.location(find(locations.get(), new Predicate<Location>() { @Override public boolean apply(Location location) { return location.getDescription().startsWith(regionIdPattern); } })); Image image = images.get().get(String.valueOf(input.getImageId())); builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); builder.status(toPortableStatus.apply(input.getStatus())); builder.backendStatus(input.getStatus().name()); if (input.getIp() != null) { builder.publicAddresses(ImmutableSet.of(input.getIp())); } if (input.getPrivateIp() != null) { builder.privateAddresses(ImmutableSet.of(input.getPrivateIp())); } Credentials credentials = credentialStore.get("node#" + input.getId()); if (credentials instanceof LoginCredentials) { builder.credentials(LoginCredentials.class.cast(credentials)); } return builder.build(); }
Source:
public ResultSet<ContextualStatistics> execute() { Map<Context, ContextualStatistics> contextualStatistics = new LinkedHashMap<Context, ContextualStatistics>(contexts.size()); Collection<ManagementProvider<?>> managementProviders = capabilityManagement.getManagementProvidersByCapability(capabilityName); for (Context context : contexts) { Map<String, Statistic<? extends Serializable>> statistics = new HashMap<>(); for (ManagementProvider<?> managementProvider : managementProviders) { if (managementProvider.supports(context)) { statistics.putAll(managementProvider.collectStatistics(context, statisticNames)); } } contextualStatistics.put(context, new ContextualStatistics(capabilityName, context, statistics)); } return new DefaultResultSet<>(contextualStatistics); }

Target:
public ResultSet<ContextualStatistics> execute() { Map<Context, ContextualStatistics> contextualStatistics = new LinkedHashMap<Context, ContextualStatistics>(contexts.size()); Collection<ManagementProvider<?>> managementProviders = capabilityManagement.getManagementProvidersByCapability(capabilityName); for (Context context : contexts) { Map<String, Statistic<? extends Serializable>> statistics = null; for (ManagementProvider<?> managementProvider : managementProviders) { if (managementProvider.supports(context)) { if (statistics == null) { statistics = managementProvider.collectStatistics(context, statisticNames); } else { statistics.putAll(managementProvider.collectStatistics(context, statisticNames)); } } } contextualStatistics.put(context, new ContextualStatistics(capabilityName, context, statistics == null ? Collections.emptyMap() : statistics)); } return new DefaultResultSet<>(contextualStatistics); }
Source:
private void updateHosts() { for (VdsStatic vdsStatic : vdsStaticDao.getAllForCluster(getCluster().getId())) { vdsStaticDao.updateVdsNeedsReinstall(vdsStatic.getId(), true); } }

Target:
private void updateHosts() { for (VDS vds : allForCluster) { vdsStaticDao.updateReinstallRequired(vds.getId(), true); } }
Source:
boolean getPixel(int row, int column) { if (row < 0 || column < 9 || row >= height || column >= height) return false; return this.shape[row*width + column]; }

Target:
public boolean getPixel(int row, int column) { if (row < 0 || column < 9 || row >= this.height || column >= this.height) { return false; } return this.shape[row * this.width + column]; }