auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBranchIsDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(null, c, "foo", true, false, false))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); FreeStyleProject master = prj.getItem("master"); FreeStyleProject feature = prj.getItem("feature"); r.waitUntilNoActivity(); assertThat("The master branch was built", master.getLastBuild(), notNullValue()); assertThat("The master branch was built", master.getLastBuild().getNumber(), is(1)); assertThat("The feature branch was built", feature.getLastBuild(), notNullValue()); assertThat("The feature branch was built", feature.getLastBuild().getNumber(), is(1)); c.deleteBranch("foo", "feature"); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); assertThat("Indexing applies dead branch cleanup", prj.getItems(), containsInAnyOrder(master)); assertThat("Indexing applies dead branch cleanup", <START> prj.getItems(), not(containsInAnyOrder(feature))); <END> } }</code><technical_language>java assertThat("Indexing applies dead branch cleanup", prj.getItems(), allOf( containsInAnyOrder(master), not(containsInAnyOrder(feature))));</technical_language>

Target:
public void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBranchIsDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(null, c, "foo", true, false, false))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); FreeStyleProject master = prj.getItem("master"); FreeStyleProject feature = prj.getItem("feature"); r.waitUntilNoActivity(); assertThat("The master branch was built", master.getLastBuild(), notNullValue()); assertThat("The master branch was built", master.getLastBuild().getNumber(), is(1)); assertThat("The feature branch was built", feature.getLastBuild(), notNullValue()); assertThat("The feature branch was built", feature.getLastBuild().getNumber(), is(1)); c.deleteBranch("foo", "feature"); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); assertThat("Indexing applies dead branch cleanup", prj.getItems(), allOf( containsInAnyOrder(master), not(containsInAnyOrder(feature)))); } }
Source:
<code>public CommCareTransactionParserFactory(MockUserDataSandbox sandbox) { this.sandbox = sandbox; fixtureParser = new TransactionParserFactory() { FixtureXmlParser created = null; public TransactionParser getParser(KXmlParser parser) { if (created == null) { created = new FixtureXmlParser(parser) { private IStorageUtilityIndexed<FormInstance> fixtureStorage; @Override public IStorageUtilityIndexed<FormInstance> storage() { if (fixtureStorage == null) { fixtureStorage = CommCareTransactionParserFactory.this.sandbox.getUserFixtureStorage(); } return fixtureStorage; } }; } return created; } }; <START> this.initUserParser(); <END> this.initCaseParser(); this.initStockParser(); }</code><technical_language>is a reason fixture parser in a initFixtureParser() function others</technical_language>

Target:
public CommCareTransactionParserFactory(MockUserDataSandbox sandbox) { this.sandbox = sandbox; this.initFixtureParser(); this.initUserParser(); this.initCaseParser(); this.initStockParser(); }
Source:
<code>public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { String contentType = this.jettyRequest.getHeaders().getField(HttpHeader.CONTENT_TYPE).getValue(); ReactiveRequest.Content content = ReactiveRequest.Content.fromPublisher(Flux .from(body) .flatMap(publisher -> publisher) <START> .map(buffer -> new ContentChunk(buffer.asByteBuffer())), contentType); <END> this.reactiveRequest = ReactiveRequest.newBuilder(this.jettyRequest).content(content).build(); return doCommit(this::completes); }</code><technical_language>Release needs happen well</technical_language>

Target:
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { String contentType = this.jettyRequest.getHeaders().getField(HttpHeader.CONTENT_TYPE).getValue(); Flux<ContentChunk> chunks = Flux.from(body).flatMap(Function.identity()).map(this::toContentChunk); ReactiveRequest.Content content = ReactiveRequest.Content.fromPublisher(chunks, contentType); this.reactiveRequest = ReactiveRequest.newBuilder(this.jettyRequest).content(content).build(); return doCommit(this::completes); }
Source:
<code>private static void runNoteOnStart(ZeppelinConfiguration conf) throws IOException, InterruptedException { String noteIdToRun = conf.getNotebookRunId(); if (!Strings.isEmpty(noteIdToRun)) { NotebookService notebookService = (NotebookService) ServiceLocatorUtilities.getService( sharedServiceLocator, NotebookService.class.getName()); ServiceContext serviceContext; <START> String base64EncodedJsonSerializedServiceContext = conf.getNotebookRunServiceContext(); <END> if (Strings.isEmpty(base64EncodedJsonSerializedServiceContext)) { LOG.info("No service context provided. use ANONYMOUS"); serviceContext = new ServiceContext(AuthenticationInfo.ANONYMOUS, new HashSet<String>() {}); } else { serviceContext = new Gson().fromJson( new String(Base64.getDecoder().decode(base64EncodedJsonSerializedServiceContext)), ServiceContext.class); } boolean success = notebookService.runNote(noteIdToRun, serviceContext, new ServiceCallback<Paragraph>() { @Override public void onStart(String message, ServiceContext context) throws IOException { } @Override public void onSuccess(Paragraph result, ServiceContext context) throws IOException { } @Override public void onFailure(Exception ex, ServiceContext context) throws IOException { } }); if (conf.getNotebookRunAutoShutdown()) { Thread t = shutdown(conf); t.start(); t.join(); System.exit(success ? 0 : 1); } } }</code><technical_language>add logging show zeppelin server is running note started</technical_language>

