auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void setupPattern() { view.setupPatternList(); setUpPatternList(); view.selectPattern(currentPatternValue()); view.hidePatternListWhenItIsEmpty(); }

Target:
void setupPattern() { view.clearPatternList(); setUpPatternList(); view.selectPattern(currentPatternValue()); view.hidePatternListWhenItIsEmpty(); }
Source:
public Deferred<Object> prefetchMeta(final byte[] table, final byte[] start, final byte[] stop) { if (Bytes.equals(table, META) || Bytes.equals(table, ROOT)) { return Deferred.fromResult(null); } byte[] meta_start = createRegionSearchKey(table, start); meta_start[meta_start.length - 1] = 0; byte[] meta_stop; if (stop.length == 0) { byte[] nulled_table = new byte[table.length + 1]; System.arraycopy(table, 0, nulled_table, 0, table.length); meta_stop = createRegionSearchKey(nulled_table, stop); } else { meta_stop = createRegionSearchKey(table, stop); } final Scanner meta_scanner = newScanner(META); meta_scanner.setStartKey(meta_start); meta_scanner.setStopKey(meta_stop); Callback<Object, ArrayList<ArrayList<KeyValue>>> callback = new Callback<Object, ArrayList<ArrayList<KeyValue>>>() { public Object call(final ArrayList<ArrayList<KeyValue>> results) { if (results != null && !results.isEmpty()) { for (ArrayList<KeyValue> row : results) { discoverRegion(row); } meta_scanner.nextRows().addCallback(this); } return results; } public String toString() { return "prefetchMeta nextRows"; } }; Deferred<Object> deferred = meta_scanner.nextRows().addCallback(callback); return deferred; }

Target:
public Deferred<Object> prefetchMeta(final byte[] table, final byte[] start, final byte[] stop) { if (Bytes.equals(table, META) || Bytes.equals(table, ROOT)) { return Deferred.fromResult(null); } byte[] meta_start = createRegionSearchKey(table, start); meta_start[meta_start.length - 1] = 0; byte[] meta_stop; if (stop.length == 0) { meta_stop = createRegionSearchKey(table, stop); meta_stop[table.length] = 0; meta_stop[meta_stop.length - 1] = ','; } else { meta_stop = createRegionSearchKey(table, stop); } final Scanner meta_scanner = newScanner(META); meta_scanner.setStartKey(meta_start); meta_scanner.setStopKey(meta_stop); Callback<Object, ArrayList<ArrayList<KeyValue>>> callback = new Callback<Object, ArrayList<ArrayList<KeyValue>>>() { public Object call(final ArrayList<ArrayList<KeyValue>> results) { if (results != null && !results.isEmpty()) { for (ArrayList<KeyValue> row : results) { discoverRegion(row); } meta_scanner.nextRows().addCallback(this); } return results; } public String toString() { return "prefetchMeta nextRows"; } }; Deferred<Object> deferred = meta_scanner.nextRows().addCallback(callback); return deferred; }
Source:
public static Response<RecipientCreateResponse> createRecipientWithIban(PlaidClient client) throws Exception { Address address = new Address(Arrays.asList("Street Name 999"), "City", "99999", "GB"); RecipientCreateRequest recipientCreateRequest = new RecipientCreateRequest("John Doe", "GB33BUKB20201555555555", address); Response<RecipientCreateResponse> response = client.service().recipientCreate(recipientCreateRequest).execute(); return response; }

Target:
public static Response<RecipientCreateResponse> createRecipientWithIban(PlaidClient client) throws Exception { Address address = new Address(Arrays.asList("Street Name 999"), "City", "99999", "GB"); RecipientCreateRequest recipientCreateRequest = new RecipientCreateRequest("John Doe").withIban("GB33BUKB20201555555555").withAddress(address); Response<RecipientCreateResponse> response = client.service().recipientCreate(recipientCreateRequest).execute(); return response; }
Source:
private static List<String> mapValuesToListIgnoreCase(String keyName, Map<String, List<String>> m) { List<String> fields = new LinkedList<>(); m.entrySet().stream().filter(e -> keyName.equalsIgnoreCase(e.getKey())) .forEach(e -> fields.addAll(e.getValue())); return fields; }

Target:
private static List<String> mapValuesToListIgnoreCase(String keyName, Map<String, List<String>> m) { List<String> fields = new LinkedList<>(); m.entrySet().stream().filter(e -> keyName.equalsIgnoreCase(e.getKey())) .filter(e -> e.getValue() != null) .forEach(e -> fields.addAll(e.getValue())); return fields; }
Source:
OperationController() throws IOException { networkClient = networkClientFactory.getNetworkClient(); putManager = new PutManager(NonBlockingRouter.this); getManager = new GetManager(NonBlockingRouter.this); deleteManager = new DeleteManager(NonBlockingRouter.this); requestResponseHandlerThread = Utils.newThread("RequestResponseHandlerThread", this, true); requestResponseHandlerThread.start(); }

Target:
OperationController() throws IOException { networkClient = networkClientFactory.getNetworkClient(); putManager = new PutManager(clusterMap, responseHandler, notificationSystem, routerConfig, routerMetrics, time); getManager = new GetManager(clusterMap, responseHandler, routerConfig, routerMetrics, time); deleteManager = new DeleteManager(clusterMap, responseHandler, notificationSystem, routerConfig, routerMetrics, time); requestResponseHandlerThread = Utils.newThread("RequestResponseHandlerThread", this, true); requestResponseHandlerThread.start(); }
Source:
public void executeInBackground(final Runnable task) { executor.execute(new Runnable() { public void run() { System.out.println("STARTING TASK"); task.run(); System.out.println("ENDING TASK"); } }); }

Target:
public void executeInBackground(final Runnable task) { executor.execute(new Runnable() { public void run() { task.run(); } }); }
Source:
public Response intercept(Chain chain) throws IOException { Request input = chain.request(); Request signed = appendBasicAuthHeaderParameters(input); Response response = chain.proceed(signed); if (response.code() == 403) { try (ResponseBody body = response.body()) { JsonReader message = enterPath(JsonReader.of(body.source()), "message"); if (message != null) throw new IllegalStateException(message.nextString()); } throw new IllegalStateException(response.toString()); } return response; }

