auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static KubernetesClient createClient(KubernetesCloud cloud) throws Exception { String displayName = cloud.getDisplayName(); final Client c = clients.getIfPresent(displayName); if (c == null) { KubernetesClient client = new KubernetesFactoryAdapter(cloud.getServerUrl(), cloud.getNamespace(), cloud.getServerCertificate(), cloud.getCredentialsId(), cloud.isSkipTlsVerify(), cloud.getConnectTimeout(), cloud.getReadTimeout(), cloud.getMaxRequestsPerHost()).createClient(); clients.put(displayName, new Client(getValidity(cloud), client)); LOGGER.log(Level.INFO, "Created new Kubernetes client: {0} {1}", new Object[] { displayName, client }); return client; } return c.getClient(); }

Target:
static KubernetesClient createClient(KubernetesCloud cloud) throws KubernetesAuthException, IOException { String displayName = cloud.getDisplayName(); final Client c = clients.getIfPresent(displayName); if (c == null) { KubernetesClient client = new KubernetesFactoryAdapter(cloud.getServerUrl(), cloud.getNamespace(), cloud.getServerCertificate(), cloud.getCredentialsId(), cloud.isSkipTlsVerify(), cloud.getConnectTimeout(), cloud.getReadTimeout(), cloud.getMaxRequestsPerHost()).createClient(); clients.put(displayName, new Client(getValidity(cloud), client)); LOGGER.log(Level.INFO, "Created new Kubernetes client: {0} {1}", new Object[] { displayName, client }); return client; } return c.getClient(); }
Source:
public double[] transformToDoubleValuesSV(ProjectionBlock projectionBlock) { int[] selected = getSelectedArray(projectionBlock); double[] results = new double[DocIdSetPlanNode.MAX_DOC_PER_CALL]; for (int i = 0; i < _elseThenStatements.size(); i++) { TransformFunction transformFunction = _elseThenStatements.get(i); FieldSpec.DataType dataType = transformFunction.getResultMetadata().getDataType(); switch (dataType) { case INT: int[] evalInts = transformFunction.transformToIntValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = evalInts[j]; } } break; case LONG: long[] evalLongs = transformFunction.transformToLongValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = evalLongs[j]; } } break; case FLOAT: float[] evalFloats = transformFunction.transformToFloatValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = evalFloats[j]; } } break; case DOUBLE: double[] evalDoubles = transformFunction.transformToDoubleValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = evalDoubles[j]; } } break; case STRING: String[] evalStrings = transformFunction.transformToStringValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = new BigDecimal(evalStrings[i]).doubleValue(); } } break; default: throw new IllegalStateException(String .format("Cannot convert result type [%s] to [DOUBLE] for transform function [%s]", dataType, transformFunction)); } } return results; }

Target:
public double[] transformToDoubleValuesSV(ProjectionBlock projectionBlock) { if (_resultMetadata.getDataType() != FieldSpec.DataType.DOUBLE) { return super.transformToDoubleValuesSV(projectionBlock); } int[] selected = getSelectedArray(projectionBlock); if (_doubleResults == null) { _doubleResults = new double[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } for (int i = 0; i < _elseThenStatements.size(); i++) { TransformFunction transformFunction = _elseThenStatements.get(i); FieldSpec.DataType dataType = transformFunction.getResultMetadata().getDataType(); int blockNumDocs = projectionBlock.getNumDocs(); double[] evalDoubles; if (dataType == FieldSpec.DataType.DOUBLE) { evalDoubles = transformFunction.transformToDoubleValuesSV(projectionBlock); } else { evalDoubles = new double[blockNumDocs]; switch (dataType) { case INT: ArrayCopyUtils.copy(transformFunction.transformToIntValuesSV(projectionBlock), evalDoubles, blockNumDocs); break; case LONG: ArrayCopyUtils.copy(transformFunction.transformToLongValuesSV(projectionBlock), evalDoubles, blockNumDocs); break; case FLOAT: ArrayCopyUtils.copy(transformFunction.transformToFloatValuesSV(projectionBlock), evalDoubles, blockNumDocs); break; default: throw new IllegalStateException(String .format("Cannot convert result type [%s] to [DOUBLE] for transform function [%s]", dataType, transformFunction)); } } for (int j = 0; j < blockNumDocs; j++) { if (selected[j] == i) { _doubleResults[j] = evalDoubles[j]; } } } return _doubleResults; }
Source:
default void onBeforeClass(ITestClass testClass) { throw new UnsupportedOperationException("Method is not implemented"); }

Target:
default void onBeforeClass(ITestClass testClass) { }
Source:
public Observable<ResultsPage<Entity>> searchCollection( final CollectionSearch search ) { final ApplicationScope applicationScope = search.getApplicationScope(); final String collectionName = search.getCollectionName(); final Optional<String> query = search.getQuery(); final IdBuilder pipelineBuilder = pipelineBuilderFactory.create( applicationScope ) .withCursor( search.getCursor() ) .withLimit( search.getLimit() ) .keepStaleEntries(search.getKeepStaleEntries()) .query(search.getQuery()) .fromId( search.getCollectionOwnerId() ); final EntityBuilder results; if ( !query.isPresent()) { results = pipelineBuilder.traverseCollection( collectionName ).loadEntities(); } else { results = pipelineBuilder.searchCollection( collectionName, query.get(),search).loadEntities(); } return results.build(); }

Target:
public Observable<ResultsPage<Entity>> searchCollection( final CollectionSearch search ) { final ApplicationScope applicationScope = search.getApplicationScope(); final String collectionName = search.getCollectionName(); final Optional<String> query = search.getQuery(); final IdBuilder pipelineBuilder = pipelineBuilderFactory.create( applicationScope ) .withCursor( search.getCursor() ) .withLimit( search.getLimit() ) .keepStaleEntries(search.getKeepStaleEntries()) .query(query) .fromId( search.getCollectionOwnerId() ); final EntityBuilder results; if ( !query.isPresent()) { results = pipelineBuilder.traverseCollection( collectionName ).loadEntities(); } else { results = pipelineBuilder.searchCollection( collectionName, query.get(),search).loadEntities(); } return results.build(); }
Source:
public void replacePopulations(List<T> main, List<T> temp){ for(int i=0; i<populationSize; i++){ T mainIndividual = main.get(i); T tempIndividual = temp.get(i); for (FitnessFunction<T> fitnessFunction : fitnessFunctions) { fitnessFunction.getFitness(mainIndividual); notifyEvaluation(mainIndividual); fitnessFunction.getFitness(tempIndividual); notifyEvaluation(tempIndividual); } if(keepOffspring(mainIndividual, tempIndividual)){ if (!(isTooLong(tempIndividual) || tempIndividual.size() == 0)){ main.set(i, tempIndividual); } } } }

Target:
public void replacePopulations(List<T> main, List<T> temp){ assert main.size() == temp.size(); for(int i=0; i<Properties.POPULATION; i++){ T mainIndividual = main.get(i); T tempIndividual = temp.get(i); for (FitnessFunction<T> fitnessFunction : fitnessFunctions) { fitnessFunction.getFitness(mainIndividual); notifyEvaluation(mainIndividual); fitnessFunction.getFitness(tempIndividual); notifyEvaluation(tempIndividual); } if(isBetterOrEqual(mainIndividual, tempIndividual)){ if (!(isTooLong(tempIndividual) || tempIndividual.size() == 0)){ main.set(i, tempIndividual); } } } }
Source:
protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = new DateTime(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); if (beginValidTime != null && endValidTime != null) { if (isConditionsDefaultValueEnabled()) { beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); } if(beginValidTime.isBefore(endValidTime)) { return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); } } return null; }

