auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldReturnAMapOfAllTemplateNamesToPipelinesForAnAdminUser() { BasicCruiseConfig cruiseConfig = GoConfigMother.defaultCruiseConfig(); CaseInsensitiveString adminUser = new CaseInsensitiveString("admin"); ServerConfig serverConfig = new ServerConfig(new SecurityConfig(null, null, false, new AdminsConfig(new AdminUser(adminUser))), null); cruiseConfig.setServerConfig(serverConfig); GoConfigMother.enableSecurityWithPasswordFile(cruiseConfig); new GoConfigMother().addPipelineWithTemplate(cruiseConfig, "p1", "t1", "s1", "j1"); new GoConfigMother().addPipelineWithTemplate(cruiseConfig, "p2", "t2", "s2", "j2"); HashMap<CaseInsensitiveString, List<CaseInsensitiveString>> map = new HashMap<>(); ArrayList<CaseInsensitiveString> template1Pipelines = new ArrayList<>(); ArrayList<CaseInsensitiveString> template2Pipelines = new ArrayList<>(); template1Pipelines.add(new CaseInsensitiveString("p1")); template2Pipelines.add(new CaseInsensitiveString("p2")); map.put(new CaseInsensitiveString("t1"), template1Pipelines); map.put(new CaseInsensitiveString("t2"), template2Pipelines); assertThat(cruiseConfig.templatesWithPipelinesForUser(adminUser.toString(), null), is(map)); }

Target:
public void shouldReturnAMapOfAllTemplateNamesToPipelinesForAnAdminUser() { BasicCruiseConfig cruiseConfig = getCruiseConfigWithSecurityEnabled(); new GoConfigMother().addPipelineWithTemplate(cruiseConfig, "p1", "t1", "s1", "j1"); new GoConfigMother().addPipelineWithTemplate(cruiseConfig, "p2", "t2", "s2", "j2"); HashMap<CaseInsensitiveString, List<CaseInsensitiveString>> map = new HashMap<>(); List<CaseInsensitiveString> template1Pipelines = Arrays.asList(new CaseInsensitiveString("p1")); List<CaseInsensitiveString> template2Pipelines = Arrays.asList(new CaseInsensitiveString("p2")); map.put(new CaseInsensitiveString("t1"), template1Pipelines); map.put(new CaseInsensitiveString("t2"), template2Pipelines); assertThat(cruiseConfig.templatesWithPipelinesForUser("admin", null), is(map)); }
Source:
private boolean needsToRePrepare(Throwable throwable) { Throwable cause = throwable; while (cause != null) { if (cause instanceof RetryPrepareException) { return true; } cause = cause.getCause(); } return false; }

Target:
private boolean needsToRePrepare(Throwable throwable) { return throwable instanceof RemoteException && throwable.getCause() instanceof RetryPrepareException; }
Source:
public ColorPalette(RGB background, String registryKey, RGB defaultRGB) { RGB registry = JFaceResources.getColorRegistry().getRGB(registryKey); if (registry != null) { selected = registry; } else { selected = defaultRGB; } normal = interpolate(selected, background, 0.6); fill = interpolate(selected, background, 0.97); textFill = interpolate(selected, background, 0.85); }

Target:
public ColorPalette(RGB background, String registryKey, RGB defaultRGB) { RGB registry = JFaceResources.getColorRegistry().getRGB(registryKey); if (registry != null) { selected = registry; } else { selected = defaultRGB; } normal = interpolate(selected, background, 0.6); fill = interpolate(selected, background, 0.9); textFill = interpolate(selected, background, 0.8); }
Source:
@Override public Converter<?> get(Type type) { JsonMapper<?> mapper = LoganSquare.mapperFor((Class<?>) type); return new LoganSquareConverter<>(mapper); }

Target:
@Override public Converter<?> get(Type type) { if (type instanceof Class) { return new LoganSquareObjectConverter<>(mapperFor(type)); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] typeArguments = parameterizedType.getActualTypeArguments(); Type firstType = typeArguments[0]; if (parameterizedType.getRawType() == Map.class) { Type secondType = typeArguments[1]; if (firstType != String.class) throw new RuntimeException("LoganSquareConverter can't convert Map keys of type '" + firstType + '\''); if (!(secondType instanceof Class)) throw new RuntimeException("LoganSquareConverter can't convert Map values of type '" + secondType + '\''); return new LoganSquareMapConverter<>(mapperFor(secondType)); } else { if (!(firstType instanceof Class)) throw new RuntimeException("LoganSquareConverter can't convert List items of type '" + firstType + '\''); return new LoganSquareListConverter<>(mapperFor(firstType)); } } throw new RuntimeException("LoganSquareConverter encountered non-convertable type '" + type + '\''); }
Source:
public RestRequestInfo addListener(RestRequestInfoEventListener restRequestInfoEventListener) { if (restRequestInfoEventListener != null) { if (operationComplete.get()) { logger.debug("Firing onHandlingComplete() for late listener"); restRequestInfoEventListener.onHandlingComplete(this, handlingException); } else { synchronized (listeners) { if (operationComplete.get()) { logger.debug("Firing onHandlingComplete() for late listener"); restRequestInfoEventListener.onHandlingComplete(this, handlingException); } else { listeners.add(restRequestInfoEventListener); } } } } return this; }

Target:
public RestRequestInfo addListener(RestRequestInfoEventListener restRequestInfoEventListener) { if (restRequestInfoEventListener != null) { if (operationComplete.get()) { logger.trace("Firing onComplete() for late listener"); restRequestInfoEventListener.onHandlingComplete(this, exception); } else { synchronized (listeners) { if (operationComplete.get()) { logger.trace("Firing onComplete() for late listener"); restRequestInfoEventListener.onHandlingComplete(this, exception); } else { listeners.add(restRequestInfoEventListener); } } } } return this; }
Source:
public JsonElement serialize(IncomingTransferReject src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if (src.error != null) { object.addProperty(MEMBER_ERROR, src.error.code); } else { object.addProperty(MEMBER_STATUS, src.status.code); } return object; }

