auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static Level toLevel(EventPriority eventPriority) { switch (eventPriority) { case ALERT: case EMERGENCY: case CRITICAL: case ERROR: return Level.SEVERE; case WARNING: return Level.WARNING; case INFORMATIONAL: return Level.INFO; default: return Level.FINEST; } }

Target:
private static Level toLevel(EventPriority eventPriority) { switch (eventPriority) { case ALERT: case EMERGENCY: case CRITICAL: case ERROR: return Level.SEVERE; case WARNING: return Level.WARNING; case INFORMATIONAL: return Level.INFO; case OFF: throw audit.invalidEventPriority(eventPriority); default: return Level.FINEST; } }
Source:
private void verifyEditResultCode(EditingResult result) { assertThat(result.getResult(), equalTo(SUCCESS)); }

Target:
private void verifyEditResultCode(EditingResult result) { assertThat(result.getResult(), is(SUCCESS)); }
Source:
private void configureBackground(IFigure fig) { DSemanticDiagram dSemanticDiagram = (DSemanticDiagram) this.resolveDDiagram().get(); if (dSemanticDiagram != null && fig != null) { ColorDescription backgroundColor = dSemanticDiagram.getDescription().getBackgroundColor(); if (backgroundColor != null) { RGBValues rgbBackgroundValues = new AbstractColorUpdater().getRGBValuesFromColorDescription(dSemanticDiagram.getTarget(), backgroundColor); Color colorUpdate = new Color(null, rgbBackgroundValues.getRed(), rgbBackgroundValues.getGreen(), rgbBackgroundValues.getBlue()); if (isWhiteColor(rgbBackgroundValues)) { fig.setBackgroundColor(null); fig.setOpaque(false); } else { fig.setBackgroundColor(colorUpdate); fig.setOpaque(true); } } } }

Target:
private void configureBackground(IFigure fig) { if (resolveDDiagram().some() && fig != null) { DSemanticDiagram dSemanticDiagram = (DSemanticDiagram) this.resolveDDiagram().get(); ColorDescription backgroundColor = dSemanticDiagram.getDescription().getBackgroundColor(); if (backgroundColor != null) { RGBValues rgbBackgroundValues = new AbstractColorUpdater().getRGBValuesFromColorDescription(dSemanticDiagram.getTarget(), backgroundColor); Color colorUpdate = new Color(null, rgbBackgroundValues.getRed(), rgbBackgroundValues.getGreen(), rgbBackgroundValues.getBlue()); if (isWhiteColor(rgbBackgroundValues)) { fig.setBackgroundColor(null); fig.setOpaque(false); } else { fig.setBackgroundColor(colorUpdate); fig.setOpaque(true); } } } }
Source:
public String[] getPreferredKeyAlgorithms(SlaveComputer computer) throws IOException { if (!KNOWN_HOSTS_FILE.exists()) { return super.getPreferredKeyAlgorithms(computer); } KnownHosts knownHosts = new KnownHosts(KNOWN_HOSTS_FILE); return knownHosts.getPreferredServerHostkeyAlgorithmOrder(((SSHLauncher) computer.getLauncher()).getHost()); }

Target:
public String[] getPreferredKeyAlgorithms(SlaveComputer computer) throws IOException { ComputerLauncher launcher = computer.getLauncher(); if (!(launcher instanceof SSHLauncher) || !KNOWN_HOSTS_FILE.exists()) { return super.getPreferredKeyAlgorithms(computer); } KnownHosts knownHosts = new KnownHosts(KNOWN_HOSTS_FILE); return knownHosts.getPreferredServerHostkeyAlgorithmOrder(((SSHLauncher) launcher).getHost()); }
Source:
protected void sendReport(RassBatchJobReport report) { LOG.debug("sendReport, The report-sending functionality has not been implemented yet."); rassReportService.sendReportEmail(); }

Target:
protected void sendReport(RassBatchJobReport report) { rassReportService.sendReportEmail(); }
Source:
public Optional<ServiceBindingType> convert(Map<String, Object> map) { Optional<ServiceBindingType> optionalBinding = Optional.empty(); if (MapUtils.isEmpty(map)) { return optionalBinding; } optionalBinding = super.convert(map); optionalBinding = mapToSchemaElement.populateStringElement( map, ACCESS_URI, optionalBinding, (valueToPopulate, serviceBinding) -> serviceBinding.setAccessURI(valueToPopulate)); optionalBinding = mapToSchemaElement.populateStringElement( map, SERVICE, optionalBinding, (valueToPopulate, serviceBinding) -> serviceBinding.setService(valueToPopulate)); if (map.containsKey(SPECIFICATION_LINK_KEY)) { SpecificationLinkTypeConverter slConverter = new SpecificationLinkTypeConverter(); Optional<SpecificationLinkType> optionalSpec; for (Map<String, Object> specMap : (List<Map<String, Object>>) map.get(SPECIFICATION_LINK_KEY)) { optionalSpec = slConverter.convert(specMap); if (optionalSpec.isPresent()) { if (!optionalBinding.isPresent()) { optionalBinding = Optional.of(mapToSchemaElement.getObjectFactory().get()); } optionalBinding.get().getSpecificationLink().add(optionalSpec.orElse(null)); } } } optionalBinding = mapToSchemaElement.populateStringElement( map, TARGET_BINDING, optionalBinding, (valueToPopulate, serviceBinding) -> serviceBinding.setTargetBinding(valueToPopulate)); return optionalBinding; }