Target:
protected Conditions createConditions(final CallbackProperties properties) { DateTime issueInstant = new DateTime(); DateTime beginValidTime = properties.getSamlConditionsNotBefore(); DateTime endValidTime = properties.getSamlConditionsNotAfter(); if (beginValidTime != null && endValidTime != null) { if (isConditionsDefaultValueEnabled() || beginValidTime.isAfter(endValidTime)) { beginValidTime = setBeginValidTime(beginValidTime, issueInstant); endValidTime = setEndValidTime(endValidTime, issueInstant); } return OpenSAML2ComponentBuilder.getInstance().createConditions(beginValidTime, endValidTime); } return null; }
Source:
public void testReadResolve() throws IOException { User user = User.get("User"); MyViewsProperty property = new MyViewsProperty(AllView.DEFAULT_VIEW_NAME); property.setUser(user); user.addProperty(property); property.readResolve(); assertNotNull("Property should contain " + AllView.DEFAULT_VIEW_NAME + " default.", property.getView(AllView.DEFAULT_VIEW_NAME)); }

Target:
public void testReadResolve() throws IOException { User user = User.get("User"); MyViewsProperty property = new MyViewsProperty(AllView.DEFAULT_VIEW_NAME); property.setUser(user); user.addProperty(property); property.readResolve(); assertNotNull("Property should contain " + AllView.DEFAULT_VIEW_NAME + " by default.", property.getView(AllView.DEFAULT_VIEW_NAME)); }
Source:
public String getResolvedAddress(String hostname) { if (_resolvedAddress.isPresent()) return _resolvedAddress.get(); ProcessTaskWrapper<Integer> task = SshEffectorTasks.ssh("ping -c 1 -t 1 "+hostname).machine(getMachine()) .summary("checking resolution of "+hostname).allowingNonZeroExitCode().newTask(); DynamicTasks.queueIfPossible(task).orSubmitAndBlock(getEntity()).asTask().blockUntilEnded(); if (task.asTask().isError()) { log.warn("ping could not be run, at "+getEntity()+" / "+getMachine()+": "+Tasks.getError(task.asTask())); return ""; } if (task.getExitCode()==null || task.getExitCode()!=0) { if (task.getExitCode()!=null && task.getExitCode()<10) return (_resolvedAddress = Maybe.of((String)null)).get(); log.warn("ping not run as expected, at "+getEntity()+" / "+getMachine()+" (code "+task.getExitCode()+"):\n"+task.getStdout().trim()+" --- "+task.getStderr().trim()); return (_resolvedAddress = Maybe.of("")).get(); } String out = task.getStdout(); try { String line1 = Strings.getFirstLine(out); String ip = Strings.getFragmentBetween(line1, "(", ")"); if (Strings.isNonBlank(ip)) return (_resolvedAddress = Maybe.of(ip)).get(); } catch (Exception e) { } if (out.contains("127.0.0.1")) return (_resolvedAddress = Maybe.of("127.0.0.1")).get(); return (_resolvedAddress = Maybe.of("")).get(); }

Target:
public String getResolvedAddress(String hostname) { if (resolvedAddressCache.isPresent()) return resolvedAddressCache.get(); return (resolvedAddressCache = Maybe.of(BrooklynAccessUtils.getResolvedAddress(getEntity(), getMachine(), hostname))).get(); }
Source:
public void setEnvironment(String value) { switch (value) { case "LEGACY": this.environment = CompilerOptions.Environment.BROWSER; break; case "CUSTOM": this.environment = CompilerOptions.Environment.CUSTOM; break; default: throw new BuildException( "Unrecognized 'environment' option value (" + value + ")"); } }

Target:
public void setEnvironment(String value) { switch (value) { case "BROWSER": this.environment = CompilerOptions.Environment.BROWSER; break; case "CUSTOM": this.environment = CompilerOptions.Environment.CUSTOM; break; default: throw new BuildException( "Unrecognized 'environment' option value (" + value + ")"); } }
Source:
String getLiveness() { String liveness = UP; if (resourceStatePolicy.isHardDown()) { liveness = NODE_DOWN; } else if (resourceStatePolicy.isDown()) { liveness = SOFT_DOWN; } return liveness; }

