auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void should_add_error_to_context_but_not_fail_analysis_with_technical_error() { JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); InputFile file = inputFile("file.js"); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor) check), ImmutableList.of(file), executor, progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); <START> assertThat(logTester.logs()).contains("Unable to analyse file: " + file.toString()); <END> }</code><technical_language>@vilchik-elena if follow suggestion file.uri() update</technical_language>

Target:
public void should_add_error_to_context_but_not_fail_analysis_with_technical_error() { JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); InputFile file = inputFile("file.js"); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor) check), ImmutableList.of(file), executor, progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); assertThat(logTester.logs()).contains("Unable to analyse file: " + file.uri()); }
Source:
<code>private Map<Class<? extends Service>, Object> createProvidedServices(SearchConfiguration searchConfiguration) { Map<Class<? extends Service>, Object> tmpServices = new HashMap<Class<? extends Service>, Object>(); tmpServices.putAll( searchConfiguration.getProvidedServices() ); <START> if ( tmpServices.containsKey( ClassLoaderService.class ) ) { <END> throw log.classLoaderServiceContainedInProvidedServicesException(); } else { tmpServices.put( ClassLoaderService.class, searchConfiguration.getClassLoaderService() ); } return Collections.unmodifiableMap( tmpServices ); }</code><technical_language>btw this method _static_, do in case rewriting it</technical_language>

Target:
private Map<Class<? extends Service>, Object> createProvidedServices(SearchConfiguration searchConfiguration) { Map<Class<? extends Service>, Object> tmpServices = new HashMap<Class<? extends Service>, Object>(); for ( Map.Entry<Class<? extends Service>, Object> entry : searchConfiguration.getProvidedServices() .entrySet() ) { Object service = entry.getValue(); if ( service instanceof Startable ) { throw log.providedServicesCannotImplementStartableOrStoppable( service.getClass().getName(), Startable.class.getName() ); } else if ( service instanceof Stoppable ) { throw log.providedServicesCannotImplementStartableOrStoppable( service.getClass().getName(), Stoppable.class.getName() ); } else { tmpServices.put( entry.getKey(), entry.getValue() ); } } if ( tmpServices.containsKey( ClassLoaderService.class ) ) { throw log.classLoaderServiceContainedInProvidedServicesException(); } else { tmpServices.put( ClassLoaderService.class, searchConfiguration.getClassLoaderService() ); } return Collections.unmodifiableMap( tmpServices ); }
Source:
<code>public void createSchemaSpecificSchedulers() throws BeansException { logger.info("In postProcessBeanFactory"); Set<String> schemas = studyDao.findAll().stream() .map(study -> study.getSchemaName()) .collect(Collectors.toSet()); for (String schema : schemas) { CoreResources.setRequestSchema(schema); if (ocQrtzTriggersDAO.findAll().size() != 0) { <START> CoreResources.setRequestSchema("public"); <END> logger.info("Found triggers in " + schema); schedulerUtilService.createSchedulerFactoryBean(applicationContext, schema); } } }</code><technical_language>switching schema public</technical_language>

Target:
public void createSchemaSpecificSchedulers() throws BeansException { logger.info("In postProcessBeanFactory"); Set<String> schemas = studyDao.findAll().stream() .map(study -> study.getSchemaName()) .collect(Collectors.toSet()); for (String schema : schemas) { CoreResources.setRequestSchema(schema); if (ocQrtzTriggersDAO.findAll().size() != 0) { logger.info("Found triggers in " + schema); schedulerUtilService.createSchedulerFactoryBean(applicationContext, schema); } } }
Source:
<code>public static synchronized CamelReactiveStreams get(CamelContext context) { if (!instances.containsKey(context)) { CamelReactiveStreamsService service = resolveReactiveStreamsService(context); try { context.addService(service, true, true); } catch (Exception ex) { throw new IllegalStateException("Cannot add the CamelReactiveStreamsService to the Camel context", ex); } instances.put(context, new CamelReactiveStreams(service)); } <START> return instances.get(context); <END> }</code><technical_language>I ConcurrentHashMap::computeIfAbsent replace synchronized containsKey</technical_language>

Target:
public static CamelReactiveStreamsService get(CamelContext context) { return get(context, null); }
Source:
<code><START> public <T> void put(VdcParameter param, T value) { <END> VdcParameterValue.raiseExceptionIfInvalidObjectType(param, value); paramsMap.put(param.getGuid(), new VdcParameterValue<T>(param, value)); }</code><technical_language>I do understand is this template, I expect: public void put(VdcParameter param, Object value)</technical_language>

Target:
public <T> void put(VdcParameter param, T value) { Pair.raiseExceptionIfInvalidObjectType(param, value); paramsMap.put(param, value); }
Source:
<code>public void run() { B batch = null; do { try { batch = changeSource.firstBatch(); } catch (RetryableException e) { log.warn("Retryable error fetching first batch. Retrying.", e); } } while (batch == null); log.debug("{} changes in batch", batch.changes().size()); Instant oldDate = null; while (!currentThread().isInterrupted()) { try { handleChanges(batch.changes()); Instant leftOffDate = batch.leftOffDate(); if (leftOffDate != null) { leftOffDate = leftOffDate.minusSeconds(1); if (oldDate == null || !oldDate.equals(leftOffDate)) { syncDate(leftOffDate); oldDate = leftOffDate; } } batchAdvanced.mark(batch.advanced()); log.info("Polled up to at updates per second and per second", batch.leftOffHuman(), meterReport(updatesMeter), meterReport(batchAdvanced), batch.advancedUnits()); if (batch.last()) { return; } <START> streamDumper.rotate(); <END> batch = nextBatch(batch); } catch (InterruptedException e) { currentThread().interrupt(); } catch (ExecutionException e) { log.error("Syncing encountered a fatal exception", e); break; } } }</code><technical_language>In fact, this is place dumper in Updater, WikibaseRepository do remove Updater. point in classes I think</technical_language>

