auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute(IProgressMonitor m) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(m); IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor actMonitor) throws CoreException { String taskName; if (branches.size() == 1) taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, branches .iterator().next().getName()); else { StringBuilder names = new StringBuilder(); for (Iterator<Ref> it = branches.iterator(); it.hasNext(); ) { Ref ref = it.next(); names.append(ref.getName()); if (it.hasNext()) names.append(", "); } taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, names); } actMonitor.beginTask(taskName, branches.size()); for (Ref branch : branches) { if (actMonitor.isCanceled()) { throw new OperationCanceledException( <START> "Deletion of branches canceled"); END> } try (Git git = new Git(repository)) { git.branchDelete().setBranchNames( branch.getName()).setForce(force).call(); status = OK; } catch (NotMergedException e) { status = REJECTED_UNMERGED; break; } catch (CannotDeleteCurrentBranchException e) { status = REJECTED_CURRENT; break; } catch (JGitInternalException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } actMonitor.worked(1); } actMonitor.done(); } }; ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, subMonitor); }</code><technical_language>externalize message</technical_language>

Target:
public void execute(IProgressMonitor m) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(m); IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor actMonitor) throws CoreException { String taskName; if (branches.size() == 1) taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, branches .iterator().next().getName()); else { StringBuilder names = new StringBuilder(); for (Iterator<Ref> it = branches.iterator(); it.hasNext(); ) { Ref ref = it.next(); names.append(ref.getName()); if (it.hasNext()) names.append(", "); } taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, names); } actMonitor.beginTask(taskName, branches.size()); for (Ref branch : branches) { if (actMonitor.isCanceled()) { throw new OperationCanceledException( CoreText.DeleteBranchOperation_Canceled); } try (Git git = new Git(repository)) { git.branchDelete().setBranchNames( branch.getName()).setForce(force).call(); status = OK; } catch (NotMergedException e) { status = REJECTED_UNMERGED; break; } catch (CannotDeleteCurrentBranchException e) { status = REJECTED_CURRENT; break; } catch (JGitInternalException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } catch (GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } actMonitor.worked(1); } actMonitor.done(); } }; ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, subMonitor); }
Source:
<code>public static <T> void verifyInvariance(String testName, BiPredicate<RoaringBitmap, RoaringBitmap> validity, int count, int maxKeys, BiFunction<RoaringBitmap, RoaringBitmap, T> left, BiFunction<RoaringBitmap, RoaringBitmap, T> right) { IntStream.range(0, count) .parallel() .forEach(i -> { RoaringBitmap one = randomBitmap(maxKeys); RoaringBitmap two = randomBitmap(maxKeys); if (validity.test(one, two)) { try { T res1 = left.apply(one, two); T res2 = right.apply(one, two); <START> if (!res1.equals(res2)) { <END> T res3 = left.apply(one, two); res1.equals(res2); Assert.assertEquals("Key " + i, res1, res2); } } catch (Throwable t) { Reporter.report(testName, ImmutableMap.of(), t, one, two); throw t; } } }); }</code><technical_language>This resolved- res1.equals(res2) line debugging code. revert this prior merging please? FYI @lemire</technical_language>

Target:
public static <T> void verifyInvariance(String testName, BiPredicate<RoaringBitmap, RoaringBitmap> validity, int count, int maxKeys, BiFunction<RoaringBitmap, RoaringBitmap, T> left, BiFunction<RoaringBitmap, RoaringBitmap, T> right) { IntStream.range(0, count) .parallel() .forEach(i -> { RoaringBitmap one = randomBitmap(maxKeys); RoaringBitmap two = randomBitmap(maxKeys); if (validity.test(one, two)) { try { Assert.assertEquals(left.apply(one, two), right.apply(one, two)); } catch (Throwable t) { Reporter.report(testName, ImmutableMap.of(), t, one, two); throw t; } } }); }
Source:
<code><START> public static synchronized void updateCache(AttestationValue value){ <END> if (exists(value.getHostName())){ AttestationValue cacheValue = getValueFromCache(value.getHostName()); cacheValue.setTrustLevel(value.getTrustLevel()); cacheValue.setVtime(value.getVtime()); } }</code><technical_language>Instead of "synchronzed" modifier rely synchronization of ConcurrentHashMap do this: AttestationValue cacheValue = attestationValues.get(value.getHostName()); if (cacheValue != null) { cacheValue.setTrustLeve(...); cacheVaue.setVtime(...); }</technical_language>

