auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Builder addRequestHandler(RequestHandler requestHandler) { if (requestHandler == null) { throw new IllegalArgumentException("RequestHandler must not be null."); } if (requestHandlers == null) { requestHandlers = new ArrayList(); } if (requestHandlers.contains(requestHandler)) { throw new IllegalStateException("RequestHandler already registered."); } requestHandlers.add(requestHandler); return this; }

Target:
public Builder addRequestHandler(RequestHandler requestHandler) { if (requestHandler == null) { throw new IllegalArgumentException("RequestHandler must not be null."); } if (requestHandlers == null) { requestHandlers = new ArrayList<RequestHandler>(); } if (requestHandlers.contains(requestHandler)) { throw new IllegalStateException("RequestHandler already registered."); } requestHandlers.add(requestHandler); return this; }
Source:
protected void performPlugCommnad(VDSCommandType commandType, DiskImage diskImage, VmDevice vmDevice, boolean isUpdateDb) { Backend.getInstance().getResourceManager().RunVdsCommand( commandType, new HotPlugDiskVDSParameters(getVm().getrun_on_vds().getValue(), getVm().getId(), diskImage, vmDevice)); if (isUpdateDb) { vmDevice.setIsPlugged(!vmDevice.getIsPlugged()); getVmDeviceDao().update(vmDevice); } setSucceeded(true); }

Target:
protected void performPlugCommnad(VDSCommandType commandType, DiskImage diskImage, VmDevice vmDevice, boolean isUpdateDb) { runVdsCommand(commandType, new HotPlugDiskVDSParameters(getVm().getrun_on_vds().getValue(), getVm().getId(), diskImage, vmDevice)); if (isUpdateDb) { vmDevice.setIsPlugged(!vmDevice.getIsPlugged()); getVmDeviceDao().update(vmDevice); } setSucceeded(true); }
Source:
public void should_fail_list_asserts_on_non_list_objects_even_with_asList() { Object nonList = new Object(); thrown.expectAssertionErrorWithMessageContaining(format("an instance of:%n <java.util.List>%nbut was instance of:%n <java.lang.Object>")); assertThat(nonList).asList().isSorted(); }

Target:
public void should_fail_list_asserts_on_non_list_objects_even_with_asList() { Object nonList = new Object(); thrown.expectAssertionErrorWithMessageContaining("an instance of:%n <java.util.List>%nbut was instance of:%n <java.lang.Object>"); assertThat(nonList).asList().isSorted(); }
Source:
public AbfsOutputStream( final AbfsClient client, final String path, final long position, final int bufferSize, final boolean supportFlush, final boolean disableOutputStreamFlush) { this.client = client; this.path = path; this.position = position; this.closed = false; this.supportFlush = supportFlush; this.disableOutputStreamFlush = disableOutputStreamFlush; this.lastError = null; this.lastFlushOffset = 0; this.bufferSize = bufferSize; this.buffer = byteBufferPool.getBuffer(false, bufferSize).array(); this.bufferIndex = 0; this.writeOperations = new ConcurrentLinkedDeque<>(); this.maxConcurrentRequestCount = 4 * Runtime.getRuntime().availableProcessors(); this.threadExecutor = new ThreadPoolExecutor(maxConcurrentRequestCount, maxConcurrentRequestCount, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); this.completionService = new ExecutorCompletionService<AuthorizationStatus>(this.threadExecutor); }

Target:
public AbfsOutputStream( final AbfsClient client, final String path, final long position, final int bufferSize, final boolean supportFlush, final boolean disableOutputStreamFlush) { this.client = client; this.path = path; this.position = position; this.closed = false; this.supportFlush = supportFlush; this.disableOutputStreamFlush = disableOutputStreamFlush; this.lastError = null; this.lastFlushOffset = 0; this.bufferSize = bufferSize; this.buffer = byteBufferPool.getBuffer(false, bufferSize).array(); this.bufferIndex = 0; this.writeOperations = new ConcurrentLinkedDeque<>(); this.maxConcurrentRequestCount = 4 * Runtime.getRuntime().availableProcessors(); this.threadExecutor = new ThreadPoolExecutor(maxConcurrentRequestCount, maxConcurrentRequestCount, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); this.completionService = new ExecutorCompletionService<>(this.threadExecutor); }
Source:
public Response load(String payload) { try { loadHandler.handle(extractRegisterNameFromRequest(), payload); return Response.ok().build(); } catch (Exception e) { if (e.getCause() instanceof EntryValidator.EntryValidationException) { EntryValidator.EntryValidationException errorCause = (EntryValidator.EntryValidationException) e.getCause(); return Response.status(400).entity(errorCause.getMessage() + "\nEntity: '" + errorCause.getEntry().toString() + "'").build(); } else { return Response.serverError().entity(e).build(); } } }

Target:
public Response load(String payload) { try { loadHandler.handle(extractRegisterNameFromRequest(), payload); return Response.ok().build(); } catch (EntryValidationException e) { return Response.status(400).entity(e.getMessage() + " Error entry: '" + e.getEntry().toString() + "'").build(); } catch (Exception e) { return Response.serverError().entity(e).build(); } }
Source:
public Run getByAlias(String alias) throws IOException { Criteria criteria = currentSession().createCriteria(RunImpl.class); criteria.add(Restrictions.eq("alias", alias)); @SuppressWarnings("unchecked") List<Run> records = criteria.list(); if (records.size() == 1) { return records.iterator().next(); } else { throw new IOException("Found more than one run by this name"); } }

Target:
public Run getByAlias(String alias) throws IOException { Criteria criteria = currentSession().createCriteria(RunImpl.class); criteria.add(Restrictions.eq("alias", alias)); return (Run) criteria.uniqueResult(); }
Source:
public void jetWordCount() { try { dataStoreOut = DataStoreFactory.getDataStore(Long.class, ResultPageView.class, new Configuration()); } catch (GoraException e) { e.printStackTrace(); } Query<Long, ResultPageView> query = dataStoreOut.newQuery(); JetEngine<Long, ResultPageView, Long, ResultPageView> jetEngine = new JetEngine<>(); Pattern delimiter = Pattern.compile("\\W+"); Pipeline p = Pipeline.create(); p.drawFrom(jetEngine.createDataSource(dataStoreOut, query)) .flatMap(e -> traverseArray(delimiter.split(e.getValue().getUrl().toString().toLowerCase()))) .filter(word -> !word.isEmpty()) .groupingKey(wholeItem()) .aggregate(counting()) .drainTo(Sinks.map("COUNTS")); JetInstance jet = Jet.newJetInstance();; try { System.out.print("\nCounting words... "); jet.newJob(p).join(); IMap<String, Long> counts = jet.getMap("COUNTS"); if (counts.get("the") != 2) { throw new AssertionError("Wrong count of 'the'"); } System.out.println("Count of 'the' is valid"); } finally { Jet.shutdownAll(); } }