Target:
public Response intercept(Chain chain) throws IOException { Request input = chain.request(); Request requestWithCredentials = appendBasicAuthHeaderParameters(input); Response response = chain.proceed(requestWithCredentials); if (response.code() == 403) { try (ResponseBody body = response.body()) { JsonReader message = enterPath(JsonReader.of(body.source()), "message"); if (message != null) throw new IllegalStateException(message.nextString()); } throw new IllegalStateException(response.toString()); } return response; }
Source:
public void testCreateDynamicGraphAllIndependent() { DynamicGraph<ITestNGMethod> graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); for (Map.Entry<ITestNGMethod, List<DynamicGraph.Edge<ITestNGMethod>>> edge : graph.getEdges().entrySet()) { assertThat(edge.getValue()).isEmpty(); } }

Target:
public void testCreateDynamicGraphAllIndependent() { DynamicGraph<ITestNGMethod> graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); for (List<DynamicGraph.Edge<ITestNGMethod>> edge : graph.getEdges().values()) { assertThat(edge).isEmpty(); } }
Source:
public AuthMePlayer getPlayerInfo(String playerName) { PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } return AuthMePlayerImpl.fromPlayerAuth(auth); }

Target:
public Optional<AuthMePlayer> getPlayerInfo(String playerName) { PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } return AuthMePlayerImpl.fromPlayerAuth(auth); }
Source:
public SystemAccessControl create(Map<String, String> config) { requireNonNull(config, "config is null"); String configFileName = config.get(CONFIG_FILE_NAME); checkState( configFileName != null, "Security configuration must contain the '%s' property", CONFIG_FILE_NAME); if (config.containsKey(PERIOD)) { return refreshingSystemAccessControl( () -> { log.info("Refreshing access control, because '%s' was modified", configFileName); return create(configFileName); }, wasFileModified(toPath(configFileName)), Duration.valueOf(config.get(PERIOD))); } return create(configFileName); }

Target:
public SystemAccessControl create(Map<String, String> config) { requireNonNull(config, "config is null"); String configFileName = config.get(SECURITY_CONFIG_FILE); checkState(configFileName != null, "Security configuration must contain the '%s' property", SECURITY_CONFIG_FILE); if (config.containsKey(SECURITY_REFRESH_PERIOD)) { Duration refreshPeriod; try { refreshPeriod = Duration.valueOf(config.get(SECURITY_REFRESH_PERIOD)); } catch (IllegalArgumentException e) { throw invalidRefreshPeriodException(config, configFileName); } if (refreshPeriod.toMillis() == 0) { throw invalidRefreshPeriodException(config, configFileName); } return ForwardingSystemAccessControl.of(memoizeWithExpiration( () -> { log.info("Refreshing system access control from %s", configFileName); return create(configFileName); }, refreshPeriod.toMillis(), MILLISECONDS)); } return create(configFileName); }
Source:
private String prepareQuery(MultiSyncStep step, Collection<String> entityTopIds, Collection<String> entityIdsWithLexemes, List<Statement> insertStatements, ClassifiedStatements classifiedStatements, Set<String> refSet, Set<String> valueSet, Instant timestamp) { switch (step) { case CLEAR_OOD_SITE_LINKS: return MultiSyncStep.createClearOodLinksQuery(entityTopIds, classifiedStatements, uris); case CLEAR_OOD_ST_ABOUT_ST: return MultiSyncStep.createClearOodStatementsAboutStatementsQuery(entityIdsWithLexemes, classifiedStatements, uris); case CLEAR_OOD_ST_ABOUT_ENT: return MultiSyncStep.createClearOodStatementsAboutEntitiesQuery(entityIdsWithLexemes, classifiedStatements, uris); case INSERT_NEW_DATA: return MultiSyncStep.createInsertNewDataQuery(insertStatements); case ADD_TIMESTAMPS: return MultiSyncStep.createAddTimestampsQuery(entityTopIds, timestamp, uris); case CLEANUP_REFERENCES: return !refSet.isEmpty() ? MultiSyncStep.createCleanupReferencesQuery(refSet) : ""; case CLEANUP_VALUES: return !valueSet.isEmpty() ? MultiSyncStep.createCleanupValuesQuery(valueSet) : ""; default: throw new IllegalArgumentException("Step " + step.getStepName() + " is unknown!"); } }

Target:
private String prepareQuery(MultiSyncStep step, Collection<String> entityTopIds, Collection<String> entityIdsWithLexemes, List<Statement> insertStatements, ClassifiedStatements classifiedStatements, Set<String> refSet, Set<String> valueSet, Instant timestamp) { switch (step) { case CLEAR_OOD_SITE_LINKS: return MultiSyncStep.createClearOodLinksQuery(entityTopIds, classifiedStatements, uris); case CLEAR_OOD_ST_ABOUT_ST: return MultiSyncStep.createClearOodStatementsAboutStatementsQuery(entityIdsWithLexemes, classifiedStatements, uris); case CLEAR_OOD_ST_ABOUT_ENT: return MultiSyncStep.createClearOodStatementsAboutEntitiesQuery(entityIdsWithLexemes, classifiedStatements, uris); case INSERT_NEW_DATA: return MultiSyncStep.createInsertNewDataQuery(insertStatements); case ADD_TIMESTAMPS: return MultiSyncStep.createAddTimestampsQuery(entityTopIds, timestamp, uris); case CLEANUP_REFERENCES: return MultiSyncStep.createCleanupReferencesQuery(refSet); case CLEANUP_VALUES: return MultiSyncStep.createCleanupValuesQuery(valueSet); default: throw new IllegalArgumentException("Step " + step.getStepName() + " is unknown!"); } }
Source:
public void testMessageCountWithPaging() throws Exception { final String data = "Simple Text " + UUID.randomUUID().toString(); final String queueName = "simpleQueue"; final String addressName = "simpleAddress"; server.getAddressSettingsRepository().getMatch(addressName).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setMaxSizeBytes(1024 * 10).setPageSizeBytes(1024 * 5); session.createQueue(new QueueConfiguration(queueName).setAddress(addressName).setRoutingType(RoutingType.ANYCAST)); ClientProducer producer = session.createProducer(addressName); ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString(data); int messageCount = 0; while (!server.getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) { producer.send(message); messageCount++; } assertEquals(messageCount, server.locateQueue(queueName).getMessageCount()); checkMetric(getMetrics(), "artemis.message.count", "queue", queueName, Double.valueOf(messageCount)); for (int i = 0; i < messageCount; i++) { producer.send(message); } producer.close(); assertEquals(messageCount * 2, server.locateQueue(queueName).getMessageCount()); checkMetric(getMetrics(), "artemis.message.count", "queue", queueName, Double.valueOf(messageCount * 2)); }