Target:
public Optional<ServiceBindingType> convert(Map<String, Object> map) { Optional<ServiceBindingType> optionalBinding = Optional.empty(); if (MapUtils.isEmpty(map)) { return optionalBinding; } optionalBinding = super.convert(map); optionalBinding = mapToSchemaElement.populateStringElement( map, ACCESS_URI, optionalBinding, (valueToPopulate, serviceBinding) -> serviceBinding.setAccessURI(valueToPopulate)); optionalBinding = mapToSchemaElement.populateStringElement( map, SERVICE, optionalBinding, (valueToPopulate, serviceBinding) -> serviceBinding.setService(valueToPopulate)); if (map.containsKey(SPECIFICATION_LINK_KEY)) { SpecificationLinkTypeConverter slConverter = new SpecificationLinkTypeConverter(); Optional<SpecificationLinkType> optionalSpec; for (Map<String, Object> specMap : (List<Map<String, Object>>) map.get(SPECIFICATION_LINK_KEY)) { optionalSpec = slConverter.convert(specMap); if (optionalSpec.isPresent()) { if (!optionalBinding.isPresent()) { optionalBinding = Optional.of(mapToSchemaElement.getObjectFactory().get()); } optionalBinding.get().getSpecificationLink().add(optionalSpec.get()); } } } optionalBinding = mapToSchemaElement.populateStringElement( map, TARGET_BINDING, optionalBinding, (valueToPopulate, serviceBinding) -> serviceBinding.setTargetBinding(valueToPopulate)); return optionalBinding; }
Source:
public void run() { final long oldTimeStamp = lastMeasuredTimestamp; lastMeasuredTimestamp = System.currentTimeMillis(); final boolean clusterOverloaded = isClusterOverloaded(); final boolean clusterIdle = isClusterIdle(); LOG.log(Level.INFO, "Task Num = {0}. Overloaded = {1}, Idle = {2}", new Object[]{taskStatsMap.entrySet().size(), clusterOverloaded, clusterIdle}); if (clusterOverloaded) { overloadedTimeElapsed += lastMeasuredTimestamp - oldTimeStamp; if (overloadedTimeElapsed > scaleOutGracePeriod && taskStatsMap.getTaskList().size() < maxTaskNum && recoveryScheduler.tryAcquireRecoveryLock()) { try { overloadedTimeElapsed = 0; } catch (final Exception e) { e.printStackTrace(); } finally { recoveryScheduler.releaseRecoveryLock(); } return; } } else { overloadedTimeElapsed = 0; } if (clusterIdle) { idleTimeElapsed += lastMeasuredTimestamp - oldTimeStamp; if (idleTimeElapsed > scaleInGracePeriod && taskStatsMap.getTaskList().size() > minTaskNum && recoveryScheduler.tryAcquireRecoveryLock()) { LOG.log(Level.INFO, "Start scaling-in..."); try { scaleInManager.scaleIn(); idleTimeElapsed = 0; } catch (final Exception e) { e.printStackTrace(); } finally { recoveryScheduler.releaseRecoveryLock(); } } } else { idleTimeElapsed = 0; } }

Target:
public void run() { final long oldTimeStamp = lastMeasuredTimestamp; lastMeasuredTimestamp = System.currentTimeMillis(); final boolean clusterOverloaded = isClusterOverloaded(); final boolean clusterIdle = isClusterIdle(); LOG.log(Level.INFO, "Task Num = {0}. Overloaded = {1}, Idle = {2}", new Object[]{taskStatsMap.entrySet().size(), clusterOverloaded, clusterIdle}); if (clusterOverloaded) { overloadedTimeElapsed += lastMeasuredTimestamp - oldTimeStamp; if (overloadedTimeElapsed > scaleOutGracePeriod && taskStatsMap.getTaskList().size() < maxTaskNum && recoveryLock.tryLock()) { try { overloadedTimeElapsed = 0; } catch (final Exception e) { e.printStackTrace(); } finally { recoveryLock.unlock(); } return; } } else { overloadedTimeElapsed = 0; } if (clusterIdle) { idleTimeElapsed += lastMeasuredTimestamp - oldTimeStamp; if (idleTimeElapsed > scaleInGracePeriod && taskStatsMap.getTaskList().size() > minTaskNum && recoveryLock.tryLock()) { LOG.log(Level.INFO, "Start scaling-in..."); try { scaleInManager.scaleIn(); idleTimeElapsed = 0; } catch (final Exception e) { e.printStackTrace(); } finally { recoveryLock.unlock(); } } } else { idleTimeElapsed = 0; } }
Source:
public static RelDataType toSql(final RelDataTypeFactory typeFactory, RelDataType type) { if (type instanceof RelRecordType) { return typeFactory.createTypeWithNullability( typeFactory.createStructType( Lists.transform(type.getFieldList(), field -> toSql(typeFactory, field.getType())), type.getFieldNames()), type.isNullable()); } if (type instanceof JavaType) { return typeFactory.createTypeWithNullability( typeFactory.createSqlType(type.getSqlTypeName()), type.isNullable()); } return type; }

Target:
public static RelDataType toSql(final RelDataTypeFactory typeFactory, RelDataType type) { return toSql(typeFactory, type, true); }
Source:
static int getFileExifRotation(Uri uri) throws IOException { ExifInterface exifInterface = new ExifInterface(uri.getPath()); int orientation = exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); return orientation; }

Target:
static int getFileExifRotation(Uri uri) throws IOException { ExifInterface exifInterface = new ExifInterface(uri.getPath()); return exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); }
Source:
public void testDescribeTable() { MaterializedResult actualColumns = this.computeActual("DESC orders").toTestTypes(); MaterializedResult.Builder builder = resultBuilder(this.getQueryRunner().getDefaultSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR); for (MaterializedRow row : actualColumns.getMaterializedRows()) { builder.row(row.getField(0), row.getField(1), "", ""); } MaterializedResult filteredActual = builder.build(); builder = resultBuilder(this.getQueryRunner().getDefaultSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR); MaterializedResult expectedColumns = builder .row("orderkey", "bigint", "", "") .row("custkey", "bigint", "", "") .row("orderstatus", "varchar", "", "") .row("totalprice", "double", "", "") .row("orderdate", "varchar", "", "") .row("orderpriority", "varchar", "", "") .row("clerk", "varchar", "", "") .row("shippriority", "bigint", "", "") .row("comment", "varchar", "", "").build(); assertEquals(filteredActual, expectedColumns, String.format("%s != %s", filteredActual, expectedColumns)); }

Target:
public void testDescribeTable() { MaterializedResult actualColumns = computeActual("DESC orders").toTestTypes(); MaterializedResult.Builder builder = resultBuilder(getQueryRunner().getDefaultSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR); for (MaterializedRow row : actualColumns.getMaterializedRows()) { builder.row(row.getField(0), row.getField(1), "", ""); } MaterializedResult actualResult = builder.build(); builder = resultBuilder(getQueryRunner().getDefaultSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR); MaterializedResult expectedColumns = builder .row("orderkey", "bigint", "", "") .row("custkey", "bigint", "", "") .row("orderstatus", "varchar", "", "") .row("totalprice", "double", "", "") .row("orderdate", "varchar", "", "") .row("orderpriority", "varchar", "", "") .row("clerk", "varchar", "", "") .row("shippriority", "bigint", "", "") .row("comment", "varchar", "", "").build(); assertEquals(actualResult, expectedColumns, format("%s != %s", actualResult, expectedColumns)); }
Source:
protected void putManagedState(Object tuple) { ((ManagedTimeStateImpl)managedState).put(getBucketId(getKey(tuple)), DEFAULT_CONSTANT_TIME, getKey(tuple), new Slice(new byte[0])); }