Target:
String getLiveness() { return resourceStatePolicy.isHardDown() ? NODE_DOWN : resourceStatePolicy.isDown() ? SOFT_DOWN : UP; }
Source:
public void fetchEapMethods() throws Exception { final List<MethodType> encodings = Lists.newArrayList(EAP_SIM, IDENTITY); final List<String> list = Lists.newArrayList("EAP_SIM", "IDENTITY"); context.checking(new Expectations() {{ oneOf(methodCatalog).findAll(); will(returnValue(encodings)); }}); Reply<?> reply = endpoint.fetchEapMethods(); assertThat(reply, contains(list)); assertThat(reply, isOk()); }

Target:
public void fetchEapMethods() throws Exception { final List<Method> methods = Lists.newArrayList(EAP_SIM, IDENTITY); final List<String> dtos = Lists.newArrayList("EAP_SIM", "IDENTITY"); context.checking(new Expectations() {{ oneOf(methodCatalog).findAll(); will(returnValue(methods)); }}); Reply<?> reply = endpoint.fetchEapMethods(); assertThat(reply, contains(dtos)); assertThat(reply, isOk()); }
Source:
public static UUID boundJobId(@Nullable Symbol jobId, CoordinatorTxnCtx txnCtx, Functions functions, Row parameters, SubQueryResults subQueryResults) { if (jobId != null) { try { return UUID.fromString( DataTypes.STRING.value( SymbolEvaluator.evaluate( txnCtx, functions, jobId, parameters, subQueryResults ))); } catch (Exception e) { throw new IllegalArgumentException("Can not parse job ID", e); } } return null; }

Target:
public static UUID boundJobId(@Nullable Symbol jobId, CoordinatorTxnCtx txnCtx, Functions functions, Row parameters, SubQueryResults subQueryResults) { if (jobId != null) { try { return UUID.fromString( DataTypes.STRING.value( SymbolEvaluator.evaluate( txnCtx, functions, jobId, parameters, subQueryResults ))); } catch (Exception e) { throw new IllegalArgumentException("Can not parse job ID: " + jobId, e); } } return null; }
Source:
public String toString() { return "TdchParameters [_mrParams=" + _mrParams + ", _libJars=" + _libJars + ", _tdJdbcClassName=" + _tdJdbcClassName + ", _tdUrl=" + _tdUrl + ", _fileFormat=" + _fileFormat + ", _fieldSeparator=" + _fieldSeparator + ", _jobType=" + _jobType + ", _userName=" + _userName + ", _tdPassword=" + getMaskedPassword() + ", _avroSchemaPath=" + _avroSchemaPath + ", _numMappers=" + _numMappers + ", _tdchType=" + _tdchType + ", _sourceHdfsPath=" + _sourceHdfsPath + ", _targetTdTableName=" + _targetTdTableName + ", _tdInsertMethod=" + _tdInsertMethod + ", _sourceQuery=" + _sourceQuery + ", _sourceTdTableName=" + _sourceTdTableName + ", _tdRetrieveMethod=" + _tdRetrieveMethod + ", _targetHdfsPath=" + _targetHdfsPath + "]"; }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TdchParameters [_mrParams=").append(_mrParams) .append(", _libJars=").append(_libJars) .append(", _tdJdbcClassName=").append(_tdJdbcClassName) .append(", _tdUrl=").append(_tdUrl) .append(", _fileFormat=").append(_fileFormat) .append(", _fieldSeparator=").append(_fieldSeparator) .append(", _jobType=").append(_jobType) .append(", _userName=").append(_userName) .append(", _tdPassword=").append(getMaskedPassword()) .append(", _avroSchemaPath=").append(_avroSchemaPath) .append(", _numMappers=").append(_numMappers) .append(", _tdchType=").append(_tdchType) .append(", _sourceHdfsPath=").append(_sourceHdfsPath) .append(", _targetTdTableName=").append(_targetTdTableName) .append(", _tdInsertMethod=").append(_tdInsertMethod) .append(", _sourceQuery=").append(_sourceQuery) .append(", _sourceTdTableName=").append(_sourceTdTableName) .append(", _tdRetrieveMethod=").append(_tdRetrieveMethod) .append(", _targetHdfsPath=").append(_targetHdfsPath) .append("]"); return builder.toString(); }
Source:
protected void nocache(final HttpServletResponse rsp) { rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, must-revalidate"); }

Target:
protected void nocache(final HttpServletResponse rsp) { rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate"); }
Source:
private void execute(final ITmfTrace trace) { if (fFinishedLatch.getCount() == 0) { return; } synchronized (syncObj) { if (fStarted) { return; } fStarted = true; } final Iterable<IAnalysisModule> dependentAnalyses = getDependentAnalyses(); for (IAnalysisModule module : dependentAnalyses) { module.schedule(); } String jobName = NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName()); fJob = new Job(jobName) { @Override protected @Nullable IStatus run(final @Nullable IProgressMonitor monitor) { IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } try { mon.beginTask("", IProgressMonitor.UNKNOWN); broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this)); fAnalysisCancelled = !executeAnalysis(mon); for (IAnalysisModule module : dependentAnalyses) { module.waitForCompletion(mon); } } catch (TmfAnalysisException e) { Activator.logError("Error executing analysis with trace " + trace.getName(), e); } finally { synchronized (syncObj) { mon.done(); setAnalysisCompleted(); } TmfTraceManager.refreshSupplementaryFiles(trace); } if (!fAnalysisCancelled) { return Status.OK_STATUS; } resetAnalysis(); return Status.CANCEL_STATUS; } @Override protected void canceling() { TmfAbstractAnalysisModule.this.canceling(); } }; fJob.schedule(); }