Target:
public JsonElement serialize(IncomingTransferReject src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); object.addProperty(MEMBER_STATUS, src.status.code); if (src.error != null) { object.addProperty(MEMBER_ERROR, src.error.code); } return object; }
Source:
void markContainerInactiveOnZk(Set<Container> inactiveContainerCandidateSet) { if (inactiveContainerCandidateSet != null) { Map<Short, Account> accountToUpdateMap = new HashMap<>(); inactiveContainerCandidateSet.forEach(container -> { container = new ContainerBuilder(container).setStatus(Container.ContainerStatus.INACTIVE).build(); short accountId = container.getParentAccountId(); Account account = new AccountBuilder(accountToUpdateMap.getOrDefault(accountId, getAccountById(accountId))).addOrUpdateContainer(container).build(); accountToUpdateMap.put(accountId, account); }); updateAccounts(accountToUpdateMap.values()); } }

Target:
void markContainerInactiveOnZk(Set<Container> inactiveContainerCandidateSet) throws InterruptedException { if (inactiveContainerCandidateSet != null) { boolean success = false; int retry = 0; while (!success && retry < config.maxRetryCountOnUpdateFailure) { Map<Short, Account> accountToUpdateMap = new HashMap<>(); inactiveContainerCandidateSet.forEach(container -> { short accountId = container.getParentAccountId(); Account accountToEdit = accountToUpdateMap.computeIfAbsent(accountId, this::getAccountById); Container containerToEdit = accountToEdit.getContainerById(container.getId()); Container editedContainer = new ContainerBuilder(containerToEdit).setStatus(Container.ContainerStatus.INACTIVE).build(); accountToUpdateMap.put(accountId, new AccountBuilder(accountToEdit).addOrUpdateContainer(editedContainer).build()); }); success = updateAccounts(accountToUpdateMap.values()); if (!success) { retry++; Thread.sleep(config.retryDelayMs); } } if (!success) { logger.error("Failed to mark containers INACTIVE in set : after retries", inactiveContainerCandidateSet, config.maxRetryCountOnUpdateFailure); accountServiceMetrics.accountUpdatesToZkErrorCount.inc(); } } }
Source:
public AbstractContainerRequestValueFactory<?> createValueFactory(Parameter parameter) { final boolean isOptionalPrincipal = parameter.getRawType().equals(Optional.class) && ParameterizedType.class.isAssignableFrom(parameter.getType().getClass()) && principalClass.equals(((ParameterizedType) parameter.getType()).getActualTypeArguments()[0]); if (!parameter.isAnnotationPresent(Auth.class) || !(principalClass.equals(parameter.getRawType()) || isOptionalPrincipal)) { return null; } else if (isOptionalPrincipal) { return new OptionalPrincipalContainerRequestValueFactory(); } else { return new PrincipalContainerRequestValueFactory(); } }

Target:
public AbstractContainerRequestValueFactory<?> createValueFactory(Parameter parameter) { if (!parameter.isAnnotationPresent(Auth.class)) { return null; } else if (principalClass.equals(parameter.getRawType())) { return new PrincipalContainerRequestValueFactory(); } else { final boolean isOptionalPrincipal = parameter.getRawType() == Optional.class && ParameterizedType.class.isAssignableFrom(parameter.getType().getClass()) && principalClass == ((ParameterizedType) parameter.getType()).getActualTypeArguments()[0]; return isOptionalPrincipal ? new OptionalPrincipalContainerRequestValueFactory() : null; } }
Source:
public Iterable<VApp> listNodesByIds(final Iterable<String> ids) { return Iterables.filter(listNodes(), new Predicate<VApp>() { @Override public boolean apply(VApp vm) { return Iterables.contains(ids, vm.getHref().toASCIIString()); } }); }

Target:
public Iterable<VApp> listNodesByIds(final Iterable<String> ids) { return filter(listNodes(), new Predicate<VApp>() { @Override public boolean apply(VApp vm) { return contains(ids, vm.getHref().toASCIIString()); } }); }
Source:
public void awaitFlushCompletion() throws InterruptedException { try { for (ProducerBatch batch : this.incomplete.copyAll()) { batch.produceFuture.await(); waitForPossibleSplittedBatches(batch); batch.clearChildrenProducerBatch(); } } finally { this.flushesInProgress.decrementAndGet(); } }

Target:
public void awaitFlushCompletion() throws InterruptedException { try { for (ProducerBatch batch : this.incomplete.copyAll()) { batch.await(); } } finally { this.flushesInProgress.decrementAndGet(); } }
Source:
public void addEvents(Collection<IEventDeclaration> events) throws CTFReaderException { if (fEvents != Collections.EMPTY_LIST) { if (fEventUnsetId) { throw new CTFReaderException("Cannot add to a stream with an unidentified event"); } for (IEventDeclaration event : events) { if (event != null) { int index = event.getId().intValue(); while (fEvents.size() >= index) { fEvents.add(null); } if (fEvents.get(index) != null) { throw new CTFReaderException("Both lists have an event defined at position " + index); } fEvents.set(index, event); } } } else { fEvents = new ArrayList<>(events); } }

Target:
public void addEvents(Collection<IEventDeclaration> events) throws CTFReaderException { if (fEvents != Collections.EMPTY_LIST) { if (fEventUnsetId) { throw new CTFReaderException("Cannot add to a stream with an unidentified event"); } for (IEventDeclaration event : events) { if (event != null) { int index = event.getId().intValue(); ensureSize(index); if (fEvents.get(index) != null) { throw new CTFReaderException("Both lists have an event defined at position " + index); } fEvents.set(index, event); } } } else { fEvents = new ArrayList<>(events); } }
Source:
public void exceptionWhenStartingNewTransactionOnShutdownInstance() throws Throwable { KernelTransactions kernelTransactions = newKernelTransactions(); SecurityContext securityContext = mock( SecurityContext.class ); availabilityGuard.shutdown(); t2.execute( (OtherThreadExecutor.WorkerCommand<Void,Void>) state -> { stopKernelTransactions( kernelTransactions ); return null; } ); expectedException.expect( DatabaseShutdownException.class ); kernelTransactions.newInstance( KernelTransaction.Type.explicit, securityContext, 0L ); }

Target:
public void exceptionWhenStartingNewTransactionOnShutdownInstance() throws Throwable { KernelTransactions kernelTransactions = newKernelTransactions(); SecurityContext securityContext = mock( SecurityContext.class ); availabilityGuard.shutdown(); expectedException.expect( DatabaseShutdownException.class ); kernelTransactions.newInstance( KernelTransaction.Type.explicit, securityContext, 0L ); }
Source:
public OrcAggregatedMemoryContext newOrcAggregatedMemoryContext() { return null; }

