auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testBuilderWithPopulatedFieldValues() { String expectedGoogleId = "dummyGoogleId"; <START> String expectedEmail = "dummyEmail"; <END> String expectedName = "dummyName"; String expectedInstitute = "dummyInstitute"; boolean expectedIsInstructor = true; Date expectedCreatedAt = new Date(98765); AccountAttributes observedAccountAttributes = AccountAttributes.builder() .withGoogleId(expectedGoogleId) .withEmail(expectedEmail) .withName(expectedName) .withInstitute(expectedInstitute) .withIsInstructor(expectedIsInstructor) .withCreatedAt(expectedCreatedAt) .withDefaultStudentProfileAttributes(expectedGoogleId) .build(); assertEquals(expectedGoogleId, observedAccountAttributes.getGoogleId()); assertEquals(expectedEmail, observedAccountAttributes.getEmail()); assertEquals(expectedCreatedAt, observedAccountAttributes.createdAt); assertEquals(expectedInstitute, observedAccountAttributes.getInstitute()); assertEquals(expectedIsInstructor, observedAccountAttributes.isInstructor()); assertEquals(expectedName, observedAccountAttributes.getName()); assertEquals(expectedGoogleId, observedAccountAttributes.studentProfile.googleId); }</code><technical_language>provide a valid email discussed below</technical_language>

Target:
public void testBuilderWithPopulatedFieldValues() { String expectedGoogleId = "dummyGoogleId"; String expectedEmail = "email@example.com"; String expectedName = "dummyName"; String expectedInstitute = "dummyInstitute"; boolean expectedIsInstructor = true; Date expectedCreatedAt = new Date(98765); AccountAttributes observedAccountAttributes = AccountAttributes.builder() .withGoogleId(expectedGoogleId) .withEmail(expectedEmail) .withName(expectedName) .withInstitute(expectedInstitute) .withIsInstructor(expectedIsInstructor) .withCreatedAt(expectedCreatedAt) .withDefaultStudentProfileAttributes(expectedGoogleId) .build(); assertEquals(expectedGoogleId, observedAccountAttributes.getGoogleId()); assertEquals(expectedEmail, observedAccountAttributes.getEmail()); assertEquals(expectedCreatedAt, observedAccountAttributes.createdAt); assertEquals(expectedInstitute, observedAccountAttributes.getInstitute()); assertEquals(expectedIsInstructor, observedAccountAttributes.isInstructor()); assertEquals(expectedName, observedAccountAttributes.getName()); assertEquals(expectedGoogleId, observedAccountAttributes.studentProfile.googleId); }
Source:
<code>public void start() { try { final HttpJsonResponse pingResponse = httpJsonRequestFactory.fromUrl(apiEndpoint) .setMethod(HttpMethod.GET) .setTimeout(2000) .request(); if (pingResponse.getResponseCode() == HttpURLConnection.HTTP_OK) { return; } } catch (ApiException | IOException e) { LOG.error( e.getLocalizedMessage(), e); } LOG.error("The workspace agent has attempted to start, but it is unable to ping the Che server at " + apiEndpoint); <START> LOG.error(WSocketEventBusClient.WORKSPACE_AGENT_STOPPED_MESSAGE); <END> try { LOG.info("Workspace /etc/hosts: " + IoUtil.readAndCloseQuietly(new FileInputStream(new File("/etc/hosts")))); } catch (Exception e) { LOG.info(e.getLocalizedMessage(), e); } System.exit(0); }</code><technical_language>log. warn</technical_language>

Target:
public void start() { try { final HttpJsonResponse pingResponse = httpJsonRequestFactory.fromUrl(apiEndpoint) .setMethod(HttpMethod.GET) .setTimeout(2000) .request(); if (pingResponse.getResponseCode() == HttpURLConnection.HTTP_OK) { return; } } catch (ApiException | IOException e) { LOG.error( e.getLocalizedMessage(), e); } LOG.error("The workspace agent has attempted to start, but it is unable to ping the Che server at " + apiEndpoint); LOG.error("The workspace agent has been forcefully stopped. " + "This error happens when the agent cannot resolve the location of the Che server. " + "This error can usually be fixed with additional configuration settings in /conf/che.properties. " + "The Che server will stop this workspace after a short timeout. " + "You can get help by posting your config, stacktrace and workspace /etc/hosts below as a GitHub issue."); try { LOG.info("Workspace /etc/hosts: " + IoUtil.readAndCloseQuietly(new FileInputStream(new File("/etc/hosts")))); } catch (Exception e) { LOG.info(e.getLocalizedMessage(), e); } System.exit(0); }
Source:
<code>private static String buildExceptionMessage(Error error) { Assert.notNull(error, "Error argument cannot be null."); StringBuilder sb = new StringBuilder(); sb.append("HTTP ").append(error.getStatus()); String requestId = error.getRequestId(); <START> if (Strings.hasText(requestId)) { <END> sb.append(", RequestId: ").append(error.getRequestId()); } sb.append(", Stormpath ").append(error.getCode()) .append(" (").append(error.getMoreInfo()).append("): ") .append(error.getDeveloperMessage()); return sb.toString(); }</code><technical_language>this Stormpath status code in string message (rather separate http status Stormpath status)</technical_language>