Target:
public void testMessageCountWithPaging() throws Exception { final String data = "Simple Text " + UUID.randomUUID().toString(); final String queueName = "simpleQueue"; final String addressName = "simpleAddress"; server.getAddressSettingsRepository().getMatch(addressName).setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE).setMaxSizeBytes(1024 * 10).setPageSizeBytes(1024 * 5); session.createQueue(new QueueConfiguration(queueName).setAddress(addressName).setRoutingType(RoutingType.ANYCAST)); ClientProducer producer = session.createProducer(addressName); ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeString(data); long messageCount = 0; while (!server.getPagingManager().getPageStore(new SimpleString(addressName)).isPaging()) { producer.send(message); messageCount++; } Wait.assertEquals(messageCount, server.locateQueue(queueName)::getMessageCount, 2000, 100); checkMetric(getMetrics(), "artemis.message.count", "queue", queueName, Double.valueOf(messageCount)); for (int i = 0; i < messageCount; i++) { producer.send(message); } producer.close(); Wait.assertEquals(messageCount * 2, server.locateQueue(queueName)::getMessageCount, 2000, 100); checkMetric(getMetrics(), "artemis.message.count", "queue", queueName, Double.valueOf(messageCount * 2)); }
Source:
public static boolean isSame( @Nullable Metacard cachedMetacard, @Nullable Metacard updatedMetacard) { if (cachedMetacard == null && updatedMetacard == null) { return true; } if (cachedMetacard == null || updatedMetacard == null) { return false; } if (!Objects.equals(cachedMetacard.getId(), updatedMetacard.getId())) { return false; } if (!Objects.equals( cachedMetacard.getAttribute(Metacard.CHECKSUM), updatedMetacard.getAttribute(Metacard.CHECKSUM))) { return false; } return allMetacardMethodsReturnMatchingAttributes(cachedMetacard, updatedMetacard); }

Target:
public static boolean isSame( @Nullable Metacard cachedMetacard, @Nullable Metacard updatedMetacard) { if (cachedMetacard == null && updatedMetacard == null) { return true; } if (cachedMetacard == null || updatedMetacard == null) { return false; } if (!Objects.equals(cachedMetacard.getId(), updatedMetacard.getId())) { return false; } if (!Objects.equals( cachedMetacard.getAttribute(Core.CHECKSUM), updatedMetacard.getAttribute(Core.CHECKSUM))) { return false; } return allMetacardMethodsReturnMatchingAttributes(cachedMetacard, updatedMetacard); }
Source:
public void destroy() { connectionFactoryList.forEach((ldap, connectionFactory) -> { connectionFactory.close(); }); }

Target:
public void destroy() { connectionFactoryList.forEach((ldap, connectionFactory) -> connectionFactory.close() ); }
Source:
public void onUploadError(MediaModel media, MediaStore.MediaError error) { String localMediaId = String.valueOf(media.getId()); MediaFile mf = FluxCUtils.fromMediaModel(media); Map<String, Object> properties = AnalyticsUtils.getMediaProperties(this, mf.isVideo(), null, mf.getFilePath()); properties.put("error_type", error.type.name()); AnalyticsTracker.track(Stat.EDITOR_UPLOAD_MEDIA_FAILED, properties); String errorMessage; switch (error.type) { case AUTHORIZATION_REQUIRED: errorMessage = getString(R.string.media_error_no_permission_upload); break; case GENERIC_ERROR: default: errorMessage = TextUtils.isEmpty(error.message) ? getString(R.string.tap_to_try_again) : error.message; } mEditorMediaUploadListener.onMediaUploadFailed(localMediaId, errorMessage); removeMediaFromPendingList(media); }

Target:
public void onUploadError(MediaModel media, MediaStore.MediaError error) { String localMediaId = String.valueOf(media.getId()); Map<String, Object> properties = null; MediaFile mf = FluxCUtils.fromMediaModel(media); if (mf != null) { properties = AnalyticsUtils.getMediaProperties(this, mf.isVideo(), null, mf.getFilePath()); properties.put("error_type", error.type.name()); } AnalyticsTracker.track(Stat.EDITOR_UPLOAD_MEDIA_FAILED, properties); String errorMessage; switch (error.type) { case AUTHORIZATION_REQUIRED: errorMessage = getString(R.string.media_error_no_permission_upload); break; case GENERIC_ERROR: default: errorMessage = TextUtils.isEmpty(error.message) ? getString(R.string.tap_to_try_again) : error.message; } mEditorMediaUploadListener.onMediaUploadFailed(localMediaId, errorMessage); removeMediaFromPendingList(media); }
Source:
public AttributeValue get(final String str) throws IOException { AttributeValue value = null; if (this.updatemap.containsKey(str)) { value = this.updatemap.get(str).getValue(); } return value; }

Target:
public AttributeValue get(final String str) throws IOException { if (!this.updatemap.containsKey(str)) { throw new IllegalArgumentException(); } return this.updatemap.get(str).getValue(); }
Source:
private Account executeAccount(IProgressMonitor monitor) throws GerritException { if (isVersion29OrLater(monitor)) { String query = "/accounts/self"; org.eclipse.mylyn.internal.gerrit.core.client.rest.AccountInfo accountInfo = executeGetRestRequest(query, org.eclipse.mylyn.internal.gerrit.core.client.rest.AccountInfo.class, monitor); Account account = new Account(new Account.Id(accountInfo.getId())); account.setFullName(accountInfo.getName()); account.setUserName(accountInfo.getUsername()); account.setPreferredEmail(accountInfo.getEmail()); return account; } else { return execute(monitor, new Operation<Account>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { getAccountService(monitor).myAccount(this); } }); } }

