auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void display(final ChangeDetail detail, final PatchSet.Id diffBaseId) { clear(); final PatchSet currps = detail.getCurrentPatchSet(); currentPatchSetId = currps.getId(); patchSets = new ArrayList<PatchSet>(); for (PatchSet ps : detail.getPatchSets()) { if (!ps.isDraft() || (Gerrit.isSignedIn() && <START> detail.hasDraftAccess(Gerrit.getUserAccount().getId()))) { <END> patchSets.add(ps); } else if (currentPatchSetId == ps.getId()) { currentPatchSetId = null; } } if (currentPatchSetId == null) { if (!patchSets.isEmpty()) { currentPatchSetId = patchSets.get(patchSets.size() - 1).getId(); } else { currentPatchSetId = currps.getId(); } } if (Gerrit.isSignedIn()) { final AccountGeneralPreferences p = Gerrit.getUserAccount().getGeneralPreferences(); if (p.isDisplayPatchSetsInReverseOrder()) { Collections.reverse(patchSets); } } patchSetPanelsList = new ArrayList<PatchSetComplexDisclosurePanel>(); for (final PatchSet ps : patchSets) { final PatchSetComplexDisclosurePanel p; if (ps == currps) { p = new PatchSetComplexDisclosurePanel(parent, detail, detail .getCurrentPatchSetDetail()); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); p.refresh(); } } else { p = new PatchSetComplexDisclosurePanel(parent, detail, ps); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); } if (ps.getId() == currentPatchSetId){ p.setOpen(true); } } add(p); patchSetPanelsList.add(p); } }</code><technical_language>I this filtered server side</technical_language>

Target:
public void display(final ChangeDetail detail, final PatchSet.Id diffBaseId) { clear(); final PatchSet currps = detail.getCurrentPatchSet(); currentPatchSetId = currps.getId(); patchSets = detail.getPatchSets(); final List<PatchSet.Id> changePatchSets = new ArrayList<PatchSet.Id>(); for (final PatchSet ps : patchSets) { changePatchSets.add(ps.getId()); } if (Gerrit.isSignedIn()) { final AccountGeneralPreferences p = Gerrit.getUserAccount().getGeneralPreferences(); if (p.isDisplayPatchSetsInReverseOrder()) { Collections.reverse(patchSets); } } patchSetPanelsList = new ArrayList<PatchSetComplexDisclosurePanel>(); for (final PatchSet ps : patchSets) { final PatchSetComplexDisclosurePanel p; if (ps == currps) { p = new PatchSetComplexDisclosurePanel(parent, detail, detail .getCurrentPatchSetDetail()); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); p.refresh(); } } else { p = new PatchSetComplexDisclosurePanel(parent, detail, ps); if (diffBaseId != null) { p.setDiffBaseId(diffBaseId); } } add(p); patchSetPanelsList.add(p); } }
Source:
<code>public String[] getPlantsOfStudent(String student) { String[] plants = new String[PARTITION_SIZE_WIDTH * 2]; int studentPlantsIndex = Arrays.binarySearch(students, student) * PARTITION_SIZE_WIDTH; <START> for (int i = 0; i < PARTITION_SIZE_WIDTH; i++) { <END> plants[i] = getPlantName(garden.charAt(studentPlantsIndex + i)); } int newRowLocation = garden.indexOf('\n'); for (int i = PARTITION_SIZE_WIDTH; i < PARTITION_SIZE_WIDTH * 2; i++) { plants[i] = getPlantName(garden.charAt(newRowLocation - 1 + studentPlantsIndex + i)); } return plants; }</code><technical_language>a bit more readable int i = studentPlantsIndex; i < studentPlantsIndex + PARTITITON_SIZE_WIDTH; i++ if a list instead of array return plants, need i for index, append list :)</technical_language>

Target:
public List<Plant> getPlantsOfStudent(String student) { List<Plant> plants = new ArrayList<Plant>(); int studentPlantsIndex = Arrays.binarySearch(students, student) * PLANTS_PER_STUDENT_PER_ROW; for (int i = studentPlantsIndex; i < studentPlantsIndex + PLANTS_PER_STUDENT_PER_ROW; i++) { plants.add(Plant.getPlant(garden.charAt(i))); } for (int i = newRowLocation + studentPlantsIndex; i < newRowLocation + studentPlantsIndex + PLANTS_PER_STUDENT_PER_ROW; i++) { plants.add(Plant.getPlant(garden.charAt(i))); } return plants; }
Source:
<code>protected int index(String urlFormat, String bulkString) throws IOException { String tempUrl = String.format(urlFormat, getBaseUrl()); HttpEntity entity = new NStringEntity(bulkString, ContentType.APPLICATION_JSON); int statusCode = 0; Queue<String> callQ = new LinkedList<>(); callQ.add(tempUrl); int callCount = 0; while(!callQ.isEmpty() && callCount < MAX_CALL_COUNT) { callCount++; String url = callQ.remove(); logger.info("Using url [{}]", url); HttpPost httpPost = new HttpPost(url); httpPost.setHeaders(getHeaders()); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = closeableHttpClient.execute(httpPost); statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { logger.error("index method failed with status code: and error: {}", response.getStatusLine().getStatusCode(), <START> EntityUtils.toString(response.getEntity())); <END> } } catch (Exception e) { if(response == null){ logger.error("index method failed with message: {}", e.getMessage()); url = String.format(urlFormat, getBaseUrl()); callQ.add(url); } else { logger.error("index method failed with status code: and exception message: {}", response.getStatusLine().getStatusCode(), e.getMessage()); } } finally { if(response != null) { response.close(); } } } return statusCode; }</code><technical_language>other http calls do a consume() entity. Do need do here</technical_language>

