auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static <RESPONSE extends PaxosResponse> void cancelOutstandingRequestsAfterTimeout( List<Future<RESPONSE>> responseFutures) { boolean areAllRequestsComplete = Iterables.all(responseFutures, Future::isDone); if (areAllRequestsComplete) { return; } CANCELLATION_EXECUTOR.schedule(() -> { for (Future<?> future : responseFutures) { boolean isCanceled = future.cancel(true); if (isCanceled) { cancelOutstandingRequestSuccess.mark(); } else { cancelOutstandingRequestNoOp.mark(); } } }, OUTSTANDING_REQUEST_CANCELLATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); if (shouldLogCancellationStatus()) { <START> log.debug("Quorum checker canceled pending requests" <END> + ". Rate of successful cancellations: {}, rate of no-op cancellations: {}", SafeArg.of("rateCancelled", cancelOutstandingRequestSuccess.getOneMinuteRate()), SafeArg.of("rateNoOpCancellation", cancelOutstandingRequestNoOp.getOneMinuteRate())); } }</code><technical_language>sense add a log.isDebugEnabled() above? I getOneMinuteRate() is implemented, if is costly avoid calculating if</technical_language>

Target:
private static <RESPONSE extends PaxosResponse> void cancelOutstandingRequestsAfterTimeout( List<Future<RESPONSE>> responseFutures) { boolean areAllRequestsComplete = Iterables.all(responseFutures, Future::isDone); if (areAllRequestsComplete) { return; } CANCELLATION_EXECUTOR.schedule(() -> { for (Future<?> future : responseFutures) { boolean isCanceled = future.cancel(true); if (isCanceled) { cancelOutstandingRequestSuccess.mark(); } else { cancelOutstandingRequestNoOp.mark(); } } }, OUTSTANDING_REQUEST_CANCELLATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); if (log.isDebugEnabled() && shouldLogCancellationStatus()) { log.debug("Quorum checker canceled pending requests" + ". Rate of successful cancellations: {}, rate of no-op cancellations: {}", SafeArg.of("rateCancelled", cancelOutstandingRequestSuccess.getOneMinuteRate()), SafeArg.of("rateNoOpCancellation", cancelOutstandingRequestNoOp.getOneMinuteRate())); } }
Source:
<code>public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); if (e != null && !e.isRemoved()) { Object value = e.getValue(); Object prevValue = e.getValue(); Metadata metadata = e.getMetadata(); if (lifespan == null) { if (valueMatcher.matches(prevValue, value, null)) { e.setExpired(true); return performRemove(e, prevValue, ctx); } } else if (metadata == null || metadata.version() == nonExistentVersion) { if (value == null || valueMatcher.matches(prevValue, value, null)) { e.setExpired(true); return performRemove(e, prevValue, ctx); } } else if (e.getLifespan() > 0 && e.getLifespan() == lifespan) { if (valueMatcher.matches(prevValue, value, null)) { <START> if (ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), timeService.wallClockTime() + 100)) { <END> if (trace) { log.tracef("Removing entry as its lifespan and value match and it created on %s with a current time of %s", e.getCreated(), timeService.wallClockTime()); } e.setExpired(true); return performRemove(e, prevValue, ctx); } else if (trace) { log.tracef("Cannot remove entry due to it not being expired - this can be caused by different " + "clocks on nodes or a concurrent write"); } } } else if (trace) { log.trace("Cannot remove entry as its lifespan or value do not match"); } } else if (trace) { log.trace("Nothing to remove since the entry doesn't exist in the context or it is already removed"); } successful = false; return false; }</code><technical_language>this a constant. Hardcoding is fine, I visibility top of class</technical_language>

Target:
public Object perform(InvocationContext ctx) throws Throwable { MVCCEntry e = (MVCCEntry) ctx.lookupEntry(key); if (e != null && !e.isRemoved()) { Object prevValue = e.getValue(); Metadata metadata = e.getMetadata(); if (lifespan == null) { if (valueMatcher.matches(prevValue, value, null)) { e.setExpired(true); return performRemove(e, prevValue, ctx); } } else if (metadata == null || metadata.version() == nonExistentVersion) { if (value == null || valueMatcher.matches(prevValue, value, null)) { e.setExpired(true); return performRemove(e, prevValue, ctx); } } else if (e.getLifespan() > 0 && e.getLifespan() == lifespan) { if (valueMatcher.matches(prevValue, value, null)) { if (ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), timeService.wallClockTime() + CLOCK_BUFFER)) { if (trace) { log.tracef("Removing entry as its lifespan and value match and it created on %s with a current time of %s", e.getCreated(), timeService.wallClockTime()); } e.setExpired(true); return performRemove(e, prevValue, ctx); } else if (trace) { log.tracef("Cannot remove entry due to it not being expired - this can be caused by different " + "clocks on nodes or a concurrent write"); } } } else if (trace) { log.trace("Cannot remove entry as its lifespan or value do not match"); } } else if (trace) { log.trace("Nothing to remove since the entry doesn't exist in the context or it is already removed"); } successful = false; return false; }
Source:
<code><START> public void decorate(JLabel label) { <END> label.setText("<html><a href=\"" + server.getBaseUrl().toString() + "\">" + getDescription() + "</a></html>"); label.setCursor(getPredefinedCursor(HAND_CURSOR)); label.addMouseListener(new MouseAdapterBuilder() .onClick(__ -> invokeLater(() -> uncheckedBrowse(server.getBaseUrl()))) .build()); }</code><technical_language>decorate is called twice, clicking link creates browser tabs. <img width="651" alt="1" src="<LINK_1>"> <img width="551" alt="2" src="<LINK_0>"></technical_language>