Target:
public OrcAggregatedMemoryContext newOrcAggregatedMemoryContext() { return NOOP_ORC_AGGREGATED_MEMORY_CONTEXT; }
Source:
protected Response patch(String uri, String path, Entity entity) { Invocation.Builder builder = builder(uri, path); builder.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); return builder.method("PATCH", entity); }

Target:
protected Response patch(String uri, String path, Entity entity) { Invocation.Builder builder = builder(uri, path); builder.property(SET_METHOD_WORKAROUND, true); return builder.method("PATCH", entity); }
Source:
CreateReviewNotes(@GerritPersonIdent final PersonIdent gerritIdent, final AccountCache accountCache, final @AnonymousCowardName String anonymousCowardName, final ProjectCache projectCache, final LabelNormalizer labelNormalizer, final NotesBranchUtil.Factory notesBranchUtilFactory, final @Nullable @CanonicalWebUrl String canonicalWebUrl, final @Assisted ReviewDb reviewDb, final @Assisted Project.NameKey project, final @Assisted Repository git) { this.gerritServerIdent = gerritIdent; this.accountCache = accountCache; this.anonymousCowardName = anonymousCowardName; ProjectState projectState = projectCache.get(project); if (projectState == null) { this.labelTypes = new LabelTypes(Collections.<LabelType> emptyList()); } else { this.labelTypes = projectState.getLabelTypes(); } this.labelNormalizer = labelNormalizer; this.notesBranchUtilFactory = notesBranchUtilFactory; this.canonicalWebUrl = canonicalWebUrl; this.reviewDb = reviewDb; this.project = project; this.git = git; }

Target:
CreateReviewNotes(@GerritPersonIdent final PersonIdent gerritIdent, final AccountCache accountCache, final @AnonymousCowardName String anonymousCowardName, final ProjectCache projectCache, final LabelNormalizer labelNormalizer, final NotesBranchUtil.Factory notesBranchUtilFactory, final @Nullable @CanonicalWebUrl String canonicalWebUrl, final @Assisted ReviewDb reviewDb, final @Assisted Project.NameKey project, final @Assisted Repository git) { this.gerritServerIdent = gerritIdent; this.accountCache = accountCache; this.anonymousCowardName = anonymousCowardName; ProjectState projectState = projectCache.get(project); if (projectState == null) { log.error("Could not obtain available labels for project " + project.get() + ". Expect missing labels its review notes."); this.labelTypes = new LabelTypes(Collections.<LabelType> emptyList()); } else { this.labelTypes = projectState.getLabelTypes(); } this.labelNormalizer = labelNormalizer; this.notesBranchUtilFactory = notesBranchUtilFactory; this.canonicalWebUrl = canonicalWebUrl; this.reviewDb = reviewDb; this.project = project; this.git = git; }
Source:
public Date getUpdatedAt() { if (updatedAt == null) { updatedAt = new Date(Const.DEFAULT_STUDENT_CREATION_DATE); } return updatedAt; }

Target:
public Date getUpdatedAt() { return (updatedAt == null) ? Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP : updatedAt; }
Source:
public String enchantment$getName() { return I18n.translateToLocal(shadow$getName()); }

Target:
public String enchantment$getName() { return shadow$getName(); }
Source:
public CompletableFuture<Void> handleDiscoveryTask(DiscoveryConfiguration config) { this.configFactory = new DiscoveryConfigFactory(config); final Map<String, List<DiscoveryJob>> jobsByLocation = rangeChunker.chunk(config); if (jobsByLocation.size() == 0) { LOG.info("No IP addresses to discover."); return CompletableFuture.completedFuture(null); } final int taskId = taskIdTracker.incrementAndGet(); final List<CompletableFuture<Void>> futures = new ArrayList<>(jobsByLocation.keySet().size()); Logging.withPrefix(Discovery.getLoggingCategory(), new Runnable() { @Override public void run() { jobsByLocation.entrySet().stream() .map(e -> triggerJobsAsync(e.getKey(), e.getValue(), taskId)) .forEach(futures::add); } }); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); }

Target:
public CompletableFuture<Void> handleDiscoveryTask(DiscoveryConfiguration config) { final Map<String, List<DiscoveryJob>> jobsByLocation = rangeChunker.chunk(config); if (jobsByLocation.size() == 0) { LOG.info("No IP addresses to discover."); return CompletableFuture.completedFuture(null); } final int taskId = taskIdTracker.incrementAndGet(); final List<CompletableFuture<Void>> futures = new ArrayList<>(jobsByLocation.keySet().size()); Logging.withPrefix(Discovery.getLoggingCategory(), new Runnable() { @Override public void run() { jobsByLocation.entrySet().stream() .map(e -> triggerJobsAsync(e.getKey(), e.getValue(), taskId)) .forEach(futures::add); } }); return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); }
Source:
public EhcacheEntityMessage decodeMessage(byte[] payload) throws MessageCodecException { ByteBuffer payloadBuf = ByteBuffer.wrap(payload); if (payloadBuf.get() == 1) { return LifeCycleOpCodec.decode(payloadBuf); } else { return ServerStoreOpCodec.decode(payload); } }

Target:
public EhcacheEntityMessage decodeMessage(byte[] payload) throws MessageCodecException { ByteBuffer payloadBuf = ByteBuffer.wrap(payload); if (payloadBuf.get() == EhcacheEntityMessage.Type.LIFECYCLE_OP.getOpCode()) { return LifeCycleOpCodec.decode(payloadBuf); } else { return ServerStoreOpCodec.decode(payload); } }
Source:
private static boolean setValueIsSameAsDefaultValue(@Nullable Object defaultValue, Tree valueSet) { if (valueSet.is(Tree.Kind.STRING_LITERAL)) { return LiteralUtils.trimQuotes(((LiteralTree) valueSet).value()).equals(defaultValue); } else if (valueSet.is(Tree.Kind.INT_LITERAL)) { return LiteralUtils.intLiteralValue((LiteralTree) valueSet).equals(defaultValue); } return false; }