Target:
public int index(String urlFormat, String bulkString) throws IOException { String tempUrl = String.format(urlFormat, getBaseUrl()); HttpEntity entity = new NStringEntity(bulkString, ContentType.APPLICATION_JSON); int statusCode = 0; Queue<String> callQ = new LinkedList<>(); callQ.add(tempUrl); int callCount = 0; while(!callQ.isEmpty() && callCount < MAX_CALL_COUNT) { callCount++; String url = callQ.remove(); logger.info("Using url [{}]", url); HttpPost httpPost = new HttpPost(url); httpPost.setHeaders(getHeaders()); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = closeableHttpClient.execute(httpPost); statusCode = response.getStatusLine().getStatusCode(); String str = EntityUtils.toString(response.getEntity()); EntityUtils.consume(response.getEntity()); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { logger.error("index method failed with status code: and error: {}", statusCode, str); } } catch (Exception e) { if(response == null){ logger.error("index method failed with message: {}", e.getMessage()); url = String.format(urlFormat, getBaseUrl()); callQ.add(url); } else { logger.error("index method failed with status code: and exception message: {}", statusCode, e.getMessage()); } } finally { if(response != null) { response.close(); } } } return statusCode; }
Source:
<code>private ClusterConfig getClusterConfig(ServicesConfig servicesConfig) { if (servicesConfig != null && !servicesConfig.services().isEmpty()) { Map<String, String> metadata = clusterConfig.metadata(); if (metadata.isEmpty()) { metadata = new HashMap<>(); } metadata.putAll(Microservices.metadata(servicesConfig)); <START> clusterConfig.metadata(metadata); <END> } return clusterConfig.build(); }</code><technical_language>I propose change to: Map<String, String> metadata = new HashMap<>(); metadata.putAll(clusterConfig.metadata()); metadata.putAll(Microservices.metadata(servicesConfig)); clusterConfig.metadata(metadata);</technical_language>

Target:
private ClusterConfig getClusterConfig(ServicesConfig servicesConfig) { if (servicesConfig != null && !servicesConfig.services().isEmpty()) { Map<String, String> metadata = new HashMap<>(); metadata.putAll(clusterConfig.metadata()); metadata.putAll(Microservices.metadata(servicesConfig)); clusterConfig.metadata(metadata); } return clusterConfig.build(); }
Source:
<code>public void testGetAnnotation() { DocumentModel docToAnnotate = session.createDocumentModel("/", "testDoc", "File"); docToAnnotate = session.createDocument(docToAnnotate); String annotationId = "foo"; String docIdToAnnotate = docToAnnotate.getId(); String xpathToAnnotate = "files:files/0/file"; <START> CoreInstance.doPrivileged(session, adminSession -> { <END> DocumentModel annotationModel = adminSession.createDocumentModel(null, "testName", ANNOTATION_DOC_TYPE); annotationModel.setPropertyValue(ANNOTATION_ID_PROPERTY, annotationId); annotationModel.setPropertyValue(ANNOTATION_XPATH_PROPERTY, xpathToAnnotate); annotationModel.setPropertyValue(ANNOTATION_DOCUMENT_ID_PROPERTY, docIdToAnnotate); adminSession.createDocument(annotationModel); adminSession.save(); }); Annotation annotation = annotationService.getAnnotation(session, annotationId); assertNotNull("Unable to get the annotation", annotation); assertEquals(docIdToAnnotate, annotation.getDocumentId()); }</code><technical_language>coreFeature.getCoreSession() for admin session, do in setup method</technical_language>

Target:
public void testGetAnnotation() { DocumentModel docToAnnotate = session.createDocumentModel("/", "testDoc", "File"); docToAnnotate = session.createDocument(docToAnnotate); String annotationId = "foo"; String docIdToAnnotate = docToAnnotate.getId(); String xpathToAnnotate = "files:files/0/file"; createAnnotationAsDocumentModel(annotationId, docIdToAnnotate, xpathToAnnotate); Annotation annotation = annotationService.getAnnotation(session, annotationId); assertNotNull("Unable to get the annotation", annotation); assertEquals(docIdToAnnotate, annotation.getDocumentId()); }
Source:
<code>TryCastResolver(DataType type, String name) { <START> super(FuncParams.builder().withIndependentVarArgs(Param.ANY).build()); <END> this.type = type; this.name = name; }</code><technical_language>here, I this limited 1 2 arguments</technical_language>

