auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
PluginInfo(Plugin p) { id = Url.encode(p.getName()); version = p.getVersion(); disabled = p.isDisabled() ? true : null; if (p.getJarFile() != null) { indexUrl = String.format("plugins/%s/", p.getName()); try { adminUrl = p.getJarFile().getManifest().getMainAttributes().getValue("Gerrit-AdminUrl"); } catch (IOException e) { log.error(String.format("Failed to read admin URL from plugin '%s'.", p.getName()), e); } } }

Target:
PluginInfo(Plugin p) { id = Url.encode(p.getName()); version = p.getVersion(); disabled = p.isDisabled() ? true : null; if (p.getJarFile() != null) { indexUrl = String.format("plugins/%s/", p.getName()); } }
Source:
public void testValidationMetaModelsVSM() { TransactionalEditingDomain editingDomain = new TransactionalEditingDomainImpl(new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE), modeler.eResource().getResourceSet()); CommandStack commandStack = editingDomain.getCommandStack(); RepresentationDescription repDescription = modeler.getOwnedViewpoints().iterator().next().getOwnedRepresentations().iterator().next(); EList<EPackage> metamodel = repDescription.getMetamodel(); Command removeMMCommand = RemoveCommand.create(editingDomain, repDescription, DescriptionPackage.Literals.REPRESENTATION_DESCRIPTION__METAMODEL, metamodel); assertTrue(removeMMCommand.canExecute()); commandStack.execute(removeMMCommand); Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(repDescription); assertEquals("The RepresentationDescription should have a warning because there is no meta-models on RepresentationDescription", Diagnostic.WARNING, diagnostic.getSeverity()); }

Target:
public void testValidationMetaModelsVSM() { editingDomain = new TransactionalEditingDomainImpl(new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE), modeler.eResource().getResourceSet()); CommandStack commandStack = editingDomain.getCommandStack(); RepresentationDescription repDescription = modeler.getOwnedViewpoints().iterator().next().getOwnedRepresentations().iterator().next(); EList<EPackage> metamodel = repDescription.getMetamodel(); Command removeMMCommand = RemoveCommand.create(editingDomain, repDescription, DescriptionPackage.Literals.REPRESENTATION_DESCRIPTION__METAMODEL, metamodel); assertTrue(removeMMCommand.canExecute()); commandStack.execute(removeMMCommand); Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(repDescription); List<Diagnostic> children = diagnostic.getChildren(); String message = "Bad diagnostic {0} on the RepresentationDescription " + repDescription.getName(); assertEquals(MessageFormat.format(message, "number"), 1, children.size()); assertEquals(MessageFormat.format(message, "type"), Diagnostic.WARNING, diagnostic.getSeverity()); assertEquals(MessageFormat.format(message, "message"), Messages.RepresentationDescriptionMetaModelsConstraint_noMetaModel, children.get(0).getMessage()); }
Source:
public void testValidModifiedBondsFailsWhenBondNotHaveNameAndId() throws Exception { doTestValidModifiedBonds(new Bond(), ValidationResult.VALID, new ValidationResult(EngineMessage.HOST_NETWORK_INTERFACE_DOES_NOT_HAVE_NAME_SET), ValidationResult.VALID); }

Target:
public void testValidModifiedBondsFailsWhenBondNotHaveNameAndId() throws Exception { doTestValidModifiedBonds(new Bond(), ValidationResult.VALID, new ValidationResult(EngineMessage.BOND_DOES_NOT_HAVE_NEITHER_ID_NOR_NAME_SPECIFIED), ValidationResult.VALID); }
Source:
private Point getStartPoint(BufferedImage patternImage, boolean isLeft) { return isLeft ? new Point(articleLeftSideX - patternImage.getWidth(), startSkinY) : new Point(articleRightSideX, startSkinY); }

Target:
private Point getStartPoint(BufferedImage patternImage, boolean isLeft) { if (isLeft) { return new Point(articleLeftSideX - patternImage.getWidth(), startSkinY); } else { return new Point(articleRightSideX, startSkinY); } }
Source:
private void testBlobRecordV2(int blobSize, BlobType blobType) throws IOException, MessageFormatException { ByteBuffer blobContent = ByteBuffer.allocate(blobSize); new Random().nextBytes(blobContent.array()); int size = (int) MessageFormatRecord.Blob_Format_V2.getBlobRecordSize(blobSize); ByteBuffer entireBlob = ByteBuffer.allocate((int) size); BlobOutput outputData = getBlobRecordV2(blobSize, blobType, blobContent, entireBlob); Assert.assertEquals(outputData.getSize(), blobSize); byte[] verify = new byte[blobSize]; outputData.getStream().read(verify); Assert.assertArrayEquals(verify, blobContent.array()); entireBlob.flip(); byte currentRandomByte = entireBlob.get(16); entireBlob.put(16, (byte) (currentRandomByte + 1)); try { MessageFormatRecord.deserializeBlob(new ByteBufferInputStream(entireBlob)); Assert.fail("Failed to dedect corruption of blob record"); } catch (MessageFormatException e) { Assert.assertEquals(e.getErrorCode(), MessageFormatErrorCodes.Data_Corrupt); } }