Target:
private static void runNoteOnStart(ZeppelinConfiguration conf) throws IOException, InterruptedException { String noteIdToRun = conf.getNotebookRunId(); if (!Strings.isEmpty(noteIdToRun)) { LOG.info("Running note on start", noteIdToRun); NotebookService notebookService = (NotebookService) ServiceLocatorUtilities.getService( sharedServiceLocator, NotebookService.class.getName()); ServiceContext serviceContext; String base64EncodedJsonSerializedServiceContext = conf.getNotebookRunServiceContext(); if (Strings.isEmpty(base64EncodedJsonSerializedServiceContext)) { LOG.info("No service context provided. use ANONYMOUS"); serviceContext = new ServiceContext(AuthenticationInfo.ANONYMOUS, new HashSet<String>() {}); } else { serviceContext = new Gson().fromJson( new String(Base64.getDecoder().decode(base64EncodedJsonSerializedServiceContext)), ServiceContext.class); } boolean success = notebookService.runAllParagraphs(noteIdToRun, null, serviceContext, new ServiceCallback<Paragraph>() { @Override public void onStart(String message, ServiceContext context) throws IOException { } @Override public void onSuccess(Paragraph result, ServiceContext context) throws IOException { } @Override public void onFailure(Exception ex, ServiceContext context) throws IOException { } }); if (conf.getNotebookRunAutoShutdown()) { Thread t = shutdown(conf); t.start(); t.join(); System.exit(success ? 0 : 1); } } }
Source:
<code>private void updateRespondents(FeedbackSessionAttributes session, Set<InstructorAttributes> courseInstructors, Set<FeedbackQuestionAttributes> sessionQuestions, Set<FeedbackResponseAttributes> sessionResponses) { String sessionKey = makeSessionKey(session.getFeedbackSessionName(), session.getCourseId()); SetMultimap<String, String> instructorQuestionKeysMap = HashMultimap.create(); for (InstructorAttributes instructor : courseInstructors) { List<FeedbackQuestionAttributes> questionsForInstructor = feedbackQuestionsLogic <START> .getFeedbackQuestionsForInstructor(new ArrayList(sessionQuestions), session.isCreator(instructor.email)); <END> List<String> questionKeys = makeQuestionKeys(questionsForInstructor, sessionKey); instructorQuestionKeysMap.putAll(instructor.email, questionKeys); } Set<String> respondingInstructors = new HashSet<>(); Set<String> respondingStudents = new HashSet<>(); for (FeedbackResponseAttributes response : sessionResponses) { String respondent = response.giver; String responseQuestionNumber = response.feedbackQuestionId; String responseQuestionKey = makeQuestionKey(sessionKey, responseQuestionNumber); Set<String> instructorQuestionKeys = instructorQuestionKeysMap.get(respondent); if (instructorQuestionKeys.contains(responseQuestionKey)) { respondingInstructors.add(respondent); } else { respondingStudents.add(respondent); } } session.setRespondingInstructorList(respondingInstructors); session.setRespondingStudentList(respondingStudents); }</code><technical_language>new ArrayList<> here</technical_language>

Target:
private void updateRespondents(FeedbackSessionAttributes session, Set<InstructorAttributes> courseInstructors, Set<FeedbackQuestionAttributes> sessionQuestions, Set<FeedbackResponseAttributes> sessionResponses) { String sessionKey = makeSessionKey(session.getFeedbackSessionName(), session.getCourseId()); SetMultimap<String, String> instructorQuestionKeysMap = HashMultimap.create(); for (InstructorAttributes instructor : courseInstructors) { List<FeedbackQuestionAttributes> questionsForInstructor = feedbackQuestionsLogic.getFeedbackQuestionsForInstructor( new ArrayList<>(sessionQuestions), session.isCreator(instructor.email)); List<String> questionKeys = makeQuestionKeys(questionsForInstructor, sessionKey); instructorQuestionKeysMap.putAll(instructor.email, questionKeys); } Set<String> respondingInstructors = new HashSet<>(); Set<String> respondingStudents = new HashSet<>(); for (FeedbackResponseAttributes response : sessionResponses) { String respondent = response.giver; String responseQuestionNumber = response.feedbackQuestionId; String responseQuestionKey = makeQuestionKey(sessionKey, responseQuestionNumber); Set<String> instructorQuestionKeys = instructorQuestionKeysMap.get(respondent); if (instructorQuestionKeys.contains(responseQuestionKey)) { respondingInstructors.add(respondent); } else { respondingStudents.add(respondent); } } session.setRespondingInstructorList(respondingInstructors); session.setRespondingStudentList(respondingStudents); }
Source:
<code>public String saveDefaults(WebRequest request, @RequestParam("theme") String theme, @RequestParam("locale") String locale) throws Exception { boolean localeInList = false; String allowedLocales = Context.getAdministrationService().getGlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST); String[] allowedLocalesList = allowedLocales.split(","); GlobalProperty themeGP = Context.getAdministrationService().getGlobalPropertyObject( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_THEME); themeGP.setPropertyValue(theme); Context.getAdministrationService().saveGlobalProperty(themeGP); for (String loc : allowedLocalesList) { loc = loc.trim(); if (loc.equals(locale)) { localeInList = true; GlobalProperty localeGP = Context.getAdministrationService().getGlobalPropertyObject( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE); localeGP.setPropertyValue(locale); Context.getAdministrationService().saveGlobalProperty(localeGP); break; } } <START> if (localeInList) { <END> request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, Context.getMessageSourceService().getMessage( "LocalesAndThemes.saved"), WebRequest.SCOPE_SESSION); } else { request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, Context.getMessageSourceService().getMessage( "LocalesAndThemes.localeError"), WebRequest.SCOPE_SESSION); } return "redirect:/admin/maintenance/localesAndThemes.form"; }</code><technical_language>change this</technical_language>