Target:
private static boolean setValueIsSameAsDefaultValue(@Nullable Object defaultValue, Tree valueSet) { if (valueSet.is(Tree.Kind.STRING_LITERAL)) { return LiteralUtils.trimQuotes(((LiteralTree) valueSet).value()).equals(defaultValue); } else if (valueSet.is(Tree.Kind.INT_LITERAL)) { Integer intLiteralValue = LiteralUtils.intLiteralValue((LiteralTree) valueSet); return intLiteralValue != null && intLiteralValue.equals(defaultValue); } return false; }
Source:
public void phaseEnded(LocalSearchPhaseScope phaseScope) { super.phaseEnded(phaseScope); initialWaterLevel = null; waterLevelIncrementRatio = DEFAULT_WATER_LEVEL_INCREMENT_RATIO; waterLevelIncrementScore = null; }

Target:
public void phaseEnded(LocalSearchPhaseScope phaseScope) { super.phaseEnded(phaseScope); initialWaterLevel = null; }
Source:
public void doStart() { List<StreamListener> listeners = new ArrayList<>(); listeners.add(new StreamListener() { @Override public void onTweet(Tweet tweet) { try { sendMessage(MessageBuilder.withPayload(objectMapper.writeValueAsString(tweet)).build()); } catch (JsonProcessingException e) { logger.debug("JSON processing exception while processing the tweet: " + e); } } @Override public void onDelete(StreamDeleteEvent deleteEvent) { } @Override public void onLimit(int numberOfLimitedTweets) { logger.info("The stream is being track limited for " + numberOfLimitedTweets + " tweets."); } @Override public void onWarning(StreamWarningEvent warningEvent) { logger.error("Streaming source is in the danger of being disconnected."); } }); if (this.streamType.equalsIgnoreCase(TwitterStreamProperties.FIREHOSE)) { twitterTemplate.streamingOperations().firehose(listeners); } else { twitterTemplate.streamingOperations().sample(listeners); } }

Target:
public void doStart() { List<StreamListener> listeners = new ArrayList<>(); listeners.add(new StreamListener() { @Override public void onTweet(Tweet tweet) { try { sendMessage(MessageBuilder.withPayload(objectMapper.writeValueAsString(tweet)).build()); } catch (JsonProcessingException e) { logger.debug("JSON processing exception while processing the tweet: " + e); } } @Override public void onDelete(StreamDeleteEvent deleteEvent) { } @Override public void onLimit(int numberOfLimitedTweets) { logger.info("The stream is being track limited for " + numberOfLimitedTweets + " tweets."); } @Override public void onWarning(StreamWarningEvent warningEvent) { logger.error("Streaming source is in the danger of being disconnected."); } }); if (this.streamType.equals(TwitterStreamType.FIREHOSE)) { twitterTemplate.streamingOperations().firehose(listeners); } else { twitterTemplate.streamingOperations().sample(listeners); } }
Source:
public void testActions(final IntervalListTools.Action action, final long bases, final int intervals) throws IOException { final IntervalList il = tester(action); Assert.assertEquals(il.getBaseCount(), bases, "unexpcted number of bases found."); Assert.assertEquals(il.getIntervals().size(), intervals, "unexpcted number of intervals found."); }

Target:
public void testActions(final IntervalListTools.Action action, final long bases, final int intervals) throws IOException { final IntervalList il = tester(action); Assert.assertEquals(il.getBaseCount(), bases, "unexpected number of bases found."); Assert.assertEquals(il.getIntervals().size(), intervals, "unexpected number of intervals found."); }
Source:
public void test_ensureOnlyOne() { assertEquals(Arrays.asList().stream().reduce(Guavate.ensureOnlyOne()), Optional.empty()); assertEquals(Arrays.asList("a").stream().reduce(Guavate.ensureOnlyOne()), Optional.of("a")); assertThrowsIllegalArg(() -> Arrays.asList("a", "b").stream().reduce(Guavate.ensureOnlyOne())); }

Target:
public void test_ensureOnlyOne() { assertEquals(Stream.empty().reduce(Guavate.ensureOnlyOne()), Optional.empty()); assertEquals(Stream.of("a").reduce(Guavate.ensureOnlyOne()), Optional.of("a")); assertThrowsIllegalArg(() -> Stream.of("a", "b").reduce(Guavate.ensureOnlyOne())); }
Source:
private void merge(PushOneCommit.Result r) throws Exception { review(r, 2); SubmitInput input = new SubmitInput(); input.waitForMerge = true; revision(r).submit(input); Repository repo = repoManager.openRepository(project); try { assertEquals(r.getCommitId(), repo.getRef("refs/heads/master").getObjectId()); } finally { repo.close(); } }

Target:
private void merge(PushOneCommit.Result r) throws Exception { review(r, 2); revision(r).submit(); Repository repo = repoManager.openRepository(project); try { assertEquals(r.getCommitId(), repo.getRef("refs/heads/master").getObjectId()); } finally { repo.close(); } }
Source:
private static boolean differentContract(JavaSymbol.MethodJavaSymbol method, JavaSymbol.MethodJavaSymbol overridee) { return removingParametrizedAspect(method, overridee) || differentReturnType(method, overridee) || differentParameters(method, overridee) || differentAnnotations(method, overridee) || differentThrows(method, overridee); }

Target:
private static boolean differentContract(JavaSymbol.MethodJavaSymbol method, JavaSymbol.MethodJavaSymbol overridee) { return removingParametrizedAspect(method, overridee) || differentThrows(method, overridee) || differentReturnType(method, overridee) || differentParameters(method, overridee) || differentAnnotations(method.metadata(), overridee.metadata()); }
Source:
private void cleanUpOrphanTasks(List<Guid> runningTasksinCluster) { List<Guid> taskListInDB = getProvider().getMonitoredTaskIDsInDB(); if (taskListInDB == null) { taskListInDB = new ArrayList<Guid>(); } final Set<Guid> tasksNotRunning = new HashSet<Guid>(taskListInDB); tasksNotRunning.removeAll(runningTasksinCluster); for (Guid taskId: tasksNotRunning) { GlusterVolumeEntity vol= getVolumeDao().getVolumeByGlusterTask(taskId); if (vol != null && vol.getStatus() != GlusterStatus.UP) { continue; } List<Step> steps = getStepDao().getStepsByExternalId(taskId); for (Step step: steps) { step.markStepEnded(JobExecutionStatus.UNKNOWN); endStepJob(step); } releaseVolumeLock(taskId); } }

