auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void executeCommand() { if (getDiskImage() != null) { try { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = performDeleteImageVdsmOperation(); getTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getStorageDomainId())); } catch (EngineException e) { if (e.getErrorCode() == EngineError.ImageDoesNotExistInDomainError) { log.info("Disk '{}' doesn't exist on storage domain '{}', rolling forward", getDiskImage().getId(), getStorageDomainId()); } else if (e.getErrorCode() == EngineError.ImageDeleteError && isImageRemovedFromStorage()) { log.info("Disk '{}' was deleted from storage domain '{}'", getDiskImage().getId(), getStorageDomainId()); } else { throw e; } } <START> if (getParameters().getParentCommand() != ActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != ActionType.RemoveVmTemplateFromImportExport && getParameters().getParentCommand() != ActionType.RemoveUnregisteredVmTemplate && getParameters().getParentCommand() != ActionType.RemoveUnregisteredVm) { <END> performImageDbOperations(); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }</code><technical_language>changed "switch" 4 cases a break-through a "performImageDbOperations()" end of "case"s.. more readable</technical_language>

Target:
protected void executeCommand() { if (getDiskImage() != null) { try { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = performDeleteImageVdsmOperation(); getTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getStorageDomainId())); } catch (EngineException e) { if (e.getErrorCode() == EngineError.ImageDoesNotExistInDomainError) { log.info("Disk '{}' doesn't exist on storage domain '{}', rolling forward", getDiskImage().getId(), getStorageDomainId()); } else if (e.getErrorCode() == EngineError.ImageDeleteError && isImageRemovedFromStorage()) { log.info("Disk '{}' was deleted from storage domain '{}'", getDiskImage().getId(), getStorageDomainId()); } else { throw e; } } if (!actionsNotRequiredDbOperation.contains(getParameters().getParentCommand())) { performImageDbOperations(); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }
Source:
<code>private void offerPaymentStateTransitionEvents(long currentId, ChargeEventEntity chargeEventEntity, PaymentStateTransition transition) { Event event = EventFactory.createPaymentEvent(chargeEventEntity, transition.getStateTransitionEventClass()); final boolean emittedBefore = emittedEventDao.hasBeenEmittedBefore(event); <START> if (doNotForceEmission && emittedBefore) { <END> logger.info("[{}] - found - charge event emitted before", currentId, chargeEventEntity.getId()); } else { logger.info("[{}] - found - emitting for charge event ", currentId, event, chargeEventEntity.getId()); stateTransitionQueue.offer(transition); persistEventEmittedRecord(event); } }</code><technical_language>need additional DB call hasBeenEmittedBefore(event) doNotForceEmission=false. suggestion public void emitAndPersistEventForRefundHistoryEntry(RefundHistory refundHistory) { Class refundEventClass = RefundStateEventMap.calculateRefundEventClass(refundHistory.getUserExternalId(), refundHistory.getStatus()); Event event = EventFactory.createRefundEvent(refundHistory, refundEventClass); if(!doNotForceEmission){ emitRefundEvent(refundHistory, refundEventClass, event); } else{ boolean emittedBefore = emittedEventDao.hasBeenEmittedBefore(event); if(emittedBefore) logger.info("Refund history event emitted [refundExternalId={}] [refundHistoryId={}]", refundHistory.getExternalId(), refundHistory.getId()); else { emitRefundEvent(refundHistory, refundEventClass, event); } } } private void emitRefundEvent(RefundHistory refundHistory, Class refundEventClass, Event event) { RefundStateTransition stateTransition = new RefundStateTransition( refundHistory.getExternalId(), refundHistory.getStatus(), refundEventClass); logger.info("Processing new refund history event: [refundExternalId={}] [refundHistoryId={}]", refundHistory.getExternalId(), refundHistory.getId()); stateTransitionQueue.offer(stateTransition); persistEventEmittedRecord(event); }</technical_language>

Target:
private void offerPaymentStateTransitionEvents(long currentId, ChargeEventEntity chargeEventEntity, PaymentStateTransition transition) { Event event = EventFactory.createPaymentEvent(chargeEventEntity, transition.getStateTransitionEventClass()); if (shouldForceEmission) { offerStateTransitionEvent(currentId, chargeEventEntity, transition, event); } else { final boolean emittedBefore = emittedEventDao.hasBeenEmittedBefore(event); if (emittedBefore) { logger.info("[{}] - found - charge event emitted before", currentId, chargeEventEntity.getId()); } else { offerStateTransitionEvent(currentId, chargeEventEntity, transition, event); } } }
Source:
<code>Column<ObjectProperty, List<ImageWrapper>> createPropertyTypeBrowseColumn() { final Column<ObjectProperty, List<ImageWrapper>> column = new Column<ObjectProperty, List<ImageWrapper>>(new MultiImageCell()) { int maxColumnWidth = 40; @Override public List<ImageWrapper> getValue(final ObjectProperty property) { List<ImageWrapper> imageWrapperList = fieldMetadataProviderList.stream() .map(p -> p.getFieldMetadata(property)) .flatMap(s -> s.map(Stream::of).orElseGet(Stream::empty)) .map(FieldMetadata::getImageWrapper) .filter(Objects::nonNull) .collect(Collectors.toList()); if (!imageWrapperList.isEmpty()) { <START> int targetColumnWidth = imageWrapperList.size() * 30; <END> if (targetColumnWidth > maxColumnWidth) { maxColumnWidth = targetColumnWidth; } propertiesTable.setColumnWidth(this, maxColumnWidth, Style.Unit.PX); } return imageWrapperList; } }; return column; }</code><technical_language>this assume icons 30px wide</technical_language>