Target:
private void testBlobRecordV2(int blobSize, BlobType blobType) throws IOException, MessageFormatException { ByteBuffer blobContent = ByteBuffer.allocate(blobSize); new Random().nextBytes(blobContent.array()); int size = (int) MessageFormatRecord.Blob_Format_V2.getBlobRecordSize(blobSize); ByteBuffer entireBlob = ByteBuffer.allocate(size); BlobData blobData = getBlobRecordV2(blobSize, blobType, blobContent, entireBlob); Assert.assertEquals("Blob size mismatch", blobSize, blobData.getSize()); byte[] verify = new byte[blobSize]; blobData.getStream().read(verify); Assert.assertArrayEquals("BlobContent mismatch", blobContent.array(), verify); entireBlob.flip(); byte savedByte = entireBlob.get(blobSize / 2); entireBlob.put(blobSize / 2, (byte) (savedByte + 1)); try { MessageFormatRecord.deserializeBlob(new ByteBufferInputStream(entireBlob)); Assert.fail("Failed to detect corruption of blob record"); } catch (MessageFormatException e) { Assert.assertEquals("Error code mismatch", MessageFormatErrorCodes.Data_Corrupt, e.getErrorCode()); } }
Source:
public static Set<String> initRange(String start, String end) { String parsedRangeStart = parseRangePart(start); String parsedRangeEnd = parseRangePart(end); if (parsedRangeEnd == null || parsedRangeStart == null) { return Collections.emptySet(); } long startNum = Long.parseLong(parseRangePart(start), HEX_RADIX); long endNum = Long.parseLong(parseRangePart(end), HEX_RADIX); if (startNum > endNum) { return Collections.emptySet(); } Set<String> macAddresses = new HashSet<String>(); for (long i = startNum; i <= endNum; i++) { String value = String.format("%x", i); if (value.length() > 12) { return macAddresses; } else if (value.length() < 12) { value = StringUtils.leftPad(value, 12, '0'); } value = createMacAddress(value); if (value == null) { break; } macAddresses.add(value); } return macAddresses; }

Target:
public static List<String> initRange(String start, String end) { String parsedRangeStart = StringUtils.remove(start, ':'); String parsedRangeEnd = StringUtils.remove(end, ':'); if (parsedRangeEnd == null || parsedRangeStart == null) { return Collections.emptyList(); } long startNum = Long.parseLong(parsedRangeStart, HEX_RADIX); long endNum = Long.parseLong(parsedRangeEnd, HEX_RADIX); if (startNum > endNum) { return Collections.emptyList(); } List<String> macAddresses = new ArrayList<String>(); for (long i = startNum; i <= endNum; i++) { if ((MAC_ADDRESS_MULTICAST_BIT & i) != 0) { continue; } String value = String.format("%012x", i); macAddresses.add(StringUtils.join(value.split(".."), ':')); } return macAddresses; }
Source:
public void setup() throws Exception { System.setProperty(CARBON_HOME, ""); PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class); PowerMockito.mockStatic(PrivilegedCarbonContext.class); PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext); }

Target:
public void setup() throws Exception { System.setProperty(CARBON_HOME, ""); privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class); subscriptionDataHolder = Mockito.mock(SubscriptionDataHolder.class); tenantSubscriptionStore = Mockito.mock(SubscriptionDataStore.class); PowerMockito.mockStatic(PrivilegedCarbonContext.class); PowerMockito.mockStatic(SubscriptionDataHolder.class); PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext); }
Source:
public double getProducerMetricValue(MetricName metricName) { Producer<?, ?> producer = _kafkaProducer; if (producer != null) { Metric metric = producer.metrics().get(metricName); if (metric != null) { return metric.value(); } } return 0; }

Target:
public Optional<Double> getProducerMetricValue(MetricName metricName) { return Optional.ofNullable(_kafkaProducer).map(p -> p.metrics().get(metricName)).map(Metric::value); }
Source:
private void subscribeDataChange(String path, NotificationContext.Type callbackType) { if (callbackType == NotificationContext.Type.INIT || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug("{} subscribe data-change. path: {}, listener: {}", _manager.getInstanceName(), path, _listener); } boolean subStatus = _zkClient.subscribeDataChanges(path, this, callbackType != Type.INIT); logger.debug("CallbackHandler subscribe data path result {}", this, path, subStatus); if (!subStatus) { logger.info("CallbackHandler subscribe data path failed!", this, path); } } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info("{} unsubscribe data-change. path: {}, listener: {}", _manager.getInstanceName(), path, _listener); _zkClient.unsubscribeDataChanges(path, this); } }

Target:
private void subscribeDataChange(String path, NotificationContext.Type callbackType) { if (callbackType == NotificationContext.Type.INIT || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug("CallbackHandler {}, subscribe data-change. path: {}, listener: {}", _uid, _manager.getInstanceName(), path, _listener); } boolean subStatus = _zkClient.subscribeDataChanges(path, this, callbackType != Type.INIT); logger.debug("CallbackHandler subscribe data path result {}", _uid, path, subStatus); if (!subStatus) { logger.info("CallbackHandler subscribe data path failed!", _uid, path); } } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info("CallbackHandler{}, unsubscribe data-change. path: {}, listener: {}", _uid, _manager.getInstanceName(), path, _listener); _zkClient.unsubscribeDataChanges(path, this); } }
Source:
public Execution onRegion(Region region) { if (region == null) { throw new FunctionException("Region instance passed is null"); } if (region.getAttributes() == null) { ((LocalRegion) region).getCancelCriterion().checkCancelInProgress(); throw new FunctionException("Region attributes is null"); } ProxyCache proxyCache = null; String poolName = region.getAttributes().getPoolName(); if (poolName != null) { Pool pool = findPool(poolName); if (pool == null) { throw new IllegalStateException(String.format("Could not find a pool named %s.", poolName)); } else { if (pool.getMultiuserAuthentication()) { if (region instanceof ProxyRegion) { ProxyRegion proxyRegion = (ProxyRegion) region; region = proxyRegion.getRealRegion(); proxyCache = proxyRegion.getAuthenticatedCache(); } else { throw new UnsupportedOperationException(); } } } } if (isClientRegion(region)) { return new ServerRegionFunctionExecutor(region, proxyCache); } if (PartitionRegionHelper.isPartitionedRegion(region)) { return new PartitionedRegionFunctionExecutor(region); } return new DistributedRegionFunctionExecutor(region); }