Target:
public void decorate(JLabel label) { label.setText("<html><a href=\"" + server.getBaseUrl().toString() + "\">" + getDescription() + "</a></html>"); label.setCursor(getPredefinedCursor(HAND_CURSOR)); removeAllMouseListeners(label); label.addMouseListener(new MouseAdapterBuilder() .onClick(__ -> invokeLater(() -> uncheckedBrowse(server.getBaseUrl()))) .build()); }
Source:
<code>public void testSlackResponseObject() throws Exception { SlackSendStep.SlackSendStepExecution stepExecution = spy(new SlackSendStep.SlackSendStepExecution()); SlackSendStep slackSendStep = new SlackSendStep("message"); slackSendStep.setToken("token"); slackSendStep.setTokenCredentialId("tokenCredentialId"); slackSendStep.setBotUser(true); slackSendStep.setBaseUrl("baseUrl/"); slackSendStep.setTeamDomain("teamDomain"); slackSendStep.setChannel("channel"); slackSendStep.setColor("good"); stepExecution.step = slackSendStep; when(Jenkins.getActiveInstance()).thenReturn(jenkins); stepExecution.listener = taskListenerMock; when(taskListenerMock.getLogger()).thenReturn(printStreamMock); doNothing().when(printStreamMock).println(); when(stepExecution.getSlackService(anyString(), anyString(), anyString(), anyString(), anyBoolean(), anyString())).thenReturn(slackServiceMock); String savedResponse = IOUtils.toString( this.getClass().getResourceAsStream("response.json") ); when(slackServiceMock.getResponseString()).thenReturn(savedResponse); when(slackServiceMock.publish(anyString(), anyString())).thenReturn(true); SlackResponse response = stepExecution.run(); String expectedId = "F4KE1DABC"; String expectedTs = "1543931401.000500"; assertNotNull(response); assertEquals(expectedId, response.getChannelId()); <START> assertEquals(expectedTs, response.getTs()); <END> }</code><technical_language>more assertion for thread id slack response</technical_language>

Target:
public void testSlackResponseObject() throws Exception { SlackSendStep.SlackSendStepExecution stepExecution = spy(new SlackSendStep.SlackSendStepExecution()); SlackSendStep slackSendStep = new SlackSendStep(); slackSendStep.setMessage("message"); slackSendStep.setToken("token"); slackSendStep.setTokenCredentialId("tokenCredentialId"); slackSendStep.setBotUser(true); slackSendStep.setBaseUrl("baseUrl/"); slackSendStep.setTeamDomain("teamDomain"); slackSendStep.setChannel("channel"); slackSendStep.setColor("good"); stepExecution.step = slackSendStep; when(Jenkins.getActiveInstance()).thenReturn(jenkins); stepExecution.listener = taskListenerMock; when(taskListenerMock.getLogger()).thenReturn(printStreamMock); doNothing().when(printStreamMock).println(); when(stepExecution.getSlackService(anyString(), anyString(), anyString(), anyString(), anyBoolean(), anyString())).thenReturn(slackServiceMock); String savedResponse = IOUtils.toString( this.getClass().getResourceAsStream("response.json") ); when(slackServiceMock.getResponseString()).thenReturn(savedResponse); when(slackServiceMock.publish(anyString(), anyString())).thenReturn(true); SlackResponse response = stepExecution.run(); String expectedId = "F4KE1DABC"; String expectedTs = "1543931401.000500"; String expectedThreadId = "F4KE1DABC:1543931401.000500"; assertNotNull(response); assertEquals(expectedId, response.getChannelId()); assertEquals(expectedTs, response.getTs()); assertEquals(expectedThreadId, response.getThreadId()); }
Source:
<code>private void toggleCartVisibility() { if (shoppingCartOpen) { closeCart(); } else { $(sidePanelContainer).addClass(res.style().rightPanel__open()); $(cartIcon).text("+"); <START> $(cartIcon).removeClass("class", font.icons().iconCart()); <END> $(cartButton).addClass(res.style().active()); shoppingCartOpen = true; } }</code><technical_language>remove argument</technical_language>

Target:
private void toggleCartVisibility() { if (shoppingCartOpen) { closeCart(); } else { openCart(); } }
Source:
<code>private void updateDataModel(){ unitList.clear(); if( selectedUnit == null || selectedUnit.getRoot() == null ) { logger.warn("selectedUnit is null?"); return; } List<CourseComponent> leaves = new ArrayList<>(); PrefManager.UserPrefManager userPrefManager = new PrefManager.UserPrefManager(MainApplication.instance()); EnumSet<BlockType> types = userPrefManager.isUserPrefVideoModel() ? EnumSet.of(BlockType.VIDEO) : EnumSet.allOf(BlockType.class); <START> (selectedUnit.getRoot()).fetchAllLeafComponents(leaves, types); <END> unitList.addAll( leaves ); pagerAdapter.notifyDataSetChanged(); ViewPagerDownloadManager.instance.setMainComponent(selectedUnit, unitList); int index = unitList.indexOf(selectedUnit); if ( index >= 0 ){ pager.setCurrentItem( index ); tryToUpdateForEndOfSequential(); } if ( pagerAdapter != null ) pagerAdapter.notifyDataSetChanged(); }</code><technical_language>get rid of extra parenthesis surrounding selectedUnit.getRoot()</technical_language>

Target:
private void updateDataModel(){ unitList.clear(); if( selectedUnit == null || selectedUnit.getRoot() == null ) { logger.warn("selectedUnit is null?"); return; } List<CourseComponent> leaves = new ArrayList<>(); PrefManager.UserPrefManager userPrefManager = new PrefManager.UserPrefManager(MainApplication.instance()); EnumSet<BlockType> types = userPrefManager.isUserPrefVideoModel() ? EnumSet.of(BlockType.VIDEO) : EnumSet.allOf(BlockType.class); selectedUnit.getRoot().fetchAllLeafComponents(leaves, types); unitList.addAll( leaves ); pagerAdapter.notifyDataSetChanged(); ViewPagerDownloadManager.instance.setMainComponent(selectedUnit, unitList); int index = unitList.indexOf(selectedUnit); if ( index >= 0 ){ pager.setCurrentItem( index ); tryToUpdateForEndOfSequential(); } if ( pagerAdapter != null ) pagerAdapter.notifyDataSetChanged(); }
Source:
<code>public static EditorHandle fetchAndOpen(final IWorkbenchPage page, IBuild build) { final EditorHandle handle = new EditorHandle(); final BuildEditor editor = openEditor(page, handle, build, true); final IBuildPlan plan = build.getPlan(); final String label = build.getLabel(); GetBuildsRequest request = new GetBuildsRequest(build.getPlan(), Collections.singletonList(label), Scope.FULL); GetBuildsOperation operation = BuildsUiInternal.getFactory().getGetBuildsOperation(request); operation.addOperationChangeListener(new OperationChangeListener() { @Override public void done(OperationChangeEvent event) { if (event.getStatus().isOK() && !Display.getDefault().isDisposed()) { final GetBuildsOperation operation = (GetBuildsOperation) event.getOperation(); List<IBuild> builds = operation.getBuilds(); if (builds != null && builds.size() > 0) { final IBuild build2 = builds.get(0); build2.setPlan(plan); build2.setServer(plan.getServer()); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { <START> editor.setBuild(build2); <END> } }); } else { IStatus status = new Status(IStatus.ERROR, BuildsUiPlugin.ID_PLUGIN, NLS.bind( "The requested build ''{0}'' was not found", label)); handle.setStatus(status); } } else { handle.setStatus(event.getStatus()); } } }); operation.execute(); return handle; }</code><technical_language>check for disposal</technical_language>