Target:
public void run() { B batch = null; do { try { batch = changeSource.firstBatch(); } catch (RetryableException e) { log.warn("Retryable error fetching first batch. Retrying.", e); } } while (batch == null); log.debug("{} changes in batch", batch.changes().size()); Instant oldDate = null; while (!currentThread().isInterrupted()) { try { handleChanges(batch.changes()); Instant leftOffDate = batch.leftOffDate(); if (leftOffDate != null) { leftOffDate = leftOffDate.minusSeconds(1); if (oldDate == null || !oldDate.equals(leftOffDate)) { syncDate(leftOffDate); oldDate = leftOffDate; } } batchAdvanced.mark(batch.advanced()); log.info("Polled up to at updates per second and per second", batch.leftOffHuman(), meterReport(updatesMeter), meterReport(batchAdvanced), batch.advancedUnits()); if (batch.last()) { return; } wikibase.batchDone(); batch = nextBatch(batch); } catch (InterruptedException e) { currentThread().interrupt(); } catch (ExecutionException e) { log.error("Syncing encountered a fatal exception", e); break; } } }
Source:
<code>public void requestNetworkScanLocationOffHelper(boolean includeBandsAndChannels) { if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { Log.e(TAG, "No cellular support, the test will be skipped."); return; } if (!mTelephonyManager.hasCarrierPrivileges()) { fail("This test requires a SIM card with carrier privilege rule on it."); } mNetworkScanRequest = buildNetworkScanRequest(includeBandsAndChannels); <START> for (int i = 0; i < mNetworkScanRequest.getSpecifiers().length; i++) { int[] bands = includeBandsAndChannels ? new int[]{1} : null; mNetworkScanRequest.getSpecifiers()[i] = new RadioAccessSpecifier( mNetworkScanRequest.getSpecifiers()[i].getRadioAccessNetwork(), bands, null); } <END> boolean isLocationSwitchOn = cacheAndTurnOffLocationSwitch(); try { mNetworkScanCallback = new NetworkScanCallbackImpl(); Message startNetworkScan = mHandler.obtainMessage(EVENT_NETWORK_SCAN_START); setReady(false); startNetworkScan.sendToTarget(); waitUntilReady(); if (includeBandsAndChannels) { assertEquals(EVENT_SCAN_DENIED, mNetworkScanStatus); return; } Log.d(TAG, "mNetworkScanStatus: " + mNetworkScanStatus); assertTrue("The final scan status is not ScanCompleted or ScanError with an error " + "code ERROR_MODEM_UNAVAILABLE or ERROR_UNSUPPORTED", isScanStatusValid()); } finally { setLocationSwitch(isLocationSwitchOn); } }</code><technical_language>reason this is separate buildNetworkScanRequest below? add bands based includeBandsAndChannels initial map</technical_language>

Target:
public void requestNetworkScanLocationOffHelper(boolean includeBandsAndChannels) { if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { Log.e(TAG, "No cellular support, the test will be skipped."); return; } if (!mTelephonyManager.hasCarrierPrivileges()) { fail("This test requires a SIM card with carrier privilege rule on it."); } mNetworkScanRequest = buildNetworkScanRequest(includeBandsAndChannels); boolean isLocationSwitchOn = cacheAndTurnOffLocationSwitch(); try { mNetworkScanCallback = new NetworkScanCallbackImpl(); Message startNetworkScan = mHandler.obtainMessage(EVENT_NETWORK_SCAN_START); setReady(false); startNetworkScan.sendToTarget(); waitUntilReady(); if (includeBandsAndChannels) { assertEquals(EVENT_SCAN_DENIED, mNetworkScanStatus); return; } Log.d(TAG, "mNetworkScanStatus: " + mNetworkScanStatus); assertTrue("The final scan status is not ScanCompleted or ScanError with an error " + "code ERROR_MODEM_UNAVAILABLE or ERROR_UNSUPPORTED", isScanStatusValid()); } finally { setLocationSwitch(isLocationSwitchOn); } }
Source:
<code>private void generateGeneralInsights(final Long accountId, final Long deviceId) { final Set<InsightCard.Category> recentCategories = this.getRecentInsightsCategories(accountId); <START> Integer dayOfWeek = Integer.parseInt(DateTime.now().dayOfWeek().getAsString()); <END> LOGGER.debug("The day of week is {}", dayOfWeek); InsightCard.Category categoryToGenerate; switch (dayOfWeek) { case 5: if (featureFlipper.userFeatureActive(FeatureFlipper.INSIGHTS_TESTING, accountId, Collections.EMPTY_LIST)) { LOGGER.debug("setting category to generate as wake variance"); categoryToGenerate = InsightCard.Category.WAKE_VARIANCE; break; } else { return; } case 6: if (featureFlipper.userFeatureActive(FeatureFlipper.INSIGHTS_TESTING, accountId, Collections.EMPTY_LIST)) { LOGGER.debug("setting category to generate as wake variance"); categoryToGenerate = InsightCard.Category.WAKE_VARIANCE; break; } else { return; } default: return; } if (!recentCategories.contains(categoryToGenerate)) { generateInsightsByCategory(accountId, deviceId, categoryToGenerate); } }</code><technical_language>extract a String parse int? DateTime.now().getDayOfWeek() returns Integer</technical_language>