Target:
private void execute(final ITmfTrace trace) { if (fFinishedLatch.getCount() == 0) { return; } synchronized (syncObj) { if (fStarted) { return; } fStarted = true; } final Iterable<IAnalysisModule> dependentAnalyses = getDependentAnalyses(); for (IAnalysisModule module : dependentAnalyses) { module.schedule(); } String jobName = checkNotNull(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName())); fJob = new Job(jobName) { @Override protected @Nullable IStatus run(final @Nullable IProgressMonitor monitor) { IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } try { mon.beginTask("", IProgressMonitor.UNKNOWN); broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this)); fAnalysisCancelled = !executeAnalysis(mon); for (IAnalysisModule module : dependentAnalyses) { module.waitForCompletion(mon); } } catch (TmfAnalysisException e) { Activator.logError("Error executing analysis with trace " + trace.getName(), e); } finally { synchronized (syncObj) { mon.done(); setAnalysisCompleted(); } TmfTraceManager.refreshSupplementaryFiles(trace); } if (!fAnalysisCancelled) { return Status.OK_STATUS; } resetAnalysis(); return Status.CANCEL_STATUS; } @Override protected void canceling() { TmfAbstractAnalysisModule.this.canceling(); } }; fJob.schedule(); }
Source:
public static ThreadGroup[] getAllThreadGroups() { final ThreadGroup systemThreadGroup = getSystemThreadGroup(); int estimatedThreadGroupCount = systemThreadGroup.activeGroupCount(); int threadGroupCount = 0; ThreadGroup[] threadGroups; do { estimatedThreadGroupCount *= 2; threadGroups = new ThreadGroup[estimatedThreadGroupCount]; threadGroupCount = systemThreadGroup.enumerate(threadGroups); } while (threadGroupCount == estimatedThreadGroupCount); final ThreadGroup[] allGroups = new ThreadGroup[threadGroupCount+1]; allGroups[0] = systemThreadGroup; System.arraycopy(threadGroups, 0, allGroups, 1, threadGroupCount); return allGroups; }

Target:
public static Collection<ThreadGroup> getAllThreadGroups() { return selectThreadGroups(ALWAYS_TRUE_PREDICATE); }
Source:
private ModuleType verifyModuleOfTypeExists(ModuleDeploymentRequest request, String moduleName, ModuleType type) { ModuleDefinition def = moduleDefinitionRepository.findByNameAndType(moduleName, type); if (def == null || def.getResource() == null) { List<ModuleDefinition> definitions = moduleDefinitionRepository.findByName(moduleName); if (definitions == null || definitions.size() == 0) { throw new NoSuchModuleException(moduleName); } return definitions.get(0).getType(); } return def.getType(); }

Target:
private ModuleType verifyModuleOfTypeExists(ModuleDeploymentRequest request, String moduleName, ModuleType type) { ModuleDefinition def = moduleDefinitionRepository.findByNameAndType(moduleName, type); if (def == null || def.getResource() == null) { List<ModuleDefinition> definitions = moduleDefinitionRepository.findByName(moduleName); if (definitions.isEmpty()) { throw new NoSuchModuleException(moduleName); } return definitions.get(0).getType(); } return def.getType(); }
Source:
public String createEntityType(DataCollection dataCollection) { String entityTypeId = idGenerator.generateId(); EntityType entityType = entityTypeFactory.create(); entityType.setPackage(defaultPackage); entityType.setId(entityTypeId); entityType.setLabel(dataCollection.getName()); entityType.addAttribute(createIdAttribute(), ROLE_ID); dataCollection.getColumns().forEach(column -> entityType.addAttribute(createAttribute(column))); metaDataService.addEntityType(entityType); AtomicInteger rowIndex = new AtomicInteger(0); List<Entity> rows = newArrayList(); while (rowIndex.get() < dataCollection.getNumberOfRows()) { Entity row = entityManager.create(entityType, NO_POPULATE); row.setIdValue(idGenerator.generateId()); final int finalRowIndex = rowIndex.getAndIncrement(); dataCollection.getColumns() .forEach(column -> row.set(column.getName(), column.getDataValues().get(finalRowIndex))); rows.add(row); } dataService.add(entityType.getId(), rows.stream()); return entityTypeId; }

Target:
public EntityType createEntityType(DataCollection dataCollection) { String entityTypeId = idGenerator.generateId(); EntityType entityType = entityTypeFactory.create(); entityType.setPackage(defaultPackage); entityType.setId(entityTypeId); entityType.setLabel(dataCollection.getName()); entityType.addAttribute(createIdAttribute(), ROLE_ID); dataCollection.getColumns().forEach(column -> { Attribute attribute = createAttribute(column); entityType.addAttribute(attribute); }); metaDataService.addEntityType(entityType); AtomicInteger rowIndex = new AtomicInteger(0); List<Entity> rows = newArrayList(); while (rowIndex.get() < dataCollection.getNumberOfRows()) { Entity row = entityManager.create(entityType, NO_POPULATE); row.setIdValue(idGenerator.generateId()); int index = rowIndex.getAndIncrement(); dataCollection.getColumns().forEach(column -> setRowValueForAttribute(row, index, column)); rows.add(row); } dataService.add(entityType.getId(), rows.stream()); return entityType; }
Source:
public static void tearDown() throws InterruptedException, TimeoutException, IOException, OperationException { operations.removeIfExists(C_HANDLER_ADDRESS); administration.reloadIfRequired(); operations.removeIfExists(C_HANDLER_TB_REMOVED_ADDRESS); administration.reloadIfRequired(); }