Target:
protected void putManagedState(Object tuple) { Slice key = getKey(tuple); ((ManagedTimeStateImpl)managedState).put(getBucketId(key), DEFAULT_CONSTANT_TIME, key, new Slice(new byte[0])); }
Source:
private void generateAspects(ITmfEventField[] fieldsArray) { ImmutableList.Builder<ITmfEventAspect> builder = new ImmutableList.Builder<>(); for (ITmfEventAspect criterion : TmfTrace.BASE_ASPECTS) { builder.add(criterion); } for (ITmfEventField field : fieldsArray) { String name = field.getName(); if (name == null) { break; } ITmfEventAspect criterion = new TmfEventFieldAspect(name, name); if (name.equals(CRITERION_CPU)) { criterion = new XmlStubCpuAspect((TmfEventFieldAspect) criterion); } builder.add(criterion); } @SuppressWarnings("null") @NonNull Collection<ITmfEventAspect> criteriaList = builder.build(); fAspect = criteriaList; }

Target:
private void generateAspects(ITmfEventField[] fieldsArray) { ImmutableList.Builder<ITmfEventAspect> builder = new ImmutableList.Builder<>(); builder.add(ITmfEventAspect.BaseAspects.TIMESTAMP); builder.add(ITmfEventAspect.BaseAspects.EVENT_TYPE); for (ITmfEventField field : fieldsArray) { String name = field.getName(); if (name == null) { break; } ITmfEventAspect aspect = new TmfEventFieldAspect(name, name); if (name.equals(ASPECT_CPU)) { aspect = new XmlStubCpuAspect((TmfEventFieldAspect) aspect); } builder.add(aspect); } builder.add(ITmfEventAspect.BaseAspects.CONTENTS); @SuppressWarnings("null") @NonNull Collection<ITmfEventAspect> aspectList = builder.build(); fAspects = aspectList; }
Source:
public void testToString_withCustomConfigurations() { toolbarConfig = new ToolbarConfiguration() { @Override protected String getToolbarGroupConfiguration() { return "CKEDITOR.config.toolbarGroups = [];"; } @Override protected String getRemoveButtonConfiguration() { return "CKEDITOR.config.removeButtons = \"Subscript\";"; } @Override public String getToolbarLanguage() { return "de"; } }; JsonObject config = ( JsonObject )JsonValue.readFrom( toolbarConfig.toString() ); assertNotNull( config.get( "toolbarGroups" ) ); assertNotNull( config.get( "removeButtons" ) ); assertNotNull( config.get( "toolbarCanCollapse" ) ); assertNotNull( config.get( "toolbarStartupExpanded" ) ); assertEquals( "en", config.get( "language" ).asString() ); }

Target:
public void testToString_withCustomConfigurations() { toolbarConfig = new ToolbarConfiguration() { @Override protected String getToolbarGroupConfiguration() { return "CKEDITOR.config.toolbarGroups = [];"; } @Override protected String getRemoveButtonConfiguration() { return "CKEDITOR.config.removeButtons = \"Subscript\";"; } @Override public String getToolbarLanguage() { return "de"; } }; JsonObject config = ( JsonObject )JsonValue.readFrom( toolbarConfig.toString() ); assertNotNull( config.get( "toolbarGroups" ) ); assertNotNull( config.get( "removeButtons" ) ); assertNotNull( config.get( "toolbarCanCollapse" ) ); assertNotNull( config.get( "toolbarStartupExpanded" ) ); assertEquals( "de", config.get( "language" ).asString() ); }
Source:
public void canSetRequestedArchiveLocationPrefix() { Assert.assertFalse(this.jobEntity.getRequestedArchiveLocationPrefix().isPresent()); final String requestedArchiveLocationPrefix = UUID.randomUUID().toString(); this.jobEntity.setRequestedArchiveLocationPrefix(requestedArchiveLocationPrefix); Assert.assertThat( this.jobEntity.getRequestedArchiveLocationPrefix().orElse(UUID.randomUUID().toString()), Matchers.is(requestedArchiveLocationPrefix) ); }

Target:
public void canSetRequestedArchiveLocationPrefix() { Assert.assertFalse(this.jobEntity.getRequestedArchiveLocationPrefix().isPresent()); final String requestedArchiveLocationPrefix = UUID.randomUUID().toString(); this.jobEntity.setRequestedArchiveLocationPrefix(requestedArchiveLocationPrefix); Assert.assertThat( this.jobEntity.getRequestedArchiveLocationPrefix().get(), Matchers.is(requestedArchiveLocationPrefix) ); }
Source:
public Long getDbGeneration() { return dbGeneration; }

Target:
public long getDbGeneration() { return dbGeneration; }
Source:
public ElasticsearchPersistentEntity<?> getPersistentEntityFor(Class<?> type) { Assert.notNull(type, "type must not be null!"); Assert.isTrue(type.isAnnotationPresent(Document.class), "Unable to identify index name. " + type.getSimpleName() + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")"); return getElasticsearchConverter().getMappingContext().getRequiredPersistentEntity(type); }

Target:
public ElasticsearchPersistentEntity<?> getPersistentEntityFor(Class<?> type) { Assert.notNull(type, "type must not be null!"); Assert.isTrue(type.isAnnotationPresent(Document.class), "Unable to identify index name. " + type.getSimpleName() + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")"); return elasticsearchConverter.getMappingContext().getRequiredPersistentEntity(type); }
Source:
public boolean hasSelectedResources() { return selectedBaseResources.size() > 0; }