Target:
private void generateGeneralInsights(final Long accountId, final Long deviceId) { final Set<InsightCard.Category> recentCategories = this.getRecentInsightsCategories(accountId); final List<InsightCard.Category> eligibleCategories = new ArrayList<>(); for (final InsightCard.Category category : InsightCard.Category.values()) { if (!recentCategories.contains(category)) { eligibleCategories.add(category); } } if (eligibleCategories.isEmpty()) { LOGGER.debug("No new insights generated: {}", accountId); return; } if (!recentCategories.contains(InsightCard.Category.LIGHT)) { LOGGER.debug("Light has not been generated recently, will now generate by category"); this.generateInsightsByCategory(accountId, deviceId, InsightCard.Category.LIGHT); } else if (!recentCategories.contains(InsightCard.Category.TEMPERATURE)) { this.generateInsightsByCategory(accountId, deviceId, InsightCard.Category.TEMPERATURE); } else if (!recentCategories.contains(InsightCard.Category.SLEEP_QUALITY)) { this.generateInsightsByCategory(accountId, deviceId, InsightCard.Category.SLEEP_QUALITY); } final Integer dayOfWeek = DateTime.now().getDayOfWeek(); LOGGER.debug("The day of week is {}", dayOfWeek); InsightCard.Category categoryToGenerate; switch (dayOfWeek) { case 1: case 2: case 3: if (!featureFlipper.userFeatureActive(FeatureFlipper.INSIGHTS_WAKE_VARIANCE, accountId, Collections.EMPTY_LIST)) { return; } LOGGER.debug("setting category to generate as wake variance"); categoryToGenerate = InsightCard.Category.WAKE_VARIANCE; break; default: return; } if (!recentCategories.contains(categoryToGenerate)) { generateInsightsByCategory(accountId, deviceId, categoryToGenerate); } }
Source:
<code>public void acknowledgeAlarm(OnmsAlarm alarm, Date now) { LOG.info("Acknowledging alarm with id: @ {}", alarm.getId(), now); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping ack.", alarm); return; } <START> OnmsAcknowledgment ack = new OnmsAcknowledgment(alarm, DEFAULT_USER, now); <END> ack.setAckAction(AckAction.ACKNOWLEDGE); acknowledgmentDao.processAck(ack); }</code><technical_language>alarm retrieved transaction i.e.: suggestion OnmsAcknowledgment ack = new OnmsAcknowledgment(alarmInTrans, DEFAULT_USER, now);</technical_language>

Target:
public void acknowledgeAlarm(OnmsAlarm alarm, Date now) { LOG.info("Acknowledging alarm with id: @ {}", alarm.getId(), now); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping ack.", alarm); return; } OnmsAcknowledgment ack = new OnmsAcknowledgment(alarmInTrans, DEFAULT_USER, now); ack.setAckAction(AckAction.ACKNOWLEDGE); acknowledgmentDao.processAck(ack); }
Source:
<code>private void initMultiViewJobStatusTracker(Configuration config) { try { Class<?> defaultViewDeletionTrackerClass = DefaultMultiViewJobStatusTracker.class; if (config.get(PhoenixConfigurationUtil.MAPREDUCE_VIEW_TTL_MAPPER_TRACKER_CLAZZ) != null) { LOGGER.info("Using customized tracker class : " + config.get(PhoenixConfigurationUtil.MAPREDUCE_VIEW_TTL_MAPPER_TRACKER_CLAZZ)); defaultViewDeletionTrackerClass = Class.forName( config.get(PhoenixConfigurationUtil.MAPREDUCE_VIEW_TTL_MAPPER_TRACKER_CLAZZ)); } else { LOGGER.info("Using default tracker class "); } this.multiViewJobStatusTracker = (MultiViewJobStatusTracker) defaultViewDeletionTrackerClass.newInstance(); } catch (Exception e) { <START> LOGGER.info("exception " + e.getMessage()); <END> LOGGER.info("stack trace" + e.getStackTrace().toString()); } }</code><technical_language>throw exception log error</technical_language>

Target:
private void initMultiViewJobStatusTracker(Configuration config) throws Exception { try { Class<?> defaultViewDeletionTrackerClass = DefaultMultiViewJobStatusTracker.class; if (config.get(PhoenixConfigurationUtil.MAPREDUCE_MULTI_INPUT_MAPPER_TRACKER_CLAZZ) != null) { LOGGER.info("Using customized tracker class : " + config.get(PhoenixConfigurationUtil.MAPREDUCE_MULTI_INPUT_MAPPER_TRACKER_CLAZZ)); defaultViewDeletionTrackerClass = Class.forName( config.get(PhoenixConfigurationUtil.MAPREDUCE_MULTI_INPUT_MAPPER_TRACKER_CLAZZ)); } else { LOGGER.info("Using default tracker class "); } this.multiViewJobStatusTracker = (MultiViewJobStatusTracker) defaultViewDeletionTrackerClass.newInstance(); } catch (Exception e) { LOGGER.error("Getting exception While initializing initMultiViewJobStatusTracker with error message"); LOGGER.error("stack trace" + e.getStackTrace().toString()); throw e; } }
Source:
<code>public void createGaugeMetric( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { <START> if(metricDefinition.getType() != null && metricDefinition.getType() != MetricType.GAUGE) { <END> asyncResponse.resume(badRequest(new ApiError("MetricDefinition type does not match " + MetricType .GAUGE.getText()))); } Metric<Double> metric = new Metric<>(new MetricId<>(tenantId, GAUGE, metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/gauges/{id}").build(metric.getId().getName()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); }</code><technical_language>Replace if (GAUGE != metricDefinition.getType()) {</technical_language>

Target:
public void createGaugeMetric( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { if(metricDefinition.getType() != null && MetricType.GAUGE != metricDefinition.getType()) { asyncResponse.resume(badRequest(new ApiError("MetricDefinition type does not match " + MetricType .GAUGE.getText()))); } Metric<Double> metric = new Metric<>(new MetricId<>(tenantId, GAUGE, metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/gauges/{id}").build(metric.getId().getName()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); }
Source:
<code>public Response<PageBlobItem> uploadPagesWithResponse(PageRange pageRange, InputStream body, PageBlobAccessConditions pageBlobAccessConditions, Duration timeout, Context context) { Objects.requireNonNull(body); <START> long length = pageRange.end() - pageRange.start() + 1; <END> Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(body, length, PAGE_BYTES); Mono<Response<PageBlobItem>> response = pageBlobAsyncClient.uploadPagesWithResponse(pageRange, fbb.subscribeOn(Schedulers.elastic()), pageBlobAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); }</code><technical_language>nit: final modifier for unmodifiable variable</technical_language>

Target:
public Response<PageBlobItem> uploadPagesWithResponse(PageRange pageRange, InputStream body, PageBlobAccessConditions pageBlobAccessConditions, Duration timeout, Context context) { Objects.requireNonNull(body); final long length = pageRange.end() - pageRange.start() + 1; Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(body, length, PAGE_BYTES); Mono<Response<PageBlobItem>> response = pageBlobAsyncClient.uploadPagesWithResponse(pageRange, fbb.subscribeOn(Schedulers.elastic()), pageBlobAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); }
Source:
<code>public ViewAction<T> cloneInstance() { <START> return new CompositeViewAction<T>(getViewId(), getTriggerType()); <END> }</code><technical_language>This is perfect. 2 though. 1. need add clones of actions in composite action here. 2. PrepareView call prepareView actions in actionList</technical_language>

Target:
public ViewAction<T> cloneInstance() { CompositeViewAction<T> newCompositeAction = new CompositeViewAction<T>(getViewId(), getTriggerType()); for (ViewAction<T> action : actionList) { newCompositeAction.registerAction(action.cloneInstance()); } return newCompositeAction; }
Source:
<code>public void removed(IExtension[] extensions) { for (IExtension extension : extensions) { CustomLayoutAlgorithmProvider layoutAlgorithmProvider = extensionToLayoutAlgorithmProvider.get(extension); if (layoutAlgorithmProvider != null) { List<CustomLayoutAlgorithm> customLayoutAlgorithms = layoutAlgorithmProvider.getCustomLayoutAlgorithms(); for (CustomLayoutAlgorithm customLayoutAlgorithm : customLayoutAlgorithms) { layoutProviderRegistry.remove(customLayoutAlgorithm.getId()); } } <START> extensionToLayoutAlgorithmProvider.put(extension, <END> null); } }</code><technical_language>remove instead</technical_language>

Target:
public void removed(IExtension[] extensions) { for (IExtension extension : extensions) { CustomLayoutAlgorithmProvider layoutAlgorithmProvider = extensionToLayoutAlgorithmProvider.get(extension); if (layoutAlgorithmProvider != null) { List<CustomLayoutAlgorithm> customLayoutAlgorithms = layoutAlgorithmProvider.getCustomLayoutAlgorithms(); for (CustomLayoutAlgorithm customLayoutAlgorithm : customLayoutAlgorithms) { layoutProviderRegistry.remove(customLayoutAlgorithm.getId()); } } extensionToLayoutAlgorithmProvider.remove(extension); } }
Source:
<code>private static Map<String, List<String>> extractToMap(List<String> lines, Pattern pattern) { Map<String, List<String>> results = new HashMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); Matcher matcher = pattern.matcher(line); if (matcher.matches()) { String elementName = matcher.group("name"); if (!results.containsKey(elementName)) { results.put(elementName, new ArrayList<>()); } <START> List<String> currentDescriptions = results.get(elementName); <END> String elementDescription = getNextLineIfNeeded(lines, i, matcher.group("descr")); if (elementDescription != null) { currentDescriptions.add(elementDescription); } } } return results; }</code><technical_language>results.computeIfAbsent(elementName, ArrayList::new)</technical_language>

Target:
private static Map<String, List<String>> extractToMap(List<String> lines, Pattern pattern) { Map<String, List<String>> results = new HashMap<>(); for (int i = 0; i < lines.size(); i++) { Matcher matcher = pattern.matcher(lines.get(i)); if (matcher.matches()) { List<String> descriptions = results.computeIfAbsent(matcher.group("name"), key -> new ArrayList<>()); String newDescription = getNextLineIfNeeded(lines, i, matcher.group("descr")); if (newDescription != null) { descriptions.add(newDescription); } } } return results; }
Source:
<code>public void testCatalogLeaksBundlesToReferencedYaml() throws Exception { String parentCatalogId = "my.catalog.app.id.url.parent"; addCatalogItem( "brooklyn.catalog:", " id: " + parentCatalogId, " libraries:", " - url: " + OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL, "", "services:", <START> "- type: classpath:/yaml-ref-bundle-without-libraries.yaml"); <END> Entity app = createAndStartApplication( "services:", "- type: " + parentCatalogId); Collection<Entity> children = app.getChildren(); Assert.assertEquals(children.size(), 1); Entity child = Iterables.getOnlyElement(children); Assert.assertEquals(child.getEntityType().getName(), "brooklyn.osgi.tests.SimpleEntity"); deleteCatalogEntity(parentCatalogId); }</code><technical_language>slash? Test passes if matters</technical_language>

Target:
public void testCatalogLeaksBundlesToReferencedYaml() throws Exception { String parentCatalogId = "my.catalog.app.id.url.parent"; addCatalogItem( "brooklyn.catalog:", " id: " + parentCatalogId, " libraries:", " - url: " + OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL, "", "services:", "- type: classpath://yaml-ref-bundle-without-libraries.yaml"); Entity app = createAndStartApplication( "services:", "- type: " + parentCatalogId); Collection<Entity> children = app.getChildren(); Assert.assertEquals(children.size(), 1); Entity child = Iterables.getOnlyElement(children); Assert.assertEquals(child.getEntityType().getName(), "brooklyn.osgi.tests.SimpleEntity"); deleteCatalogEntity(parentCatalogId); }
Source:
<code>public Object asJSON(Object value) { byte[] bytes; <START> if(Boolean.class.isAssignableFrom(value.getClass())){ <END> bytes = new byte[]{(byte) ((Boolean)value?1:0)}; }else { bytes = (byte[]) value; } if ( bytes.length == 8 && ((bytes[7] & 0xFF) > 127) ) { return bytesToBigInteger(bytes); } else { return bytesToLong(bytes); } }</code><technical_language>classes accounting for isAssignableFrom</technical_language>

Target:
public Object asJSON(Object value) { byte[] bytes; if( value instanceof Boolean ){ bytes = new byte[]{(byte) (( Boolean ) value ? 1 : 0)}; }else { bytes = (byte[]) value; } if ( bytes.length == 8 && ((bytes[7] & 0xFF) > 127) ) { return bytesToBigInteger(bytes); } else { return bytesToLong(bytes); } }
Source:
<code>public synchronized void stopListener() { closeListenerSockets(); while(connections.size() > 0) { Socket conn = connections.get(0); try { conn.close(); } catch (Exception e) { tsLogger.i18NLogger.warn_could_not_close_transaction_listener_connection(conn, e); } try { wait(); } catch (InterruptedException ignoredIe) { <START> tsLogger.logger.debug("Waiting for connection close was interrupted", ignoredIe); <END> } } try { this.join(); } catch (InterruptedException ignoredIe) { tsLogger.logger.debug("Waiting to ensure the listener thread has exited was interrupted", ignoredIe); } }</code><technical_language>is anymore name needs updating too</technical_language>

Target:
public synchronized void stopListener() { closeListenerSockets(); while(connections.size() > 0) { Socket conn = connections.get(0); try { conn.close(); } catch (Exception e) { tsLogger.i18NLogger.warn_could_not_close_transaction_listener_connection(conn, e); } try { wait(); } catch (InterruptedException ie) { tsLogger.logger.debug("Waiting for connection close was interrupted", ie); } } try { this.join(); } catch (InterruptedException ie) { tsLogger.logger.debug("Waiting to ensure the listener thread has exited was interrupted", ie); } }
Source:
<code>public Date getEndDate() { <START> return new Date(endDate.getTime()); <END> }</code><technical_language>Do for this</technical_language>

Target:
public Date getEndDate() { return (Date) endDate.clone(); }
Source:
<code>VoltTableSpliterator(VoltTable table, int origin, int fence) { System.out.printf("New VTS %d -> %d in Table with %d rows\n", origin, fence, table.getRowCount()); <START> System.out.flush(); <END> if (origin == fence) { m_row = null; return; } assert(origin < fence); m_row = table.fetchRow(origin); m_fence = fence; }</code><technical_language>Cleanup</technical_language>

Target:
VoltTableSpliterator(VoltTable table, int origin, int fence) { m_fence = fence; if (origin == fence) { m_row = null; return; } assert(origin < fence); m_row = table.fetchRow(origin); }
Source:
<code>public void testSingleStream() throws Exception { List<Type> types = ImmutableList.of(INTEGER, INTEGER); MaterializedResult actual = mergeSortedPages( types, ImmutableList.of(0, 1), <START> ImmutableList.of(ASC_NULLS_FIRST, ASC_NULLS_FIRST), <END> ImmutableList.of( rowPagesBuilder(types) .row(1, 1) .row(2, 2) .pageBreak() .row(3, 3) .row(4, 4) .build()), new Duration(50, MILLISECONDS), executor); MaterializedResult expected = resultBuilder(TEST_SESSION, types) .row(1, 1) .row(2, 2) .row(3, 3) .row(4, 4) .build(); assertEquals(actual, expected); }</code><technical_language>lets ordering, do think</technical_language>

Target:
public void testSingleStream() throws Exception { List<Type> types = ImmutableList.of(INTEGER, INTEGER); MaterializedResult actual = mergeSortedPages( types, ImmutableList.of(0, 1), ImmutableList.of(ASC_NULLS_FIRST, DESC_NULLS_FIRST), ImmutableList.of( rowPagesBuilder(types) .row(1, 4) .row(2, 3) .pageBreak() .row(3, 2) .row(4, 1) .build()), new Duration(50, MILLISECONDS), executor); MaterializedResult expected = resultBuilder(TEST_SESSION, types) .row(1, 4) .row(2, 3) .row(3, 2) .row(4, 1) .build(); assertEquals(actual, expected); }
Source:
<code>public FacebookAuth(Activity activity) { super(activity); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, <START> new FacebookCallback<LoginResult>() { <END> @Override public void onSuccess(LoginResult loginResult) { if (callback != null) { callback.onLogin(loginResult.getAccessToken().getToken()); } logger.debug("Facebook Logged in successfully."); } @Override public void onCancel() { logger.debug("Facebook Log in canceled."); } @Override public void onError(FacebookException error) { logger.debug("Facebook Log in got error."); } }); }</code><technical_language>Spacing here. extra spaces</technical_language>

Target:
public FacebookAuth(Activity activity) { super(activity); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { if (callback != null) { callback.onLogin(loginResult.getAccessToken().getToken()); } logger.debug("Facebook Logged in successfully."); } @Override public void onCancel() { logger.debug("Facebook Log in canceled."); } @Override public void onError(FacebookException error) { logger.error(error); } }); }
Source:
<code>public void testOneNodeDiesOnRequest() throws Exception { CountDownLatch nodeStopLatch = new CountDownLatch(1); Ignite srv1 = startGrid(0); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv1, "ctx")).io(), 0, nodeStopLatch); Ignite srv2 = startGrid(1); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv2, "ctx")).io()); Ignite srv3 = startGrid(2); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv3, "ctx")).io()); srv3.cache(DEFAULT_CACHE_NAME).put( 1, new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA")); <START> clientMode = true; <END> Ignite cl1 = startClientGrid(4); cl1.cache(DEFAULT_CACHE_NAME).get(1); nodeStopLatch.await(5_000, TimeUnit.MILLISECONDS); int result = mappingReqsCounter.get(); assertEquals("Expected requests count is 2, actual is " + result, 2, result); }</code><technical_language>This is redundant</technical_language>

Target:
public void testOneNodeDiesOnRequest() throws Exception { CountDownLatch nodeStopLatch = new CountDownLatch(1); Ignite srv1 = startGrid(0); replaceWithStoppingMappingRequestListener( ((GridKernalContext)U.field(srv1, "ctx")).io(), 0, nodeStopLatch); Ignite srv2 = startGrid(1); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv2, "ctx")).io()); Ignite srv3 = startGrid(2); replaceWithCountingMappingRequestListener(((GridKernalContext)U.field(srv3, "ctx")).io()); srv3.cache(DEFAULT_CACHE_NAME).put( 1, new Organization(1, "Microsoft", "One Microsoft Way Redmond, WA 98052-6399, USA")); Ignite cl1 = startClientGrid(4); cl1.cache(DEFAULT_CACHE_NAME).get(1); nodeStopLatch.await(5_000, TimeUnit.MILLISECONDS); int result = mappingReqsCounter.get(); assertEquals("Expected requests count is 2, actual is " + result, 2, result); }
Source:
<code>protected void executeCommand() { for (Guid templateGuid : getTemplatesList()) { VmTemplate template = DbFacade.getInstance().getVmTemplateDao().get(templateGuid); <START> if (DbFacade.getInstance().getTagDao().getTagTemplateByTagIdAndByTemplateId(getTagId(), templateGuid) == null) { <END> if (template != null) { appendCustomValue("TemplatesNames", template.getName(), ", "); TagsTemplateMap map = new TagsTemplateMap(getTagId(), templateGuid); DbFacade.getInstance().getTagDao().attachTemplateToTag(map); noActionDone = false; } } else { if (template != null) { appendCustomValue("TemplatesNamesExists", template.getName(), ", "); } } } setSucceeded(true); }</code><technical_language>in case checking if template is null, if nothing, check db get tag</technical_language>