Target:
public Execution onRegion(Region region) { if (region == null) { throw new FunctionException("Region instance passed is null"); } if (region.isDestroyed()) { throw new FunctionException("Region is destroyed"); } ProxyCache proxyCache = null; String poolName = region.getAttributes().getPoolName(); if (poolName != null) { Pool pool = findPool(poolName); if (pool == null) { throw new IllegalStateException(String.format("Could not find a pool named %s.", poolName)); } else { if (pool.getMultiuserAuthentication()) { if (region instanceof ProxyRegion) { ProxyRegion proxyRegion = (ProxyRegion) region; region = proxyRegion.getRealRegion(); proxyCache = proxyRegion.getAuthenticatedCache(); } else { throw new UnsupportedOperationException(); } } } } if (isClientRegion(region)) { return new ServerRegionFunctionExecutor(region, proxyCache); } if (PartitionRegionHelper.isPartitionedRegion(region)) { return new PartitionedRegionFunctionExecutor(region); } return new DistributedRegionFunctionExecutor(region); }
Source:
public void init(ICommonContentExtensionSite aConfig) { super.init(aConfig); this.model = new NestedProjectsProblemsModel(); this.refreshModelJob = refreshSeverities(); refreshSeveritiesOnProblemMarkerChange = event -> { if (event.getDelta() == null) { return; } MarkerManager markerManager = ((Workspace) WorkbenchNavigatorPlugin.getWorkspace()).getMarkerManager(); try { event.getDelta().accept(delta -> { IMarkerDelta[] markerDeltas = delta.getMarkerDeltas(); for (IMarkerDelta markerDelta : markerDeltas) { if (markerManager.isSubtype(markerDelta.getType(), IMarker.PROBLEM)) { model.markDirty(Collections.singleton(markerDelta.getResource())); } } return true; }); } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); } if (model.isDirty()) { this.refreshModelJob = refreshSeverities(); this.refreshModelJob.thenAccept(model -> { for (StructuredViewer viewer : viewersToUpdate) { viewer.update(model.getResourcesWithModifiedSeverity().toArray(), new String[] {}); } }); } }; WorkbenchNavigatorPlugin.getWorkspace().addResourceChangeListener(refreshSeveritiesOnProblemMarkerChange); }

Target:
public void init(ICommonContentExtensionSite aConfig) { super.init(aConfig); this.model = new NestedProjectsProblemsModel(); this.refreshModelJob = refreshSeverities(); refreshSeveritiesOnProblemMarkerChange = event -> { if (event.getDelta() == null) { return; } MarkerManager markerManager = ((Workspace) WorkbenchNavigatorPlugin.getWorkspace()).getMarkerManager(); try { event.getDelta().accept(delta -> { IMarkerDelta[] markerDeltas = delta.getMarkerDeltas(); for (IMarkerDelta markerDelta : markerDeltas) { if (markerManager.isSubtype(markerDelta.getType(), IMarker.PROBLEM)) { IResource resource = markerDelta.getResource(); if (resource != null) { model.markDirty(Collections.singleton(markerDelta.getResource())); } } } return true; }); } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); } if (model.isDirty()) { this.refreshModelJob = refreshSeverities(); this.refreshModelJob.thenAccept(model -> { Object[] toUpdate = model.getResourcesWithModifiedSeverity().toArray(); for (StructuredViewer viewer : viewersToUpdate) { viewer.update(toUpdate, new String[] {}); } }); } }; WorkbenchNavigatorPlugin.getWorkspace().addResourceChangeListener(refreshSeveritiesOnProblemMarkerChange); }
Source:
public void logsOnlyOnceEvenIfManyRequestsAreSlow() { makeOperationsTakeSpecifiedDuration(LONG_DURATION); for (int i = 0; i < 100; i++) { profilingTimelockService.lockImmutableTimestamp(); } makeOperationsTakeSpecifiedDuration(SHORT_DURATION); allowLogging(); profilingTimelockService.startIdentifiedAtlasDbTransaction(); verifyLoggerInvokedWithSpecificProfile("lockImmutableTimestamp", LONG_DURATION); verifyNoMoreInteractions(logger); }

Target:
public void logsOnlyOnceEvenIfManyRequestsAreSlow() { for (int i = 0; i < 100; i++) { accumulateLogsWithCall(LONG_DURATION, profilingTimelockService::lockImmutableTimestamp); } flushLogsWithCall(SHORT_DURATION, profilingTimelockService::startIdentifiedAtlasDbTransaction); verifyLoggerInvokedOnceWithSpecificProfile("lockImmutableTimestamp", LONG_DURATION); verifyNoMoreInteractions(logger); }
Source:
public Stream<BooleanResult> nodeManualIndexExists( @Name( "indexName" ) String legacyIndexName ) { BooleanResult result = new BooleanResult( graphDatabaseAPI.index().existsForNodes( legacyIndexName ) ); ArrayList<BooleanResult> arrayResult = new ArrayList<>(); arrayResult.add( result ); return arrayResult.stream(); }

Target:
public Stream<BooleanResult> nodeManualIndexExists( @Name( "indexName" ) String legacyIndexName ) { return Stream.of( new BooleanResult( graphDatabaseAPI.index().existsForNodes( legacyIndexName ) ) ); }
Source:
public void testGitHubAppEndpoints() throws Exception { CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); service = client.upsertServiceVersion(serviceRepo, "1.0", installationId); assertNotNull(service); assertEquals("Should have a new version", 1, service.getWorkflowVersions().size()); assertEquals("Should have 3 source files", 3, service.getWorkflowVersions().get(0).getSourceFiles().size()); service = client.addService(serviceRepo, "DockstoreTestUser2", installationId); assertNotNull(service); assertEquals("Should have 2 users, has " + service.getUsers().size(), service.getUsers().size(), 2); }