Target:
Column<ObjectProperty, List<ImageWrapper>> createPropertyTypeBrowseColumn() { final int defaultColumnWidth = 40; final Column<ObjectProperty, List<ImageWrapper>> column = new Column<ObjectProperty, List<ImageWrapper>>(new MultiImageCell()) { int maxColumnWidth = defaultColumnWidth; @Override public List<ImageWrapper> getValue(final ObjectProperty property) { List<ImageWrapper> imageWrapperList = fieldMetadataProviderList.stream() .map(p -> p.getFieldMetadata(property)) .flatMap(s -> s.map(Stream::of).orElseGet(Stream::empty)) .map(FieldMetadata::getImageWrapper) .filter(Objects::nonNull) .collect(Collectors.toList()); if (!imageWrapperList.isEmpty()) { int targetColumnWidth = imageWrapperList.size() * (MultiImageCell.IMAGE_WIDTH + 5) + 20; if (targetColumnWidth > maxColumnWidth) { maxColumnWidth = targetColumnWidth; } propertiesTable.setColumnWidth(this, maxColumnWidth, Style.Unit.PX); } return imageWrapperList; } }; propertiesTable.setColumnWidth(column, defaultColumnWidth, Style.Unit.PX); return column; }
Source:
<code>public Dataset open(final Assembler assembler, final Resource root, final Mode mode) { checkType(root, MemoryDataset); final Dataset dataset = createTxnMem(); setContext(root, dataset.getContext()); final Resource defaultGraphDef = root.hasProperty(pDefaultGraph) ? getResourceValue(root, pDefaultGraph) : root.hasProperty(pGraph) ? getResourceValue(root, pGraph) : null; if (defaultGraphDef != null) dataset.setDefaultModel(retrieve(defaultGraphDef, assembler, mode)); final Predicate<RDFNode> isResource = n -> { if (n.isResource()) return true; throw new DatasetAssemblerException(root, "Not a resource: " + stringForRDFNode(n)); }; multiValue(root, data).parallelStream().filter(isResource) .forEach(defaultGraphNode -> read(dataset, defaultGraphNode.asResource().getURI())); <START> <END> multiValue(root, pNamedGraph).parallelStream().filter(isResource).forEach(namedGraphNode -> { final Resource namedGraphResource = namedGraphNode.asResource(); final String graphName = getAsStringValue(namedGraphResource, pGraphName); if (namedGraphResource.hasProperty(data)) { multiValue(namedGraphResource, data).parallelStream().filter(isResource).forEach(namedGraphData -> { final Model namedGraph = loadModel(namedGraphData.asResource().getURI()); dataset.addNamedModel(graphName, namedGraph); }); } else { final Model namedGraph = retrieve(namedGraphResource, assembler, mode); dataset.addNamedModel(graphName, namedGraph); } }); return dataset; }</code><technical_language>parallelStream() sense here. I needs sequential in transaction. memory dataset support parallel updates. best, get queued lock. error messages random order</technical_language>

Target:
public Dataset open(final Assembler assembler, final Resource root, final Mode mode) { checkType(root, MemoryDataset); final Dataset dataset = createTxnMem(); setContext(root, dataset.getContext()); dataset.begin(WRITE); if (root.hasProperty(data)) multiValueResource(root, data) .forEach(defaultGraphDocument -> read(dataset, defaultGraphDocument.getURI())); multiValueResource(root, pNamedGraph).forEach(namedGraphResource -> { final String graphName = getAsStringValue(namedGraphResource, pGraphName); if (namedGraphResource.hasProperty(data)) multiValueResource(namedGraphResource, data) .forEach(namedGraphData -> read(dataset.getNamedModel(graphName), namedGraphData.getURI())); }); dataset.commit(); return dataset; }
Source:
<code>public void testMqttSessionPresent() throws MqttException { MockMqttClient mockClient = new MockMqttClient(); final boolean actualSessionPresent; actualSessionPresent = mockClient.testToken.getSessionPresent(); final AWSIotMqttManager testSessionPresentFlag = new AWSIotMqttManager("test-sessionPresent-flag", Region.getRegion(Regions.US_EAST_1), TEST_ENDPOINT_PREFIX); testSessionPresentFlag.setMqttClient(mockClient); KeyStore testKeystore = AWSIotKeystoreHelper.getIotKeystore(CERT_ID, KEYSTORE_PATH, KEYSTORE_NAME, KEYSTORE_PASSWORD); testSessionPresentFlag.connect(testKeystore, new AWSIotMqttClientStatusCallback() { @Override public void onStatusChanged(AWSIotMqttClientStatus status, Throwable throwable) { <START> if (status == AWSIotMqttClientStatus.Connecting) { System.out.println("Client persistent-client-id connecton status: " + status); System.out.println("getSessionPresent: " + testSessionPresentFlag.getSessionPresent()); assertEquals(testSessionPresentFlag.getSessionPresent(), actualSessionPresent); } else if (status == AWSIotMqttClientStatus.Connected) { System.out.println("Client persistent-client-id connecton status: " + status); System.out.println("getSessionPresent: " + testSessionPresentFlag.getSessionPresent()); assertEquals(testSessionPresentFlag.getSessionPresent(), actualSessionPresent); } <END> } }); }</code><technical_language>duplicate code. if statement</technical_language>