Target:
protected void executeCommand() { for (Guid templateGuid : getTemplatesList()) { VmTemplate template = DbFacade.getInstance().getVmTemplateDao().get(templateGuid); if (template != null) { if (DbFacade.getInstance().getTagDao().getTagTemplateByTagIdAndByTemplateId(getTagId(), templateGuid) == null) { appendCustomValue("TemplatesNames", template.getName(), ", "); TagsTemplateMap map = new TagsTemplateMap(getTagId(), templateGuid); DbFacade.getInstance().getTagDao().attachTemplateToTag(map); noActionDone = false; } else { appendCustomValue("TemplatesNamesExists", template.getName(), ", "); } } } setSucceeded(true); }
Source:
<code>public void verifyAdditionalPropertyIntegerResponse() throws Exception { Map<String, String> queryParams = new HashMap<String, String>(); String str = client.invokeAPI("/mockResponses/additionalProperties1", "GET", queryParams, null, new HashMap<String, String>(), null, "application/json", null, new String[0]); assertEquals(str, "{\"key\":\"key\",\"value\":{\"bar\":0}}"); <START> } <END></code><technical_language>right, "{\"foo\":0,\"additionalPropertyExampleKey\":{\"bar\":0}}}"</technical_language>

Target:
public void verifyAdditionalPropertyIntegerResponse() throws Exception { Map<String, String> queryParams = new HashMap<String, String>(); String str = client.invokeAPI("/mockResponses/additionalProperties1", "GET", queryParams, null, new HashMap<String, String>(), null, "application/json", null, new String[0]); assertEquals(str, "{\"foo\":0,\"additionalProperty\":{\"bar\":0}}"); }
Source:
<code>public MemoryEstimate visitJoin(JoinNode node, EstimationContext context) { verify(context.sourcesCosts.size() == 2, "Unexpected number of sources for %s: %s", node, context.sourcesCosts.size()); double localMaxMemory = context.localMaxMemory; double probeMaxMemoryWhenOutputting = context.sourcesCosts.get(0).getMaxMemoryWhenOutputting(); double buildMaxMemoryWhenOutputting = context.sourcesCosts.get(1).getMaxMemoryWhenOutputting(); return new MemoryEstimate( <START> localMaxMemory + buildMaxMemoryWhenOutputting, <END> localMaxMemory + probeMaxMemoryWhenOutputting); }</code><technical_language>beforeOutputting memory estimate include probeMaxMemoryWhenOutputting? probe side computations started while hash table is built. depends scheduling, complexity, etc. memory hitting buffer limit</technical_language>