Target:
public void testGitHubAppEndpoints() throws Exception { final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); service = client.upsertServiceVersion(serviceRepo, "DockstoreTestUser2", "1.0", installationId); assertNotNull(service); assertEquals("Should have a new version", 1, service.getWorkflowVersions().size()); assertEquals("Should have 3 source files", 3, service.getWorkflowVersions().get(0).getSourceFiles().size()); assertEquals("Should have 2 users", 2, service.getUsers().size()); final long count = testingPostgres .runSelectStatement("select count(*) from service where sourcecontrol = 'github.com' and organization = 'DockstoreTestUser2' and repository = 'test-service'", new ScalarHandler<>()); Assert.assertEquals("there should be one matching service", 1, count); }
Source:
public void setLeaderEventPublisher(LeaderEventPublisher leaderEventPublisher) { Assert.notNull(leaderEventPublisher); this.leaderEventPublisher = leaderEventPublisher; }

Target:
public void setLeaderEventPublisher(LeaderEventPublisher leaderEventPublisher) { Assert.notNull(leaderEventPublisher, "leaderEventPublisher cannot be null"); this.leaderEventPublisher = leaderEventPublisher; }
Source:
public DynamoDbDatastoreDialog(final WindowContext windowContext, final MutableDatastoreCatalog catalog, @Nullable final DynamoDbDatastore originalDatastore, final UserPreferences userPreferences) { super(originalDatastore, catalog, windowContext, userPreferences); _regionField = new DCComboBox<>(Regions.values()); _regionField.setSelectedItem(Regions.DEFAULT_REGION); _accessKeyField = WidgetFactory.createTextField(); _accessSecretField = WidgetFactory.createPasswordField(); _accessKeyField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); _accessSecretField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); if (originalDatastore == null) { _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, null); } else { _datastoreNameTextField.setText(originalDatastore.getName()); _datastoreNameTextField.setEnabled(false); _accessKeyField.setText(originalDatastore.getAccessKey()); _accessSecretField.setText(originalDatastore.getAccessSecret()); final String originalRegion = originalDatastore.getRegion(); try { final Regions region = Regions.fromName(originalRegion); _regionField.setSelectedItem(region); } catch (IllegalArgumentException e) { } _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, originalDatastore.getTableDefs()); } }

Target:
public DynamoDbDatastoreDialog(final WindowContext windowContext, final MutableDatastoreCatalog catalog, @Nullable final DynamoDbDatastore originalDatastore, final UserPreferences userPreferences) { super(originalDatastore, catalog, windowContext, userPreferences); _regionField = new DCComboBox<>(Regions.values()); _regionField.setSelectedItem(Regions.DEFAULT_REGION); _accessKeyIdField = WidgetFactory.createTextField(); _secretAccessKeyField = WidgetFactory.createPasswordField(); _accessKeyIdField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); _secretAccessKeyField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); if (originalDatastore == null) { _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, null); } else { _datastoreNameTextField.setText(originalDatastore.getName()); _datastoreNameTextField.setEnabled(false); _accessKeyIdField.setText(originalDatastore.getAccessKeyId()); _secretAccessKeyField.setText(originalDatastore.getSecretAccessKey()); final String originalRegion = originalDatastore.getRegion(); try { final Regions region = Regions.fromName(originalRegion); _regionField.setSelectedItem(region); } catch (IllegalArgumentException e) { } _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, originalDatastore.getTableDefs()); } }
Source:
public Object executeScript(ScriptSource scriptSource, Map<String, Object> variables) { Object result = null; try { if (variables != null) { for (Entry<String, Object> entry : variables.entrySet()) { scriptEngine.put(entry.getKey(), entry.getValue()); } } scriptSource.isModified(); String script = scriptSource.getScriptAsString(); Date start = new Date(); if (logger.isDebugEnabled()) { logger.debug("executing script: " + script); } result = scriptEngine.eval(script); result = postProcess(result, scriptEngine, script); if (logger.isDebugEnabled()) { logger.debug("script executed in " + (new Date().getTime() - start.getTime()) + " ms"); } } catch (Exception e) { throw new ScriptingException(e.getMessage(), e); } return result; }

Target:
public Object executeScript(ScriptSource scriptSource, Map<String, Object> variables) { Object result = null; try { if (variables != null) { for (Entry<String, Object> entry : variables.entrySet()) { scriptEngine.put(entry.getKey(), entry.getValue()); } } String script = scriptSource.getScriptAsString(); Date start = new Date(); if (logger.isDebugEnabled()) { logger.debug("executing script: " + script); } result = scriptEngine.eval(script); result = postProcess(result, scriptEngine, script); if (logger.isDebugEnabled()) { logger.debug("script executed in " + (new Date().getTime() - start.getTime()) + " ms"); } } catch (Exception e) { throw new ScriptingException(e.getMessage(), e); } return result; }
Source:
private static boolean isZeroDimension(ArrayDimensionTree dim) { ExpressionTree expression = dim.expression(); return expression == null || (expression.is(Tree.Kind.INT_LITERAL) && "0".equals(((LiteralTree) expression).value())); }

Target:
private static boolean isZeroDimension(ArrayDimensionTree dim) { ExpressionTree expression = dim.expression(); return expression != null && expression.is(Tree.Kind.INT_LITERAL) && "0".equals(((LiteralTree) expression).value()); }
Source:
public Team update(Long teamId, TeamDTO input) { Team current = this.getTeamById(teamId).get(); current.setTeamName(input.getTeamName()); User captian = userService.getUserById(input.getCaptainID()).get(); current.setCaptain(captian); return teamRepository.saveAndFlush(current); }