Target:
private static String buildExceptionMessage(Error error) { Assert.notNull(error, "Error argument cannot be null."); StringBuilder sb = new StringBuilder(); sb.append("HTTP ").append(error.getStatus()) .append(", Stormpath ").append(error.getCode()) .append(" (").append(error.getMoreInfo()).append(")"); String requestId = error.getRequestId(); if (Strings.hasText(requestId)) { sb.append(", RequestId ").append(error.getRequestId()); } return sb.append(": ").append(error.getDeveloperMessage()).toString(); }
Source:
<code>public WriteTxnMarkersResponse(Map<Long, Map<TopicPartition, Errors>> errors) { List<WritableTxnMarkerResult> markers = new ArrayList<>(); for (Map.Entry<Long, Map<TopicPartition, Errors>> markerEntry : errors.entrySet()) { Map<String, WritableTxnMarkerTopicResult> responseTopicDataMap = new HashMap<>(); for (Map.Entry<TopicPartition, Errors> topicEntry : markerEntry.getValue().entrySet()) { TopicPartition topicPartition = topicEntry.getKey(); String topicName = topicPartition.topic(); WritableTxnMarkerTopicResult topic = responseTopicDataMap.getOrDefault(topicName, new WritableTxnMarkerTopicResult()); if (topic.name().equals("")) { <START> topic.setName(topicName); <END> } topic.partitions().add(new WritableTxnMarkerPartitionResult() .setErrorCode(topicEntry.getValue().code()) .setPartitionIndex(topicPartition.partition()) ); responseTopicDataMap.put(topicName, topic); } markers.add(new WritableTxnMarkerResult() .setProducerId(markerEntry.getKey()) .setTopics(new ArrayList<>(responseTopicDataMap.values())) ); } this.errors = errors; this.data = new WriteTxnMarkersResponseData() .setMarkers(markers); }</code><technical_language>do creating topic? For example: WritableTxnMarkerTopicResult topic = responseTopicDataMap.getOrDefault(topicName, new WritableTxnMarkerTopicResult().setName(topicName));</technical_language>

Target:
public WriteTxnMarkersResponse(Map<Long, Map<TopicPartition, Errors>> errors) { List<WritableTxnMarkerResult> markers = new ArrayList<>(); for (Map.Entry<Long, Map<TopicPartition, Errors>> markerEntry : errors.entrySet()) { Map<String, WritableTxnMarkerTopicResult> responseTopicDataMap = new HashMap<>(); for (Map.Entry<TopicPartition, Errors> topicEntry : markerEntry.getValue().entrySet()) { TopicPartition topicPartition = topicEntry.getKey(); String topicName = topicPartition.topic(); WritableTxnMarkerTopicResult topic = responseTopicDataMap.getOrDefault(topicName, new WritableTxnMarkerTopicResult().setName(topicName)); topic.partitions().add(new WritableTxnMarkerPartitionResult() .setErrorCode(topicEntry.getValue().code()) .setPartitionIndex(topicPartition.partition()) ); responseTopicDataMap.put(topicName, topic); } markers.add(new WritableTxnMarkerResult() .setProducerId(markerEntry.getKey()) .setTopics(new ArrayList<>(responseTopicDataMap.values())) ); } this.errors = errors; this.data = new WriteTxnMarkersResponseData() .setMarkers(markers); }
Source:
<code>public static Version getEffective(Version vmCustomCompatibilityVersion, Version vdsGroupCompatibilityVersion, Version defaultVersion) { if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } else if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } else { return defaultVersion; <START> } <END> }</code><technical_language>I find more readable as: if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } return defaultVersion; please consider</technical_language>

Target:
public static Version getEffective(Version vmCustomCompatibilityVersion, Version vdsGroupCompatibilityVersion, Version defaultVersion) { if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } return defaultVersion; }
Source:
<code>public void receiveEndInSource(BubbleMergeWithSearchMessage incomingMsg) { BubbleMergeWithSearchVertexValueWritable vertex = getVertexValue(); vertex.getArrayOfPathList().add(incomingMsg.getPathList()); vertex.getArrayOfInternalKmer().add(incomingMsg.getInternalKmer()); vertex.getArrayOfEdgeTypes().add(incomingMsg.getEdgeTypeList()); int numBranches = vertex.getNumBranches(); numBranches--; <START> vertex.setNumBranches(numBranches); <END> if (numBranches == 0) { int k = 1; VKmerList pathList = vertex.getArrayOfPathList().get(k); VKmer mergeKmer = vertex.getArrayOfInternalKmer().get(k); EdgeTypeList edgeTypes = vertex.getArrayOfEdgeTypes().get(k); vertex.setInternalKmer(mergeKmer); vertex.getEdgeMap(vertex.getArrayOfEdgeTypes().get(k).get(0)).remove(pathList.getPosition(1)); for (int i = 1; i < pathList.size(); i++) { VKmer dest = new VKmer(pathList.getPosition(i)); outgoingMsg.reset(); outgoingMsg.setFlag(State.KILL_MESSAGE_FROM_SOURCE); VKmerList kmerList = new VKmerList(); kmerList.append(pathList.getPosition(i - 1)); if (i + 1 < pathList.size()) { kmerList.append(pathList.getPosition(i + 1)); } outgoingMsg.setPathList(kmerList); outgoingMsg.getEdgeTypeList().add(edgeTypes.get(i - 1).mirror()); if (i < edgeTypes.size()) outgoingMsg.getEdgeTypeList().add(edgeTypes.get(i)); sendMsg(dest, outgoingMsg); } } }</code><technical_language>vertex.getNumBranches()--</technical_language>

Target:
public void receiveEndInSource(BubbleMergeWithSearchMessage incomingMsg) { BubbleMergeWithSearchVertexValueWritable vertex = getVertexValue(); vertex.getArrayOfPathList().add(incomingMsg.getPathList()); vertex.getArrayOfInternalKmer().add(incomingMsg.getInternalKmer()); vertex.getArrayOfEdgeTypes().add(incomingMsg.getEdgeTypeList()); int numBranches = vertex.getNumBranches(); vertex.setNumBranches(--numBranches); if (numBranches == 0) { pickBestPath(); } }
Source:
<code>public static int binToInt(String bits, boolean unsignd) throws IrregularStringOfBitsException { if ((bits.length() > 32) || (unsignd && bits.length() == 32 && bits.charAt(0) == '1') || !isBinaryString(bits)) { throw new IrregularStringOfBitsException(); } if (!unsignd && bits.length() == 32 && isOverflow(bits)) { <START> return (int)(-Math.pow(2.0, 32.0)); <END> } if (unsignd) { return getUnsignedIntValue(bits); } else { if (bits.charAt(0) == '0') { return Converter.binToInt(bits.substring(1), true); } else{ String s = Converter.twoComplement(bits); return -1 * Converter.binToInt(s, true); } } }</code><technical_language>please store this in a constant? more efficient computing time. Also, a general point, if want do this type of operations (working powers of two) shift operators floating-point operations converting result int</technical_language>

