auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void validateApplicationContributions(IBuildEntry binIncludes) { <END> try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(PDEProject.getPluginXml(fProject).getContents()); XPath xpath = XPathFactory.newInstance().newXPath(); Node nodeProduct = (Node) xpath.evaluate("/plugin/extension[@point='org.eclipse.core.runtime.products']/product", doc, XPathConstants.NODE); if (nodeProduct != null) { Node attValue = (Node) xpath.evaluate("property[@name='applicationXMI']/@value", nodeProduct, XPathConstants.NODE); if (attValue != null) { if (attValue.getNodeValue().isEmpty()) { } else { validateBinIncludes(binIncludes, attValue.getNodeValue()); } } else { validateBinIncludes(binIncludes, "Application.e4xmi"); } } } catch (Exception e) { e.printStackTrace(); } }</code><technical_language>this method private</technical_language>

Target:
private void validateApplicationContributions(IBuildEntry binIncludes) { try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(PDEProject.getPluginXml(fProject).getContents()); XPath xpath = XPathFactory.newInstance().newXPath(); Node nodeProduct = (Node) xpath.evaluate("/plugin/extension[@point='org.eclipse.core.runtime.products']/product", doc, XPathConstants.NODE); if (nodeProduct != null) { Node attValue = (Node) xpath.evaluate("property[@name='applicationXMI']/@value", nodeProduct, XPathConstants.NODE); if (attValue != null) { if (attValue.getNodeValue().isEmpty()) { } else { validateBinIncludes(binIncludes, attValue.getNodeValue()); } } else { validateBinIncludes(binIncludes, "Application.e4xmi"); } } } catch (Exception e) { e.printStackTrace(); } }
Source:
<code>public YamlClientFailoverConfigBuilder(String resource) throws IOException { URL url = ConfigLoader.locateConfig(resource); <START> if (url == null) { <END> throw new IllegalArgumentException("Could not load " + resource); } this.in = url.openStream(); }</code><technical_language>if decided throw IllegalArgumentException, I prefer a utility method instead of repeating this if statement. I is repeated 9 times in this PR</technical_language>

Target:
public YamlClientFailoverConfigBuilder(String resource) throws IOException { URL url = ConfigLoader.locateConfig(resource); checkTrue(url != null, "Could not load " + resource); this.in = url.openStream(); }
Source:
<code>public void onImageProcessed(UploadItem uploadItem, Place place) { this.uploadItem = uploadItem; if (uploadItem.getTitle() != null) { etTitle.setText(uploadItem.getTitle().toString()); } descriptions = uploadItem.getDescriptions(); compositeDisposable .add(downSampleImage(uploadItem.getContentUri()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(bitmap -> { if (null != bitmap) { <START> photoViewBackgroundImage.setImageBitmap(bitmap); <END> } }, Timber::d)); setDescriptionsInAdapter(descriptions); }</code><technical_language>a SimpleDraweeView .setImageURI avoid manual bounds decoding</technical_language>

Target:
public void onImageProcessed(UploadItem uploadItem, Place place) { this.uploadItem = uploadItem; if (uploadItem.getTitle() != null) { etTitle.setText(uploadItem.getTitle().toString()); } descriptions = uploadItem.getDescriptions(); showImageWithLocalUri(uploadItem.getMediaUri()); setDescriptionsInAdapter(descriptions); }
Source:
<code>private void updateNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("id"); String name = (String) fromMessage.get("name"); Map<String, Object> config = (Map<String, Object>) fromMessage.get("config"); if (noteId == null) { return; } if (config == null) { return; } if (!hasParagraphWriterPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "update")) { return; } Note note = notebook.getNote(noteId); if (note != null) { if (!notebook.getConf().isZeppelinNotebookCronEnable()) { if (config.get("cron") != null) { <START> config.remove("cron"); <END> } } boolean cronUpdated = isCronUpdated(config, note.getConfig()); note.setName(name); note.setConfig(config); if (cronUpdated) { notebook.refreshCron(note.getId()); } AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); note.persist(subject); broadcast(note.getId(), new Message(OP.NOTE_UPDATED).put("name", name).put("config", config) .put("info", note.getInfo())); broadcastNoteList(subject, userAndRoles); } }</code><technical_language>hmm, - is this modify notebook? if cron is disabled modify content permanently - if cron is enabled note work as-is before</technical_language>

Target:
private void updateNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message fromMessage) throws IOException { String noteId = (String) fromMessage.get("id"); String name = (String) fromMessage.get("name"); Map<String, Object> config = (Map<String, Object>) fromMessage.get("config"); if (noteId == null) { return; } if (config == null) { return; } if (!hasParagraphWriterPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "update")) { return; } Note note = notebook.getNote(noteId); if (note != null) { if (!(Boolean) note.getConfig().get("isZeppelinNotebookCronEnable")) { if (config.get("cron") != null) { config.remove("cron"); } } boolean cronUpdated = isCronUpdated(config, note.getConfig()); note.setName(name); note.setConfig(config); if (cronUpdated) { notebook.refreshCron(note.getId()); } AuthenticationInfo subject = new AuthenticationInfo(fromMessage.principal); note.persist(subject); broadcast(note.getId(), new Message(OP.NOTE_UPDATED).put("name", name).put("config", config) .put("info", note.getInfo())); broadcastNoteList(subject, userAndRoles); } }
Source:
<code>public List<String> validateQuestionDetails(String courseId) { List<String> errors = new ArrayList<>(); if (!distributeToRecipients && numOfConstSumOptions < Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_OPTIONS) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_NOT_ENOUGH_OPTIONS + Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_OPTIONS + "."); } if (points < Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_POINTS) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_NOT_ENOUGH_POINTS + Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_POINTS + "."); } if (!FieldValidator.areElementsUnique(constSumOptions)) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_DUPLICATE_OPTIONS); } <START> if (maxPointsConstraint != NO_MIN_MAX_CONSTRAINT && minPointsConstraint > maxPointsConstraint) { <END> errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_MIN_CONSTRAINT_GREATER_THAN_MAX); } return errors; }</code><technical_language>Cases u want cover: 1. onlyMinPointsConstraint -> bigger zero 2. onlyMaxPointsConstraint -> bigger zero 3. bothMinMaxPointsConstraint -> bigger zero (covered above) min < max</technical_language>