Target:
public MemoryEstimate visitJoin(JoinNode node, EstimationContext context) { return memoryEstimateForLookupJoin(node, context); }
Source:
<code>private Boolean getMigrateEncrypted() { Version version = getVm().getCompatibilityVersion(); if (version == null) { return null; } if (!FeatureSupported.isMigrateEncryptedSupported(version)) { return null; } if (getVm().getMigrateEncrypted() != null) { return getVm().getMigrateEncrypted(); } return <START> getCluster().getMigrateEncrypted(); <END> }</code><technical_language>If getCluster().getMigrateEncrypted() is null, this method return default config</technical_language>

Target:
private Boolean getMigrateEncrypted() { Version version = getVm().getCompatibilityVersion(); if (version == null) { return null; } if (!FeatureSupported.isMigrateEncryptedSupported(version)) { return null; } if (getVm().getMigrateEncrypted() != null) { return getVm().getMigrateEncrypted(); } return Config.getValue(ConfigValues.DefaultMigrationEncryption); }
Source:
<code>public void clearVm(VmStatic vm) { Set<Guid> modifiedHosts; synchronized (this) { if (!resourcesByVm.containsKey(vm.getId())) { return; } log.debug("Clearing pending resources for VM {}", vm.getId()); modifiedHosts = new HashSet<>(); resourcesByVm.compute(vm.getId(), (vmId, resources) -> { <START> for (PendingResource resource : resources) { if(resourcesByHost.containsKey(resource.getHost())){ modifiedHosts.add(resource.getHost()); } removeFromSetMap(resourcesByHost, resource.getHost(), resource); pendingResources.remove(resource); } <END> resources.clear(); return resources; }); } for (Guid hostId: modifiedHosts) { notifyHostManagers(hostId); } }</code><technical_language>bothers a bit this is duplicate of code clearHost. returning true removeFromSetMap removal succeeds in resources.stream() .peek(pendingResources::remove) .filter(r -> removeFromSetMap(resourcesByHost, r.getHost(), r)) .forEach(modifiedHosts::add); allow more expressible code visible loop. do presence check deletion atomically</technical_language>

