Input:
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.tinycloud.bean.entity.UcUser;
import org.tinycloud.bean.param.UcUserPageQuery;
import org.tinycloud.bean.vo.UcUserVo;
import org.tinycloud.common.consts.GlobalConstant;
import org.tinycloud.common.model.PageModel;
import org.tinycloud.common.utils.LambdaUtils;
import org.tinycloud.common.utils.StringUtils;
import org.tinycloud.common.utils.bean.BeanUtils;
import org.tinycloud.user.mapper.UcUserMapper;
import org.tinycloud.user.service.UcUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.stream.Collectors;

Context:
tinycloud-user/src/main/java/org/tinycloud/user/service/impl/UcUserServiceImpl.java
package org.tinycloud.user.service.impl;

@Service
public class UcUserServiceImpl implements UcUserService {

    @Autowired
    private UcUserMapper ucUserMapper;

    /**
     * 根据id查询详情
     * @param userId
     * @return
     */
    @Override
    public UcUserVo detail(String userId) {
        UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery()
                .eq(UcUser::getUserId, userId)
                .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED));
        if (ucUser != null) {
            return BeanUtils.transformBean(ucUser, UcUserVo.class);
        }
        return null;
    }

    /**
     * 第二种动态排序的方法
     * @param pageQuery UcUserPageQuery
     * @return PageModel<UcUserVo>
     */
    @Override
    public PageModel<UcUserVo> query(UcUserPageQuery pageQuery) {
        PageModel<UcUserVo> responsePage = new PageModel<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        LambdaQueryWrapper<UcUser> wrapper = new LambdaQueryWrapper<>();

        boolean isAsc = false;
        if (GlobalConstant.ASC.equalsIgnoreCase(pageQuery.getSortType())) {
            isAsc = true;
        }

        wrapper.like(StringUtils.isNotEmpty(pageQuery.getUsername()), UcUser::getUsername, pageQuery.getUsername());
        wrapper.like(StringUtils.isNotEmpty(pageQuery.getNickname()), UcUser::getNickname, pageQuery.getNickname());
        wrapper.orderBy(StringUtils.isNotEmpty(pageQuery.getSortType()) && StringUtils.isNotEmpty(pageQuery.getSortFiled()),
                isAsc,
                LambdaUtils.getLambdaGetter(UcUser.class, pageQuery.getSortFiled()));

        Page<UcUser> page = this.ucUserMapper.selectPage(new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize()), wrapper);
        if (page != null && !CollectionUtils.isEmpty(page.getRecords())) {
            responsePage.setTotalPage((int) page.getPages());

tinycloud-bean/src/main/java/org/tinycloud/bean/param/UcUserPageQuery.java
@Getter
@Setter
public class UcUserPageQuery extends BasePageParam {
    private static final long serialVersionUID = -1L;

    @ApiModelProperty("用户账号")
    private String username;

    @ApiModelProperty("用户昵称（中文姓名）")
    private String nickname;
}

tinycloud-common/src/main/java/org/tinycloud/common/consts/GlobalConstant.java
public final class GlobalConstant {

    /**
     * 系统包名前缀(用于扫描包的配置)
     */
    public static final String BASE_PACKAGE_PREFIX = "org.tinycloud";

    /**
     * Feign包名前缀(用于扫描Feign的配置)
     */
    public static final String FEIGN_PACKAGE_PREFIX = "org.tinycloud.api";

    /**
     * 前端请求头的的请求客户端
     */
    public static final String HEADER_CLIENT_TYPE = "client-type";

    /**
     * 已删除标记
     */
    public static final Integer DELETED = 1;

    /**
     * 未删除标记
     */
    public static final Integer NOT_DELETED = 0;

    /**
     * 升序排序
     */
    public static final String ASC = "asc";

    /**
     * 降序排序
     */
    public static final String DESC = "desc";

    /**
     * 统一接口限流 redis-key
     */
    public static final String LIMIT_KEY = "tinycloud:limit";
}

tinycloud-common/src/main/java/org/tinycloud/common/utils/LambdaUtils.java
public class LambdaUtils {
    private static final Logger logger = LoggerFactory.getLogger(LambdaUtils.class);

    public static final Map<Class<?>, PropertyDescriptor[]> cache = new HashMap<>();

    public static <T> SFunction<T, ?> getLambdaGetter(Class<T> clazz, String prop) {
        try {
            PropertyDescriptor[] beanGetters;
            if (cache.containsKey(clazz)) {
                beanGetters = cache.get(clazz);
            } else {
                beanGetters = ReflectUtils.getBeanGetters(clazz);
                cache.put(clazz, beanGetters);
            }

            MethodHandles.Lookup lookup = MethodHandles.lookup();
            Optional<PropertyDescriptor> optional = Arrays.stream(beanGetters)
                    .filter(pd -> pd.getName().equals(prop))
                    .findFirst();
            if (optional.isPresent()) {
                // 反射获取getter方法
                Method readMethod = optional.get().getReadMethod();
                // 拿到方法句柄
                final MethodHandle methodHandle = lookup.unreflect(readMethod);
                // 创建动态调用链
                CallSite callSite = LambdaMetafactory.altMetafactory(
                        lookup,
                        "apply",
                        MethodType.methodType(SFunction.class),
                        MethodType.methodType(Object.class, Object.class),
                        methodHandle,
                        MethodType.methodType(readMethod.getReturnType(), clazz),
                        LambdaMetafactory.FLAG_SERIALIZABLE
                );
                return (SFunction<T, ?>) callSite.getTarget().invokeExact();
            }
        } catch (Throwable throwable) {
            logger.error("getLambdaGetter Throwable: ", throwable);
        }

        return null;
    }

}

tinycloud-common/src/main/java/org/tinycloud/common/model/PageModel.java
public class PageModel<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    // 总记录数
    private Integer totalCount;

    // 总页数
    private Integer totalPage;

    // 结果集
    private List<T> records;

    // 当前页码
    private Integer pageNo;

    // 当前页大小
    private Integer pageSize;

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getRecords() {
        return records;
    }

    public void setRecords(List<T> records) {
        this.records = records;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public PageModel() {
    }

    public PageModel(Integer pageNo, Integer pageSize) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
    }

    public PageModel(Integer pageNo, Integer pageSize, List<T> records, Integer totalCount) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.records = records;
        this.totalCount = totalCount;
        // 自动计算出总页数
        if (totalCount != 0) {
            this.totalPage = (totalCount - 1) / pageSize + 1;
        } else {
            this.totalPage = 0;
        }
    }

    public PageModel(Integer pageNo, Integer pageSize, List<T> records, Integer totalCount, Integer totalPage) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.records = records;
        this.totalCount = totalCount;
        this.totalPage = totalPage;
    }

    public static <T> PageModel<T> build(Integer page, Integer size, List<T> list, Integer totalCount, Integer totalPage) {
        return new PageModel<>(page, size, list, totalCount, totalPage);
    }
}