Target:
public static EditorHandle fetchAndOpen(final IWorkbenchPage page, IBuild build) { final EditorHandle handle = new EditorHandle(); openEditor(page, handle, build, true); final IBuildPlan plan = build.getPlan(); final String label = build.getLabel(); GetBuildsRequest request = new GetBuildsRequest(build.getPlan(), Collections.singletonList(label), Scope.FULL); GetBuildsOperation operation = BuildsUiInternal.getFactory().getGetBuildsOperation(request); operation.addOperationChangeListener(new OperationChangeListener() { @Override public void done(OperationChangeEvent event) { if (event.getStatus().isOK() && !Display.getDefault().isDisposed()) { final GetBuildsOperation operation = (GetBuildsOperation) event.getOperation(); List<IBuild> builds = operation.getBuilds(); if (builds != null && builds.size() > 0) { final IBuild build2 = builds.get(0); build2.setPlan(plan); build2.setServer(plan.getServer()); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { if (handle.getPart() instanceof BuildEditor) { BuildEditor buildEditor = (BuildEditor) handle.getPart(); if (!buildEditor.isDisposed() && !page.getWorkbenchWindow().getShell().isDisposed()) { buildEditor.getEditorInput().setCompleteBuild(build2); buildEditor.refresh(); } } } }); } else { IStatus status = new Status(IStatus.ERROR, BuildsUiPlugin.ID_PLUGIN, NLS.bind( "The requested build ''{0}'' was not found", label)); handle.setStatus(status); } } else { handle.setStatus(event.getStatus()); } } }); operation.execute(); return handle; }
Source:
<code>public void networkNotInUse() throws Exception { <START> networkNotUsedTest(ValidationResult.VALID, new ArrayList<Nameable>()); <END> }</code><technical_language>please replace Collections.<Network> emptyList()</technical_language>

Target:
public void networkNotInUse() throws Exception { networkNotUsedTest(ValidationResult.VALID, Collections.<Nameable> emptyList()); }
Source:
<code>public boolean hasMultipleValues(final String dimension) { if (isVirtualColumn(dimension)) { return virtualColumns.getVirtualColumn(dimension).capabilities(dimension).hasMultipleValues(); } final Column column = index.getColumn(dimension); <START> if (column == null || !columnSupportsFiltering(column)) { <END> return false; } else { return column.getCapabilities().hasMultipleValues(); } }</code><technical_language>question, "column supports filtering" relates "has multiple values"</technical_language>

Target:
public boolean hasMultipleValues(final String dimension) { if (isVirtualColumn(dimension)) { return virtualColumns.getVirtualColumn(dimension).capabilities(dimension).hasMultipleValues(); } final Column column = index.getColumn(dimension); return column != null && column.getCapabilities().hasMultipleValues(); }
Source:
<code>private String getUniqueSynchronizationString(final Message message) { final String triggeringContainer = message.getHeader(MBHeader.TRIGGERINGCONTAINER_STRING.toString(), String.class); final String deploymentLocation = Settings.OPENTOSCA_CONTAINER_HOSTNAME; final QName typeImplementationID = message.getHeader(MBHeader.TYPEIMPLEMENTATIONID_QNAME.toString(), QName.class); final String implementationArtifactName = message.getHeader(MBHeader.IMPLEMENTATIONARTIFACTNAME_STRING.toString(), String.class); if (triggeringContainer != null && deploymentLocation != null && typeImplementationID != null && implementationArtifactName != null) { return triggeringContainer + "/" + deploymentLocation + "/" + typeImplementationID.toString() + "/" + implementationArtifactName; } else { return null; <START> } <END> }</code><technical_language>inverting condition improves readability. Stream.of Collectors.joining('/') simplify return</technical_language>

Target:
private String getUniqueSynchronizationString(final Message message) { final String triggeringContainer = message.getHeader(MBHeader.TRIGGERINGCONTAINER_STRING.toString(), String.class); final String deploymentLocation = Settings.OPENTOSCA_CONTAINER_HOSTNAME; final QName typeImplementationID = message.getHeader(MBHeader.TYPEIMPLEMENTATIONID_QNAME.toString(), QName.class); final String implementationArtifactName = message.getHeader(MBHeader.IMPLEMENTATIONARTIFACTNAME_STRING.toString(), String.class); return ManagementBusServiceImpl.getUniqueSynchronizationString(triggeringContainer, deploymentLocation, typeImplementationID, implementationArtifactName); }
Source:
<code>private static boolean isBuilderSetterMethod(Accessor method) { if ( method.isBuilder() ) { String methodReturnType = method.getExecutable().getReturnType().toString(); String builderType = method.getBuilderType().toString(); <START> return methodReturnType.equals( builderType ); <END> } else { return false; } }</code><technical_language>This work generic builders I think</technical_language>