Target:
public static int binToInt(String bits, boolean unsignd) throws IrregularStringOfBitsException { if ((bits.length() > 32) || (unsignd && bits.length() == 32 && bits.charAt(0) == '1') || !isBinaryString(bits)) { throw new IrregularStringOfBitsException(); } if (!unsignd && bits.length() == 32 && isOverflow(bits)) { return OVERFLOW_32; } if (unsignd) { return getUnsignedIntValue(bits); } else { if (bits.charAt(0) == '0') { return Converter.binToInt(bits.substring(1), true); } else{ String s = Converter.twoComplement(bits); return -1 * Converter.binToInt(s, true); } } }
Source:
<code><START> public void activateImage() throws ProtocolAdapterException, ImageTransferException { <END> final MethodResultCode imageActivate = this.imageTransferCosem.callMethod(Method.IMAGE_ACTIVATE.getValue(), DataObject.newInteger8Data((byte) 0)); if (imageActivate == null) { throw new ProtocolAdapterException(EXCEPTION_MSG_IMAGE_VERIFY_NOT_CALLED); } if (imageActivate == MethodResultCode.TEMPORARY_FAILURE) { final Future<Integer> newStatus = EXECUTOR_SERVICE.submit(new ImageTransferStatusChangeWatcher( ImageTransferStatus.ACTIVATION_INITIATED, properties.getActivationStatusCheckInterval(), properties .getActivationStatusCheckTimeout(), true)); int status; try { status = newStatus.get(); } catch (InterruptedException | ExecutionException e) { throw new ProtocolAdapterException(EXCEPTION_MSG_WAITING_FOR_IMAGE_ACTIVATION, e); } if (status == ImageTransferStatus.ACTIVATION_FAILED.getValue()) { throw new ImageTransferException(EXCEPTION_MSG_IMAGE_TO_ACTIVATE_NOT_OK); } if (status == ImageTransferStatus.ACTIVATION_INITIATED.getValue()) { throw new ImageTransferException(EXCEPTION_MSG_ACTIVATION_TAKING_TOO_LONG); } return; } if (imageActivate != MethodResultCode.SUCCESS) { throw new ImageTransferException(EXCEPTION_MSG_IMAGE_ACTIVATE_NOT_SUCCESS); } }</code><technical_language>![MAJOR](<LINK_1> Refactor this method throw checked exception instead of: org.osgp.adapter.protocol.dlms.exceptions.ProtocolAdapterException, org.osgp.adapter.protocol.dlms.exceptions.ImageTransferException [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public void activateImage() throws ProtocolAdapterException, ImageTransferException { this.connector.getDlmsMessageListener().setDescription( "ImageTransfer call image_activate " + ", call method: " + JdlmsObjectToStringUtil.describeMethod(this.imageTransferCosem.createMethodParameter( Method.IMAGE_ACTIVATE, DataObject.newInteger8Data((byte) 0)))); final MethodResultCode imageActivate = this.imageTransferCosem.callMethod(Method.IMAGE_ACTIVATE, DataObject.newInteger8Data((byte) 0)); if (imageActivate == null) { throw new ProtocolAdapterException(EXCEPTION_MSG_IMAGE_VERIFY_NOT_CALLED); } if (imageActivate == MethodResultCode.TEMPORARY_FAILURE) { this.waitForImageActivation(); return; } if (imageActivate != MethodResultCode.SUCCESS) { throw new ImageTransferException(EXCEPTION_MSG_IMAGE_ACTIVATE_NOT_SUCCESS); } }
Source:
<code>private boolean predefinedSamplesCount() { <START> return totalSamplesRequested != -1; <END> }</code><technical_language>is more obvious dedicated variable for that? 'boolean predefinedSamplesCount' instead of 'totalSamplesRequested != -1'</technical_language>

Target:
private boolean predefinedSamplesCount() { return totalSamplesCountRequested != -1; }
Source:
<code>public Map<String, SourceFile> processImports(String repositoryId, String content, Version version, SourceCodeRepoInterface sourceCodeRepoInterface, String filepath) { <START> Pattern pattern = Pattern.compile("(?i)(?m)^[ \t]*includeConfig(.*)"); <END> final Matcher matcher = pattern.matcher(content); Set<String> suspectedConfigImports = new HashSet<>(); while (matcher.find()) { suspectedConfigImports.add(CharMatcher.is('\'').trimFrom(matcher.group(1).trim())); } final Configuration configuration = NextflowUtilities.grabConfig(content); Map<String, SourceFile> imports = new HashMap<>(); String mainScriptPath = "main.nf"; if (configuration.containsKey("manifest.mainScript")) { mainScriptPath = configuration.getString("manifest.mainScript"); } suspectedConfigImports.add(mainScriptPath); for (String filename : suspectedConfigImports) { String filenameAbsolutePath = convertRelativePathToAbsolutePath(filepath, filename); Optional<SourceFile> sourceFile = sourceCodeRepoInterface .readFile(repositoryId, version, SourceFile.FileType.NEXTFLOW, filenameAbsolutePath); if (sourceFile.isPresent()) { sourceFile.get().setPath(filename); imports.put(filename, sourceFile.get()); } } List<String> strings = sourceCodeRepoInterface.listFiles(repositoryId, "/", version.getReference()); handleNextFlowImports(repositoryId, version, sourceCodeRepoInterface, imports, strings, "lib"); handleNextFlowImports(repositoryId, version, sourceCodeRepoInterface, imports, strings, "bin"); return imports; }</code><technical_language>This is called frequently, if is, a tiny performance improvement this a a static instantiated once</technical_language>

Target:
public Map<String, SourceFile> processImports(String repositoryId, String content, Version version, SourceCodeRepoInterface sourceCodeRepoInterface, String filepath) { final Matcher matcher = INCLUDE_CONFIG_PATTERN.matcher(content); Set<String> suspectedConfigImports = new HashSet<>(); while (matcher.find()) { suspectedConfigImports.add(CharMatcher.is('\'').trimFrom(matcher.group(1).trim())); } final Configuration configuration = NextflowUtilities.grabConfig(content); Map<String, SourceFile> imports = new HashMap<>(); String mainScriptPath = "main.nf"; if (configuration.containsKey("manifest.mainScript")) { mainScriptPath = configuration.getString("manifest.mainScript"); } suspectedConfigImports.add(mainScriptPath); for (String filename : suspectedConfigImports) { String filenameAbsolutePath = convertRelativePathToAbsolutePath(filepath, filename); Optional<SourceFile> sourceFile = sourceCodeRepoInterface .readFile(repositoryId, version, SourceFile.FileType.NEXTFLOW, filenameAbsolutePath); if (sourceFile.isPresent()) { sourceFile.get().setPath(filename); imports.put(filename, sourceFile.get()); } } List<String> strings = sourceCodeRepoInterface.listFiles(repositoryId, "/", version.getReference()); handleNextFlowImports(repositoryId, version, sourceCodeRepoInterface, imports, strings, "lib"); handleNextFlowImports(repositoryId, version, sourceCodeRepoInterface, imports, strings, "bin"); return imports; }
Source:
<code>public FilePath basePath() { <START> return FilePathCreator.create(getExternalFileDirWithBiggerAvailableSpace().getAbsolutePath(), "/downloads/"); <END> }</code><technical_language>extract constant</technical_language>

Target:
public FilePath basePath() { return FilePathCreator.create(getExternalFileDirWithBiggerAvailableSpace().getAbsolutePath(), DOWNLOADS_DIR); }
Source:
<code>public void deletePreset(final String crop, final Integer presetId) { final ProgramPreset programPreset = presetService.getProgramPresetById(presetId); if (programPreset == null) { errors = new MapBindingResult(new HashMap<String, String>(), PresetDTO.class.getName()); errors.reject("preset.not.found", ""); throw new ResourceNotFoundException(errors.getAllErrors().get(0)); } <START> validateUserIsAProgramMember(crop, securityService.getCurrentlyLoggedInUser().getName(), programPreset.getProgramUuid()); <END> presetService.deleteProgramPreset(presetId); }</code><technical_language>I suggest this follow BMS Inspect Code rules</technical_language>

Target:
public void deletePreset(final String crop, final Integer presetId) { final ProgramPreset programPreset = presetService.getProgramPresetById(presetId); if (programPreset == null) { errors = new MapBindingResult(new HashMap<String, String>(), PresetDTO.class.getName()); errors.reject("preset.not.found", ""); throw new ResourceNotFoundException(errors.getAllErrors().get(0)); } this.validateUserIsAProgramMember(crop, securityService.getCurrentlyLoggedInUser().getName(), programPreset.getProgramUuid()); presetService.deleteProgramPreset(presetId); }
Source:
<code>public QueryBuilder doRewrite(QueryRewriteContext context) throws IOException { OsStats.Cpu cpu = osService.stats().getCpu(); return <START> super.doRewrite(c -> <END> c.test(cpu)); }</code><technical_language>slightly confusing name. I thought c short for cpu, short for condition</technical_language>

Target:
public QueryBuilder doRewrite(QueryRewriteContext context) throws IOException { OsStats.Cpu cpu = osService.stats().getCpu(); return super.doRewrite(condition -> condition.test(cpu)); }
Source:
<code>TaskTerminationData(InternalJob internalJob, RunningTaskData taskData, TerminationStatus terminationStatus, TaskResultImpl taskResult) { this.taskData = taskData; this.terminationStatus = terminationStatus; <START> taskResult.setPropagatedVariables(SerializationUtil.serializeVariableMap(restoreNonInheritedTaskVariables(taskResult))); <END> this.taskResult = taskResult; this.internalJob = internalJob; }</code><technical_language>serialization embedded in private method</technical_language>

Target:
TaskTerminationData(InternalJob internalJob, RunningTaskData taskData, TerminationStatus terminationStatus, TaskResultImpl taskResult) { this.taskData = taskData; this.terminationStatus = terminationStatus; if (taskResult != null) { taskResult.setPropagatedVariables(restoreNonInheritedTaskVariables(taskResult)); } this.taskResult = taskResult; this.internalJob = internalJob; }
Source:
<code>public void testNoLocalWrite() { try { addEntries(listFile, "singlefile1/file1"); createFiles("singlefile1/file1", "target"); Configuration conf = new Configuration(getConf()); conf.set("fs.file.impl", MockFileSystem.class.getName()); conf.setBoolean("fs.file.impl.disable.cache", true); runTest(listFile, target, false, false, false, false, true, conf); checkResult(target, 1); <START> } catch (IOException e) { <END> LOG.error("Exception encountered while testing distcp", e); Assert.fail("distcp failure"); } finally { TestDistCpUtils.delete(fs, root); } }</code><technical_language>remove catch, test method throw IOException</technical_language>

Target:
public void testNoLocalWrite() throws IOException { try { addEntries(listFile, "singlefile1/file1"); createFiles("singlefile1/file1", "target"); Configuration conf = new Configuration(getConf()); conf.set("fs.file.impl", MockFileSystem.class.getName()); conf.setBoolean("fs.file.impl.disable.cache", true); runTest(listFile, target, false, false, false, false, true, conf); checkResult(target, 1); } finally { TestDistCpUtils.delete(fs, root); } }
Source:
<code>public void mouseMove(MouseEvent event) { if (fDragState == DRAG_RANGE) { <START> int offset = event.x - fStartPosition; <END> setOffset(offset); fCanvas.redraw(); return; } else if (fDragState == DRAG_ZOOM) { long endTime = getTimestamp(event.x); fRangeDuration = endTime - fRangeStartTime; fCanvas.redraw(); return; } super.mouseMove(event); }</code><technical_language>checks, I</technical_language>

Target:
public void mouseMove(MouseEvent event) { if (fDragState == DRAG_RANGE) { int offset = Math.max(fMinOffset, Math.min(fMaxOffset, event.x - fStartPosition)); setOffset(offset); fCanvas.redraw(); return; } else if (fDragState == DRAG_ZOOM) { long endTime = Math.max(getStartTime(), Math.min(getEndTime(), getTimestamp(event.x))); fRangeDuration = endTime - fRangeStartTime; fCanvas.redraw(); return; } super.mouseMove(event); }
Source:
<code>public ListenableFuture<?> sync(final boolean nofsync) { <START> return m_es.submit(new Runnable() { <END> @Override public void run() { new SyncRunnable(nofsync).run(); } }); }</code><technical_language>simplified return m_es.submit(new SyncRunnable(nofsync));</technical_language>

Target:
public ListenableFuture<?> sync(final boolean nofsync) { return m_es.submit(new SyncRunnable(nofsync)); }
Source:
<code>public int compareTo(Key that) { <START> return this.date.compareTo(that.date); <END> }</code><technical_language>need include channelId in break stuff, e.g. int comp = this.date.compareTo(that.date); if (comp != 0) return comp; comp = this.channelId.compareTo(that.channelId); if (comp != 0) return comp; return 0;</technical_language>

Target:
public int compareTo(Key that) { int comp = this.channelId.compareTo(that.channelId); if (comp != 0) return comp; comp = this.source.compareTo(that.source); if (comp != 0) return comp; comp = this.date.compareTo(that.date); if (comp != 0) return comp; return 0; }
Source:
<code>public void remove() { PsiElement psi = getPsi(); if (psi != null) { PsiElement prePsi = UsefulPsiTreeUtil.getPrevSiblingSkipWhiteSpaces(psi, true); PsiElement nextPsi = UsefulPsiTreeUtil.getNextSiblingNoSpaces(psi); TextRange range = psi.getTextRange(); if (prePsi != null && prePsi.getText().equals(",")) { range = range.union(prePsi.getTextRange()); } else if (nextPsi != null && nextPsi.getText().equals(",")) { <START> range = range.union(nextPsi.getTextRange()); <END> } getDocument().replaceElementText(range, ""); } }</code><technical_language>leave commas in place in case: (existing, toRemove, existing)</technical_language>

Target:
public void remove() { PsiElement psi = getPsi(); if (psi != null) { PsiElement prePsi = UsefulPsiTreeUtil.getPrevSiblingSkipWhiteSpaces(psi, true); PsiElement nextPsi = UsefulPsiTreeUtil.getNextSiblingNoSpaces(psi); TextRange range = psi.getTextRange(); StripSpaces stripSpaces = StripSpaces.NONE; if (prePsi != null && prePsi.getText().equals(",")) { range = range.union(prePsi.getTextRange()); stripSpaces = StripSpaces.BEFORE; } else if (nextPsi != null && nextPsi.getText().equals(",")) { range = range.union(nextPsi.getTextRange()); stripSpaces = StripSpaces.AFTER; } getDocument().replaceElementText(range, "", stripSpaces); } }
Source:
<code>public void setActiveEditor(IEditorPart part) { <START> if (part != null && part.getEditorInput() instanceof SessionEditorInput && ((SessionEditorInput) part.getEditorInput()).getStatus() == null) { <END> boolean updateCreateMenus = part != activeEditor && part != null; super.setActiveEditor(part); if (updateCreateMenus && activeEditor instanceof AbstractDTableEditor) { AbstractDTableViewerManager tableViewer = ((AbstractDTableEditor) activeEditor).getTableViewer(); if (tableViewer instanceof DTableViewerManager) { addCreateLineMenu(((DTableViewerManager) tableViewer).getCreateLineMenu()); } } if (activeEditor instanceof DTableCrossEditor) { DTableCrossEditor tableCrossEditor = (DTableCrossEditor) activeEditor; IEditorActionBarContributor actionBarContributor = tableCrossEditor.getEditorSite().getActionBarContributor(); if (actionBarContributor instanceof DTableActionBarContributor) { DTableActionBarContributor dTableActionBarContributor = (DTableActionBarContributor) actionBarContributor; AbstractDTableViewerManager tableViewer = tableCrossEditor.getTableViewer(); if (tableViewer instanceof DTableViewerManager) { DTableViewerManager dTableViewerManager = (DTableViewerManager) tableViewer; dTableActionBarContributor.addCreateTargetColumnMenu(dTableViewerManager.getCreateTargetColumnMenu()); } } } } }</code><technical_language>if getStatus return ok, info warning? supposed Status is null well. Perhaps, add "|| ...getStatus()<IStatus.ERROR</technical_language>

Target:
public void setActiveEditor(IEditorPart part) { if (part != null && part.getEditorInput() instanceof SessionEditorInput && ((SessionEditorInput) part.getEditorInput()).getStatus().getSeverity() < IStatus.ERROR) { boolean updateCreateMenus = part != activeEditor && part != null; super.setActiveEditor(part); if (updateCreateMenus && activeEditor instanceof AbstractDTableEditor) { AbstractDTableViewerManager tableViewer = ((AbstractDTableEditor) activeEditor).getTableViewer(); if (tableViewer instanceof DTableViewerManager) { addCreateLineMenu(((DTableViewerManager) tableViewer).getCreateLineMenu()); } } if (activeEditor instanceof DTableCrossEditor) { DTableCrossEditor tableCrossEditor = (DTableCrossEditor) activeEditor; IEditorActionBarContributor actionBarContributor = tableCrossEditor.getEditorSite().getActionBarContributor(); if (actionBarContributor instanceof DTableActionBarContributor) { DTableActionBarContributor dTableActionBarContributor = (DTableActionBarContributor) actionBarContributor; AbstractDTableViewerManager tableViewer = tableCrossEditor.getTableViewer(); if (tableViewer instanceof DTableViewerManager) { DTableViewerManager dTableViewerManager = (DTableViewerManager) tableViewer; dTableActionBarContributor.addCreateTargetColumnMenu(dTableViewerManager.getCreateTargetColumnMenu()); } } } } }
Source:
<code>protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("diskId", disk.getId()) <START> .append("addressMap", addressMap.toString()); <END> }</code><technical_language>TostringBuilder.append(final String name, final Map<K, V> value) please replace .append("addressMap", addressMap);</technical_language>

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("diskId", disk.getId()) .append("addressMap", addressMap); }
Source:
<code>private static String getNodeName(URL file, GenerationConfig config) { try { String fileName = FilenameUtils.getName(URLDecoder.decode(file.toString(), "UTF-8")); String[] extensions = config.getFileExtensions(); boolean extensionRemoved = false; for (int i = 0; i < extensions.length; i++) { String extension = extensions[i]; if (extension.length() == 0) { continue; } if (!extension.startsWith(".")) { extension = "." + extension; } <START> if (fileName.endsWith(extension)) { <END> fileName = fileName.substring(0, fileName.length() - extension.length()); extensionRemoved = true; break; } } if (!extensionRemoved) { fileName = FilenameUtils.getBaseName(fileName); } return fileName; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(String.format("Unable to generate node name from URL: %s", file.toString()), e); } }</code><technical_language>I removeEnd StringUtils here</technical_language>