Target:
private void cleanUpOrphanTasks(List<Guid> runningTasksinCluster) { List<Guid> taskListInDB = getProvider().getMonitoredTaskIDsInDB(); if (taskListInDB == null) { return; } final Set<Guid> tasksNotRunning = new HashSet<Guid>(taskListInDB); tasksNotRunning.removeAll(runningTasksinCluster); for (Guid taskId: tasksNotRunning) { GlusterVolumeEntity vol= getVolumeDao().getVolumeByGlusterTask(taskId); if (vol != null && vol.getStatus() != GlusterStatus.UP) { continue; } List<Step> steps = getStepDao().getStepsByExternalId(taskId); for (Step step: steps) { step.markStepEnded(JobExecutionStatus.UNKNOWN); endStepJob(step); } releaseVolumeLock(taskId); } }
Source:
public static String[] valuesWithFullNames() { LANGUAGE[] allValues = values(); ArrayList<String> result = new ArrayList<String>(allValues.length); for (int i = 0; i < allValues.length; i++) { if(allValues[i] != UNLISTED) result.add(allValues[i].fullName); } Collections.sort(result); result.add(UNLISTED.fullName); return (String[])result.toArray(new String[result.size()]); }

Target:
public static String[] valuesWithFullNames() { LANGUAGE[] allValues = values(); ArrayList<String> result = new ArrayList<String>(allValues.length); for (int i = 0; i < allValues.length; i++) { if(allValues[i] != UNLISTED) result.add(allValues[i].fullName); } Collections.sort(result); result.add(UNLISTED.fullName); return result.toArray(new String[result.size()]); }
Source:
private void writeServiceInvokeRequest( PayloadOutputChannel ch, Collection<UUID> nodeIds, Method method, Object[] args ) { ch.clientChannel().protocolCtx().checkFeatureSupported(ProtocolBitmaskFeature.SERVICE_INVOKE); try (BinaryRawWriterEx writer = utils.createBinaryWriter(ch.out())) { writer.writeString(name); writer.writeByte(FLAG_PARAMETER_TYPES_MASK); writer.writeLong(timeout); if (nodeIds == null) writer.writeInt(0); else { writer.writeInt(nodeIds.size()); for (UUID nodeId : nodeIds) writer.writeUuid(nodeId); } PlatformServiceMethod ann = method.getDeclaredAnnotation(PlatformServiceMethod.class); writer.writeString(ann != null ? ann.value() : method.getName()); Class<?>[] paramTypes = method.getParameterTypes(); if (F.isEmpty(args)) writer.writeInt(0); else { writer.writeInt(args.length); assert args.length == paramTypes.length : "args=" + args.length + ", types=" + paramTypes.length; for (int i = 0; i < args.length; i++) { writer.writeInt(marsh.context().typeId(paramTypes[i].getName())); writer.writeObject(args[i]); } } } }

Target:
private void writeServiceInvokeRequest( PayloadOutputChannel ch, Collection<UUID> nodeIds, Method method, Object[] args ) { ch.clientChannel().protocolCtx().checkFeatureSupported(ProtocolBitmaskFeature.SERVICE_INVOKE); try (BinaryRawWriterEx writer = utils.createBinaryWriter(ch.out())) { writer.writeString(name); writer.writeByte(FLAG_PARAMETER_TYPES_MASK); writer.writeLong(timeout); if (nodeIds == null) writer.writeInt(0); else { writer.writeInt(nodeIds.size()); for (UUID nodeId : nodeIds) { writer.writeLong(nodeId.getMostSignificantBits()); writer.writeLong(nodeId.getLeastSignificantBits()); } } PlatformServiceMethod ann = method.getDeclaredAnnotation(PlatformServiceMethod.class); writer.writeString(ann != null ? ann.value() : method.getName()); Class<?>[] paramTypes = method.getParameterTypes(); if (F.isEmpty(args)) writer.writeInt(0); else { writer.writeInt(args.length); assert args.length == paramTypes.length : "args=" + args.length + ", types=" + paramTypes.length; for (int i = 0; i < args.length; i++) { writer.writeInt(marsh.context().typeId(paramTypes[i].getName())); writer.writeObject(args[i]); } } } }
Source:
private void translateTurnCostsParamToEdgeBased(GHRequest request, MultivaluedMap<String, String> queryParams) { if (queryParams.containsKey(TURN_COSTS)) { List<String> turnCosts = queryParams.get(TURN_COSTS); if (turnCosts.size() != 1) { throw new IllegalArgumentException("You may only specify the turn_costs parameter once"); } request.putHint(EDGE_BASED, turnCosts.get(0)); } }

Target:
private void translateTurnCostsParamToEdgeBased(GHRequest request, MultivaluedMap<String, String> queryParams) { if (queryParams.containsKey(TURN_COSTS)) { List<String> turnCosts = queryParams.get(TURN_COSTS); if (turnCosts.size() != 1) { throw new IllegalArgumentException("You may only specify the turn_costs parameter once"); } request.putHint(EDGE_BASED, Helper.toObject(turnCosts.get(0))); } }
Source:
public ListViewMaxHeight(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ListViewMaxHeight); maxHeight = a.getDimensionPixelSize(R.styleable.ListViewMaxHeight_maxHeight, Integer.MAX_VALUE); a.recycle(); } else { maxHeight = 0; } }

Target:
public ListViewMaxHeight(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (attrs != null) { TypedArray styleAttributes = getContext().obtainStyledAttributes(attrs, R.styleable.ListViewMaxHeight); maxHeight = styleAttributes.getDimensionPixelSize(R.styleable.ListViewMaxHeight_maxHeight, Integer.MAX_VALUE); styleAttributes.recycle(); } else { maxHeight = 0; } }
Source:
private void populateHash() throws SQLException { hash = new HashMap<ImmutableBytesWritable, Aggregator[]>(HASH_AGG_INIT_SIZE, 0.75f); for (Tuple result = resultIterator.next(); result != null; result = resultIterator.next()) { ImmutableBytesWritable key = new ImmutableBytesWritable(UNITIALIZED_KEY_BUFFER); key = getGroupingKey(result, key); Aggregator[] rowAggregators = hash.get(key); if (rowAggregators == null) { rowAggregators = aggregators.newAggregators(); hash.put(key, rowAggregators); } aggregators.aggregate(rowAggregators, result); } }