Target:
public static void tearDown() throws InterruptedException, TimeoutException, IOException, OperationException { operations.removeIfExists(C_HANDLER_ADDRESS); operations.removeIfExists(C_HANDLER_TB_REMOVED_ADDRESS); administration.reloadIfRequired(); }
Source:
private void handleIntent(Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null) { Site site = new Site(intent.getData().getAuthority()); PageTitle title = site.titleForUri(intent.getData()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_EXTERNAL_LINK); displayPageInForegroundTab(title, historyEntry); } else if (ACTION_PAGE_FOR_TITLE.equals(intent.getAction())) { hideLinkPreview(); PageTitle title = intent.getParcelableExtra(EXTRA_PAGETITLE); HistoryEntry historyEntry = intent.getParcelableExtra(EXTRA_HISTORYENTRY); displayNewPage(title, historyEntry); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); PageTitle title = new PageTitle(query, app.getPrimarySite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_SEARCH); displayPageInForegroundTab(title, historyEntry); } else if (Intent.ACTION_SEND.equals(intent.getAction()) && PLAIN_TEXT_MIME_TYPE.equals(intent.getType())) { handleShareIntent(intent); } else if (intent.hasExtra(EXTRA_SEARCH_FROM_WIDGET)) { new WidgetsFunnel(app).logSearchWidgetTap(); openSearch(); } else if (intent.hasExtra(EXTRA_FEATURED_ARTICLE_FROM_WIDGET)) { new WidgetsFunnel(app).logFeaturedArticleWidgetTap(); displayMainPageInForegroundTab(); } else { displayMainPageIfNoTabs(); } }

Target:
private void handleIntent(Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null) { Site site = new Site(intent.getData().getAuthority()); PageTitle title = site.titleForUri(intent.getData()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_EXTERNAL_LINK); displayPageInForegroundTab(title, historyEntry); } else if (ACTION_PAGE_FOR_TITLE.equals(intent.getAction())) { PageTitle title = intent.getParcelableExtra(EXTRA_PAGETITLE); HistoryEntry historyEntry = intent.getParcelableExtra(EXTRA_HISTORYENTRY); displayNewPage(title, historyEntry); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); PageTitle title = new PageTitle(query, app.getPrimarySite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_SEARCH); displayPageInForegroundTab(title, historyEntry); } else if (Intent.ACTION_SEND.equals(intent.getAction()) && PLAIN_TEXT_MIME_TYPE.equals(intent.getType())) { handleShareIntent(intent); } else if (intent.hasExtra(EXTRA_SEARCH_FROM_WIDGET)) { new WidgetsFunnel(app).logSearchWidgetTap(); openSearch(); } else if (intent.hasExtra(EXTRA_FEATURED_ARTICLE_FROM_WIDGET)) { new WidgetsFunnel(app).logFeaturedArticleWidgetTap(); displayMainPageInForegroundTab(); } else { displayMainPageIfNoTabs(); } }
Source:
private double getWeightValue(Tuple input){ double weight = 1.0; if(StringUtils.isNotBlank(modelConfig.getWeightColumnName())) { for(ColumnConfig columnConfig: columnConfigList) { if(columnConfig.getColumnName().equalsIgnoreCase(modelConfig.getWeightColumnName().trim())) { int columnId = columnConfig.getColumnNum(); try { weight = Double.parseDouble(((DataByteArray) input.get(columnId)).toString()); } catch (ExecException ignore) { } break; } } } return weight; }

Target:
private double getWeightValue(Tuple input){ double weight = 1.0; int columnId = getWeightColumnId(); if(columnId != INVALID_INDEX){ try { weight = Double.parseDouble(String.valueOf(input.get(columnId))); } catch (ExecException ignore) { } } return weight; }
Source:
public void testInsertionQualityFilter() { final SAMRecordSetBuilder builder = getRecordBuilder(); final int startPosition = 165; String qualityString = "++++++++++,,,+++++++++++++++++***+++"; for (int i = 0; i < coverage; i++) { builder.addFrag("record" + i, 0, startPosition, true, false, "10M3I17M3I3M", qualityString, 10); } final int insStart1 = 174; final int insStart2 = 194; for (final boolean incIndels : new boolean[] {false, true}) { final SamLocusIterator sli = createSamLocusIterator(builder); sli.setIncludeIndels(incIndels); sli.setQualityScoreCutoff(10); int pos = startPosition; for (final SamLocusIterator.LocusInfo li : sli) { Assert.assertEquals(li.getPosition(), pos++); Assert.assertEquals(li.getRecordAndOffsets().size(), coverage); for (final SamLocusIterator.RecordAndOffset rao : li.getRecordAndOffsets()) { Assert.assertEquals(rao.getAlignmentType(), SamLocusIterator.RecordAndOffset.AlignmentType.Match); } Assert.assertEquals(li.size(), coverage); Assert.assertEquals(li.getDeletedInRecord().size(), 0); if (incIndels && li.getPosition() == insStart1) { Assert.assertEquals(li.getInsertedInRecord().size(), coverage); for (final SamLocusIterator.RecordAndOffset rao : li.getInsertedInRecord()) { Assert.assertEquals(rao.getAlignmentType(), SamLocusIterator.RecordAndOffset.AlignmentType.Insertion); } } else if (incIndels && li.getPosition() == insStart2){ Assert.assertEquals(li.getInsertedInRecord().size(), 0); } else { Assert.assertEquals(li.getInsertedInRecord().size(), 0); } } } }

Target:
public void testInsertionQualityFilter() { final SAMRecordSetBuilder builder = getRecordBuilder(); final int startPosition = 165; String qualityString = "++++++++++,,,+++++++++++++++++***+++"; for (int i = 0; i < coverage; i++) { builder.addFrag("record" + i, 0, startPosition, true, false, "10M3I17M3I3M", qualityString, 10); } final int insStart1 = 174; final int insStart2 = 191; for (final int qualityScoreCutoff : new int[] {0, 10}){ final SamLocusIterator sli = createSamLocusIterator(builder); sli.setQualityScoreCutoff(10); sli.setQualityScoreCutoff(qualityScoreCutoff); sli.includeIndels = true; int pos = startPosition; for (final SamLocusIterator.LocusInfo li : sli) { Assert.assertEquals(li.getPosition(), pos++); Assert.assertEquals(li.getRecordAndOffsets().size(), coverage); for (final SamLocusIterator.RecordAndOffset rao : li.getRecordAndOffsets()) { Assert.assertEquals(rao.getAlignmentType(), SamLocusIterator.RecordAndOffset.AlignmentType.Match); } Assert.assertEquals(li.size(), coverage); Assert.assertEquals(li.getDeletedInRecord().size(), 0); if (li.getPosition() == insStart1) { Assert.assertEquals(li.getInsertedInRecord().size(), coverage); for (final SamLocusIterator.RecordAndOffset rao : li.getInsertedInRecord()) { Assert.assertEquals(rao.getAlignmentType(), SamLocusIterator.RecordAndOffset.AlignmentType.Insertion); } } else if ((qualityScoreCutoff == 0) && (li.getPosition() == insStart2)) { Assert.assertEquals(li.getInsertedInRecord().size(), coverage); } else { Assert.assertEquals(li.getInsertedInRecord().size(), 0); } } } }
Source:
private void loadDefinitions() { PageService contentService = ContentServiceFactory.create(new Site(pageTitle.getSite().getLanguageCode() + WIKTIONARY_DOMAIN)); if (contentService instanceof RbContentService) { ((RbContentService) contentService).define( addUnderscores(selectedText), definitionOnLoadCallback); } else { FeedbackUtil.showMessage(getActivity(), "Wiktionary definitions require mobile content service loading!"); } }