Target:
private static String getNodeName(URL file, GenerationConfig config) { try { String fileName = FilenameUtils.getName(URLDecoder.decode(file.toString(), "UTF-8")); String[] extensions = config.getFileExtensions(); boolean extensionRemoved = false; for (int i = 0; i < extensions.length; i++) { String extension = extensions[i]; if (extension.length() == 0) { continue; } if (!extension.startsWith(".")) { extension = "." + extension; } if (fileName.endsWith(extension)) { fileName = removeEnd(fileName, extension); extensionRemoved = true; break; } } if (!extensionRemoved) { fileName = FilenameUtils.getBaseName(fileName); } return fileName; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(String.format("Unable to generate node name from URL: %s", file.toString()), e); } }
Source:
<code>public String toString() { String consumerType = (this.getType() != null) ? this.getType().getLabel() : "null"; <START> return String.format("Consumer [id: %s, uuid: %s, type: %s, name: %s]", <END> this.getId(), this.getUuid(), consumerType, this.getName()); }</code><technical_language>change name property? Accident due mass refactor/rename IDE</technical_language>

Target:
public String toString() { String consumerType = (this.getType() != null) ? this.getType().getLabel() : "null"; return String.format("Consumer [id: %s, uuid: %s, consumerType: %s, name: %s]", this.getId(), this.getUuid(), consumerType, this.getName()); }
Source:
<code>private void handleNotification(ExecuteCommandParams params) { String command = params.getCommand(); List<Object> arguments = params.getArguments(); switch (command) { case Notifications.UPDATE_PROJECTS_CLASSPATH: { List<Object> fixedPathList = new ArrayList<>(arguments.size()); for (Object uri : arguments) { String uriString = convertToJson(uri).getAsString(); String projectPath = removePrefixUri(uriString); fixedPathList.add(projectPath); projectManager .get(projectPath) .ifPresent( project -> { try { LOG.info("updating projectconfig for {}", projectPath); eventService.publish(new ProjectClassPathChangedEvent(project.getPath())); projectManager.update(project); } catch (ForbiddenException | ServerException | NotFoundException | ConflictException | BadRequestException e) { throw toJsonRpcException(e); } }); } <START> params.setArguments(fixedPathList); <END> notifyTransmitter.sendNotification(params); break; } case Notifications.MAVEN_PROJECT_CREATED: { List<Object> fixedPathList = new ArrayList<>(arguments.size()); for (Object uri : arguments) { String uriString = convertToJson(uri).getAsString(); String projectPath = removePrefixUri(uriString); fixedPathList.add(projectPath); projectSynchronizer.ensureMavenProject(projectPath); } params.setArguments(fixedPathList); notifyTransmitter.sendNotification(params); break; } } }</code><technical_language>This shortened ApiException, no</technical_language>