Target:
public boolean hasSelectedResources() { return !selectedBaseContainers.isEmpty(); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComparableEvent other = (ComparableEvent) obj; if (outcome != other.outcome) return false; if (!Arrays.equals(predIndexes, other.predIndexes)) return false; if (seen != other.seen) return false; if (!Arrays.equals(values, other.values)) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj instanceof ComparableEvent) { ComparableEvent other = (ComparableEvent) obj; return outcome == other.outcome && Arrays.equals(predIndexes, other.predIndexes) && seen == other.seen && Arrays.equals(values, other.values); } return false; }
Source:
private AuthenticationResult parseJsonResponse(final String responseBody) throws JSONException, AuthenticationException { HashMap<String, String> responseItems = new HashMap<>(); extractJsonObjects(responseItems, responseBody); return processUIResponseParams(responseItems); }

Target:
private AuthenticationResult parseJsonResponse(final String responseBody) throws JSONException, AuthenticationException { final Map<String, String> responseItems = new HashMap<>(); extractJsonObjects(responseItems, responseBody); return processUIResponseParams(responseItems); }
Source:
public void createClaimWithLogging(String wikidataEntityId, String fileName) { if (wikidataEntityId == null) { Timber.d("Skipping creation of claim as Wikidata entity ID is null"); return; } if (fileName == null) { Timber.d("Skipping creation of claim as fileName entity ID is null"); return; } if (!(directKvStore.getBoolean("Picture_Has_Correct_Location", true))) { Timber.d("Image location and nearby place location mismatched, so Wikidata item won't be edited"); return; } editWikidataProperty(wikidataEntityId, fileName); editWikidataPropertyP180(wikidataEntityId, fileName); }

Target:
public void createClaimWithLogging(String wikidataEntityId, String fileName) { if (wikidataEntityId == null) { Timber.d("Skipping creation of claim as Wikidata entity ID is null"); return; } if (fileName == null) { Timber.d("Skipping creation of claim as fileName entity ID is null"); return; } if (!(directKvStore.getBoolean("Picture_Has_Correct_Location", true))) { Timber.d("Image location and nearby place location mismatched, so Wikidata item won't be edited"); return; } editWikidataProperty(wikidataEntityId, fileName); editWikiBaseDepictsProperty(wikidataEntityId, fileName); }
Source:
public Builder metadata(Map<String, Object> metadata) { if (metadata == null) { this.metadata = ImmutableMap.of(); } else { this.metadata = ImmutableMap.copyOf(metadata); } return this; }

Target:
public Builder metadata(Map<String, Object> metadata) { this.metadata = metadata; return this; }
Source:
private static <K, V> void testMultimapAggWithGroupBy( InternalAggregationFunction aggregationFunction, GroupedAccumulator groupedAccumulator, int groupId, Type keyType, List<K> expectedKeys, Type valueType, List<V> expectedValues) { RowPageBuilder pageBuilder = RowPageBuilder.rowPageBuilder(keyType, valueType); ImmutableMultimap.Builder<K, V> outputBuilder = ImmutableMultimap.builder(); for (int i = 0; i < expectedValues.size(); i++) { pageBuilder.row(expectedKeys.get(i), expectedValues.get(i)); outputBuilder.put(expectedKeys.get(i), expectedValues.get(i)); } Page page = pageBuilder.build(); AggregationTestInput input = new AggregationTestInputBuilder( new Block[]{page.getBlock(0), page.getBlock(1)}, aggregationFunction ).build(); AggregationTestOutput testOutput2 = new AggregationTestOutput(outputBuilder.build().asMap()); input.runPagesOnAccumulatorWithAssertion(groupId, groupedAccumulator, testOutput2); }

Target:
private static <K, V> void testMultimapAggWithGroupBy( InternalAggregationFunction aggregationFunction, GroupedAccumulator groupedAccumulator, int groupId, Type keyType, List<K> expectedKeys, Type valueType, List<V> expectedValues) { RowPageBuilder pageBuilder = RowPageBuilder.rowPageBuilder(keyType, valueType); ImmutableMultimap.Builder<K, V> outputBuilder = ImmutableMultimap.builder(); for (int i = 0; i < expectedValues.size(); i++) { pageBuilder.row(expectedKeys.get(i), expectedValues.get(i)); outputBuilder.put(expectedKeys.get(i), expectedValues.get(i)); } Page page = pageBuilder.build(); AggregationTestInput input = new AggregationTestInputBuilder( new Block[] {page.getBlock(0), page.getBlock(1)}, aggregationFunction).build(); AggregationTestOutput testOutput = new AggregationTestOutput(outputBuilder.build().asMap()); input.runPagesOnAccumulatorWithAssertion(groupId, groupedAccumulator, testOutput); }
Source:
public void NGramFeatureGenerator(int minGram, int maxGram) throws InvalidFormatException { if (minGram <= maxGram) { this.minGram = minGram; this.maxGram = maxGram; } else { throw new InvalidFormatException("minimum range value (minGram) should be less than or equal to maximum range value (maxGram)!"); } }

Target:
public NGramFeatureGenerator(int minGram, int maxGram) throws InvalidFormatException { if (minGram > 0 && maxGram > 0) { if (minGram <= maxGram) { this.minGram = minGram; this.maxGram = maxGram; } else { throw new InvalidFormatException("Minimum range value (minGram) should be less than or equal to maximum range value (maxGram)!"); } } else { throw new InvalidFormatException("Both minimum range value (minGram) & maximum range value (maxGram) should be greater than or equal to 1!"); } }
Source:
public String getText(Object object) { LabelProviderService labelProviderService = Activator.getDefault().getLabelProviderService(); if (labelProviderService != null) { return labelProviderService.getLabelProvider(PAPYRUS_LABEL_PROVIDER_COMPARE_CONTEXT, object) .getText(object); } return super.getText(object); }

Target:
public String getText(Object object) { LabelProviderService labelProviderService = Activator.getDefault().getLabelProviderService(); if (labelProviderService != null) { ILabelProvider labelProvider = labelProviderService .getLabelProvider(PAPYRUS_LABEL_PROVIDER_COMPARE_CONTEXT, object); if (labelProvider != null) { return labelProvider.getText(object); } } return super.getText(object); }
Source:
public AsyncRequestResponseHandlerFactory(Integer handlerCount, RestServerMetrics restServerMetrics, BlobStorageService blobStorageService) { if (restServerMetrics == null || blobStorageService == null) { throw new IllegalArgumentException("One or more arguments received is null"); } else if (handlerCount <= 0) { throw new IllegalArgumentException("Request handler scaling unit count has to be > 0. Is " + handlerCount); } else { AsyncRequestResponseHandler requestHandler = buildInstance(restServerMetrics); requestHandler.setRequestWorkersCount(handlerCount); requestHandler.setBlobStorageService(blobStorageService); } logger.trace("Instantiated AsyncRequestResponseHandlerFactory as RestRequestHandler"); }