Target:
public void testMqttSessionPresent() throws MqttException, InterruptedException { MockMqttClient mockClient = new MockMqttClient(); final boolean actualSessionPresent; actualSessionPresent = mockClient.testToken.getSessionPresent(); final CountDownLatch countDownLatch = new CountDownLatch(1); final AWSIotMqttManager testSessionPresentFlag = new AWSIotMqttManager("test-sessionPresent-flag", Region.getRegion(Regions.US_EAST_1), TEST_ENDPOINT_PREFIX); testSessionPresentFlag.setMqttClient(mockClient); KeyStore testKeystore = AWSIotKeystoreHelper.getIotKeystore(CERT_ID, KEYSTORE_PATH, KEYSTORE_NAME, KEYSTORE_PASSWORD); testSessionPresentFlag.connect(testKeystore, new AWSIotMqttClientStatusCallback() { @Override public void onStatusChanged(AWSIotMqttClientStatus status, Throwable throwable) { if (status == AWSIotMqttClientStatus.Connecting || status == AWSIotMqttClientStatus.Connected) { System.out.println("Client persistent-client-id connection status: " + status); System.out.println("getSessionPresent: " + testSessionPresentFlag.getSessionPresent()); countDownLatch.countDown(); } } }); if (countDownLatch.await(2, TimeUnit.SECONDS)) { assertEquals(testSessionPresentFlag.getSessionPresent(), actualSessionPresent); } else { fail("CountDownLatch timed out."); } }
Source:
<code>public TemplateWatcher( final MonitoringManager manager, final File templateDir, final long pollInterval ) throws IOException { this.manager = manager; this.handlebars.registerHelper( AllHelper.NAME, AllHelper.INSTANCE ); this.templateDir = templateDir.getCanonicalFile(); final FileAlterationObserver observer = new FileAlterationObserver( this.templateDir, TemplateEntry.getTemplateFileFilter( this.templateDir ) ); observer.addListener( this ); this.monitor = new FileAlterationMonitor( pollInterval, observer ); <START> this.monitor.setThreadFactory( new ThreadFactory() { <END> @Override public Thread newThread( final Runnable r ) { return new Thread( r, "Roboconf.TemplateWatcher" ); } } ); this.logger.fine( "Template watcher configured with templateDir=" + this.templateDir.toString() + " and pollInterval=" + pollInterval ); }</code><technical_language>I a private static class instead</technical_language>

Target:
public TemplateWatcher( final MonitoringManager manager, final File templateDir, final long pollInterval ) throws IOException { this.manager = manager; this.handlebars.registerHelper(AllHelper.NAME, AllHelper.INSTANCE); this.templateDir = templateDir.getCanonicalFile(); final FileAlterationObserver observer = new FileAlterationObserver( this.templateDir, TemplateEntry.getTemplateFileFilter(this.templateDir)); observer.addListener(this); this.monitor = new FileAlterationMonitor(pollInterval, observer); this.monitor.setThreadFactory(THREAD_FACTORY); this.logger.fine("Template watcher configured with templateDir=" + this.templateDir.toString() + " and pollInterval=" + pollInterval); }
Source:
<code>private void handleInternalLink(PageTitle title) { if (!isAdded()) { return; } if (referenceDialog != null && referenceDialog.isShowing()) { referenceDialog.dismiss(); } if (linkPreviewFunnel.getVersion() == 0 || app.getReleaseType() == WikipediaApp.RELEASE_PROD) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); ((PageActivity) getActivity()).displayNewPage(title, historyEntry); linkPreviewFunnel.logLinkClick(); <START> linkPreviewFunnel.logNavigate(); <END> } else { LinkPreviewDialog dialog = LinkPreviewDialog.newInstance(title, linkPreviewFunnel.getVersion()); dialog.show(getActivity().getSupportFragmentManager(), "link_preview_dialog"); } }</code><technical_language>For sake of saving some network traffic, call logNavigate in this case. simply assume that, in case of version 0, a linkClick event implies a navigate event</technical_language>

Target:
private void handleInternalLink(PageTitle title) { if (!isAdded()) { return; } if (referenceDialog != null && referenceDialog.isShowing()) { referenceDialog.dismiss(); } LinkPreviewFunnel linkPreviewFunnel = new LinkPreviewFunnel(app, title); if (linkPreviewFunnel.getVersion() == 0 || app.getReleaseType() == WikipediaApp.RELEASE_PROD) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); ((PageActivity) getActivity()).displayNewPage(title, historyEntry); linkPreviewFunnel.logLinkClick(); } else { LinkPreviewDialog dialog = LinkPreviewDialog.newInstance(title, linkPreviewFunnel.getVersion()); dialog.show(getActivity().getSupportFragmentManager(), "link_preview_dialog"); } }
Source:
<code>public void testFinalLocalVariableSwitchExpressions() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(FinalLocalVariableCheck.class); final String[] expected = { "19:19: " + getCheckMessage(MSG_KEY, "e"), "57:19: " + getCheckMessage(MSG_KEY, "e"), "95:19: " + getCheckMessage(MSG_KEY, "e"), "129:19: " + getCheckMessage(MSG_KEY, "e"), <START> }; <END> verify(checkConfig, getNonCompilablePath("InputFinalLocalVariableCheckSwitchExpressions.java"), expected); }</code><technical_language>Please move new code block end of file this change</technical_language>