Target:
private static boolean isBuilderSetterMethod(Accessor method) { if ( method.isBuilder() ) { return !method.getSimpleName().contentEquals( "build" ); } else { return false; } }
Source:
<code>private void listFiles(File directory, List<File> files, String suffix) { if (directory != null) { File[] fList = directory.listFiles(); if (fList != null) { for (File file : fList) { <START> if (suffix != null) { <END> if (file.isFile() && file.getName().toLowerCase().endsWith("." + suffix)) { files.add(file); } else if (file.isDirectory()) { listFiles(file, files, suffix); } } else { if (file.isFile()) { files.add(file); } else if (file.isDirectory()) { listFiles(file, files, suffix); } } } } } }</code><technical_language>replace lines 933 945 of short-circuit evaluation: if (file.isFile() && ((suffix == null) || (file.getName().toLowerCase().endsWith("." + suffix)))) { files.add(file); } else if (file.isDirectory()) { listFiles(file, files, suffix); }</technical_language>

Target:
private void listFiles(File directory, List<File> files, String suffix) { if (directory != null) { File[] fList = directory.listFiles(); if (fList != null) { for (File file : fList) { if (file.isFile() && ((suffix == null) || (file.getName().toLowerCase().endsWith("." + suffix)))) { files.add(file); } else if (file.isDirectory()) { listFiles(file, files, suffix); } } } } }
Source:
<code>public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateSignalEventCatching emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); <START> assertSignalEventExecutionSet(emptyTopEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, ""); <END> assertDataIOSet(emptyTopEvent.getDataIOSet(), EMPTY_VALUE); }</code><technical_language>suggestion assertSignalEventExecutionSet(emptyTopEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, EMPTY_VALUE);</technical_language>

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateSignalEventCatching emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertSignalEventExecutionSet(emptyTopEvent.getExecutionSet(), EMPTY_VALUE, NON_CANCELLING, EMPTY_VALUE); assertDataIOSet(emptyTopEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
<code>public LocalTime getStartTimeForTrips (Collection<Trip> trips) { int earliestDeparture = Integer.MAX_VALUE; for (Trip trip : trips) { StopTime st; try { <START> st = StreamSupport.stream(feed.getInterpolatedStopTimesForTrip(trip.trip_id).spliterator(), false) <END> .findFirst() .orElse(null); } catch (GTFSFeed.FirstAndLastStopsDoNotHaveTimes e) { return null; } if (st.departure_time > 86399) continue; if (st.departure_time <= earliestDeparture) { earliestDeparture = st.departure_time; } } return LocalTime.ofSecondOfDay(earliestDeparture); }</code><technical_language>If stop, interpolated times? illegal for stop times specified</technical_language>

Target:
public LocalTime getStartTimeForTrips (Collection<Trip> trips) { int earliestDeparture = Integer.MAX_VALUE; for (Trip trip : trips) { StopTime st = feed.getOrderedStopTimesForTrip(trip.trip_id).iterator().next(); int dep = st.departure_time; if (dep > 86399) { dep = dep % 86399; } if (dep <= earliestDeparture) { earliestDeparture = dep; } } return LocalTime.ofSecondOfDay(earliestDeparture); }
Source:
<code>public static Message parseMessage(InputStream is) throws IOException, MimeIOException { try { MessageImpl message = new MessageImpl(); MimeConfig cfg = new MimeConfig(); boolean strict = cfg.isStrictParsing(); DecodeMonitor mon = strict ? DecodeMonitor.STRICT : DecodeMonitor.SILENT; BodyDescriptorBuilder bdb = new DefaultBodyDescriptorBuilder(null, strict ? DefaultFieldParser.getParser() : LenientFieldParser.getParser(), mon); BodyFactory bf = new BasicBodyFactory(); MimeStreamParser parser = new MimeStreamParser(cfg, mon, bdb); parser.setContentHandler(new Mime4jWorkaroundBinaryEntityBuilder(message, bf)); parser.setContentDecoding(false); parser.setRecurse(); parser.parse(is); return message; <START> } catch (MimeException e) { <END> throw new MimeIOException(e); } }</code><technical_language>org.apache.james.mime4j.message.DefaultMessageBuilder class, I if a reason for new MimeConfig() instead of MimeConfig.DEFAULT</technical_language>

Target:
public static Message parseMessage(InputStream is) throws IOException, MimeIOException { try { MessageImpl message = new MessageImpl(); MimeConfig cfg = new MimeConfig(); boolean strict = cfg.isStrictParsing(); DecodeMonitor mon = strict ? DecodeMonitor.STRICT : DecodeMonitor.SILENT; BodyDescriptorBuilder bdb = new DefaultBodyDescriptorBuilder(null, strict ? DefaultFieldParser.getParser() : LenientFieldParser.getParser(), mon); StorageProvider storageProvider; if (System.getProperty(DefaultStorageProvider.DEFAULT_STORAGE_PROVIDER_PROPERTY) != null) { storageProvider = DefaultStorageProvider.getInstance(); } else { StorageProvider backend = new CustomTempFileStorageProvider(); storageProvider = new ThresholdStorageProvider(backend, 1024); } BodyFactory bf = new StorageBodyFactory(storageProvider, mon); MimeStreamParser parser = new MimeStreamParser(cfg, mon, bdb); parser.setContentHandler(new Mime4jWorkaroundBinaryEntityBuilder(message, bf)); parser.setContentDecoding(false); parser.setRecurse(); parser.parse(is); return message; } catch (MimeException e) { throw new MimeIOException(e); } }
Source:
<code>public String enqueueGetMbusEncryptionKeyStatusByChannelRequest(final String organisationIdentification, final String deviceIdentification, final int messagePriority, final Long scheduleTime, final short channel) throws FunctionalException { final Organisation organisation = this.domainHelperService.findOrganisation(organisationIdentification); final Device device = this.domainHelperService.findActiveDevice(deviceIdentification); <START> this.domainHelperService.isAllowed(organisation, device, DeviceFunction.GET_MBUS_ENCRYPTION_KEY_STATUS); <END> LOGGER.debug("enqueueGetMbusEncryptionKeyStatusRequest called with organisation and device {}", organisationIdentification, deviceIdentification); final String correlationUid = this.correlationIdProviderService.getCorrelationId(organisationIdentification, deviceIdentification); final DeviceMessageMetadata deviceMessageMetadata = new DeviceMessageMetadata(deviceIdentification, organisationIdentification, correlationUid, SmartMeteringRequestMessageType.GET_MBUS_ENCRYPTION_KEY_STATUS_BY_CHANNEL.toString(), messagePriority, scheduleTime); final SmartMeteringRequestMessage message = new SmartMeteringRequestMessage.Builder() .deviceMessageMetadata(deviceMessageMetadata) .request(new GetMbusEncryptionKeyStatusByChannelRequestData(channel)).build(); this.smartMeteringRequestMessageSender.send(message); return correlationUid; }</code><technical_language>this be: is allowed GET_MBUS_ENCRYPTION_KEY_STATUS_BY_CHANNEL</technical_language>

Target:
public String enqueueGetMbusEncryptionKeyStatusByChannelRequest(final String organisationIdentification, final String deviceIdentification, final int messagePriority, final Long scheduleTime, final short channel) throws FunctionalException { final Organisation organisation = this.domainHelperService.findOrganisation(organisationIdentification); final Device device = this.domainHelperService.findActiveDevice(deviceIdentification); this.domainHelperService.isAllowed(organisation, device, DeviceFunction.GET_MBUS_ENCRYPTION_KEY_STATUS_BY_CHANNEL); LOGGER.debug("enqueueGetMbusEncryptionKeyStatusByChannelRequest called with organisation and device {}", organisationIdentification, deviceIdentification); final String correlationUid = this.correlationIdProviderService.getCorrelationId(organisationIdentification, deviceIdentification); final DeviceMessageMetadata deviceMessageMetadata = new DeviceMessageMetadata(deviceIdentification, organisationIdentification, correlationUid, SmartMeteringRequestMessageType.GET_MBUS_ENCRYPTION_KEY_STATUS_BY_CHANNEL.toString(), messagePriority, scheduleTime); final SmartMeteringRequestMessage message = new SmartMeteringRequestMessage.Builder() .deviceMessageMetadata(deviceMessageMetadata) .request(new GetMbusEncryptionKeyStatusByChannelRequestData(channel)).build(); this.smartMeteringRequestMessageSender.send(message); return correlationUid; }
Source:
<code>public KinesisInputDescriptor<StreamMessageType> withRegion(String region) { <START> this.region = Optional.of(region); <END> return this; }</code><technical_language>Nit: For defensive programming, I prefer String.stripToNull(region); Please update for similar invocations</technical_language>

Target:
public KinesisInputDescriptor<StreamMessageType> withRegion(String region) { this.region = Optional.of(StringUtils.stripToNull(region)); return this; }
Source:
<code>private void startSeekForRange( IndexProgressor.NodeValueClient client, GeometryRangePredicate rangePredicate, IndexQuery[] query ) { try { BridgingIndexProgressor multiProgressor = new BridgingIndexProgressor( client, descriptor.schema().getPropertyIds() ); client.initialize( descriptor, multiProgressor, query ); SpaceFillingCurve curve = spatial.getSpaceFillingCurve(); Envelope completeEnvelope = SpatialKnownIndex.envelopeFromCRS( spatial.crs ); double[] from = rangePredicate.from() == null ? completeEnvelope.getMin() : rangePredicate.from().coordinate(); double[] to = rangePredicate.to() == null ? completeEnvelope.getMax() : rangePredicate.to().coordinate(); Envelope envelope = new Envelope( from, to ); List<SpaceFillingCurve.LongRange> ranges = curve.getTilesIntersectingEnvelope( envelope ); for ( SpaceFillingCurve.LongRange range : ranges ) { KEY treeKeyFrom = layout.newKey(); KEY treeKeyTo = layout.newKey(); treeKeyFrom.fromDerivedValue( Long.MIN_VALUE, range.min ); treeKeyTo.fromDerivedValue( Long.MAX_VALUE, range.max + 1 ); <START> RawCursor<Hit<KEY,VALUE>,IOException> seeker = makeIndexSeeker( treeKeyFrom, treeKeyTo ); <END> IndexProgressor hitProgressor = new NativeHitIndexProgressor<>( seeker, client, openSeekers ); multiProgressor.initialize( descriptor, hitProgressor, query ); } } catch ( IllegalArgumentException e ) { client.initialize( descriptor, IndexProgressor.EMPTY, query ); } catch ( IOException e ) { throw new UncheckedIOException( e ); } }</code><technical_language>range.max Long.MAX_VALUE</technical_language>

Target:
private void startSeekForRange( IndexProgressor.NodeValueClient client, GeometryRangePredicate rangePredicate, IndexQuery[] query ) { try { BridgingIndexProgressor multiProgressor = new BridgingIndexProgressor( client, descriptor.schema().getPropertyIds() ); client.initialize( descriptor, multiProgressor, query ); SpaceFillingCurve curve = spatial.getSpaceFillingCurve(); Envelope completeEnvelope = SpatialKnownIndex.envelopeFromCRS( spatial.crs ); double[] from = rangePredicate.from() == null ? completeEnvelope.getMin() : rangePredicate.from().coordinate(); double[] to = rangePredicate.to() == null ? completeEnvelope.getMax() : rangePredicate.to().coordinate(); Envelope envelope = new Envelope( from, to ); List<SpaceFillingCurve.LongRange> ranges = curve.getTilesIntersectingEnvelope( envelope ); for ( SpaceFillingCurve.LongRange range : ranges ) { KEY treeKeyFrom = layout.newKey(); KEY treeKeyTo = layout.newKey(); treeKeyFrom.fromDerivedValue( Long.MIN_VALUE, range.min ); treeKeyTo.fromDerivedValue( Long.MAX_VALUE, range.max + 1 ); RawCursor<Hit<KEY,VALUE>,IOException> seeker = makeIndexSeeker( treeKeyFrom, treeKeyTo ); IndexProgressor hitProgressor = new SpatialHitIndexProgressor<>( seeker, client, openSeekers ); multiProgressor.initialize( descriptor, hitProgressor, query ); } } catch ( IllegalArgumentException e ) { client.initialize( descriptor, IndexProgressor.EMPTY, query ); } catch ( IOException e ) { throw new UncheckedIOException( e ); } }
Source:
<code>private void listenForMessages() { while (isEnabled.get()) { <START> ReceiveMessageResult receiveMessageResult = <END> amazonSQS.receiveMessage( new ReceiveMessageRequest(this.queueUrl) .withMaxNumberOfMessages(subscription.getMaxNumberOfMessages()) .withVisibilityTimeout(subscription.getVisibilityTimeout()) .withWaitTimeSeconds(subscription.getWaitTimeSeconds()) .withMessageAttributeNames("All")); if (receiveMessageResult.getMessages().isEmpty()) { log.debug("Received no messages for queue {}", queueARN); continue; } receiveMessageResult.getMessages().forEach(this::handleMessage); } }</code><technical_language>need error handling break out of while loop AmazonException</technical_language>

Target:
private void listenForMessages() { while (isEnabled.get()) { ReceiveMessageResult receiveMessageResult = amazonSQS.receiveMessage( new ReceiveMessageRequest(this.subscriptionInfo.queueUrl) .withMaxNumberOfMessages(subscription.getMaxNumberOfMessages()) .withVisibilityTimeout(subscription.getVisibilityTimeout()) .withWaitTimeSeconds(subscription.getWaitTimeSeconds()) .withMessageAttributeNames("All")); if (receiveMessageResult.getMessages().isEmpty()) { log.debug("Received no messages for queue {}", queueARN); continue; } receiveMessageResult.getMessages().forEach(this::handleMessage); } }
Source:
<code>public static int getClientReachableLocalInetAddressCount() { try { Set<InetAddress> validInetAddresses = new HashSet<>(); Enumeration<NetworkInterface> allNetworkInterfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface networkInterface : Collections.list(allNetworkInterfaces)) { for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) { if (inetAddress.isLinkLocalAddress()) { continue; } if (inetAddress.isMulticastAddress()) { <START> continue; <END> } if (inetAddress.isLoopbackAddress()) { continue; } validInetAddresses.add(inetAddress); } } if (LOG.isDebugEnabled()) { LOG.debug("Detected local network addresses", validInetAddresses.size()); LOG.debug("Resolved local addresses are: {}", Arrays.toString(validInetAddresses.toArray())); } return validInetAddresses.size() > 0 ? validInetAddresses.size() : DEFAULT_INET_ADDRESS_COUNT; } catch (SocketException ex) { LOG.warn("Failed to list all network interfaces, assuming 1", ex); return DEFAULT_INET_ADDRESS_COUNT; } }</code><technical_language>If debug...log 'Ignoring inetAddress because...'</technical_language>