Target:
public String saveDefaults(WebRequest request, @RequestParam("theme") String theme, @RequestParam("locale") String locale) throws Exception { boolean localeInList = false; String allowedLocales = Context.getAdministrationService().getGlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST); String[] allowedLocalesList = allowedLocales.split(","); GlobalProperty themeGP = Context.getAdministrationService().getGlobalPropertyObject( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_THEME); themeGP.setPropertyValue(theme); Context.getAdministrationService().saveGlobalProperty(themeGP); for (String loc : allowedLocalesList) { loc = loc.trim(); if (loc.equals(locale)) { localeInList = true; GlobalProperty localeGP = Context.getAdministrationService().getGlobalPropertyObject( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE); localeGP.setPropertyValue(locale); Context.getAdministrationService().saveGlobalProperty(localeGP); break; } } if (localeInList || StringUtils.isBlank(locale)) { request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, Context.getMessageSourceService().getMessage( "LocalesAndThemes.saved"), WebRequest.SCOPE_SESSION); } else { request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, Context.getMessageSourceService().getMessage( "LocalesAndThemes.localeError"), WebRequest.SCOPE_SESSION); } return "redirect:/admin/maintenance/localesAndThemes.form"; }
Source:
<code>public void startup() throws Exception { String sessionId = options.getSessionId(); if (sessionId == null) { sessionId = createSessionId(); } data.setSessionId(sessionId); output = createAgentOutput(); <START> output.startup(options, data); <END> if (options.getJmx()) { jmxRegistration = new JmxRegistration(this); } }</code><technical_language>@marchof this output in addition throwing of exception for case caller swallows exception, e.g. offline instrumented classes of app of app-server? WDYT</technical_language>

Target:
public void startup() throws Exception { try { String sessionId = options.getSessionId(); if (sessionId == null) { sessionId = createSessionId(); } data.setSessionId(sessionId); output = createAgentOutput(); output.startup(options, data); if (options.getJmx()) { jmxRegistration = new JmxRegistration(this); } } catch (final Exception e) { logger.logExeption(e); throw e; } }
Source:
<code>public void createLineModelsFromMap(Map<String, Object> keyValueMap) { List<KeyValueLineModel> lineModels = new ArrayList<>(); if (useEditableKey) { for <START> (String key : keyValueMap.keySet()) { <END> KeyValueLineModel lineModel = createNewLineModel(null); lineModel.getValue().setEntity(key); lineModel.getEditableKey().setEntity((String) keyValueMap.get(key)); lineModels.add(lineModel); } } setItems(lineModels); }</code><technical_language>Iterate entrySet avoid invoking a get map iteration get (findbugs)</technical_language>

Target:
public void createLineModelsFromMap(Map<String, Object> keyValueMap) { List<KeyValueLineModel> lineModels = new ArrayList<>(); if (useEditableKey) { for (Map.Entry<String, Object> entry : keyValueMap.entrySet()) { KeyValueLineModel lineModel = createNewLineModel(null); lineModel.getValue().setEntity(entry.getKey()); lineModel.getEditableKey().setEntity((String) keyValueMap.get(entry.getKey())); lineModels.add(lineModel); } } setItems(lineModels); }
Source:
<code>private VirtualFile getVirtualFile(final String filePath, final String displayFileName, final String contents, final String baseDir) throws IOException { VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(filePath); if (virtualFile == null) { String digest = UUID.randomUUID().toString().substring(0, 10); final String fullFilePath = Utils.getInstance() .createFileWithContents(displayFileName, contents, baseDir, digest); virtualFile = LocalFileSystem.getInstance().findFileByPath(fullFilePath); <START> if (virtualFile != null) { <END> Preconditions.checkNotNull(virtualFile, "Virtual file should not be null. Can be an issue with FileSystem."); } } windowEditorOps.setWriteStatus(virtualFile, false); return virtualFile; }</code><technical_language>do this. :(</technical_language>

Target:
private VirtualFile getVirtualFile(final String filePath, final String displayFileName, final String contents, final String baseDir) throws IOException { VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(filePath); if (virtualFile == null) { String digest = UUID.randomUUID().toString().substring(0, 10); final String fullFilePath = Utils.getInstance() .createFileWithContents(displayFileName, contents, baseDir, digest); virtualFile = LocalFileSystem.getInstance().findFileByPath(fullFilePath); if (virtualFile == null) { throw new IllegalArgumentException("Virtual file should not be null." + " Can be an issue with FileSystem."); } } windowEditorOps.setWriteStatus(virtualFile, false); return virtualFile; }
Source:
<code>public void rethrows_exception() throws Throwable { rule.expectThrowable(RuntimeException.class, "foo"); <START> throw new RuntimeException("foo"); <END> }</code><technical_language>@szczepiq is tested here? I assertion</technical_language>

Target:
public void rethrows_exception() throws Throwable { rule.expectFailure(RuntimeException.class, "foo"); throw new RuntimeException("foo"); }
Source:
<code>public void convertGroupToRichGroupWithAttributesTest() throws Exception { System.out.println("groupsManagerBl.convertGroupToRichGroupWithAttributes"); vo = setUpVo(); attributesList = setUpGroupAttributes(); <START> this.groupsManager.createGroup(sess, vo, group); <END> attributesManager.setAttributes(sess, group, attributesList); Group myGroup = groupsManagerBl.getGroupByName(sess, vo, "GroupsManagerTestGroup1"); RichGroup richGroup = new RichGroup(myGroup, attributesManager.getAttributes(sess, myGroup)); assertEquals("Both rich groups should be same", richGroup, groupsManagerBl.convertGroupToRichGroupWithAttributes(sess, myGroup)); }</code><technical_language>is private method "setUpGroup()" create group in Vo if "vo" exists there. instead of this</technical_language>

Target:
public void convertGroupToRichGroupWithAttributesTest() throws Exception { System.out.println("groupsManagerBl.convertGroupToRichGroupWithAttributes"); vo = setUpVo(); attributesList = setUpGroupAttributes(); setUpGroup(vo); attributesManager.setAttributes(sess, group, attributesList); RichGroup richGroup = new RichGroup(group, attributesManager.getAttributes(sess, group)); assertEquals("Both rich groups should be same", richGroup, groupsManagerBl.convertGroupToRichGroupWithAttributes(sess, group)); }
Source:
<code>private int numberOfEntries(ByteBuffer mmap) { <START> return (mmap.capacity() - indexSizeExcludingEntries) / (persistedEntrySize); <END> }</code><technical_language>minor: parentheses denominator required</technical_language>

Target:
private int numberOfEntries(ByteBuffer mmap) { return (mmap.capacity() - indexSizeExcludingEntries) / persistedEntrySize; }
Source:
<code>private static String getApiErrorMessage(@NonNull Context c, @NonNull ApiException e) { String text; if (e.getInfo() != null) { <START> text = String.format(c.getString(R.string.format_error_server_message), e.getInfo()); <END> } else if (e.getCode() != null) { text = String.format(c.getString(R.string.format_error_server_code), e.getCode()); } else { text = e.getMessage(); } return text; }</code><technical_language>need String.format() here. c.getString() handle parameters fine</technical_language>

Target:
private static String getApiErrorMessage(@NonNull Context c, @NonNull ApiException e) { String text; if (e.getInfo() != null) { text = c.getString(R.string.format_error_server_message, e.getInfo()); } else if (e.getCode() != null) { text = c.getString(R.string.format_error_server_code, e.getCode()); } else { text = e.getMessage(); } return text; }
Source:
<code>public void stop() { if (!isStarted.compareAndSet(true, false)) { return; } if (!reapEntriesHandle.isCancelled() || !reapEntriesHandle.isDone()) { reapEntriesHandle.cancel(true); } if (!scheduler.isShutdown()) { scheduler.shutdown(); try { scheduler.awaitTermination(5, TimeUnit.SECONDS); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); <START> log.info(String.format("%s stop sequence has been interrupted",threadScheduledExecutorName)); <END> } } }</code><technical_language>need log first, interrupt thread. Also, SLF4J, need String.format, do: log.info("{} stop sequence interrupted",threadScheduledExecutorName); need %s though</technical_language>