Target:
private void handleNotification(ExecuteCommandParams params) { String command = params.getCommand(); List<Object> arguments = params.getArguments(); switch (command) { case Notifications.UPDATE_PROJECTS_CLASSPATH: { List<Object> fixedPathList = new ArrayList<>(arguments.size()); for (Object uri : arguments) { String uriString = convertToJson(uri).getAsString(); String projectPath = removePrefixUri(uriString); fixedPathList.add(projectPath); projectManager .get(projectPath) .ifPresent( project -> { try { LOG.info("updating projectconfig for {}", projectPath); eventService.publish(new ProjectClassPathChangedEvent(project.getPath())); projectManager.update(project); } catch (ForbiddenException | ServerException | NotFoundException | ConflictException | BadRequestException e) { throw toJsonRpcException(e); } }); } params.setArguments(fixedPathList); notifyClient(params); break; } case Notifications.MAVEN_PROJECT_CREATED: { List<Object> fixedPathList = new ArrayList<>(arguments.size()); for (Object uri : arguments) { String uriString = convertToJson(uri).getAsString(); String projectPath = removePrefixUri(uriString); fixedPathList.add(projectPath); projectSynchronizer.ensureMavenProject(projectPath); } params.setArguments(fixedPathList); notifyClient(params); break; } } }
Source:
<code>public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { <START> db.execSQL("DROP TABLE IF EXISTS " + AMPLITUDE_STORE_TABLE_NAME); <END> db.execSQL(CREATE_AMPLITUDE_STORE_TABLE); db.execSQL("DROP TABLE IF EXISTS " + EVENT_TABLE_NAME); db.execSQL(CREATE_EVENTS_TABLE); }</code><technical_language>read SQLiteOpenHelper onUpgrade. need do version version upgrading, preserve data (we've this method before)</technical_language>

Target:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch (oldVersion) { case 1: db.execSQL(CREATE_STORE_TABLE); case 2: break; default: Log.e(TAG, "onUpgrade() with unknown oldVersion " + oldVersion); resetDatabase(db); } }
Source:
<code>public boolean init() { if (!ClientSession.isConnected()) { return false; } try{ ScpClient scpclient = new ScpClient(); scpclient.transfer(filename,"/tmp/"+ filename.substring(filename.lastIndexOf('/')+1)); } catch (IOException e) { e.printStackTrace(); } catch (JSchException e) { e.printStackTrace(); } scriptid = ClientSession.getNewScriptId(); final DMRequest subreq = new DMRequest(DMRequest.SUBSCRIBE,scriptid, filename,session.getcid(), 0, isGuru); if (!session.sendRequest(subreq)) { } session.addSubscription(scriptid); try { Thread.sleep(500); } catch (InterruptedException ie) final DMResponse subrep = session.recvResponse(scriptid); if (subrep.isValid()) { scriptid = subrep.getscriptID(); logger = new LoggingStreamDaemon(); inputListeners.add(logger); try{ pos = new PipedOutputStream(); pis = new PipedInputStream(pos); pos.flush(); }catch (IOException e) { new ErrorMessage("Could not subscribe!", "See stderr for more details").open(); <START> e.printStackTrace(); <END> } inputGobbler = new StreamGobbler(pis); addInputStreamListener(logger); return true; } else { session.delSubscription(scriptid); new ErrorMessage("Could not subscribe!", "Response from Server not valid \n See stderr for more details").open(); return false; } }</code><technical_language>is need add printing of stack trace if is ErrorMessage. right add stack trace message itself</technical_language>