Target:
public List<String> validateQuestionDetails(String courseId) { List<String> errors = new ArrayList<>(); if (!distributeToRecipients && numOfConstSumOptions < Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_OPTIONS) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_NOT_ENOUGH_OPTIONS + Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_OPTIONS + "."); } if (points < Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_POINTS) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_NOT_ENOUGH_POINTS + Const.FeedbackQuestion.CONST_SUM_MIN_NUM_OF_POINTS + "."); } if (!FieldValidator.areElementsUnique(constSumOptions)) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_DUPLICATE_OPTIONS); } if (minPointsConstraint != NO_MIN_MAX_CONSTRAINT && minPointsConstraint < 0) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_MIN_POINTS_CONSTRAINT_LESS_THAN_ZERO); } if (maxPointsConstraint != NO_MIN_MAX_CONSTRAINT && maxPointsConstraint < 1) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_MAX_POINTS_CONSTRAINT_LESS_THAN_ONE); } if (minPointsConstraint != NO_MIN_MAX_CONSTRAINT && maxPointsConstraint != NO_MIN_MAX_CONSTRAINT && minPointsConstraint > maxPointsConstraint) { errors.add(Const.FeedbackQuestion.CONST_SUM_ERROR_MIN_CONSTRAINT_GREATER_THAN_MAX); } return errors; }
Source:
<code>public Blob watermarkWithPdf(Blob inBlob) throws NuxeoException { Blob result = null; PDDocument pdfDoc = null; PDDocument pdfOverlayDoc = null; <START> try { <END> pdfDoc = PDDocument.load(blob.getStream()); pdfOverlayDoc = PDDocument.load(inBlob.getStream()); Overlay overlay = new Overlay(); overlay.overlay(pdfOverlayDoc, pdfDoc); result = PDFUtils.saveInTempFile(pdfDoc); } catch (IOException | COSVisitorException e) { throw new NuxeoException(e); } finally { PDFUtils.closeSilently(pdfDoc, pdfOverlayDoc); } return result; }</code><technical_language>try resource</technical_language>

Target:
public Blob watermarkWithPdf(Blob inBlob) throws NuxeoException { Blob result; PDDocument pdfOverlayDoc; try (PDDocument pdfDoc = PDDocument.load(blob.getStream())) { pdfOverlayDoc = PDDocument.load(inBlob.getStream()); Overlay overlay = new Overlay(); overlay.overlay(pdfOverlayDoc, pdfDoc); result = PDFUtils.saveInTempFile(pdfDoc); } catch (IOException | COSVisitorException e) { throw new NuxeoException(e); } return result; }
Source:
<code>public MessageStream<M> merge(Collection<MessageStream<M>> otherStreams) { MessageStreamImpl<M> outputStream = new MessageStreamImpl<>(); otherStreams.add(this); otherStreams.forEach(other -> ((MessageStreamImpl<M>) other) <START> .getRegisteredOperatorSpecs() <END> .add(OperatorSpecs.createMergeOperator(outputStream))); return outputStream; }</code><technical_language>returning a mutable Collection of getRegisteredOperatorSpecs() here? This method is meant for implementation/internal usage for users. I felt OK put scope of MessageStream's public method a) code structure better; b) returns immutable collection user (programmer) change. prefer characteristics if public method visible programmers</technical_language>

Target:
public MessageStream<M> merge(Collection<MessageStream<M>> otherStreams) { MessageStreamImpl<M> outputStream = new MessageStreamImpl<>(); otherStreams.add(this); otherStreams.forEach(other -> ((MessageStreamImpl<M>) other).registeredOperatorSpecs.add(OperatorSpecs.createMergeOperator(outputStream))); return outputStream; }
Source:
<code>protected void onBind() { super.onBind(); registerHandler(getTable().getSelectionModel() .addSelectionChangeHandler(event -> { modelProvider.setSelectedItems(getSelectedItems()); fireTableSelectionChangeEvent(); if (!isVisible()) { handlePlaceTransition(); } })); registerHandler(getEventBus().addHandler(ApplySearchStringEvent.getType(), event -> { applySearchString(event.getSearchString()); })); getView().setDetailPlaceTransitionHandler(this); this.breadCrumbs.setSelectionModel(getTable().getSelectionModel()); <START> searchStringCollector.markActivePrefix(modelProvider.getModel().getDefaultSearchString()); <END> String searchString = searchStringCollector.getSearchString(modelProvider.getModel().getSearchString()); if (searchString != null) { applySearchString(searchString); } }</code><technical_language>this line in onReveal() hook</technical_language>

Target:
protected void onBind() { super.onBind(); registerHandler(getTable().getSelectionModel() .addSelectionChangeHandler(event -> { modelProvider.setSelectedItems(getSelectedItems()); fireTableSelectionChangeEvent(); if (!isVisible()) { handlePlaceTransition(); } })); registerHandler(getEventBus().addHandler(ApplySearchStringEvent.getType(), event -> { applySearchString(event.getSearchString()); })); getView().setDetailPlaceTransitionHandler(this); searchStringCollector.markActivePrefix(modelProvider.getModel().getDefaultSearchString()); String searchString = searchStringCollector.getSearchStringPrefix(modelProvider.getModel().getSearchString()); if (searchString != null) { applySearchString(searchString); } }
Source:
<code>private AbstractGCEvent<?> handleTail(ParseContext context, AbstractGCEvent<?> event, String tags, String tail) { AbstractGCEvent<?> returnEvent = event; <START> switch (tags) { <END> case TAG_GC_START: returnEvent = handleTagGcStartTail(context, event); break; case TAG_GC_HEAP: returnEvent = handleTagGcHeapTail(context, event, tail); if (returnEvent == null) { break; } case TAG_GC_METASPACE: returnEvent = handleTagGcMetaspaceTail(context, event, tail); break; case TAG_GC: returnEvent = handleTagGcTail(context, event, tail); break; case TAG_GC_PHASES: returnEvent = parseTail(context, event, tail); break; default: getLogger().warning(String.format("Unexpected tail present in the end of line number %d (tail=\"%s\"; line=\"%s\")", in.getLineNumber(), tail, context.getLine())); } return returnEvent; }</code><technical_language>nice this switch shortened code moved separate methods</technical_language>