Target:
public void updateCache(AttestationValue value) { AttestationValue cacheValue = attestationValues.get(value.getHostName()); if (cacheValue != null) { cacheValue.setTrustLevel(value.getTrustLevel()); cacheValue.setVtime(value.getVtime()); } }
Source:
<code>public SerialPortProvider getPortProviderForPortName(URI portName) { PathType pathType = PathType.fromURI(portName); synchronized (this.portCreators) { String scheme = portName.getScheme(); Optional<SerialPortProvider> first = scheme != null ? portCreators.stream() .filter(provider -> provider.getAcceptedProtocols() .filter(prot -> prot.getScheme().equals(scheme)).count() > 0) .findFirst() : Optional.empty(); if (!first.isPresent() && scheme != null) { return null; } return first.orElseGet(() -> { <START> return portCreators.stream() <END> .filter(provider -> provider.getAcceptedProtocols() .filter(prot -> prot.getPathType().equals(pathType)).count() > 0) .findFirst().orElse(null); }); } }</code><technical_language>omit { return' } expression is one</technical_language>

Target:
public @NonNullByDefault({}) SerialPortProvider getPortProviderForPortName(URI portName) { PathType pathType = PathType.fromURI(portName); synchronized (this.portCreators) { String scheme = portName.getScheme(); Optional<SerialPortProvider> first = scheme != null ? portCreators.stream() .filter(provider -> provider.getAcceptedProtocols() .filter(prot -> prot.getScheme().equals(scheme)).count() > 0) .findFirst() : Optional.empty(); if (!first.isPresent() && scheme != null) { return null; } return first .orElse(portCreators.stream() .filter(provider -> provider.getAcceptedProtocols() .filter(prot -> prot.getPathType().equals(pathType)).count() > 0) .findFirst().orElse(null)); } }
Source:
<code>private void changeLanguage(String languageCode) { if (mLanguagePreference == null || TextUtils.isEmpty(languageCode)) return; Resources res = getResources(); Configuration conf = res.getConfiguration(); Locale currentLocale = conf.locale != null ? conf.locale : LanguageUtils.getCurrentDeviceLanguage(WordPress.getContext()); if (currentLocale.toString().equals(languageCode)) return; updateLanguagePreference(languageCode); Locale newLocale = WPPrefUtils.languageLocale(languageCode); conf.locale = newLocale; res.updateConfiguration(conf, res.getDisplayMetrics()); <START> mSettings.edit().putString(LANGUAGE_PREF_KEY, newLocale.toString()).apply(); <END> Map<String, Object> properties = new HashMap<>(); properties.put("app_locale", conf.locale.toString()); AnalyticsTracker.track(Stat.ACCOUNT_SETTINGS_LANGUAGE_CHANGED, properties); AnalyticsUtils.refreshMetadata(); Intent refresh = new Intent(getActivity(), getActivity().getClass()); startActivity(refresh); getActivity().setResult(LANGUAGE_CHANGED); getActivity().finish(); }</code><technical_language>Actually, flow more sense... I agree, sense if app is device language, app language change if user updates device language</technical_language>

Target:
private void changeLanguage(String languageCode) { if (mLanguagePreference == null || TextUtils.isEmpty(languageCode)) return; Resources res = getResources(); Configuration conf = res.getConfiguration(); Locale currentLocale = LanguageUtils.getCurrentDeviceLanguage(WordPress.getContext()); Locale newLocale = WPPrefUtils.languageLocale(languageCode); if (currentLocale.toString().equals(newLocale.getDisplayLanguage())) { return; } if (Locale.getDefault().toString().equals(newLocale.toString())) { mSettings.edit().remove(LANGUAGE_PREF_KEY).apply(); } else { mSettings.edit().putString(LANGUAGE_PREF_KEY, newLocale.toString()).apply(); } updateLanguagePreference(languageCode); conf.locale = newLocale; res.updateConfiguration(conf, res.getDisplayMetrics()); Map<String, Object> properties = new HashMap<>(); properties.put("app_locale", conf.locale.toString()); AnalyticsTracker.track(Stat.ACCOUNT_SETTINGS_LANGUAGE_CHANGED, properties); AnalyticsUtils.refreshMetadata(); Intent refresh = new Intent(getActivity(), getActivity().getClass()); startActivity(refresh); getActivity().setResult(LANGUAGE_CHANGED); getActivity().finish(); }
Source:
<code>private void runNodes(List<T> freeNodes) { List<IWorker<T>> runnables = m_factory.createWorkers(freeNodes); CountDownLatch latch = null; if (useLatches && runnables.size() > 1) { latch = new CountDownLatch(runnables.size()); } boolean latchUsed = false; for (IWorker<T> r : runnables) { m_activeRunnables.add(r); <START> if (latch != null && (r instanceof TestMethodWorker)) { <END> r.setLatch(latch); latchUsed = true; } ppp("Added to active runnable"); setStatus(r, Status.RUNNING); ppp("Executing: " + r); try { execute(r); } catch(Exception ex) { ex.printStackTrace(); } } if (latch != null && latchUsed) { try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }</code><technical_language>TestMethodWorker? suppose issue is for other workers</technical_language>

Target:
private void runNodes(List<T> freeNodes) { List<IWorker<T>> runnables = m_factory.createWorkers(freeNodes); CountDownLatch latch = null; if (useLatches && runnables.size() > 1) { latch = new CountDownLatch(runnables.size()); } boolean latchUsed = false; for (IWorker<T> r : runnables) { m_activeRunnables.add(r); if (latch != null && (r instanceof IThreadSynchronizer)) { ((IThreadSynchronizer)r).setLatch(latch); latchUsed = true; } setStatus(r, Status.RUNNING); try { execute(r); } catch(Exception ex) { ex.printStackTrace(); } } if (latch != null && latchUsed) { try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }
Source:
<code>public void onFileChanged(String endpointId, FileChangedEventDto dto) { switch (dto.getStatus()) { <START> case ADDED: <END> break; case MODIFIED: if (alteredFiles.addFile(removeProjectName(dto.getPath()), Status.MODIFIED)) { updateChangedFiles(alteredFiles); } break; case UNTRACKED: break; case NOT_MODIFIED: if (alteredFiles.removeFile(removeProjectName(dto.getPath()))) { updateChangedFiles(alteredFiles); } break; } }</code><technical_language>do need this case segment a body</technical_language>

Target:
public void onFileChanged(String endpointId, FileChangedEventDto dto) { switch (dto.getStatus()) { case MODIFIED: if (alteredFiles.addFile(removeProjectName(dto.getPath()), Status.MODIFIED)) { updateChangedFiles(alteredFiles); } break; case NOT_MODIFIED: if (alteredFiles.removeFile(removeProjectName(dto.getPath()))) { updateChangedFiles(alteredFiles); } break; default: } }
Source:
<code>private List<CourseAttributes> extractArchivedCourses(List<CourseDetailsBundle> courseBundles) { ArrayList<CourseAttributes> archivedCourses = new ArrayList<CourseAttributes>(); for (CourseDetailsBundle courseBundle : courseBundles) { CourseAttributes course = courseBundle.course; InstructorAttributes curInstructor = logic.getInstructorForGoogleId(course.id, account.googleId); boolean isCourseArchived; if (curInstructor.isArchived != null) { isCourseArchived = curInstructor.isArchived; } else { <START> isCourseArchived = course.isArchived; <END> } if (isCourseArchived) { archivedCourses.add(course); } } return archivedCourses; }</code><technical_language>This similar duplicated condition mentioned above</technical_language>

Target:
private List<CourseAttributes> extractArchivedCourses(List<CourseDetailsBundle> courseBundles) { ArrayList<CourseAttributes> archivedCourses = new ArrayList<CourseAttributes>(); for (CourseDetailsBundle courseBundle : courseBundles) { CourseAttributes course = courseBundle.course; InstructorAttributes curInstructor = logic.getInstructorForGoogleId(course.id, account.googleId); if (logic.isCourseArchived(course.id, curInstructor.googleId)) { archivedCourses.add(course); } } return archivedCourses; }
Source:
<code>void drawInteriorWithFrame_inView_searchfield(long id, long sel, NSRect cellFrame, long viewid) { <START> Control control = findBackgroundControl(); <END> if (control == null) control = this; Image image = control.backgroundImage; if (image != null && !image.isDisposed()) { NSGraphicsContext context = NSGraphicsContext.currentContext(); control.fillBackground (view, context, cellFrame, -1); } else { double searchFieldHeight = 22.0d; cellFrame.y = (cellFrame.height - searchFieldHeight) / 2.0d; cellFrame.height = searchFieldHeight; NSColor bgColor; if(background == null) { bgColor = NSColor.textBackgroundColor(); } else { bgColor = NSColor.colorWithDeviceRed (background [0], background [1], background [2], background [3]); } bgColor.setFill(); NSBezierPath.bezierPathWithRoundedRect(cellFrame, 4.0d, 4.0d).fill(); NSSearchField searchField = ((NSSearchField)view); NSCell _cell = (NSCell) searchField.cell(); SWTSearchFieldCell cell = new SWTSearchFieldCell(_cell.id); if(cell.searchButtonCell() != null) { cell.searchButtonCell().drawInteriorWithFrame(cell.searchButtonRectForBounds(cellFrame), view); } if(cell.cancelButtonCell() != null && ((NSSearchField) view).stringValue().length() > 0) { cell.cancelButtonCell().drawInteriorWithFrame(cell.cancelButtonRectForBounds(cellFrame), view); } } super.drawInteriorWithFrame_inView(id, sel, cellFrame, viewid); }</code><technical_language>Code is duplicated drawInteriorWithFrame_inView_text. combine in a single method add else part SWT.SEARCH check</technical_language>

Target:
void drawInteriorWithFrame_inView_searchfield(long id, long sel, NSRect cellFrame, long viewid) { if(background == null) { return; } cellFrame.x += 1.0; cellFrame.width -= 2.0; cellFrame.y = (cellFrame.height - 20.0) / 2.0; cellFrame.height = 20.0; NSBezierPath path = NSBezierPath.bezierPathWithRoundedRect(cellFrame, 2.0d, 2.0d); path.addClip(); NSColor bgColor = NSColor.colorWithDeviceRed (background [0], background [1], background [2], background [3]); bgColor.setFill(); path.fill(); NSSearchField searchField = ((NSSearchField)view); NSCell _cell = (NSCell) searchField.cell(); SWTSearchFieldCell cell = new SWTSearchFieldCell(_cell.id); if(cell.searchButtonCell() != null) { cell.searchButtonCell().drawInteriorWithFrame(cell.searchButtonRectForBounds(cellFrame), view); } if(cell.cancelButtonCell() != null && ((NSSearchField) view).stringValue().length() > 0) { cell.cancelButtonCell().drawInteriorWithFrame(cell.cancelButtonRectForBounds(cellFrame), view); } }
Source:
<code>public ElasticsearchWork<Long> count(Set<URLEncodedString> indexNames, Set<String> routingKeys, JsonObject payload) { <START> JsonObject filteredPayload = new JsonObject(); <END> filteredPayload.add( "query", JsonAccessor.root().property( "query" ).asObject().get( payload ).get() ); ElasticsearchRequest.Builder builder = ElasticsearchRequest.post() .multiValuedPathComponent( indexNames ) .pathComponent( Paths._COUNT ) .body( filteredPayload ); if ( !routingKeys.isEmpty() ) { builder.param( "_routing", routingKeys.stream().collect( Collectors.joining( "," ) ) ); } return new ElasticsearchStubWork<>( builder.build(), JsonAccessor.root().property( "count" ).asLong() ); }</code><technical_language>filtering in query class. fact payload is derived payload of a Search request is implementation detail of ElasticsearchSearchQuery taint other class... If trigger a count query else, expect payload correct start</technical_language>

Target:
public ElasticsearchWork<Long> count(Set<URLEncodedString> indexNames, Set<String> routingKeys, JsonObject payload) { ElasticsearchRequest.Builder builder = ElasticsearchRequest.post() .multiValuedPathComponent( indexNames ) .pathComponent( Paths._COUNT ) .body( payload ); if ( !routingKeys.isEmpty() ) { builder.param( "_routing", routingKeys.stream().collect( Collectors.joining( "," ) ) ); } return new ElasticsearchStubWork<>( builder.build(), JsonAccessor.root().property( "count" ).asLong() ); }
Source:
<code>protected final JComponent createCenterPanel() { JPanel iconPanel = new JBPanel(new BorderLayout()); iconPanel.add(new JBLabel(AllIcons.General.WarningDialog), BorderLayout.NORTH); JEditorPane messageEditorPane = new JEditorPane(); messageEditorPane.setEditorKit(UIUtil.getHTMLEditorKit()); messageEditorPane.setEditable(false); messageEditorPane.setPreferredSize(MESSAGE_EDITOR_PANE_PREFERRED_SIZE); messageEditorPane.setBorder(BorderFactory.createLineBorder(Gray._200)); String text = DIV_STYLE_MARGIN_5PX + getLegalNoticeMessage() + DIV; messageEditorPane.setText(text + "\n" + String.format(PRIVACY_POLICY)); JPanel legalNoticePanel = new JPanel(LEGAL_NOTICE_LAYOUT); legalNoticePanel.add(iconPanel, BorderLayout.WEST); legalNoticePanel.add(messageEditorPane, BorderLayout.CENTER); <START> messageEditorPane.addMouseListener(new MouseAdapter() { <END> @Override public void mouseClicked(final MouseEvent e) { BrowserUtil.browse(KODEBEAGLE_PRIVACY_POLICY); } }); return legalNoticePanel; }</code><technical_language>seems, set listener entire pane ! link</technical_language>

Target:
protected final JComponent createCenterPanel() { JPanel iconPanel = new JBPanel(new BorderLayout()); iconPanel.add(new JBLabel(AllIcons.General.WarningDialog), BorderLayout.NORTH); JEditorPane messageEditorPane = new JEditorPane(); messageEditorPane.setEditorKit(UIUtil.getHTMLEditorKit()); messageEditorPane.setEditable(false); messageEditorPane.setPreferredSize(MESSAGE_EDITOR_PANE_PREFERRED_SIZE); messageEditorPane.setBorder(BorderFactory.createLineBorder(Gray._200)); String text = DIV_STYLE_MARGIN_5PX + getLegalNoticeMessage() + "\n" + KODEBEAGLE_PRIVACY_POLICY + DIV; messageEditorPane.setText(text); JPanel legalNoticePanel = new JPanel(LEGAL_NOTICE_LAYOUT); legalNoticePanel.add(iconPanel, BorderLayout.WEST); legalNoticePanel.add(messageEditorPane, BorderLayout.CENTER); messageEditorPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(final HyperlinkEvent he) { if (he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { BrowserUtil.browse(he.getURL()); } } }); return legalNoticePanel; }
Source:
<code>private void commit() { if (getEntity() != null) { if (getWindow() != null) { return; } Snapshot snapshot = getSelectedItem(); ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().commitSnapshotTitle()); model.setHelpTag(HelpTag.commit_snapshot); model.setHashName("commit_snapshot"); model.setMessage(ConstantsManager.getInstance() .getMessages() .areYouSureYouWantToCommitSanpshot( DateTimeFormat.getFormat(DATE_FORMAT).format(snapshot.getCreationDate()), snapshot.getDescription())); UICommand <START> tempVar = <END> UICommand.createDefaultOkUiCommand("OnCommit", this); model.getCommands().add(tempVar); UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); model.getCommands().add(tempVar2); } }</code><technical_language>I suggest a bit more meaningful name. 'commitCommand'? 'commit'</technical_language>