Target:
public AsyncRequestResponseHandlerFactory(Integer handlerCount, RestServerMetrics restServerMetrics, BlobStorageService blobStorageService) { if (restServerMetrics == null || blobStorageService == null) { throw new IllegalArgumentException("One or more arguments received is null"); } else if (handlerCount <= 0) { throw new IllegalArgumentException("Request handler scaling unit count has to be > 0. Is " + handlerCount); } else { buildInstance(restServerMetrics); instance.setupRequestHandling(handlerCount, blobStorageService); } logger.trace("Instantiated AsyncRequestResponseHandlerFactory as RestRequestHandler"); }
Source:
protected void maybeSetNotificationBadge(NotificationData data) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE && data.badgeCount > 0) { builder.setNumber(data.badgeCount); } }

Target:
protected void maybeSetNotificationBadge(NotificationData data) { if (data.badgeCount > 0) { builder.setNumber(data.badgeCount); } }
Source:
private ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> getMappings(TransportClient client, GetMappingsRequest request) { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(maxRetryTime, 2.0) .run("getMappings", () -> { return client.admin() .indices() .getMappings(request) .actionGet(requestTimeout.toMillis()) .getMappings(); }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> getMappings(TransportClient client, GetMappingsRequest request) { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(maxRetryTime) .run("getMappings", () -> client.admin() .indices() .getMappings(request) .actionGet(requestTimeout.toMillis()) .getMappings()); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public LifeCycleMethods get(Class<?> clazz) { LifeCycleMethods methods = map.get(clazz); if (methods == null) { synchronized (this) { methods = map.get(clazz); if(methods == null) { methods = new LifeCycleMethods(clazz); map.put(clazz, methods); } } } return methods; }

Target:
public LifeCycleMethods get(Class<?> clazz) { return map.computeIfAbsent(clazz, (c) -> new LifeCycleMethods(c)); }
Source:
private PhpCfgBlock buildIfStatement(IfStatementTree tree, PhpCfgBlock successor) { PhpCfgBlock elseBlock = successor; if (tree.elseClause() != null) { elseBlock = buildSubFlow(tree.elseClause().statements(), successor); } PhpCfgBlock falseSuccessor = elseBlock; if (!tree.elseifClauses().isEmpty()) { List<ElseifClauseTree> elseIfs = tree.elseifClauses(); for (int i = elseIfs.size() - 1; i >= 0; i--) { falseSuccessor = buildElseIfStatement(elseIfs.get(i), successor, falseSuccessor); } } PhpCfgBlock thenBlock = buildSubFlow(tree.statements(), successor); PhpCfgBranchingBlock conditionBlock = createBranchingBlock(tree, thenBlock, falseSuccessor); conditionBlock.addElement(tree.condition().expression()); return conditionBlock; }

Target:
private PhpCfgBlock buildIfStatement(IfStatementTree tree, PhpCfgBlock successor) { PhpCfgBlock falseBlock = successor; if (tree.elseClause() != null) { falseBlock = buildSubFlow(tree.elseClause().statements(), successor); } if (!tree.elseifClauses().isEmpty()) { for (ElseifClauseTree elseifClause : Lists.reverse(tree.elseifClauses())) { falseBlock = buildElseIfStatement(elseifClause, successor, falseBlock); } } PhpCfgBlock trueBlock = buildSubFlow(tree.statements(), successor); PhpCfgBranchingBlock conditionBlock = createBranchingBlock(tree, trueBlock, falseBlock); conditionBlock.addElement(tree.condition().expression()); return conditionBlock; }
Source:
public void quietDownShouldSuccessOnAlreadyQuietDownedJenkins() throws Exception { j.jenkins.get().doQuietDown(); assertJenkinsInQuietMode(); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER) .invoke(); assertThat(result, succeededSilently()); assertJenkinsInQuietMode(); }

Target:
public void quietDownShouldSuccessOnAlreadyQuietDownedJenkins() throws Exception { j.jenkins.doQuietDown(); assertJenkinsInQuietMode(); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER) .invoke(); assertThat(result, succeededSilently()); assertJenkinsInQuietMode(); }
Source:
public void addMembersToGroup() throws Exception { System.out.println(CLASS_NAME + "addMembersToGroup"); vo = setUpVo(); setUpGroup(vo); Attribute synchroAttr = new Attribute(perun.getAttributesManager().getAttributeDefinition(sess, GroupsManager.GROUPSYNCHROENABLED_ATTRNAME)); synchroAttr.setValue("false"); perun.getAttributesManager().setAttribute(sess, group, synchroAttr); List<Member> members = Arrays.asList(setUpMember(vo), setUpMember(vo), setUpMember(vo)); groupsManager.addMembers(sess, group, members); List<Member> membersFromDb = groupsManager.getGroupMembers(sess, group); for (Member member : members) { assertTrue("List of members should contain member", membersFromDb.contains(member)); } }

Target:
public void addMembersToGroup() throws Exception { System.out.println(CLASS_NAME + "addMembersToGroup"); vo = setUpVo(); setUpGroup(vo); List<Member> members = Arrays.asList(setUpMember(vo), setUpMember(vo), setUpMember(vo)); groupsManager.addMembers(sess, group, members); List<Member> membersFromDb = groupsManager.getGroupMembers(sess, group); for (Member member : members) { assertTrue("List of members should contain member", membersFromDb.contains(member)); } }
Source:
public void init() { initState(); setReportBaseUrl((String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.RedirectServletReportsPage)); parseReportsXML(); }

Target:
public void init() { initState(); setReportBaseUrl((String) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.RedirectServletReportsPage)); if (!reportBaseUrl.trim().isEmpty()) { parseReportsXML(); } else { setXmlInitialized(); } }
Source:
public boolean isEmpty() { for ( int i = 0; i < keys.length; i = i + width ) { if ( keys[i] != NOT_IN_USE ) { return false; } } return true; }