Target:
public void testFinalLocalVariableSwitchExpressions() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(FinalLocalVariableCheck.class); final String[] expected = { "12:19: " + getCheckMessage(MSG_KEY, "e"), "50:19: " + getCheckMessage(MSG_KEY, "e"), "88:19: " + getCheckMessage(MSG_KEY, "e"), "122:19: " + getCheckMessage(MSG_KEY, "e"), }; verify(checkConfig, getNonCompilablePath("InputFinalLocalVariableCheckSwitchExpressions.java"), expected); }
Source:
<code>private void changeValue(String itemName, String deviceIP, EdimaxBindingConfiguration config, Command cmd) { if (cmd instanceof OnOffType) { try { Boolean currentState = createSender(config).getState(deviceIP); OnOffType targetState = (OnOffType) cmd; if (targetState == OnOffType.ON && !currentState) { createSender(config).switchState(deviceIP, Boolean.TRUE); } else if (targetState == OnOffType.OFF && currentState) { createSender(config).switchState(deviceIP, Boolean.FALSE); } } catch (IOException e) { <START> logger.error("Error in communication with device: " + itemName <END> + ". Cannot set update to device.", e); } } else { logger.error("Unsupported command: " + cmd); } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
private void changeValue(String itemName, String deviceIP, EdimaxBindingConfiguration config, Command cmd) { if (cmd instanceof OnOffType) { try { Boolean currentState = createSender(config).getState(deviceIP); OnOffType targetState = (OnOffType) cmd; if (targetState == OnOffType.ON && !currentState) { createSender(config).switchState(deviceIP, Boolean.TRUE); } else if (targetState == OnOffType.OFF && currentState) { createSender(config).switchState(deviceIP, Boolean.FALSE); } } catch (IOException e) { logger.error("Error in communication with device: {}. Cannot set update to device.", itemName, e); } } else { logger.error("Unsupported command: {}.", cmd); } }
Source:
<code>public String marshal(ZonedDateTime zonedDateTime) throws Exception { if (null == zonedDateTime) { return null; } <START> return zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).format(formatter); <END> }</code><technical_language>Ah, this on-obvious me: do switch zone UTF</technical_language>

Target:
public String marshal(ZonedDateTime zonedDateTime) { if (null == zonedDateTime) { return null; } return zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).format(formatter); }
Source:
<code>public List<Server> getReachableServers() { <START> return getServerList(true); <END> }</code><technical_language>In LB impls (both this Base version), if deprecating getServerList(boolean), preferable move code logic getReachableServer() getAllServers(), defer getServerList(boolean) call getReachableServers getAllServers based boolean</technical_language>

Target:
public List<Server> getReachableServers() { return null; }
Source:
<code>public final boolean include(RevWalk walker, RevCommit cmit) { BitmapIndex index = bitmap.getBitmapIndex(); Bitmap visitedBitmap; if (bitmap.contains(cmit)) { } else if ((visitedBitmap = <START> index.getBitmap(cmit)) <END> != null) { bitmap.or(visitedBitmap); } else { bitmap.addObject(cmit, Constants.OBJ_COMMIT); return true; } for (RevCommit p : cmit.getParents()) { p.add(RevFlag.SEEN); } return false; }</code><technical_language>Inlining bitmap.getBitmapIndex() avoids additional lookup needed if conditional statement is met. big a performance gain is, this is a RevWalk filter, worth doing</technical_language>

Target:
public final boolean include(RevWalk walker, RevCommit cmit) { Bitmap visitedBitmap; if (bitmap.contains(cmit)) { } else if ((visitedBitmap = bitmap.getBitmapIndex().getBitmap(cmit)) != null) { bitmap.or(visitedBitmap); } else { bitmap.addObject(cmit, Constants.OBJ_COMMIT); return true; } for (RevCommit p : cmit.getParents()) { p.add(RevFlag.SEEN); } return false; }
Source:
<code>@Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.set(offsets); <START> if (parent.getChildAdapterPosition(view) == 0) { <END> outRect.top = firstItemTopOffset; } }</code><technical_language>this is considered a more single purpose decorator? For example: public class HeaderMarginItemDecoration extends MarginItemDecoration { ... @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { if (parent.getChildAdapterPosition(view) == 0) { super.getItemOffsets(outRect, view, parent, state); } } ... benefit add decorations needed for a job. In case of FeedView, be: addItemDecoration(new MarginItemDecoration()); addItemDecoration(new HeaderMarginItemDecoration()); Other places MarginItemDecoration HeaderMarginItemDecoration other combinations. complication I of is compounding: > Item decorations ordered. Decorations earlier in list run/queried/drawn for effects item views. Padding added views nested; a padding added earlier decoration item decorations in list asked draw/pad previous decoration's area. a couple ways handle that: 1 account defining header margin (i.e., margin = desired - item_margin). 2 Change Item optionally omit header / footer items</technical_language>

Target:
@Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.set(offsets); }
Source:
<code><START> public ConstantExpression(final ByteBuffer value) { <END> this(Type.BLOB_TYPE, String.valueOf(value)); }</code><technical_language>First, this function is used, second, return a summary string of ByteBuffer. a problem for getJavaString parsed some value, for ConstantExpression constructor expecting a direct in a JSON string. I UnsupportedOperationException more sense if want output bytes string</technical_language>

Target:
public ConstantExpression(final ByteBuffer value) { throw new UnsupportedOperationException(); }
Source:
<code>public void nothing_to_do_when_new_assignee_is_same_as_old_one() throws Exception { IssueDto issue = newIssueWithBrowsePermission(); <START> UserDto userDto = db.users().insertUser(PREVIOUS_ASSIGNEE); <END> addUserAsMemberOfDefaultOrganization(userDto); tester.newRequest() .setParam("issue", issue.getKey()) .setParam("assignee", PREVIOUS_ASSIGNEE) .execute(); IssueDto issueReloaded = db.getDbClient().issueDao().selectByKey(db.getSession(), issue.getKey()).get(); assertThat(issueReloaded.getAssignee()).isEqualTo(PREVIOUS_ASSIGNEE); assertThat(issueReloaded.getUpdatedAt()).isEqualTo(PAST); assertThat(issueReloaded.getIssueUpdateTime()).isEqualTo(PAST); }</code><technical_language>I call magic. closer default behavior for premise instances. I said, a suggestion</technical_language>