Target:
private AbstractGCEvent<?> handleTail(ParseContext context, AbstractGCEvent<?> event, String tags, String tail) { AbstractGCEvent<?> returnEvent = event; switch (tags) { case TAG_GC_START: returnEvent = handleTagGcStartTail(context, event); break; case TAG_GC_HEAP: returnEvent = handleTagGcHeapTail(context, event, tail); if (returnEvent == null) { break; } case TAG_GC_METASPACE: returnEvent = handleTagGcMetaspaceTail(context, event, tail); break; case TAG_GC: returnEvent = handleTagGcTail(context, event, tail); break; case TAG_GC_PHASES: returnEvent = handleTagGcPhasesTail(context, event, tail); break; default: getLogger().warning(String.format("Unexpected tail present in the end of line number %d (tail=\"%s\"; line=\"%s\")", in.getLineNumber(), tail, context.getLine())); } return returnEvent; }
Source:
<code>public void maybeRotate(long currentTimeMillis) { final long rotateBefore = currentTimeMillis - mRotateAgeMillis; final long deleteBefore = currentTimeMillis - mDeleteAgeMillis; final FileInfo info = new FileInfo(mPrefix); String[] baseFiles = mBasePath.list(); if (baseFiles == null) { <START> Slog.e(TAG, "retrieving files from " + mBasePath + " returned null"); <END> return; } for (String name : baseFiles) { if (!info.parse(name)) continue; if (info.isActive()) { if (info.startMillis <= rotateBefore) { if (LOGD) Slog.d(TAG, "rotating " + name); info.endMillis = currentTimeMillis; final File file = new File(mBasePath, name); final File destFile = new File(mBasePath, info.build()); file.renameTo(destFile); } } else if (info.endMillis <= deleteBefore) { if (LOGD) Slog.d(TAG, "deleting " + name); final File file = new File(mBasePath, name); file.delete(); } } }</code><technical_language>need log, return. for return null boot</technical_language>

Target:
public void maybeRotate(long currentTimeMillis) { final long rotateBefore = currentTimeMillis - mRotateAgeMillis; final long deleteBefore = currentTimeMillis - mDeleteAgeMillis; final FileInfo info = new FileInfo(mPrefix); String[] baseFiles = mBasePath.list(); if (baseFiles == null) { return; } for (String name : baseFiles) { if (!info.parse(name)) continue; if (info.isActive()) { if (info.startMillis <= rotateBefore) { if (LOGD) Slog.d(TAG, "rotating " + name); info.endMillis = currentTimeMillis; final File file = new File(mBasePath, name); final File destFile = new File(mBasePath, info.build()); file.renameTo(destFile); } } else if (info.endMillis <= deleteBefore) { if (LOGD) Slog.d(TAG, "deleting " + name); final File file = new File(mBasePath, name); file.delete(); } } }
Source:
<code>private boolean hasLostSubDataTypes(final DataType dataType) { final ItemDefinition itemDefinition = itemDefinitionStore.get(dataType.getUUID()); <START> return !isStructure(dataType) && itemDefinition.getTypeRef() == null; <END> }</code><technical_language>covered this private method tests: - testIfDataTypeDoesNotHaveLostSubDataTypesWhenCallbackIsExecuted - testIfDataTypeDoesNotHaveLostSubDataTypesWhenCallbackIsNotExecuted in tests itemDefinition.getTypeRef() == null is evaluated true ask if this part of condition is needed if is kind of forgotten early development phase</technical_language>

Target:
private boolean hasLostSubDataTypes(final DataType dataType) { final ItemDefinition itemDefinition = itemDefinitionStore.get(dataType.getUUID()); final boolean isDataTypeNotStructure = !isStructure(dataType); final boolean hasItemDefinitionSubItemDefinitions = !itemDefinition.getItemComponent().isEmpty(); return isDataTypeNotStructure && hasItemDefinitionSubItemDefinitions; }
Source:
<code><START> public void reset(MessageBuffer buf) { <END> this.buffer = buf; this.isRead = false; }</code><technical_language>public MesageBuffer reset(MessageBuffer buf)</technical_language>

Target:
public MessageBuffer reset(MessageBuffer buf) { MessageBuffer old = this.buffer; this.buffer = buf; this.isRead = false; return old; }
Source:
<code>private InterpreterGroup findInterpreterGroupForParagraph(Note note, String paragraphId) throws Exception { final Paragraph paragraph = note.getParagraph(paragraphId); if (paragraph == null) { throw new IllegalArgumentException("Unknown paragraph with id : " + paragraphId); } <START> return paragraph.getInterpreter().getInterpreterGroup(); <END> }</code><technical_language>I getInterpreter is a bit generic - getInterpreter in other classes purposes this</technical_language>

Target:
private InterpreterGroup findInterpreterGroupForParagraph(Note note, String paragraphId) throws Exception { final Paragraph paragraph = note.getParagraph(paragraphId); if (paragraph == null) { throw new IllegalArgumentException("Unknown paragraph with id : " + paragraphId); } return paragraph.getBindedInterpreter().getInterpreterGroup(); }
Source:
<code>public void setupWindow() { <START> browser.manage().window().maximize(); <END> browser.navigate().refresh(); Console.withBrowser(browser).refreshAndNavigate(HomePage.class); Console.withBrowser(browser).waitUntilLoaded(); }</code><technical_language>Console.withBrowser(browser).refreshAndNavigate(HomePage.class); is IMHO needed line in this method I missing anything</technical_language>