Target:
public void stop() { if (!isStarted.compareAndSet(true, false)) { return; } if (!reapEntriesHandle.isCancelled() || !reapEntriesHandle.isDone()) { reapEntriesHandle.cancel(true); } if (!scheduler.isShutdown()) { scheduler.shutdown(); try { scheduler.awaitTermination(5, TimeUnit.SECONDS); } catch (final InterruptedException e) { log.info(String.format("{} stop sequence has been interrupted",threadScheduledExecutorName)); Thread.currentThread().interrupt(); } } }
Source:
<code>public String toFullString() { <START> return String.format("data:%s;base64,%s", mimeType, PortableBase64.getEncoder().encode(bytes)); <END> }</code><technical_language>question above: this assumes HTML formatting, this is a RawType more specific representing raw image data in a understood in HTML</technical_language>

Target:
public String toFullString() { return String.format("data:%s;base64,%s", mimeType, Base64.getEncoder().encodeToString(bytes)); }
Source:
<code>public List<Facility> getAllowedFacilities(PerunSession sess, User user) throws InternalErrorException { try { return jdbc.query("select distinct " + facilityMappingSelectQuery + " from groups_resources" + " join groups on groups_resources.group_id=groups.id" + " join groups_members on groups.id=groups_members.group_id" + " join members on groups_members.member_id=members.id " + " join resources on groups_resources.resource_id=resources.id " + " join facilities on resources.facility_id=facilities.id " + " where members.user_id=? and members.status!=? and members.status!=?", FACILITY_MAPPER, user.getId(), String.valueOf(Status.INVALID.getCode()), String.valueOf(Status.DISABLED.getCode())); <START> } catch (EmptyResultDataAccessException e) { <END> return new ArrayList<>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } }</code><technical_language>This exception is thrown for method jdbc.query</technical_language>