Target:
public void jetWordCount() throws GoraException { dataStoreOut = DataStoreFactory.getDataStore(Long.class, ResultPageView.class, utility.getConfiguration()); Query<Long, ResultPageView> query = dataStoreOut.newQuery(); JetEngine<Long, ResultPageView, Long, ResultPageView> jetEngine = new JetEngine<>(); Pattern delimiter = Pattern.compile("\\W+"); Pipeline p = Pipeline.create(); p.drawFrom(jetEngine.createDataSource(dataStoreOut, query)) .flatMap(e -> traverseArray(delimiter.split(e.getValue().getUrl().toString()))) .filter(word -> !word.isEmpty()) .groupingKey(wholeItem()) .aggregate(counting()) .drainTo(Sinks.map("COUNTS")); JetInstance jet = Jet.newJetInstance();; jet.newJob(p).join(); IMap<String, Long> counts = jet.getMap("COUNTS"); assertEquals(3L, (long)counts.get("the")); }
Source:
protected void render0(FunctionRenderContext context) { Object[] jsonPathElements = new Object[context.getArgumentsSize() - 2]; for (int i = 2; i < context.getArgumentsSize(); i++) { try { jsonPathElements[i - 2] = Integer.parseInt(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } catch (NumberFormatException e) { jsonPathElements[i - 2] = JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i)); } } context.addChunk("(select "); context.addChunk("json_mergepatch("); context.addArgument(0); context.addChunk(",'"); for (int i = 0; i < jsonPathElements.length; i++) { startJsonPathElement(context, jsonPathElements, i); } context.addChunk("' || "); context.addChunk("column_value"); context.addChunk(" || '"); for (int i = jsonPathElements.length - 1; i >= 0; i--) { endJsonPathElement(context, jsonPathElements, i); } context.addChunk("')"); context.addChunk(" from table(sys.ODCIVARCHAR2LIST("); context.addArgument(1); context.addChunk(")))"); }

Target:
protected void render0(FunctionRenderContext context) { List<Object> jsonPathElements = AbstractJsonGetFunction.retrieveJsonPathElements(context, 2); context.addChunk("(select "); context.addChunk("json_mergepatch("); context.addArgument(0); context.addChunk(",'"); for (int i = 0; i < jsonPathElements.size(); i++) { startJsonPathElement(context, jsonPathElements, i); } context.addChunk("' || "); context.addChunk("column_value"); context.addChunk(" || '"); for (int i = jsonPathElements.size() - 1; i >= 0; i--) { endJsonPathElement(context, jsonPathElements, i); } context.addChunk("')"); context.addChunk(" from table(sys.ODCIVARCHAR2LIST("); context.addArgument(1); context.addChunk(")))"); }
Source:
public void testLimitOfSalesforceBulQueryReader() throws Exception { SalesforceInputProperties properties = createCommonSalesforceInputPropertiesForModule(); SalesforceDataprepSource source = new SalesforceDataprepSource(); source.initialize(null, properties); source.validate(null); properties.getDatasetProperties().selectColumnIds.setValue(Arrays.asList("IsDeleted", "Id", "Name")); try (Reader reader = source.createReader(null);) { ((SalesforceBulkQueryReader) reader).setLimit(1); boolean available = reader.start(); available = reader.advance(); IndexedRecord record = (IndexedRecord) reader.getCurrent(); assertEquals(3, record.getSchema().getFields().size()); available = reader.advance(); } }

Target:
public void testLimitOfSalesforceBulQueryReader() throws Exception { SalesforceInputProperties properties = createCommonSalesforceInputPropertiesForModule(); SalesforceDataprepSource source = new SalesforceDataprepSource(); source.initialize(null, properties); source.validate(null); properties.getDatasetProperties().selectColumnIds.setValue(Arrays.asList("IsDeleted", "Id", "Name")); try (Reader reader = source.createReader(null);) { ((SalesforceBulkQueryReader) reader).setLimit(1); reader.start(); reader.advance(); IndexedRecord record = (IndexedRecord) reader.getCurrent(); assertEquals(3, record.getSchema().getFields().size()); try{ reader.advance(); fail(); } catch (IOException e) { } } }
Source:
private static Block serializeStruct(Type type, BlockBuilder builder, Object object) { if (object == null) { requireNonNull(builder, "parent builder is null").appendNull(); return null; } List<Type> typeParameters = type.getTypeParameters(); BlockBuilder currentBuilder; boolean builderSynthesized = false; if (builder == null) { builderSynthesized = true; builder = type.createBlockBuilder(null, 1); } currentBuilder = builder.beginBlockEntry(); for (int i = 0; i < typeParameters.size(); i++) { Optional<String> fieldName = type.getTypeSignature().getParameters().get(i).getNamedTypeSignature().getName(); String name = ""; if (fieldName.isPresent()) { name = fieldName.get().toLowerCase(ENGLISH); } Object value = ((Map) object).get(name); serializeObject(typeParameters.get(i), currentBuilder, value); } builder.closeEntry(); if (builderSynthesized) { return (Block) type.getObject(builder, 0); } else { return null; } }