Target:
public void setupWindow() { Console.withBrowser(browser).refreshAndNavigate(HomePage.class); }
Source:
<code>public static CredentialInfo from(String connectionString) { CredentialInfo credentialInfo = new CredentialInfo(); if (ImplUtils.isNullOrEmpty(connectionString)) { <START> throw new IllegalArgumentException(connectionString); <END> } String[] args = connectionString.split(";"); if (args.length < 3) { throw new IllegalArgumentException("invalid connection string segment count"); } for (String arg : args) { String segment = arg.trim(); if (segment.startsWith(ENDPOINT)) { try { credentialInfo.endpoint = new URI(segment.substring(ENDPOINT.length())); } catch (URISyntaxException e) { throw new IllegalArgumentException(String.format(Locale.US, "Invalid endpoint: %s", segment), e); } } else if (segment.startsWith(SHARED_ACCESS_KEY_NAME)) { credentialInfo.sharedAccessKeyName = segment.substring(SHARED_ACCESS_KEY_NAME.length()); } else if (segment.startsWith(SHARED_ACCESS_KEY)) { credentialInfo.sharedAccessKey = segment.substring(SHARED_ACCESS_KEY.length()); } else if (segment.startsWith(ENTITY_PATH)) { credentialInfo.eventHubName = segment.substring(ENTITY_PATH.length()); } } if (credentialInfo.endpoint == null || credentialInfo.sharedAccessKeyName == null || credentialInfo.sharedAccessKey == null) { throw new IllegalArgumentException("Could not parse 'connectionString'." + " Expected format: 'Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey}'. Actual:" + connectionString); } return credentialInfo; }</code><technical_language>This a message, variable, null empty</technical_language>