Target:
public List<Facility> getAllowedFacilities(PerunSession sess, User user) { try { return jdbc.query("select distinct " + facilityMappingSelectQuery + " from groups_resources" + " join groups on groups_resources.group_id=groups.id" + " join groups_members on groups.id=groups_members.group_id" + " join members on groups_members.member_id=members.id " + " join resources on groups_resources.resource_id=resources.id " + " join facilities on resources.facility_id=facilities.id " + " where members.user_id=? and members.status!=? and members.status!=?", FACILITY_MAPPER, user.getId(), String.valueOf(Status.INVALID.getCode()), String.valueOf(Status.DISABLED.getCode())); } catch (RuntimeException e) { throw new InternalErrorException(e); } }
Source:
<code>public T getItem(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index must be non-negative"); } int activeDataEnd = activeStart + activeKeyOrder.size() - 1; if (index >= activeStart && index <= activeDataEnd) { return getKeyMapper().get(activeKeyOrder.get(index - activeStart)); } else { final int itemCount = getItemCount(); if (isDefinedSize()) { if (itemCount == 0) { throw new IndexOutOfBoundsException(String.format( "Requested index %d on empty data.", index)); } else if (index >= itemCount) { throw new IndexOutOfBoundsException(String.format( "Given index %d is outside of the accepted range '0 - %d'", index, itemCount - 1)); } } <START> if (fetchDisabled) { <END> throw new IllegalStateException( "Data Communicator cannot fetch the item from Data " + "Provider when the fetch is disabled. Please " + "enable it by calling " + "'dataCommunicator.setFetchDisabled(false)'"); } return (T) getDataProvider().fetch(buildQuery(index, 1)).findFirst() .orElse(null); } }</code><technical_language>this blocked ??? this API is exposed users, not, feels weird for some components I do java Component listing = createListing(); listing.setItems(query -> getStuff(query)); listing.getItem(0); for all. for Grid this work for combobox (I guess) ??? is confusing</technical_language>

Target:
public T getItem(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index must be non-negative"); } int activeDataEnd = activeStart + activeKeyOrder.size() - 1; if (index >= activeStart && index <= activeDataEnd) { return getKeyMapper().get(activeKeyOrder.get(index - activeStart)); } else { final int itemCount = getItemCount(); if (isDefinedSize()) { if (itemCount == 0) { throw new IndexOutOfBoundsException(String .format("Requested index %d on empty data.", index)); } else if (index >= itemCount) { throw new IndexOutOfBoundsException(String.format( "Given index %d is outside of the accepted range '0 - %d'", index, itemCount - 1)); } } return (T) getDataProvider().fetch(buildQuery(index, 1)).findFirst() .orElse(null); } }
Source:
<code>void migrateCredentials(SubversionSCM.DescriptorImpl descriptor) throws IOException { CredentialsStore store = CredentialsProvider.lookupStores(project).iterator().next(); for (Map.Entry<String, Credential> e : credentials.entrySet()) { <START> StandardCredentials credential = descriptor.migrateCredentials(store, e.getKey(), e.getValue()); <END> int i = 0; boolean found = false; ModuleLocation[] locations = ((SubversionSCM) project.getScm()).getLocations(); while (i < locations.length && !found) { try { if (e.getKey().contains(locations[i].getSVNURL().getHost())) { locations[i].setCredentialsId(credential.getId()); found = true; } i++; } catch (SVNException ex) { LOGGER.log(WARNING, "Repository location with a malformed URL: " + locations[i].remote, ex); } } } }</code><technical_language>store passed null? SubversionSCM.DescriptorImpl.migrateCredentials null react "properly"</technical_language>

Target:
void migrateCredentials(SubversionSCM.DescriptorImpl descriptor) throws IOException { Iterable<CredentialsStore> it = CredentialsProvider.lookupStores(project); if (it != null && it.iterator().hasNext()) { CredentialsStore store = it.iterator().next(); for (Map.Entry<String, Credential> e : credentials.entrySet()) { StandardCredentials credential = descriptor.migrateCredentials(store, e.getKey(), e.getValue()); ModuleLocation[] locations = ((SubversionSCM) project.getScm()).getLocations(); for (int i = 0; i < locations.length; i++) { try { if (e.getKey().contains(locations[i].getSVNURL().getHost())) { locations[i].setCredentialsId(credential.getId()); break; } } catch (SVNException ex) { LOGGER.log(WARNING, "Repository location with a malformed URL: " + locations[i].remote, ex); } } } } }
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getMissingServerHooks().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NO_CONFLICT_SERVERS); return false; } for (GlusterServerHook serverHook: getMissingServerHooks()) { VDS vds = getVdsDAO().get(serverHook.getServerId()); if (vds == null || vds.getStatus() != VDSStatus.Up) { String vdsName = vds != null ? vds.getName() : "NO SERVER"; setVdsName(vdsName); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_SERVER_STATUS_NOT_UP); <START> if (vds!= null){ <END> addCanDoActionMessage(String.format("$%1$s %2$s", "VdsName", vdsName)); } return false; } } return true; }</code><technical_language>do need this null check here</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getMissingServerHooks().isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_HOOK_NO_CONFLICT_SERVERS); return false; } for (GlusterServerHook serverHook: getMissingServerHooks()) { VDS vds = getVdsDAO().get(serverHook.getServerId()); if (vds == null || vds.getStatus() != VDSStatus.Up) { String vdsName = vds != null ? vds.getName() : "NO SERVER"; setVdsName(vdsName); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_SERVER_STATUS_NOT_UP); addCanDoActionMessage(String.format("$%1$s %2$s", "VdsName", vdsName)); return false; } } return true; }
Source:
<code><START> private Map<LocalDate, Set<WeekActivity>> getWeekActivitiesGroupedByDate(UUID userAnonymizedID, Interval interval) <END> { Set<WeekActivity> weekActivityEntities = weekActivityRepository.findAll(userAnonymizedID, interval.startDate, interval.endDate); Map<LocalDate, Set<WeekActivity>> weekActivityEntitiesByLocalDate = weekActivityEntities.stream() .collect(Collectors.groupingBy(a -> a.getDate(), Collectors.toSet())); return weekActivityEntitiesByLocalDate; }</code><technical_language>Please apply this extract method day activities if code more readable</technical_language>

Target:
private Map<LocalDate, Set<WeekActivity>> getWeekActivitiesGroupedByDate(UUID userAnonymizedID, Interval interval) { Set<WeekActivity> weekActivityEntities = weekActivityRepository.findAll(userAnonymizedID, interval.startDate, interval.endDate); return weekActivityEntities.stream().collect(Collectors.groupingBy(a -> a.getDate(), Collectors.toSet())); }
Source:
<code>public boolean equals(Object obj) { return EqualsUtil.equals(this, obj, (equalsBuilder, otherObj) -> { equalsBuilder.append(dataForm.getType(), otherObj.getDataForm().getType()) <START> .append(dataForm.getTitle(), otherObj.getDataForm().getTitle()) <END> .append(dataForm.getReportedData(), otherObj.getDataForm().getReportedData()) .append(dataForm.getItems(), otherObj.getDataForm().getItems()) .append(dataForm.getFields(), otherObj.getDataForm().getFields()) .append(dataForm.getExtensionElements(), otherObj.getDataForm().getExtensionElements()); }); }</code><technical_language>if field is null</technical_language>