Target:
private static Block serializeStruct(Type type, BlockBuilder builder, Object object) { if (object == null) { requireNonNull(builder, "builder is null"); builder.appendNull(); return null; } boolean builderSynthesized = false; if (builder == null) { builderSynthesized = true; builder = type.createBlockBuilder(null, 1); } BlockBuilder currentBuilder = builder.beginBlockEntry(); List<Type> typeParameters = type.getTypeParameters(); for (int i = 0; i < typeParameters.size(); i++) { Optional<String> fieldName = type.getTypeSignature().getParameters().get(i).getNamedTypeSignature().getName(); String name = ""; if (fieldName.isPresent()) { name = fieldName.get().toLowerCase(ENGLISH); } Object value = ((Map) object).get(name); serializeObject(typeParameters.get(i), currentBuilder, value); } builder.closeEntry(); if (builderSynthesized) { return (Block) type.getObject(builder, 0); } return null; }
Source:
public void writeDoesNotPopulateTimestampCache() { Transaction transaction = txMgr.runTaskWithRetry(txn -> { put(txn, TEST_TABLE, "row", "column", "test"); return txn; }); assertThat(timestampCache.getCommitTimestampIfPresent(transaction.getTimestamp())).isNull(); }

Target:
public void writeDoesNotPopulateTimestampCache() { Long writerStartTimestamp = txMgr.runTaskWithRetry(txn -> { put(txn, TEST_TABLE, "row", "column", "test"); return txn.getTimestamp(); }); assertThat(timestampCache.getCommitTimestampIfPresent(writerStartTimestamp)).isNull(); }
Source:
public void persistParticipantInformation(final ParticipantInformation participantInformation) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.persistParticipantInformation: participantInformation=" + participantInformation); } if (!isRecoverableParticipant(participantInformation.getParticipant())) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.persistParticipantInformation: participant is not recoverable"); } return; } try { final RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); final OutputObjectState state = getParticipantInformationOutputState(participantInformation); final Uid uid = new Uid(participantInformation.getId()); committedParticipants.put(participantInformation.getId(), uid); recoveryStore.write_committed(uid, PARTICIPANT_INFORMATION_RECORD_TYPE, state); } catch (Exception e) { LOG.warn("Failure while persisting participant information.", e); } }

Target:
public void persistParticipantInformation(final ParticipantInformation participantInformation) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.persistParticipantInformation: participantInformation=" + participantInformation); } if (!isRecoverableParticipant(participantInformation.getParticipant())) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.persistParticipantInformation: participant is not recoverable"); } return; } try { final RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); final OutputObjectState state = getParticipantInformationOutputState(participantInformation); final Uid uid = new Uid(participantInformation.getId()); recoveryStore.write_committed(uid, PARTICIPANT_INFORMATION_RECORD_TYPE, state); persistedParticipants.put(participantInformation.getId(), uid); } catch (Exception e) { LOG.warn("Failure while persisting participant information.", e); } }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; SymbolMetadata symbolMetadata = methodTree.symbol().metadata(); boolean hasIgnoreAnnotation = isSilentlyIgnored(symbolMetadata, "org.junit.Ignore"); boolean hasDisabledAnnotation = isSilentlyIgnored(symbolMetadata, "org.junit.jupiter.api.Disabled"); if (hasIgnoreAnnotation || hasDisabledAnnotation) { reportIssue(methodTree.simpleName(), String.format("Either add an explanation about why this test is skipped or remove the " + "\"@%s\" annotation.", hasIgnoreAnnotation ? "Ignore" : "Disabled")); } BlockTree block = methodTree.block(); if (block != null) { block.body().stream() .filter(s -> s.is(Tree.Kind.EXPRESSION_STATEMENT)) .map(s -> ((ExpressionStatementTree) s).expression()) .filter(s -> s.is(Tree.Kind.METHOD_INVOCATION)) .map(MethodInvocationTree.class::cast) .filter(ASSUME_METHODS::matches) .filter(IgnoredTestsCheck::hasConstantOppositeArg) .forEach(mit -> reportIssue(mit, "Either remove this assumption or use an @Ignore or @Disabled annotation in combination with " + "an explanation about why this test is skipped.")); } }

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; SymbolMetadata symbolMetadata = methodTree.symbol().metadata(); boolean hasIgnoreAnnotation = isSilentlyIgnored(symbolMetadata, "org.junit.Ignore"); boolean hasDisabledAnnotation = isSilentlyIgnored(symbolMetadata, "org.junit.jupiter.api.Disabled"); if (hasIgnoreAnnotation || hasDisabledAnnotation) { reportIssue(methodTree.simpleName(), String.format("Either add an explanation about why this test is skipped or remove the " + "\"@%s\" annotation.", hasIgnoreAnnotation ? "Ignore" : "Disabled")); } BlockTree block = methodTree.block(); if (block != null) { block.body().stream() .filter(s -> s.is(Tree.Kind.EXPRESSION_STATEMENT)) .map(s -> ((ExpressionStatementTree) s).expression()) .filter(s -> s.is(Tree.Kind.METHOD_INVOCATION)) .map(MethodInvocationTree.class::cast) .filter(ASSUME_METHODS::matches) .filter(IgnoredTestsCheck::hasConstantOppositeArg) .forEach(mit -> { List<JavaFileScannerContext.Location> secondaryLocation = Collections.singletonList(new JavaFileScannerContext.Location( "A constant boolean value is passed as argument, causing this test to always be skipped.", mit.arguments())); reportIssue(ExpressionUtils.methodName(mit), "This assumption is called with a constant boolean. Either remove it or, to skip " + "this test, use an @Ignore or @Disabled annotation in combination with an explanation about why this test is skipped.", secondaryLocation, null); }); } }
Source:
public TcpClientConnector(int numberOfThreads, int connectTimeoutMillis, int idleTimeout) { this.numberOfThreads = numberOfThreads; this.connectionIdleTimeoutSeconds = idleTimeout; this.connectTimeoutMillis = connectTimeoutMillis; this.listenUri = URI.create(String.format("%s://0.0.0.0:0", getSupportedScheme())); }