Target:
TryCastResolver(DataType type, String name) { super(FuncParams.builder(Param.ANY) .withVarArgs(Param.ANY) .limitVarArgOccurrences(1) .build()); this.type = type; this.name = name; }
Source:
<code>public String processBulkSubmit(@RequestBody JSONArray librariesDtos) throws IOException, MalformedLibraryException { try { if (librariesDtos != null && librariesDtos.size() > 0) { List<Long> savedLibraryIds = new ArrayList<>(); for (Object lDto : librariesDtos) { ObjectMapper mapper = new ObjectMapper(); LibraryDto libDto = mapper.readValue(lDto.toString(), LibraryDto.class); Library library = Dtos.to(libDto); library.setSample(sampleService.get(libDto.getParentSampleId())); library.setLibrarySelectionType(libraryService.getLibrarySelectionTypeById(libDto.getLibrarySelectionTypeId())); library.setLibraryStrategyType(libraryService.getLibraryStrategyTypeById(libDto.getLibraryStrategyTypeId())); <START> library.setLibraryType(libraryService.getLibraryTypeById(libDto.getLibraryTypeId())); <END> Long savedId = libraryService.save(library).getId(); savedLibraryIds.add(savedId); } return "redirect:/miso/library/bulk/edit/" + savedLibraryIds.toString(); } else { throw new IOException("There are no libraries to save!"); } } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Failed to save library", ex); } throw ex; } }</code><technical_language>need for fetches - DTO conversion copies IDs Service fetches of save</technical_language>

Target:
public String processBulkSubmit(@RequestBody JSONArray librariesDtos) throws IOException, MalformedLibraryException { try { if (librariesDtos != null && librariesDtos.size() > 0) { List<Long> savedLibraryIds = new ArrayList<>(); for (Object lDto : librariesDtos) { ObjectMapper mapper = new ObjectMapper(); LibraryDto libDto = mapper.readValue(lDto.toString(), LibraryDto.class); Library library = Dtos.to(libDto); Long savedId = libraryService.create(library); savedLibraryIds.add(savedId); } return "redirect:/miso/library/bulk/edit/" + savedLibraryIds.toString(); } else { throw new IOException("There are no libraries to save!"); } } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Failed to save library", ex); } throw ex; } }
Source:
<code>public List<@NonNull IDataChartDescriptor<T, ?>> getDataDescriptors() { <START> return fDescriptors; <END> }</code><technical_language>this is pretty interesting, arraylist here? is design? a naughty dev, I want fo SegmentStoreDataModel.getDataDescriptors().clear() SegmentStoreDataModel.getDataDescriptors().shuffle(); Is this desired? if not, consider immutable list</technical_language>

Target:
public List<@NonNull IDataChartDescriptor<T, ?>> getDataDescriptors() { return ImmutableList.copyOf(fDescriptors); }
Source:
<code>private SourceFile getSourceFile(String path, String repositoryId, String branch, SourceFile.FileType type) { SourceFile file = new SourceFile(); String url = BITBUCKET_API_URL + "repositories/" + repositoryId + "/raw/" + branch + "/" + path; Optional<String> asString = ResourceUtilities.asString(url, bitbucketTokenContent, client); LOG.info(gitUsername + ": RESOURCE CALL: {}", url); if (asString.isPresent()) { String content = asString.get(); <START> Boolean validWorkflow; <END> if (type == SourceFile.FileType.DOCKSTORE_CWL) { validWorkflow = checkValidCWLWorkflow(content); } else { validWorkflow = checkValidWDLWorkflow(content); } if (validWorkflow) { file.setType(type); file.setContent(content); file.setPath(path); } } return file; }</code><technical_language>Is a reason big-B Boolean here</technical_language>

Target:
private SourceFile getSourceFile(String path, String repositoryId, String branch, SourceFile.FileType type) { SourceFile file = new SourceFile(); String url = BITBUCKET_API_URL + "repositories/" + repositoryId + "/raw/" + branch + "/" + path; Optional<String> asString = ResourceUtilities.asString(url, bitbucketTokenContent, client); LOG.info(gitUsername + ": RESOURCE CALL: {}", url); if (asString.isPresent()) { String content = asString.get(); boolean validWorkflow; if (type == SourceFile.FileType.DOCKSTORE_CWL) { validWorkflow = checkValidCWLWorkflow(content); } else { validWorkflow = checkValidWDLWorkflow(content); } if (validWorkflow) { file.setType(type); file.setContent(content); file.setPath(path); } } return file; }
Source:
<code>void testPolymorphicConfig() { AggregateConfigurer<A> aggregateConfigurer = AggregateConfigurer.defaultConfiguration(A.class); <START> aggregateConfigurer.registerSubtype(B.class); <END> Configuration configuration = DefaultConfigurer.defaultConfiguration() .configureAggregate(aggregateConfigurer) .configureEmbeddedEventStore(c -> new InMemoryEventStorageEngine()) .buildConfiguration(); configuration.start(); CommandGateway commandGateway = configuration.commandGateway(); String aggregateAId = commandGateway.sendAndWait(new CreateACommand("123")); String aggregateBId = commandGateway.sendAndWait(new CreateBCommand("456")); String result1 = commandGateway.sendAndWait(new DoSomethingCommand(aggregateAId)); String result2 = commandGateway.sendAndWait(new DoSomethingCommand(aggregateBId)); String result3 = commandGateway.sendAndWait(new BSpecificCommand(aggregateBId)); assertEquals("A123", result1); assertEquals("B456", result2); assertEquals("bSpecific456", result3); configuration.shutdown(); }</code><technical_language>This is notice fluent interfacing simplify configuration: AggregateConfigurer<A> aggregateConfigurer = AggregateConfigurer.defaultConfiguration(A.class) .withSubtype(B.class);</technical_language>

Target:
void testPolymorphicConfig() { AggregateConfigurer<A> aggregateConfigurer = AggregateConfigurer.defaultConfiguration(A.class) .withSubtypes(B.class); Configuration configuration = DefaultConfigurer.defaultConfiguration() .configureAggregate(aggregateConfigurer) .configureEmbeddedEventStore(c -> new InMemoryEventStorageEngine()) .buildConfiguration(); configuration.start(); CommandGateway commandGateway = configuration.commandGateway(); String aggregateAId = commandGateway.sendAndWait(new CreateACommand("123")); String aggregateBId = commandGateway.sendAndWait(new CreateBCommand("456")); String result1 = commandGateway.sendAndWait(new DoSomethingCommand(aggregateAId)); String result2 = commandGateway.sendAndWait(new DoSomethingCommand(aggregateBId)); String result3 = commandGateway.sendAndWait(new BSpecificCommand(aggregateBId)); assertEquals("A123", result1); assertEquals("B456", result2); assertEquals("bSpecific456", result3); configuration.shutdown(); }
Source:
<code>public void afterPropertiesSet() { super.afterPropertiesSet(); proxyObject = ProxyFactory.getProxy(getObjectType(), this); <START> objectMapper = null; <END> if (applicationContext != null && applicationContext.containsBean("objectMapper")) { objectMapper = (ObjectMapper) applicationContext.getBean("objectMapper"); } if (objectMapper == null && applicationContext != null) { try { objectMapper = BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, ObjectMapper.class); } catch (Exception e) { logger.debug(e); } } if (objectMapper == null) { objectMapper = new ObjectMapper(); } try { jsonRpcRestClient = new JsonRpcRestClient(new URL(getServiceUrl()), objectMapper, restTemplate, new HashMap<String, String>()); jsonRpcRestClient.setRequestListener(requestListener); jsonRpcRestClient.setSslContext(sslContext); jsonRpcRestClient.setHostNameVerifier(hostNameVerifier); if (exceptionResolver!=null) { jsonRpcRestClient.setExceptionResolver(exceptionResolver); } } catch (MalformedURLException mue) { throw new RuntimeException(mue); } ReflectionUtil.clearCache(); }</code><technical_language>Ditto - objectMapper null check</technical_language>

Target:
public void afterPropertiesSet() { super.afterPropertiesSet(); proxyObject = ProxyFactory.getProxy(getObjectType(), this); if (jsonRpcRestClient==null) { if (objectMapper == null && applicationContext != null && applicationContext.containsBean("objectMapper")) { objectMapper = (ObjectMapper) applicationContext.getBean("objectMapper"); } if (objectMapper == null && applicationContext != null) { try { objectMapper = BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, ObjectMapper.class); } catch (Exception e) { logger.debug(e); } } if (objectMapper == null) { objectMapper = new ObjectMapper(); } try { jsonRpcRestClient = new JsonRpcRestClient(new URL(getServiceUrl()), objectMapper, restTemplate, new HashMap<String, String>()); jsonRpcRestClient.setRequestListener(requestListener); jsonRpcRestClient.setSslContext(sslContext); jsonRpcRestClient.setHostNameVerifier(hostNameVerifier); if (exceptionResolver!=null) { jsonRpcRestClient.setExceptionResolver(exceptionResolver); } } catch (MalformedURLException mue) { throw new RuntimeException(mue); } } ReflectionUtil.clearCache(); }
Source:
<code>public AppearanceTabViewModel(DialogService dialogService, JabRefPreferences preferences) { this.dialogService = dialogService; this.preferences = preferences; fontSizeValidator = new FunctionBasedValidator<>( fontSizeProperty, input -> { try { int fontSize = Integer.parseInt(fontSizeProperty().getValue()); <START> return (fontSize > 8) && (fontSize < 22); <END> } catch (NumberFormatException ex) { return false; } }, ValidationMessage.error(String.format("%s > %s %n %n %s", Localization.lang("Appearance"), Localization.lang("Font settings"), Localization.lang("You must enter an integer value in the interval 8-22.")))); }</code><technical_language>limit font size</technical_language>