Target:
public boolean init() { if (!ClientSession.isConnected()) { return false; } try{ ScpClient scpclient = new ScpClient(); scpclient.transfer(filename,"/tmp/"+ filename.substring(filename.lastIndexOf('/')+1)); } catch (IOException e) { e.printStackTrace(); } catch (JSchException e) { e.printStackTrace(); } scriptid = ClientSession.getNewScriptId(); final DMRequest subreq = new DMRequest(DMRequest.SUBSCRIBE,scriptid, filename,session.getcid(), 0, isGuru); if (!session.sendRequest(subreq)) { } session.addSubscription(scriptid); try { Thread.sleep(500); } catch (InterruptedException ie) final DMResponse subrep = session.recvResponse(scriptid); if (subrep.isValid()) { scriptid = subrep.getscriptID(); logger = new LoggingStreamDaemon(); inputListeners.add(logger); try{ pos = new PipedOutputStream(); pis = new PipedInputStream(pos); pos.flush(); }catch (IOException e) { new ErrorMessage("Could not subscribe!", "See stderr for more details").open(); } inputGobbler = new StreamGobbler(pis); addInputStreamListener(logger); return true; } else { session.delSubscription(scriptid); new ErrorMessage("Could not subscribe!", "Response from Server not valid \n See stderr for more details").open(); return false; } }
Source:
<code>private void addHookStepToTestCaseMap(Map<String, Object> currentStepOrHookMap, HookType hookType) { String hookName; if (hookType.toString().contains("after")) hookName = "after"; else hookName = "before"; Map<String, Object> mapToAddTo; if (hookType == HookType.After || hookType == HookType.Before) { mapToAddTo = currentTestCaseMap; } else { <START> if (hookType == HookType.AfterStep) <END> mapToAddTo = currentStepsList.get(currentStepsList.size() - 1); else mapToAddTo = currentBeforeStepHookList; } if (!mapToAddTo.containsKey(hookName)) { mapToAddTo.put(hookName, new ArrayList<Map<String, Object>>()); } ((List<Map<String, Object>>)mapToAddTo.get(hookName)).add(currentStepOrHookMap); }</code><technical_language>I explicitly check hook type. if (hookType == HookType.AfterStep) if(hookType == HookType.BeforeStep) flatten nested if statement else if</technical_language>