Target:
private void commit() { if (getEntity() != null) { if (getWindow() != null) { return; } Snapshot snapshot = getSelectedItem(); ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().commitSnapshotTitle()); model.setHelpTag(HelpTag.commit_snapshot); model.setHashName("commit_snapshot"); model.setMessage(ConstantsManager.getInstance() .getMessages() .areYouSureYouWantToCommitSnapshot( DateTimeFormat.getFormat(DATE_FORMAT).format(snapshot.getCreationDate()), snapshot.getDescription())); model.getCommands().add(UICommand.createDefaultOkUiCommand("OnCommit", this)); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); } }
Source:
<code>public void addField() { <START> if (addFieldNameProperty.getValue() == null) { <END> return; } if (filterListProperty.getValue().stream().filter(item -> item.getField().equals(addFieldNameProperty.getValue())).findAny().isEmpty()) { filterListProperty.add(new XmpPrivacyItemModel(addFieldNameProperty.getValue())); addFieldNameProperty.setValue(null); } }</code><technical_language>StringUtil.isBlank catch whitespace well</technical_language>

Target:
public void addField() { if (addFieldProperty.getValue() == null) { return; } if (xmpFilterListProperty.getValue().stream().filter(item -> item.equals(addFieldProperty.getValue())).findAny().isEmpty()) { xmpFilterListProperty.add(addFieldProperty.getValue()); addFieldProperty.setValue(null); } }
Source:
<code>private Range <START> findRangeByBoundaries(long <END> rangeStart, long rangeEnd) { return ranges.stream().filter(range -> range.isSameRange(rangeStart, rangeEnd)).findFirst().orElse(null); }</code><technical_language>i suggest this method Range.isSameRange() name meaning. e.g. Range.isSameBoundaries()</technical_language>