Target:
private Account executeAccount(IProgressMonitor monitor) throws GerritException { if (isVersion29OrLater(monitor)) { return getAccount29(monitor); } else { return execute(monitor, new Operation<Account>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { getAccountService(monitor).myAccount(this); } }); } }
Source:
protected void doStart() throws Exception { for (int i = 0; i < schedulers.length; i++) { ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor( threadsPerScheduler, Threads.daemonThreadsNamed(threadBaseName + "-timeout-%s" + i)); scheduledExecutorService.setRemoveOnCancelPolicy(true); schedulers[i] = scheduledExecutorService; } }

Target:
protected void doStart() throws Exception { for (int i = 0; i < schedulers.length; i++) { ScheduledThreadPoolExecutor scheduledExecutorService = new ScheduledThreadPoolExecutor(threadsPerScheduler, threadFactory); scheduledExecutorService.setRemoveOnCancelPolicy(true); schedulers[i] = scheduledExecutorService; } }
Source:
public void removeTrigger(Trigger trigger) { if (null != rules.getFact(trigger)) { rules.removeFact(trigger); final String triggerId = trigger.getId(); rules.removeFacts(t -> { if (t instanceof Dampening) { return ((Dampening)t).getTriggerId().equals(triggerId); } else if (t instanceof Condition) { return ((Condition)t).getTriggerId().equals(triggerId); } return false; }); } else { log.debug("Trigger not found. Not removed from rulebase " + trigger.toString()); } }

Target:
private void removeTrigger(Trigger trigger) { if (null != rules.getFact(trigger)) { rules.removeFact(trigger); alertsEngineCache.remove(trigger.getTenantId(), trigger.getId()); final String triggerId = trigger.getId(); rules.removeFacts(t -> { if (t instanceof Dampening) { return ((Dampening)t).getTriggerId().equals(triggerId); } else if (t instanceof Condition) { return ((Condition)t).getTriggerId().equals(triggerId); } return false; }); } else { if (log.isDebugEnabled()) { log.debug("Trigger not found. Not removed from rulebase " + trigger.toString()); } } }
Source:
private AMethodWithItsArgs findBestMethodByParamsNode(Set<Method> methods, JsonNode paramsNode) { if (hasNoParameters(paramsNode)) { return findBestMethodUsingParamIndexes(methods, 0, null); } AMethodWithItsArgs matchedMethod; if (paramsNode.isArray()) { matchedMethod = findBestMethodUsingParamIndexes(methods, paramsNode.size(), ArrayNode.class.cast(paramsNode)); } else if (paramsNode.isObject()) { matchedMethod = findBestMethodUsingParamNames(methods, collectFieldNames(paramsNode), ObjectNode.class.cast(paramsNode)); } else { throw new IllegalArgumentException("Unknown params node type: " + paramsNode.toString()); } if(matchedMethod==null) { for (Method method : methods) { if(method.getParameterTypes().length!=1) { continue; } if(method.isVarArgs()) { matchedMethod = new AMethodWithItsArgs(method); if (paramsNode.isArray()) { ArrayNode arrayNode = ArrayNode.class.cast(paramsNode); for (int i = 0; i < paramsNode.size(); i++) { matchedMethod.arguments.add(arrayNode.get(i)); } } if (paramsNode.isObject()) { ObjectNode objectNode = ObjectNode.class.cast(paramsNode); Iterator<Map.Entry<String, JsonNode>> items = objectNode.fields(); while (items.hasNext()) { Map.Entry<String, JsonNode> item = items.next(); JsonNode name = JsonNodeFactory.instance.objectNode().put(item.getKey(),item.getKey()); matchedMethod.arguments.add(name.get(item.getKey())); matchedMethod.arguments.add(item.getValue()); } } break; } } } return matchedMethod; }

Target:
private AMethodWithItsArgs findBestMethodByParamsNode(Set<Method> methods, JsonNode paramsNode) { if (hasNoParameters(paramsNode)) { return findBestMethodUsingParamIndexes(methods, 0, null); } AMethodWithItsArgs matchedMethod; if (paramsNode.isArray()) { matchedMethod = findBestMethodUsingParamIndexes(methods, paramsNode.size(), ArrayNode.class.cast(paramsNode)); } else if (paramsNode.isObject()) { matchedMethod = findBestMethodUsingParamNames(methods, collectFieldNames(paramsNode), ObjectNode.class.cast(paramsNode)); } else { throw new IllegalArgumentException("Unknown params node type: " + paramsNode.toString()); } if (matchedMethod == null) { matchedMethod = findBestMethodForVarargs(methods, paramsNode); } return matchedMethod; }
Source:
public int hashCode() { return (null != value) ? value.hashCode() : 0; }

Target:
public int hashCode() { return HashUtil.combineHashCodes(Objects.hashCode(value)); }
Source:
private void registerArgumentResolverMessageConverter(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition( IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME)) { BeanDefinitionBuilder resolverBuilder = BeanDefinitionBuilder .genericBeanDefinition(ConfigurableCompositeMessageConverter.class); registry.registerBeanDefinition(IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME, resolverBuilder.getBeanDefinition()); } }

Target:
private void registerArgumentResolverMessageConverter(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition( IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME)) { BeanDefinitionBuilder converterBuilder = BeanDefinitionBuilder .genericBeanDefinition(ConfigurableCompositeMessageConverter.class); registry.registerBeanDefinition(IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME, converterBuilder.getBeanDefinition()); } }
Source:
public Adapter getContentAdapter() { if (adapter == null) { adapter = new AdapterImpl() { @Override public void notifyChanged(final Notification notification) { int type = notification.getEventType(); switch (type) { case Notification.ADD: case Notification.ADD_MANY: case Notification.REMOVE: case Notification.REMOVE_MANY: refreshChildren(); break; default: break; } } }; } return adapter; }