Target:
public AppearanceTabViewModel(DialogService dialogService, JabRefPreferences preferences) { this.dialogService = dialogService; this.preferences = preferences; fontSizeValidator = new FunctionBasedValidator<>( fontSizeProperty, input -> { try { return Integer.parseInt(fontSizeProperty().getValue()) > 8; } catch (NumberFormatException ex) { return false; } }, ValidationMessage.error(String.format("%s > %s %n %n %s", Localization.lang("Appearance"), Localization.lang("Font settings"), Localization.lang("You must enter an integer value higher than 8.")))); }
Source:
<code>private synchronized List<Role> getSpecialRolesHierarchy() throws DotDataException { <START> if (specialRolesHierarchy == null) { <END> final Role anyWhoCanEditPermisionsContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_PERMISSIONS_ROLE_KEY); final Role anyWhoCanPublishContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_PUBLISH_ROLE_KEY); final Role anyWhoCanEditContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_ROLE_KEY); final Role anyWhoCanViewContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_VIEW_ROLE_KEY); specialRolesHierarchy = ImmutableList .of(anyWhoCanEditPermisionsContent, anyWhoCanPublishContent, anyWhoCanEditContent, anyWhoCanViewContent); } return specialRolesHierarchy; }</code><technical_language>I double check algorithm if (x == null) { sync { if (x == null) { I a java.util.Set</technical_language>

Target:
private List<Role> getSpecialRolesHierarchy() throws DotDataException { if (specialRolesHierarchy == null) { synchronized (this) { if (specialRolesHierarchy == null) { final Role anyWhoCanEditPermisionsContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_PERMISSIONS_ROLE_KEY); final Role anyWhoCanPublishContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_PUBLISH_ROLE_KEY); final Role anyWhoCanEditContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_ROLE_KEY); final Role anyWhoCanViewContent = roleAPI .loadRoleByKey(RoleAPI.WORKFLOW_ANY_WHO_CAN_VIEW_ROLE_KEY); specialRolesHierarchy = ImmutableList .of(anyWhoCanEditPermisionsContent, anyWhoCanPublishContent, anyWhoCanEditContent, anyWhoCanViewContent); } } } return specialRolesHierarchy; }
Source:
<code>protected void buildCommonRecordAttributes(Job item, Record record) { record.setAttribute(ID_ATTR.getName(), item.getId()); long duration = -1; record.setAttribute(STATE_ATTR.getName(), item.getStatus().toString()); record.setAttribute(ISSUES_ATTR.getName(), buildIssuesAttr(item)); record.setAttribute(USER_ATTR.getName(), item.getUser()); record.setAttribute(PRIORITY_ATTR.getName(), item.getPriority().toString()); record.setAttribute(NAME_ATTR.getName(), item.getName()); if (item.getStatus() != JobStatus.IN_ERROR) { if (item.getFinishTime() > 0 && item.getStartTime() > 0) { duration = item.getFinishTime() - item.getStartTime(); } } else { duration = item.getInErrorTime() - item.getStartTime(); } record.setAttribute(DURATION_ATTR.getName(), duration); for (GridColumns extraColumn : EXTRA_COLUMNS) { String columnName = extraColumn.getName(); <START> if (columnName.startsWith(GENERIC_INFORMATION_MATCHER)) { <END> String key = columnName.replace(GENERIC_INFORMATION_MATCHER, ""); record.setAttribute(columnName, item.getGenericInformation().get(key)); } } }</code><technical_language>usage simpler understand if extract retrieval/construction of key/columnName in a dedicated utility class</technical_language>