Target:
public void clearVm(VmStatic vm) { Set<Guid> modifiedHosts; synchronized (this) { if (!resourcesByVm.containsKey(vm.getId())) { return; } log.debug("Clearing pending resources for VM {}", vm.getId()); modifiedHosts = new HashSet<>(); resourcesByVm.compute(vm.getId(), (vmId, resources) -> { resources.stream() .peek(pendingResources::remove) .filter(r -> removeFromSetMap(resourcesByHost, r.getHost(), r)) .forEach(r -> modifiedHosts.add(r.getHost())); resources.clear(); return resources; }); } for (Guid hostId: modifiedHosts) { notifyHostManagers(hostId); } }
Source:
<code>private static Envelope getEnvelope(BasicSliceInput input, GeometryType type, int length) { switch (type) { case POINT: return getPointEnvelope(input); case MULTI_POINT: case LINE_STRING: case MULTI_LINE_STRING: case POLYGON: case MULTI_POLYGON: return getSimpleGeometryEnvelope(input, length); case GEOMETRY_COLLECTION: return getGeometryCollectionOverallEnvelope(input); default: <START> throw new UnsupportedOperationException("Unexpected type: " + type); <END> } }</code><technical_language>In other switches IllegalArgumentException is thrown, I is a fit here</technical_language>