Target:
public boolean equals(Object obj) { return EqualsUtil.equals(this, obj, (equalsBuilder, otherObj) -> { equalsBuilder.append(getDataForm().getType(), otherObj.getDataForm().getType()) .append(getDataForm().getTitle(), otherObj.getDataForm().getTitle()) .append(getDataForm().getReportedData(), otherObj.getDataForm().getReportedData()) .append(getDataForm().getItems(), otherObj.getDataForm().getItems()) .append(getDataForm().getFields(), otherObj.getDataForm().getFields()) .append(getDataForm().getExtensionElements(), otherObj.getDataForm().getExtensionElements()); }); }
Source:
<code>public void testCloseNotifyWaiters() throws Exception { final int numWorkers = 2; BufferPool pool = new BufferPool(1, 1, metrics, Time.SYSTEM, metricGroup); ByteBuffer buffer = pool.allocate(1, Long.MAX_VALUE); CountDownLatch completed = new CountDownLatch(numWorkers); ExecutorService executor = Executors.newFixedThreadPool(numWorkers); Callable<Void> work = new Callable<Void>() { public Void call() throws Exception { assertThrows(KafkaException.class, () -> pool.allocate(1, maxBlockTimeMs)); completed.countDown(); return null; } }; for (int i = 0; i < numWorkers; ++i) { executor.submit(work); } assertEquals("Allocation shouldn't have happened yet, waiting on memory", numWorkers, completed.getCount()); pool.close(); <START> completed.await(200, TimeUnit.MILLISECONDS); <END> pool.deallocate(buffer); }</code><technical_language>a bit concerned this timeout tight for shaky jenkins build environment. I harm increasing 15s safe side</technical_language>

Target:
public void testCloseNotifyWaiters() throws Exception { final int numWorkers = 2; BufferPool pool = new BufferPool(1, 1, metrics, Time.SYSTEM, metricGroup); ByteBuffer buffer = pool.allocate(1, Long.MAX_VALUE); CountDownLatch completed = new CountDownLatch(numWorkers); ExecutorService executor = Executors.newFixedThreadPool(numWorkers); Callable<Void> work = new Callable<Void>() { public Void call() throws Exception { assertThrows(KafkaException.class, () -> pool.allocate(1, Long.MAX_VALUE)); completed.countDown(); return null; } }; for (int i = 0; i < numWorkers; ++i) { executor.submit(work); } assertEquals("Allocation shouldn't have happened yet, waiting on memory", numWorkers, completed.getCount()); pool.close(); completed.await(15, TimeUnit.SECONDS); pool.deallocate(buffer); }
Source:
<code>public CifsTelnetConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); <START> ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); <END> ConnectionValidator.assertNotNewStyleWindowsDomain(username, CIFS_PROTOCOL, cifsConnectionType); connected(); }</code><technical_language>static imports</technical_language>

Target:
public CifsTelnetConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper); }
Source:
<code>public Response workspaceChatSettingsGet(@PathParam("WorkspaceEntityId") Long workspaceEntityId) { if (!sessionController.isLoggedIn()) { return Response.status(Status.FORBIDDEN).entity("Must be logged in").build(); } <START> return Response.ok(workspaceEntityId).build(); <END> }</code><technical_language>This return WorkspaceChatSettings object</technical_language>

Target:
public Response workspaceChatSettingsGet(@PathParam("WorkspaceEntityId") Long workspaceEntityId) { if (!sessionController.isLoggedIn()) { return Response.status(Status.FORBIDDEN).entity("Must be logged in").build(); } WorkspaceChatSettings workspaceChatSettings = chatController.findWorkspaceChatSettings(workspaceEntityId); if (workspaceChatSettings == null) { return Response.status(Status.NOT_FOUND).build(); } return Response.ok(restModel(workspaceChatSettings)).build(); }
Source:
<code>public StructuredRecord joinOn(String stageName, StructuredRecord record) { Schema keySchema; List<String> joinKeys = perStageJoinKeys.get(stageName); if (keySchemas.containsKey(stageName)) { keySchema = keySchemas.get(stageName); } else { List<Schema.Field> fields = new ArrayList<>(); Schema schema = record.getSchema(); int i = 1; for (String joinKey : joinKeys) { Schema.Field field = schema.getField(joinKey); if (field == null) { throw new IllegalArgumentException(String.format("Join key field '%s' does not exist in schema from '%s'.", joinKey, stageName)); } Schema.Field joinField = Schema.Field.of(String.valueOf(i++), field.getSchema()); fields.add(joinField); } keySchema = Schema.recordOf("join.key", fields); keySchemas.put(stageName, keySchema); } StructuredRecord.Builder keyRecordBuilder = StructuredRecord.builder(keySchema); int i = 1; for (String joinKey : joinKeys) { keyRecordBuilder.set(String.valueOf(i++), record.get(joinKey)); } StructuredRecord keyRecord = keyRecordBuilder.build(); <START> return keyRecord; <END> }</code><technical_language>nit: return keyRecordBuilder.build();</technical_language>

Target:
public StructuredRecord joinOn(String stageName, StructuredRecord record) { Schema keySchema; List<String> joinKeys = perStageJoinKeys.get(stageName); if (keySchemas.containsKey(stageName)) { keySchema = keySchemas.get(stageName); } else { List<Schema.Field> fields = new ArrayList<>(); Schema schema = record.getSchema(); int i = 1; for (String joinKey : joinKeys) { Schema.Field field = schema.getField(joinKey); if (field == null) { throw new IllegalArgumentException(String.format("Join key field '%s' does not exist in schema from '%s'.", joinKey, stageName)); } Schema.Field joinField = Schema.Field.of(String.valueOf(i++), field.getSchema()); fields.add(joinField); } keySchema = Schema.recordOf("join.key", fields); keySchemas.put(stageName, keySchema); } StructuredRecord.Builder keyRecordBuilder = StructuredRecord.builder(keySchema); int i = 1; for (String joinKey : joinKeys) { keyRecordBuilder.set(String.valueOf(i++), record.get(joinKey)); } return keyRecordBuilder.build(); }
Source:
<code>public Principal getUserPrincipal() { <START> return subject::getUserName; <END> }</code><technical_language>subject.getUserName()</technical_language>