Target:
private Range findRangeByBoundaries(long rangeStart, long rangeEnd) { return ranges.stream().filter(range -> range.isSameBoundaries(rangeStart, rangeEnd)).findFirst().orElse(null); }
Source:
<code><START> Integer getShapeIndex() { <END> if ((getShape() instanceof CaseManagementDiagramShapeView)) { return 0; } if (!(getParent() instanceof CaseManagementShapeView) || getShape() == null) { return null; } int index = ((CaseManagementShapeView) getParent()).getIndex(getShape()); return index >= 0 ? index : null; }</code><technical_language>avoid of null here, if possible... refactor for example OptionalInt</technical_language>

Target:
OptionalInt getShapeIndex() { if ((getShape() instanceof CaseManagementDiagramShapeView)) { return OptionalInt.of(0); } if (!(getParent() instanceof CaseManagementShapeView) || getShape() == null) { return OptionalInt.empty(); } int index = ((CaseManagementShapeView) getParent()).getIndex(getShape()); return index >= 0 ? OptionalInt.of(index) : OptionalInt.empty(); }
Source:
<code>public void specFailsWhenHostnameVerifierCannotVerify() { httpUrl = server.url("<LINK_0>"); mockApi = new XingApi.Builder().custom() .apiEndpoint(httpUrl) .build(); HostnameVerifier noGoogleVerifier = new HostnameVerifier() { @Override public boolean verify(String host, SSLSession sslSession) { <START> return !host.contains("google"); <END> } }; server.enqueue(new MockResponse().setResponseCode(200)); this.<Void, Void>builder(HttpMethod.GET, "/", false) .responseAs(Void.class) .errorAs(Void.class) .hostnameVerifier(noGoogleVerifier) .build() .completableResponse() .test() .assertError(SSLPeerUnverifiedException.class); }</code><technical_language>I suggest avoid !host.contains.. host.contains logic. Instead more explicitly. return false; return true; for next test. In case names alwaysFailsVerifier alwaysSucceedVerifier</technical_language>