Target:
private void addHookStepToTestCaseMap(Map<String, Object> currentStepOrHookMap, HookType hookType) { String hookName; if (hookType.toString().contains("after")) hookName = "after"; else hookName = "before"; Map<String, Object> mapToAddTo; switch (hookType) { case Before: mapToAddTo = currentTestCaseMap; break; case After: mapToAddTo = currentTestCaseMap; break; case BeforeStep: mapToAddTo = currentBeforeStepHookList; break; case AfterStep: mapToAddTo = currentStepsList.get(currentStepsList.size() - 1); break; default: mapToAddTo = currentTestCaseMap; } if (!mapToAddTo.containsKey(hookName)) { mapToAddTo.put(hookName, new ArrayList<Map<String, Object>>()); } ((List<Map<String, Object>>)mapToAddTo.get(hookName)).add(currentStepOrHookMap); }
Source:
<code>private void validate() { <START> if (!containsMacro("timeSuffix") && !Strings.isNullOrEmpty(timeSufix)) { <END> new SimpleDateFormat(timeSufix); } }</code><technical_language>do need check !containsMacro("timeSuffix")? sufficient check !Strings.isNullOrEmpty(timeSufix)</technical_language>

Target:
private void validate() { if (!Strings.isNullOrEmpty(timeSufix)) { new SimpleDateFormat(timeSufix); } }
Source:
<code>public synchronized void start() { <START> if (!running) { <END> LOG.info("Starting Replication Monitor Thread."); running = true; replicationMonitor = new Thread(this::run); replicationMonitor.setName("ReplicationMonitor"); replicationMonitor.setDaemon(true); replicationMonitor.start(); } else { LOG.info("Replication Monitor Thread is already running."); } }</code><technical_language>need check isRunning() method. example: call 1. start, 2. stop, (but stopped completely) 3. calling start immediately try start if check running flag</technical_language>

Target:
public synchronized void start() { if (!isRunning()) { LOG.info("Starting Replication Monitor Thread."); running = true; replicationMonitor = new Thread(this::run); replicationMonitor.setName("ReplicationMonitor"); replicationMonitor.setDaemon(true); replicationMonitor.start(); } else { LOG.info("Replication Monitor Thread is already running."); } }
Source:
<code>public Optional<PaxosValue> getGreatestLearnedValue() { if (!state.isEmpty()) { <START> return Optional.ofNullable(state.get(state.lastKey())); <END> } return Optional.empty(); }</code><technical_language>If I understood correctly empty result is a "non-standard" path I invert if</technical_language>