Target:
private void loadDefinitions() { PageService contentService = ContentServiceFactory.create(new Site(pageTitle.getSite().getLanguageCode() + WIKTIONARY_DOMAIN)); if (contentService instanceof RbContentService) { ((RbContentService) contentService).define( addUnderscores(selectedText), definitionOnLoadCallback); } else { L.e("Wiktionary definitions require mobile content service loading!"); displayNoDefinitionsFound(); } }
Source:
private void sendEquivalentContentChangedMessage(Content content, EquivalenceGraph graph) throws MessagingException { contentUpdatedMessageSender.sendMessage( new EquivalentContentUpdatedMessage( UUID.randomUUID().toString(), Timestamp.of(DateTime.now(DateTimeZone.UTC)), graph.getId().longValue(), content.toRef() ), getPartitionKey(graph.getId()) ); }

Target:
private void sendEquivalentContentChangedMessage(Content content, EquivalenceGraph graph) throws MessagingException { equivContentUpdatedMessageSender.sendMessage( new EquivalentContentUpdatedMessage( UUID.randomUUID().toString(), Timestamp.of(DateTime.now(DateTimeZone.UTC)), graph.getId().longValue(), content.toRef() ), getPartitionKey(graph.getId()) ); }
Source:
public TrackStatistics (final long trackId, ContentResolver cr) { this.trackId = trackId; contentResolver = cr; length = 0; maxSpeed = 0; pointCount = 0; timeMoving = 0; update(); }

Target:
public TrackStatistics (final long trackId, ContentResolver cr) { this.trackId = trackId; contentResolver = cr; update(); }
Source:
public boolean isChildPolicyAllowed(SchedulingPolicy childPolicy) throws AllocationConfigurationException { throw new AllocationConfigurationException(getName() + " policy is only for" + " leaf queues. Please choose policies other than " + getName() + " for parent queues."); }

Target:
public boolean isChildPolicyAllowed(SchedulingPolicy childPolicy) { LOG.error(getName() + " policy is only for leaf queues. Please choose " + DominantResourceFairnessPolicy.NAME + " or " + FairSharePolicy.NAME + " for parent queues."); return false; }
Source:
private TNonblockingTransport getTransport(FrameBuffer frameBuffer) { try { return (TNonblockingTransport) fbTansportField.get(frameBuffer); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } }

Target:
private TNonblockingTransport getTransport(FrameBuffer frameBuffer) { try { return (TNonblockingTransport) fbTansportField.get(frameBuffer); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
public int readToEndOfSegment() throws Exception { int end = (m_totalRead/47 + 1) * 47; boolean done = false; int numRead = 0; for (int i=m_totalRead; i<end && !done; i++) { BBContainer bbC = m_reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY); if (bbC==null) { done = true; continue; } numRead++; bbC.discard(); } return numRead; }

Target:
public int readToEndOfSegment() throws Exception { int end = (m_totalRead/s_segmentFillCount + 1) * s_segmentFillCount; boolean done = false; int numRead = 0; for (int i=m_totalRead; i<end && !done; i++) { BBContainer bbC = m_reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY); if (bbC==null) { done = true; continue; } numRead++; bbC.discard(); } return numRead; }
Source:
public CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId) { if (rpcManager != null) { TxCompletionNotificationCommand ftc = commandFactory.buildTxCompletionNotificationCommand(internalId); CompletionStage<Void> stage = sendTxCompletionNotification(where, ftc); return stage.thenRun(() -> removeRecoveryInformation(internalId)); } else { removeRecoveryInformation(internalId); return CompletableFutures.completedNull(); } }

Target:
public CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId) { if (rpcManager != null) { TxCompletionNotificationCommand ftc = commandFactory.buildTxCompletionNotificationCommand(internalId); CompletionStage<Void> stage = sendTxCompletionNotification(where, ftc); removeRecoveryInformation(internalId); return stage; } else { removeRecoveryInformation(internalId); return CompletableFutures.completedNull(); } }
Source:
public boolean equals(Object obj) { if (obj instanceof Entry) { Entry<?, ?> other = (Entry<?, ?>) obj; Object k1 = entry.getKey(); @SuppressWarnings("unchecked") Object k2 = (other instanceof CaseInsentiveEntry) ? ((CaseInsentiveEntry<K, V>) other).entry.getKey() : other.getKey(); if (Objects.equals(k1, k2)) { if (Objects.equals(entry.getValue(), other.getValue())) { return true; } } } return false; }