Target:
public TcpClientConnector(int numberOfThreads, int connectTimeoutMillis, int idleTimeout) { this.numberOfThreads = numberOfThreads; this.connectionIdleTimeoutSeconds = idleTimeout; this.connectTimeoutMillis = connectTimeoutMillis; this.listenUri = URI.create(String.format("%s://%s:%d", getSupportedScheme(), localSocketAddress.getHostString(), localSocketAddress.getPort())); }
Source:
public ExecutionResult execute(Item item) { ProcessType processType = getProcessType(item); if (getProject().getLanguage() != ECodeLanguage.JAVA || processType == null) { return ExecutionResult.NOTHING_TO_DO; } String[] componentsName = new String[] { "tLDAPConnection", "tLDAPAttributesInput", "tLDAPInput", "tLDAPOutput", "tLDAPRenameEntry" }; IComponentConversion changeAlwaysTrustValue = new IComponentConversion() { public void transform(NodeType node) { ElementParameterType advancedCa = ComponentUtilities.getNodeProperty(node, "ADVANCEDCA"); if(advancedCa != null) { boolean isAdvancedCa = "true".equalsIgnoreCase(advancedCa.getValue()); if(isAdvancedCa) { ComponentUtilities.getNodeProperty(node, "ALWAYS_TRUST").setValue("true"); } } } }; for (String name : componentsName) { IComponentFilter filter = new NameComponentFilter(name); try { ModifyComponentsAction.searchAndModify(item, processType, filter, Arrays .<IComponentConversion> asList(changeAlwaysTrustValue)); } catch (PersistenceException e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } } return ExecutionResult.SUCCESS_WITH_ALERT; }

Target:
public ExecutionResult execute(Item item) { ProcessType processType = getProcessType(item); if (getProject().getLanguage() != ECodeLanguage.JAVA || processType == null) { return ExecutionResult.NOTHING_TO_DO; } String[] componentsName = new String[] { "tLDAPConnection", "tLDAPAttributesInput", "tLDAPInput", "tLDAPOutput", "tLDAPRenameEntry" }; IComponentConversion changeAlwaysTrustValue = new IComponentConversion() { public void transform(NodeType node) { ElementParameterType advancedCa = ComponentUtilities.getNodeProperty(node, "ADVANCEDCA"); if(advancedCa != null) { boolean isAdvancedCa = "true".equalsIgnoreCase(advancedCa.getValue()); if(isAdvancedCa) { ComponentUtilities.getNodeProperty(node, "ALWAYS_TRUST").setValue("true"); } } } }; for (String name : componentsName) { IComponentFilter filter = new NameComponentFilter(name); try { ModifyComponentsAction.searchAndModify(item, processType, filter, Arrays .<IComponentConversion> asList(changeAlwaysTrustValue)); } catch (PersistenceException e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } } return ExecutionResult.SUCCESS_NO_ALERT; }
Source:
public void rewindLifespan(Lifespan lifespan, ConnectorPartitionHandle partitionHandle) { checkState(state == State.INITIALIZED || state == State.SPLITS_ADDED); scheduleGroups.put(lifespan, new ScheduleGroup(partitionHandle)); splitSource.rewind(partitionHandle); }

Target:
public synchronized void rewindLifespan(Lifespan lifespan, ConnectorPartitionHandle partitionHandle) { checkState(state == State.INITIALIZED || state == State.SPLITS_ADDED, "Current state %s is not rewindable", state); scheduleGroups.remove(lifespan); splitSource.rewind(partitionHandle); }
Source:
protected void Perform() { final VM vm = getVm(); final IVdcUser currentUser = getCurrentUser(); final String domainController = currentUser != null ? currentUser.getDomainControler() : ""; final String password = currentUser != null ? currentUser.getPassword() : ""; setSucceeded(Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.VmLogon, new VmLogonVDSCommandParameters(getVdsId(), vm.getvm_guid(), domainController, getUserName(), password)).getSucceeded()); if (getSucceeded() && currentUser != null) { vm.setguest_cur_user_name(currentUser.getUserName()); vm.setguest_cur_user_id(currentUser.getUserId()); DbFacade.getInstance().getVmDynamicDAO().update(vm.getDynamicData()); } }

Target:
protected void Perform() { final VM vm = getVm(); final IVdcUser currentUser = getCurrentUser(); final String domainController = currentUser != null ? currentUser.getDomainControler() : ""; final String password = currentUser != null ? currentUser.getPassword() : ""; final boolean sentToVM = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.VmLogon, new VmLogonVDSCommandParameters(getVdsId(), vm.getvm_guid(), domainController, getUserName(), password)).getSucceeded(); if (sentToVM && currentUser != null) { vm.setguest_cur_user_name(currentUser.getUserName()); vm.setguest_cur_user_id(currentUser.getUserId()); DbFacade.getInstance().getVmDynamicDAO().update(vm.getDynamicData()); } setSucceeded(sentToVM); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("FRAGMENT_TASK (FROM "); sb.append(CoreUtils.hsIdToString(m_coordinatorHSId)); sb.append(") FOR TXN ").append(m_txnId); sb.append(" FOR REPLAY ").append(isForReplay()); sb.append(", SP HANDLE: ").append(TxnEgo.txnIdToString(getSpHandle())); sb.append("\n"); if (m_isReadOnly) sb.append(" READ, COORD "); else sb.append(" WRITE, COORD "); sb.append(CoreUtils.hsIdToString(m_coordinatorHSId)); if (!m_emptyForRestart) { for (FragmentData item : m_items) { sb.append("\n=====\n"); sb.append(item.toString()); } } else { sb.append("\n=====\n"); sb.append(" FRAGMENT EMPTY FOR RESTART SERIALIZATION"); } if (m_isFinal) sb.append("\n THIS IS THE FINAL TASK"); if (m_taskType == USER_PROC) { sb.append("\n THIS IS A USER TASK"); } else if (m_taskType == SYS_PROC_PER_PARTITION) { sb.append("\n THIS IS A SYSPROC RUNNING PER PARTITION"); } else if (m_taskType == SYS_PROC_PER_SITE) { sb.append("\n THIS IS A SYSPROC TASK RUNNING PER EXECUTION SITE"); } else { sb.append("\n UNKNOWN FRAGMENT TASK TYPE"); } if (m_emptyForRestart) sb.append("\n THIS IS A NULL FRAGMENT TASK USED FOR RESTART"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("FRAGMENT_TASK (FROM "); sb.append(CoreUtils.hsIdToString(m_coordinatorHSId)); sb.append(") FOR TXN ").append(TxnEgo.txnIdToString(m_txnId)); sb.append(" FOR REPLAY ").append(isForReplay()); sb.append(", SP HANDLE: ").append(TxnEgo.txnIdToString(getSpHandle())); sb.append("\n"); if (m_isReadOnly) sb.append(" READ, COORD "); else sb.append(" WRITE, COORD "); sb.append(CoreUtils.hsIdToString(m_coordinatorHSId)); if (!m_emptyForRestart) { for (FragmentData item : m_items) { sb.append("\n=====\n"); sb.append(item.toString()); } } else { sb.append("\n=====\n"); sb.append(" FRAGMENT EMPTY FOR RESTART SERIALIZATION"); } if (m_isFinal) sb.append("\n THIS IS THE FINAL TASK"); if (m_taskType == USER_PROC) { sb.append("\n THIS IS A USER TASK"); } else if (m_taskType == SYS_PROC_PER_PARTITION) { sb.append("\n THIS IS A SYSPROC RUNNING PER PARTITION"); } else if (m_taskType == SYS_PROC_PER_SITE) { sb.append("\n THIS IS A SYSPROC TASK RUNNING PER EXECUTION SITE"); } else { sb.append("\n UNKNOWN FRAGMENT TASK TYPE"); } if (m_emptyForRestart) sb.append("\n THIS IS A NULL FRAGMENT TASK USED FOR RESTART"); return sb.toString(); }
Source:
public List<DocumentRevs> getRevisions(String documentId, Collection<String> revisionIds, Collection<String> attsSince, boolean pullAttachmentsInline) { List<OpenRevision> openRevisions = couchClient.getDocWithOpenRevisions(documentId, revisionIds, attsSince, pullAttachmentsInline); List<DocumentRevs> documentRevs = new ArrayList<DocumentRevs>(); for(OpenRevision openRev : openRevisions) { if(openRev instanceof OkOpenRevision) { documentRevs.add(((OkOpenRevision) openRev).getDocumentRevs()); } else { MissingOpenRevision missing = (MissingOpenRevision) openRev; logger.info(String.format(Locale.ENGLISH, "Revision %s for document %s is missing, generating stub.", missing.getRevision(), documentId)); DocumentRevs stub = new DocumentRevs(); stub.setRev(((MissingOpenRevision) openRev).getRevision()); stub.setId(documentId); documentRevs.add(stub); } } return documentRevs; }