Target:
private HashMap<ImmutableBytesWritable, Aggregator[]> populateHash() throws SQLException { hash = new HashMap<ImmutableBytesWritable, Aggregator[]>(HASH_AGG_INIT_SIZE, 0.75f); final int aggSize = aggregators.getEstimatedByteSize(); long keySize = 0; for (Tuple result = resultIterator.next(); result != null; result = resultIterator.next()) { ImmutableBytesWritable key = new ImmutableBytesWritable(UNITIALIZED_KEY_BUFFER); key = getGroupingKey(result, key); Aggregator[] rowAggregators = hash.get(key); if (rowAggregators == null) { keySize += key.getSize(); long hashSize = SizedUtil.sizeOfMap(hash.size() + 1, SizedUtil.IMMUTABLE_BYTES_WRITABLE_SIZE, aggSize) + keySize; if (hashSize > memoryChunk.getSize() + CLIENT_HASH_AGG_MEMORY_CHUNK_SIZE) { memoryChunk.resize(hashSize + CLIENT_HASH_AGG_MEMORY_CHUNK_SIZE); } rowAggregators = aggregators.newAggregators(); hash.put(key, rowAggregators); } aggregators.aggregate(rowAggregators, result); } return hash; }
Source:
public void get() { Call<CardPageItem> call = cachedService.service(site).get(); call.enqueue(new Callback<CardPageItem>() { @Override public void onResponse(Call<CardPageItem> call, Response<CardPageItem> response) { responseHeaderHandler.onHeaderCheck(response); CardPageItem item = response.body(); String namespace = item.namespace() == null ? null : item.namespace().toLegacyString(); PageTitle title = new PageTitle(namespace, item.title(), site); cb.onSuccess(title); } @Override public void onFailure(Call<CardPageItem> call, Throwable t) { L.w("Failed to get random page title/summary", t); cb.onError(t); } }); }

Target:
public void get() { Call<CardPageItem> call = cachedService.service(site).get(); call.enqueue(new Callback<CardPageItem>() { @Override public void onResponse(Call<CardPageItem> call, Response<CardPageItem> response) { if (response.isSuccessful()) { responseHeaderHandler.onHeaderCheck(response); CardPageItem item = response.body(); String namespace = item.namespace() == null ? null : item.namespace().toLegacyString(); PageTitle title = new PageTitle(namespace, item.title(), site); cb.onSuccess(title); } else { L.v(response.message()); cb.onError(new IOException(response.message())); } } @Override public void onFailure(Call<CardPageItem> call, Throwable t) { L.w("Failed to get random page title/summary", t); cb.onError(t); } }); }
Source:
public void testLoggerExpressionValue() { localSession.getLocalSessionBrowser().perCategory().selectViewpoint("testColumnFinderExpressionLog").selectRepresentation("CrossTableDesc") .selectRepresentationInstance("new CrossTableDesc", UITableRepresentation.class).open(); try { openErrorLogView(); SWTBotView logViewBot = bot.viewByTitle("Error Log"); assertTrue("Find column expression error does not appear in the error log.", checkErrorLogMessage(logViewBot)); logViewBot.close(); } finally { errors.clear(); } }

Target:
public void testLoggerExpressionValue() { openRepresentation(localSession.getOpenedSession(), "CrossTableDesc", "new CrossTableDesc", DTable.class); try { openErrorLogView(); SWTBotView logViewBot = bot.viewByTitle("Error Log"); assertTrue("Find column expression error does not appear in the error log.", checkErrorLogMessage(logViewBot)); logViewBot.close(); } finally { errors.clear(); } }
Source:
public void addConstituent(Constituent constituent) { int start = constituent.getStartSpan(); int end = constituent.getEndSpan(); if (!allowOverlappingSpans && this.getConstituentsCoveringSpan(start, end).size() != 0) throw new IllegalArgumentException("Span [" + start + ", " + end + "] already labeled."); super.addConstituent(constituent); int size = this.constituents.size(); if (size > 1) { Constituent before = this.constituents.get(size-2); Constituent after = this.constituents.get(size-1); if (before.getStartSpan() > after.getStartSpan()) { Collections.sort(this.constituents, TextAnnotationUtilities.constituentStartComparator); } } }

Target:
public void addConstituent(Constituent constituent) { if (!allowOverlappingSpans) { int start = constituent.getStartSpan(); int end = constituent.getEndSpan(); if (this.getConstituentsCoveringSpan(start, end).size() != 0) throw new IllegalArgumentException("Span [" + start + ", " + end + "] already labeled."); } super.addConstituent(constituent); int size = this.constituents.size(); if (size > 1) { Constituent before = this.constituents.get(size-2); Constituent after = this.constituents.get(size-1); if (before.getStartSpan() > after.getStartSpan()) { Collections.sort(this.constituents, TextAnnotationUtilities.constituentStartComparator); } } }
Source:
private OnlineOptions(Data data) { if (data.protocol == null && System.getProperty(CREAPER_WILDFLY) != null) { if (data.sslOptions == null) { data.protocol = ManagementProtocol.HTTP_REMOTING; } else { data.protocol = ManagementProtocol.HTTPS_REMOTING; } } if (data.localDefault) { data.host = "localhost"; if (data.protocol == ManagementProtocol.HTTP_REMOTING || data.protocol == ManagementProtocol.HTTP) { data.port = 9990; } else if (data.protocol == ManagementProtocol.HTTPS_REMOTING) { data.port = 9993; } else if (data.protocol == ManagementProtocol.HTTPS) { data.port = System.getProperty(CREAPER_WILDFLY) != null ? 9993 : 9443; } else { data.port = 9999; } } this.isStandalone = data.isStandalone; this.isDomain = data.isDomain; this.defaultProfile = data.defaultProfile; this.defaultHost = data.defaultHost; this.host = data.host; this.port = data.port; this.protocol = data.protocol; this.connectionTimeout = data.connectionTimeout; this.bootTimeout = data.bootTimeout; this.username = data.username; this.password = data.password; this.localAuthDisabled = data.localAuthDisabled; this.sslOptions = data.sslOptions; this.wrappedModelControllerClient = data.wrappedModelControllerClient; this.isWrappedClient = data.wrappedModelControllerClient != null; if (protocol == ManagementProtocol.HTTPS && sslOptions == null) { throw new IllegalArgumentException("SSL must be configured when HTTPS protocol is used!"); } }