Target:
private static Envelope getEnvelope(BasicSliceInput input, GeometryType type, int length) { switch (type) { case POINT: return getPointEnvelope(input); case MULTI_POINT: case LINE_STRING: case MULTI_LINE_STRING: case POLYGON: case MULTI_POLYGON: return getSimpleGeometryEnvelope(input, length); case GEOMETRY_COLLECTION: return getGeometryCollectionOverallEnvelope(input); default: throw new IllegalArgumentException("Unexpected type: " + type); } }
Source:
<code>public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { index = 0; displayCurrent(); $(contents).on(TRANSITION_END, new Function() { @Override public void f() { <START> GQuery.console.log("TRANSITION_END"); <END> activeAnimation = false; $("[data-remove]", contents).remove(); } }); } else { $(contents).off(TRANSITION_END); } }</code><technical_language>remove console outputs for production</technical_language>

Target:
public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { index = 0; displayCurrent(); $(contents).on(TRANSITION_END, new Function() { @Override public void f() { activeAnimation = false; $("[data-remove]", contents).remove(); } }); } else { $(contents).off(TRANSITION_END); } }
Source:
<code>public void testBasic() throws Exception { try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", 10, new byte[0])) { node.start(); <START> node.waitForInitialCreate(timing.session(), TimeUnit.MILLISECONDS); <END> for ( int i = 0; i < 10; ++i ) { Thread.sleep(10); Assert.assertNotNull(client.checkExists().forPath("/test")); } } timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test")); } }</code><technical_language>This assert return is true</technical_language>

Target:
public void testBasic() throws Exception { try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", 100, new byte[0])) { node.start(); Assert.assertTrue(node.waitForInitialCreate(timing.session(), TimeUnit.MILLISECONDS)); for ( int i = 0; i < 10; ++i ) { Thread.sleep(110); Assert.assertNotNull(client.checkExists().forPath("/test")); } } Assert.assertNotNull(client.checkExists().forPath("/test")); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test")); } }
Source:
<code>public void update() { Stock updatedStock = (Stock) subject.getUpdate(); <START> if (updatedStock == null || m.getStockForSymbol(updatedStock.getSymbol()) == null) { return; } if (history.containsKey(updatedStock.getSymbol())) { List<Double> priceList = history.get(updatedStock.getSymbol()); priceList.add(updatedStock.getPrice()); history.put(updatedStock.getSymbol(), priceList); } else { List<Double> priceList = new ArrayList<Double>(); priceList.add(updatedStock.getPrice()); history.put(updatedStock.getSymbol(), priceList); } <END> }</code><technical_language>This is a long method try extract methods</technical_language>

Target:
public void update() { Stock updatedStock = (Stock) subject.getUpdate(); if (updatedStock == null || market.getStockForSymbol(updatedStock.getSymbol()) == null) { return; } addToHistory(marketHistory.containsKey(updatedStock.getSymbol())); }
Source:
<code>public void sync() throws IOException { flush(); <START> } <END></code><technical_language>removing call hsync()? hflush() guarantee data written stable storage</technical_language>

Target:
public void sync() throws IOException { flush(); Hadoop.FSDataOutputStream.hsync.invoke(outgoing); }
Source:
<code>protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(mapEntries); <START> out.writeBoolean(triggerMapLoader); <END> }</code><technical_language>a feature called "rolling upgrade" means a point, a cluster consist of members of minor versions, minor version apart. In another words, this operation other objects serialised deserialised received members of versions. In case this object a 4.0 member received a 4.1 member, this exception. This is introduce additional safeguards. starts adding Versioned interface this class. that, add checks in writeInternal readInternal methods, like: java @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(mapEntries); if (out.getVersion().isGreaterOrEqual(Versions.V4_1)) { out.writeBoolean(triggerMapLoader); } } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); mapEntries = in.readObject(); if (in.getVersion().isGreaterOrEqual(Versions.V4_1)) { triggerMapLoader = in.readBoolean(); } else { // behaviour triggerMapLoader = true; } } for PutAllPartitionAwareOperationFactory</technical_language>

Target:
protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(mapEntries); if (out.getVersion().isGreaterOrEqual(Versions.V4_1)) { out.writeBoolean(triggerMapLoader); } }
Source:
<code>private boolean <START> isDiagramOutlinePage(IWorkbenchPart <END> part) { if (part instanceof ContentOutline) { IPage page = ((ContentOutline) part).getCurrentPage(); return page instanceof DiagramOutlinePage; } return false; }</code><technical_language>add additional check: this outline correspond current diagram editor</technical_language>