Target:
public List<DocumentRevs> getRevisions(String documentId, Collection<String> revisionIds, Collection<String> attsSince, boolean pullAttachmentsInline) { List<OpenRevision> openRevisions = couchClient.getDocWithOpenRevisions(documentId, revisionIds, attsSince, pullAttachmentsInline); List<DocumentRevs> documentRevs = new ArrayList<DocumentRevs>(); for(OpenRevision openRev : openRevisions) { if(openRev instanceof OkOpenRevision) { documentRevs.add(((OkOpenRevision) openRev).getDocumentRevs()); } else { throw new RuntimeException("Missing open revision for document:" + documentId + ", revisions: " + Arrays.asList(revisionIds)); } } return documentRevs; }
Source:
protected boolean isKerboseEnabled() { if (!StringUtils.isAnyEmpty(getProperty(ZEPPELIN_SUBMARINE_AUTH_TYPE)) && getProperty(ZEPPELIN_SUBMARINE_AUTH_TYPE) .equalsIgnoreCase("kerberos")) { return true; } return false; }

Target:
protected boolean isKerboseEnabled() { String authType = getProperty(ZEPPELIN_SUBMARINE_AUTH_TYPE, ""); if (StringUtils.equals(authType, "kerberos")) { return true; } return false; }
Source:
public TimeSeries timeSeries(LogsMessage logsMessage, Double[] output) throws NumberFormatException { Match match = grok().match(logsMessage.getLogLine()); match.captures(); if (match.getEnd() == 0) return null; Map<String, Object> matches = match.toMap(); if (output != null) { if (matches.containsKey(valueLabel)) { output[0] = Double.parseDouble((String) matches.get(valueLabel)); } else { output[0] = null; } } TimeSeries.Builder builder = TimeSeries.newBuilder(); String dynamicName = expandTemplate(metricName, matches); String sourceName = StringUtils.isBlank(hostName) ? logsMessage.hostOrDefault("parsed-logs") : expandTemplate(hostName, matches); Map<String, String> tags = Maps.newTreeMap(); for (int i = 0; i < tagKeys.size(); i++) { String tagKey = tagKeys.get(i); if (tagValues.size() > 0) { String value = expandTemplate(tagValues.get(i), matches); if(value.trim().length() > 0) { tags.put(tagKey, value); } } else { String tagValueLabel = tagValueLabels.get(i); if (!matches.containsKey(tagValueLabel)) { logger.severe("Application error: unparsed tag key."); continue; } String value = (String) matches.get(tagValueLabel); if(value.trim().length() > 0) { tags.put(tagKey, value); } } } builder.setAnnotations(tags); return builder.setMetric(dynamicName).setHost(sourceName).build(); }

Target:
public TimeSeries timeSeries(LogsMessage logsMessage, Double[] output) throws NumberFormatException { Match match = grok().match(logsMessage.getLogLine()); match.captures(); if (match.getEnd() == 0) return null; Map<String, Object> matches = match.toMap(); if (output != null) { if (matches.containsKey(valueLabel)) { output[0] = Double.parseDouble((String) matches.get(valueLabel)); } else { output[0] = null; } } TimeSeries.Builder builder = TimeSeries.newBuilder(); String dynamicName = expandTemplate(metricName, matches); String sourceName = StringUtils.isBlank(hostName) ? logsMessage.hostOrDefault("parsed-logs") : expandTemplate(hostName, matches); Map<String, String> tags = Maps.newTreeMap(); for (int i = 0; i < tagKeys.size(); i++) { String tagKey = tagKeys.get(i); if (tagValues.size() > 0) { String value = expandTemplate(tagValues.get(i), matches); if(StringUtils.isNotBlank(value)) { tags.put(tagKey, value); } } else { String tagValueLabel = tagValueLabels.get(i); if (!matches.containsKey(tagValueLabel)) { logger.severe("Application error: unparsed tag key."); continue; } String value = (String) matches.get(tagValueLabel); if(StringUtils.isNotBlank(value)) { tags.put(tagKey, value); } } } builder.setAnnotations(tags); return builder.setMetric(dynamicName).setHost(sourceName).build(); }
Source:
private void getAccessToken(String code) { String clientSecret = getString(R.string.mapbox_auth_flow_secret); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .addHeader("User-Agent", "Android Dev Preview") .addHeader("Content-Type", "application/x-www-form-urlencoded") .url(ACCESS_TOKEN_URL) .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "grant_type=authorization_code&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=" + redirectUri + "&code=" + code)) .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException exception) { Log.d("AccountRetrievalService", "onFailure: " + exception); } @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException { String json = response.body().string(); try { JSONObject data = new JSONObject(json); String accessToken = data.optString("access_token"); try { getUsernameFromJwt(accessToken); } catch (Exception exception) { exception.printStackTrace(); } getUserInfo(username, accessToken); } catch (JSONException exception) { exception.printStackTrace(); } } }); }