Target:
public static CredentialInfo from(String connectionString) { return createCredentialInfo(connectionString, null); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { RebaseCurrentRefCommand rebaseCurrent = new RebaseCurrentRefCommand(); rebaseCurrent.setEnabled(event.getApplicationContext()); <START> if (rebaseCurrent.isEnabled()) { <END> return rebaseCurrent.execute(event); } else { return null; } }</code><technical_language>style nit: braces</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { RebaseCurrentRefCommand rebaseCurrent = new RebaseCurrentRefCommand(); rebaseCurrent.setEnabled(event.getApplicationContext()); if (rebaseCurrent.isEnabled()) return rebaseCurrent.execute(event); else return null; }
Source:
<code>private String allRegionsSpoken() { List<String> activeRegions = obaClient.getAllRegions() .stream() <START> .filter(r -> RegionUtils.isRegionUsable(r) && !r.getExperimental()) <END> .map(r -> String.format("%s, ", r.getName())) .collect(Collectors.toList()); int lastElem = activeRegions.size()-1; activeRegions.set(lastElem, activeRegions.get(lastElem).replaceFirst(", $", "")); if (activeRegions.size() > 1) { activeRegions.add(lastElem, "and "); } String finalStr = activeRegions.stream().collect(Collectors.joining("")); log.debug("All regions spoken: " + finalStr); return finalStr; }</code><technical_language>consistent other code check if r.getObaBaseUrl() == null, if remove region well</technical_language>

Target:
private String allRegionsSpoken() { List<String> activeRegions = obaClient.getAllRegions() .stream() .filter(r -> RegionUtils.isRegionUsable(r) && !r.getExperimental() && r.getObaBaseUrl() != null) .map(r -> String.format("%s, ", r.getName())) .sorted() .collect(Collectors.toList()); int lastElem = activeRegions.size()-1; activeRegions.set(lastElem, activeRegions.get(lastElem).replaceFirst(", $", "")); if (activeRegions.size() > 1) { activeRegions.add(lastElem, "and "); } String finalStr = activeRegions.stream().collect(Collectors.joining("")); log.debug("All regions spoken: " + finalStr); return finalStr; }
Source:
<code>private ResponseEntity<Object> getStudySubjectInfo(String studyOid, String siteOid, String participantID,boolean includeRelatedInfo,HttpServletRequest request) throws Exception { ResponseEntity<Object> response = null; try { StudyBean study = null; try { study = this.getRestfulServiceHelper().setSchema(studyOid, request); study = participantService.validateRequestAndReturnStudy(studyOid, siteOid,request); if(study != null) { StudyParticipantDetailDTO responseSuccess = new StudyParticipantDetailDTO(); responseSuccess = getStudyParticipantDTO(request,studyOid, siteOid,study,participantID,includeRelatedInfo); response = new ResponseEntity(responseSuccess, org.springframework.http.HttpStatus.OK); } } catch (OpenClinicaSystemException e) { String errorMsg = e.getErrorCode(); HashMap<String, String> map = new HashMap<>(); map.put("studyOid", studyOid); map.put("siteOid", siteOid); map.put("participantID", participantID); ParameterizedErrorVM responseDTO =new ParameterizedErrorVM(errorMsg, map); response = new ResponseEntity(responseDTO, HttpStatus.BAD_REQUEST); return response; } } catch (Exception eee) { <START> eee.printStackTrace(); <END> throw eee; } return response; }</code><technical_language>log.error("Error ....", e);</technical_language>

Target:
private ResponseEntity<Object> getStudySubjectInfo(String studyOid, String siteOid, String participantID,boolean includeRelatedInfo,HttpServletRequest request) throws Exception { ResponseEntity<Object> response = null; try { StudyBean study = null; try { study = this.getRestfulServiceHelper().setSchema(studyOid, request); study = participantService.validateRequestAndReturnStudy(studyOid, siteOid,request); if(study != null) { StudyParticipantDetailDTO responseSuccess = new StudyParticipantDetailDTO(); responseSuccess = getStudyParticipantDTO(request,studyOid, siteOid,study,participantID,includeRelatedInfo); response = new ResponseEntity(responseSuccess, org.springframework.http.HttpStatus.OK); } } catch (OpenClinicaSystemException e) { String errorMsg = e.getErrorCode(); HashMap<String, String> map = new HashMap<>(); map.put("studyOid", studyOid); map.put("siteOid", siteOid); map.put("participantID", participantID); ParameterizedErrorVM responseDTO =new ParameterizedErrorVM(errorMsg, map); response = new ResponseEntity(responseDTO, HttpStatus.BAD_REQUEST); return response; } } catch (Exception eee) { logger.error("Error...", eee); throw eee; } return response; }
Source:
<code>protected void ExecuteVmCommand() { List<VM> vms = DbFacade.getInstance().getVmDAO().getAllForDedicatedPowerClientByVds(getVdsId()); if (vms != null && vms.size() != 0) { vms.get(0).setdedicated_vm_for_vds(null); DbFacade.getInstance().getVmStaticDAO().update(vms.get(0).getStaticData()); } VM vm = DbFacade.getInstance().getVmDAO().get(getVmId()); <START> VmHandler.updateNetworkInterfacesFromDb(vm); <END> vm.setdedicated_vm_for_vds(!(getVdsId().equals(Guid.Empty)) ? getVdsId() : null); DbFacade.getInstance().getVmStaticDAO().update(vm.getStaticData()); setSucceeded(true); }</code><technical_language>removed</technical_language>

Target:
protected void ExecuteVmCommand() { List<VM> vms = getVmDAO().getAllForDedicatedPowerClientByVds(getVdsId()); if (vms != null && vms.size() != 0) { vms.get(0).setdedicated_vm_for_vds(null); getVmStaticDAO().update(vms.get(0).getStaticData()); } VM vm = getVmDAO().get(getVmId()); vm.setdedicated_vm_for_vds(!(getVdsId().equals(Guid.Empty)) ? getVdsId() : null); getVmStaticDAO().update(vm.getStaticData()); setSucceeded(true); }
Source:
<code>public void register(@PathVariable("type") ApplicationType type, @PathVariable("name") String name, @PathVariable("version") String version, @RequestParam("uri") String uri, @RequestParam(name = "metadata-uri", required = false) String metadataUri, @RequestParam(value = "force", defaultValue = "false") boolean force) { <START> AppRegistration defaultApp = appRegistryService.getDefaultApp(name, type); <END> if (defaultApp != null && StringUtils.hasText(version)) { String defaultAppUri = defaultApp.getUri().toString(); String defaultAppUriNoVersion = removeLastMatch(defaultAppUri, defaultApp.getVersion()); String newAppUriNoVersion = removeLastMatch(uri, version); if (!ObjectUtils.nullSafeEquals(defaultAppUriNoVersion, newAppUriNoVersion)) { throw new IllegalArgumentException("Existing default application [" + defaultAppUri + "] can only differ by a version but is [" + uri + "]"); } } AppRegistration previous = appRegistryService.find(name, type, version); if (!force && previous != null) { throw new AppAlreadyRegisteredException(previous); } try { AppRegistration registration = this.appRegistryService.save(name, type, version, new URI(uri), metadataUri != null ? new URI(metadataUri) : null); prefetchMetadata(Arrays.asList(registration)); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }</code><technical_language>I move this logic out of controller a validate method appRegistryService</technical_language>

Target:
public void register(@PathVariable("type") ApplicationType type, @PathVariable("name") String name, @PathVariable("version") String version, @RequestParam("uri") String uri, @RequestParam(name = "metadata-uri", required = false) String metadataUri, @RequestParam(value = "force", defaultValue = "false") boolean force) { appRegistryService.validate(appRegistryService.getDefaultApp(name, type), uri, version); AppRegistration previous = appRegistryService.find(name, type, version); if (!force && previous != null) { throw new AppAlreadyRegisteredException(previous); } try { AppRegistration registration = this.appRegistryService.save(name, type, version, new URI(uri), metadataUri != null ? new URI(metadataUri) : null); prefetchMetadata(Arrays.asList(registration)); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
Source:
<code>private void checkForContainedIn(XProperty member, TypeMetadata.Builder typeMetadataBuilder, ParseContext parseContext) { ContainedIn containedInAnnotation = member.getAnnotation( ContainedIn.class ); if ( containedInAnnotation == null ) { return; } <START> ContainedInMetadata containedInMetadata = new ContainedInMetadata( member ); <END> updateContainedInMaxDepths( containedInMetadata, member ); typeMetadataBuilder.addContainedIn( containedInMetadata ); typeMetadataBuilder.addCollectionRole( StringHelper.qualify( parseContext.getCurrentClass().getName(), member.getName() ) ); }</code><technical_language>reasonable, a builder</technical_language>

Target:
private void checkForContainedIn(XProperty member, TypeMetadata.Builder typeMetadataBuilder, ParseContext parseContext) { ContainedIn containedInAnnotation = member.getAnnotation( ContainedIn.class ); if ( containedInAnnotation == null ) { return; } ContainedInMetadataBuilder containedInMetadataBuilder = new ContainedInMetadataBuilder( member ); updateContainedInMaxDepths( containedInMetadataBuilder, member ); typeMetadataBuilder.addContainedIn( containedInMetadataBuilder.createContainedInMetadata() ); typeMetadataBuilder.addCollectionRole( StringHelper.qualify( parseContext.getCurrentClass().getName(), member.getName() ) ); }
Source:
<code>static <T extends PublicKey> Certificate<T> readPubKey(Buffer<?> buf, KeyType innerKeyType) throws GeneralSecurityException { final byte[] nonce; final T key; final BigInteger serial; long type; String id; List<String> validPrincipals; Date validAfter; Date validBefore; Map<String, String> critOptions; Map<String, String> extensions; byte[] signatureKey; byte[] signature; try { <START> nonce = buf.readStringAsBytes(); <END> key = (T) innerKeyType.readPubKeyFromBuffer(buf); serial = buf.readUInt64AsBigInteger(); type = buf.readUInt32(); id = buf.readString(); validPrincipals = unpackList(buf.readStringAsBytes()); validAfter = dateFromEpoch(buf.readUInt64()); validBefore = dateFromEpoch(buf.readUInt64()); critOptions = unpackMap(buf.readStringAsBytes()); extensions = unpackMap(buf.readStringAsBytes()); buf.readString(); signatureKey = buf.readStringAsBytes(); signature = buf.readStringAsBytes(); } catch (Buffer.BufferException be) { throw new GeneralSecurityException(be); } Certificate.Builder<T> builder = Certificate.getBuilder(); builder.publicKey(key) .nonce(nonce) .serial(serial) .type(type) .id(id) .validPrincipals(validPrincipals) .validAfter(validAfter) .validBefore(validBefore) .critOptions(critOptions) .extensions(extensions) .signatureKey(signatureKey) .signature(signature); return builder.build(); }</code><technical_language>immediately build builder instead of defining fields, assigning them, passing builder</technical_language>

Target:
static <T extends PublicKey> Certificate<T> readPubKey(Buffer<?> buf, KeyType innerKeyType) throws GeneralSecurityException { Certificate.Builder<T> builder = Certificate.getBuilder(); try { builder.nonce(buf.readBytes()); builder.publicKey((T) innerKeyType.readPubKeyFromBuffer(buf)); builder.serial(buf.readUInt64AsBigInteger()); builder.type(buf.readUInt32()); builder.id(buf.readString()); builder.validPrincipals(unpackList(buf.readBytes())); builder.validAfter(dateFromEpoch(buf.readUInt64())); builder.validBefore(dateFromEpoch(buf.readUInt64())); builder.critOptions(unpackMap(buf.readBytes())); builder.extensions(unpackMap(buf.readBytes())); buf.readString(); builder.signatureKey(buf.readBytes()); builder.signature(buf.readBytes()); } catch (Buffer.BufferException be) { throw new GeneralSecurityException(be); } return builder.build(); }
Source:
<code>public EventType findByName(final String name) throws NakadiException, NoSuchEventTypeException { <START> final SqlRowSet rs = jdbcTemplate.queryForRowSet("SELECT et_name, et_event_type_object FROM zn_data.event_type"); <END> if(rs.next()) { try { return jsonMapper.readValue(rs.getString(2), EventType.class); } catch (IOException e) { throw new NakadiException("Problem deserializing event type", e); } } else { throw new NoSuchEventTypeException("EventType \"" + name + "\" does not exist."); } }</code><technical_language>do need select et_name here</technical_language>

Target:
public EventType findByName(final String name) throws NakadiException, NoSuchEventTypeException { final String sql = "SELECT et_event_type_object FROM zn_data.event_type WHERE et_name = ?"; try { return jdbcTemplate.queryForObject(sql, new Object[] { name }, new EventTypeMapper()); } catch (EmptyResultDataAccessException e) { throw new NoSuchEventTypeException("EventType \"" + name + "\" does not exist.", e); } }
Source:
<code>public Response processAddDestination(DestinationInfo dest) throws Exception { Response resp = null; try { <START> System.out.println("___adding dest: " + dest); <END> addDestination(dest); } catch (Exception e) { if (e instanceof ActiveMQSecurityException) { resp = new ExceptionResponse(new JMSSecurityException(e.getMessage())); } else { resp = new ExceptionResponse(e); } } return resp; }</code><technical_language>removed</technical_language>

Target:
public Response processAddDestination(DestinationInfo dest) throws Exception { Response resp = null; try { addDestination(dest); } catch (Exception e) { if (e instanceof ActiveMQSecurityException) { resp = new ExceptionResponse(new JMSSecurityException(e.getMessage())); } else { resp = new ExceptionResponse(e); } } return resp; }
Source:
<code>public ListBlobBlocksResponseImpl(List<BlobBlockProperties> blocks) { <START> this.blocks = blocks; <END> }</code><technical_language>checkNotNull</technical_language>

Target:
public ListBlobBlocksResponseImpl(List<BlobBlockProperties> blocks) { this.blocks = checkNotNull(blocks, "block list must not be null"); }
Source:
<code>public void setup() { <START> generator = new SequentialIdentifierGenerator(); <END> handler = new SequentialIdentifierGeneratorResourceHandler(); }</code><technical_language>setting here? class level variables</technical_language>

Target:
public void setup() { handler = new SequentialIdentifierGeneratorResourceHandler(); }
Source:
<code>public boolean execute() { if ( this.contentIds.getSize() == 0 ) { return true; } final QueryExpr selectInvalidExpr = QueryExpr.from( LogicalExpr. or( LogicalExpr. or( new NotExpr( CompareExpr. <START> like( FieldExpr.from( ContentPropertyNames.DISPLAY_NAME ), ValueExpr.string( "*" ) ) ), CompareExpr. <END> like( FieldExpr.from( ContentPropertyNames.NAME ), ValueExpr.string( ContentName.UNNAMED_PREFIX + "*" ) ) ), CompareExpr. eq( FieldExpr.from( ContentPropertyNames.VALID ), ValueExpr.fromBoolean( false ) ) ) ); final ContentQuery query = ContentQuery.create(). queryExpr( selectInvalidExpr ). queryFilter( IdFilter.create(). fieldName( ContentIndexPath.ID.getPath() ). values( contentIds.asStrings() ). build() ). size( 0 ). build(); final FindContentByQueryResult result = FindContentByQueryCommand.create(). params( FindContentByQueryParams.create(). contentQuery( query ). populateChildren( false ). build() ). contentTypeService( this.contentTypeService ). eventPublisher( this.eventPublisher ). nodeService( this.nodeService ). translator( this.translator ). build(). execute(); return result.getTotalHits() == 0; }</code><technical_language>do need DISPLAYNAME = "*" here</technical_language>

Target:
public boolean execute() { if ( this.contentIds.getSize() == 0 ) { return true; } final LogicalExpr contentIsUnnamed = LogicalExpr. or( new NotExpr( CompareExpr. like( FieldExpr.from( ContentPropertyNames.DISPLAY_NAME ), ValueExpr.string( "*" ) ) ), CompareExpr.like( FieldExpr.from( ContentPropertyNames.NAME ), ValueExpr.string( ContentName.UNNAMED_PREFIX + "*" ) ) ); final CompareExpr contentIsInvalid = CompareExpr. eq( FieldExpr.from( ContentPropertyNames.VALID ), ValueExpr.fromBoolean( false ) ); final QueryExpr selectInvalidExpr = QueryExpr.from( LogicalExpr. or( contentIsUnnamed, contentIsInvalid ) ); final ContentQuery query = ContentQuery.create(). queryExpr( selectInvalidExpr ). queryFilter( IdFilter.create(). fieldName( ContentIndexPath.ID.getPath() ). values( contentIds.asStrings() ). build() ). size( 0 ). build(); final FindContentByQueryResult result = FindContentByQueryCommand.create(). params( FindContentByQueryParams.create(). contentQuery( query ). populateChildren( false ). build() ). contentTypeService( this.contentTypeService ). eventPublisher( this.eventPublisher ). nodeService( this.nodeService ). translator( this.translator ). build(). execute(); return result.getTotalHits() == 0; }
Source:
<code>public Response post( @Context SecurityContext securityContext, String graphQLDocument) { boolean isVerbose = false; try (DataStoreTransaction tx = elide.getDataStore().beginTransaction()) { ObjectMapper mapper = elide.getMapper().getObjectMapper(); JsonNode jsonDocument = mapper.readTree(graphQLDocument); final User user = tx.accessUser(getUser.apply(securityContext)); GraphQLRequestScope requestScope = new GraphQLRequestScope(tx, user, null, elide.getElideSettings()); if (!jsonDocument.has(QUERY)) { return Response.status(400).entity("A `query` key is required.").build(); } String query = jsonDocument.get(QUERY).asText(); String operationName = null; if (jsonDocument.has(OPERATION_NAME)) { operationName = jsonDocument.get(OPERATION_NAME).asText(); } ExecutionResult result; <START> if (jsonDocument.has(VARIABLES)) { <END> Map<String, Object> variables = mapper.convertValue(jsonDocument.get(VARIABLES), Map.class); result = api.execute(query, operationName, requestScope, variables); } else { result = api.execute(query, operationName, requestScope); } if (query.startsWith(MUTATION)) { requestScope.saveOrCreateObjects(); } tx.commit(requestScope); return Response.ok(mapper.writeValueAsString(result.getData())).build(); } catch (JsonProcessingException e) { return buildErrorResponse(new InvalidEntityBodyException(graphQLDocument), isVerbose); } catch (IOException e) { return buildErrorResponse(new TransactionException(e), isVerbose); } catch (Exception | Error e) { log.debug("Unhandled error or exception.", e); throw e; } }</code><technical_language>Do tests for new options</technical_language>

Target:
public Response post( @Context SecurityContext securityContext, String graphQLDocument) { boolean isVerbose = false; try (DataStoreTransaction tx = elide.getDataStore().beginTransaction()) { ObjectMapper mapper = elide.getMapper().getObjectMapper(); JsonNode jsonDocument = mapper.readTree(graphQLDocument); final User user = tx.accessUser(getUser.apply(securityContext)); GraphQLRequestScope requestScope = new GraphQLRequestScope(tx, user, elide.getElideSettings()); if (!jsonDocument.has(QUERY)) { return Response.status(400).entity("A `query` key is required.").build(); } String query = jsonDocument.get(QUERY).asText(); String operationName = null; if (jsonDocument.has(OPERATION_NAME)) { operationName = jsonDocument.get(OPERATION_NAME).asText(); } ExecutionResult result; if (jsonDocument.has(VARIABLES)) { Map<String, Object> variables = mapper.convertValue(jsonDocument.get(VARIABLES), Map.class); result = api.execute(query, operationName, requestScope, variables); } else { result = api.execute(query, operationName, requestScope); } if (query.startsWith(MUTATION)) { requestScope.saveOrCreateObjects(); } tx.commit(requestScope); return Response.ok(mapper.writeValueAsString(result.getData())).build(); } catch (JsonProcessingException e) { return buildErrorResponse(new InvalidEntityBodyException(graphQLDocument), isVerbose); } catch (IOException e) { return buildErrorResponse(new TransactionException(e), isVerbose); } catch (Exception | Error e) { log.debug("Unhandled error or exception.", e); throw e; } }
Source:
<code>RubricRecipientStatistics(String recipientEmail, String recipientName, String recipientTeam) { <START> Assumption.assertTrue(hasAssignedWeights); <END> this.recipientEmail = recipientEmail; this.recipientName = recipientName; this.recipientTeam = recipientTeam; numOfResponsesPerSubQuestionPerChoice = new int[getNumOfRubricSubQuestions()][getNumOfRubricChoices()]; totalPerSubQuestion = new double[getNumOfRubricSubQuestions()]; respondentsPerSubQuestion = new int[getNumOfRubricSubQuestions()]; this.rubricWeightsForEachCell = getRubricWeights(); }</code><technical_language>some message "Per Recipient Stats is weights enabled."</technical_language>

Target:
RubricRecipientStatistics(String recipientEmail, String recipientName, String recipientTeam) { Assumption.assertTrue("Per Recipient Stats is only available when weights are enabled", hasAssignedWeights); this.recipientEmail = recipientEmail; this.recipientName = recipientName; this.recipientTeam = recipientTeam; numOfResponsesPerSubQuestionPerChoice = new int[getNumOfRubricSubQuestions()][getNumOfRubricChoices()]; totalPerSubQuestion = new double[getNumOfRubricSubQuestions()]; respondentsPerSubQuestion = new int[getNumOfRubricSubQuestions()]; weights = getRubricWeights(); }
Source:
<code>private static List<String> optionalList(final Config config, final String name) { String s[] = config.getStringList("ldap", null, name); <START> if(s == null || s.length == 0) { <END> return null; } final List<String> vlist = new ArrayList<String>(); for(int i = 0; i < s.length; i++) { vlist.add(s[i]); } return vlist; }</code><technical_language>IIRC getStringList returns String[0] elements, get null here</technical_language>

Target:
private static List<String> optionalList(final Config config, final String name) { String s[] = config.getStringList("ldap", null, name); return Arrays.asList(s); }
Source:
<code>public void oreonSpawn(OreonSpawnEvent event, EntityRef player) { prefabToSpawn = event.getOreonPrefab(); spawnPos = event.getSpawnPos(); <START> spawnPos.y = spawnPos.y - (float)0.5; <END> boolean toSpawn = consumeItem(player, prefabToSpawn); if(toSpawn) { EntityRef newOreon = entityManager.create(prefabToSpawn, spawnPos); NetworkComponent netComp = new NetworkComponent(); netComp.replicateMode = NetworkComponent.ReplicateMode.ALWAYS; newOreon.addComponent(netComp); newOreon.getComponent(OreonSpawnComponent.class).parent = player; assignRandomAttributes(newOreon); logger.info("Player " + newOreon.getComponent(OreonSpawnComponent.class).parent + "Spawned a new Oreon of Type : " + prefabToSpawn); } }</code><technical_language>0.5f instead of (float)0.5. Actually, spawnPos.y -= 0.5f;</technical_language>

Target:
public void oreonSpawn(OreonSpawnEvent event, EntityRef player) { prefabToSpawn = event.getOreonPrefab(); spawnPos = event.getSpawnPos(); spawnPos.y -= 0.5f; boolean shouldSpawn = consumeItem(player, prefabToSpawn); if (shouldSpawn) { EntityRef newOreon = entityManager.create(prefabToSpawn, spawnPos); NetworkComponent networkComponent = new NetworkComponent(); networkComponent.replicateMode = NetworkComponent.ReplicateMode.ALWAYS; newOreon.addComponent(networkComponent); newOreon.getComponent(OreonSpawnComponent.class).parent = player; assignRandomAttributes(newOreon); logger.info("Player " + PlayerUtil.getColoredPlayerName(player.getOwner()) + " spawned a new Oreon of Type : " + prefabToSpawn.getName()); } }
Source:
<code>public void setMetadata( Map<String, Serializable> metadata ) throws RepositoryException { this.executeOperation( new SessionOperation() { @Override public void execute( Session session ) { try { JcrRepositoryFileUtils.setFileMetadata( session, getId(), metadata ); } catch ( InvalidItemStateException | ItemNotFoundException | PathNotFoundException e ) { <START> getLogger().warn( "InvalidItemStateException in setMetadata. Probable cause: File does not exist anymore" ); <END> } catch ( RepositoryException e ) { getLogger().error( "RepositoryException was found: ", e ); } } } ); }</code><technical_language>add this message in a message.properties file</technical_language>

Target:
public void setMetadata( Map<String, Serializable> metadata ) { this.executeOperation( session -> { try { JcrRepositoryFileUtils.setFileMetadata( session, getId(), metadata ); } catch ( InvalidItemStateException | ItemNotFoundException | PathNotFoundException e ) { getLogger().warn( Messages.getInstance().getString( INVALID_ITEM_STATE_EXCEPTION_MESSAGE, "setMetadata" ) ); } catch ( RepositoryException e ) { getLogger().error( Messages.getInstance().getString( REPOSITORY_EXCEPTION_WAS_FOUND_MESSAGE ), e ); } } ); }
Source:
<code>public void testGeneralUseMixedCase1() { DataUse dataUse = new DataUseBuilder(). setGeneralUse(true). setDiseaseRestrictions(Collections.singletonList(ConsentUseCases.CANCER)). build(); UseRestriction restriction = restrictionBuilder.buildUseRestriction(dataUse); <START> Assert.assertNotEquals(restriction, everything); <END> }</code><technical_language>bothered assertNotEquals. tests succeed wrong behavior assertNotEquals. instead check for result instead of be</technical_language>

Target:
public void testGeneralUseMixedCase1() { DataUse dataUse = new DataUseBuilder(). setDiseaseRestrictions(Collections.singletonList(ConsentUseCases.CANCER)). build(); DataUse mc1 = new DataUseBuilder(). setGeneralUse(true). setDiseaseRestrictions(Collections.singletonList(ConsentUseCases.CANCER)). build(); Assert.assertEquals( restrictionBuilder.buildUseRestriction(dataUse), restrictionBuilder.buildUseRestriction(mc1)); }
Source:
<code>protected void serviceStop() throws Exception { if (executorService != null) { executorService.shutdown(); <START> boolean terminated = false; <END> try { terminated = executorService.awaitTermination(10, TimeUnit.SECONDS); } finally { if (!terminated && !executorService.isTerminated()) { LOG.warn("Executor service still active for plugins", executorService); } executorService = null; } } }</code><technical_language>service null, result in start stop unbalanced</technical_language>

Target:
protected void serviceStop() throws Exception { if (executorService != null) { executorService.shutdown(); boolean terminated = false; try { terminated = executorService.awaitTermination(TIMEOUT, TimeUnit.SECONDS); } finally { if (!terminated) { LOG.warn("{} executor service failed to terminate withing seconds", getClass().getSimpleName(), executorService, TIMEOUT); } executorService = null; super.serviceStop(); } } }
Source:
<code>protected void checkExpressionSyntax() { <START> String value = getValue(); <END> if (!value.startsWith(EXPRESSION_VALUE_PREFIX)) { if (value.startsWith(MVEL_ESCAPE_SYMBOL)) { widget.setValue(value.replaceFirst(MVEL_ESCAPE_SYMBOL, EXPRESSION_VALUE_PREFIX)); } else if (value.startsWith(" ")) { widget.setValue(value.replaceFirst(" ", EXPRESSION_VALUE_PREFIX)); } else { widget.setValue(EXPRESSION_VALUE_PREFIX + value); } } }</code><technical_language>final</technical_language>

Target:
protected void checkExpressionSyntax() { final String value = getValue(); if (!value.startsWith(EXPRESSION_VALUE_PREFIX)) { if (value.startsWith(MVEL_ESCAPE_SYMBOL)) { widget.setValue(value.replaceFirst(MVEL_ESCAPE_SYMBOL, EXPRESSION_VALUE_PREFIX)); } else if (value.startsWith(" ")) { widget.setValue(value.replaceFirst(" ", EXPRESSION_VALUE_PREFIX)); } else { widget.setValue(EXPRESSION_VALUE_PREFIX + value); } } }