Target:
public Adapter getContentAdapter() { if (null == adapter) { adapter = new AdapterImpl() { @Override public void notifyChanged(final Notification notification) { int type = notification.getEventType(); switch (type) { case Notification.ADD: case Notification.ADD_MANY: case Notification.REMOVE: case Notification.REMOVE_MANY: refreshChildren(); break; default: break; } } }; } return adapter; }
Source:
private <P> void updateWidgetsAndFireEvent(final boolean sync, final String property, final P oldValue, final P newValue, final Object excluding) { for (final Binding binding : bindings.get(property)) { final Object component = binding.getComponent(); final Converter converter = binding.getConverter(); if (component == excluding) continue; if (!sync && binding.propertyIsList() && component instanceof BindableListChangeHandler) continue; if (component instanceof TakesValue) { updateComponentValue(newValue, (TakesValue) component, converter); } else if (component instanceof HasText) { updateComponentValue(newValue, (HasText) component, converter); } else if (component instanceof IsElement || component instanceof org.jboss.errai.common.client.api.elemental2.IsElement || isElement(component)) { final Element element = BoundUtil.asElement(getComponent(component)); final ElementWrapperWidget<?> wrapper = ElementWrapperWidget.getWidget(element); if (wrapper instanceof TakesValue) { updateComponentValue(newValue, (TakesValue) wrapper, converter); } else if (wrapper instanceof HasText) { updateComponentValue(newValue, (HasText) wrapper, converter); } } } maybeFirePropertyChangeEvent(property, oldValue, newValue); }

Target:
private <P> void updateWidgetsAndFireEvent(final boolean sync, final String property, final P oldValue, final P newValue, final Object excluding) { for (final Binding binding : bindings.get(property)) { final Object component = binding.getComponent(); final Converter converter = binding.getConverter(); if (component == excluding) continue; if (!sync && binding.propertyIsList() && component instanceof BindableListChangeHandler) continue; if (component instanceof TakesValue) { updateComponentValue(newValue, (TakesValue) component, converter); } else if (component instanceof HasText) { updateComponentValue(newValue, (HasText) component, converter); } else if (component instanceof IsElement || component instanceof org.jboss.errai.common.client.api.elemental2.IsElement || isElement(component)) { final Element element = BoundUtil.asElement(getUIPart(component)); final ElementWrapperWidget<?> wrapper = ElementWrapperWidget.getWidget(element); if (wrapper instanceof TakesValue) { updateComponentValue(newValue, (TakesValue) wrapper, converter); } else if (wrapper instanceof HasText) { updateComponentValue(newValue, (HasText) wrapper, converter); } } } maybeFirePropertyChangeEvent(property, oldValue, newValue); }
Source:
private static Map<TaskId, SortedSet<UUID>> tasksToCaughtUpClients(final Set<TaskId> statefulTasks, final Map<UUID, ClientState> clientStates, final long acceptableRecoveryLag) { final Map<TaskId, SortedSet<UUID>> taskToCaughtUpClients = new HashMap<>(); for (final TaskId task : statefulTasks) { final TreeSet<UUID> caughtUpClients = new TreeSet<>(); for (final Map.Entry<UUID, ClientState> clientEntry : clientStates.entrySet()) { final UUID client = clientEntry.getKey(); final long taskLag = clientEntry.getValue().lagFor(task); if (active(taskLag) || unbounded(acceptableRecoveryLag) || acceptable(acceptableRecoveryLag, taskLag)) { caughtUpClients.add(client); } } taskToCaughtUpClients.put(task, caughtUpClients); } return taskToCaughtUpClients; }

Target:
private static Map<TaskId, SortedSet<UUID>> tasksToCaughtUpClients(final Set<TaskId> statefulTasks, final Map<UUID, ClientState> clientStates, final long acceptableRecoveryLag) { final Map<TaskId, SortedSet<UUID>> taskToCaughtUpClients = new HashMap<>(); for (final TaskId task : statefulTasks) { final TreeSet<UUID> caughtUpClients = new TreeSet<>(); for (final Map.Entry<UUID, ClientState> clientEntry : clientStates.entrySet()) { final UUID client = clientEntry.getKey(); final long taskLag = clientEntry.getValue().lagFor(task); if (activeRunning(taskLag) || unbounded(acceptableRecoveryLag) || acceptable(acceptableRecoveryLag, taskLag)) { caughtUpClients.add(client); } } taskToCaughtUpClients.put(task, caughtUpClients); } return taskToCaughtUpClients; }
Source:
public void setViewer(SDView viewer) { fLock.lock(); try { fView = viewer; PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().addPostSelectionListener(this); fView.setSDFindProvider(this); fView.setSDPagingProvider(this); fView.setSDFilterProvider(this); resetLoader(); IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (activePage != null) { IEditorPart editor = activePage.getActiveEditor(); if (editor instanceof ITmfTraceEditor) { ITmfTrace trace = ((ITmfTraceEditor) editor).getTrace(); if (trace != null) { traceSelected(new TmfTraceSelectedSignal(this, trace)); } } } } finally { fLock.unlock(); } }

Target:
public void setViewer(SDView viewer) { fLock.lock(); try { fView = viewer; PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().addPostSelectionListener(this); fView.setSDFindProvider(this); fView.setSDPagingProvider(this); fView.setSDFilterProvider(this); resetLoader(); IEditorPart editor = fView.getSite().getPage().getActiveEditor(); if (editor instanceof ITmfTraceEditor) { ITmfTrace trace = ((ITmfTraceEditor) editor).getTrace(); if (trace != null) { traceSelected(new TmfTraceSelectedSignal(this, trace)); } } } finally { fLock.unlock(); } }
Source:
public static void main(String[] args) { NGrinderControllerStarter server = new NGrinderControllerStarter(); JCommander commander = new JCommander(server); commander.setAcceptUnknownOptions(true); commander.setProgramName("ngrinder"); PortAvailabilityValidator validator = new PortAvailabilityValidator(); try { commander.parse(args); if (server.port == null) { server.port = 8080; } validator.validate("-p / --port", server.port); } catch (Exception e) { System.err.println(e.getMessage()); commander.usage(); System.exit(0); } System.setProperty("server.port", Integer.toString(server.port)); if (!server.contextPath.startsWith("/")) { server.contextPath = "/" + server.contextPath; } System.setProperty("server.contextPath", server.contextPath); if (server.help) { commander.usage(); System.exit(0); } if (server.home != null) { System.setProperty("ngrinder.home", server.home); } if (server.exHome != null) { System.setProperty("ngrinder.ex.home", server.exHome); } final List<String> unknownOptions = commander.getUnknownOptions(); final ClusterMode clusterMode = ClusterMode.valueOf(server.clusterMode); clusterMode.parseArgs(unknownOptions.toArray(new String[unknownOptions.size()])); System.getProperties().putAll(server.params); SpringApplication.run(NGrinderControllerStarter.class, args); cleanupPreviouslyUnpackedFolders(); }