Target:
private void getAccessToken(String code) { String clientSecret = getString(R.string.mapbox_auth_flow_secret); String query = new Uri.Builder() .appendQueryParameter("grant_type", "authorization_code") .appendQueryParameter("client_id", clientId) .appendQueryParameter("client_secret", clientSecret) .appendQueryParameter("redirect_uri", redirectUri) .appendQueryParameter("code", code) .build().getQuery(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .addHeader("User-Agent", "Android Dev Preview") .addHeader("Content-Type", "application/x-www-form-urlencoded") .url(ACCESS_TOKEN_URL) .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), query)) .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException exception) { Log.d("AccountRetrievalService", "onFailure: " + exception); } @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException { String json = response.body().string(); try { JSONObject data = new JSONObject(json); String accessToken = data.optString("access_token"); try { getUsernameFromJwt(accessToken); } catch (Exception exception) { exception.printStackTrace(); } getUserInfo(username, accessToken); } catch (JSONException exception) { exception.printStackTrace(); } } }); }
Source:
public void parseOptionMap(Map<String, String[]> parameters, Set<String> argNames) throws CmdLineException { ArrayList<String> tmp = new ArrayList<String>(); for (Map.Entry<String, String[]> ent : parameters.entrySet()) { String name = ent.getKey(); if (name.equals("token")) { continue; } if (!name.startsWith("-")) { if (name.length() == 1) { name = "-" + name; } else { name = "--" + name; } } if (findHandler(name) instanceof BooleanOptionHandler) { boolean on = false; for (String value : ent.getValue()) { on = toBoolean(ent.getKey(), value); } if (on) { tmp.add(name); } } else { for (String value : ent.getValue()) { if (!argNames.contains(ent.getKey())) { tmp.add(name); } tmp.add(value); } } } parser.parseArgument(tmp.toArray(new String[tmp.size()])); }

Target:
public void parseOptionMap(Map<String, String[]> parameters, Set<String> argNames) throws CmdLineException { ArrayList<String> tmp = new ArrayList<String>(); for (Map.Entry<String, String[]> ent : parameters.entrySet()) { String name = ent.getKey(); if (name.equals("_token")) { continue; } if (!name.startsWith("-")) { if (name.length() == 1) { name = "-" + name; } else { name = "--" + name; } } if (findHandler(name) instanceof BooleanOptionHandler) { boolean on = false; for (String value : ent.getValue()) { on = toBoolean(ent.getKey(), value); } if (on) { tmp.add(name); } } else { for (String value : ent.getValue()) { if (!argNames.contains(ent.getKey())) { tmp.add(name); } tmp.add(value); } } } parser.parseArgument(tmp.toArray(new String[tmp.size()])); }
Source:
private static Field getField(Object svc, String fieldName) throws NoSuchFieldException { Field field = null; Class clazz = svc.getClass(); while (!(clazz == Object.class || field != null)) { try { field = clazz.getDeclaredField(fieldName); break; } catch (NoSuchFieldException e) { } clazz = clazz.getSuperclass(); } if (field == null) { throw new NoSuchFieldException("Field not found"); } return field; }

Target:
private static Field getField(Object svc, String fieldName) throws NoSuchFieldException { Field field = null; Class clazz = svc.getClass(); while (!(clazz == Object.class || field != null)) { try { field = clazz.getDeclaredField(fieldName); break; } catch (NoSuchFieldException e) { } clazz = clazz.getSuperclass(); } if (field == null) { throw new NoSuchFieldException(String.format("Field not found: %s", fieldName)); } return field; }
Source:
private void parseOptions(String argv) { OptionParser parser = new OptionParser(); parser.accepts( "host" ).withRequiredArg(); parser.accepts( "password" ).withRequiredArg(); parser.accepts( "user" ).withRequiredArg(); parser.accepts( "port" ).withRequiredArg(); parser.accepts( "producer" ).withRequiredArg(); OptionSet options = parser.parse(argv); if ( options.has("host")) this.mysqlHost = (String) options.valueOf("host"); if ( options.has("password")) this.mysqlPassword = (String) options.valueOf("password"); if ( options.has("user")) this.mysqlUser = (String) options.valueOf("user"); if ( options.has("port")) this.mysqlPort = Integer.valueOf((String) options.valueOf("port")); if ( options.has("producer")) this.producer = (String) options.valueOf("producer"); }

Target:
private void parseOptions(String argv) { OptionParser parser = new OptionParser(); parser.accepts( "host" ).withRequiredArg(); parser.accepts( "password" ).withRequiredArg(); parser.accepts( "user" ).withRequiredArg(); parser.accepts( "port" ).withRequiredArg(); parser.accepts( "producer" ).withRequiredArg(); OptionSet options = parser.parse(argv); if ( options.has("host")) this.mysqlHost = (String) options.valueOf("host"); if ( options.has("password")) this.mysqlPassword = (String) options.valueOf("password"); if ( options.has("user")) this.mysqlUser = (String) options.valueOf("user"); if ( options.has("port")) this.mysqlPort = Integer.valueOf((String) options.valueOf("port")); if ( options.has("producer")) this.producerType = (String) options.valueOf("producer"); }
Source:
public CompletableFuture<Object> invokeAsync(ComponentRegistry componentRegistry) { gtxToCheck.removeIf(globalTransaction -> componentRegistry.getTransactionTable().containsLocalTx(globalTransaction)); return CompletableFuture.completedFuture(gtxToCheck); }