Target:
private boolean isDiagramOutlinePage(IWorkbenchPart part) { if (part instanceof ContentOutline) { IPage page = ((ContentOutline) part).getCurrentPage(); if (page instanceof DiagramOutlinePage) { GraphicalViewer graphicalViewer = getGraphicalViewer(); if (graphicalViewer != null) { Control control = ((DiagramOutlinePage) page).getEditor(); return control == graphicalViewer.getControl(); } } } return false; }
Source:
<code>public List<View> getRootViews() { WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); if (windowManager == null) { <START> throw new RuntimeException("unfortunately, you cannot view the view tree of the dialog etc. windowManager == null !"); <END> } Object wm = getOuter(windowManager); return getWindowViews(wm); }</code><technical_language>message is misleading. crash process. fine, should, if a severe issue is detected</technical_language>

Target:
public List<View> getRootViews() { WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Object wm = getOuter(windowManager); return getWindowViews(wm); }
Source:
<code>public Subject extractSubject(String token) throws ServletException { Jws<Claims> jwt = jwtParser.parseClaimsJws(token); Claims claims = jwt.getBody(); LOG.debug("JWT = {}", jwt); try { String username = claims.get( keycloakSettings.get().get(KeycloakConstants.USERNAME_CLAIM_SETTING), String.class); if (username == null) { username = claims.getIssuer() + ":" + claims.getSubject(); } <START> if (!isNullOrEmpty(backSlashReplaceWith) && username.contains("\\")) { <END> username = username.replace("\\", backSlashReplaceWith); } String id = claims.getSubject(); String email = retrieveEmail(token, claims, id) .orElseThrow( () -> new JwtException( "Unable to authenticate user because email address is not set in keycloak profile")); User user = userManager.getOrCreateUser(id, email, username); return new AuthorizedSubject( new SubjectImpl(user.getName(), user.getId(), token, false), permissionChecker); } catch (ServerException | ConflictException e) { throw new ServletException( "Unable to identify user " + claims.getSubject() + " in Che database", e); } }</code><technical_language>Nitpick: username.contains() username.replace() is searching string for in a row... just: java if (!isNullOrEmpty(backSlashReplaceWith)) { username = username.replace("\\", backSlashReplaceWith); }</technical_language>

Target:
public Subject extractSubject(String token) throws ServletException { Jws<Claims> jwt = jwtParser.parseClaimsJws(token); Claims claims = jwt.getBody(); LOG.debug("JWT = {}", jwt); try { String username = claims.get( keycloakSettings.get().get(KeycloakConstants.USERNAME_CLAIM_SETTING), String.class); if (username == null) { username = claims.getIssuer() + ":" + claims.getSubject(); } if (!userNameReplacementPatterns.isEmpty()) { for (Map.Entry<String, String> entry : userNameReplacementPatterns.entrySet()) { username = username.replaceAll(entry.getKey(), entry.getValue()); } } String id = claims.getSubject(); String email = retrieveEmail(token, claims, id) .orElseThrow( () -> new JwtException( "Unable to authenticate user because email address is not set in keycloak profile")); User user = userManager.getOrCreateUser(id, email, username); return new AuthorizedSubject( new SubjectImpl(user.getName(), user.getId(), token, false), permissionChecker); } catch (ServerException | ConflictException e) { throw new ServletException( "Unable to identify user " + claims.getSubject() + " in Che database", e); } }
Source:
<code>public ArrayAdapter<JSONObject> createAdapter() { ArrayAdapter<JSONObject> itemAdapter = new ArrayAdapter<JSONObject>(container.$context(), 0, currentItems) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = createView(); TextView text1 = view.findViewById(2); TextView text2 = view.findViewById(3); JSONObject row = filterCurrentItems.get(position); String val1 = row.has("Text1") ? row.getString("Text1") : ""; String val2 = row.has("Text2") ? row.getString("Text2") : ""; text1.setText(val1); text2.setText(val2); text1.setTextColor(textColor); text2.setTextColor(detailTextColor); text1.setTextSize(textSize); text2.setTextSize(detailTextSize); return view; } @Override public Filter getFilter() { <START> Filter filter = new Filter() { <END> @Override protected FilterResults performFiltering(CharSequence charSequence) { String filterQuery = charSequence.toString().toLowerCase(); FilterResults results = new FilterResults(); if(filterQuery == null || filterQuery.length() == 0) { ArrayList<JSONObject> arrayList = new ArrayList<>(currentItems); results.count = arrayList.size(); results.values = arrayList; } else { ArrayList<JSONObject> arrayList = new ArrayList<>(currentItems); ArrayList<JSONObject> filteredList = new ArrayList<>(); for(int i = 0; i < arrayList.size(); ++i) { JSONObject object = arrayList.get(i); if ((object.has("Text1") && object.getString("Text1").toLowerCase() .contains(charSequence.toString())) || (object.has("Text2")) && object.getString("Text2") .toLowerCase().contains(charSequence.toString())) { filteredList.add(object); } } results.count = filteredList.size(); results.values = filteredList; } return results; } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { filterCurrentItems = (ArrayList<JSONObject>) filterResults.values; clear(); for(int i = 0; i < filterCurrentItems.size(); ++i) { add(filterCurrentItems.get(i)); } } }; return filter; } }; return itemAdapter; }</code><technical_language>A call getFilter construct a new filter object time. For memory reasons, sense move this a final variable class return object (so is constructed ListView object</technical_language>

Target:
public ArrayAdapter<YailDictionary> createAdapter() { itemAdapter = new ArrayAdapter<YailDictionary>(container.$context(), 0, currentItems) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = createView(); TextView text1 = view.findViewById(2); TextView text2 = view.findViewById(3); YailDictionary row = filterCurrentItems.get(position); String val1 = ElementsUtil.toStringEmptyIfNull(row.get("Text1")); String val2 = ElementsUtil.toStringEmptyIfNull(row.get("Text2")); text1.setText(val1); text2.setText(val2); text1.setTextColor(textColor); text2.setTextColor(detailTextColor); text1.setTextSize(textSize); text2.setTextSize(detailTextSize); return view; } @Override public Filter getFilter() { return filter; } }; return itemAdapter; }