Target:
public Team update(Long teamId, TeamDTO input) { Team current = this.getTeamById(teamId).get(); current.setTeamName(input.getTeamName()); User captain = userService.getUserById(input.getCaptainID()).get(); current.setCaptain(captain); return teamRepository.saveAndFlush(current); }
Source:
private Function<Void, CompletionStage<Void>> bootstrap( List<CompletableFuture<?>> toCancelFutures, KubernetesMachineImpl machine) { final Span activeSpan = tracerUtil.getActiveSpan(); return ignored -> { Span tracingSpan = tracerUtil.buildSpan( "BootstrapInstallers", activeSpan, getContext().getIdentity().getWorkspaceId(), machine.getName()); final InternalMachineConfig machineConfig = getContext().getEnvironment().getMachines().get(machine.getName()); LOG.debug( "Bootstrapping machine '{}' in workspace '{}'", machine.getName(), getContext().getIdentity().getWorkspaceId()); final CompletableFuture<Void> bootstrapperFuture; if (!machineConfig.getInstallers().isEmpty()) { bootstrapperFuture = bootstrapperFactory .create( getContext().getIdentity(), machineConfig.getInstallers(), machine, namespace, startSynchronizer) .bootstrapAsync(); bootstrapperFuture.whenComplete((res, ex) -> tracerUtil.finishSpan(tracingSpan)); toCancelFutures.add(bootstrapperFuture); } else { bootstrapperFuture = CompletableFuture.completedFuture(null); } return bootstrapperFuture; }; }

Target:
private Function<Void, CompletionStage<Void>> bootstrap( List<CompletableFuture<?>> toCancelFutures, KubernetesMachineImpl machine) { final Span activeSpan = tracerUtil.getActiveSpan(); return ignored -> { Span tracingSpan = tracerUtil.buildSpan( "BootstrapInstallers", activeSpan, getContext().getIdentity().getWorkspaceId(), machine.getName()); final InternalMachineConfig machineConfig = getContext().getEnvironment().getMachines().get(machine.getName()); LOG.debug( "Bootstrapping machine '{}' in workspace '{}'", machine.getName(), getContext().getIdentity().getWorkspaceId()); final CompletableFuture<Void> bootstrapperFuture; if (!machineConfig.getInstallers().isEmpty()) { bootstrapperFuture = bootstrapperFactory .create( getContext().getIdentity(), machineConfig.getInstallers(), machine, namespace, startSynchronizer) .bootstrapAsync(); bootstrapperFuture.whenComplete( (res, ex) -> { if (ex != null) { tracerUtil.finishSpanAsFailure(tracingSpan, ex.getMessage()); } else { tracerUtil.finishSpan(tracingSpan); } }); toCancelFutures.add(bootstrapperFuture); } else { bootstrapperFuture = CompletableFuture.completedFuture(null); } return bootstrapperFuture; }; }
Source:
public long getWrittenPositions() { return operatorSummaries.stream() .filter(stats -> stats.getOperatorType().equals(TableWriterOperator.class.getSimpleName())) .map(stats -> stats.getInputPositions()) .reduce(0L, Long::sum); }

Target:
public long getWrittenPositions() { return operatorSummaries.stream() .filter(stats -> stats.getOperatorType().equals(TableWriterOperator.class.getSimpleName())) .mapToLong(stats -> stats.getInputPositions()) .sum(); }
Source:
private FieldValueCounter getOrCreate(String name) { synchronized (map) { FieldValueCounter result = findOne(name); if (result == null) { result = create(name); result = save(result); } return result; } }

Target:
private FieldValueCounter getOrCreate(String name) { FieldValueCounter result = findOne(name); if (result == null) { synchronized (map) { result = create(name); } result = save(result); } return result; }
Source:
private String getFileContents(String filename) throws FileNotFoundException, IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new FileReader(filename)); try { String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } } finally { br.close(); } return sb.toString(); }

Target:
private String getFileContents(String filename) throws IOException { Path filePath = Paths.get(filename); return Files.lines(filePath).collect(Collectors.joining(System.lineSeparator())); }
Source:
public LocalPageStore(LocalPageStoreOptions options) { mRoot = options.getRootDir(); mPageSize = options.getPageSize(); mCacheSize = options.getCacheSize(); mFileBuckets = options.getFileBuckets(); mPagePattern = Pattern.compile( String.format("%s/%d/(\\d+)/([^/]+)/(\\d+)", Pattern.quote(mRoot), mPageSize)); }

Target:
public LocalPageStore(LocalPageStoreOptions options) { mRoot = options.getRootDir(); mPageSize = options.getPageSize(); mCacheSize = options.getCacheSize(); mFileBuckets = options.getFileBuckets(); Path rootDir = Paths.get(mRoot); mPagePattern = Pattern.compile( String.format("%s/%d/(\\d+)/([^/]+)/(\\d+)", Pattern.quote(rootDir.toString()), mPageSize)); }
Source:
protected void addCanDoActionMessageVariable(String varName, Object varValue) { String message = String.format("$%s %s", varName, varValue); getReturnValue().getCanDoActionMessages().add(message); }

Target:
protected void addCanDoActionMessageVariable(String varName, Object varValue) { getReturnValue().getCanDoActionMessages().add(String.format("$%s %s", varName, varValue)); }
Source:
public void testMassive() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(100, 0.0, 1.0); ArrayList<Double> values = new ArrayList<>(); ArrayList<Double> weights = new ArrayList<>(); IntStream.range(0, 1000000).forEach(i -> { double value = Math.random(); double weight = ((int) (10 * Math.random())) / 10.0; values.add(value); weights.add(weight); histogram.add(value, weight, 1); }); Streams.stream(histogram.iterator()).forEach(b -> { long count = IntStream.range(0, values.size()) .filter(i -> b.getLeft() < values.get(i) && values.get(i) <= b.getRight() && b.getWeight() == weights.get(i)) .count(); assertEquals(b.getCount(), count); }); }