Target:
private OnlineOptions(Data data) { if (data.protocol == null && System.getProperty(CREAPER_WILDFLY) != null) { if (data.sslOptions == null) { data.protocol = ManagementProtocol.HTTP_REMOTING; } else { data.protocol = ManagementProtocol.HTTPS_REMOTING; } } if (data.localDefault) { data.host = "localhost"; if (data.protocol == ManagementProtocol.HTTP_REMOTING || data.protocol == ManagementProtocol.HTTP) { data.port = 9990; } else if (data.protocol == ManagementProtocol.HTTPS_REMOTING) { data.port = 9993; } else if (data.protocol == ManagementProtocol.HTTPS) { data.port = System.getProperty(CREAPER_WILDFLY) != null ? 9993 : 9443; } else { data.port = 9999; } } this.isStandalone = data.isStandalone; this.isDomain = data.isDomain; this.defaultProfile = data.defaultProfile; this.defaultHost = data.defaultHost; this.host = data.host; this.port = data.port; this.protocol = data.protocol; this.connectionTimeout = data.connectionTimeout; this.bootTimeout = data.bootTimeout; this.username = data.username; this.password = data.password; this.localAuthDisabled = data.localAuthDisabled; this.sslOptions = data.sslOptions; this.wrappedModelControllerClient = data.wrappedModelControllerClient; this.isWrappedClient = data.wrappedModelControllerClient != null; if ((protocol == ManagementProtocol.HTTPS || protocol == ManagementProtocol.HTTPS_REMOTING) && sslOptions == null) { throw new IllegalArgumentException("SSL must be configured when HTTPS or HTTPS_REMOTING protocol is used!"); } }
Source:
public static void main(final String[] args) { final String TRACE_PATH = "testfiles/kernel"; final int NUM_LOOPS = 100; final boolean USE_TEXT = true; Long nbEvent = 0L; final Vector<Double> benchs = new Vector<Double>(); CtfTmfTrace trace = null; long start, stop; for (int loops = 0; loops < NUM_LOOPS; loops++) { nbEvent = 0L; trace = new CtfTmfTrace(); try { trace.initTrace(null, TRACE_PATH, CtfTmfEvent.class); } catch (final TmfTraceException e) { loops = NUM_LOOPS +1; break; } start = System.nanoTime(); if (nbEvent != -1) { final CtfTmfLightweightContext traceReader = (CtfTmfLightweightContext) trace.seekEvent(0); start = System.nanoTime(); CtfTmfEvent current = traceReader.getCurrentEvent(); while (current != null) { nbEvent++; if (USE_TEXT) { System.out.println("Event " + nbEvent + " Time " + current.getTimestamp().toString() + " type " + current.getEventName() + " on CPU " + current.getSource() + " " + current.getContent().toString()) ; } if(nbEvent == 30) { new Object(); } boolean hasMore = traceReader.advance(); current = traceReader.getCurrentEvent(); } } stop = System.nanoTime(); System.out.print('.'); final double time = (stop - start) / (double) nbEvent; benchs.add(time); } System.out.println(""); double avg = 0; for (final Double val : benchs) { avg += val; } avg /= benchs.size(); System.out.println("Time to read = " + avg + " events/ns"); for (final Double val : benchs) { System.out.print(val); System.out.print(", "); } }

Target:
public static void main(final String[] args) { final String TRACE_PATH = "testfiles/kernel"; final int NUM_LOOPS = 100; final boolean USE_TEXT = true; Long nbEvent = 0L; final Vector<Double> benchs = new Vector<Double>(); CtfTmfTrace trace = null; long start, stop; for (int loops = 0; loops < NUM_LOOPS; loops++) { nbEvent = 0L; trace = new CtfTmfTrace(); try { trace.initTrace(null, TRACE_PATH, CtfTmfEvent.class); } catch (final TmfTraceException e) { loops = NUM_LOOPS +1; break; } start = System.nanoTime(); if (nbEvent != -1) { final CtfTmfLightweightContext traceReader = (CtfTmfLightweightContext) trace.seekEvent(0); start = System.nanoTime(); CtfTmfEvent current = traceReader.getCurrentEvent(); while (current != null) { nbEvent++; if (USE_TEXT) { System.out.println("Event " + nbEvent + " Time " + current.getTimestamp().toString() + " type " + current.getEventName() + " on CPU " + current.getSource() + " " + current.getContent().toString()) ; } boolean hasMore = traceReader.advance(); if( hasMore ){ } current = traceReader.getCurrentEvent(); } } stop = System.nanoTime(); System.out.print('.'); final double time = (stop - start) / (double) nbEvent; benchs.add(time); } System.out.println(""); double avg = 0; for (final Double val : benchs) { avg += val; } avg /= benchs.size(); System.out.println("Time to read = " + avg + " events/ns"); for (final Double val : benchs) { System.out.print(val); System.out.print(", "); } }
Source:
private static @Pointer long retain (ObjCObject self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self.getHandle(), retainCount) == 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.put(self.getHandle(), self); } } return ObjCRuntime.ptr_objc_msgSendSuper(new Super(self.getHandle(), NS_OBJECT_CLASS).getHandle(), sel); }

Target:
private static @Pointer long retain(ObjCObject self, @Pointer long sel) { if (ObjCRuntime.int_objc_msgSend(self.getHandle(), retainCount) <= 1) { synchronized (CUSTOM_OBJECTS) { CUSTOM_OBJECTS.put(self.getHandle(), self); } } return ObjCRuntime.ptr_objc_msgSendSuper(new Super(self.getHandle(), NS_OBJECT_CLASS).getHandle(), sel); }
Source:
public void toIntArray() throws Exception { RangeSet rs = new RangeSet(4); int[] array = rs.toIntArray(); assertEquals(4, array.length); assertEquals(0, array[0]); assertEquals(1, array[1]); assertEquals(2, array[2]); assertEquals(3, array[3]); }

Target:
public void toIntArray() throws Exception { RangeSet rs = new RangeSet(4); int[] array = rs.toIntArray(); assertArrayEquals(new int[]{0, 1, 2, 3}, array); }
Source:
protected Map<String, Object> getCapabilities() { String capabilitiesString = getProperty(SELENIUM_JSONCAPABILITIES); try { Map<String, Object> result = new HashMap<String, Object>(); Gson gson = new Gson(); result = (Map<String, Object>)gson.fromJson(capabilitiesString, result.getClass()); return result; } catch (Exception e) { throw new RuntimeException("Unable to parse Selenium capabilities: " + capabilitiesString + "\n*", e); } }