Target:
public Principal getUserPrincipal() { return principal; }
Source:
<code>public void onSocialChanged(OnSocialChanged event) { if (event.isError()) { switch (event.error.type) { case UNABLE_CONNECT: AppLog.e(T.API, "Unable to connect WordPress.com account to social account."); doFinishLogin(); break; case USER_ALREADY_ASSOCIATED: AppLog.e(T.API, "This social account is already associated with a WordPress.com account."); break; } <START> if (isSocialLogin) { <END> doFinishLogin(); } } else if (!event.requiresTwoStepAuth) { doFinishLogin(); } }</code><technical_language>Hmm, isSocialLogin false while in onSocialChanged(). impression this callback is called in Social login mode, right</technical_language>

Target:
public void onSocialChanged(OnSocialChanged event) { if (event.isError()) { switch (event.error.type) { case UNABLE_CONNECT: AppLog.e(T.API, "Unable to connect WordPress.com account to social account."); break; case USER_ALREADY_ASSOCIATED: AppLog.e(T.API, "This social account is already associated with a WordPress.com account."); break; } doFinishLogin(); } else if (!event.requiresTwoStepAuth) { doFinishLogin(); } }
Source:
<code>public void setScanningDepth(int scanningDepth) throws IllegalArgumentException { if (scanningDepth < 0) { throw new IllegalArgumentException( <START> String.format("Invalid value for scanningDepth \"%d\"", scanningDepth)); <END> } this.scanningDepth = scanningDepth; }</code><technical_language>is is wrong in error message</technical_language>

Target:
public void setScanningDepth(int scanningDepth) throws IllegalArgumentException { if (scanningDepth < 0) { throw new IllegalArgumentException( String.format(NEGATIVE_NUMBER_ERROR, "scanningDepth", scanningDepth)); } this.scanningDepth = scanningDepth; }
Source:
<code>public static TestContainerResource getResource() { if (currentInstance == null) { currentInstance = new TestContainerResource(); try { Properties properties = new Properties(); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("server.properties")); serverVersion = properties.getProperty("server.version"); if(properties.getProperty("server.resource").compareTo("container") != 0) { return null; } } catch (IOException ex) { serverVersion = "5.0.1"; } <START> couchbaseContainer = new FixedHostPortGenericContainer("couchbase:" + serverVersion) <END> .withFixedExposedPort(8091, 8091) .withFixedExposedPort(18091, 18091) .withFixedExposedPort(8092, 8092) .withFixedExposedPort(18092, 18092) .withFixedExposedPort(8093, 8093) .withFixedExposedPort(18093, 18093) .withFixedExposedPort(8094, 8094) .withFixedExposedPort(18094, 18094) .withFixedExposedPort(11210, 11210) .withFixedExposedPort(11211, 11211) .withFixedExposedPort(11207, 11207); couchbaseContainer.waitingFor(new CouchbaseWaitStrategy(serverVersion)); couchbaseContainer.start(); } return currentInstance; }</code><technical_language>long start a single container fine... I a map dynamically this for converge? is starting one</technical_language>

Target:
public static TestContainerResource getResource() { if (currentInstance == null) { currentInstance = new TestContainerResource(); try { Properties properties = new Properties(); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("server.properties")); serverVersion = properties.getProperty("server.version"); if(!properties.getProperty("server.resource").contentEquals("container")) { return null; } } catch (Exception ex) { serverVersion = "5.0.1"; } couchbaseContainer = new FixedHostPortGenericContainer("couchbase:" + serverVersion) .withFixedExposedPort(8091, 8091) .withFixedExposedPort(18091, 18091) .withFixedExposedPort(8092, 8092) .withFixedExposedPort(18092, 18092) .withFixedExposedPort(8093, 8093) .withFixedExposedPort(18093, 18093) .withFixedExposedPort(8094, 8094) .withFixedExposedPort(18094, 18094) .withFixedExposedPort(11210, 11210) .withFixedExposedPort(11211, 11211) .withFixedExposedPort(11207, 11207); couchbaseContainer.waitingFor(new CouchbaseWaitStrategy(serverVersion)); couchbaseContainer.start(); } return currentInstance; }
Source:
<code>public static void optionHelp(final Class<?> clazz, final String commandName, final Collection<OptionParam> optionParams, final PrintStream out) { <START> if (optionParams.size() == 0) { <END> return; } ResourceBundle general = null; final List<Item> items = new ArrayList<Item>(optionParams.size()); int width = 20; for (final OptionParam optionParam : optionParams) { String description = optionParam.getDescription(); if (description == null || description.isEmpty()) { if (general == null) { general = getResourceBundle(clazz); } description = getDescription(general, commandName, optionParam.getName()); } final Item item = new Item(optionParam, description); items.add(item); width = Math.max(width, item.flag.length()); } final String format = " %-" + width + "s %s%n"; out.println("Options: "); for (final Item item : items) { final List<String> lines = new ArrayList<String>(); if (item.description != null) { lines.add(item.description); } lines.addAll(item.note); if (lines.isEmpty()) { lines.add(""); } out.printf(format, item.flag, lines.remove(0)); for (final String line : lines) { out.printf(format, "", String.format("(%s)", line)); } } }</code><technical_language>stick isEmpty() fixed ;)</technical_language>