Target:
public void specFailsWhenHostnameVerifierCannotVerify() { httpUrl = server.url("<LINK_0>"); mockApi = new XingApi.Builder().custom() .apiEndpoint(httpUrl) .build(); HostnameVerifier failingVerifier = new HostnameVerifier() { @Override public boolean verify(String host, SSLSession sslSession) { return false; } }; server.enqueue(new MockResponse().setResponseCode(200)); this.<Void, Void>builder(HttpMethod.GET, "/", false) .responseAs(Void.class) .errorAs(Void.class) .hostnameVerifier(failingVerifier) .build() .completableResponse() .test() .assertError(SSLPeerUnverifiedException.class); }
Source:
<code>public void testIntegerRetrievalFromHexadecimalProperty() { int hexaValue = 0x3000000; String wrongValue = "0xwel"; int defaultValue = 100; ZKClientConfig zkClientConfig = new ZKClientConfig(); zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, Integer.toString(hexaValue)); int result = zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); assertEquals(result, hexaValue); zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, wrongValue); try { result = zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); fail("NumberFormatException is expected"); } catch (NumberFormatException exception) { } zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, " " + hexaValue + " "); <START> zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); <END> assertEquals(result, hexaValue); zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, " " + hexaValue); zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); assertEquals(result, hexaValue); zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, hexaValue + " "); zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); assertEquals(result, hexaValue); }</code><technical_language>assign returned result result used</technical_language>

Target:
public void testIntegerRetrievalFromHexadecimalProperty() { int hexaValue = 0x3000000; String wrongValue = "0xwel"; int defaultValue = 100; ZKClientConfig zkClientConfig = new ZKClientConfig(); zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, Integer.toString(hexaValue)); int result = zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); assertEquals(result, hexaValue); zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, wrongValue); try { result = zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); fail("NumberFormatException is expected"); } catch (NumberFormatException exception) { } zkClientConfig.setProperty(ZKConfig.JUTE_MAXBUFFER, " " + hexaValue + " "); result = zkClientConfig.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue); assertEquals(result, hexaValue); }
Source:
<code>public int compare(SolverBenchmarkResult a, SolverBenchmarkResult b) { return Comparator .comparing(SolverBenchmarkResult::getFailureCount, Comparator.reverseOrder()) <START> .thenComparing(SolverBenchmarkResult::getTotalScore, new ResilientScoreComparator()) <END> .thenComparing(new WorstScoreSolverRankingComparator()) .compare(a, b); }</code><technical_language>This creates a new ResilientScoreComparator instance for compareTo call. compareTo calls, n instances sorting n sized list. ResilientScoreComparator worstScoreSolverRankingComparator stateless, 2 fields reuse those</technical_language>

Target:
public int compare(SolverBenchmarkResult a, SolverBenchmarkResult b) { return Comparator .comparing(SolverBenchmarkResult::getFailureCount, Comparator.reverseOrder()) .thenComparing(SolverBenchmarkResult::getTotalScore, resilientScoreComparator) .thenComparing(worstScoreSolverRankingComparator) .compare(a, b); }
Source:
<code><START> private Pair<Account, Container> getContainer() throws RestServiceException { <END> String accountName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_NAME, true); String containerName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_CONTAINER_NAME, true); Container container; Account account = accountService.getAccountByName(accountName); if (account == null) { throw new RestServiceException("Account " + accountName + " is not found.", RestServiceErrorCode.NotFound); } try { container = accountService.getContainer(accountName, containerName); } catch (AccountServiceException e) { throw new RestServiceException("Failed to get container " + containerName + " from account " + accountName, RestServiceErrorCode.getRestServiceErrorCode(e.getErrorCode())); } if (container == null) { throw new RestServiceException("Container " + containerName + " in account " + accountName + " is not found.", RestServiceErrorCode.NotFound); } return new Pair<>(account, container); }</code><technical_language>this method return account container? I setting account id in response, get container.getParentAccountId()</technical_language>

Target:
private Container getContainer() throws RestServiceException { String accountName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_ACCOUNT_NAME, true); String containerName = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.TARGET_CONTAINER_NAME, true); Container container; try { container = accountService.getContainer(accountName, containerName); } catch (AccountServiceException e) { throw new RestServiceException("Failed to get container " + containerName + " from account " + accountName, RestServiceErrorCode.getRestServiceErrorCode(e.getErrorCode())); } if (container == null) { throw new RestServiceException("Container " + containerName + " in account " + accountName + " is not found.", RestServiceErrorCode.NotFound); } return container; }
Source:
<code>public List<String> validateQuestionDetails(String courseId) { List<String> errors = new ArrayList<>(); if (generateOptionsFor == FeedbackParticipantType.NONE) { if (numOfMcqChoices < Const.FeedbackQuestion.MCQ_MIN_NUM_OF_CHOICES) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_NOT_ENOUGH_CHOICES + Const.FeedbackQuestion.MCQ_MIN_NUM_OF_CHOICES + "."); } if (hasAssignedWeights && mcqChoices.size() != mcqWeights.size()) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_INVALID_WEIGHT); <START> } <END> } return errors; }</code><technical_language>if (!hasAssignedWeights && (mcqWeights.size() != 0 || mcqOtherWeight != 0))</technical_language>