Target:
public static int getClientReachableLocalInetAddressCount() { try { Set<InetAddress> validInetAddresses = new HashSet<>(); Enumeration<NetworkInterface> allNetworkInterfaces = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface networkInterface : Collections.list(allNetworkInterfaces)) { for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) { if (inetAddress.isLinkLocalAddress()) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring link-local InetAddress {}", inetAddress); } continue; } if (inetAddress.isMulticastAddress()) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring multicast InetAddress {}", inetAddress); } continue; } if (inetAddress.isLoopbackAddress()) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring loopback InetAddress {}", inetAddress); } continue; } validInetAddresses.add(inetAddress); } } if (LOG.isDebugEnabled()) { LOG.debug("Detected local network addresses", validInetAddresses.size()); LOG.debug("Resolved local addresses are: {}", Arrays.toString(validInetAddresses.toArray())); } return validInetAddresses.size() > 0 ? validInetAddresses.size() : DEFAULT_INET_ADDRESS_COUNT; } catch (SocketException ex) { LOG.warn("Failed to list all network interfaces, assuming 1", ex); return DEFAULT_INET_ADDRESS_COUNT; } }
Source:
<code>private void doButtonPressed(int index) { switch (index) { case IDX_ADD:{ List<String> existing= fFilterListField.getElements(); TypeFilterInputDialog dialog= new TypeFilterInputDialog(getShell(), existing); if (dialog.open() == Window.OK) { String res= (String) dialog.getResult(); fFilterListField.addElement(res); fFilterListField.setChecked(res, true); } } break; case IDX_ADD_PACKAGE: String[] res= choosePackage(); if (res != null) { fFilterListField.addElements(Arrays.asList(res)); for (String re : res) { fFilterListField.setChecked(re, true); } } break; case IDX_EDIT:{ List<String> selected= fFilterListField.getSelectedElements(); if (selected.isEmpty()) { return; } String editedEntry= selected.get(0); List<String> existing= fFilterListField.getElements(); existing.remove(editedEntry); TypeFilterInputDialog dialog= new TypeFilterInputDialog(getShell(), existing); dialog.setInitialString(editedEntry); if (dialog.open() == Window.OK) { fFilterListField.replaceElement(editedEntry, (String) dialog.getResult()); <START> } <END> } break; default: break; } }</code><technical_language>Please remove extraneous space end of line</technical_language>