Target:
public void nothing_to_do_when_new_assignee_is_same_as_old_one() throws Exception { IssueDto issue = newIssueWithBrowsePermission(); UserDto userDto = db.users().insertUser(PREVIOUS_ASSIGNEE); addUserAsMemberOfDefaultOrganization(userDto); ws.newRequest() .setParam("issue", issue.getKey()) .setParam("assignee", PREVIOUS_ASSIGNEE) .execute(); IssueDto issueReloaded = db.getDbClient().issueDao().selectByKey(db.getSession(), issue.getKey()).get(); assertThat(issueReloaded.getAssignee()).isEqualTo(PREVIOUS_ASSIGNEE); assertThat(issueReloaded.getUpdatedAt()).isEqualTo(PAST); assertThat(issueReloaded.getIssueUpdateTime()).isEqualTo(PAST); }
Source:
<code>public void testAddModuleRequiresAndImportProposal() throws Exception { StringBuffer buf= new StringBuffer(); buf.append("module test {\n"); buf.append("}\n"); IPackageFragment def= fSourceFolder.createPackageFragment("", false, null); def.createCompilationUnit("module-info.java", buf.toString(), false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); buf= new StringBuffer(); buf.append("package test;\n"); buf.append("public class Cls {\n"); buf.append(" One one;\n"); buf.append("}\n"); ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); <START> <END> CompilationUnit astRoot= getASTRoot(cu); ArrayList<IJavaCompletionProposal> proposals= collectCorrections(cu, astRoot); String[] args = {"java.defaultProject"}; String requiresStr= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_add_requires_module_info, args); String[] args2 = {"One", "java.defaultProject"}; final String importStr= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args2); requiresStr= requiresStr.substring(0, 1).toLowerCase() + requiresStr.substring(1); String proposalStr= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_combine_two_proposals_info, new String[] { importStr, requiresStr }); assertProposalExists(proposals, proposalStr); }</code><technical_language>remove extra line</technical_language>

Target:
public void testAddModuleRequiresAndImportProposal() throws Exception { StringBuffer buf= new StringBuffer(); buf.append("module test {\n"); buf.append("}\n"); IPackageFragment def= fSourceFolder.createPackageFragment("", false, null); def.createCompilationUnit("module-info.java", buf.toString(), false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); buf= new StringBuffer(); buf.append("package test;\n"); buf.append("public class Cls {\n"); buf.append(" One one;\n"); buf.append("}\n"); ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); CompilationUnit astRoot= getASTRoot(cu); ArrayList<IJavaCompletionProposal> proposals= collectCorrections(cu, astRoot); String[] args= { "java.defaultProject" }; String requiresStr= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_add_requires_module_info, args); requiresStr= requiresStr.substring(0, 1).toLowerCase() + requiresStr.substring(1); String[] args2= { "One", "java.defaultProject" }; final String importStr= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args2); String proposalStr= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_combine_two_proposals_info, new String[] { importStr, requiresStr }); assertProposalExists(proposals, proposalStr); }
Source:
<code>cepStatelessRulesTranslator( final ContinuousStream<Map<String, Object>> inputMap, final List<CepStatelessRule> cepStatelessRules) { int ruleNum = cepStatelessRules.size(); for(int i=0; i<ruleNum; i++){ <START> CepStatelessRule rule = cepStatelessRules.get(i); <END> CepAction action = rule.getAction(); CepSink sink = action.getCepSink(); ContinuousStream<Map<String, Object>> temp = inputMap; if(action.getCepActionType() == CepActionType.TEXT_WRITE) { temp = cepConditionTranslator(temp, rule.getCondition()); } else { continue; } if(sink.getCepSinkType() == CepSinkType.TEXT_SOCKET_OUTPUT) { final List<Object> params = action.getParams(); final String separator = sink.getSeparator(); final MISTFunction<Map<String, Object>, String> mapFunction = s -> CepTuple.mapToString(s, params, separator); temp.map(mapFunction) .textSocketOutput((String)sink.getSinkConfigs().get("SOCKET_SINK_ADDRESS"), (int)sink.getSinkConfigs().get("SOCKET_SINK_PORT")); } else { throw new IllegalStateException("Only TEXT_SOCKET_OUTPUT is supported now!"); } } return inputMap; }</code><technical_language>final</technical_language>