Target:
protected void buildCommonRecordAttributes(Job item, Record record) { record.setAttribute(ID_ATTR.getName(), item.getId()); long duration = -1; record.setAttribute(STATE_ATTR.getName(), item.getStatus().toString()); record.setAttribute(ISSUES_ATTR.getName(), buildIssuesAttr(item)); record.setAttribute(USER_ATTR.getName(), item.getUser()); record.setAttribute(PRIORITY_ATTR.getName(), item.getPriority().toString()); record.setAttribute(NAME_ATTR.getName(), item.getName()); if (item.getStatus() != JobStatus.IN_ERROR) { if (item.getFinishTime() > 0 && item.getStartTime() > 0) { duration = item.getFinishTime() - item.getStartTime(); } } else { duration = item.getInErrorTime() - item.getStartTime(); } record.setAttribute(DURATION_ATTR.getName(), duration); for (GridColumns extraColumn : EXTRA_COLUMNS) { String columnName = extraColumn.getName(); String key = JobColumnsUtil.getGenericInformationKey(columnName); if (key != null) { record.setAttribute(columnName, item.getGenericInformation().get(key)); } } }
Source:
<code>public void testRemoveColumnMetaFromColumnsForAddDomainSpecifColumns() { TaskListViewImpl taskListView = view; GridGlobalPreferences gridPreferences = new GridGlobalPreferences("test", taskListView.getInitColumns(), taskListView.getBannedColumns()); ListTable<TaskSummary> extendedPagedTable = new ListTable<TaskSummary>(gridPreferences); extendedPagedTable.getGridPreferencesStore().getColumnPreferences().add(new GridColumnPreference("Extra",-1,"")); Set<String> set = new HashSet<String>(); set.add("Extra"); <START> <END> taskListView.initColumns(extendedPagedTable); assertThat(extendedPagedTable.getColumnMetaList().size()).isEqualTo(16); taskListView.addDomainSpecifColumns(extendedPagedTable, set); assertThat(set.size()).isEqualTo(0); }</code><technical_language>@bxf12315 Set<String> set = Collections.singleton("Extra");, instead of "set" named set of represents (for readability of code), e.g. in this case Set<String> headers... that</technical_language>

Target:
public void testRemoveColumnMetaFromColumnsForAddDomainSpecifColumns() { GridGlobalPreferences gridPreferences = new GridGlobalPreferences("test", view.getInitColumns(), view.getBannedColumns()); ListTable<TaskSummary> extendedPagedTable = new ListTable<TaskSummary>(gridPreferences); extendedPagedTable.getGridPreferencesStore().getColumnPreferences().add(new GridColumnPreference("Extra",-1,"")); Set<String> set = Sets.newHashSet("Extra"); view.initColumns(extendedPagedTable); assertThat(extendedPagedTable.getColumnMetaList().size()).isEqualTo(16); view.addDomainSpecifColumns(extendedPagedTable, set); assertThat(set.size()).isEqualTo(0); }
Source:
<code>public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { Socket socket = null; try { socket = pool.borrowObject(address); PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (NumberUtils.isNumeric(value)) { String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix) .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000 + "\n"; log.debug("Graphite Message: {}", line); writer.write(line); writer.flush(); if (writer.checkError()) { log.error("Error writing to Graphite, clearing Graphite socket pool"); pool.returnObject(address, socket); <START> pool.clear(); <END> } } else { log.warn("Unable to submit non-numeric value to Graphite: from result [{}]", value, result); } } } } } finally { pool.returnObject(address, socket); } }</code><technical_language>Clearing pool get rid of a single dirty connection is a bit overkill. is thread safe is a chance dirty connection is out of pool clear (and clear() clears idle objects. invalidateObject() is better. said, good catch ! kind of problems, pinpoint</technical_language>

Target:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { Socket socket = null; PrintWriter writer = null; try { socket = pool.borrowObject(address); writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (NumberUtils.isNumeric(value)) { String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix) .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000 + "\n"; log.debug("Graphite Message: {}", line); writer.write(line); writer.flush(); } else { log.warn("Unable to submit non-numeric value to Graphite: from result [{}]", value, result); } } } } } finally { if (writer != null && writer.checkError()) { log.error("Error writing to Graphite, clearing Graphite socket pool"); pool.invalidateObject(address, socket); } else { pool.returnObject(address, socket); } } }
Source:
<code><START> public void shutdownBlobStore(PartitionId id){ <END> DiskManager diskManager = partitionToDiskManager.get(id); if(diskManager != null){ diskManager.shutdownBlobStore(id); } }</code><technical_language>doc</technical_language>

Target:
public boolean shutdownBlobStore(PartitionId id) { DiskManager diskManager = partitionToDiskManager.get(id); return diskManager != null && diskManager.shutdownBlobStore(id); }
Source:
<code>public void updateImpl(List<Metric> metrics) { Preconditions.checkNotNull(metrics); List<Metric> batch = new ArrayList<Metric>(batchSize); int batchCount = 1; while (metrics.size() > 0) { Metric m = metrics.remove(0); if (m.hasNumberValue()) { batch.add(m); if (batchCount++ % batchSize == 0) { try { cloudWatch.putMetricData(createPutRequest(batch)); } catch (Exception e) { log.error("Error while submitting data for metrics : " + Arrays.toString(batch.toArray()), e); } batch.clear(); } } } if (!batch.isEmpty()) { try { cloudWatch.putMetricData(createPutRequest(batch)); } catch (Exception e) { <START> log.error("Error while submitting data for metrics : " + Arrays.toString(batch.toArray()), e); <END> } } }</code><technical_language>conversion array? log call creates string if log level is high enough, SLF API support that</technical_language>

Target:
public void updateImpl(List<Metric> metrics) { Preconditions.checkNotNull(metrics); List<Metric> batch = new ArrayList<Metric>(batchSize); int batchCount = 1; while (metrics.size() > 0) { Metric m = metrics.remove(0); if (m.hasNumberValue()) { batch.add(m); if (batchCount++ % batchSize == 0) { try { cloudWatch.putMetricData(createPutRequest(batch)); } catch (Exception e) { log.error("Error while submitting data for metrics : " + batch, e); } batch.clear(); } } } if (!batch.isEmpty()) { try { cloudWatch.putMetricData(createPutRequest(batch)); } catch (Exception e) { log.error("Error while submitting data for metrics : " + batch, e); } } }
Source:
<code>public void close(final long timeoutMs) throws InterruptedException, TimeoutException, ExecutionException { <START> <END> }</code><technical_language>throw new NotImplementedException();</technical_language>