Target:
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) { TransactionTable txTable = componentRegistry.getTransactionTable(); gtxToCheck.removeIf(txTable::containsLocalTx); return CompletableFuture.completedFuture(gtxToCheck); }
Source:
public Solution[] computeOptimizationProblemForAllDifferentSolutions(SuitableOptions cloudOffers, QualityInformation requirements, Topology topology, int numPlansToGenerate) { return super.filterUniqueSolutions( computeOptimizationProblem(cloudOffers, requirements, topology, numPlansToGenerate)); }

Target:
public Solution[] computeOptimizationProblemForAllDifferentSolutions(SuitableOptions cloudOffers, QualityInformation requirements, Topology topology, int numPlansToGenerate) { return filterUniqueSolutions(computeOptimizationProblem(cloudOffers, requirements, topology, numPlansToGenerate)); }
Source:
private String buildRequest(VariantAnnotation annotation) { StringBuilder sb = new StringBuilder(annotation.getVariantId()); sb.insert(0,"chr"); return sb.toString(); }

Target:
private String buildRequest(VariantAnnotation annotation) { StringBuilder sb = new StringBuilder(annotation.getVariantId()); if(!sb.toString().startsWith("chr")) { sb.insert(0,"chr"); } return sb.toString(); }
Source:
public List<String> getUsages() { return Arrays.asList(new String[] { buildCommandUsage(SUBCMD_LIST + " <itemname> <namespace>", "lists the metadata for the specific item in the given namespace"), buildCommandUsage(SUBCMD_REMOVE + " <itemname> <namespace>", "removes metadata for the specific item in the given namespace"), buildCommandUsage(SUBCMD_ADD + " <itemName> <namespace> <value> [{key1=value1, key2=value2, ...}]", "adds or updates metadata value (and optional config values) for the specific item in the given namespace") }); }

Target:
public List<String> getUsages() { return Arrays.asList(new String[] { buildCommandUsage(SUBCMD_LIST + " <itemName> <namespace>", "lists the metadata for the specific item in the given namespace"), buildCommandUsage(SUBCMD_REMOVE + " <itemName> <namespace>", "removes metadata for the specific item in the given namespace"), buildCommandUsage(SUBCMD_ADD + " <itemName> <namespace> <value> [{key1=value1, key2=value2, ...}]", "adds or updates metadata value (and optional config values) for the specific item in the given namespace") }); }
Source:
public void initializeDefaultPreferences() { IPreferenceStore store = getPreferenceStore(); DiagramGeneralPreferencePage.initDefaults(store); DiagramAppearancePreferencePage.initDefaults(store); DiagramConnectionsPreferencePage.initDefaults(store); DiagramPrintingPreferencePage.initDefaults(store); DiagramRulersAndGridPreferencePage.initDefaults(store); }

Target:
public void initializeDefaultPreferences() { IPreferenceStore store = getPreferenceStore(); DiagramsPreferencePage.initDefaults(store); AppearancePreferencePage.initDefaults(store); ConnectionsPreferencePage.initDefaults(store); PrintingPreferencePage.initDefaults(store); RulerGridPreferencePage.initDefaults(store); }
Source:
public final CloseFuture closeAsync() { CloseFuture future = closeFuture.get(); if (future != null) return future; phase.set(Phase.CLOSING); for (SettableFuture<Connection> pendingBorrow : pendingBorrows) { pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); } future = new CloseFuture.Forwarding(discardAvailableConnections()); return closeFuture.compareAndSet(null, future) ? future : closeFuture.get(); }

Target:
final CloseFuture closeAsync() { CloseFuture future = closeFuture.get(); if (future != null) return future; phase.set(Phase.CLOSING); for (SettableFuture<Connection> pendingBorrow : pendingBorrows) { pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); } future = new CloseFuture.Forwarding(discardAvailableConnections()); return closeFuture.compareAndSet(null, future) ? future : closeFuture.get(); }
Source:
public static void start(final Stage primaryStage) { GridPane grid = new GridPane(); grid.setPadding(new javafx.geometry.Insets(10, 10, 10, 10)); grid.setVgap(20); grid.setHgap(20); Button backButton; backButton = new Button("Back"); GridPane.setConstraints(backButton, 3, 20); Label label = new Label("Hier komen settings lijstjes ofzo?"); GridPane.setConstraints(label, 10, 10); grid.getChildren().addAll(backButton, label); backButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { StartScreen.start(primaryStage); } }); settings = new Scene(grid, 640, 480); primaryStage.setScene(settings); primaryStage.show(); }

Target:
public static void start(final Stage primaryStage) { GridPane grid = new GridPane(); grid.setPadding(new javafx.geometry.Insets(10, 10, 10, 10)); grid.setVgap(20); grid.setHgap(20); Button backButton; backButton = new Button("Back"); GridPane.setConstraints(backButton, 3, 20); Label label = new Label("Hier komen settings lijstjes ofzo?"); GridPane.setConstraints(label, 10, 10); grid.getChildren().addAll(backButton, label); backButton.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { StartScreen.start(primaryStage); } }); settings = new Scene(grid, GameWindow.WIDTH, GameWindow.HEIGHT); primaryStage.setScene(settings); primaryStage.show(); }
Source:
void close() { isOpen.set(false); try { chunkFillerThread.join(NonBlockingRouter.SHUTDOWN_WAIT_MS); } catch (InterruptedException e) { logger.error("Caught interrupted exception while waiting for chunkFillerThread to finish"); Thread.currentThread().interrupt(); } Iterator<PutOperation> iter = putOperations.values().iterator(); while (iter.hasNext()) { PutOperation op = iter.next(); router.completeOperation(op.getFuture(), op.getCallback(), null, new RouterException("Cannot accept operation because Router is closed", RouterErrorCode.RouterClosed)); iter.remove(); } }

Target:
void close() { isOpen.set(false); try { chunkFillerThread.join(NonBlockingRouter.SHUTDOWN_WAIT_MS); } catch (InterruptedException e) { logger.error("Caught interrupted exception while waiting for chunkFillerThread to finish"); Thread.currentThread().interrupt(); } Iterator<PutOperation> iter = putOperations.iterator(); while (iter.hasNext()) { PutOperation op = iter.next(); NonBlockingRouter.completeOperation(op.getFuture(), op.getCallback(), null, new RouterException("Aborted operation because Router is closed", RouterErrorCode.RouterClosed)); iter.remove(); } }
Source:
public String pop() { String value = lines.remove(lines.lastKey()); return value; }