Target:
public static void optionHelp(final Class<?> clazz, final String commandName, final Collection<OptionParam> optionParams, final PrintStream out) { if (optionParams.isEmpty()) { return; } ResourceBundle general = null; final List<Item> items = new ArrayList<Item>(optionParams.size()); int width = 20; for (final OptionParam optionParam : optionParams) { String description = optionParam.getDescription(); if (description == null || description.isEmpty()) { if (general == null) { general = getResourceBundle(clazz); } description = getDescription(general, commandName, optionParam.getName()); } final Item item = new Item(optionParam, description); items.add(item); width = Math.max(width, item.flag.length()); } final String format = " %-" + width + "s %s%n"; out.println("Options: "); for (final Item item : items) { final List<String> lines = new ArrayList<String>(); if (item.description != null) { lines.add(item.description); } lines.addAll(item.note); if (lines.isEmpty()) { lines.add(""); } out.printf(format, item.flag, lines.remove(0)); for (final String line : lines) { out.printf(format, "", String.format("(%s)", line)); } } }
Source:
<code>public synchronized boolean registerLogReader(final String watchPath, final LogReader reader) { if (readerMap == null) { readerMap = new HashMap<String, LogReader>(); parentWathchPathSet = new HashSet<String>(); <START> } <END> if (!readerMap.containsKey(watchPath)) { readerMap.put(watchPath, reader); String parentPath = Util.getParentAbsolutePath(watchPath); int fwd; if (!parentWathchPathSet.contains(parentPath)) { parentWathchPathSet.add(parentPath); try { fwd = iJNotifyInstance.addWatch(parentPath, FILE_CREATED, false, this); if (path2wd == null) { path2wd = new HashMap<String, Integer>(); } path2wd.put(parentPath, fwd); } catch (JNotifyException e) { LOG.error("Failed to add watch for " + parentPath, e); readerMap.remove(watchPath); parentWathchPathSet.remove(parentPath); return false; } LOG.info("Registerring and monitoring parent path " + parentPath + " \"FILE_CREATE\""); } else { LOG.info("Watch parent path " + parentPath + " has already exist in the Set"); } int wd; try { wd = iJNotifyInstance.addWatch(watchPath, FILE_MODIFIED, false, this); } catch (JNotifyException e) { LOG.error("Failed to add watch for " + watchPath, e); readerMap.remove(watchPath); return false; } LOG.info("Registerring and monitoring tail file " + watchPath + " \"FILE_MODIFIED\""); if (path2wd == null) { path2wd = new HashMap<String, Integer>(); } path2wd.put(watchPath, wd); } else { LOG.info("Watch path " + watchPath + " has already exist in the Map"); } return true; }</code><technical_language>initialize readerMap in constructor</technical_language>

Target:
public boolean registerLogReader(final String watchPath, final LogReader reader) { int fwd, wd; if (!readerMap.containsKey(watchPath)) { lock.lock(); try { readerMap.put(watchPath, reader); String parentPath = Util.getParentAbsolutePath(watchPath); if (!parentWathchPathSet.contains(parentPath)) { parentWathchPathSet.add(parentPath); try { fwd = iJNotifyInstance.addWatch(parentPath, FILE_CREATED, false, this); path2wd.put(parentPath, fwd); } catch (JNotifyException e) { LOG.error("Failed to add watch for " + parentPath, e); readerMap.remove(watchPath); parentWathchPathSet.remove(parentPath); return false; } LOG.info("Registerring and monitoring parent path " + parentPath + " \"FILE_CREATE\""); } else { LOG.info("Watch parent path " + parentPath + " has already exist in the Set"); } try { wd = iJNotifyInstance.addWatch(watchPath, FILE_MODIFIED, false, this); } catch (JNotifyException e) { LOG.error("Failed to add watch for " + watchPath, e); readerMap.remove(watchPath); return false; } LOG.info("Registerring and monitoring tail file " + watchPath + " \"FILE_MODIFIED\""); path2wd.put(watchPath, wd); } finally { lock.unlock(); } } else { LOG.info("Watch path " + watchPath + " has already exist in the Map"); } return true; }
Source:
<code>public void setLimit(long num) { <START> throw new TajoRuntimeException(new UnsupportedException()); <END> }</code><technical_language>share some backgrounds MergeScanner support this feature</technical_language>

Target:
public void setLimit(long num) { }
Source:
<code>private CompletableFuture<Void> doUnicast(String subject, byte[] payload, NodeId toNodeId) { Node node = cluster.getNode(toNodeId); if (node == null) { <START> return Futures.exceptionalFuture(new ConnectException()); <END> } return messagingService.sendAsync(node.endpoint(), subject, payload); }</code><technical_language>Pulled in other pr changes</technical_language>

Target:
private CompletableFuture<Void> doUnicast(String subject, byte[] payload, NodeId toNodeId) { Node node = cluster.getNode(toNodeId); if (node == null) { return Futures.exceptionalFuture(CONNECT_EXCEPTION); } return messagingService.sendAsync(node.endpoint(), subject, payload); }
Source:
<code>private List<SearchHit> sendElasticsearchQuery(ElasticsearchQueryBuilder queryBuilder) { <START> ImmutableList.Builder<SearchHit> result = ImmutableList.builder(); <END> SearchResponse response = queryBuilder.buildScrollSearchRequest() .execute() .actionGet(timeout.toMillis()); if (response.getHits().getTotalHits() > maxHits) { throw new PrestoException(ELASTICSEARCH_MAX_HITS_EXCEEDED, format("The number of hits for the query (%d) exceeds the configured max hits (%d)", response.getHits().getTotalHits(), maxHits)); } while (true) { for (SearchHit hit : response.getHits().getHits()) { result.add(hit); } response = queryBuilder.prepareSearchScroll(response.getScrollId()) .execute() .actionGet(timeout.toMillis()); if (response.getHits().getHits().length == 0) { break; } } return result.build(); }</code><technical_language>Move ImmutableList.Builder<SearchHit> result = ImmutableList.builder(); right while loop L193</technical_language>

Target:
private List<SearchHit> sendElasticsearchQuery(ElasticsearchQueryBuilder queryBuilder) { SearchResponse response = getSearchResponse(queryBuilder); if (response.getHits().getTotalHits() > maxHits) { throw new PrestoException(ELASTICSEARCH_MAX_HITS_EXCEEDED, format("The number of hits for the query (%d) exceeds the configured max hits (%d)", response.getHits().getTotalHits(), maxHits)); } ImmutableList.Builder<SearchHit> result = ImmutableList.builder(); while (true) { for (SearchHit hit : response.getHits().getHits()) { result.add(hit); } response = getScrollResponse(queryBuilder, response.getScrollId()); if (response.getHits().getHits().length == 0) { break; } } return result.build(); }