Target:
public boolean isEmpty() { return numberOfEntries == 0; }
Source:
public VcrMetrics(MetricRegistry registry) { this.registry = registry; blobEncryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionCount")); blobDecryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionCount")); blobEncryptionErrorCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionErrorCount")); blobDecryptionErrorCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionErrorCount")); blobEncryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionTime")); blobDecryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionTime")); blobUploadSkippedCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobUploadSkippedCount")); updateTtlNotSetError = registry.counter(MetricRegistry.name(CloudBlobStore.class, "UpdateTtlNotSetError")); addPartitionErrorCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "AddPartitionErrorCount")); removePartitionErrorCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "RemovePartitionErrorCount")); tokenReloadWarnCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "TokenReloadWarnCount")); }

Target:
public VcrMetrics(MetricRegistry registry) { this.registry = registry; blobEncryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionCount")); blobDecryptionCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionCount")); blobEncryptionErrorCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionErrorCount")); blobDecryptionErrorCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionErrorCount")); blobEncryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobEncryptionTime")); blobDecryptionTime = registry.timer(MetricRegistry.name(CloudBlobStore.class, "BlobDecryptionTime")); blobUploadSkippedCount = registry.counter(MetricRegistry.name(CloudBlobStore.class, "BlobUploadSkippedCount")); updateTtlNotSetError = registry.counter(MetricRegistry.name(CloudBlobStore.class, "UpdateTtlNotSetError")); addPartitionErrorCount = registry.counter(MetricRegistry.name(CloudBackupManager.class, "AddPartitionErrorCount")); removePartitionErrorCount = registry.counter(MetricRegistry.name(CloudBackupManager.class, "RemovePartitionErrorCount")); tokenReloadWarnCount = registry.counter(MetricRegistry.name(CloudBackupManager.class, "TokenReloadWarnCount")); }
Source:
protected Object writeReplace() { Channel currentChannel = Channel.current(); if (currentChannel == null) return null; return remoteProxyFor(currentChannel.export(GitClient.class, this)); }

Target:
protected Object writeReplace() throws java.io.ObjectStreamException { Channel currentChannel = Channel.current(); if (currentChannel == null) throw new java.io.WriteAbortedException("No current channel", new java.lang.NullPointerException()); return remoteProxyFor(currentChannel.export(GitClient.class, this)); }
Source:
public Object getValue(final Object element, final String property) { VarDeclaration var = (VarDeclaration) element; switch (property) { case IV_NAME: return var.getName(); case IV_TYPE: for (int i = 0; i < typeDropDown.getItems().length; i++) { if (typeDropDown.getItems()[i].equals(var.getType().getName())) { return i; } } return 0; case IV_COMMENT: return var.getComment(); case IV_ARRAY: return Integer.toString(var.getArraySize()); default: return var.getValue().getValue(); } }

Target:
public Object getValue(final Object element, final String property) { VarDeclaration var = (VarDeclaration) element; switch (property) { case IV_NAME: return var.getName(); case IV_TYPE: return Arrays.asList(typeDropDown.getItems()).indexOf(var.getType().getName()); case IV_COMMENT: return var.getComment(); case IV_ARRAY: return Integer.toString(var.getArraySize()); default: return var.getValue().getValue(); } }
Source:
private Map<String, Pair<String, String>> getSharedLocksForVmDisk() { Map<String, Pair<String, String>> lockMap = new HashMap<>(); if (getDiskImage() != null) { vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); if (!vmsForDisk.isEmpty()) { for (Pair<VM, VmDevice> pair : vmsForDisk) { lockMap.put(pair.getFirst().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_LOCKED)); } } } return lockMap; }

Target:
private Map<String, Pair<String, String>> getSharedLocksForVmDisk() { Map<String, Pair<String, String>> lockMap = new HashMap<>(); if (getDiskImage() != null) { List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); if (!vmsForDisk.isEmpty()) { for (Pair<VM, VmDevice> pair : vmsForDisk) { lockMap.put(pair.getFirst().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_LOCKED)); } } } return lockMap; }
Source:
private String getStatsSection(ExecutionHandlerContext context) { final RedisStats redisStats = context.getRedisStats(); String instantaneous_input_kbps = new DecimalFormat("0.00") .format(redisStats .getNetworkKiloBytesReadOverLastSecond()); final String STATS_STRING = "# Stats\r\n" + "total_commands_processed:" + redisStats.getCommandsProcessed() + "\r\n" + "instantaneous_ops_per_sec:" + redisStats.getOpsPerformedOverLastSecond() + "\r\n" + "total_net_input_bytes:" + redisStats.getTotalNetworkBytesRead() + "\r\n" + "instantaneous_input_kbps:" + instantaneous_input_kbps + "\r\n" + "total_connections_received:" + redisStats.getConnectionsReceived() + "\r\n" + "keyspace_hits:" + redisStats.getKeyspaceHits() + "\r\n" + "keyspace_misses:" + redisStats.getKeyspaceMisses() + "\r\n" + "evicted_keys:0\r\n" + "rejected_connections:0\r\n"; return STATS_STRING; }

Target:
private String getStatsSection(ExecutionHandlerContext context) { final RedisStats redisStats = context.getRedisStats(); String instantaneous_input_kbps = decimalFormat.format(redisStats .getNetworkKiloBytesReadOverLastSecond()); final String STATS_STRING = "# Stats\r\n" + "total_commands_processed:" + redisStats.getCommandsProcessed() + "\r\n" + "instantaneous_ops_per_sec:" + redisStats.getOpsPerformedOverLastSecond() + "\r\n" + "total_net_input_bytes:" + redisStats.getTotalNetworkBytesRead() + "\r\n" + "instantaneous_input_kbps:" + instantaneous_input_kbps + "\r\n" + "total_connections_received:" + redisStats.getConnectionsReceived() + "\r\n" + "keyspace_hits:" + redisStats.getKeyspaceHits() + "\r\n" + "keyspace_misses:" + redisStats.getKeyspaceMisses() + "\r\n" + "evicted_keys:0\r\n" + "rejected_connections:0\r\n"; return STATS_STRING; }
Source:
private static void checkExceptions(DataTable dataTable, PinotSplit split) { Map<String, String> metadata = dataTable.getMetadata(); List<String> exceptions = new ArrayList<>(); metadata.forEach((k, v) -> { if (k.startsWith(DataTable.EXCEPTION_METADATA_KEY)) { exceptions.add(v); } }); if (exceptions.size() > 0) { throw new PinotException(PinotErrorCode.PINOT_EXCEPTION, split.getSegmentPql(), String.format("Encountered %d pinot exceptions for split %s: %s", exceptions.size(), split, exceptions)); } }