Target:
public List<String> validateQuestionDetails(String courseId) { List<String> errors = new ArrayList<>(); if (generateOptionsFor == FeedbackParticipantType.NONE) { if (numOfMcqChoices < Const.FeedbackQuestion.MCQ_MIN_NUM_OF_CHOICES) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_NOT_ENOUGH_CHOICES + Const.FeedbackQuestion.MCQ_MIN_NUM_OF_CHOICES + "."); } if (hasAssignedWeights && mcqChoices.size() != mcqWeights.size()) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_INVALID_WEIGHT); } if (!hasAssignedWeights && (!mcqWeights.isEmpty() || mcqOtherWeight != 0)) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_INVALID_WEIGHT); } if (hasAssignedWeights && !otherEnabled && mcqOtherWeight != 0) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_INVALID_WEIGHT); } if (hasAssignedWeights && !mcqWeights.isEmpty()) { for (double weight : mcqWeights) { if (weight < 0) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_INVALID_WEIGHT); } } if (otherEnabled && mcqOtherWeight < 0) { errors.add(Const.FeedbackQuestion.MCQ_ERROR_INVALID_WEIGHT); } } } return errors; }
Source:
<code>private static String scriptFor(JdbcSinkProperties properties) { StringBuilder result = new StringBuilder("DROP TABLE "); result.append(properties.getTableName()).append(";\n\n"); result.append("CREATE TABLE ").append(properties.getTableName()).append('('); int i = 0; for (String column : properties.getColumns().keySet()) { if (i++ > 0) { result.append(", "); } result.append(column).append(" VARCHAR(2000)"); } result.append(");\n"); <START> System.out.println(result); <END> return result.toString(); }</code><technical_language>this system.out removed (or replaced logging)</technical_language>

Target:
private static String scriptFor(JdbcSinkProperties properties) { StringBuilder result = new StringBuilder("DROP TABLE "); result.append(properties.getTableName()).append(";\n\n"); result.append("CREATE TABLE ").append(properties.getTableName()).append('('); int i = 0; for (String column : properties.getColumns().keySet()) { if (i++ > 0) { result.append(", "); } result.append(column).append(" VARCHAR(2000)"); } result.append(");\n"); logger.debug("Generated the following initializing script for table {}:\n{}", properties.getTableName(), result); return result.toString(); }
Source:
<code>public Integer evaluate(String string, String sub, Integer fromIndex) { <START> return string.indexOf(sub, fromIndex) + 1; <END> }</code><technical_language>fromIndex - 1 fromIndex starts 1</technical_language>

Target:
public Integer evaluate(String string, String sub, Integer fromIndex) { return string.indexOf(sub, fromIndex - 1) + 1; }
Source:
<code>public PageSet<? extends StorageMetadata> apply(PaginatedVaultCollection vaults) { return new PageSetImpl<StorageMetadata>(Iterables.transform(vaults, new VaultMetadataToStorageMetadata()), <START> vaults.nextMarker().isPresent() ? (String) vaults.nextMarker().get() : null); <END> }</code><technical_language>Call (String) vaults.nextMarker().orNull() instead</technical_language>

Target:
public PageSet<? extends StorageMetadata> apply(PaginatedVaultCollection vaults) { return new PageSetImpl<StorageMetadata>(Iterables.transform(vaults, new VaultMetadataToStorageMetadata()), (String) vaults.nextMarker().orNull()); }
Source:
<code>protected Spanned doInBackground(Void... params) { Spanned contentSpannable; if (getActivity() == null) { return null; } <START> PostModel post = ((EditPostActivity) getActivity()).getPost(); <END> if (post == null) { return null; } String postTitle = "<h1>" + post.getTitle() + "</h1>"; String postContent = postTitle + post.getContent(); if (post.isLocalDraft()) { contentSpannable = WPHtml.fromHtml( postContent.replaceAll("\uFFFC", ""), getActivity(), post, Math.min(mTextView.getWidth(), mTextView.getHeight()) ); } else { String htmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"webview.css\" /></head><body><div id=\"container\">%s</div></body></html>"; htmlText = String.format(htmlText, StringUtils.addPTags(postContent)); contentSpannable = new SpannableString(htmlText); } return contentSpannable; }</code><technical_language>a bit pass PostModel Activity Fragment, fragment reusable</technical_language>

Target:
protected Spanned doInBackground(Void... params) { Spanned contentSpannable; if (getActivity() == null) { return null; } if (mPost == null) { return null; } String postTitle = "<h1>" + mPost.getTitle() + "</h1>"; String postContent = postTitle + mPost.getContent(); if (mPost.isLocalDraft()) { contentSpannable = WPHtml.fromHtml( postContent.replaceAll("\uFFFC", ""), getActivity(), mPost, Math.min(mTextView.getWidth(), mTextView.getHeight()) ); } else { String htmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><html><head><link rel=\"stylesheet\" " + "type=\"text/css\" href=\"webview.css\" /></head><body><div " + "id=\"container\">%s</div></body></html>"; htmlText = String.format(htmlText, StringUtils.addPTags(postContent)); contentSpannable = new SpannableString(htmlText); } return contentSpannable; }
Source:
<code>private String getEULAText() { try { String tfLocation = TfTool.getLocation(); if (tfLocation == null) { return null; } String path = Path.combine(Path.combine(Path.getDirectoryName(tfLocation), "lib"), "com.microsoft.tfs.client.common.jar"); <START> JarFile jar = new JarFile(path); <END> InputStream stream = jar.getInputStream(jar.getEntry("eula.txt")); BufferedReader rdr = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8)); StringBuilder result = new StringBuilder(); String line; while ((line = rdr.readLine()) != null) { result.append(line).append("\n"); } return result.toString(); } catch (IOException e) { System.out.println(e.getMessage()); } return null; }</code><technical_language>tfLocation + "lib" + "com.microsoft.tfs.client.common.jar" location of JAR? super speed Java works, so... happen if path lead a file disk? new JarFile(...) throw exception? I suppose IOException, catch (IOException) handle it, println side effects (think scripts), is this want / is acceptable</technical_language>

Target:
private String getEULAText() { JarFile jarFile = null; InputStream eulaStream = null; String jarName = "com.microsoft.tfs.client.common.jar"; try { String tfLocation = TfTool.getLocation(); if (tfLocation == null) { return null; } String path = Path.combine(Path.combine(Path.getDirectoryName(tfLocation), "lib"), jarName); jarFile = new JarFile(path); eulaStream = jarFile.getInputStream(jarFile.getEntry("eula.txt")); return StreamUtil.readText(eulaStream, Charsets.UTF_8); } catch (IOException e) { logger.error("Cannot read EULA text from: " + jarName, e); } finally { if (eulaStream != null) { try { eulaStream.close(); } catch (IOException e) { logger.error("Cannot eulaStream properly", e); } } if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { logger.error("Cannot jarFile properly", e); } } } return null; }
Source:
<code>public boolean cancel(final Exception rootReason) { if (transitionCancel(rootReason)) { final Exception reason = new CancellationException(rootReason); try { traceFailure(reason); } catch (Throwable ex) { <START> LOGGER.warn("Exception thrown in logging trace for failure!", ex); <END> } getSettableDelegate().fail(reason); return true; } return false; }</code><technical_language>issue original reason logged due error in toString. Do concern logging _new_ error issue? stages this? 1. Catch logging error, try log error. 2. Catch _that_ error if happens, log a generic, static message</technical_language>