Target:
public void close(final long timeoutMs) throws InterruptedException, TimeoutException, ExecutionException { throw new NotImplementedException(); }
Source:
<code>public HypervisorUpdateJob(OwnerCurator ownerCurator, ConsumerCurator consumerCurator, ConsumerTypeCurator consumerTypeCurator, ConsumerResource consumerResource, I18n i18n, SubscriptionServiceAdapter subAdapter, ComplianceRules complianceRules) { this.ownerCurator = ownerCurator; this.consumerCurator = consumerCurator; this.consumerTypeCurator = consumerTypeCurator; this.consumerResource = consumerResource; this.i18n = i18n; this.subAdapter = subAdapter; this.complianceRules = complianceRules; <START> this.hypervisorType = consumerTypeCurator.lookupByLabel(ConsumerTypeEnum.HYPERVISOR.getLabel()); <END> }</code><technical_language>need a bit careful in actual production code: broken if this returns null</technical_language>

Target:
public HypervisorUpdateJob(OwnerCurator ownerCurator, ConsumerCurator consumerCurator, ConsumerTypeCurator consumerTypeCurator, ConsumerResource consumerResource, I18n i18n, SubscriptionServiceAdapter subAdapter, ComplianceRules complianceRules) { this.ownerCurator = ownerCurator; this.consumerCurator = consumerCurator; this.consumerResource = consumerResource; this.i18n = i18n; this.subAdapter = subAdapter; this.complianceRules = complianceRules; this.hypervisorType = consumerTypeCurator.lookupByLabel(ConsumerTypeEnum.HYPERVISOR.getLabel()); if (this.hypervisorType == null) { this.hypervisorType = consumerTypeCurator.create(new ConsumerType(ConsumerTypeEnum.HYPERVISOR)); } }
Source:
<code>public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { AbstractBasePattern pattern = this.pattern; if (pattern == null) { if (!getPatternExpression().evaluate(tuple, ptr)) { if (logger.isDebugEnabled()) { logger.debug("LIKE is FALSE: pattern is null"); } return false; } String value = (String) PVarchar.INSTANCE.toObject(ptr, getPatternExpression().getSortOrder()); pattern = compilePattern(value); if (logger.isDebugEnabled()) { logger.debug("LIKE pattern is expression: " + pattern.pattern()); } } if (!getStrExpression().evaluate(tuple, ptr)) { if (logger.isDebugEnabled()) { logger.debug("LIKE is FALSE: child expression is null"); } return false; } if (ptr.getLength() == 0) { return true; } String value = null; if (logger.isDebugEnabled()) { <START> value = (String) PVarchar.INSTANCE.toObject(ptr, getStrExpression().getSortOrder()); <END> } boolean matched = pattern.macher(ptr, getStrExpression().getSortOrder()).matches(); ptr.set(matched ? PDataType.TRUE_BYTES : PDataType.FALSE_BYTES); if (logger.isDebugEnabled()) { logger.debug("LIKE(value='" + value + "'pattern='" + pattern.pattern() + "' is " + matched); } return true; }</code><technical_language>This is for debugging assuming, want turn ptr a String. Also, rename getStrExpression()</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { AbstractBasePattern pattern = this.pattern; if (pattern == null) { if (!getPatternExpression().evaluate(tuple, ptr)) { if (logger.isTraceEnabled()) { logger.trace("LIKE is FALSE: pattern is null"); } return false; } String value = (String) PVarchar.INSTANCE.toObject(ptr, getPatternExpression().getSortOrder()); pattern = compilePattern(value); if (logger.isTraceEnabled()) { logger.trace("LIKE pattern is expression: " + pattern.pattern()); } } Expression strExpression = getStrExpression(); SortOrder strSortOrder = strExpression.getSortOrder(); PVarchar strDataType = PVarchar.INSTANCE; if (!strExpression.evaluate(tuple, ptr)) { if (logger.isTraceEnabled()) { logger.trace("LIKE is FALSE: child expression is null"); } return false; } String value = null; if (logger.isTraceEnabled()) { value = (String) strDataType.toObject(ptr, strSortOrder); } strDataType.coerceBytes(ptr, strDataType, strSortOrder, SortOrder.ASC); pattern.matches(ptr, ptr); if (logger.isTraceEnabled()) { boolean matched = ((Boolean) PBoolean.INSTANCE.toObject(ptr)).booleanValue(); logger.trace("LIKE(value='" + value + "'pattern='" + pattern.pattern() + "' is " + matched); } return true; }
Source:
<code>public void shouldCreateVisitWithGivenParameters() { Location location = new Location(); location.setName("testLocation"); Patient patient = new Patient(); patient.setUuid("10"); DateTime startDateTime = new DateTime("2010-01-10T07:22:05Z"); DateTime endDateTime = new DateTime("2012-08-01T07:22:05Z"); Visit visit = new Visit(startDateTime.toDate(), endDateTime.toDate(), patient, new VisitType("testVisitType"), location); doReturn(patient).when(patientService).getPatientByUuid(eq(CONFIG_NAME), eq(patient.getUuid())); doReturn(Collections.singletonList(location)) .when(locationService).getLocations(eq(CONFIG_NAME), eq(location.getName())); openMRSActionProxyService.createVisit(CONFIG_NAME, patient.getUuid(), new DateTime(visit.getStartDatetime()), <START> new DateTime(visit.getEndDatetime()), visit.getVisitType().getDisplay(), location.getName()); <END> verify(visitService).createVisit(eq(CONFIG_NAME), visitCaptor.capture()); assertEquals(visit, visitCaptor.getValue()); }</code><technical_language>do send visitType display</technical_language>