Target:
private static void checkExceptions(DataTable dataTable, PinotSplit split) { Map<String, String> metadata = dataTable.getMetadata(); List<String> exceptions = new ArrayList<>(); metadata.forEach((k, v) -> { if (k.startsWith(DataTable.EXCEPTION_METADATA_KEY)) { exceptions.add(v); } }); if (!exceptions.isEmpty()) { throw new PinotException(PinotErrorCode.PINOT_EXCEPTION, split.getSegmentPql(), String.format("Encountered %d pinot exceptions for split %s: %s", exceptions.size(), split, exceptions)); } }
Source:
public int isApplicable(VElement vElement, ViewModelContext context) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; IValueProperty valueProperty; try { valueProperty = Activator.getDefault().getEMFFormsDatabinding() .getValueProperty(control.getDomainModelReference(), context.getDomainModel()); } catch (final DatabindingFailedException ex) { Activator.getDefault().getReportService().report(new DatabindingFailedReport(ex)); return NOT_APPLICABLE; } catch (final IllegalArgumentException ex) { Activator.getDefault().getReportService().report(new AbstractReport(ex)); return NOT_APPLICABLE; } final EStructuralFeature feature = (EStructuralFeature) valueProperty.getValueType(); return isApplicable(feature); }

Target:
public int isApplicable(VElement vElement, ViewModelContext context) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; if (control.getDomainModelReference() == null) { return NOT_APPLICABLE; } IValueProperty valueProperty; try { valueProperty = Activator.getDefault().getEMFFormsDatabinding() .getValueProperty(control.getDomainModelReference(), context.getDomainModel()); } catch (final DatabindingFailedException ex) { Activator.getDefault().getReportService().report(new DatabindingFailedReport(ex)); return NOT_APPLICABLE; } catch (final IllegalArgumentException ex) { Activator.getDefault().getReportService().report(new AbstractReport(ex)); return NOT_APPLICABLE; } final EStructuralFeature feature = (EStructuralFeature) valueProperty.getValueType(); return isApplicable(feature); }
Source:
public Block distinct(@TypeParameter("E") Type type, @SqlType("array(E)") Block array) { int length = 0; if (array.getPositionCount() < 2) { return array; } if (array.getPositionCount() == 2) { if (type.equalTo(array, 0, array, 1)) { return array.getSingleValueBlock(0); } else { return array; } } TypedSet typedSet = new TypedSet(type, array.getPositionCount(), "array_distinct"); BlockBuilder distinctElementBlockBuilder = pageBuilder.getBlockBuilder(0); for (int i = 0; i < array.getPositionCount(); i++) { if (!typedSet.contains(array, i)) { typedSet.add(array, i); length++; type.appendTo(array, i, distinctElementBlockBuilder); } } if (pageBuilder.isFull()) { pageBuilder.reset(); } pageBuilder.declarePositions(length); return distinctElementBlockBuilder.getRegion(distinctElementBlockBuilder.getPositionCount() - length, length); }

Target:
public Block distinct(@TypeParameter("E") Type type, @SqlType("array(E)") Block array) { if (array.getPositionCount() < 2) { return array; } if (array.getPositionCount() == 2) { if (type.equalTo(array, 0, array, 1)) { return array.getSingleValueBlock(0); } else { return array; } } TypedSet typedSet = new TypedSet(type, array.getPositionCount(), "array_distinct"); int distinctCount = 0; if (pageBuilder.isFull()) { pageBuilder.reset(); } BlockBuilder distinctElementBlockBuilder = pageBuilder.getBlockBuilder(0); for (int i = 0; i < array.getPositionCount(); i++) { if (!typedSet.contains(array, i)) { typedSet.add(array, i); distinctCount++; type.appendTo(array, i, distinctElementBlockBuilder); } } pageBuilder.declarePositions(distinctCount); return distinctElementBlockBuilder.getRegion(distinctElementBlockBuilder.getPositionCount() - distinctCount, distinctCount); }
Source:
public static void main(final String[] args) throws Exception { Properties jobProps = HadoopSecureWrapperUtils.loadAzkabanProps(); HadoopConfigurationInjector.injectResources(new Props(null, jobProps)); final Configuration conf = new Configuration(); UserGroupInformation.setConfiguration(conf); securityEnabled = UserGroupInformation.isSecurityEnabled(); if (HadoopSecureWrapperUtils.shouldProxy(jobProps)) { UserGroupInformation proxyUser = null; String userToProxy = jobProps.getProperty("user.to.proxy"); if (securityEnabled) { proxyUser = HadoopSecureWrapperUtils.createSecurityEnabledProxyUser(userToProxy, logger); } else { proxyUser = UserGroupInformation.createRemoteUser(userToProxy); } logger.info("Proxying to execute job. Proxied as user " + userToProxy); proxyUser.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { runSpark(args); return null; } }); } else { logger.info("Not proxying to execute job. "); runSpark(args); } }

Target:
public static void main(final String[] args) throws Exception { Properties jobProps = HadoopSecureWrapperUtils.loadAzkabanProps(); HadoopConfigurationInjector.injectResources(new Props(null, jobProps)); final Configuration conf = new Configuration(); UserGroupInformation.setConfiguration(conf); securityEnabled = UserGroupInformation.isSecurityEnabled(); if (HadoopSecureWrapperUtils.shouldProxy(jobProps)) { UserGroupInformation proxyUser = null; String userToProxy = jobProps.getProperty(HadoopSecurityManager.USER_TO_PROXY); if (securityEnabled) { proxyUser = HadoopSecureWrapperUtils.createSecurityEnabledProxyUser(userToProxy, logger); } else { proxyUser = UserGroupInformation.createRemoteUser(userToProxy); } logger.info("Proxying to execute job. Proxied as user " + userToProxy); proxyUser.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { runSpark(args); return null; } }); } else { logger.info("Not proxying to execute job. "); runSpark(args); } }
Source:
public void testHttpAnnouncement() { final StaticAnnouncementHttpServerInfoImpl httpServerInfo = new StaticAnnouncementHttpServerInfoImpl( URI.create("<LINK_0>"), URI.create("<LINK_1>"), null, null); Injector injector = Guice.createInjector( new TestingDiscoveryModule(), binder -> { binder.bind(AnnouncementHttpServerInfo.class).toInstance(httpServerInfo); DiscoveryBinder.discoveryBinder(binder).bindHttpAnnouncement("apple"); }); ServiceAnnouncement announcement = serviceAnnouncement("apple") .addProperty("http", httpServerInfo.getHttpUri().toASCIIString()) .addProperty("http-external", httpServerInfo.getHttpExternalUri().toASCIIString()) .build(); Set<ServiceAnnouncement> announcements = injector.getInstance(Key.get(new TypeLiteral<Set<ServiceAnnouncement>>() { })); assertAnnouncement(announcements, announcement); }