Target:
private static ContinuousStream<Map<String, Object>> cepStatelessRulesTranslator( final ContinuousStream<Map<String, Object>> inputMap, final List<CepStatelessRule> cepStatelessRules) { final int ruleNum = cepStatelessRules.size(); for (int i = 0; i < ruleNum; i++) { final CepStatelessRule rule = cepStatelessRules.get(i); final CepAction action = rule.getAction(); final CepSink sink = action.getCepSink(); ContinuousStream<Map<String, Object>> temp = inputMap; switch (action.getCepActionType()) { case TEXT_WRITE: { switch (sink.getCepSinkType()) { case TEXT_SOCKET_OUTPUT: { temp = cepConditionTranslator(temp, rule.getCondition()); final List<Object> params = action.getParams(); final String separator = sink.getSeparator(); temp.map(new CepMapToStringFunction(params, separator)) .textSocketOutput((String)sink.getSinkConfigs().get("SOCKET_SINK_ADDRESS"), (int)sink.getSinkConfigs().get("SOCKET_SINK_PORT")); break; } default: throw new IllegalStateException("Only TEXT_SOCKET_OUTPUT is supported now!"); } break; } default: continue; } } return inputMap; }
Source:
<code>public RabbitmqProducer(MaxwellContext context) { super(context); this.exchangeName = context.getConfig().rabbitmqExchange; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(context.getConfig().rabbitmqHost); try { this.connection = factory.newConnection(); this.channel = connection.createChannel(); this.channel.exchangeDeclare(exchangeName, context.getConfig().rabbitmqExchangeType); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>rethrow runtime errors, I think. If connect channel crash in a separate thread. Note producer error handling needs some tender loving care</technical_language>

Target:
public RabbitmqProducer(MaxwellContext context) { super(context); exchangeName = context.getConfig().rabbitmqExchange; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(context.getConfig().rabbitmqHost); try { this.channel = factory.newConnection().createChannel(); this.channel.exchangeDeclare(exchangeName, context.getConfig().rabbitmqExchangeType); } catch (IOException | TimeoutException e) { throw new RuntimeException(e); } }
Source:
<code>public final String toHaskellType() { final StringBuilder out = new StringBuilder(); for (final Type type : this.types) { <START> out.append("instance ").append(this.name).append(" ").append(type.toHaskellType()).append("\n"); <END> } return out.toString().trim(); }</code><technical_language>Hardcoded "\n"</technical_language>

Target:
public final String toHaskellType() { final StringBuilder out = new StringBuilder(); for (final Type type : this.types) { out.append("instance ").append(this.name).append(" ").append(type.toHaskellType()) .append(System.lineSeparator()); } return out.toString().trim(); }
Source:
<code><START> private IGraphicalEditPart getEditPart(Diagram diagram, String semanticElement) { <END> modelSetFixture.getPageManager().openPage(diagram); View diagramView = DiagramUtils.findShape(diagram, semanticElement); if (diagramView == null) { diagramView = DiagramUtils.findEdge(diagram, semanticElement); } if (diagramView == null) { Iterator<?> iterator = diagram.eAllContents(); while (null == diagramView && iterator.hasNext()) { Object object = iterator.next(); if (object instanceof View) { diagramView = DiagramUtils.findShape((View) object, semanticElement); if (diagramView == null) { diagramView = DiagramUtils.findEdge((View) object, semanticElement); } } } } assertNotNull(diagramView); IGraphicalEditPart semanticEP = DiagramUtils.findEditPartforView(modelSetFixture.getEditor(), diagramView, IGraphicalEditPart.class); assertNotNull(semanticEP); return semanticEP; }</code><technical_language>final *2</technical_language>

Target:
private IGraphicalEditPart getEditPart(Diagram diagram, String semanticElement) { modelSetFixture.getPageManager().openPage(diagram); View diagramView = DiagramUtils.findShape(diagram, semanticElement); if (null == diagramView) { diagramView = DiagramUtils.findEdge(diagram, semanticElement); } if (null == diagramView) { Iterator<?> iterator = diagram.eAllContents(); while (null == diagramView && iterator.hasNext()) { Object object = iterator.next(); if (object instanceof View) { diagramView = DiagramUtils.findShape((View) object, semanticElement); if (null == diagramView) { diagramView = DiagramUtils.findEdge((View) object, semanticElement); } } } } assertNotNull(diagramView); IGraphicalEditPart semanticEP = DiagramUtils.findEditPartforView(modelSetFixture.getEditor(), diagramView, IGraphicalEditPart.class); assertNotNull(semanticEP); return semanticEP; }
Source:
<code><START> public void deserializeJetpackRestResponse(SiteModel site, JSONObject response) { <END> if (site == null || response == null) return; JSONObject settingsObject = response.optJSONObject("settings"); mRemoteSettings.monitorActive = settingsObject.optBoolean(JP_MONITOR_ACTIVE_KEY, false); mRemoteSettings.emailNotifications = settingsObject.optBoolean(JP_MONITOR_EMAIL_NOTES_KEY, false); mRemoteSettings.wpNotifications = settingsObject.optBoolean(JP_MONITOR_WP_NOTES_KEY, false); }</code><technical_language>private here</technical_language>

Target:
private void deserializeJetpackRestResponse(SiteModel site, JSONObject response) { if (site == null || response == null) return; JSONObject settingsObject = response.optJSONObject("settings"); mRemoteSettings.monitorActive = settingsObject.optBoolean(JP_MONITOR_ACTIVE_KEY, false); mRemoteSettings.emailNotifications = settingsObject.optBoolean(JP_MONITOR_EMAIL_NOTES_KEY, false); mRemoteSettings.wpNotifications = settingsObject.optBoolean(JP_MONITOR_WP_NOTES_KEY, false); }
Source:
<code>private Map<String, ?> resolveConfigVariables(Map<String, ?> configProviderProps, Map<String, Object> originals) { Map<String, String> providerConfigString; Map<String, ?> configProperties; <START> Map<String, Object> originalsMutable = new HashMap<>(); <END> originalsMutable.putAll(originals); Map<String, String> indirectVariables = extractPotentialVariables(originals); if (configProviderProps == null || configProviderProps.isEmpty()) { providerConfigString = indirectVariables; configProperties = originals; } else { providerConfigString = extractPotentialVariables(configProviderProps); configProperties = configProviderProps; } Map<String, ConfigProvider> providers = instantiateConfigProviders(providerConfigString, configProperties); if (!providers.isEmpty()) { ConfigTransformer configTransformer = new ConfigTransformer(providers); ConfigTransformerResult result = configTransformer.transform(indirectVariables); originalsMutable.putAll(result.data()); } return originalsMutable; }</code><technical_language>a bit weird convert immutable map mutable convert back. refactor logic push modification logic</technical_language>

Target:
private Map<String, ?> resolveConfigVariables(Map<String, ?> configProviderProps, Map<String, Object> originals) { Map<String, String> providerConfigString; Map<String, ?> configProperties; Map<String, Object> resolvedOriginals = new HashMap<>(); Map<String, String> indirectVariables = extractPotentialVariables(originals); resolvedOriginals.putAll(originals); if (configProviderProps == null || configProviderProps.isEmpty()) { providerConfigString = indirectVariables; configProperties = originals; } else { providerConfigString = extractPotentialVariables(configProviderProps); configProperties = configProviderProps; } Map<String, ConfigProvider> providers = instantiateConfigProviders(providerConfigString, configProperties); if (!providers.isEmpty()) { ConfigTransformer configTransformer = new ConfigTransformer(providers); ConfigTransformerResult result = configTransformer.transform(indirectVariables); if (!result.data().isEmpty()) { resolvedOriginals.putAll(result.data()); } } return new ResolvingMap<>(resolvedOriginals, originals); }
Source:
<code>private JPanel getTechPanel() { if (techPanel == null) { techPanel = new JPanel(new GridBagLayout()); JScrollPane scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setViewportView(getTechTree()); scrollPane.setBorder( javax.swing.BorderFactory.createEtchedBorder( javax.swing.border.EtchedBorder.RAISED)); techPanel.add(scrollPane, LayoutHelper.getGBC(0, 0, 1, 1, 1.0D, 1.0D)); } else { <START> getTechTree().refresh(); <END> } return techPanel; }</code><technical_language>This resets tree state, losing previous selections</technical_language>

Target:
private JPanel getTechPanel() { if (techPanel == null) { techPanel = new JPanel(new GridBagLayout()); JScrollPane scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setViewportView(getTechTree()); scrollPane.setBorder( javax.swing.BorderFactory.createEtchedBorder( javax.swing.border.EtchedBorder.RAISED)); techPanel.add(scrollPane, LayoutHelper.getGBC(0, 0, 1, 1, 1.0D, 1.0D)); } return techPanel; }
Source:
<code>public void onAddAccountsToGroup(Account.Id me, Collection<AccountGroupMember> added) { List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); for (AccountGroupMember m : added) { AccountGroupMemberAudit audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs()); auditInserts.add(audit); } try { db.get().accountGroupMembersAudit().insert(auditInserts); } catch (OrmException e) { <START> String header = "Cannot log add accounts to group event performed by user "; <END> logOrmExceptionForAccounts(me, added, e, header); } }</code><technical_language>Unnecessary, inline string in method invocation directly, below</technical_language>