Target:
public String pop() { return lines.remove(lines.lastKey()); }
Source:
public static void getHDFSEntities(NavApiCient client, MetadataExtractor extractor, String marker){ Iterable<Map<String, Object>> HdfsAll = extractor.extractMetadata(marker, "sourceType:HDFS", null).getEntities(); getFirstResult(HdfsAll); Iterable<Map<String, Object>> HdfsSingleSource = extractor.extractMetadata(marker, "sourceType:HDFS AND " + "identity: 4fb48492c18e21ae5be9c2f7faeffe62", null).getEntities(); getFirstResult(HdfsSingleSource); }

Target:
public static void getHDFSEntities(NavApiCient client, MetadataExtractor extractor, String marker){ Iterable<Map<String, Object>> HdfsAll = extractor.extractMetadata(marker, null, "sourceType:HDFS", null) .getEntities(); getFirstResult(HdfsAll); Source hdfsSource = client.getOnlySource(SourceType.HDFS); Iterable<Map<String, Object>> HdfsSingleSource = extractor.extractMetadata(marker, null, "sourceType:HDFS AND " + "sourceId:" + hdfsSource.getIdentity(), null).getEntities(); getFirstResult(HdfsSingleSource); }
Source:
public static Path getApexDFSRootDir(FileSystem fs, Configuration conf) throws IOException { String apexDfsRootDir = conf.get(APEX_APP_DFS_ROOT_DIR); if (StringUtils.isBlank(apexDfsRootDir)) { return getDTDFSRootDir(fs, conf); } boolean useImpersonated = conf.getBoolean(StramUserLogin.DT_APP_PATH_IMPERSONATED, false); return processDFSRootDirHelper(fs, conf, apexDfsRootDir, useImpersonated, true); }

Target:
public static Path getApexDFSRootDir(FileSystem fs, Configuration conf) { String apexDfsRootDir = conf.get(APEX_APP_DFS_ROOT_DIR); boolean useImpersonated = conf.getBoolean(StramUserLogin.DT_APP_PATH_IMPERSONATED, false); String userShortName = null; if (useImpersonated) { try { userShortName = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException ex) { LOG.warn("Error getting current/login user name {}", apexDfsRootDir, ex); } } if (!useImpersonated || userShortName == null) { return getDTDFSRootDir(fs, conf); } if (StringUtils.isBlank(apexDfsRootDir)) { apexDfsRootDir = getDefaultRootFolder(); } return evalDFSRootDir(fs, conf, apexDfsRootDir, userShortName, true); }
Source:
public void refreshPersonDetails() { if (!isAdded()) return; Person person = loadPerson(); if (person != null) { int avatarSz = getResources().getDimensionPixelSize(R.dimen.people_avatar_sz); String avatarUrl = GravatarUtils.fixGravatarUrl(person.getAvatarUrl(), avatarSz); mAvatarImageView.setImageUrl(avatarUrl, WPNetworkImageView.ImageType.AVATAR); mDisplayNameTextView.setText(StringUtils.unescapeHTML(person.getDisplayName())); mRoleTextView.setText(StringUtils.capitalize(person.getRole())); if (!person.getUsername().isEmpty()) { mUsernameTextView.setVisibility(View.VISIBLE); mUsernameTextView.setText(String.format("@%s", person.getUsername())); } else { mUsernameTextView.setVisibility(View.GONE); } if (person.isFollower() || person.isEmailFollower()) { mSubscribedTextView.setVisibility(View.VISIBLE); String dateSubscribed = SimpleDateFormat.getDateInstance().format(person.getDateSubscribed()); String dateText = getString(R.string.follower_subscribed_since, dateSubscribed); mSubscribedTextView.setText(dateText); } else { mSubscribedTextView.setVisibility(View.GONE); } if (person.isFollower() || person.isEmailFollower()) { mRoleContainer.setVisibility(View.GONE); } else { mRoleContainer.setVisibility(View.VISIBLE); setupRoleContainerForCapability(); } } else { AppLog.w(AppLog.T.PEOPLE, "Person returned null from DB for personID: " + mPersonID + " & localTableBlogID: " + mLocalTableBlogID); } }

Target:
public void refreshPersonDetails() { if (!isAdded()) return; Person person = loadPerson(); if (person != null) { int avatarSz = getResources().getDimensionPixelSize(R.dimen.people_avatar_sz); String avatarUrl = GravatarUtils.fixGravatarUrl(person.getAvatarUrl(), avatarSz); mAvatarImageView.setImageUrl(avatarUrl, WPNetworkImageView.ImageType.AVATAR); mDisplayNameTextView.setText(StringUtils.unescapeHTML(person.getDisplayName())); mRoleTextView.setText(StringUtils.capitalize(person.getRole())); if (!TextUtils.isEmpty(person.getUsername())) { mUsernameTextView.setText(String.format("@%s", person.getUsername())); } if (mPersonType == Person.PersonType.USER) { mRoleContainer.setVisibility(View.VISIBLE); setupRoleContainerForCapability(); mSubscribedDateContainer.setVisibility(View.GONE); } else { mRoleContainer.setVisibility(View.GONE); mSubscribedDateContainer.setVisibility(View.VISIBLE); if (mPersonType == Person.PersonType.FOLLOWER) { mSubscribedDateTitleView.setText(R.string.title_follower); } else if (mPersonType == Person.PersonType.EMAIL_FOLLOWER) { mSubscribedDateTitleView.setText(R.string.title_email_follower); } String dateSubscribed = SimpleDateFormat.getDateInstance().format(person.getDateSubscribed()); String dateText = getString(R.string.follower_subscribed_since, dateSubscribed); mSubscribedDateTextView.setText(dateText); } int padding = mPersonType == Person.PersonType.EMAIL_FOLLOWER ? (int) getResources().getDimension(R.dimen.margin_small) : 0; changeDisplayNameTopPadding(padding); } else { AppLog.w(AppLog.T.PEOPLE, "Person returned null from DB for personID: " + mPersonID + " & localTableBlogID: " + mLocalTableBlogID); } }