Target:
public void testMassive() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(100, 0.0, 1.0); ArrayList<Double> values = new ArrayList<>(); ArrayList<Double> weights = new ArrayList<>(); for (int i = 0; i < 1000000; ++i) { double value = Math.random(); double weight = ((int) (10 * Math.random())) / 10.0; values.add(value); weights.add(weight); histogram.add(value, weight, 1); } Streams.stream(histogram.iterator()).forEach(bucketWeight -> { long count = 0; for (int i = 0; i < values.size(); ++i) { if (bucketWeight.getLeft() < values.get(i) && values.get(i) <= bucketWeight.getRight() && bucketWeight.getWeight() == weights.get(i)) { ++count; } } assertEquals(bucketWeight.getCount(), count); }); }
Source:
private boolean specialCaseMapEntries(String propName, FunctionType propertyType) { if (propertyType.getMaxArity() != 0 || !propName.equals("entries")) { return false; } ImmutableList<JSType> ttypes = null; JSType returnType = propertyType.getReturnType(); if (returnType.isTemplatizedType()) ttypes = ((TemplatizedType) returnType).getTemplateTypes(); if (returnType.isNoResolvedType()) ttypes = ((NoResolvedType) returnType).getTemplateTypes(); if (ttypes == null || !returnType.getDisplayName().equals("IteratorIterable") || ttypes.size() != 1 || !isTemplateOf(ttypes.get(0), "Array")) { return false; } JSType arrayMembers = ttypes.get(0).toMaybeTemplatizedType().getTemplateTypes().get(0); if (!arrayMembers.isUnionType() || arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().size() != 2) { return false; } emit("(): IterableIterator<["); Iterator<JSType> it = arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().iterator(); visitType(it.next()); emit(","); visitType(it.next()); emit("]>;"); emitBreak(); return true; }

Target:
private boolean specialCaseMapEntries(String propName, FunctionType propertyType) { if (propertyType.getMaxArity() != 0 || !propName.equals("entries")) { return false; } ImmutableList<JSType> ttypes = null; JSType returnType = propertyType.getReturnType(); if (returnType.isTemplatizedType()) { ttypes = ((TemplatizedType) returnType).getTemplateTypes(); } else if (returnType.isNoResolvedType()) { ttypes = ((NoResolvedType) returnType).getTemplateTypes(); } if (ttypes == null || !returnType.getDisplayName().equals("IteratorIterable") || ttypes.size() != 1 || !isTemplateOf(ttypes.get(0), "Array")) { return false; } JSType arrayMembers = ttypes.get(0).toMaybeTemplatizedType().getTemplateTypes().get(0); if (!arrayMembers.isUnionType() || arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().size() != 2) { return false; } emit("(): IterableIterator<["); Iterator<JSType> it = arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().iterator(); visitType(it.next()); emit(","); visitType(it.next()); emit("]>;"); emitBreak(); return true; }
Source:
protected void validateParameters() { if (user == null && (users == null || users.isEmpty()) && email == null) { throw new IllegalParameterException("'users' or 'email' parameters must be set"); } else if (email != null && end == null) { throw new IllegalParameterException("'end' parameter must be set when adding a permission for an 'email'"); } ConfigurationService configService = Framework.getService(ConfigurationService.class); if (configService.isBooleanPropertyFalse(ALLOW_VIRTUAL_USER)) { UserManager userManager = Framework.getService(UserManager.class); if (user != null) { checkUserAndGroupExistence(user, userManager); } if (users != null && !users.isEmpty()) { for (String username : users) { checkUserAndGroupExistence(username, userManager); } } } }

Target:
protected void validateParameters() { if (user == null && (users == null || users.isEmpty()) && email == null) { throw new IllegalParameterException("'users' or 'email' parameters must be set"); } else if (email != null && end == null) { throw new IllegalParameterException("'end' parameter must be set when adding a permission for an 'email'"); } ensureUserListIsUsed(); ConfigurationService configService = Framework.getService(ConfigurationService.class); if (configService.isBooleanPropertyFalse(ALLOW_VIRTUAL_USER)) { UserManager userManager = Framework.getService(UserManager.class); List<String> unknownNames = users.stream() .filter(userOrGroupName -> !isTransientUsername(userOrGroupName) && userManager.getUserModel(userOrGroupName) == null && userManager.getGroupModel(userOrGroupName) == null) .collect(toList()); if (!unknownNames.isEmpty()) { String errorMsg = String.format( "The following set of User or Group names do not exist: [%s]. Please provide valid ones.", String.join(",", unknownNames)); throw new IllegalParameterException(errorMsg); } } }
Source:
public void copyFormatting(BaseComponent component) { copyFormatting( component, FormatRetention.ALL, false ); }

Target:
public void copyFormatting(BaseComponent component) { copyFormatting( component, FormatRetention.ALL, true ); }
Source:
private void removeDuplicateAttacks(int entityId) { int allowed = 1; Entity en = game.getEntity(entityId); if (null != en) { allowed = en.getAllowedPhysicalAttacks(); } Vector<EntityAction> toKeep = new Vector<>(); for (Enumeration<EntityAction> i = game.getActions(); i.hasMoreElements(); ) { EntityAction action = i.nextElement(); if (action.getEntityId() != entityId) { toKeep.addElement(action); } else if (allowed > 0) { toKeep.addElement(action); if (!(action instanceof SearchlightAttackAction)) { allowed--; } } else { MegaMek.getLogger().error("removing duplicate phys attack for id#" + entityId + "\n\t\taction was " + action.toString()); } } game.resetActions(); for (EntityAction entityAction : toKeep) { game.addAction(entityAction); } }