Target:
public void onAddAccountsToGroup(Account.Id me, Collection<AccountGroupMember> added) { List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); for (AccountGroupMember m : added) { AccountGroupMemberAudit audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs()); auditInserts.add(audit); } try { db.get().accountGroupMembersAudit().insert(auditInserts); } catch (OrmException e) { logOrmExceptionForAccounts( "Cannot log add accounts to group event performed by user", me, added, e); } }
Source:
<code>private void connect() { Controller[] controllers; while (true) { controllers = Joysticks.availableControllers(); <START> for (Controller c : controllers) { <END> if (Pattern.matches(NAME, c.getName())) { this.jsController.onNext(new LogitechExtremeJoystick( createEvents(c), createAxes(c), createButtons(c))); return; } } } }</code><technical_language>final</technical_language>

Target:
private Controller connect() { final Controller[] controllers = Joysticks.availableControllers(); for (Controller c : controllers) { if (Pattern.matches(NAME, c.getName())) { return c; } } return null; }
Source:
<code>public void testOvfDataUpdaterPartOfVmsAndTemplatesAreLocked() { int size = ITEMS_COUNT_PER_UPDATE; List<Guid> vmGuids = generateGuidList(size); List<Guid> removedGuids = generateGuidList(size); List<Guid> templatesGuids = generateGuidList(size); addVms(vmGuids, 2, VMStatus.ImageLocked, ImageStatus.OK); addTemplates(templatesGuids, 2, VmTemplateStatus.Locked, ImageStatus.OK); List<Guid> vmGuidsUnlocked = generateGuidList(size); List<Guid> templatesGuidsUnlocked = generateGuidList(size); addVms(vmGuidsUnlocked, 2, VMStatus.Down, ImageStatus.OK); addTemplates(templatesGuidsUnlocked, 2, VmTemplateStatus.OK, ImageStatus.OK); vmGuids.addAll(vmGuidsUnlocked); templatesGuids.addAll(templatesGuidsUnlocked); initTestForPool(pool1.getId(), vmGuids, templatesGuids, removedGuids); updater.ovfUpdate_timer(); List<Guid> neededToBeUpdated = new LinkedList<Guid>(vmGuidsUnlocked); neededToBeUpdated.addAll(templatesGuidsUnlocked); <START> verify(updater, times(numberOfTimesToBeCalled(size, true))).performOvfUpdate(any(Guid.class), any(Map.class)); <END> verify(updater, times(size)).executeRemoveVmInSpm(any(Guid.class), any(Guid.class), any(Guid.class)); verifyCorrectOvfDataUpdaterRun(pool1.getId(), neededToBeUpdated, removedGuids); }</code><technical_language>s/any(Map.class)/anyMap()/</technical_language>