tinycloud-common/src/main/java/org/tinycloud/common/utils/bean/BeanUtils.java
public class BeanUtils {

    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 批量copy两个bean属性
     *
     * @param source 源
     * @param tClass 目标类型
     * @return List<T> 目标类型列表中
     */
    public static <S, T> List<T> batchTransformBean(List<S> source, Class<T> tClass) {
        List<T> result = new ArrayList<>();
        try {
            for (S co : source) {
                T t = tClass.newInstance();

                org.springframework.beans.BeanUtils.copyProperties(co, t);
                result.add(t);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("转换失败");
        }
        return result;
    }

    /**
     * 拷贝两个bean属性
     *
     * @param source 源
     * @param tClass 目标类型
     * @return 目标类型实例
     */
    public static <S, T> T transformBean(S source, Class<T> tClass) {
        T t;
        try {
            t = tClass.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(source, t);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("转换失败");
        }
        return t;
    }

    /**
     * Bean属性复制工具方法
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source, Object target) {
        try {
            org.springframework.beans.BeanUtils.copyProperties(source, target);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException("拷贝bean失败");
        }
    }

    /**
     * bean转map
     *
     * @param source bean
     * @param <T>    传入的bean类型
     * @return Map<String, Object>
     */
    public static <T> Map<String, Object> beanToMap(T source) {
        Map<String, Object> map = new HashMap<>(16);
        if (source != null) {
            BeanMap beanMap = BeanMap.create(source);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * map转为javaBean
     *
     * @param map   要转换的map
     * @param clazz 转换成的bean类
     * @return 转换后的bean
     */
    public static <T> T mapToBean(Map<String, ?> map, Class<T> clazz) {
        try {
            T bean = clazz.newInstance();
            BeanMap beanMap = BeanMap.create(bean);
            for (String key : map.keySet()) {
                if (key.contains("_")) {
                    String newKey = StringUtils.toLowerCaseFirstOne(StringUtils.lineToHump(key));
                    beanMap.put(newKey, map.get(key));
                } else {
                    beanMap.put(key, map.get(key));
                }
            }
            return bean;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 批量转换map为javaBean
     *
     * @param list  map
     * @param clazz 类型
     * @return 转换后的list
     */
    public static <T, S> List<T> batchMapToBean(List<Map<String, S>> list, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        for (Map<String, ?> map : list) {
            result.add(mapToBean(map, clazz));
        }
        return result;
    }
}

Answer: responsePage.setTotalCount((int) page.getTotal());

<think>
The query method builds a PageModel response. Inside the if block after setting totalPage, the next logical step is to set the total record count before populating the records list. The Page object provides getTotal() for total records, so the next line should assign this to responsePage.
</think>
responsePage.setTotalCount((int) page.getTotal());


Input:
import java.util.function.Function;
import java.util.function.Supplier;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import com.tom.peripherals.block.GPUBlock;
import com.tom.peripherals.block.MonitorBlock;
import com.tom.peripherals.block.RedstonePortBlock;
import com.tom.peripherals.block.WatchDogTimerBlock;
import com.tom.peripherals.block.entity.GPUBlockEntity;
import com.tom.peripherals.block.entity.MonitorBlockEntity;
import com.tom.peripherals.block.entity.RedstonePortBlockEntity;
import com.tom.peripherals.block.entity.WatchDogTimerBlockEntity;
import com.tom.peripherals.platform.GameObject;
import com.tom.peripherals.platform.GameObject.GameObjectBlockEntity;
import com.tom.peripherals.platform.GameObject.GameRegistryBE.BlockEntityFactory;
import com.tom.peripherals.platform.Platform;

Context:
Forge/src/platform-shared/java/com/tom/peripherals/Content.java
package com.tom.peripherals;

public class Content {
	public static final GameObject<GPUBlock> gpu = blockWithItem("gpu", GPUBlock::new);
	public static final GameObject<MonitorBlock> monitor = blockWithItem("monitor", MonitorBlock::new);
	public static final GameObject<WatchDogTimerBlock> wdt = blockWithItem("wdt", WatchDogTimerBlock::new);
	public static final GameObject<RedstonePortBlock> redstonePort = blockWithItem("redstone_port", RedstonePortBlock::new);

	public static final GameObject<Item> gpuChip = item("gpu_chip", () -> new Item(new Item.Properties()));
	public static final GameObject<Item> gpuChipRaw = item("gpu_chip_raw", () -> new Item(new Item.Properties()));

	public static final GameObjectBlockEntity<GPUBlockEntity> gpuBE = blockEntity("gpu", GPUBlockEntity::new, gpu);

Fabric/src/main/java/com/tom/peripherals/platform/GameObject.java
public static class GameObjectBlockEntity<T extends BlockEntity> extends GameObject<BlockEntityType<T>> {
	private BlockEntityType<T> value;
	private List<GameObject<? extends Block>> blocks;
	private BlockEntityFactory<T> factory;
	private GameRegistryBE registry;
	private String name;

	public GameObjectBlockEntity(GameRegistryBE registry, String name, List<GameObject<? extends Block>> blocks, BlockEntityFactory<T> factory) {
		super(null);
		this.name = name;
		this.blocks = blocks;
		this.factory = factory;
		this.registry = registry;
	}

	protected void register() {
		value = FabricBlockEntityTypeBuilder.create((a, b) -> factory.create(value, a, b), blocks.stream().map(GameObject::get).toArray(Block[]::new)).build(null);
		Registry.register(registry.registry, new ResourceLocation(PeripheralsMod.ID, name), value);
	}

	@Override
	public BlockEntityType<T> get() {
		return value;
	}

	@SuppressWarnings("unchecked")
	public void addBlocks(GameObject<? extends Block>... blocks) {
		this.blocks.addAll(Arrays.asList(blocks));
	}
}

Forge/src/platform-shared/java/com/tom/peripherals/block/entity/RedstonePortBlockEntity.java
public class RedstonePortBlockEntity extends AbstractPeripheralBlockEntity implements TickableServer {
	private static final Object[] SIDES = Arrays.stream(Direction.values()).map(e -> e.getSerializedName()).toArray();
	private ObjectWrapper peripheral;

	private boolean internalOutputChanged = false;
	private final int[] internalOutput = new int[6];
	private final int[] internalBundledOutput = new int[6];
	private final int[] externalOutput = new int[6];
	private final int[] externalBundledOutput = new int[6];
	private boolean inputChanged = false;
	private final int[] input = new int[6];
	private final int[] bundledInput = new int[6];

	public RedstonePortBlockEntity(BlockEntityType<?> p_155228_, BlockPos p_155229_, BlockState p_155230_) {
		super(p_155228_, p_155229_, p_155230_);
	}

	@Override
	public ObjectWrapper getPeripheral() {
		if(peripheral == null)peripheral = new ObjectWrapper("tm_rsPort", new RSPort());
		return peripheral;
	}

	public class RSPort extends TMLuaObject {

		@LuaMethod
		public Object[] getSides() throws LuaException {
			return SIDES;
		}

		@LuaMethod
		public boolean getInput(Object[] args) throws LuaException {
			if (args.length < 1) {
				throw new LuaException("Too few arguments (expected direction)");
			}
			return RedstonePortBlockEntity.this.getInput(getDir(args[0])) > 0;
		}

		@LuaMethod
		public int getAnalogInput(Object[] args) throws LuaException {
			if (args.length < 1) {
				throw new LuaException("Too few arguments (expected direction)");
			}
			return RedstonePortBlockEntity.this.getInput(getDir(args[0]));
		}

		@LuaMethod
		public int getAnalogueInput(Object[] args) throws LuaException {
			return getAnalogInput(args);
		}

		@LuaMethod
		public int getBundledInput(Object[] args) throws LuaException {
			if (args.length < 1) {
				throw new LuaException("Too few arguments (expected direction)");
			}
			return RedstonePortBlockEntity.this.getBundledInput(getDir(args[0]));
		}

		@LuaMethod
		public boolean getOutput(Object[] args) throws LuaException {
			if (args.length < 1) {
				throw new LuaException("Too few arguments (expected direction)");
			}
			return RedstonePortBlockEntity.this.getOutput(getDir(args[0])) > 0;
		}

		@LuaMethod
		public int getAnalogOutput(Object[] args) throws LuaException {
			if (args.length < 1) {
				throw new LuaException("Too few arguments (expected direction)");
			}
			return RedstonePortBlockEntity.this.getOutput(getDir(args[0]));
		}

		@LuaMethod
		public int getAnalogueOutput(Object[] args) throws LuaException {
			return getAnalogOutput(args);
		}

		@LuaMethod
		public int getBundledOutput(Object[] args) throws LuaException {
			if (args.length < 1) {
				throw new LuaException("Too few arguments (expected direction)");
			}
			return RedstonePortBlockEntity.this.getBundledOutput(getDir(args[0]));
		}

		@LuaMethod
		public void setOutput(Object[] args) throws LuaException {
			if (args.length < 2) {
				throw new LuaException("Too few arguments (expected direction, value)");
			}
			if (!(args[1] instanceof Boolean v))
				throw new LuaException("Bad argument #2 (expected Boolean)");
			RedstonePortBlockEntity.this.setOutput(getDir(args[0]), v ? 15 : 0);
		}

		@LuaMethod
		public void setAnalogOutput(Object[] args) throws LuaException {
			if (args.length < 2) {
				throw new LuaException("Too few arguments (expected direction, value)");
			}
			if (!(args[1] instanceof Double v))
				throw new LuaException("Bad argument #2 (expected Number)");
			Direction dir = getDir(args[0]);
			int out = Mth.floor(v);
			if (out < 0 || out > 15)
				throw new LuaException("Bad argument #2: Expected number in range 0-15");

			RedstonePortBlockEntity.this.setOutput(dir, out);
		}

		@LuaMethod
		public void setAnalogueOutput(Object[] args) throws LuaException {
			setAnalogOutput(args);
		}

		@LuaMethod
		public void setBundledOutput(Object[] args) throws LuaException {
			if (args.length < 2) {
				throw new LuaException("Too few arguments (expected direction, value)");
			}
			if (!(args[1] instanceof Double v))
				throw new LuaException("Bad argument #2 (expected Number)");
			Direction dir = getDir(args[0]);
			int out = Mth.floor(v);

			RedstonePortBlockEntity.this.setBundledOutput(dir, out);
		}

		@LuaMethod
		public boolean testBundledInput(Object[] args) throws LuaException {
			if (args.length < 2) {
				throw new LuaException("Too few arguments (expected direction, mask)");
			}
			if (!(args[1] instanceof Double md))
				throw new LuaException("Bad argument #2 (expected Number)");
			int value = RedstonePortBlockEntity.this.getBundledInput(getDir(args[0]));
			int mask = Mth.floor(md);
			return (value & mask) == mask;
		}

		private Direction getDir(Object in) throws LuaException {
			String side = String.valueOf(in);
			Direction dir = null;
			for(Direction d : Direction.values()) {
				if (d.getName().equalsIgnoreCase(side)) {
					dir = d;
					break;
				}
			}
			if (dir == null)throw new LuaException("Bad argument #1: expected one of: up, down, north, south, east, west");
			return dir;
		}
	}

	public boolean updateOutput() {
		synchronized (this.internalOutput) {
			if (!this.internalOutputChanged) {
				return false;
			} else {
				boolean changed = false;

				for (int i = 0; i < 6; ++i) {
					if (this.externalOutput[i] != this.internalOutput[i]) {
						this.externalOutput[i] = this.internalOutput[i];
						changed = true;
					}

					if (this.externalBundledOutput[i] != this.internalBundledOutput[i]) {
						this.externalBundledOutput[i] = this.internalBundledOutput[i];
						changed = true;
					}
				}

				this.internalOutputChanged = false;
				return changed;
			}
		}
	}

	@Override
	public void updateServer() {
		if (inputChanged) {
			inputChanged = false;
			getPeripheral().queueEvent("tm_redstone", new Object[0]);
		}
		if (updateOutput()) {
			for (var dir : DirectionUtil.FACINGS) RedstoneUtil.propagateRedstoneOutput(getLevel(), getBlockPos(), dir);
			updateRedstoneInputs();
		}
	}

	public int getInput(Direction side) {
		return input[side.ordinal()];
	}

	public int getBundledInput(Direction side) {
		return bundledInput[side.ordinal()];
	}

	public void setOutput(Direction side, int output) {
		var index = side.ordinal();
		synchronized (internalOutput) {
			if (internalOutput[index] != output) {
				internalOutput[index] = output;
				internalOutputChanged = true;
			}
		}
	}

	public int getOutput(Direction side) {
		synchronized (internalOutput) {
			return internalOutput[side.ordinal()];
		}
	}

	public void setBundledOutput(Direction side, int output) {
		var index = side.ordinal();
		synchronized (internalOutput) {
			if (internalBundledOutput[index] != output) {
				internalBundledOutput[index] = output;
				internalOutputChanged = true;
			}
		}
	}

	public int getBundledOutput(Direction side) {
		synchronized (internalOutput) {
			return internalBundledOutput[side.ordinal()];
		}
	}

	public int getExternalRedstoneOutput(Direction side) {
		return externalOutput[side.ordinal()];
	}

	public int getExternalBundledRedstoneOutput(Direction side) {
		return externalBundledOutput[side.ordinal()];
	}

	public void setRedstoneInput(Direction side, int level) {
		var index = side.ordinal();
		if (input[index] != level) {
			input[index] = level;
			inputChanged = true;
		}
	}

	public void setBundledRedstoneInput(Direction side, int combination) {
		var index = side.ordinal();
		if (bundledInput[index] != combination) {
			bundledInput[index] = combination;
			inputChanged = true;
		}
	}

	private void updateRedstoneInput(Direction dir, BlockPos targetPos) {
		var offsetSide = dir.getOpposite();

		setRedstoneInput(dir, RedstoneUtil.getRedstoneInput(level, targetPos, dir));
		setBundledRedstoneInput(dir, BundledRedstone.getOutput(getLevel(), targetPos, offsetSide));
	}

	private void updateRedstoneInputs() {
		var pos = getBlockPos();
		for (var dir : DirectionUtil.FACINGS) updateRedstoneInput(dir, pos.relative(dir));
	}

	public void neighborChanged(BlockPos neighbour) {
		updateInputAt(neighbour);
	}

	private void updateInputAt(BlockPos neighbour) {
		for (var dir : DirectionUtil.FACINGS) {
			var offset = getBlockPos().relative(dir);
			if (offset.equals(neighbour)) {
				updateRedstoneInput(dir, offset);
				return;
			}
		}

		// If the position is not any adjacent one, update all inputs. This is pretty terrible, but some redstone mods
		// handle this incorrectly.
		updateRedstoneInputs();
	}
}

Answer: public static final GameObjectBlockEntity<MonitorBlockEntity> monitorBE = blockEntity("monitor", MonitorBlockEntity::new, monitor);

<think>
In Content.java the static fields for blocks and items are being declared. After the gpuBE field, the next logical declaration is the block entity for the monitor block, following the same pattern as gpuBE. The method blockEntity is used to create a GameObjectBlockEntity, taking the name, a factory, and the associated block GameObject. Therefore the next line should declare monitorBE accordingly.
</think>
public static final GameObjectBlockEntity<MonitorBlockEntity> monitorBE = blockEntity("monitor", MonitorBlockEntity::new, monitor);


Input:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import routing.maxprop.MaxPropDijkstra;
import routing.maxprop.MeetingProbabilitySet;
import routing.util.RoutingInfo;
import util.Tuple;
import core.Connection;
import core.DTNHost;
import core.Message;
import core.Settings;
import core.SimClock;

Context:
src/routing/MaxPropRouterWithEstimation.java
/*
 * Copyright 2010 Aalto University, ComNet
 * Released under GPLv3. See LICENSE.txt for details.
 */
package routing;

/**
 * Implementation of MaxProp router as described in
 * MaxProp: Routing for Vehicle-Based Disruption-Tolerant Networks by
 * John Burgess et al.
 *
 * but with parameter estimation for finding an alpha based on timescale
 * definition:
 *
 * Extension of the protocol by adding a parameter alpha (default 1)
 * By new connection, the delivery likelihood is increased by alpha
 * and divided by 1+alpha.  Using the default results in the original
 * algorithm.  Refer to Karvo and Ott, Time Scales and Delay-Tolerant Routing
 * Protocols Chants, 2008
 *
 * This version tries to estimate a good value of alpha from a timescale parameter
 * given by the user, and from the encounters the node sees during simulation.
 *
 * @version 1.0
 */
public class MaxPropRouterWithEstimation extends ActiveRouter {
	/** probabilities of meeting hosts */
	private MeetingProbabilitySet probs;
	/** meeting probabilities of all hosts from this host's point of view
	 * mapped using host's network address */
	private Map<Integer, MeetingProbabilitySet> allProbs;
	/** the cost-to-node calculator */
	private MaxPropDijkstra dijkstra;
	/** IDs of the messages that are known to have reached the final dst */
	private Set<String> ackedMessageIds;
	/** mapping of the current costs for all messages. This should be set to
	 * null always when the costs should be updated (a host is met or a new
	 * message is received) */
	private Map<Integer, Double> costsForMessages;
	/** From host of the last cost calculation */
	private DTNHost lastCostFrom;

	/** Over how many samples the "average number of bytes transferred per
	 * transfer opportunity" is taken */
	public static int BYTES_TRANSFERRED_AVG_SAMPLES = 10;
	private int[] avgSamples;
	private int nextSampleIndex = 0;
	/** current value for the "avg number of bytes transferred per transfer
	 * opportunity"  */
	private int avgTransferredBytes = 0;

	/** MaxPROP router's setting namespace ({@value})*/
	public static final String MAXPROP_NS = "MaxPropRouterWithEstimation";

	/* Number of seconds in time scale.*/
	public static final String TIME_SCALE_S ="timeScale";

	/** The alpha variable, default = 1;
	*/
	private double alpha;

	/** The default value for alpha
	*/
	public static final double DEFAULT_ALPHA = 1.0;

	/** value of time scale variable */
	private int timescale;

	/** last meeting time with a node */
	private Map<DTNHost, Double> meetings;
	private int nrofSamplesIET;
	private double meanIET;

	/** number of encounters between encounters */
	private Map<DTNHost, Integer> encounters;
	private int nrofSamplesENC;
	private double meanENC;
	private int nrofTotENC;

	/**
	 * Constructor. Creates a new prototype router based on the settings in
	 * the given Settings object.
	 * @param settings The settings object
	 */
	public MaxPropRouterWithEstimation(Settings settings) {
		super(settings);
		Settings maxPropSettings = new Settings(MAXPROP_NS);
		alpha = DEFAULT_ALPHA;
		timescale = maxPropSettings.getInt(TIME_SCALE_S);
		initMeetings();
	}

	/**
	 * Copy constructor. Creates a new router based on the given prototype.
	 * @param r The router prototype where setting values are copied from
	 */
	protected MaxPropRouterWithEstimation(MaxPropRouterWithEstimation r) {
		super(r);
		this.alpha = r.alpha;
		this.timescale = r.timescale;
		this.probs = new MeetingProbabilitySet(
				MeetingProbabilitySet.INFINITE_SET_SIZE, this.alpha);
		this.allProbs = new HashMap<Integer, MeetingProbabilitySet>();
		this.dijkstra = new MaxPropDijkstra(this.allProbs);
		this.ackedMessageIds = new HashSet<String>();
		this.avgSamples = new int[BYTES_TRANSFERRED_AVG_SAMPLES];
		initMeetings();
	}

	/**
	 * Initializes interencounter estimators
	 */
	private void initMeetings() {
		this.meetings = new HashMap<DTNHost, Double>();
		this.encounters = new HashMap<DTNHost, Integer>();
		this.meanIET = 0;
		this.nrofSamplesIET = 0;
		this.meanENC = 0;
		this.nrofSamplesENC = 0;
		this.nrofTotENC = 0;
	}

	@Override

src/routing/util/RoutingInfo.java
public class RoutingInfo {
	private String text;
	private List<RoutingInfo> moreInfo = null;

	/**
	 * Creates a routing info based on a text.
	 * @param infoText The text of the info
	 */
	public RoutingInfo(String infoText) {
		this.text = infoText;
	}

	/**
	 * Creates a routing info based on any object. Object's
	 * toString() method's output is used as the info text.
	 * @param o The object this info is based on
	 */
	public RoutingInfo(Object o) {
		this.text = o.toString();
	}

	/**
	 * Adds child info object for this routing info.
	 * @param info The info object to add.
	 */
	public void addMoreInfo(RoutingInfo info) {
		if (this.moreInfo == null) { // lazy creation
			this.moreInfo = new ArrayList<RoutingInfo>();
		}
		this.moreInfo.add(info);
	}

	/**
	 * Returns the child routing infos of this info.
	 * @return The children of this info or an empty list if this info
	 * doesn't have any children.
	 */
	public List<RoutingInfo> getMoreInfo() {
		if (this.moreInfo == null) {
			return new ArrayList<RoutingInfo>(0);
		}
		return this.moreInfo;
	}

	/**
	 * Returns the info text of this routing info.
	 * @return The info text
	 */
	public String toString() {
		return this.text;
	}

}

src/routing/maxprop/MeetingProbabilitySet.java
public class MeetingProbabilitySet {
	public static final int INFINITE_SET_SIZE = Integer.MAX_VALUE;
	/** meeting probabilities (probability that the next node one meets is X) */
	private Map<Integer, Double> probs;
	/** the time when this MPS was last updated */
	private double lastUpdateTime;
	/** the alpha parameter */
	private double alpha;
    private int maxSetSize;

	/**
	 * Constructor. Creates a probability set with empty node-probability
	 * mapping.
	 * @param maxSetSize Maximum size of the probability set; when the set is
	 *        full, smallest values are dropped when new are added
	 */
	public MeetingProbabilitySet(int maxSetSize, double alpha) {
		this.alpha = alpha;
		this.probs = new HashMap<Integer, Double>();
        if (maxSetSize == INFINITE_SET_SIZE || maxSetSize < 1) {
	this.probs = new HashMap<Integer, Double>();
	this.maxSetSize = INFINITE_SET_SIZE;
        } else {
	this.probs = new HashMap<Integer, Double>(maxSetSize);
            this.maxSetSize = maxSetSize;
        }
		this.lastUpdateTime = 0;
	}

	/**
	 * Constructor. Creates a probability set with empty node-probability
	 * mapping and infinite set size
	 */
	public MeetingProbabilitySet() {
		this(INFINITE_SET_SIZE, 1);
	}

	/**
	 * Constructor. Creates a probability set with equal probability for
	 * all the given node indexes.
	 */
	public MeetingProbabilitySet(double alpha,
				List<Integer> initiallyKnownNodes) {
		this(INFINITE_SET_SIZE, alpha);
		double prob = 1.0/initiallyKnownNodes.size();
		for (Integer i : initiallyKnownNodes) {
			this.probs.put(i, prob);
		}
	}

	/**
	 * Updates meeting probability for the given node index.
	 *
 P(b) = P(b)_old + alpha
	 * Normalize{P}

	 * I.e., The probability of the given node index is increased by one and
	 * then all the probabilities are normalized so that their sum equals to 1.
	 * @param index The node index to update the probability for
	 */
	public void updateMeetingProbFor(Integer index) {
        Map.Entry<Integer, Double> smallestEntry = null;
        double smallestValue = Double.MAX_VALUE;

		this.lastUpdateTime = SimClock.getTime();

		if (probs.size() == 0) { // first entry
			probs.put(index, 1.0);
			return;
		}

		double newValue = getProbFor(index) + alpha;
		probs.put(index, newValue);

		/* now the sum of all entries is 1+alpha;
		 * normalize to one by dividing all the entries by 1+alpha */
		for (Map.Entry<Integer, Double> entry : probs.entrySet()) {
			entry.setValue(entry.getValue() / (1+alpha));
            if (entry.getValue() < smallestValue) {
                smallestEntry = entry;
                smallestValue = entry.getValue();
            }

		}

        if (probs.size() >= maxSetSize) {
            if (DEBUG) core.Debug.p("Probsize: " + probs.size() + " dropping " +
					probs.remove(smallestEntry.getKey()));
        }
	}

	public void updateMeetingProbFor(Integer index, double iet)	{
		probs.put(index, iet);
	}

	/**
	 * Returns the current delivery probability value for the given node index
	 * @param index The index of the node to look the P for
	 * @return the current delivery probability value
	 */
	public double getProbFor(Integer index) {
		if (probs.containsKey(index)) {
			return probs.get(index);
		}
		else {
			/* the node with the given index has not been met */
			return 0.0;
		}
	}

	/**
	 * Returns a reference to the probability map of this probability set
	 * @return a reference to the probability map of this probability set
	 */
	public Map<Integer, Double> getAllProbs() {
		return this.probs;
	}

	/**
	 * Returns the time when this probability set was last updated
	 * @return the time when this probability set was last updated
	 */
	public double getLastUpdateTime() {
		return this.lastUpdateTime;
	}

	/**
	 * Enables changing the alpha parameter dynamically
	 */
	public void setAlpha(double alpha) {
		this.alpha = alpha;
	}

	/**
	 * Returns a deep copy of the probability set
	 * @return a deep copy of the probability set
	 */
	public MeetingProbabilitySet replicate() {
		MeetingProbabilitySet replica = new MeetingProbabilitySet(
				this.maxSetSize, alpha);

		// do a deep copy
		for (Map.Entry<Integer, Double> e : probs.entrySet()) {
			replica.probs.put(e.getKey(), e.getValue().doubleValue());
		}

		replica.lastUpdateTime = this.lastUpdateTime;
		return replica;
	}

	/**
	 * Returns a String presentation of the probabilities
	 * @return a String presentation of the probabilities
	 */
    @Override
	public String toString() {
		return "probs: " +	this.probs.toString();
	}
}

Answer: public void changedConnection(Connection con) {

<think>
The file ends with an @Override annotation, which in Java precedes a method definition. In the MaxProp router implementations, the next overridden method after initMeetings is the changedConnection handler. Therefore the next line should be the method signature for changedConnection.
</think>
public void changedConnection(Connection con) {


Input:
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.daominh.quickmem.adapter.group.ClassAdapter;
import com.daominh.quickmem.adapter.folder.FolderAdapter;
import com.daominh.quickmem.adapter.flashcard.SetsAdapter;
import com.daominh.quickmem.data.dao.FlashCardDAO;
import com.daominh.quickmem.data.dao.FolderDAO;
import com.daominh.quickmem.data.dao.GroupDAO;
import com.daominh.quickmem.data.model.FlashCard;
import com.daominh.quickmem.data.model.Folder;
import com.daominh.quickmem.data.model.Group;
import com.daominh.quickmem.databinding.FragmentHomeBinding;
import com.daominh.quickmem.preferen.UserSharePreferences;
import com.daominh.quickmem.ui.activities.create.CreateSetActivity;
import com.daominh.quickmem.ui.activities.search.ViewSearchActivity;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;

Context:
app/src/main/java/com/daominh/quickmem/ui/fragments/home/HomeFragment.java
package com.daominh.quickmem.ui.fragments.home;

public class HomeFragment extends Fragment {
    private FragmentHomeBinding binding;
    private UserSharePreferences userSharePreferences;
    private SetsAdapter setsAdapter;
    private FolderAdapter folderAdapter;
    private ClassAdapter classAdapter;
    private ArrayList<FlashCard> flashCards;
    private ArrayList<Folder> folders;
    private ArrayList<Group> classes;
    private FlashCardDAO flashCardDAO;
    private FolderDAO folderDAO;
    private GroupDAO groupDAO;
    private String idUser;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        userSharePreferences = new UserSharePreferences(requireActivity());
        idUser = userSharePreferences.getId();
        flashCardDAO = new FlashCardDAO(requireActivity());
        folderDAO = new FolderDAO(requireActivity());
        groupDAO = new GroupDAO(requireActivity());
    }

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        userSharePreferences = new UserSharePreferences(requireActivity());
        idUser = userSharePreferences.getId();

        setupFlashCards();
        setupFolders();
        setupClasses();
        setupVisibility();
        setupSwipeRefreshLayout();
        setupSearchBar();
        setupCreateSetsButton();

        binding.swipeRefreshLayout.setOnRefreshListener(() -> {
            refreshData();
            binding.swipeRefreshLayout.setRefreshing(false);
            Toast.makeText(requireActivity(), "Refreshed", Toast.LENGTH_SHORT).show();
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void setupFlashCards() {
        flashCards = flashCardDAO.getAllFlashCardByUserId(idUser);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false);
        binding.setsRv.setLayoutManager(linearLayoutManager);
        setsAdapter = new SetsAdapter(requireActivity(), flashCards, false);
        binding.setsRv.setAdapter(setsAdapter);
        setsAdapter.notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void setupFolders() {
        folders = folderDAO.getAllFolderByUserId(idUser);
        folderAdapter = new FolderAdapter(requireActivity(), folders);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false);
        binding.foldersRv.setLayoutManager(linearLayoutManager1);
        binding.foldersRv.setAdapter(folderAdapter);
        folderAdapter.notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void setupClasses() {
        classes = groupDAO.getClassesOwnedByUser(idUser);
        classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser));
        classAdapter = new ClassAdapter(requireActivity(), classes);
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false);
        binding.classesRv.setLayoutManager(linearLayoutManager2);
        binding.classesRv.setAdapter(classAdapter);
        classAdapter.notifyDataSetChanged();
    }

    private void setupVisibility() {
        if (flashCards.isEmpty()) {
            binding.setsCl.setVisibility(View.GONE);
        } else {
            binding.setsCl.setVisibility(View.VISIBLE);
        }
        if (folders.isEmpty()) {
            binding.folderCl.setVisibility(View.GONE);
        } else {
            binding.folderCl.setVisibility(View.VISIBLE);
        }
        if (classes.isEmpty()) {
            binding.classCl.setVisibility(View.GONE);
        } else {
            binding.classCl.setVisibility(View.VISIBLE);
        }
    }

    private void setupSwipeRefreshLayout() {
        binding.swipeRefreshLayout.setOnRefreshListener(() -> {
            refreshData();
            binding.swipeRefreshLayout.setRefreshing(false);
        });
    }

    private void setupSearchBar() {
        binding.searchBar.setOnClickListener(v -> {

app/src/main/java/com/daominh/quickmem/adapter/flashcard/SetsAdapter.java
public class SetsAdapter extends RecyclerView.Adapter<SetsAdapter.SetsViewHolder> {

    private final Context context;
    private final ArrayList<FlashCard> sets;
    private final Boolean isLibrary;

    public SetsAdapter(Context context, ArrayList<FlashCard> sets, Boolean isLibrary) {
        this.context = context;
        this.sets = sets;
        this.isLibrary = isLibrary;
    }

    @NonNull
    @NotNull
    @Override
    public SetsAdapter.SetsViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        ItemSetBinding binding = ItemSetBinding.inflate(inflater, parent, false);
        return new SetsViewHolder(binding.getRoot());
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull @NotNull SetsAdapter.SetsViewHolder holder, int position) {
        if (isLibrary){
            //set weight of card
            ViewGroup.LayoutParams params = holder.binding.setCv.getLayoutParams();
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;

        }
        FlashCard set = sets.get(position);
        UserSharePreferences userSharePreferences = new UserSharePreferences(context);
        CardDAO cardDAO = new CardDAO(context);
        int count = cardDAO.countCardByFlashCardId(set.getId());
        String avatar = userSharePreferences.getAvatar();
        String userNames = userSharePreferences.getUserName();

        holder.binding.setNameTv.setText(set.getName());
        holder.binding.termCountTv.setText(count + " terms");
        holder.binding.userNameTv.setText(userNames);
        Picasso.get().load(avatar).into(holder.binding.avatarIv);
        holder.binding.createdDateTv.setText(set.getCreated_at());

        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(context, ViewSetActivity.class);
            intent.putExtra("id", set.getId());

            context.startActivity(intent);
        });

    }

    @Override
    public int getItemCount() {
        return sets.size();
    }

    public static class SetsViewHolder extends RecyclerView.ViewHolder {
        private final ItemSetBinding binding;

        public SetsViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            binding = ItemSetBinding.bind(itemView);
        }
    }

}

app/src/main/java/com/daominh/quickmem/ui/activities/create/CreateSetActivity.java
public class CreateSetActivity extends AppCompatActivity {
    private CardAdapter cardAdapter;
    private ArrayList<Card> cards;
    private ActivityCreateSetBinding binding;
    private final String id = genUUID();

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCreateSetBinding.inflate(getLayoutInflater());
        final View view = binding.getRoot();
        setContentView(view);

        setupToolbar();
        setupSubjectEditText();
        setupDescriptionTextView();
        setupCardsList();
        setupCardAdapter();
        setupAddFab();
        setupItemTouchHelper();
    }

    private void setupToolbar() {
        setSupportActionBar(binding.toolbar);
        binding.toolbar.setNavigationOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());
    }

    private void setupSubjectEditText() {
        if (binding.subjectEt.getText().toString().isEmpty()) {
            binding.subjectEt.requestFocus();
        }
    }

    private void setupDescriptionTextView() {
        binding.descriptionTv.setOnClickListener(v -> {
            if (binding.descriptionTil.getVisibility() == View.GONE) {
                binding.descriptionTil.setVisibility(View.VISIBLE);
            } else {
                binding.descriptionTil.setVisibility(View.GONE);
            }
        });
    }

    private void setupCardsList() {
        //create list two set
        cards = new ArrayList<>();
        cards.add(new Card());
        cards.add(new Card());
        updateTotalCards();
    }

    private void updateTotalCards() {
        binding.totalCardsTv.setText(String.format("Total Cards: %s", cards.size()));
    }

    @SuppressLint("NotifyDataSetChanged")
    private void setupCardAdapter() {
        cardAdapter = new CardAdapter(this, cards);
        binding.cardsLv.setAdapter(cardAdapter);
        binding.cardsLv.setLayoutManager(new LinearLayoutManager(this));
        binding.cardsLv.setHasFixedSize(true);
        cardAdapter.notifyDataSetChanged();

    }

    private void setupAddFab() {
        binding.addFab.setOnClickListener(v -> {
            if (!checkTwoCardsEmpty()) {

                Card newCard = new Card();
                cards.add(newCard);
                //scroll to last item
                binding.cardsLv.smoothScrollToPosition(cards.size() - 1);
                //notify adapter
                cardAdapter.notifyItemInserted(cards.size() - 1);
                updateTotalCards();

            } else {
                Toast.makeText(this, "Please enter front and back", Toast.LENGTH_SHORT).show();
            }

        });
    }

    private void setupItemTouchHelper() {
        ItemTouchHelper.SimpleCallback callback = createItemTouchHelperCallback();
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(binding.cardsLv);
    }

    private ItemTouchHelper.SimpleCallback createItemTouchHelperCallback() {
        return new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NotNull RecyclerView.ViewHolder viewHolder, int direction) {
                handleOnSwiped(viewHolder);
            }

            @Override
            public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                handleOnChildDraw(c, viewHolder, dX);
            }
        };
    }

    private void handleOnSwiped(RecyclerView.ViewHolder viewHolder) {
        int position = viewHolder.getBindingAdapterPosition();

        // Backup of removed item for undo purpose
        Card deletedItem = cards.get(position);

        // Removing item from recycler view
        cards.remove(position);
        updateTotalCards();
        cardAdapter.notifyItemRemoved(position);

        // Showing Snack bar with an Undo option
        Snackbar snackbar = Snackbar.make(binding.getRoot(), "Item was removed from the list.", Snackbar.LENGTH_LONG);
        snackbar.setAction("UNDO", view -> {

            // Check if the position is valid before adding the item back
            if (position >= 0 && position <= cards.size()) {
                cards.add(position, deletedItem);
                cardAdapter.notifyItemInserted(position);
                updateTotalCards();
            } else {
                // If the position isn't valid, show a message or handle the error appropriately
                Toast.makeText(getApplicationContext(), "Error restoring item", Toast.LENGTH_LONG).show();
            }
        });
        snackbar.setActionTextColor(Color.YELLOW);
        snackbar.show();
    }

    private void handleOnChildDraw(@NotNull Canvas c, @NotNull RecyclerView.ViewHolder viewHolder, float dX) {
        Drawable icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_delete);
        View itemView = viewHolder.itemView;
        assert icon != null;
        int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconBottom = iconTop + icon.getIntrinsicHeight();

        if (dX < 0) { // Swiping to the left
            int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
            int iconRight = itemView.getRight() - iconMargin;
            icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);

            final ColorDrawable background = new ColorDrawable(Color.WHITE);
            background.setBounds(itemView.getRight() + ((int) dX), itemView.getTop(), itemView.getRight(), itemView.getBottom());
            background.draw(c);
        } else { // No swipe
            icon.setBounds(0, 0, 0, 0);
        }

        icon.draw(c);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_create_set, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.done) {
            saveChanges();
            return true;
        }
        return super.onOptionsItemSelected(item);

    }

    private void saveChanges() {
        String subject = binding.subjectEt.getText().toString();
        String description = binding.descriptionEt.getText().toString();

        if (subject.isEmpty()) {
            binding.subjectTil.setError("Please enter subject");
            binding.subjectEt.requestFocus();
            return;
        } else {
            binding.subjectTil.setError(null);
        }

        if (!saveAllCards()) {
            return;
        }

        if (!saveFlashCard(subject, description)) {
            Toast.makeText(this, "Insert flashcard failed", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(this, ViewSetActivity.class);
        intent.putExtra("id", id);
        startActivity(intent);
        finish();
    }

    private boolean saveAllCards() {
        for (Card card : cards) {
            if (!saveCard(card)) {
                return false;
            }
        }
        return true;
    }

    private boolean saveCard(Card card) {
        String front = card.getFront();
        String back = card.getBack();

        if (front == null || front.isEmpty()) {
            binding.cardsLv.requestFocus();
            Toast.makeText(this, "Please enter front", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (back == null || back.isEmpty()) {
            binding.cardsLv.requestFocus();
            Toast.makeText(this, "Please enter back", Toast.LENGTH_SHORT).show();
            return false;
        }

        CardDAO cardDAO = new CardDAO(this);
        card.setId(genUUID());
        card.setFront(front);
        card.setBack(back);
        card.setStatus(0);
        card.setIsLearned(0);
        card.setFlashcard_id(id);
        card.setCreated_at(getCurrentDate());
        card.setUpdated_at(getCurrentDate());
        if (cardDAO.insertCard(card) <= 0) {
            Toast.makeText(this, "Insert card failed" + id, Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private boolean saveFlashCard(String subject, String description) {
        FlashCardDAO flashCardDAO = new FlashCardDAO(this);
        FlashCard flashCard = new FlashCard();
        flashCard.setName(subject);
        flashCard.setDescription(description);
        UserSharePreferences userSharePreferences = new UserSharePreferences(this);
        flashCard.setUser_id(userSharePreferences.getId());
        flashCard.setCreated_at(getCurrentDate());
        flashCard.setUpdated_at(getCurrentDate());
        flashCard.setId(id);
        binding.privateSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                Toast.makeText(this, "Public", Toast.LENGTH_SHORT).show();
                flashCard.setIs_public(1);
            } else {
                Toast.makeText(this, "Private", Toast.LENGTH_SHORT).show();
                flashCard.setIs_public(0);
            }
        });

        return flashCardDAO.insertFlashCard(flashCard) > 0;
    }

    private String getCurrentDate() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            return getCurrentDateNewApi();
        } else {
            return getCurrentDateOldApi();
        }
    }

    public boolean checkTwoCardsEmpty() {
        // check if 2 cards are empty return true
        int emptyCount = 0;
        for (Card card : cards) {
            if (card.getFront() == null || card.getFront().isEmpty() || card.getBack() == null || card.getBack().isEmpty()) {
                emptyCount++;
                if (emptyCount == 2) {
                    return true;
                }
            }
        }
        return false;
    }

    private String genUUID() {
        return java.util.UUID.randomUUID().toString();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private String getCurrentDateNewApi() {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        return currentDate.format(formatter);
    }

    private String getCurrentDateOldApi() {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        return sdf.format(new Date());
    }
}

Answer: Intent intent = new Intent(requireActivity(), ViewSearchActivity.class);

<think>
In HomeFragment, the setupSearchBar method opens a click listener on the search bar. The next logical statement is to create an Intent to launch the search activity (ViewSearchActivity) using the fragment's activity context. Therefore the next line should instantiate the Intent.
</think>
Intent intent = new Intent(requireActivity(), ViewSearchActivity.class);


Input:
import itertools
import logging
import numpy as np
import operator
import pickle
import torch
import torch.utils.data as torchdata
from collections import OrderedDict, defaultdict
from typing import Any, Callable, Dict, List, Optional, Union
from tabulate import tabulate
from termcolor import colored
from ..config import configurable
from ..structures import BoxMode
from ..utils.comm import get_world_size
from ..utils.env import seed_all_rng
from ..utils.file_io import PathManager
from ..utils.logger import _log_api_usage, log_first_n
from .catalog import DatasetCatalog, MetadataCatalog
from .common import AspectRatioGroupedDataset, DatasetFromList, MapDataset, ToIterableDataset
from .dataset_mapper import DatasetMapper
from .detection_utils import check_metadata_consistency
from .samplers import (
    InferenceSampler,
    RandomSubsetTrainingSampler,
    RepeatFactorTrainingSampler,
    TrainingSampler,
)

Context:
nativedancer/third_part/detectron2/data/build.py
        sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces
            indices to be applied on ``dataset``.
            If ``dataset`` is map-style, the default sampler is a :class:`TrainingSampler`,
            which coordinates an infinite random shuffle sequence across all workers.
            Sampler must be None if ``dataset`` is iterable.
        total_batch_size (int): total batch size across all workers.
        aspect_ratio_grouping (bool): whether to group images with similar
            aspect ratio for efficiency. When enabled, it requires each
            element in dataset be a dict with keys "width" and "height".
        num_workers (int): number of parallel data loading workers
        collate_fn: a function that determines how to do batching, same as the argument of
            `torch.utils.data.DataLoader`. Defaults to do no collation and return a list of
            data. No collation is OK for small batch size and simple data structures.
            If your batch size is large and each sample contains too many small tensors,
            it's more efficient to collate them in data loader.

    Returns:
        torch.utils.data.DataLoader:
            a dataloader. Each output from it is a ``list[mapped_element]`` of length
            ``total_batch_size / num_workers``, where ``mapped_element`` is produced
            by the ``mapper``.
    """
    if isinstance(dataset, list):
        dataset = DatasetFromList(dataset, copy=False)
    if mapper is not None:
        dataset = MapDataset(dataset, mapper)

    if isinstance(dataset, torchdata.IterableDataset):
        assert sampler is None, "sampler must be None if dataset is IterableDataset"
    else:
        if sampler is None:
            sampler = TrainingSampler(len(dataset))
        assert isinstance(sampler, torchdata.Sampler), f"Expect a Sampler but got {type(sampler)}"
    return build_batch_data_loader(
        dataset,
        sampler,
        total_batch_size,
        aspect_ratio_grouping=aspect_ratio_grouping,
        num_workers=num_workers,
        collate_fn=collate_fn,
        **kwargs
    )

def _test_loader_from_config(cfg, dataset_name, mapper=None):
    """
    Uses the given `dataset_name` argument (instead of the names in cfg), because the
    standard practice is to evaluate each test set individually (not combining them).
    """
    if isinstance(dataset_name, str):
        dataset_name = [dataset_name]

    dataset = get_detection_dataset_dicts(
        dataset_name,
        filter_empty=False,
        proposal_files=[
            cfg.DATASETS.PROPOSAL_FILES_TEST[list(cfg.DATASETS.TEST).index(x)] for x in dataset_name
        ]
        if cfg.MODEL.LOAD_PROPOSALS
        else None,
    )
    if mapper is None:
        mapper = DatasetMapper(cfg, False)
    return {
        "dataset": dataset,
        "mapper": mapper,
        "num_workers": cfg.DATALOADER.NUM_WORKERS,
        "sampler": InferenceSampler(len(dataset))
        if not isinstance(dataset, torchdata.IterableDataset)
        else None,
    }

@configurable(from_config=_test_loader_from_config)
def build_detection_test_loader(
    dataset: Union[List[Any], torchdata.Dataset],
    *,
    mapper: Callable[[Dict[str, Any]], Any],
    sampler: Optional[torchdata.Sampler] = None,
    batch_size: int = 1,
    num_workers: int = 0,
    collate_fn: Optional[Callable[[List[Any]], Any]] = None,
) -> torchdata.DataLoader:
    """
    Similar to `build_detection_train_loader`, with default batch size = 1,
    and sampler = :class:`InferenceSampler`. This sampler coordinates all workers
    to produce the exact set of all samples.

    Args:
        dataset: a list of dataset dicts,
            or a pytorch dataset (either map-style or iterable). They can be obtained
            by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`.
        mapper: a callable which takes a sample (dict) from dataset
           and returns the format to be consumed by the model.
           When using cfg, the default choice is ``DatasetMapper(cfg, is_train=False)``.
        sampler: a sampler that produces
            indices to be applied on ``dataset``. Default to :class:`InferenceSampler`,
            which splits the dataset across all workers. Sampler must be None
            if `dataset` is iterable.
        batch_size: the batch size of the data loader to be created.
            Default to 1 image per worker since this is the standard when reporting
            inference time in papers.
        num_workers: number of parallel data loading workers
        collate_fn: same as the argument of `torch.utils.data.DataLoader`.
            Defaults to do no collation and return a list of data.

    Returns:
        DataLoader: a torch DataLoader, that loads the given detection
        dataset, with test-time transformation and batching.

    Examples:
    ::
        data_loader = build_detection_test_loader(
            DatasetRegistry.get("my_test"),
            mapper=DatasetMapper(...))

        # or, instantiate with a CfgNode:
        data_loader = build_detection_test_loader(cfg, "my_test")
    """
    if isinstance(dataset, list):

nativedancer/third_part/detectron2/data/samplers/distributed_sampler.py
class TrainingSampler(Sampler):
    """
    In training, we only care about the "infinite stream" of training data.
    So this sampler produces an infinite stream of indices and
    all workers cooperate to correctly shuffle the indices and sample different indices.

    The samplers in each worker effectively produces `indices[worker_id::num_workers]`
    where `indices` is an infinite stream of indices consisting of
    `shuffle(range(size)) + shuffle(range(size)) + ...` (if shuffle is True)
    or `range(size) + range(size) + ...` (if shuffle is False)

    Note that this sampler does not shard based on pytorch DataLoader worker id.
    A sampler passed to pytorch DataLoader is used only with map-style dataset
    and will not be executed inside workers.
    But if this sampler is used in a way that it gets execute inside a dataloader
    worker, then extra work needs to be done to shard its outputs based on worker id.
    This is required so that workers don't produce identical data.
    :class:`ToIterableDataset` implements this logic.
    This note is true for all samplers in detectron2.
    """

    def __init__(self, size: int, shuffle: bool = True, seed: Optional[int] = None):
        """
        Args:
            size (int): the total number of data of the underlying dataset to sample from
            shuffle (bool): whether to shuffle the indices or not
            seed (int): the initial seed of the shuffle. Must be the same
                across all workers. If None, will use a random seed shared
                among workers (require synchronization among all workers).
        """
        if not isinstance(size, int):
            raise TypeError(f"TrainingSampler(size=) expects an int. Got type {type(size)}.")
        if size <= 0:
            raise ValueError(f"TrainingSampler(size=) expects a positive int. Got {size}.")
        self._size = size
        self._shuffle = shuffle
        if seed is None:
            seed = comm.shared_random_seed()
        self._seed = int(seed)

        self._rank = comm.get_rank()
        self._world_size = comm.get_world_size()

    def __iter__(self):
        start = self._rank
        yield from itertools.islice(self._infinite_indices(), start, None, self._world_size)

    def _infinite_indices(self):
        g = torch.Generator()
        g.manual_seed(self._seed)
        while True:
            if self._shuffle:
                yield from torch.randperm(self._size, generator=g).tolist()
            else:
                yield from torch.arange(self._size).tolist()

Answer: dataset = DatasetFromList(dataset, copy=False)

<think>
In build_detection_test_loader, after checking if the provided dataset is a list, the code must convert that list into a Detectron2 Dataset object. The standard utility for this is DatasetFromList, used with copy=False to avoid unnecessary copying. Therefore the next line should perform this conversion.
</think>
dataset = DatasetFromList(dataset, copy=False)