Target:
public void testHttpAnnouncement() { final StaticAnnouncementHttpServerInfoImpl httpServerInfo = new StaticAnnouncementHttpServerInfoImpl( URI.create("<LINK_0>"), URI.create("<LINK_1>"), null, null); Injector injector = Guice.createInjector( new TestingDiscoveryModule(), binder -> { binder.bind(AnnouncementHttpServerInfo.class).toInstance(httpServerInfo); discoveryBinder(binder).bindHttpAnnouncement("apple"); }); ServiceAnnouncement announcement = serviceAnnouncement("apple") .addProperty("http", httpServerInfo.getHttpUri().toASCIIString()) .addProperty("http-external", httpServerInfo.getHttpExternalUri().toASCIIString()) .build(); Set<ServiceAnnouncement> announcements = injector.getInstance(Key.get(new TypeLiteral<Set<ServiceAnnouncement>>() { })); assertAnnouncement(announcements, announcement); }
Source:
public Task<AuthResult> then(@NonNull Task<AuthResult> task) { final AuthResult authResult = task.getResult(); FirebaseUser firebaseUser = authResult.getUser(); String name = firebaseUser.getDisplayName(); Uri photoUri = firebaseUser.getPhotoUrl(); if (!TextUtils.isEmpty(name) && photoUri != null) { return Tasks.forResult(authResult); } User user = mResponse.getUser(); if (TextUtils.isEmpty(name)) { name = user.getName(); } if (photoUri == null) { photoUri = user.getPhotoUri(); } return firebaseUser.updateProfile( new UserProfileChangeRequest.Builder() .setDisplayName(name) .setPhotoUri(photoUri) .build()) .continueWithTask(new Continuation<Void, Task<AuthResult>>() { @Override public Task<AuthResult> then(@NonNull Task<Void> task) { return Tasks.forResult(authResult); } }); }

Target:
public Task<AuthResult> then(@NonNull Task<AuthResult> task) { final AuthResult authResult = task.getResult(); FirebaseUser firebaseUser = authResult.getUser(); String name = firebaseUser.getDisplayName(); Uri photoUri = firebaseUser.getPhotoUrl(); if (!TextUtils.isEmpty(name) && photoUri != null) { return Tasks.forResult(authResult); } User user = mResponse.getUser(); if (TextUtils.isEmpty(name)) { name = user.getName(); } if (photoUri == null) { photoUri = user.getPhotoUri(); } return firebaseUser.updateProfile( new UserProfileChangeRequest.Builder() .setDisplayName(name) .setPhotoUri(photoUri) .build()) .addOnFailureListener(new TaskFailureLogger(TAG, "Error updating profile")) .continueWithTask(new Continuation<Void, Task<AuthResult>>() { @Override public Task<AuthResult> then(@NonNull Task<Void> task) { return Tasks.forResult(authResult); } }); }
Source:
public void toXmlTestForAudio() { String xml = "<media xmlns='urn:xmpp:media-element'>" + "<uri type='audio/x-wav'>" + "<LINK_0>" + "</uri>" + "<uri type='audio/ogg; codecs=speex'>" + "cid:sha1+a15a505e360702b79c75a5f67773072ed392f52a@bob.xmpp.org" + "</uri>" + "<uri type='audio/mpeg'>" + "<LINK_1>" + "</uri>" + "</media>"; URI uri1 = null; URI uri2 = null; URI uri3 = null; try { uri1 = new URI("<LINK_0>"); uri2 = new URI("cid:sha1+a15a505e360702b79c75a5f67773072ed392f52a@bob.xmpp.org"); uri3 = new URI("<LINK_1>"); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI"); } List<URINode> uriNodeList = new ArrayList<URINode>(); URINode urinode1 = new URINode(MediaType.audio_xwav, uri1); URINode urinode2 = new URINode(MediaType.audio_ogg, "codecs=speex", uri2); URINode urinode3 = new URINode(MediaType.audio_mpeg, uri3); uriNodeList.add(urinode1); uriNodeList.add(urinode2); uriNodeList.add(urinode3); MediaElement mediaElement = new MediaElement(uriNodeList); assertXmlSimilar(xml, mediaElement.toXML().toString()); }

Target:
public void toXmlTestForAudio() throws URISyntaxException { String xml = "<media xmlns='urn:xmpp:media-element'>" + "<uri type='audio/x-wav'>" + "<LINK_0>" + "</uri>" + "<uri type='audio/ogg; codecs=speex'>" + "cid:sha1+a15a505e360702b79c75a5f67773072ed392f52a@bob.xmpp.org" + "</uri>" + "<uri type='audio/mpeg'>" + "<LINK_1>" + "</uri>" + "</media>"; URI uri1 = new URI("<LINK_0>"); URI uri2 = new URI("cid:sha1+a15a505e360702b79c75a5f67773072ed392f52a@bob.xmpp.org"); URI uri3 = new URI("<LINK_1>"); List<URINode> uriNodeList = new ArrayList<URINode>(); URINode urinode1 = new URINode("audio/x-wav", uri1); URINode urinode2 = new URINode("audio/ogg", "codecs=speex", uri2); URINode urinode3 = new URINode("audio/mpeg", uri3); uriNodeList.add(urinode1); uriNodeList.add(urinode2); uriNodeList.add(urinode3); MediaElement mediaElement = new MediaElement(uriNodeList); assertXmlSimilar(xml, mediaElement.toXML().toString()); }
Source:
public int getSSLPort() { for (Port extraPort : ports) { if (extraPort.getPortType() == PortType.SSL) { return extraPort.getPortNo(); } } return -1; }

Target:
public int getSSLPort() { Port sslPort = ports.get(PortType.SSL); if (sslPort != null) { return sslPort.getPort(); } throw new IllegalStateException("No SSL Port Exists for Server " + host + ":" + port); }