Target:
public void testOvfDataUpdaterPartOfVmsAndTemplatesAreLocked() { int size = ITEMS_COUNT_PER_UPDATE; List<Guid> vmGuids = generateGuidList(size); List<Guid> removedGuids = generateGuidList(size); List<Guid> templatesGuids = generateGuidList(size); addVms(vmGuids, 2, VMStatus.ImageLocked, ImageStatus.OK); addTemplates(templatesGuids, 2, VmTemplateStatus.Locked, ImageStatus.OK); List<Guid> vmGuidsUnlocked = generateGuidList(size); List<Guid> templatesGuidsUnlocked = generateGuidList(size); addVms(vmGuidsUnlocked, 2, VMStatus.Down, ImageStatus.OK); addTemplates(templatesGuidsUnlocked, 2, VmTemplateStatus.OK, ImageStatus.OK); vmGuids.addAll(vmGuidsUnlocked); templatesGuids.addAll(templatesGuidsUnlocked); initTestForPool(pool1.getId(), vmGuids, templatesGuids, removedGuids); updater.ovfUpdate_timer(); List<Guid> neededToBeUpdated = new LinkedList<Guid>(vmGuidsUnlocked); neededToBeUpdated.addAll(templatesGuidsUnlocked); verify(updater, times(numberOfTimesToBeCalled(size, true))).performOvfUpdate(any(Guid.class), anyMap()); verify(updater, times(size)).executeRemoveVmInSpm(any(Guid.class), any(Guid.class), any(Guid.class)); verifyCorrectOvfDataUpdaterRun(pool1.getId(), neededToBeUpdated, removedGuids); }
Source:
<code>HermesConsumers(HooksHandler hooksHandler, List<Binder> binders, MultiMap<String, Function<ServiceLocator, ProtocolMessageSenderProvider>> messageSenderProvidersSuppliers, List<Function<ServiceLocator, LogRepository>> logRepositories, boolean flushLogsShutdownHookEnabled) { this.hooksHandler = hooksHandler; this.messageSenderProvidersSuppliers = messageSenderProvidersSuppliers; this.logRepositories = logRepositories; serviceLocator = createDIContainer(binders); trackers = serviceLocator.getService(Trackers.class); consumerHttpServer = serviceLocator.getService(ConsumerHttpServer.class); messageSenderFactory = serviceLocator.getService(MessageSenderFactory.class); supervisorController = serviceLocator.getService(SupervisorController.class); maxRateSupervisor = serviceLocator.getService(MaxRateSupervisor.class); assignmentCache = serviceLocator.getService(SubscriptionAssignmentCache.class); oAuthHttpClient = serviceLocator.getService(OAuthClient.class); HttpClientsWorkloadReporter httpClientsWorkloadReporter = serviceLocator.getService(HttpClientsWorkloadReporter.class); <START> httpClientsWorkloadReporter.registerMetrics(); <END> hooksHandler.addShutdownHook((s) -> { try { consumerHttpServer.stop(); maxRateSupervisor.stop(); assignmentCache.stop(); oAuthHttpClient.stop(); supervisorController.shutdown(); s.shutdown(); } catch (Exception e) { logger.error("Exception while shutdown Hermes Consumers", e); } }); if (flushLogsShutdownHookEnabled) { hooksHandler.addShutdownHook(new FlushLogsShutdownHook()); } }</code><technical_language>this called in start()</technical_language>

Target:
HermesConsumers(HooksHandler hooksHandler, List<Binder> binders, MultiMap<String, Function<ServiceLocator, ProtocolMessageSenderProvider>> messageSenderProvidersSuppliers, List<Function<ServiceLocator, LogRepository>> logRepositories, boolean flushLogsShutdownHookEnabled) { this.hooksHandler = hooksHandler; this.messageSenderProvidersSuppliers = messageSenderProvidersSuppliers; this.logRepositories = logRepositories; serviceLocator = createDIContainer(binders); trackers = serviceLocator.getService(Trackers.class); consumerHttpServer = serviceLocator.getService(ConsumerHttpServer.class); messageSenderFactory = serviceLocator.getService(MessageSenderFactory.class); consumerNodesRegistry = serviceLocator.getService(ConsumerNodesRegistry.class); supervisorController = serviceLocator.getService(SupervisorController.class); maxRateSupervisor = serviceLocator.getService(MaxRateSupervisor.class); assignmentCache = serviceLocator.getService(ConsumerAssignmentCache.class); oAuthHttpClient = serviceLocator.getService(OAuthClient.class); httpClientsWorkloadReporter = serviceLocator.getService(HttpClientsWorkloadReporter.class); hooksHandler.addShutdownHook((s) -> { try { consumerHttpServer.stop(); maxRateSupervisor.stop(); assignmentCache.stop(); oAuthHttpClient.stop(); consumerNodesRegistry.stop(); supervisorController.shutdown(); s.shutdown(); } catch (Exception e) { logger.error("Exception while shutdown Hermes Consumers", e); } }); if (flushLogsShutdownHookEnabled) { hooksHandler.addShutdownHook(new FlushLogsShutdownHook()); } }
Source:
<code>public void addBasedir(File basedir) throws IOException { if (!basedir.exists()) { log.info("Project does not exist at " + basedir); return; } if (basedir.isFile()) { if (!MutablePomFile.POM_XML.equals(basedir.getName())) { log.info("Custom pom.xml file name is not supported at " + basedir); return; } basedir = basedir.getParentFile(); } if (projects.containsKey(basedir)) { return; } ProjectMetadata project = new ProjectMetadata(basedir); projects.put(basedir, project); File pomFile = new File(basedir, MutablePomFile.POM_XML); if (!pomFile.exists()) { pomFile = new File(basedir, <START> ".polyglot.build.properties"); <END> } if (!pomFile.exists()) { log.info("No pom file found at " + basedir); return; } MutablePomFile pom = MutablePomFile.read(pomFile); project.putMetadata(pom); String packaging = pom.getPackaging(); if (PACKAGING_POM.equals(packaging)) { for (File child : getChildren(basedir, pom)) { addBasedir(child); } } }</code><technical_language>implmentation detail of maven polyglot/tycho-pomless I rahter rely</technical_language>

Target:
public void addBasedir(File basedir) throws IOException { if (!basedir.exists()) { log.info("Project does not exist at " + basedir); return; } if (basedir.isFile()) { if (!PomFile.POM_XML.equals(basedir.getName())) { log.info("Custom pom.xml file name is not supported at " + basedir); return; } basedir = basedir.getParentFile(); } if (projects.containsKey(basedir)) { return; } ProjectMetadata project = new ProjectMetadata(basedir); projects.put(basedir, project); File pomFile = new File(basedir, PomFile.POM_XML); if (!pomFile.exists()) { pomFile = new File(basedir, PomFile.POLYGLOT_POM_XML); } if (!pomFile.exists()) { log.info("No pom file found at " + basedir); return; } PomFile pom = PomFile.read(pomFile, PomFile.POM_XML.equals(pomFile.getName())); project.putMetadata(pom); String packaging = pom.getPackaging(); if (PACKAGING_POM.equals(packaging)) { for (File child : getChildren(basedir, pom)) { addBasedir(child); } } }