Target:
public void shouldCreateVisitWithGivenParameters() { Location location = new Location(); location.setName("testLocation"); Patient patient = new Patient(); patient.setUuid("10"); DateTime startDateTime = new DateTime("2010-01-10T07:22:05Z"); DateTime endDateTime = new DateTime("2012-08-01T07:22:05Z"); Visit visit = new Visit(startDateTime.toDate(), endDateTime.toDate(), patient, new VisitType("ee1b6117-e40b-4082-8880-96aca7ea1472"), location); doReturn(patient).when(patientService).getPatientByUuid(eq(CONFIG_NAME), eq(patient.getUuid())); doReturn(Collections.singletonList(location)) .when(locationService).getLocations(eq(CONFIG_NAME), eq(location.getName())); openMRSActionProxyService.createVisit(CONFIG_NAME, patient.getUuid(), new DateTime(visit.getStartDatetime()), new DateTime(visit.getStopDatetime()), visit.getVisitType().getUuid(), location.getName()); verify(visitService).createVisit(eq(CONFIG_NAME), visitCaptor.capture()); assertEquals(visit, visitCaptor.getValue()); }
Source:
<code>private boolean isArrayElement(ExpressionTree expression) { if (expression.is(Tree.Kind.BRACKET_MEMBER_EXPRESSION)) { <START> BracketMemberExpressionTree bracketExpr = ((BracketMemberExpressionTree) expression); <END> if (bracketExpr.object() instanceof IdentifierTree && ((IdentifierTreeImpl) bracketExpr.object()).hasType(Type.Kind.ARRAY)) { return true; } return ((BracketMemberExpressionTree) expression).property().is(Tree.Kind.NUMERIC_LITERAL); } return false; }</code><technical_language>![MAJOR](<LINK_1> Remove useless parentheses. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private boolean isArrayElement(ExpressionTree expression) { if (expression.is(Tree.Kind.BRACKET_MEMBER_EXPRESSION)) { BracketMemberExpressionTree bracketExpr = ((BracketMemberExpressionTree) expression); return canOnlyBeArray(bracketExpr.object()); } return false; }
Source:
<code>public String retrieveUnProcessButton_action() { errorMessages.setText(""); if (!isDateSearchCriteriaValid()) { LOG.error("Error Message: " + errors); errorMessages.setText(errors); return null; } String startCreationTime = (String) startCreationDate.getText(); String stopCreationTime = (String) stopCreationDate.getText(); String statusValue = (String) status.getValue(); Date startDate = getDate(startCreationTime); Date stopDate = getDate(stopCreationTime); if (startDate == null || stopDate == null) { return null; } DeferredQueueManagerFacade deferredQueueManagerFacade = new DeferredQueueManagerFacade(); List<AsyncMsgRecord> unProcessQueueResults; <START> if (StringUtils.isNotBlank(startCreationTime) && StringUtils.isNotBlank(stopCreationTime) && StringUtils. <END> isNotBlank(statusValue)) { unProcessQueueResults = deferredQueueManagerFacade.queryForDeferredQueueSelected(); } else { unProcessQueueResults = deferredQueueManagerFacade.queryBySearchCriteria(startDate, stopDate, statusValue); } if (unProcessQueueResults == null || unProcessQueueResults.isEmpty()) { errorMessages.setText("No records found to process."); } UserSession userSession = (UserSession) getBean("UserSession"); userSession.setUnProcessQueueResults(null); userSession.getUnProcessQueueResults().addAll(unProcessQueueResults); return null; }</code><technical_language>flipped logic here. if blank, is *not* blank</technical_language>

Target:
public String retrieveUnProcessButton_action() { errorMessages.setText(""); if (!isDateSearchCriteriaValid()) { LOG.error("Error Message: " + errors); errorMessages.setText(errors); return null; } String startCreationTime = (String) startCreationDate.getText(); String stopCreationTime = (String) stopCreationDate.getText(); String statusValue = (String) status.getValue(); Date startDate = getDate(startCreationTime); Date stopDate = getDate(stopCreationTime); if (startDate == null || stopDate == null) { return null; } DeferredQueueManagerFacade deferredQueueManagerFacade = new DeferredQueueManagerFacade(); List<AsyncMsgRecord> unProcessQueueResults; if (StringUtils.isBlank(startCreationTime) && StringUtils.isBlank(stopCreationTime) && StringUtils. isBlank(statusValue)) { unProcessQueueResults = deferredQueueManagerFacade.queryForDeferredQueueSelected(); } else { unProcessQueueResults = deferredQueueManagerFacade.queryBySearchCriteria(startDate, stopDate, statusValue); } if (unProcessQueueResults == null || unProcessQueueResults.isEmpty()) { errorMessages.setText("No records found to process."); } UserSession userSession = (UserSession) getBean("UserSession"); userSession.setUnProcessQueueResults(null); userSession.getUnProcessQueueResults().addAll(unProcessQueueResults); return null; }
Source:
<code>protected Notification newActivityNotification(Context context, HostBean host) { <START> NotificationCompat.Builder notification = newNotificationBuilder(context); <END> Resources res = context.getResources(); String contentText = res.getString( R.string.notification_text, host.getNickname()); Intent notificationIntent = new Intent(context, ConsoleActivity.class); notificationIntent.setAction("android.intent.action.VIEW"); notificationIntent.setData(host.getUri()); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setContentTitle(res.getString(R.string.app_name)) .setContentText(contentText) .setContentIntent(contentIntent); notification.setAutoCancel(true); int ledOnMS = 300; int ledOffMS = 1000; notification.setDefaults(Notification.DEFAULT_LIGHTS); if (HostDatabase.COLOR_RED.equals(host.getColor())) notification.setLights(Color.RED, ledOnMS, ledOffMS); else if (HostDatabase.COLOR_GREEN.equals(host.getColor())) notification.setLights(Color.GREEN, ledOnMS, ledOffMS); else if (HostDatabase.COLOR_BLUE.equals(host.getColor())) notification.setLights(Color.BLUE, ledOnMS, ledOffMS); else notification.setLights(Color.WHITE, ledOnMS, ledOffMS); return notification.build(); }</code><technical_language>rename variable "builder" more clear</technical_language>

Target:
protected Notification newActivityNotification(Context context, HostBean host) { NotificationCompat.Builder builder = newNotificationBuilder(context); Resources res = context.getResources(); String contentText = res.getString( R.string.notification_text, host.getNickname()); Intent notificationIntent = new Intent(context, ConsoleActivity.class); notificationIntent.setAction("android.intent.action.VIEW"); notificationIntent.setData(host.getUri()); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); builder.setContentTitle(res.getString(R.string.app_name)) .setContentText(contentText) .setContentIntent(contentIntent); builder.setAutoCancel(true); int ledOnMS = 300; int ledOffMS = 1000; builder.setDefaults(Notification.DEFAULT_LIGHTS); if (HostDatabase.COLOR_RED.equals(host.getColor())) builder.setLights(Color.RED, ledOnMS, ledOffMS); else if (HostDatabase.COLOR_GREEN.equals(host.getColor())) builder.setLights(Color.GREEN, ledOnMS, ledOffMS); else if (HostDatabase.COLOR_BLUE.equals(host.getColor())) builder.setLights(Color.BLUE, ledOnMS, ledOffMS); else builder.setLights(Color.WHITE, ledOnMS, ledOffMS); return builder.build(); }
Source:
<code>private void addAttributesToEntityType(IApsEntity entityType, KieProcessFormQueryResult form) { <START> logger.debug("AddAttributesToEntityType"); <END> if (null != form && null != form.getFields()) { if (form.getFields().size() > 0) { try { if (form.getFields().get(0).getName().contains("_")) { this.processForm(form.getFields().get(0), this.getCurrentLang().getCode()); } else { String formName = null; if (KieApiUtil.getFieldProperty(form.getProperties(), "name").contains(".")) { formName = KieApiUtil.getFieldProperty(form.getProperties(), "name") .substring(0, KieApiUtil.getFieldProperty(form.getProperties(), "name").indexOf(".")); } else { formName = KieApiUtil.getFieldProperty(form.getProperties(), "name"); } String formLabel = KieApiUtil.getI18nFormLabelProperty(formName); if (null == this.getI18nManager().getLabel(formLabel, this.getCurrentLang().getCode())) { this.saveEntandoLabel(formLabel, formName); } } } catch (ApsSystemException ex) { logger.error("error on addAttributesToEntityType {}", ex); } } for (KieProcessFormField field : form.getFields()) { logger.debug("addAttributeToEntityType {}", field.getName()); this.addAttributeToEntityType(entityType, field); } if (null != form.getNestedForms()) { for (KieProcessFormQueryResult subForm : form.getNestedForms()) { logger.debug("addAttributeToEntityType getNestedForms"); this.addAttributesToEntityType(entityType, subForm); } } } }</code><technical_language>Is this needed</technical_language>