Target:
public static void main(String[] args) { NGrinderControllerStarter server = new NGrinderControllerStarter(); JCommander commander = new JCommander(server); commander.setAcceptUnknownOptions(true); commander.setProgramName("ngrinder"); PortAvailabilityValidator validator = new PortAvailabilityValidator(); try { commander.parse(args); if (server.port == null) { server.port = 8080; } validator.validate("-p / --port", server.port); } catch (Exception e) { System.err.println(e.getMessage()); commander.usage(); System.exit(0); } System.setProperty("server.port", Integer.toString(server.port)); if (!server.contextPath.startsWith("/")) { server.contextPath = "/" + server.contextPath; } System.setProperty("server.contextPath", server.contextPath); if (server.help) { commander.usage(); System.exit(0); } if (server.home != null) { System.setProperty("ngrinder.home", server.home); } if (server.exHome != null) { System.setProperty("ngrinder.ex.home", server.exHome); } final List<String> unknownOptions = commander.getUnknownOptions(); final ClusterMode clusterMode = ClusterMode.valueOf(server.clusterMode); clusterMode.parseArgs(unknownOptions.toArray(new String[unknownOptions.size()])); System.getProperties().putAll(server.params); cleanupPreviouslyUnpackedFolders(); SpringApplication.run(NGrinderControllerStarter.class, args); }
Source:
private File determineSandboxDir(SarosIntellijExtension sarosExtension) { File sandboxBaseDir = sarosExtension.getSandboxBaseDir(); if (sandboxBaseDir == null) { sandboxBaseDir = project.getBuildDir(); } if (!sandboxBaseDir.exists()) { sandboxBaseDir.mkdirs(); } Integer sandboxCount = 1; File currentSandboxDir = determineSandboxDirCandidate(sandboxBaseDir, sandboxCount); while (isSandboxLocked(currentSandboxDir)) { sandboxCount++; currentSandboxDir = determineSandboxDirCandidate(sandboxBaseDir, sandboxCount); } return currentSandboxDir; }

Target:
private File determineSandboxDir(SarosIntellijExtension sarosExtension) { File sandboxBaseDir = sarosExtension.getSandboxBaseDir(); if (sandboxBaseDir == null) { sandboxBaseDir = project.getBuildDir(); } if (!sandboxBaseDir.exists() && !sandboxBaseDir.mkdirs()) { throw new GradleException( "Unable to create the sandbox base directory: " + sandboxBaseDir.getAbsolutePath()); } Integer sandboxCount = 1; File currentSandboxDir = determineSandboxDirCandidate(sandboxBaseDir, sandboxCount); while (isSandboxLocked(currentSandboxDir)) { sandboxCount++; currentSandboxDir = determineSandboxDirCandidate(sandboxBaseDir, sandboxCount); } return currentSandboxDir; }
Source:
public Iterable<VirtualGuest> listNodesByIds(final Iterable<String> ids) { return Iterables.filter(listNodes(), new Predicate<VirtualGuest>() { @Override public boolean apply(VirtualGuest server) { return Iterables.contains(ids, server.getId()); } }); }

Target:
public Iterable<VirtualGuest> listNodesByIds(final Iterable<String> ids) { return filter(listNodes(), new Predicate<VirtualGuest>() { @Override public boolean apply(VirtualGuest server) { return contains(ids, server.getId()); } }); }
Source:
public Array<T> reverse() { if (size() <= 1) { return this; } else { final Object[] arr = new Object[delegate.length]; for (int i = 0; i < delegate.length; i++) { arr[delegate.length - 1 - i] = delegate[i]; } return wrap(arr); } }

Target:
public Array<T> reverse() { if (size() <= 1) { return this; } else { final int length = delegate.length; final Object[] arr = new Object[length]; for (int i = 0, j = length - 1; i < length; i++, j--) { arr[j] = delegate[i]; } return wrap(arr); } }
Source:
public void restartGluster() { GlusterServiceParameters parameters = new GlusterServiceParameters(getEntity().getClusterId(), getEntity().getId(), ServiceType.GLUSTER, "restart"); Frontend.getInstance().runMultipleAction(VdcActionType.ManageGlusterService, new ArrayList<>(Arrays.asList(new VdcActionParametersBase[]{parameters})), new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { } }, null); }

Target:
public void restartGluster() { GlusterServiceParameters parameters = new GlusterServiceParameters(getEntity().getClusterId(), getEntity().getId(), ServiceType.GLUSTER, "restart"); Frontend.getInstance().runAction(VdcActionType.ManageGlusterService, parameters); }
Source:
public void deleteByContentType(final ContentTypeIf type) throws DotDataException{ final DotConnect dc = new DotConnect(); dc.setSQL(sql.DELETE_RELATIONSHIP_BY_PARENT_OR_CHILD_INODE); dc.addParam(type.id()); dc.addParam(type.id()); dc.loadResults(); }

Target:
public void deleteByContentType(final ContentTypeIf type) throws DotDataException{ new DotConnect() .setSQL(sql.DELETE_RELATIONSHIP_BY_PARENT_OR_CHILD_INODE) .addParam(type.id()) .addParam(type.id()) .loadResults(); }
Source:
public final Subscription subscribe() { final MultipleAssignmentSubscription mad = new MultipleAssignmentSubscription(); subscribe(new CompletableSubscriber() { @Override public void onCompleted() { mad.unsubscribe(); } @Override public void onError(Throwable e) { ERROR_HANDLER.handleError(e); mad.unsubscribe(); Thread thread = Thread.currentThread(); thread.getUncaughtExceptionHandler().uncaughtException(thread, e); } @Override public void onSubscribe(Subscription d) { mad.set(d); } }); return mad; }

Target:
public final Subscription subscribe() { final MultipleAssignmentSubscription mad = new MultipleAssignmentSubscription(); subscribe(new CompletableSubscriber() { @Override public void onCompleted() { mad.unsubscribe(); } @Override public void onError(Throwable e) { ERROR_HANDLER.handleError(e); mad.unsubscribe(); deliverUncaughtException(e); } @Override public void onSubscribe(Subscription d) { mad.set(d); } }); return mad; }
Source:
private void send(final Message message) { sendLink.delivery(UUID.randomUUID().toString().replace("-", "").getBytes(UTF_8)); final int payloadSize = EventDataUtil.getDataSerializedSize(message) + 512; final byte[] bytes = new byte[payloadSize]; final int encodedSize = message.encode(bytes, 0, payloadSize); receiveLink.flow(1); sendLink.send(bytes, 0, encodedSize); sendLink.advance(); }