Target:
public boolean equals(Object obj) { if (obj instanceof Entry) { Entry<?, ?> other = (Entry<?, ?>) obj; Object k1 = entry.getKey(); @SuppressWarnings("unchecked") Object k2 = (other instanceof CaseInsentiveEntry) ? ((CaseInsentiveEntry<K, V>) other).entry.getKey() : other.getKey(); return Objects.equals(k1, k2) && Objects.equals(entry.getValue(), other.getValue()); } return false; }
Source:
private static String parameters(ITestResult testResult) { Object[] parameters = testResult.getParameters(); if (parameters != null) { StringBuilder builder = new StringBuilder(); for (Object parameter : parameters) { if (parameter instanceof Method) { builder.append(((Method) parameter).getName()); } } if (builder.length() != 0) { return "[" + builder.toString() + "]"; } } return ""; }

Target:
private static String parameters(ITestResult testResult) { Object[] parameters = testResult.getParameters(); if (parameters == null) { return ""; } String returnValue = ""; StringBuilder builder = new StringBuilder(); for (Object parameter : parameters) { if (parameter instanceof Method) { builder.append(((Method) parameter).getName()); } } if (builder.length() != 0) { returnValue = "[" + builder.toString() + "]"; } return returnValue; }
Source:
protected void executeCommand() { getStorageDomain().setStorageFormat( VersionStorageFormatUtil.getPreferredForVersion( getStoragePool().getcompatibility_version(), getStoragePool().getStorageType())); super.executeCommand(); if (getSucceeded()) { VdcReturnValueBase returnValue = Backend.getInstance() .runInternalAction( VdcActionType.AttachStorageDomainToPool, new StorageDomainPoolParametersBase(getStorageDomain().getId(), getStoragePool().getId())); if(!returnValue.getSucceeded()) { getReturnValue().setSucceeded(false); getReturnValue().setFault(returnValue.getFault()); } } }

Target:
protected void executeCommand() { getStorageDomain().setStorageFormat( VersionStorageFormatUtil.getPreferredForVersion( getStoragePool().getcompatibility_version(), getStorageDomain().getStorageType())); super.executeCommand(); if (getSucceeded()) { VdcReturnValueBase returnValue = Backend.getInstance() .runInternalAction( VdcActionType.AttachStorageDomainToPool, new StorageDomainPoolParametersBase(getStorageDomain().getId(), getStoragePool().getId())); if(!returnValue.getSucceeded()) { getReturnValue().setSucceeded(false); getReturnValue().setFault(returnValue.getFault()); } } }
Source:
private LogEntry getLogEntryByRevision(ILogEntry[] entries, String revision) { for (ILogEntry entrie : entries) { if (entrie.getRevision().equals(revision) && entrie instanceof LogEntry) { return (LogEntry) entrie; } } return null; }

Target:
private LogEntry getLogEntryByRevision(ILogEntry[] entries, String revision) { for (ILogEntry entry : entries) { if (entry.getRevision().equals(revision) && entry instanceof LogEntry) { return (LogEntry) entry; } } return null; }
Source:
private RequestFuture<ListOffsetResult> sendListOffsetRequest(final Node node, final Map<TopicPartition, ListOffsetRequest.PartitionData> timestampsToSearch, boolean requireTimestamp) { ListOffsetRequest.Builder builder = ListOffsetRequest.Builder .forConsumer(requireTimestamp, isolationLevel) .setTargetTimes(timestampsToSearch); log.error("[CHIA] Sending ListOffsetRequest to broker {}", builder, node); return client.send(node, builder) .compose(new RequestFutureAdapter<ClientResponse, ListOffsetResult>() { @Override public void onSuccess(ClientResponse response, RequestFuture<ListOffsetResult> future) { ListOffsetResponse lor = (ListOffsetResponse) response.responseBody(); log.trace("Received ListOffsetResponse from broker {}", lor, node); handleListOffsetResponse(timestampsToSearch, lor, future); } }); }

Target:
private RequestFuture<ListOffsetResult> sendListOffsetRequest(final Node node, final Map<TopicPartition, ListOffsetRequest.PartitionData> timestampsToSearch, boolean requireTimestamp) { ListOffsetRequest.Builder builder = ListOffsetRequest.Builder .forConsumer(requireTimestamp, isolationLevel) .setTargetTimes(timestampsToSearch); log.debug("Sending ListOffsetRequest to broker {}", builder, node); return client.send(node, builder) .compose(new RequestFutureAdapter<ClientResponse, ListOffsetResult>() { @Override public void onSuccess(ClientResponse response, RequestFuture<ListOffsetResult> future) { ListOffsetResponse lor = (ListOffsetResponse) response.responseBody(); log.trace("Received ListOffsetResponse from broker {}", lor, node); handleListOffsetResponse(timestampsToSearch, lor, future); } }); }
Source:
public void emit(Bundle bundle) { log.debug("output: {}", bundle); getOutput().send(bundle); outputCountMetric.inc(); processedMeterMetric.mark(); totalEmit.incrementAndGet(); bundleTimeSum.addAndGet(getBundleTime(bundle) >> 8); }

Target:
public void emit(Bundle bundle) { log.debug("output: {}", bundle); getOutput().send(bundle); outputCountMetric.inc(); processedMeterMetric.mark(); totalEmit.incrementAndGet(); if (timeField != null) bundleTimeSum.addAndGet(getBundleTime(bundle) >> 8); }
Source:
public List<BlockLocationInfo> getBlockLocations(AlluxioURI alluxioURI) throws IOException { Path path = toPath(alluxioURI); BlockLocation[] fileBlockLocations = fileSystem.getFileBlockLocations(path, 0, path.toString().length()); Arrays.stream(fileBlockLocations).map(this::toBlockLocationInfo).collect(Collectors.toList()); throw new UnsupportedOperationException("GetBlockLocations is not supported."); }

Target:
public List<BlockLocationInfo> getBlockLocations(AlluxioURI alluxioURI) { throw new UnsupportedOperationException("GetBlockLocations is not supported."); }
Source:
default CurrentTransferSegment createTransferSegment(long start, long end, SegmentState state) { if (state == RESTORED || state == TRANSFERRED) { return CurrentTransferSegment .builder() .status( CurrentTransferSegmentStatus .builder() .totalTransferred(end - start + 1) .segmentState(state) .build() ) .startAddress(start) .endAddress(end) .build(); } else { return CurrentTransferSegment .builder() .status( CurrentTransferSegmentStatus .builder() .totalTransferred(0L) .segmentState(state) .causeOfFailure(Optional.of(new TransferSegmentFailure())) .build() ) .startAddress(start) .endAddress(end) .build(); } }