Target:
protected Map<String, Object> getCapabilities() { String capabilitiesString = getProperty(SELENIUM_JSONCAPABILITIES); try { return Environment.getInstance().getJsonHelper().jsonStringToMap(capabilitiesString); } catch (Exception e) { throw new RuntimeException("Unable to parse Selenium capabilities: " + capabilitiesString, e); } }
Source:
public void parallelLockRelease() throws Exception { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { LockableResourcesManager.get().createResource("resource1"); LockableResourcesManager.get().createResource("resource2"); LockableResourcesManager.get().createResource("resource3"); LockableResourcesManager.get().createResource("resource4"); WorkflowJob j = story.j.jenkins.createProject(WorkflowJob.class, "j"); j.setDefinition(new CpsFlowDefinition( "lock(resource: 'resource1') {\n" + " sleep 1\n" + "}\n" + "lock(resource: 'resource2') { \n" + " sleep 3\n" + "}\n" + "lock(resource: 'resource3') { \n" + " sleep 3\n" + "}\n" + "lock(resource: 'resource4') { \n" + " sleep 3\n" + " echo 'Entering semaphore now'\n" + " semaphore 'wait-inside'\n" + "}\n", true)); WorkflowRun r1 = j.scheduleBuild2(0).waitForStart(); story.j.waitForMessage("Lock acquired on [resource1]", r1); List<WorkflowRun> nextRuns = new ArrayList<>(); WorkflowRun r2 = j.scheduleBuild2(0).waitForStart(); story.j.waitForMessage("Lock acquired on [resource1]", r2); nextRuns.add(r2); for (int i = 0; i < 10; i++) { WorkflowRun rNext = j.scheduleBuild2(0).waitForStart(); System.err.println("Waiting to acquire initial lock for " + rNext.getNumber()); story.j.waitForMessage("Lock acquired on [resource1]", rNext); nextRuns.add(rNext); } for (WorkflowRun r : nextRuns) { System.err.println("Waiting to acquire second lock for " + r.getNumber()); story.j.waitForMessage("Lock acquired on [resource2]", r); } waitAndClear(r1, 1, nextRuns); } }); }

Target:
public void parallelLockRelease() throws Exception { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { LockableResourcesManager.get().createResource("resource1"); LockableResourcesManager.get().createResource("resource2"); WorkflowJob j = story.j.jenkins.createProject(WorkflowJob.class, "j"); j.setDefinition(new CpsFlowDefinition( "lock(resource: 'resource1') {\n" + " semaphore 'wait-inside-1'\n" + "}\n" + "lock(resource: 'resource2') { \n" + " echo 'Entering semaphore now'\n" + " semaphore 'wait-inside-2'\n" + "}\n", true)); List<WorkflowRun> nextRuns = new ArrayList<>(); WorkflowRun toUnlock = null; for (int i = 0; i < 5; i++) { WorkflowRun rNext = j.scheduleBuild2(0).waitForStart(); if (toUnlock != null) { story.j.waitForMessage("[resource1] is locked, waiting...", rNext); SemaphoreStep.success("wait-inside-1/" + i, toUnlock); } SemaphoreStep.waitForStart("wait-inside-1/" + (i + 1), rNext); nextRuns.add(rNext); toUnlock = rNext; } SemaphoreStep.success("wait-inside-1/" + nextRuns.size(), toUnlock); waitAndClear(1, nextRuns); } }); }
Source:
public Model read( File input, Map<String, ?> options ) throws IOException { Objects.requireNonNull( input, "input cannot be null" ); TransformerContext context = null; if ( options != null ) { context = (TransformerContext) options.get( "transformerContext" ); } final InputStream is; if ( context == null ) { is = new FileInputStream( input ); } else { try { is = transformer.transform( input.toPath(), context ); } catch ( TransformerConfigurationException | SAXException | ParserConfigurationException e ) { throw new IOException( "Failed to transform " + input, e ); } } Model model = read( is, options ); model.setPomFile( input ); return model; }

Target:
public Model read( File input, Map<String, ?> options ) throws IOException { Objects.requireNonNull( input, "input cannot be null" ); TransformerContext context = null; if ( options != null ) { context = (TransformerContext) options.get( "transformerContext" ); } final InputStream is; if ( context == null ) { is = new FileInputStream( input ); } else { try { is = transformer.transform( input.toPath(), context ); } catch ( TransformerException e ) { throw new IOException( "Failed to transform " + input, e ); } } try ( InputStream in = is ) { Model model = read( is, options ); model.setPomFile( input ); return model; } }
Source:
protected void endSuccessfully() { endCommandActions(); if (getSucceeded() && (getDiskImage().getContentType() == DiskContentType.MEMORY_DUMP_VOLUME || getDiskImage().getContentType() == DiskContentType.MEMORY_METADATA_VOLUME)) { List<Snapshot> snapshots = snapshotDao.getSnapshotsByMemoryDiskId(getDiskImage().getId()); snapshots.forEach(s -> s.getMemoryVolume()); } incrementDbGenerationForRelatedEntities(); }

Target:
protected void endSuccessfully() { endCommandActions(); incrementDbGenerationForRelatedEntities(); }
Source:
private void readPhoneNumber() { final String phoneNumber = SimCardReader.readPhoneNumber(this); if (!Util.isNullOrEmpty(phoneNumber)) { final String number = new SimlarNumber(phoneNumber).getNationalOnly(); mEditNumber.setText(number); final TextView text = (TextView) findViewById(R.id.textViewCheckOrVerifyYourNumber); text.setText(getString(R.string.verify_number_activity_verify_your_number)); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { showSoftInputForEditNumber(); } }, 100); } updateButtonAccept(); }

Target:
private void readPhoneNumber() { final String phoneNumber = SimCardReader.readPhoneNumber(this); if (!Util.isNullOrEmpty(phoneNumber)) { mEditNumber.setText(new SimlarNumber(phoneNumber).getNationalOnly()); final TextView text = (TextView) findViewById(R.id.textViewCheckOrVerifyYourNumber); text.setText(getString(R.string.verify_number_activity_verify_your_number)); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { showSoftInputForEditNumber(); } }, 100); } updateButtonAccept(); }