Target:
private void send(final Message message) { sendLink.delivery(UUID.randomUUID().toString().replace("-", "").getBytes(UTF_8)); final int payloadSize = EventDataUtil.getDataSerializedSize(message) + MAX_EVENTHUB_AMQP_HEADER_SIZE_BYTES; final byte[] bytes = new byte[payloadSize]; final int encodedSize = message.encode(bytes, 0, payloadSize); receiveLink.flow(1); sendLink.send(bytes, 0, encodedSize); sendLink.advance(); }
Source:
public List<SegmentLoadInfo> fetchServerView(String dataSource, Interval interval, boolean incompleteOk) { try { StatusResponseHolder response = client.go( new Request( HttpMethod.GET, new URL( String.format( "%s/datasources/%s/intervals/%s/serverview?partial=%s", baseUrl(), dataSource, URLEncoder.encode(interval.toString(), "UTF-8"), incompleteOk ) ) ), RESPONSE_HANDLER ).get(); if (!response.getStatus().equals(HttpResponseStatus.OK)) { throw new ISE( "Error while fetching serverView status[%s] content[%s]", response.getStatus(), response.getContent() ); } return jsonMapper.readValue( response.getContent(), new TypeReference<List<SegmentLoadInfo>>() { } ); } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
public List<ImmutableSegmentLoadInfo> fetchServerView(String dataSource, Interval interval, boolean incompleteOk) { try { StatusResponseHolder response = client.go( new Request( HttpMethod.GET, new URL( String.format( "%s/datasources/%s/intervals/%s/serverview?partial=%s", baseUrl(), dataSource, interval.toString().replace("/", "_"), incompleteOk ) ) ), RESPONSE_HANDLER ).get(); if (!response.getStatus().equals(HttpResponseStatus.OK)) { throw new ISE( "Error while fetching serverView status[%s] content[%s]", response.getStatus(), response.getContent() ); } return jsonMapper.readValue( response.getContent(), new TypeReference<List<ImmutableSegmentLoadInfo>>() { } ); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
public boolean isDistributable() { final Distributed annotation = getAnnotation(Distributed.class); if (annotation != null) { return annotation.value(); } if (ReflectionUtils.is(getComponentClass(), HasDistributionAdvice.class)) { return true; } return true; }

Target:
public boolean isDistributable() { final Distributed annotation = getAnnotation(Distributed.class); if (annotation != null) { return annotation.value(); } return ReflectionUtils.is(getComponentClass(), HasDistributionAdvice.class); }
Source:
protected void executeCommand() { boolean success = true; if (!Guid.isNullOrEmpty(getParameters().getVdsId())) { Pair<Boolean, Integer> result = connectHostToStorage(); boolean isValidConnection = result.getFirst(); if (!isValidConnection) { throw new VdcBLLException(VdcBllErrors.forValue(result.getSecond())); } } if (success) { StorageServerConnections connection = getConnection(); connection.setid(Guid.newGuid().toString()); saveConnection(connection); getReturnValue().setActionReturnValue(connection.getid()); } setSucceeded(success); }

Target:
protected void executeCommand() { if (!Guid.isNullOrEmpty(getParameters().getVdsId())) { Pair<Boolean, Integer> result = connectHostToStorage(); boolean isValidConnection = result.getFirst(); if (!isValidConnection) { throw new VdcBLLException(VdcBllErrors.forValue(result.getSecond())); } } StorageServerConnections connection = getConnection(); connection.setid(Guid.newGuid().toString()); saveConnection(connection); getReturnValue().setActionReturnValue(connection.getid()); setSucceeded(true); }
Source:
private void checkConnection(Connection con, IInterfaceElement opposite, IInterfaceElement ownIE) { if(elementsToAdd.contains(opposite.getFBNetworkElement())){ moveConIntoSubApp(con); }else if (targetSubApp.equals(opposite.getFBNetworkElement())){ moveInterFaceCrossingConIntoSubApp(con, opposite, ownIE); } else { handleModifyConnection(con, ownIE); } }

Target:
private void checkConnection(Connection con, IInterfaceElement opposite, IInterfaceElement ownIE) { if(elementsToAdd.contains(opposite.getFBNetworkElement())){ moveConIntoSubApp(con); }else if (targetSubApp.equals(opposite.getFBNetworkElement())){ moveInterfaceCrossingConIntoSubApp(con, opposite, ownIE); } else { handleModifyConnection(con, ownIE); } }
Source:
public static void createTables(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + PEOPLE_TABLE + " (" + "person_id INTEGER DEFAULT 0," + "site_id TEXT," + "local_blog_id INTEGER DEFAULT 0," + "user_name TEXT," + "first_name TEXT," + "last_name TEXT," + "display_name TEXT," + "avatar_url TEXT," + "role TEXT," + "PRIMARY KEY (person_id, local_blog_id)" + ");"); }

Target:
public static void createTables(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + PEOPLE_TABLE + " (" + "person_id INTEGER DEFAULT 0," + "blog_id TEXT," + "local_blog_id INTEGER DEFAULT 0," + "user_name TEXT," + "first_name TEXT," + "last_name TEXT," + "display_name TEXT," + "avatar_url TEXT," + "role TEXT," + "PRIMARY KEY (person_id, local_blog_id)" + ");"); }
Source:
public ITmfStateValue getValue(ITmfEvent event) { if (fStateValue != null) { return fStateValue; } if (fType.equals(TmfXmlStrings.TYPE_NULL)) { return TmfStateValue.nullValue(); } try { return checkNotNull(fXmlStateValue).getValue(event); } catch (AttributeNotFoundException e) { Activator.logError("Failed to get the state value", e); } throw new IllegalStateException("Failed to get the value for the segment field " + fName); }

Target:
public ITmfStateValue getValue(ITmfEvent event) { if (fStateValue != null) { return fStateValue; } try { return checkNotNull(fXmlStateValue).getValue(event); } catch (AttributeNotFoundException e) { Activator.logError("Failed to get the state value", e); } throw new IllegalStateException("Failed to get the value for the segment field " + fName); }
Source:
void handleActionResult(final VdcActionType actionType, final VdcActionParametersBase parameters, final VdcReturnValueBase result, final IFrontendActionAsyncCallback callback, final Object state, final boolean showErrorDialog) { logger.log(Level.FINER, "Retrieved action result from RunAction."); FrontendActionAsyncResult f = new FrontendActionAsyncResult(actionType, parameters, result, state); boolean success = false; if (!result.getCanDoAction()) { result.setCanDoActionMessages((ArrayList<String>) translateError(result)); callback.executed(f); } else if (showErrorDialog && result.getIsSyncronious() && !result.getSucceeded()) { runActionExecutionFailed(actionType, result.getFault()); callback.executed(f); success = true; } else { success = true; callback.executed(f); } if (showErrorDialog && (!success) && (getEventsHandler() != null) && (getEventsHandler().isRaiseErrorModalPanel(actionType, result.getFault()))) { if (result.getCanDoActionMessages().size() <= 1) { String errorMessage = !result.getCanDoAction() || !result.getCanDoActionMessages().isEmpty() ? getRunActionErrorMessage(result.getCanDoActionMessages()) : result.getFault().getMessage(); failureEventHandler(result.getDescription(), errorMessage); } else { failureEventHandler(result.getDescription(), result.getCanDoActionMessages()); } } }

Target:
void handleActionResult(final VdcActionType actionType, final VdcActionParametersBase parameters, final VdcReturnValueBase result, final IFrontendActionAsyncCallback callback, final Object state, final boolean showErrorDialog) { logger.log(Level.FINER, "Retrieved action result from RunAction."); FrontendActionAsyncResult f = new FrontendActionAsyncResult(actionType, parameters, result, state); boolean failedOnCanDoAction = !result.getCanDoAction(); if (failedOnCanDoAction) { result.setCanDoActionMessages((ArrayList<String>) translateError(result)); } else if (showErrorDialog && result.getIsSyncronious() && !result.getSucceeded()) { runActionExecutionFailed(actionType, result.getFault()); } callback.executed(f); if (showErrorDialog && failedOnCanDoAction && (getEventsHandler() != null) && (getEventsHandler().isRaiseErrorModalPanel(actionType, result.getFault()))) { if (result.getCanDoActionMessages().isEmpty()) { failureEventHandler(result.getDescription(), "No Message"); } else { failureEventHandler(result.getDescription(), result.getCanDoActionMessages()); } } }
Source:
public void scheduleInitial(SourceScheduler scheduler) { checkState(!initialScheduled); initialScheduled = true; int driverGroupsScheduledPerTask = 0; while (driverGroups.hasNext()) { for (int i = 0; i < allNodes.size() && driverGroups.hasNext(); i++) { int driverGroupId = driverGroups.nextInt(); checkState(!bucketNodeMap.getAssignedNode(driverGroupId).isPresent()); bucketNodeMap.assignOrChangeBucketToNode(driverGroupId, allNodes.get(i)); scheduler.startLifespan(Lifespan.driverGroup(driverGroupId), partitionHandles.get(driverGroupId)); } driverGroupsScheduledPerTask++; if (concurrentLifespansPerTask.isPresent() && driverGroupsScheduledPerTask == concurrentLifespansPerTask.getAsInt()) { break; } } if (!driverGroups.hasNext()) { scheduler.noMoreLifespans(); } }

Target:
public void scheduleInitial(SourceScheduler scheduler) { checkState(!initialScheduled); initialScheduled = true; int driverGroupsScheduledPerTask = 0; while (driverGroups.hasNext()) { for (int i = 0; i < allNodes.size() && driverGroups.hasNext(); i++) { int driverGroupId = driverGroups.nextInt(); checkState(!bucketNodeMap.getAssignedNode(driverGroupId).isPresent()); bucketNodeMap.assignBucketToNode(driverGroupId, allNodes.get(i)); scheduler.startLifespan(Lifespan.driverGroup(driverGroupId), partitionHandles.get(driverGroupId)); } driverGroupsScheduledPerTask++; if (concurrentLifespansPerTask.isPresent() && driverGroupsScheduledPerTask == concurrentLifespansPerTask.getAsInt()) { break; } } if (!driverGroups.hasNext()) { scheduler.noMoreLifespans(); } }
Source:
private void updateCardsInList(List<Card> cards, Map<Long, String> updatedCardTags) { List<Card> allCards = CardUtils.getAllCards(CardUtils.getNotes(cards)); for (Card c : allCards) { Note note = c.note(); int pos = getPosition(getCards(), c.getId()); if (pos < 0 || pos >= getCards().size()) { continue; } if (updatedCardTags != null) { getCards().get(pos).put("tags", updatedCardTags.get(c.getNid())); } String sfld = note.getSFld(); getCards().get(pos).put("sfld", sfld); updateSearchItemQA(getCards().get(pos), c); String deckName; try { deckName = getCol().getDecks().get(c.getDid()).getString("name"); } catch (JSONException e) { throw new RuntimeException(e); } getCards().get(pos).put("deck", deckName); String flags = Integer.toString((c.getQueue() == -1 ? 1 : 0) + (note.hasTag("marked") ? 2 : 0)); getCards().get(pos).put("flags", flags); } updateList(); }

Target:
private void updateCardsInList(List<Card> cards, Map<Long, String> updatedCardTags) { Map<Long, Integer> idToPos = getPositionMap(getCards()); for (Card c : cards) { Note note = c.note(); int pos = idToPos.containsKey(c.getId()) ? idToPos.get(c.getId()) : -1; if (pos < 0 || pos >= getCards().size()) { continue; } if (updatedCardTags != null) { getCards().get(pos).put("tags", updatedCardTags.get(c.getNid())); } String sfld = note.getSFld(); getCards().get(pos).put("sfld", sfld); updateSearchItemQA(getCards().get(pos), c); String deckName; try { deckName = getCol().getDecks().get(c.getDid()).getString("name"); } catch (JSONException e) { throw new RuntimeException(e); } getCards().get(pos).put("deck", deckName); String flags = Integer.toString((c.getQueue() == -1 ? 1 : 0) + (note.hasTag("marked") ? 2 : 0)); getCards().get(pos).put("flags", flags); } updateList(); }