Target:
private void doButtonPressed(int index) { switch (index) { case IDX_ADD: TypeFilterInputDialog dialog= new TypeFilterInputDialog(getShell(), fFilterListField.getElements()); if (dialog.open() == Window.OK) { String res= (String) dialog.getResult(); fFilterListField.addElement(res); fFilterListField.setChecked(res, true); } break; case IDX_ADD_PACKAGE: String[] res= choosePackage(); if (res != null) { fFilterListField.addElements(Arrays.asList(res)); for (String re : res) { fFilterListField.setChecked(re, true); } } break; case IDX_EDIT: List<String> selected= fFilterListField.getSelectedElements(); if (selected.isEmpty()) { return; } String editedEntry= selected.get(0); List<String> existing= fFilterListField.getElements(); existing.remove(editedEntry); dialog= new TypeFilterInputDialog(getShell(), existing); dialog.setInitialString(editedEntry); if (dialog.open() == Window.OK) { fFilterListField.replaceElement(editedEntry, (String) dialog.getResult()); } break; default: break; } }
Source:
<code>public void testExpressionProfiler() { CallExpression add10Expression = call( internalOperator(ADD, BIGINT.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature())), BIGINT, field(0, BIGINT), constant(10L, BIGINT)); PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0); Supplier<PageProjection> projectionSupplier = functionCompiler.compileProjection(add10Expression, Optional.empty()); PageProjection projection = projectionSupplier.get(); Page page = new Page(createLongSequenceBlock(1, 10)); ExpressionProfiler profiler = new ExpressionProfiler(10, 10_000); for (int i = 0; i < 100; i++) { profiler.start(); Work<Block> work = projection.project(SESSION, new DriverYieldSignal(), page, SelectedPositions.positionsRange(0, page.getPositionCount())); profiler.stop(page.getPositionCount()); work.process(); } assertFalse(profiler.isExpressionExpensive()); <START> <END> profiler = new ExpressionProfiler(10, 0); for (int i = 0; i < 100; i++) { profiler.start(); Work<Block> work = projection.project(SESSION, new DriverYieldSignal(), page, SelectedPositions.positionsRange(0, page.getPositionCount())); profiler.stop(page.getPositionCount()); work.process(); } assertTrue(profiler.isExpressionExpensive()); }</code><technical_language>tighter bounds test. 10 invocations is expensive is switch back</technical_language>