Target:
public boolean cancel(final Exception rootReason) { if (transitionCancel(rootReason)) { final Exception reason = new CancellationException(rootReason); try { traceFailure(reason); } catch (Throwable ex) { LOGGER.warn("Exception thrown in logging trace for failure!", ex); } finally { getSettableDelegate().fail(reason); } return true; } return false; }
Source:
<code>public PageableResult search(RequestContext context) throws ResponseException { String source = context.getParameter("source"); String code = context.getParameter("code"); String name = context.getParameter("name"); String searchType = context.getParameter("searchType"); ConceptSource conceptSource = conceptService.getConceptSourceByUuid(source); if (conceptSource == null) { conceptSource = conceptService.getConceptSourceByName(source); } if (conceptSource == null) { return new EmptySearchResult(); } if (code != null || name != null) { if(SEARCH_TYPE_STARTS_WITH.equals(searchType)){ return searchStartsWith(context, code, name, conceptSource); } else { return searchEquals(context, code, name, conceptSource); <START> } <END> } else { List<ConceptReferenceTerm> terms = conceptService.getConceptReferenceTerms(null, conceptSource, context.getStartIndex(), context.getLimit(), context.getIncludeAll()); int count = conceptService.getCountOfConceptReferenceTerms(null, conceptSource, context.getIncludeAll()); boolean hasMore = count > (context.getStartIndex() + context.getLimit()); return new AlreadyPaged<ConceptReferenceTerm>(context, terms, hasMore); } }</code><technical_language>Please throw ResponseException if searchType is valid (neither equals startsWith empty)</technical_language>

Target:
public PageableResult search(RequestContext context) throws ResponseException { String source = context.getParameter("source"); String code = context.getParameter("code"); String name = context.getParameter("name"); String searchType = context.getParameter("searchType"); if(searchType!=null&&!SEARCH_TYPE_EQUALS.equals(searchType)&&!SEARCH_TYPE_STARTS_WITH.equals(searchType)){ throw new InvalidSearchException("Invalid searchType parameter"); } ConceptSource conceptSource = conceptService.getConceptSourceByUuid(source); if (conceptSource == null) { conceptSource = conceptService.getConceptSourceByName(source); } if (conceptSource == null) { return new EmptySearchResult(); } if (code != null || name != null) { if(SEARCH_TYPE_STARTS_WITH.equals(searchType)){ return searchStartsWith(context, code, name, conceptSource); } else { return searchEquals(context, code, name, conceptSource); } } else { List<ConceptReferenceTerm> terms = conceptService.getConceptReferenceTerms(null, conceptSource, context.getStartIndex(), context.getLimit(), context.getIncludeAll()); int count = conceptService.getCountOfConceptReferenceTerms(null, conceptSource, context.getIncludeAll()); boolean hasMore = count > (context.getStartIndex() + context.getLimit()); return new AlreadyPaged<ConceptReferenceTerm>(context, terms, hasMore); } }
Source:
<code>private void setScreenOrientationProperty(String text) { if (hasProperty(PROPERTY_NAME_WIDTH) && hasProperty(PROPERTY_NAME_HEIGHT) && hasProperty(PROPERTY_NAME_SCROLLABLE)) { if (text.equalsIgnoreCase("landscape")) { screenWidth = LANDSCAPE_WIDTH; screenHeight = LANDSCAPE_HEIGHT; landscape = true; <START> phoneWidget.setStyleName("ode-SimpleMockFormPhoneLandscape"); <END> } else { screenWidth = PORTRAIT_WIDTH; screenHeight = PORTRAIT_HEIGHT; landscape = false; phoneWidget.setStyleName("ode-SimpleMockFormPhonePortrait"); } usableScreenHeight = screenHeight - PhoneBar.HEIGHT - titleBar.getHeight() - NavigationBar.HEIGHT; resizePanel(screenWidth, screenHeight); changeProperty(PROPERTY_NAME_WIDTH, "" + screenWidth); boolean scrollable = Boolean.parseBoolean(getPropertyValue(PROPERTY_NAME_SCROLLABLE)); if (!scrollable) { changeProperty(PROPERTY_NAME_HEIGHT, "" + usableScreenHeight); } } }</code><technical_language>Need logic similar changePreviewSize. If select Monitor sizing, switch landscape, image shows is phone image scaled up</technical_language>

Target:
private void setScreenOrientationProperty(String text) { if (hasProperty(PROPERTY_NAME_WIDTH) && hasProperty(PROPERTY_NAME_HEIGHT) && hasProperty(PROPERTY_NAME_SCROLLABLE)) { if (text.equalsIgnoreCase("landscape")) { screenWidth = LANDSCAPE_WIDTH; screenHeight = LANDSCAPE_HEIGHT; landscape = true; setPhoneStyle(); } else { screenWidth = PORTRAIT_WIDTH; screenHeight = PORTRAIT_HEIGHT; landscape = false; setPhoneStyle(); } usableScreenHeight = screenHeight - PhoneBar.HEIGHT - titleBar.getHeight() - NavigationBar.HEIGHT; resizePanel(screenWidth, screenHeight); changeProperty(PROPERTY_NAME_WIDTH, "" + screenWidth); boolean scrollable = Boolean.parseBoolean(getPropertyValue(PROPERTY_NAME_SCROLLABLE)); if (!scrollable) { changeProperty(PROPERTY_NAME_HEIGHT, "" + usableScreenHeight); } } }
Source:
<code>public static void validateTimestampFieldMapping(String timestampFieldName, MapperService mapperService) { MappedFieldType timestampFieldMapper = mapperService.fieldType(timestampFieldName); if (timestampFieldMapper == null) { throw new IllegalArgumentException("expected timestamp field [" + timestampFieldName + "], but found no timestamp field"); } String type = timestampFieldMapper.typeName(); if (ALLOWED_TIMESTAMPFIELD_TYPES.contains(type) == false) { <START> throw new IllegalArgumentException("expected timestamp field [" + timestampFieldName + "] to be of types [" + ALLOWED_TIMESTAMPFIELD_TYPES + "], but instead found type [" + type + "]"); <END> } }</code><technical_language>Super minor: suggestion throw new IllegalArgumentException("expected timestamp field [" + timestampFieldName + "] of types " + ALLOWED_TIMESTAMPFIELD_TYPES + ", instead type [" + type + "]"); avoid [[]] double brackets</technical_language>