Target:
private void addAttributesToEntityType(IApsEntity entityType, KieProcessFormQueryResult form) { if (null != form && null != form.getFields()) { if (form.getFields().size() > 0) { try { if (form.getFields().get(0).getName().contains("_")) { this.processForm(form.getFields().get(0), this.getCurrentLang().getCode()); } else { String formName = null; if (KieApiUtil.getFieldProperty(form.getProperties(), "name").contains(".")) { formName = KieApiUtil.getFieldProperty(form.getProperties(), "name") .substring(0, KieApiUtil.getFieldProperty(form.getProperties(), "name").indexOf(".")); } else { formName = KieApiUtil.getFieldProperty(form.getProperties(), "name"); } String formLabel = KieApiUtil.getI18nFormLabelProperty(formName); if (null == this.getI18nManager().getLabel(formLabel, this.getCurrentLang().getCode())) { this.saveEntandoLabel(formLabel, formName); } } } catch (ApsSystemException ex) { logger.error("error on addAttributesToEntityType {}", ex); } } for (KieProcessFormField field : form.getFields()) { this.addAttributeToEntityType(entityType, field); } if (null != form.getNestedForms()) { for (KieProcessFormQueryResult subForm : form.getNestedForms()) { logger.debug("addAttributeToEntityType for nested forms"); this.addAttributesToEntityType(entityType, subForm); } } } }
Source:
<code>public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); <START> inflater.inflate(R.menu.history_details, menu); <END> }</code><technical_language>suggestion inflater.inflate(R.menu.history_detail, menu); rename this menu history_detail for consistency</technical_language>

Target:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.history_detail, menu); }
Source:
<code>public void onPartitionStateChangeToLeaderFromStandby(String partitionName) { logger.debug("Partition state change notification from Standby to Leader received for partition {}", partitionName); synchronized (notificationLock) { try { addCloudReplica(partitionName); } catch (ReplicationException rex) { logger.error("Could not add replication for paritition {}", partitionName); <START> } <END> } }</code><technical_language>suggest changing INFO level</technical_language>

Target:
public void onPartitionStateChangeToLeaderFromStandby(String partitionName) { logger.info("Partition state change notification from Standby to Leader received for partition {}", partitionName); synchronized (notificationLock) { try { addCloudReplica(partitionName); } catch (ReplicationException rex) { logger.error("Exception while adding replication for partition {}", rex, partitionName); replicationMetrics.addCloudPartitionErrorCount.inc(); } } }
Source:
<code>public long abort() throws UnknownHttpResponseException { <START> return parseLong(_run("abort", new JSONObject())); <END> }</code><technical_language>abort modify mod time, return. returning encoded json (null), long get a 200 reply command succeeded</technical_language>

Target:
public void abort() throws UnknownHttpResponseException { _run("abort", new JSONObject()); }