Target:
default TransferSegment createTransferSegment(long start, long end, SegmentState state) { if (state == RESTORED || state == TRANSFERRED) { return TransferSegment .builder() .status( builder() .totalTransferred(end - start + 1) .segmentState(state) .build() ) .startAddress(start) .endAddress(end) .build(); } else if(state == NOT_TRANSFERRED){ return TransferSegment .builder() .status( builder() .totalTransferred(0L) .segmentState(state) .build() ) .startAddress(start) .endAddress(end) .build(); } else { return TransferSegment .builder() .status(builder() .totalTransferred(0L) .segmentState(state) .causeOfFailure(Optional.of(new TransferSegmentException())) .build() ) .startAddress(start) .endAddress(end) .build(); } }
Source:
public IItemFilter read(@Nonnull Registry registry, @Nonnull Set<NBTAction> phase, @Nonnull NBTTagCompound nbt, @Nullable Field field, @Nonnull String name, @Nullable IItemFilter object) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoHandlerFoundException { if (object == null) { if (nbt.hasKey(name)) { object = FilterRegistry.loadFilterFromNbt(nbt.getCompoundTag(name)); } else { return object; } } object.readFromNBT(nbt.getCompoundTag(name)); return object; }

Target:
public IItemFilter read(@Nonnull Registry registry, @Nonnull Set<NBTAction> phase, @Nonnull NBTTagCompound nbt, @Nullable Field field, @Nonnull String name, @Nullable IItemFilter object) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoHandlerFoundException { if (object == null && !nbt.hasKey(name)) { return object; } object = FilterRegistry.loadFilterFromNbt(nbt.getCompoundTag(name)); return object; }
Source:
public boolean isDeferJavaScriptLoading() { ConfigurationService cs = Framework.getService(ConfigurationService.class); return cs.getBoolean(DEFER_JS_PROP, true); }

Target:
public boolean isDeferJavaScriptLoading() { ConfigurationService cs = Framework.getService(ConfigurationService.class); return cs.isBooleanTrue(DEFER_JS_PROP); }
Source:
public void shutdown() { log.warn("Shutdown discovery service"); shutdown = true; if (replicationManager != null) { replicationManager.stop(); } if(clusterManagerAdapter != null) { clusterManagerAdapter.shutdown(); } executorService.shutdownNow(); }

Target:
public void shutdown() { log.warn("Shutdown discovery service"); shutdown = true; if (replicationManager != null) { replicationManager.stop(); } if(clusterManagerAdapter != null) { clusterManagerAdapter.shutdown(); } if (runtime != null) { runtime.shutdown(); } executorService.shutdownNow(); }
Source:
public synchronized void setPinned(boolean pinned) { if (pinned) { ITmfTrace trace = getTrace(); if (trace == null) { if (fPinAction != null) { fPinAction.setChecked(false); } return; } TmfSignalManager.addIgnoredInboundSignal(this, TmfTraceOpenedSignal.class); TmfSignalManager.addIgnoredInboundSignal(this, TmfTraceSelectedSignal.class); setPartName(String.format("%s - %s", fOriginalTabLabel, trace.getName())); } else { TmfSignalManager.removeIgnoredInboundSignal(this, TmfTraceOpenedSignal.class); TmfSignalManager.removeIgnoredInboundSignal(this, TmfTraceSelectedSignal.class); setPartName(fOriginalTabLabel); ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null && !trace.equals(fTrace)) { loadTrace(trace); } else { refresh(); } } if (fPinAction != null) { fPinAction.setChecked(pinned); } }

Target:
public synchronized void setPinned(boolean pinned) { if (pinned) { ITmfTrace trace = getTrace(); if (trace == null) { if (fPinAction != null) { fPinAction.setChecked(false); } return; } TmfSignalManager.addIgnoredInboundSignal(this, TmfTraceOpenedSignal.class); TmfSignalManager.addIgnoredInboundSignal(this, TmfTraceSelectedSignal.class); setPartName(String.format("%s <%s>", fOriginalTabLabel, trace.getName())); } else { TmfSignalManager.removeIgnoredInboundSignal(this, TmfTraceOpenedSignal.class); TmfSignalManager.removeIgnoredInboundSignal(this, TmfTraceSelectedSignal.class); setPartName(fOriginalTabLabel); ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null && !trace.equals(fTrace)) { loadTrace(trace); } else { refresh(); } } if (fPinAction != null) { fPinAction.setChecked(pinned); } }
Source:
private static String replace(final String text, String searchString, final String replacement, int max, final boolean ignoreCase) { if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { return text; } String searchText = text; if (ignoreCase) { searchText = text.toLowerCase(); searchString = searchString.toLowerCase(); } int start = 0; int end = searchText.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return text; } final int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = Math.max(increase, 0); increase *= Math.min(max, 0); final StringBuilder buf = new StringBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text, start, end).append(replacement); start = end + replLength; if (--max == 0) { break; } end = searchText.indexOf(searchString, start); } buf.append(text, start, text.length()); return buf.toString(); }

Target:
private static String replace(final String text, String searchString, final String replacement, int max, final boolean ignoreCase) { if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { return text; } String searchText = text; if (ignoreCase) { searchText = text.toLowerCase(); searchString = searchString.toLowerCase(); } int start = 0; int end = searchText.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return text; } final int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = Math.max(increase, 0); increase *= max < 0 ? 16 : Math.min(max, 64); final StringBuilder buf = new StringBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text, start, end).append(replacement); start = end + replLength; if (--max == 0) { break; } end = searchText.indexOf(searchString, start); } buf.append(text, start, text.length()); return buf.toString(); }