Target:
public static void validateTimestampFieldMapping(String timestampFieldName, MapperService mapperService) { MappedFieldType timestampFieldMapper = mapperService.fieldType(timestampFieldName); if (timestampFieldMapper == null) { throw new IllegalArgumentException("expected timestamp field [" + timestampFieldName + "], but found no timestamp field"); } String type = timestampFieldMapper.typeName(); if (ALLOWED_TIMESTAMPFIELD_TYPES.contains(type) == false) { throw new IllegalArgumentException("expected timestamp field [" + timestampFieldName + "] to be of types " + ALLOWED_TIMESTAMPFIELD_TYPES + ", but instead found type [" + type + "]"); } }
Source:
<code>protected ClusterManager(String zkAddr, String clusterName, String instanceName, InstanceType type) { super(clusterName, instanceName, type, zkAddr); _clusterName = clusterName; _instanceName = instanceName; _type = type; _uid = UID.getAndIncrement(); <START> LOG.info("ClusterManager_watcher_{}_{}_{}_{} created, stacktrace {}", _clusterName, _instanceName, _type.name(), _uid, Thread.currentThread().getStackTrace()); <END> }</code><technical_language>I watcher is created here. created sync start is called</technical_language>

Target:
protected ClusterManager(String zkAddr, String clusterName, String instanceName, InstanceType type) { super(clusterName, instanceName, type, zkAddr); _clusterName = clusterName; _instanceName = instanceName; _type = type; _uid = UID.getAndIncrement(); }
Source:
<code>private static CliOptions convertCliToPojo(CommandLine cmdLine, List<File> filesToProcess) { final CliOptions conf = new CliOptions(); conf.format = cmdLine.getOptionValue(OPTION_F_NAME); if (conf.format == null) { conf.format = PLAIN_FORMAT_NAME; } conf.outputLocation = cmdLine.getOptionValue(OPTION_O_NAME); conf.configLocation = cmdLine.getOptionValue(OPTION_C_NAME); conf.propertiesLocation = cmdLine.getOptionValue(OPTION_P_NAME); conf.files = filesToProcess; <START> conf.omitIgnoredModules = !cmdLine.hasOption(OPTION_EXECUTE_IGNORED_MODULES_NAME); <END> return conf; }</code><technical_language>executeIgnoredModules</technical_language>

Target:
private static CliOptions convertCliToPojo(CommandLine cmdLine, List<File> filesToProcess) { final CliOptions conf = new CliOptions(); conf.format = cmdLine.getOptionValue(OPTION_F_NAME); if (conf.format == null) { conf.format = PLAIN_FORMAT_NAME; } conf.outputLocation = cmdLine.getOptionValue(OPTION_O_NAME); conf.configLocation = cmdLine.getOptionValue(OPTION_C_NAME); conf.propertiesLocation = cmdLine.getOptionValue(OPTION_P_NAME); conf.files = filesToProcess; conf.executeIgnoredModules = cmdLine.hasOption(OPTION_EXECUTE_IGNORED_MODULES_NAME); return conf; }
Source:
<code>private static Repository getRepositoryOfProjects(Collection<?> collection, boolean single) { Repository repo = null; for (Object element : collection) { <START> IProject project = AdapterUtils.adapt(element, IProject.class); if (project != null) { Repository r = getRepositoryOfMapping(project); if (single && r != null && repo != null && r != repo) { return null; } else if (r != null) { repo = r; } } else { <END> IContainer container = AdapterUtils.adapt(element, IContainer.class); RepositoryMapping mapping = null; if (container != null) { mapping = RepositoryMapping.getMapping(container); } if (container != null && mapping != null && container.equals(mapping.getContainer())) { Repository r = mapping.getRepository(); if (single && r != null && repo != null && r != repo) { return null; } else if (r != null) { repo = r; } } else { IWorkingSet workingSet = AdapterUtils.adapt(element, IWorkingSet.class); if (workingSet != null) { for (IAdaptable adaptable : workingSet.getElements()) { Repository r = getRepositoryOfProject(adaptable); if (single && r != null && repo != null && r != repo) { return null; } else if (r != null) { repo = r; } } } } } } return repo; }</code><technical_language>This branch deleted; IContainer case handle IProjects</technical_language>

Target:
private static Repository getRepositoryOfProjects(Collection<?> collection, boolean single) { Repository repo = null; for (Object element : collection) { IContainer container = AdapterUtils.adapt(element, IContainer.class); RepositoryMapping mapping = null; if (container != null) { mapping = RepositoryMapping.getMapping(container); } if (container != null && mapping != null && container.equals(mapping.getContainer())) { Repository r = mapping.getRepository(); if (single && r != null && repo != null && r != repo) { return null; } else if (r != null) { repo = r; } } else { IWorkingSet workingSet = AdapterUtils.adapt(element, IWorkingSet.class); if (workingSet != null) { for (IAdaptable adaptable : workingSet.getElements()) { Repository r = getRepositoryOfProject(adaptable); if (single && r != null && repo != null && r != repo) { return null; } else if (r != null) { repo = r; } } } } } return repo; }