Target:
private void removeDuplicateAttacks(int entityId) { int allowed = 1; Entity en = game.getEntity(entityId); if (null != en) { allowed = en.getAllowedPhysicalAttacks(); } Vector<EntityAction> toKeep = new Vector<>(); for (Enumeration<EntityAction> i = game.getActions(); i.hasMoreElements(); ) { EntityAction action = i.nextElement(); if (action.getEntityId() != entityId) { toKeep.addElement(action); } else if (allowed > 0) { toKeep.addElement(action); if (!(action instanceof SearchlightAttackAction)) { allowed--; } } else { MegaMek.getLogger().error("Removing duplicate phys attack for id#" + entityId + "\n\t\taction was " + action.toString()); } } game.resetActions(); for (EntityAction entityAction : toKeep) { game.addAction(entityAction); } }
Source:
private String acquireAccessToken() throws APIException { try { HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(new GenericUrl( String.format("%s/oauth/token?client_id=testdroid-cloud-api&client_secret=qwerty&grant_type=password&username=%s&password=%s", cloudURL, username, password))); request.setConnectTimeout(60000); request.setReadTimeout(60000); HttpResponse response = request.execute(); if(response.getStatusCode() != 200) { throw new APIException(response.getStatusCode(), "Failed to acquire access token"); } String content = StringUtils.join(IOUtils.readLines(response.getContent()), "\n"); JSONObject json = JSONObject.fromObject(content); accessTokenExpireTime = System.currentTimeMillis()+(Long.parseLong(json.optString("expires_in"))*1000); return json.optString("access_token"); } catch(IOException ex) { throw new APIException("Failed to acquire access token", ex); } }

Target:
private String acquireAccessToken() throws APIException { try { HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(new GenericUrl( String.format("%s/oauth/token?client_id=testdroid-cloud-api&client_secret=qwerty&grant_type=password&username=%s&password=%s", cloudURL, username, password))); request.setConnectTimeout(HTTP_CONNECT_TIMEOUT); request.setReadTimeout(HTTP_READ_TIMEOUT); HttpResponse response = request.execute(); if(response.getStatusCode() != 200) { throw new APIException(response.getStatusCode(), "Failed to acquire access token"); } String content = StringUtils.join(IOUtils.readLines(response.getContent()), "\n"); JSONObject json = JSONObject.fromObject(content); accessTokenExpireTime = System.currentTimeMillis()+(Long.parseLong(json.optString("expires_in"))*1000); return json.optString("access_token"); } catch(IOException ex) { throw new APIException("Failed to acquire access token", ex); } }
Source:
public synchronized IPath[] getPaths() { List<IPath> result = new ArrayList<>(); for (Object element : objects.keySet()) { IPath path = (IPath) element; Node node = getNode(path); if (node.getPayload() != null) result.add(path); } return result.toArray(new IPath[result.size()]); }

Target:
public synchronized IPath[] getPaths() { List<IPath> result = new ArrayList<>(); for (IPath path : objects.keySet()) { Node node = getNode(path); if (node.getPayload() != null) result.add(path); } return result.toArray(new IPath[result.size()]); }
Source:
static void printTweetsOnce(JCommanderSetting jCommanderSettings, Location currentLocation, String queryString) { int numberOfTries = 0; do { try { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query(queryString).geoCode( new GeoLocation( currentLocation.getLatitude(), currentLocation.getLongitude()), RADIUS, RADIUS_UNIT); query.setCount(jCommanderSettings.getLimit()); QueryResult result = twitter.search(query); long currentTime = System.currentTimeMillis(); List<Status> tweets = result.getTweets(); Collections.reverse(tweets); if (tweets.size() == 0) { System.out.println("Не найдено ни одного твита"); printSeparator(); } for (Status status : tweets) { if (!status.isRetweet() || !jCommanderSettings.isHideRetweets()) { System.out.print("[" + TimeFormatter.formatTime(currentTime, status.getCreatedAt().getTime()) + "] "); printTweet(status); printSeparator(); } } numberOfTries = MAX_NUMBER_OF_TRIES; } catch (TwitterException te) { ++numberOfTries; if (numberOfTries == MAX_NUMBER_OF_TRIES) { System.out.println(te.getMessage()); System.err.println("Something went terribly wrong, " + "probably - connection + error"); System.exit(1); } } } while (numberOfTries < MAX_NUMBER_OF_TRIES); }