Target:
public void testExpressionProfiler() { CallExpression add10Expression = call( internalOperator(ADD, BIGINT.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature())), BIGINT, field(0, BIGINT), constant(10L, BIGINT)); TestingTicker testingTicker = new TestingTicker(); PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0); Supplier<PageProjection> projectionSupplier = functionCompiler.compileProjection(add10Expression, Optional.empty()); PageProjection projection = projectionSupplier.get(); Page page = new Page(createLongSequenceBlock(1, 11)); ExpressionProfiler profiler = new ExpressionProfiler(testingTicker, SPLIT_RUN_QUANTA); for (int i = 0; i < 100; i++) { profiler.start(); Work<Block> work = projection.project(SESSION, new DriverYieldSignal(), page, SelectedPositions.positionsRange(0, page.getPositionCount())); if (i < 10) { testingTicker.increment(10, SECONDS); profiler.stop(page.getPositionCount()); assertTrue(profiler.isExpressionExpensive()); } else { testingTicker.increment(0, NANOSECONDS); profiler.stop(page.getPositionCount()); assertFalse(profiler.isExpressionExpensive()); } work.process(); } }
Source:
<code>public void createDirectory_returnsFalseWhenCannotCreate() throws IOException, StandardException { String testDir = "/noPermissionToCreateFolderInRoot"; ExportParams exportParams = ExportParams.withDirectory(testDir); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); try { assertFalse(exportFile.createDirectory()); } catch (Exception e) { <START> Assert.assertTrue(e.getMessage(), e.getMessage().contains("IOException '/noPermissionToCreateFolderInRoot' when accessing directory") <END> || e.getMessage().contains("IOException '/noPermissionToCreateFolderInRoot: Read-only file system' when accessing directory")); } assertFalse(new File(testDir).exists()); assertFalse(new File(testDir).isDirectory()); }</code><technical_language>a good case for hamcrest: more concise, more readable out of box comprehensive error message: assertThat(e.getMessage(), anyOf(containsString(strA), containsString(strB)) or, if adventurous: assertThat(e.getMessage(), matchesPattern("IOException '/noPermissionToCreateFolderInRoot(: Read-only file system)+' accessing directory")) need adjustments, a bit rusty patterns</technical_language>

Target:
public void createDirectory_returnsFalseWhenCannotCreate() throws IOException, StandardException { String testDir = "/noPermissionToCreateFolderInRoot"; ExportParams exportParams = ExportParams.withDirectory(testDir); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); try { assertFalse(exportFile.createDirectory()); } catch (Exception e) { assertThat(e.getMessage(), stringContainsInOrder("IOException '/noPermissionToCreateFolderInRoot","' when accessing directory")); } assertFalse(new File(testDir).exists()); assertFalse(new File(testDir).isDirectory()); }
Source:
<code>public void whenReadingEventsTheOrderIsCorrect() throws NakadiException, IOException, InterruptedException { final EventStreamConfig config = EventStreamConfig .builder() .withCursors(ImmutableList.of(new NakadiCursor(TIMELINE, "0", "0"))) .withBatchLimit(1) .withStreamLimit(4) .build(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final int eventNum = 4; final LinkedList<ConsumedEvent> events = new LinkedList<>(IntStream .range(0, eventNum) .boxed() .map(index -> new ConsumedEvent( <START> ("event" + index).getBytes(), new NakadiCursor(TIMELINE, "0", <END> KafkaCursor.toNakadiOffset(index)))) .collect(Collectors.toList())); final EventStream eventStream = new EventStream(predefinedConsumer(events), out, config, mock(BlacklistService.class), cursorConverter, BYTES_FLUSHED_METER); eventStream.streamEvents(new AtomicBoolean(true)); final String[] batches = out.toString().split(BATCH_SEPARATOR); assertThat(batches, arrayWithSize(eventNum)); IntStream .range(0, eventNum) .boxed() .forEach(index -> assertThat( batches[index], sameJSONAs(jsonBatch( "0", KafkaCursor.toNakadiOffset(index), Optional.of(nCopies(1, ("event" + index).getBytes())))) )); }</code><technical_language>UTF-8</technical_language>

Target:
public void whenReadingEventsTheOrderIsCorrect() throws NakadiException, IOException, InterruptedException { final EventStreamConfig config = EventStreamConfig .builder() .withCursors(ImmutableList.of(new NakadiCursor(TIMELINE, "0", "0"))) .withBatchLimit(1) .withStreamLimit(4) .build(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final int eventNum = 4; final LinkedList<ConsumedEvent> events = new LinkedList<>(IntStream .range(0, eventNum) .boxed() .map(index -> new ConsumedEvent( ("event" + index).getBytes(UTF_8), new NakadiCursor(TIMELINE, "0", KafkaCursor.toNakadiOffset(index)))) .collect(Collectors.toList())); final EventStream eventStream = new EventStream(predefinedConsumer(events), out, config, mock(BlacklistService.class), cursorConverter, BYTES_FLUSHED_METER); eventStream.streamEvents(new AtomicBoolean(true)); final String[] batches = out.toString().split(BATCH_SEPARATOR); assertThat(batches, arrayWithSize(eventNum)); IntStream .range(0, eventNum) .boxed() .forEach(index -> assertThat( batches[index], sameJSONAs(jsonBatch( "0", KafkaCursor.toNakadiOffset(index), Optional.of(nCopies(1, ("event" + index).getBytes(UTF_8))))) )); }
Source:
<code>public void configure(MavenAndroidProject mavenProject, IDEAndroidProject eclipseProject, IClasspathDescriptor classpath) { try { IJavaProject javaproject = JavaCore.create(eclipseProject.getProject()); IClasspathEntry[] tosort = javaproject.readRawClasspath(); IClasspathEntry[] sorted = sortClasspath(mavenProject, tosort); <START> javaproject.setRawClasspath(sorted, new NullProgressMonitor()); <END> javaproject.save(new NullProgressMonitor(), false); } catch (JavaModelException e) { throw new ProjectConfigurationException("error re-ordering classpath", e); } }</code><technical_language>I this is good approach. modify IClasspathDescriptor here. m2e persist contents</technical_language>

Target:
public void configure(MavenAndroidProject mavenProject, IDEAndroidProject eclipseProject, IClasspathDescriptor classpath) { try { IJavaProject javaproject = JavaCore.create(eclipseProject.getProject()); IClasspathEntry[] tosort = javaproject.readRawClasspath(); sort(tosort, bySourceFolderOrdering(mavenProject)); javaproject.setRawClasspath(tosort, new NullProgressMonitor()); javaproject.save(new NullProgressMonitor(), false); } catch (JavaModelException e) { throw new ProjectConfigurationException("error re-ordering classpath", e); } }
Source:
<code>private static boolean isVideoTag(TagNode node) { <START> return "VIDEO".equalsIgnoreCase(node.getNodeName()); <END> }</code><technical_language>please node.equalsElementName cover usage of local name well</technical_language>

Target:
private static boolean isVideoTag(TagNode node) { return node.equalsElementName("VIDEO"); }
Source:
<code><START> public static SsoMethod map(Sso model, SsoMethod template) { <END> if (model != null && model.getMethods() != null && model.getMethods().getMethod() != null && model.getMethods().getMethod().size() == 1) { if (model.getMethods().getMethod().get(0) == org.ovirt.engine.api.model.SsoMethod.GUEST_AGENT) { return SsoMethod.GUEST_AGENT; } } return SsoMethod.NONE; }</code><technical_language>In order preserve compatibility need if <sso> element provided VM is assigned GEST_AGENT method. adding updating VMs <sso> element SSO mechanism effectively disabled. Please verify adding VM <sso> tag is creates GUEST_AGENT method. for update</technical_language>

Target:
public static SsoMethod map(Sso model, SsoMethod template) { if (model != null && model.getMethods() != null && model.getMethods().getMethods() != null && model.getMethods().getMethods().size() == 0) { return SsoMethod.NONE; } return SsoMethod.GUEST_AGENT; }
Source:
<code>private View.OnClickListener onClickActionSolver(final OnClickAction action) { return new View.OnClickListener() { @Override public void onClick(View v) { switch (action) { case SET_URL: ((LoginActivity) getActivity()).setUrl(CustomFragmentDialog.this.mEditText.getText().toString().trim()); dismiss(); break; case DISMISS_URL_DIALOG: ((LoginActivity) getActivity()).hideURLDialog(); dismiss(); break; case LOGIN: ((LoginActivity) getActivity()).login(); dismiss(); break; case DISMISS: dismiss(); break; case LOGOUT: ((ACBaseActivity) getActivity()).logout(); dismiss(); break; case FINISH: getActivity().moveTaskToBack(true); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); break; case INTERNET: getActivity().startActivity(new Intent(Settings.ACTION_SETTINGS)); dismiss(); break; case UNAUTHORIZED: ((ACBaseActivity) getActivity()).moveUnauthorizedUserToLoginScreen(); dismiss(); break; case END_VISIT: ((VisitDashboardActivity) getActivity()).endVisit(); dismiss(); break; case START_VISIT: doStartVisitAction(); dismiss(); break; case REGISTER_PATIENT: <START> ((RegisterPatientActivity) getActivity()).mPresenter.confirm(); <END> dismiss(); break; case CANCEL_REGISTERING: ((RegisterPatientActivity) getActivity()).mPresenter.finishRegisterActivity(); dismiss(); break; default: break; } } }; }</code><technical_language>of this able register new patient. dialog similar patient is shown clicking register new button</technical_language>

Target:
private View.OnClickListener onClickActionSolver(final OnClickAction action) { return new View.OnClickListener() { @Override public void onClick(View v) { switch (action) { case SET_URL: ((LoginActivity) getActivity()).setUrl(CustomFragmentDialog.this.mEditText.getText().toString().trim()); dismiss(); break; case DISMISS_URL_DIALOG: ((LoginActivity) getActivity()).hideURLDialog(); dismiss(); break; case LOGIN: ((LoginActivity) getActivity()).login(); dismiss(); break; case DISMISS: dismiss(); break; case LOGOUT: ((ACBaseActivity) getActivity()).logout(); dismiss(); break; case FINISH: getActivity().moveTaskToBack(true); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); break; case INTERNET: getActivity().startActivity(new Intent(Settings.ACTION_SETTINGS)); dismiss(); break; case UNAUTHORIZED: ((ACBaseActivity) getActivity()).moveUnauthorizedUserToLoginScreen(); dismiss(); break; case END_VISIT: ((VisitDashboardActivity) getActivity()).endVisit(); dismiss(); break; case START_VISIT: doStartVisitAction(); dismiss(); break; case REGISTER_PATIENT: ((RegisterPatientActivity) getActivity()).mPresenter.registerPatient(); dismiss(); break; case CANCEL_REGISTERING: ((RegisterPatientActivity) getActivity()).mPresenter.finishRegisterActivity(); dismiss(); break; default: break; } } }; }