Target:
public Optional<PaxosValue> getGreatestLearnedValue() { if (state.isEmpty()) { return Optional.empty(); } return Optional.ofNullable(state.get(state.lastKey())); }
Source:
<code><START> default void waitForTransactionData(int expectedTopologyId, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { <END> try { CompletableFuture<Void> transactionDataFuture = transactionDataFuture(expectedTopologyId); if (transactionDataFuture != null) transactionDataFuture.get(timeout, unit); } catch (ExecutionException e) { throw new CacheException(e.getCause()); } }</code><technical_language>This SPI, worth putting implementation in interface</technical_language>

Target:
default void waitForTransactionData(int expectedTopologyId, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { try { CompletableFuture<Void> transactionDataFuture = transactionDataFuture(expectedTopologyId); transactionDataFuture.get(timeout, unit); } catch (ExecutionException e) { throw new CacheException(e.getCause()); } }
Source:
<code>private String[] getDataTypes() { List<BaseType1> list = Arrays.asList(BaseType1.values()); Collections.sort(list); String[] types = new String[list.size()]; <START> int i = 0; for (BaseType1 type : list) { types[i++] = type.getName(); } <END> return types; }</code><technical_language>this done a stream right? types = list.stream().map(e -> e.getName()).Collect(Collectors.toList())</technical_language>

Target:
private String[] getDataTypes() { List<BaseType1> list = Arrays.asList(BaseType1.values()); return list.stream().map(BaseType1::getName).collect(Collectors.toList()).toArray(new String[0]); }
Source:
<code>public FileObject getDescription() { <START> Resource sourceMd = this.getResource(); <END> Statement s = sourceMd.getProperty(PcdmModels.hasRelatedObject); if (s != null) { PID fileObjPid = PIDs.get(s.getResource().getURI()); return repository.getFileObject(fileObjPid); } else { return null; } }</code><technical_language>suggest renaming this variable sourceMd implies source metadata in this context, resource for current contentObject</technical_language>

Target:
public FileObject getDescription() { Resource res = this.getResource(); Statement s = res.getProperty(PcdmModels.hasRelatedObject); if (s != null) { PID fileObjPid = PIDs.get(s.getResource().getURI()); return repository.getFileObject(fileObjPid); } else { return null; } }
Source:
<code>public CommonXAxisModelBuilder addYSeries(IYSeries ySeries) { if (fXValues.length != ySeries.getDatapoints().length) { throw new IllegalStateException("All series in list must be of length : " + fXValues.length); } <START> deleteSeries(ySeries.getLabel()); <END> fYSeries.put(ySeries.getLabel(), ySeries); fModel = null; return this; }</code><technical_language>put remove previous mapping</technical_language>

Target:
public CommonXAxisModelBuilder addYSeries(IYSeries ySeries) { if (fXValues.length == 0) { throw new IllegalStateException("X values must be set before setting Y values"); } if (fXValues.length != ySeries.getDatapoints().length) { throw new IllegalStateException("All series in list must be of length : " + fXValues.length); } fYSeries.put(ySeries.getLabel(), ySeries); fModel = null; return this; }
Source:
<code>protected void createEmptyRepository() throws Exception { File gitDir = new File(new File(getTestDirectory(), EMPTY_REPOSITORY), Constants.DOT_GIT); <START> Repository myRepository = new RepositoryBuilder().setGitDir(gitDir) <END> .build(); myRepository.create(); IProject firstProject = ResourcesPlugin.getWorkspace().getRoot() .getProject(EMPTY_PROJECT); if (firstProject.exists()) firstProject.delete(true, null); IProjectDescription desc = ResourcesPlugin.getWorkspace() .newProjectDescription(EMPTY_PROJECT); desc.setLocation(new Path(new File(myRepository.getWorkTree(), EMPTY_PROJECT).getPath())); firstProject.create(desc, null); firstProject.open(null); IFolder folder = firstProject.getFolder(FOLDER); folder.create(false, true, null); IFile textFile = folder.getFile(FILE1); textFile.create(new ByteArrayInputStream("Hello, world" .getBytes(firstProject.getDefaultCharset())), false, null); IFile textFile2 = folder.getFile(FILE2); textFile2.create(new ByteArrayInputStream("Some more content" .getBytes(firstProject.getDefaultCharset())), false, null); new ConnectProviderOperation(firstProject, gitDir).execute(null); }</code><technical_language>FileRepositoryBuilder.create</technical_language>

Target:
protected void createEmptyRepository() throws Exception { File gitDir = new File(new File(getTestDirectory(), EMPTY_REPOSITORY), Constants.DOT_GIT); Repository myRepository = FileRepositoryBuilder.create(gitDir); myRepository.create(); IProject firstProject = ResourcesPlugin.getWorkspace().getRoot() .getProject(EMPTY_PROJECT); if (firstProject.exists()) firstProject.delete(true, null); IProjectDescription desc = ResourcesPlugin.getWorkspace() .newProjectDescription(EMPTY_PROJECT); desc.setLocation(new Path(new File(myRepository.getWorkTree(), EMPTY_PROJECT).getPath())); firstProject.create(desc, null); firstProject.open(null); IFolder folder = firstProject.getFolder(FOLDER); folder.create(false, true, null); IFile textFile = folder.getFile(FILE1); textFile.create(new ByteArrayInputStream("Hello, world" .getBytes(firstProject.getDefaultCharset())), false, null); IFile textFile2 = folder.getFile(FILE2); textFile2.create(new ByteArrayInputStream("Some more content" .getBytes(firstProject.getDefaultCharset())), false, null); new ConnectProviderOperation(firstProject, gitDir).execute(null); }
Source:
<code>protected void loadFieldIntoDatatableFromBpm(String containerId, String processId) throws ApsSystemException { KieBpmConfig config = getFormManager().getKieServerConfigurations().get(this.getKnowledgeSourcePath()); List<KieProcess> processes = getFormManager().getProcessDefinitionsList(config); if (!processes.isEmpty()) { List<String> fields = new ArrayList<>(); <START> logger.info("***************************** \n"+processes.get(0).toString()+"\n*****************************"); <END> StringTokenizer tokenizer = new StringTokenizer(processes.get(0).toString(), ","); Byte position = 1; while (tokenizer.hasMoreTokens()) { final String name = tokenizer.nextToken().trim(); fields.add(name); } super.loadDataIntoFieldDatatable(fields); } Map<String, String> columns = new HashMap<>(); this.loadDataIntoFieldDatatable(columns); }</code><technical_language>info</technical_language>

Target:
protected void loadFieldIntoDatatableFromBpm(String containerId, String processId) throws ApsSystemException { KieBpmConfig config = getFormManager().getKieServerConfigurations().get(this.getKnowledgeSourcePath()); List<KieProcess> processes = getFormManager().getProcessDefinitionsList(config); if (!processes.isEmpty()) { List<String> fields = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(processes.get(0).toString(), ","); Byte position = 1; while (tokenizer.hasMoreTokens()) { final String name = tokenizer.nextToken().trim(); fields.add(name); } super.loadDataIntoFieldDatatable(fields); } Map<String, String> columns = new HashMap<>(); this.loadDataIntoFieldDatatable(columns); }