Target:
static void printTweetsOnce(JCommanderSetting jCommanderSettings, Location currentLocation, String queryString) { int numberOfTries = 0; do { try { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query(queryString).geoCode( new GeoLocation( currentLocation.getLatitude(), currentLocation.getLongitude()), RADIUS, RADIUS_UNIT); query.setCount(jCommanderSettings.getLimit()); QueryResult result = twitter.search(query); long currentTime = System.currentTimeMillis(); List<Status> tweets = result.getTweets(); Collections.reverse(tweets); if (tweets.isEmpty()) { System.out.println("Не найдено ни одного твита"); printSeparator(); } for (Status status : tweets) { if (!status.isRetweet() || !jCommanderSettings.isHideRetweets()) { System.out.print("[" + TimeFormatter.formatTime(currentTime, status.getCreatedAt().getTime()) + "] "); printTweet(status); printSeparator(); } } numberOfTries = MAX_NUMBER_OF_TRIES; } catch (TwitterException te) { ++numberOfTries; if (numberOfTries == MAX_NUMBER_OF_TRIES) { System.out.println(te.getMessage()); System.err.println("Something went terribly wrong, " + "probably - connection + error"); System.exit(1); } } } while (numberOfTries < MAX_NUMBER_OF_TRIES); }
Source:
private void initKeyStore() throws Exception { LOG.debug("SamlCallbackHandler.initKeyStore() -- Begin"); InputStream is = null; final HashMap<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_PASSWORD_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.error("javax.net.ssl.keyStoreType is not defined"); LOG.warn("Default to JKS keyStoreType"); storeType = JKS_TYPE; } if (password == null || storeLoc == null) { LOG.error("Store password or store location not defined"); LOG.error("Please define javax.net.ssl.keyStorePassword and javax.net.ssl.keyStore"); } if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("javax.net.ssl.keyStore is not defined"); } else { try { keyStore = KeyStore.getInstance(storeType); if (!PKCS11_TYPE.equalsIgnoreCase(storeType)) { is = new FileInputStream(storeLoc); } keyStore.load(is, (password != null) ? password.toCharArray() : null); } catch (final NoSuchAlgorithmException ex) { LOG.error(KEY_STORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } catch (final CertificateException ex) { LOG.error(KEY_STORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } catch (final KeyStoreException ex) { LOG.error(KEY_STORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } finally { try { if (is != null) { is.close(); } } catch (final IOException ex) { LOG.debug("KeyStoreCallbackHandler {}", ex); } } } LOG.debug("SamlCallbackHandler.initKeyStore() -- End"); }

Target:
private void initKeyStore() throws Exception { LOG.debug("SamlCallbackHandler.initKeyStore() -- Begin"); InputStream is = null; final HashMap<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_PASSWORD_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.error("javax.net.ssl.keyStoreType is not defined"); LOG.warn("Default to JKS keyStoreType"); storeType = JKS_TYPE; } if (password !=null){ if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("javax.net.ssl.keyStore is not defined"); } else { try { keyStore = KeyStore.getInstance(storeType); if (!PKCS11_TYPE.equalsIgnoreCase(storeType)) { is = new FileInputStream(storeLoc); } keyStore.load(is, password.toCharArray()); } catch (final NoSuchAlgorithmException|CertificateException|KeyStoreException ex) { LOG.error(KEYSTORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } finally { try { if (is != null) { is.close(); } } catch (final IOException ex) { LOG.debug("KeyStoreCallbackHandler {}", ex); } } } }else{ LOG.error("Please define javax.net.ssl.keyStorePassword"); } LOG.debug("SamlCallbackHandler.initKeyStore() -- End"); }
Source:
public void onBindViewHolder(final ItemHolder holder, int position) { String item = mItems.get(holder.getAdapterPosition()); holder.text.setText(item); holder.container.setBackgroundColor( isItemSelected(position) ? mSelectedColor : mUnselectedColor ); }

Target:
public void onBindViewHolder(final ItemHolder holder, int position) { String item = getItem(holder.getAdapterPosition()); holder.text.setText(item); holder.container.setBackgroundColor( isItemSelected(position) ? mSelectedColor : mUnselectedColor ); }
Source:
public void itReturnsAllValuesWrapped() { ArgumentCaptor<ReactiveNavigator.ActivityResult> argumentCaptor = ArgumentCaptor.forClass(ActivityResult.class); Observable<ActivityResult> observable = reactiveNavigator.toActivityForResult(mockIntent, 42); observable.subscribe(mockObserver); reactiveNavigator.onActivityResult(42, Activity.RESULT_OK, mockData); verify(mockObserver).onNext(argumentCaptor.capture()); ActivityResult value = argumentCaptor.getValue(); Assert.assertEquals(Activity.RESULT_OK, value.getResultCode()); assertEquals(mockData, value.getData()); }

Target:
public void itReturnsAllValuesWrapped() { ArgumentCaptor<ReactiveNavigator.ActivityResult> argumentCaptor = ArgumentCaptor.forClass(ActivityResult.class); Observable<ActivityResult> observable = reactiveNavigator.activityResult(mockIntent, 42); observable.subscribe(mockObserver); reactiveNavigator.onActivityResult(42, Activity.RESULT_OK, mockData); verify(mockObserver).onNext(argumentCaptor.capture()); ActivityResult value = argumentCaptor.getValue(); assertEquals(Activity.RESULT_OK, value.resultCode()); assertEquals(mockData, value.data()); }
Source:
public void loadOffices() { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getOffices() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Office>>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); try { if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(List<Office> offices) { getMvpView().showProgressbar(false); getMvpView().showOffices(offices); } })); }

Target:
public void loadOffices() { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getOffices() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Office>>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(List<Office> offices) { getMvpView().showProgressbar(false); getMvpView().showOffices(offices); } })); }
Source:
public void initialize() { logger.debug("Initializing WemoLightHandler"); final String configLightId = (String) getConfig().get(DEVICE_ID); if (DEVICE_ID != null) { wemoLightID = configLightId; logger.debug("Initializing WemoLightHandler for LightID '{}'", wemoLightID); if (getWemoBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); if (SUPPORTED_THING_TYPES.contains(this.getThing().getThingTypeUID())) { logger.debug("Initialize Thing {}", this.getThing().getThingTypeUID()); updateStatus(ThingStatus.ONLINE); onSubscription(); onUpdate(); } } } else { logger.debug("Cannot initalize WemoLightHandler. LightID not set."); } }

Target:
public void initialize() { logger.debug("Initializing WemoLightHandler"); final String configLightId = (String) getConfig().get(DEVICE_ID); if (DEVICE_ID != null) { wemoLightID = configLightId; logger.debug("Initializing WemoLightHandler for LightID '{}'", wemoLightID); } }