file_id
stringlengths
5
9
content
stringlengths
24
16.1k
repo
stringlengths
8
84
path
stringlengths
7
167
token_length
int64
18
3.48k
original_comment
stringlengths
5
2.57k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
11
16.1k
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
14
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
1.74k
file-tokens-bigcode/starcoder2-7b
int64
18
3.48k
comment-tokens-bigcode/starcoder2-7b
int64
2
2.11k
file-tokens-google/codegemma-7b
int64
14
3.57k
comment-tokens-google/codegemma-7b
int64
2
1.75k
file-tokens-ibm-granite/granite-8b-code-base
int64
18
3.48k
comment-tokens-ibm-granite/granite-8b-code-base
int64
2
2.11k
file-tokens-meta-llama/CodeLlama-7b-hf
int64
31
3.93k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
2.71k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
24607_9
class Solution { private Set<Integer> cols = new HashSet<>(); private Set<Integer> pia = new HashSet<>(); private Set<Integer> na = new HashSet<>(); public List<List<String>> solveNQueens(int n) { List<List<String>> ans = new ArrayList<>(); if (n < 1) { return new ArrayList<>(); } dfs(0, n, new ArrayList<>(), ans); return ans; } private void dfs(int row, int n, List<String> res, List<List<String>> ans) { // row 相当于层级,第几层 // n 表示是几皇后场景 // 存放计算过程中产生的结果 // ans 汇总结果 // 终结条件 if (row == n) { // 这里不能直接add res 因为res里面存放的是整个中间计算过程的数据,必须要新建一个 // ans.add(res); ans.add(new ArrayList<>(res)); return; } // 如下为处理过程 // 尝试在row这一行的每一列放一下看看 for (int i = 0; i < n; i++) { if (cols.contains(i) || pia.contains(row + i) || na.contains(row - i)) { // 在攻击范围内不能放置皇后 continue; } // 尝试放入棋子在位置(row,i) char[] chars = new char[n]; Arrays.fill(chars, '.'); chars[i] = 'Q'; res.add(new String(chars)); // 记录攻击范围 cols.add(i); pia.add(row + i); na.add(row - i); // 进入下一层 dfs(row + 1, n, res, ans); // 清理状态 // res 的状态不能忘记,切记切记!!! res.remove(res.size() - 1); cols.remove(i); pia.remove(row + i); na.remove(row - i); } } }
algorithm007-class01/algorithm007-class01
Week_03/G20200343040317/LeetCode_51_0317.java
492
// 在攻击范围内不能放置皇后
line_comment
zh-cn
class Solution { private Set<Integer> cols = new HashSet<>(); private Set<Integer> pia = new HashSet<>(); private Set<Integer> na = new HashSet<>(); public List<List<String>> solveNQueens(int n) { List<List<String>> ans = new ArrayList<>(); if (n < 1) { return new ArrayList<>(); } dfs(0, n, new ArrayList<>(), ans); return ans; } private void dfs(int row, int n, List<String> res, List<List<String>> ans) { // row 相当于层级,第几层 // n 表示是几皇后场景 // 存放计算过程中产生的结果 // ans 汇总结果 // 终结条件 if (row == n) { // 这里不能直接add res 因为res里面存放的是整个中间计算过程的数据,必须要新建一个 // ans.add(res); ans.add(new ArrayList<>(res)); return; } // 如下为处理过程 // 尝试在row这一行的每一列放一下看看 for (int i = 0; i < n; i++) { if (cols.contains(i) || pia.contains(row + i) || na.contains(row - i)) { // 在攻 <SUF> continue; } // 尝试放入棋子在位置(row,i) char[] chars = new char[n]; Arrays.fill(chars, '.'); chars[i] = 'Q'; res.add(new String(chars)); // 记录攻击范围 cols.add(i); pia.add(row + i); na.add(row - i); // 进入下一层 dfs(row + 1, n, res, ans); // 清理状态 // res 的状态不能忘记,切记切记!!! res.remove(res.size() - 1); cols.remove(i); pia.remove(row + i); na.remove(row - i); } } }
false
446
7
492
12
510
7
492
12
636
20
false
false
false
false
false
true
54544_31
//给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, //ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 // // 说明:你不能倾斜容器,且 n 的值至少为 2。 // // // // // // 图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 // // // // 示例: // // 输入:[1,8,6,2,5,4,8,3,7] //输出:49 // Related Topics 数组 双指针 //leetcode submit region begin(Prohibit modification and deletion) /* * 查看解答前的思考: * 1. 最笨的方法,暴力计算每两条“高度线”之间的面积 * 根据“木桶理论”,先将最低的高度比较出来 * 然后S=(低)*|(i-j)| * 由化简公式得出只需要控制两个下标即可。 * a.将结果存入新数组后排序后返回,sort()默认升序但其返回值为void,需要手动写排序 * 而使用(j=i+1)时,开辟的用于存放结果的新数组长度应为((height.length*(height.length-1)/2)+1) * +1是为了防止整数除以2后出现的问题 * b.每次出来两个结果后仅保留较大的那个,最后返回 * 选b * 另外还要注意,j==i,因为这会导致公式与实际情况不符 * 暴力双循环遍历(内循环j=i)肯定是有重复的,使用(j=i+1)能够避免重复计算,但时间复杂度的量级没有改变,为O(n^2) * 2.短时间内没有想到其他好的方法 * */ /* * 查看解答后的思考: * 1. 哈哈,超哥题到了j=i+1的遍历优化 * 另外,学习超哥的饭吗,对方法一进行了优化 * a.直接使用Math.min()得出较小值(自己都用了Math.abs()了,竟然不用min()...) * b.对于循环的变量,直接在循环中进行声明,能使得代码简洁美观 * c.内循环使用j=i+1;外循环i的限制可以使用i<height.length-1,因为j是i后面一个 * i“最后”到height.length-2即可遍历全部 * 2. 方法二 * “从两边想中间收拢”---即,由于公式S=(低)*|(i-j)|可得,我们可以先将宽度尽可能得固定到最大 * 然后移动原来两端中较小的一条边 * 最后有两种比较法 * a.直接计算面积,取更大的存入maxS中 * b.在收缩时将每次收缩后的(低收)与原来最两端的(低原)进行比较,(低收)<(低原) * 那么不用计算便可得知这次收缩后的面积小,比最两端时的要小。 * 如果高,那么比较、计算。---###这里的比较是有窍门的---“谁更小谁就挪” * 选择a.更为简洁 * 由于没有嵌套,因此该犯法时间复杂度为O(n) * ###方法二中的循环写法要着重掌握 * */ class Solution11 { public int maxArea(int[] height) { /* * 方法一*/ // int i,j=0; // int S,maxS=0; // // for (i=0; i<height.length; i++){ // //使用j=i+1,减少次数 // for (j=i+1; j<height.length; j++){ // if (height[j]>height[i]){ // S=height[i]*Math.abs(i-j); // if (S>maxS){ // maxS=S; // } // }else{ // S=height[j]*Math.abs(i-j); // if (S>maxS){ // maxS=S; // } // } // } // } // return maxS; /* * 耗时757ms左右(5%),使用内存41.3M(5%),主要原因是双循环中肯定有重复的*/ /* * 优化方法一*/ // int S,maxS=0; // // //优化细节c:j=i+1->i<height.length-1 // for (int i=0; i<height.length-1; i++) // // //使用j=i+1,减少次数,优化细节b:循环变量内部声明 // for (int j=i+1; j<height.length; j++){ // // //优化细节a:Math.min() // S=Math.min(height[i],height[j])*Math.abs(i-j); // if (S>maxS){ // maxS=S; // } // } // } // return maxS; /* * 耗时487ms左右(10%),使用内存41.6M(5%)*/ /* * 方法二*/ int maxS=0; //从两端开始收缩,互相限制,嵌套内更新循环变量 for(int i=0, j=height.length-1; i<j;){ //那边小就收缩哪边 int low = height[i]<height[j] ? height[i++]:height[j--]; //###为什么这里要加1?(j-i+1), int S = (j-i+1)*low; maxS = Math.max(maxS, S); } return maxS; /* * 耗时3ms左右(91%),使用内存41.5M(5%)*/ } } //leetcode submit region end(Prohibit modification and deletion)
algorithm007-class02/algorithm007-class02
Week_01/G20200343040312/LeetCode_11_0312.java
1,647
// //使用j=i+1,减少次数,优化细节b:循环变量内部声明
line_comment
zh-cn
//给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, //ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 // // 说明:你不能倾斜容器,且 n 的值至少为 2。 // // // // // // 图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 // // // // 示例: // // 输入:[1,8,6,2,5,4,8,3,7] //输出:49 // Related Topics 数组 双指针 //leetcode submit region begin(Prohibit modification and deletion) /* * 查看解答前的思考: * 1. 最笨的方法,暴力计算每两条“高度线”之间的面积 * 根据“木桶理论”,先将最低的高度比较出来 * 然后S=(低)*|(i-j)| * 由化简公式得出只需要控制两个下标即可。 * a.将结果存入新数组后排序后返回,sort()默认升序但其返回值为void,需要手动写排序 * 而使用(j=i+1)时,开辟的用于存放结果的新数组长度应为((height.length*(height.length-1)/2)+1) * +1是为了防止整数除以2后出现的问题 * b.每次出来两个结果后仅保留较大的那个,最后返回 * 选b * 另外还要注意,j==i,因为这会导致公式与实际情况不符 * 暴力双循环遍历(内循环j=i)肯定是有重复的,使用(j=i+1)能够避免重复计算,但时间复杂度的量级没有改变,为O(n^2) * 2.短时间内没有想到其他好的方法 * */ /* * 查看解答后的思考: * 1. 哈哈,超哥题到了j=i+1的遍历优化 * 另外,学习超哥的饭吗,对方法一进行了优化 * a.直接使用Math.min()得出较小值(自己都用了Math.abs()了,竟然不用min()...) * b.对于循环的变量,直接在循环中进行声明,能使得代码简洁美观 * c.内循环使用j=i+1;外循环i的限制可以使用i<height.length-1,因为j是i后面一个 * i“最后”到height.length-2即可遍历全部 * 2. 方法二 * “从两边想中间收拢”---即,由于公式S=(低)*|(i-j)|可得,我们可以先将宽度尽可能得固定到最大 * 然后移动原来两端中较小的一条边 * 最后有两种比较法 * a.直接计算面积,取更大的存入maxS中 * b.在收缩时将每次收缩后的(低收)与原来最两端的(低原)进行比较,(低收)<(低原) * 那么不用计算便可得知这次收缩后的面积小,比最两端时的要小。 * 如果高,那么比较、计算。---###这里的比较是有窍门的---“谁更小谁就挪” * 选择a.更为简洁 * 由于没有嵌套,因此该犯法时间复杂度为O(n) * ###方法二中的循环写法要着重掌握 * */ class Solution11 { public int maxArea(int[] height) { /* * 方法一*/ // int i,j=0; // int S,maxS=0; // // for (i=0; i<height.length; i++){ // //使用j=i+1,减少次数 // for (j=i+1; j<height.length; j++){ // if (height[j]>height[i]){ // S=height[i]*Math.abs(i-j); // if (S>maxS){ // maxS=S; // } // }else{ // S=height[j]*Math.abs(i-j); // if (S>maxS){ // maxS=S; // } // } // } // } // return maxS; /* * 耗时757ms左右(5%),使用内存41.3M(5%),主要原因是双循环中肯定有重复的*/ /* * 优化方法一*/ // int S,maxS=0; // // //优化细节c:j=i+1->i<height.length-1 // for (int i=0; i<height.length-1; i++) // // //使用 <SUF> // for (int j=i+1; j<height.length; j++){ // // //优化细节a:Math.min() // S=Math.min(height[i],height[j])*Math.abs(i-j); // if (S>maxS){ // maxS=S; // } // } // } // return maxS; /* * 耗时487ms左右(10%),使用内存41.6M(5%)*/ /* * 方法二*/ int maxS=0; //从两端开始收缩,互相限制,嵌套内更新循环变量 for(int i=0, j=height.length-1; i<j;){ //那边小就收缩哪边 int low = height[i]<height[j] ? height[i++]:height[j--]; //###为什么这里要加1?(j-i+1), int S = (j-i+1)*low; maxS = Math.max(maxS, S); } return maxS; /* * 耗时3ms左右(91%),使用内存41.5M(5%)*/ } } //leetcode submit region end(Prohibit modification and deletion)
false
1,421
20
1,645
22
1,545
21
1,647
23
2,217
42
false
false
false
false
false
true
36379_7
package class073; // 有依赖的背包(模版) // 物品分为两大类:主件和附件 // 主件的购买没有限制,钱够就可以;附件的购买有限制,该附件所归属的主件先购买,才能购买这个附件 // 例如,若想买打印机或扫描仪这样的附件,必须先购买电脑这个主件 // 以下是一些主件及其附件的展示: // 电脑:打印机,扫描仪 | 书柜:图书 | 书桌:台灯,文具 | 工作椅:无附件 // 每个主件最多有2个附件,并且附件不会再有附件,主件购买后,怎么去选择归属附件完全随意,钱够就可以 // 所有的物品编号都在1~m之间,每个物品有三个信息:价格v、重要度p、归属q // 价格就是花费,价格 * 重要度 就是收益,归属就是该商品是依附于哪个编号的主件 // 比如一件商品信息为[300,2,6],花费300,收益600,该商品是6号主件商品的附件 // 再比如一件商品信息[100,4,0],花费100,收益400,该商品自身是主件(q==0) // 给定m件商品的信息,给定总钱数n,返回在不违反购买规则的情况下最大的收益 // 测试链接 : https://www.luogu.com.cn/problem/P1064 // 测试链接 : https://www.nowcoder.com/practice/f9c6f980eeec43ef85be20755ddbeaf4 // 请同学们务必参考如下代码中关于输入、输出的处理 // 这是输入输出处理效率很高的写法 // 提交以下的所有代码,并把主类名改成"Main",可以直接通过 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class Code05_DependentKnapsack { public static int MAXN = 33001; public static int MAXM = 61; public static int[] cost = new int[MAXM]; public static int[] val = new int[MAXM]; public static boolean[] king = new boolean[MAXM]; public static int[] fans = new int[MAXM]; public static int[][] follows = new int[MAXM][2]; public static int[] dp = new int[MAXN]; public static int n, m; public static void clean() { for (int i = 1; i <= m; i++) { fans[i] = 0; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); while (in.nextToken() != StreamTokenizer.TT_EOF) { n = (int) in.nval; in.nextToken(); m = (int) in.nval; clean(); for (int i = 1, v, p, q; i <= m; i++) { in.nextToken(); v = (int) in.nval; in.nextToken(); p = (int) in.nval; in.nextToken(); q = (int) in.nval; cost[i] = v; val[i] = v * p; king[i] = q == 0; if (q != 0) { follows[q][fans[q]++] = i; } } out.println(compute2()); } out.flush(); out.close(); br.close(); } // 严格位置依赖的动态规划 public static int compute1() { // dp[0][....] = 0 : 无商品的时候 int[][] dp = new int[m + 1][n + 1]; // p : 上次展开的主商品编号 int p = 0; for (int i = 1, fan1, fan2; i <= m; i++) { if (king[i]) { for (int j = 0; j <= n; j++) { // dp[i][j] : 0...i范围上,只关心主商品,并且进行展开 // 花费不超过j的情况下,获得的最大收益 // 可能性1 : 不考虑当前主商品 dp[i][j] = dp[p][j]; if (j - cost[i] >= 0) { // 可能性2 : 考虑当前主商品,只要主 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i]] + val[i]); } // fan1 : 如果有附1商品,编号给fan1,如果没有,fan1 == -1 // fan2 : 如果有附2商品,编号给fan2,如果没有,fan2 == -1 fan1 = fans[i] >= 1 ? follows[i][0] : -1; fan2 = fans[i] >= 2 ? follows[i][1] : -1; if (fan1 != -1 && j - cost[i] - cost[fan1] >= 0) { // 可能性3 : 主 + 附1 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i] - cost[fan1]] + val[i] + val[fan1]); } if (fan2 != -1 && j - cost[i] - cost[fan2] >= 0) { // 可能性4 : 主 + 附2 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i] - cost[fan2]] + val[i] + val[fan2]); } if (fan1 != -1 && fan2 != -1 && j - cost[i] - cost[fan1] - cost[fan2] >= 0) { // 可能性5 : 主 + 附1 + 附2 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i] - cost[fan1] - cost[fan2]] + val[i] + val[fan1] + val[fan2]); } } p = i; } } return dp[p][n]; } // 空间压缩 public static int compute2() { Arrays.fill(dp, 0, n + 1, 0); for (int i = 1, fan1, fan2; i <= m; i++) { if (king[i]) { for (int j = n; j >= cost[i]; j--) { dp[j] = Math.max(dp[j], dp[j - cost[i]] + val[i]); fan1 = fans[i] >= 1 ? follows[i][0] : -1; fan2 = fans[i] >= 2 ? follows[i][1] : -1; if (fan1 != -1 && j - cost[i] - cost[fan1] >= 0) { dp[j] = Math.max(dp[j], dp[j - cost[i] - cost[fan1]] + val[i] + val[fan1]); } if (fan2 != -1 && j - cost[i] - cost[fan2] >= 0) { dp[j] = Math.max(dp[j], dp[j - cost[i] - cost[fan2]] + val[i] + val[fan2]); } if (fan1 != -1 && fan2 != -1 && j - cost[i] - cost[fan1] - cost[fan2] >= 0) { dp[j] = Math.max(dp[j], dp[j - cost[i] - cost[fan1] - cost[fan2]] + val[i] + val[fan1] + val[fan2]); } } } } return dp[n]; } }
algorithmzuo/algorithm-journey
src/class073/Code05_DependentKnapsack.java
2,137
// 所有的物品编号都在1~m之间,每个物品有三个信息:价格v、重要度p、归属q
line_comment
zh-cn
package class073; // 有依赖的背包(模版) // 物品分为两大类:主件和附件 // 主件的购买没有限制,钱够就可以;附件的购买有限制,该附件所归属的主件先购买,才能购买这个附件 // 例如,若想买打印机或扫描仪这样的附件,必须先购买电脑这个主件 // 以下是一些主件及其附件的展示: // 电脑:打印机,扫描仪 | 书柜:图书 | 书桌:台灯,文具 | 工作椅:无附件 // 每个主件最多有2个附件,并且附件不会再有附件,主件购买后,怎么去选择归属附件完全随意,钱够就可以 // 所有 <SUF> // 价格就是花费,价格 * 重要度 就是收益,归属就是该商品是依附于哪个编号的主件 // 比如一件商品信息为[300,2,6],花费300,收益600,该商品是6号主件商品的附件 // 再比如一件商品信息[100,4,0],花费100,收益400,该商品自身是主件(q==0) // 给定m件商品的信息,给定总钱数n,返回在不违反购买规则的情况下最大的收益 // 测试链接 : https://www.luogu.com.cn/problem/P1064 // 测试链接 : https://www.nowcoder.com/practice/f9c6f980eeec43ef85be20755ddbeaf4 // 请同学们务必参考如下代码中关于输入、输出的处理 // 这是输入输出处理效率很高的写法 // 提交以下的所有代码,并把主类名改成"Main",可以直接通过 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class Code05_DependentKnapsack { public static int MAXN = 33001; public static int MAXM = 61; public static int[] cost = new int[MAXM]; public static int[] val = new int[MAXM]; public static boolean[] king = new boolean[MAXM]; public static int[] fans = new int[MAXM]; public static int[][] follows = new int[MAXM][2]; public static int[] dp = new int[MAXN]; public static int n, m; public static void clean() { for (int i = 1; i <= m; i++) { fans[i] = 0; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); while (in.nextToken() != StreamTokenizer.TT_EOF) { n = (int) in.nval; in.nextToken(); m = (int) in.nval; clean(); for (int i = 1, v, p, q; i <= m; i++) { in.nextToken(); v = (int) in.nval; in.nextToken(); p = (int) in.nval; in.nextToken(); q = (int) in.nval; cost[i] = v; val[i] = v * p; king[i] = q == 0; if (q != 0) { follows[q][fans[q]++] = i; } } out.println(compute2()); } out.flush(); out.close(); br.close(); } // 严格位置依赖的动态规划 public static int compute1() { // dp[0][....] = 0 : 无商品的时候 int[][] dp = new int[m + 1][n + 1]; // p : 上次展开的主商品编号 int p = 0; for (int i = 1, fan1, fan2; i <= m; i++) { if (king[i]) { for (int j = 0; j <= n; j++) { // dp[i][j] : 0...i范围上,只关心主商品,并且进行展开 // 花费不超过j的情况下,获得的最大收益 // 可能性1 : 不考虑当前主商品 dp[i][j] = dp[p][j]; if (j - cost[i] >= 0) { // 可能性2 : 考虑当前主商品,只要主 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i]] + val[i]); } // fan1 : 如果有附1商品,编号给fan1,如果没有,fan1 == -1 // fan2 : 如果有附2商品,编号给fan2,如果没有,fan2 == -1 fan1 = fans[i] >= 1 ? follows[i][0] : -1; fan2 = fans[i] >= 2 ? follows[i][1] : -1; if (fan1 != -1 && j - cost[i] - cost[fan1] >= 0) { // 可能性3 : 主 + 附1 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i] - cost[fan1]] + val[i] + val[fan1]); } if (fan2 != -1 && j - cost[i] - cost[fan2] >= 0) { // 可能性4 : 主 + 附2 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i] - cost[fan2]] + val[i] + val[fan2]); } if (fan1 != -1 && fan2 != -1 && j - cost[i] - cost[fan1] - cost[fan2] >= 0) { // 可能性5 : 主 + 附1 + 附2 dp[i][j] = Math.max(dp[i][j], dp[p][j - cost[i] - cost[fan1] - cost[fan2]] + val[i] + val[fan1] + val[fan2]); } } p = i; } } return dp[p][n]; } // 空间压缩 public static int compute2() { Arrays.fill(dp, 0, n + 1, 0); for (int i = 1, fan1, fan2; i <= m; i++) { if (king[i]) { for (int j = n; j >= cost[i]; j--) { dp[j] = Math.max(dp[j], dp[j - cost[i]] + val[i]); fan1 = fans[i] >= 1 ? follows[i][0] : -1; fan2 = fans[i] >= 2 ? follows[i][1] : -1; if (fan1 != -1 && j - cost[i] - cost[fan1] >= 0) { dp[j] = Math.max(dp[j], dp[j - cost[i] - cost[fan1]] + val[i] + val[fan1]); } if (fan2 != -1 && j - cost[i] - cost[fan2] >= 0) { dp[j] = Math.max(dp[j], dp[j - cost[i] - cost[fan2]] + val[i] + val[fan2]); } if (fan1 != -1 && fan2 != -1 && j - cost[i] - cost[fan1] - cost[fan2] >= 0) { dp[j] = Math.max(dp[j], dp[j - cost[i] - cost[fan1] - cost[fan2]] + val[i] + val[fan1] + val[fan2]); } } } } return dp[n]; } }
false
1,838
27
2,137
30
2,020
27
2,137
30
2,775
43
false
false
false
false
false
true
57278_7
package class06; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class ShowComparator { public static class Student { public String name; public int id; public int age; public Student(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } } // 谁id大,谁放前! public static class IdComparator implements Comparator<Student> { // 如果返回负数,认为第一个参数应该排在前面 // 如果返回正数,认为第二个参数应该排在前面 // 如果返回0,认为谁放前面无所谓 @Override public int compare(Student o1, Student o2) { if (o1.id < o2.id) { return 1; } else if (o2.id < o1.id) { return -1; } else { return 0; } } } // 谁age大,谁放前! public static class AgeComparator implements Comparator<Student> { // 如果返回负数,认为第一个参数应该排在前面 // 如果返回正数,认为第二个参数应该排在前面 // 如果返回0,认为谁放前面无所谓 @Override public int compare(Student o1, Student o2) { if (o1.age < o2.age) { return 1; } else if (o2.age < o1.age) { return -1; } else { return 0; } } } public static void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void printStudents(Student[] students) { for (int i = 0; i < students.length; i++) { System.out.println(students[i].name + ", " + students[i].id + ", " + students[i].age); } } public static void main(String[] args) { int[] arr = { 8, 1, 4, 1, 6, 8, 4, 1, 5, 8, 2, 3, 0 }; printArray(arr); Arrays.sort(arr); printArray(arr); Student s1 = new Student("张三", 5, 27); Student s2 = new Student("李四", 1, 17); Student s3 = new Student("王五", 4, 29); Student s4 = new Student("赵六", 3, 9); Student s5 = new Student("左七", 2, 34); Student[] students = { s1, s2, s3, s4, s5 }; printStudents(students); System.out.println("======="); Arrays.sort(students, new IdComparator()); printStudents(students); System.out.println("======="); ArrayList<Student> arrList = new ArrayList<>(); arrList.add(s1); arrList.add(s2); arrList.add(s3); arrList.add(s4); arrList.add(s5); for (Student s : arrList) { System.out.println(s.name + ", " + s.id + ", " + s.age); } System.out.println("======="); arrList.sort(new AgeComparator()); for (Student s : arrList) { System.out.println(s.name + ", " + s.id + ", " + s.age); } } }
algorithmzuo/algorithm-primary
src/class06/ShowComparator.java
971
// 如果返回0,认为谁放前面无所谓
line_comment
zh-cn
package class06; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class ShowComparator { public static class Student { public String name; public int id; public int age; public Student(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } } // 谁id大,谁放前! public static class IdComparator implements Comparator<Student> { // 如果返回负数,认为第一个参数应该排在前面 // 如果返回正数,认为第二个参数应该排在前面 // 如果返回0,认为谁放前面无所谓 @Override public int compare(Student o1, Student o2) { if (o1.id < o2.id) { return 1; } else if (o2.id < o1.id) { return -1; } else { return 0; } } } // 谁age大,谁放前! public static class AgeComparator implements Comparator<Student> { // 如果返回负数,认为第一个参数应该排在前面 // 如果返回正数,认为第二个参数应该排在前面 // 如果 <SUF> @Override public int compare(Student o1, Student o2) { if (o1.age < o2.age) { return 1; } else if (o2.age < o1.age) { return -1; } else { return 0; } } } public static void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void printStudents(Student[] students) { for (int i = 0; i < students.length; i++) { System.out.println(students[i].name + ", " + students[i].id + ", " + students[i].age); } } public static void main(String[] args) { int[] arr = { 8, 1, 4, 1, 6, 8, 4, 1, 5, 8, 2, 3, 0 }; printArray(arr); Arrays.sort(arr); printArray(arr); Student s1 = new Student("张三", 5, 27); Student s2 = new Student("李四", 1, 17); Student s3 = new Student("王五", 4, 29); Student s4 = new Student("赵六", 3, 9); Student s5 = new Student("左七", 2, 34); Student[] students = { s1, s2, s3, s4, s5 }; printStudents(students); System.out.println("======="); Arrays.sort(students, new IdComparator()); printStudents(students); System.out.println("======="); ArrayList<Student> arrList = new ArrayList<>(); arrList.add(s1); arrList.add(s2); arrList.add(s3); arrList.add(s4); arrList.add(s5); for (Student s : arrList) { System.out.println(s.name + ", " + s.id + ", " + s.age); } System.out.println("======="); arrList.sort(new AgeComparator()); for (Student s : arrList) { System.out.println(s.name + ", " + s.id + ", " + s.age); } } }
false
818
10
971
15
949
11
971
15
1,168
21
false
false
false
false
false
true
16033_20
package class07; // 这个代码课上没有讲,但是非常容易理解 // 一定注意看main函数及其注释,用代码展示加强堆的用法 // 展示了加强堆怎么支持非基础类型和基础类型 public class Code03_ShowHeapGreater { // 看这个测试! // 每一句都看懂 public static void main(String[] args) { // 展示非基础类型的用法 Student s1 = new Student(17, "A同学"); Student s2 = new Student(10, "B同学"); Student s3 = new Student(29, "C同学"); Student s4 = new Student(33, "D同学"); Student s5 = new Student(54, "E同学"); Student s6 = new Student(93, "F同学"); // 生成一个加强堆 // 排序策略是年龄小的放在堆顶,年龄小根堆 HeapGreater<Student> heap1 = new HeapGreater<>((a, b) -> a.age - b.age); // 把所有学生加入堆 heap1.push(s1); heap1.push(s2); heap1.push(s3); heap1.push(s4); heap1.push(s5); heap1.push(s6); // 加入之后 // 可以把某个同学的年龄改了 // 比如把s5,也就是E同学 // 年龄从54改成了4 s5.age = 4; // 此时堆被破坏了,因为你擅自改了一个同学的年龄 // 只需要调用resign方法,就能让堆恢复成年龄小根堆 // 而且复杂度是O(log N),很快的 // 系统提供的堆做不到的,加强堆可以 heap1.resign(s5); // 依次弹出所有学生 // 会发现从年龄小到年龄大依次弹出 // 说明堆是正确的 while (!heap1.isEmpty()) { Student cur = heap1.pop(); System.out.println("年龄 : " + cur.age + " , 名字 : " + cur.name); } System.out.println("======================"); // 现在展示非基础类型的加强堆用法 int[] arr = { 3, 3, 2, 5, 3 }; // arr[0] == 3 // arr[1] == 3 // arr[2] == 2 // arr[3] == 5 // arr[4] == 3 // 每个位置的数字一定会自带一个下标,这是一定的! // 任何基础类型的元素,天生一定会自带一些类似下标的身份信息的!这是一定的! // 生成一个加强堆 // 加强堆里只放下标即可,因为通过下标可以找到数字 // 排序策略是 : // 数字小的下标,在堆顶 HeapGreater<Integer> heap2 = new HeapGreater<>((i, j) -> arr[i] - arr[j]); // 把数组所有的下标加入堆 // 就等于加入了所有数字 heap2.push(0); heap2.push(1); heap2.push(2); heap2.push(3); heap2.push(4); // 加入之后 // 可以把某个下标上的数字改了 // arr[1]原来是3,现在变成了-9 arr[1] = -9; // 此时堆被破坏了,因为你擅自改了一个下标的数字 // 只需要调用resign方法,就能让堆恢复 // 而且复杂度是O(log N),很快的 // 系统提供的堆做不到的,加强堆可以 // 调用resign方法 heap2.resign(1); // 依次弹出所有下标 // 会发现下标上的数字越小,下标越早弹出 // 说明堆是正确的 while (!heap2.isEmpty()) { int curIndex = heap2.pop(); System.out.println("下标 : " + curIndex + " , 数字 :" + arr[curIndex]); } } // 一个自己定义的非基础类型 public static class Student { public int age; public String name; public Student(int a, String n) { age = a; name = n; } } }
algorithmzuo/algorithmbasic2020
src/class07/Code03_ShowHeapGreater.java
1,156
// 现在展示非基础类型的加强堆用法
line_comment
zh-cn
package class07; // 这个代码课上没有讲,但是非常容易理解 // 一定注意看main函数及其注释,用代码展示加强堆的用法 // 展示了加强堆怎么支持非基础类型和基础类型 public class Code03_ShowHeapGreater { // 看这个测试! // 每一句都看懂 public static void main(String[] args) { // 展示非基础类型的用法 Student s1 = new Student(17, "A同学"); Student s2 = new Student(10, "B同学"); Student s3 = new Student(29, "C同学"); Student s4 = new Student(33, "D同学"); Student s5 = new Student(54, "E同学"); Student s6 = new Student(93, "F同学"); // 生成一个加强堆 // 排序策略是年龄小的放在堆顶,年龄小根堆 HeapGreater<Student> heap1 = new HeapGreater<>((a, b) -> a.age - b.age); // 把所有学生加入堆 heap1.push(s1); heap1.push(s2); heap1.push(s3); heap1.push(s4); heap1.push(s5); heap1.push(s6); // 加入之后 // 可以把某个同学的年龄改了 // 比如把s5,也就是E同学 // 年龄从54改成了4 s5.age = 4; // 此时堆被破坏了,因为你擅自改了一个同学的年龄 // 只需要调用resign方法,就能让堆恢复成年龄小根堆 // 而且复杂度是O(log N),很快的 // 系统提供的堆做不到的,加强堆可以 heap1.resign(s5); // 依次弹出所有学生 // 会发现从年龄小到年龄大依次弹出 // 说明堆是正确的 while (!heap1.isEmpty()) { Student cur = heap1.pop(); System.out.println("年龄 : " + cur.age + " , 名字 : " + cur.name); } System.out.println("======================"); // 现在 <SUF> int[] arr = { 3, 3, 2, 5, 3 }; // arr[0] == 3 // arr[1] == 3 // arr[2] == 2 // arr[3] == 5 // arr[4] == 3 // 每个位置的数字一定会自带一个下标,这是一定的! // 任何基础类型的元素,天生一定会自带一些类似下标的身份信息的!这是一定的! // 生成一个加强堆 // 加强堆里只放下标即可,因为通过下标可以找到数字 // 排序策略是 : // 数字小的下标,在堆顶 HeapGreater<Integer> heap2 = new HeapGreater<>((i, j) -> arr[i] - arr[j]); // 把数组所有的下标加入堆 // 就等于加入了所有数字 heap2.push(0); heap2.push(1); heap2.push(2); heap2.push(3); heap2.push(4); // 加入之后 // 可以把某个下标上的数字改了 // arr[1]原来是3,现在变成了-9 arr[1] = -9; // 此时堆被破坏了,因为你擅自改了一个下标的数字 // 只需要调用resign方法,就能让堆恢复 // 而且复杂度是O(log N),很快的 // 系统提供的堆做不到的,加强堆可以 // 调用resign方法 heap2.resign(1); // 依次弹出所有下标 // 会发现下标上的数字越小,下标越早弹出 // 说明堆是正确的 while (!heap2.isEmpty()) { int curIndex = heap2.pop(); System.out.println("下标 : " + curIndex + " , 数字 :" + arr[curIndex]); } } // 一个自己定义的非基础类型 public static class Student { public int age; public String name; public Student(int a, String n) { age = a; name = n; } } }
false
1,082
13
1,156
12
1,054
10
1,156
12
1,620
23
false
false
false
false
false
true
35576_13
package class51; import java.util.Arrays; import java.util.HashSet; // leetcode题目 : https://leetcode-cn.com/problems/programmable-robot/ public class LCP_0003_Robot { public static boolean robot1(String command, int[][] obstacles, int x, int y) { int X = 0; int Y = 0; HashSet<Integer> set = new HashSet<>(); set.add(0); for (char c : command.toCharArray()) { X += c == 'R' ? 1 : 0; Y += c == 'U' ? 1 : 0; set.add((X << 10) | Y); } // 不考虑任何额外的点,机器人能不能到达,(x,y) if (!meet1(x, y, X, Y, set)) { return false; } for (int[] ob : obstacles) { // ob[0] ob[1] if (ob[0] <= x && ob[1] <= y && meet1(ob[0], ob[1], X, Y, set)) { return false; } } return true; } // 一轮以内,X,往右一共有几个单位 // Y, 往上一共有几个单位 // set, 一轮以内的所有可能性 // (x,y)要去的点 // 机器人从(0,0)位置,能不能走到(x,y) public static boolean meet1(int x, int y, int X, int Y, HashSet<Integer> set) { if (X == 0) { // Y != 0 往上肯定走了! return x == 0; } if (Y == 0) { return y == 0; } // 至少几轮? int atLeast = Math.min(x / X, y / Y); // 经历过最少轮数后,x剩多少? int rx = x - atLeast * X; // 经历过最少轮数后,y剩多少? int ry = y - atLeast * Y; return set.contains((rx << 10) | ry); } // 此处为一轮以内,x和y最大能移动的步数,对应的2的几次方 // 比如本题,x和y最大能移动1000步,就对应2的10次方 // 如果换一个数据量,x和y最大能移动5000步,就对应2的13次方 // 只需要根据数据量修改这一个变量,剩下的代码不需要调整 public static final int bit = 10; // 如果,x和y最大能移动的步数,对应2的bit次方 // 那么一个坐标(x,y),所有的可能性就是:(2 ^ bit) ^ 2 = 2 ^ (bit * 2) // 也就是,(1 << (bit << 1))个状态,记为bits public static int bits = (1 << (bit << 1)); // 为了表示下bits个状态,需要几个整数? // 32位只需要一个整数,所以bits个状态,需要bits / 32 个整数 // 即整型长度需要 : bits >> 5 public static int[] set = new int[bits >> 5]; public static boolean robot2(String command, int[][] obstacles, int x, int y) { Arrays.fill(set, 0); set[0] = 1; int X = 0; int Y = 0; for (char c : command.toCharArray()) { X += c == 'R' ? 1 : 0; Y += c == 'U' ? 1 : 0; add((X << 10) | Y); } if (!meet2(x, y, X, Y)) { return false; } for (int[] ob : obstacles) { if (ob[0] <= x && ob[1] <= y && meet2(ob[0], ob[1], X, Y)) { return false; } } return true; } public static boolean meet2(int x, int y, int X, int Y) { if (X == 0) { return x == 0; } if (Y == 0) { return y == 0; } int atLeast = Math.min(x / X, y / Y); int rx = x - atLeast * X; int ry = y - atLeast * Y; return contains((rx << 10) | ry); } public static void add(int status) { set[status >> 5] |= 1 << (status & 31); } public static boolean contains(int status) { return (status < bits) && (set[status >> 5] & (1 << (status & 31))) != 0; } // int num -> 32位的状态 // 请打印这32位状态 public static void printBinary(int num) { for (int i = 31; i >= 0; i--) { System.out.print((num & (1 << i)) != 0 ? "1" : "0"); } System.out.println(); } public static void main(String[] args) { int x = 7; printBinary(x); int y = 4; printBinary(y); // x_y 组合! int c = (x << 10) | y; printBinary(c); System.out.println(c); // 0 ~ 1048575 任何一个数,bit来表示的! // int[] set = new int[32768]; // set[0] = int 32 位 0~31这些数出现过没出现过 // set[1] = int 32 位 32~63这些数出现过没出现过 // 0 ~ 1048575 // int[] set = new int[32768]; // int num = 738473; // 32 bit int //// set[ 734873 / 32 ] // 734873 % 32 // boolean exist = (set[num / 32] & (1 << (num % 32))) != 0; } }
algorithmzuo/coding-for-great-offer
src/class51/LCP_0003_Robot.java
1,654
// 比如本题,x和y最大能移动1000步,就对应2的10次方
line_comment
zh-cn
package class51; import java.util.Arrays; import java.util.HashSet; // leetcode题目 : https://leetcode-cn.com/problems/programmable-robot/ public class LCP_0003_Robot { public static boolean robot1(String command, int[][] obstacles, int x, int y) { int X = 0; int Y = 0; HashSet<Integer> set = new HashSet<>(); set.add(0); for (char c : command.toCharArray()) { X += c == 'R' ? 1 : 0; Y += c == 'U' ? 1 : 0; set.add((X << 10) | Y); } // 不考虑任何额外的点,机器人能不能到达,(x,y) if (!meet1(x, y, X, Y, set)) { return false; } for (int[] ob : obstacles) { // ob[0] ob[1] if (ob[0] <= x && ob[1] <= y && meet1(ob[0], ob[1], X, Y, set)) { return false; } } return true; } // 一轮以内,X,往右一共有几个单位 // Y, 往上一共有几个单位 // set, 一轮以内的所有可能性 // (x,y)要去的点 // 机器人从(0,0)位置,能不能走到(x,y) public static boolean meet1(int x, int y, int X, int Y, HashSet<Integer> set) { if (X == 0) { // Y != 0 往上肯定走了! return x == 0; } if (Y == 0) { return y == 0; } // 至少几轮? int atLeast = Math.min(x / X, y / Y); // 经历过最少轮数后,x剩多少? int rx = x - atLeast * X; // 经历过最少轮数后,y剩多少? int ry = y - atLeast * Y; return set.contains((rx << 10) | ry); } // 此处为一轮以内,x和y最大能移动的步数,对应的2的几次方 // 比如 <SUF> // 如果换一个数据量,x和y最大能移动5000步,就对应2的13次方 // 只需要根据数据量修改这一个变量,剩下的代码不需要调整 public static final int bit = 10; // 如果,x和y最大能移动的步数,对应2的bit次方 // 那么一个坐标(x,y),所有的可能性就是:(2 ^ bit) ^ 2 = 2 ^ (bit * 2) // 也就是,(1 << (bit << 1))个状态,记为bits public static int bits = (1 << (bit << 1)); // 为了表示下bits个状态,需要几个整数? // 32位只需要一个整数,所以bits个状态,需要bits / 32 个整数 // 即整型长度需要 : bits >> 5 public static int[] set = new int[bits >> 5]; public static boolean robot2(String command, int[][] obstacles, int x, int y) { Arrays.fill(set, 0); set[0] = 1; int X = 0; int Y = 0; for (char c : command.toCharArray()) { X += c == 'R' ? 1 : 0; Y += c == 'U' ? 1 : 0; add((X << 10) | Y); } if (!meet2(x, y, X, Y)) { return false; } for (int[] ob : obstacles) { if (ob[0] <= x && ob[1] <= y && meet2(ob[0], ob[1], X, Y)) { return false; } } return true; } public static boolean meet2(int x, int y, int X, int Y) { if (X == 0) { return x == 0; } if (Y == 0) { return y == 0; } int atLeast = Math.min(x / X, y / Y); int rx = x - atLeast * X; int ry = y - atLeast * Y; return contains((rx << 10) | ry); } public static void add(int status) { set[status >> 5] |= 1 << (status & 31); } public static boolean contains(int status) { return (status < bits) && (set[status >> 5] & (1 << (status & 31))) != 0; } // int num -> 32位的状态 // 请打印这32位状态 public static void printBinary(int num) { for (int i = 31; i >= 0; i--) { System.out.print((num & (1 << i)) != 0 ? "1" : "0"); } System.out.println(); } public static void main(String[] args) { int x = 7; printBinary(x); int y = 4; printBinary(y); // x_y 组合! int c = (x << 10) | y; printBinary(c); System.out.println(c); // 0 ~ 1048575 任何一个数,bit来表示的! // int[] set = new int[32768]; // set[0] = int 32 位 0~31这些数出现过没出现过 // set[1] = int 32 位 32~63这些数出现过没出现过 // 0 ~ 1048575 // int[] set = new int[32768]; // int num = 738473; // 32 bit int //// set[ 734873 / 32 ] // 734873 % 32 // boolean exist = (set[num / 32] & (1 << (num % 32))) != 0; } }
false
1,485
28
1,654
27
1,600
26
1,654
27
1,960
32
false
false
false
false
false
true
37002_1
package followup; import java.util.HashMap; /* * 100 = 3 + 69258 / 714 * 100 = 82 + 3546 / 197 * * 等号右边的部分,可以写成 p1 + p2 / p3的形式 * 要求p1和p2和p3,所使用的数字,必须把1~9使用完全,并且不重复 * 满足的话,我们就说,形如p1 + p2 / p3,一个有效的"带分数"形式 * 要求,p2 / p3 必须整除 * * 输入N,返回N有多少种带分数形式 * 100,有11种带分数形式 * * 输入的N,N < 10的8次方 * * * */ public class AddDevideNum2 { // 1-9 所有带分数,形成的结果,都算一遍,map里去 // key 100 value 11 public static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); public final static int[] arr = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; public static int ways(int n) { if (map.size() == 0) { process(123456789, 8); } return map.containsKey(n) ? map.get(n) : 0; } // process, 当的数形成样子,num 123456789 // index 该哪个位置的数字去指定了 public static void process(int num, int index) { if (index == -1) { // num 固定了 8 ~ 0 // num + / 8 ~ 0 for (int addSplit = 8; addSplit >= 2; addSplit--) { // p1 int p1 = num / arr[addSplit]; int rest = num % arr[addSplit]; for (int devSplit = (addSplit >> 1); devSplit >= 1; devSplit--) { int p2 = rest / arr[devSplit]; int p3 = rest % arr[devSplit]; if (p2 % p3 == 0) { int ans = p1 + p2 / p3; if (!map.containsKey(ans)) { map.put(ans, 1); } else { map.put(ans, map.get(ans) + 1); } } } } } else { // 需要去指定index位置的数 for (int swap = index; swap >= 0; swap--) { int next = swap(num, index, swap); process(next, index - 1); } } } // 123456789 L == 8 R == 2 // 723456189 public static int swap(int num, int L, int R) { // num L位的数字是什么? int bitL = (num / arr[L]) % 10; int bitR = (num / arr[R]) % 10; return num - (bitL - bitR) * arr[L] + (bitL - bitR) * arr[R]; } public static void main(String[] args) { // 876543210 // int test = 672381945; // int ans = swap(test, 8, 0); // System.out.println(ans); // process(123456789, 8); long start; long end; start = System.currentTimeMillis(); System.out.println(ways(100)); end = System.currentTimeMillis(); System.out.println(end - start); // int N = 100; // long start; // long end; // // 第一次跑要去生成map,需要100多毫秒, // // 但是只需要在第一次生成,以后都是直接查询的 // start = System.currentTimeMillis(); // System.out.println(N + "用带分数表示的方法数 : " + ways(N)); // end = System.currentTimeMillis(); // System.out.println("运行了(毫秒) : " + (end - start)); // // 第二次跑map已经在上面生成好了,自然很快 // N = 10000; // start = System.currentTimeMillis(); // System.out.println(N + "用带分数表示的方法数 : " + ways(N)); // end = System.currentTimeMillis(); // System.out.println("运行了(毫秒) : " + (end - start)); } }
algorithmzuo/leetcode-top-interview-questions
src/followup/AddDevideNum2.java
1,289
// 1-9 所有带分数,形成的结果,都算一遍,map里去
line_comment
zh-cn
package followup; import java.util.HashMap; /* * 100 = 3 + 69258 / 714 * 100 = 82 + 3546 / 197 * * 等号右边的部分,可以写成 p1 + p2 / p3的形式 * 要求p1和p2和p3,所使用的数字,必须把1~9使用完全,并且不重复 * 满足的话,我们就说,形如p1 + p2 / p3,一个有效的"带分数"形式 * 要求,p2 / p3 必须整除 * * 输入N,返回N有多少种带分数形式 * 100,有11种带分数形式 * * 输入的N,N < 10的8次方 * * * */ public class AddDevideNum2 { // 1- <SUF> // key 100 value 11 public static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); public final static int[] arr = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; public static int ways(int n) { if (map.size() == 0) { process(123456789, 8); } return map.containsKey(n) ? map.get(n) : 0; } // process, 当的数形成样子,num 123456789 // index 该哪个位置的数字去指定了 public static void process(int num, int index) { if (index == -1) { // num 固定了 8 ~ 0 // num + / 8 ~ 0 for (int addSplit = 8; addSplit >= 2; addSplit--) { // p1 int p1 = num / arr[addSplit]; int rest = num % arr[addSplit]; for (int devSplit = (addSplit >> 1); devSplit >= 1; devSplit--) { int p2 = rest / arr[devSplit]; int p3 = rest % arr[devSplit]; if (p2 % p3 == 0) { int ans = p1 + p2 / p3; if (!map.containsKey(ans)) { map.put(ans, 1); } else { map.put(ans, map.get(ans) + 1); } } } } } else { // 需要去指定index位置的数 for (int swap = index; swap >= 0; swap--) { int next = swap(num, index, swap); process(next, index - 1); } } } // 123456789 L == 8 R == 2 // 723456189 public static int swap(int num, int L, int R) { // num L位的数字是什么? int bitL = (num / arr[L]) % 10; int bitR = (num / arr[R]) % 10; return num - (bitL - bitR) * arr[L] + (bitL - bitR) * arr[R]; } public static void main(String[] args) { // 876543210 // int test = 672381945; // int ans = swap(test, 8, 0); // System.out.println(ans); // process(123456789, 8); long start; long end; start = System.currentTimeMillis(); System.out.println(ways(100)); end = System.currentTimeMillis(); System.out.println(end - start); // int N = 100; // long start; // long end; // // 第一次跑要去生成map,需要100多毫秒, // // 但是只需要在第一次生成,以后都是直接查询的 // start = System.currentTimeMillis(); // System.out.println(N + "用带分数表示的方法数 : " + ways(N)); // end = System.currentTimeMillis(); // System.out.println("运行了(毫秒) : " + (end - start)); // // 第二次跑map已经在上面生成好了,自然很快 // N = 10000; // start = System.currentTimeMillis(); // System.out.println(N + "用带分数表示的方法数 : " + ways(N)); // end = System.currentTimeMillis(); // System.out.println("运行了(毫秒) : " + (end - start)); } }
false
1,127
21
1,289
24
1,233
19
1,289
24
1,537
30
false
false
false
false
false
true
66347_7
package mca_08_dp; public class Code05_CardsInLine { public static int getWinnerScore(int[] arr) { int xian = xian(arr, 0, arr.length - 1); int hou = hou(arr, 0, arr.length - 1); return Math.max(xian, hou); } // 目前,是在arr[L...R]这个范围上玩牌! // 返回,先手最终的最大得分 public static int xian(int[] arr, int L, int R) { if (L == R) { return arr[L]; } if (L == R - 1) { return Math.max(arr[L], arr[R]); } // L...R上,不止两张牌! // 可能性1:拿走L位置的牌 int p1 = arr[L] + hou(arr, L + 1, R); // 可能性2:拿走R位置的牌 int p2 = arr[R] + hou(arr, L, R - 1); return Math.max(p1, p2); } // 目前,是在arr[L...R]这个范围上玩牌! // 返回,后手最终的最大得分 public static int hou(int[] arr, int L, int R) { if (L == R) { return 0; } if (L == R - 1) { return Math.min(arr[L], arr[R]); } // L..R上,不止两张牌 // 后手! // 可能性1:对手,先手,拿走L位置的牌,接下来!你就可以在L+1..R上先手了! int p1 = xian(arr, L + 1, R); // 可能性2:对手,先手,拿走R位置的牌,接下来!你就可以在L..R-1上先手了! int p2 = xian(arr, L, R - 1); return Math.min(p1, p2); } public static int getWinnerScore2(int[] arr) { int n = arr.length; int[][] dpxian = new int[n][n]; int[][] dphou = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dpxian[i][j] = -1; dphou[i][j] = -1; } } int xian = xian2(arr, 0, arr.length - 1, dpxian, dphou); int hou = hou2(arr, 0, arr.length - 1, dpxian, dphou); return Math.max(xian, hou); } public static int xian2(int[] arr, int L, int R, int[][] dpxian, int[][] dphou) { if (dpxian[L][R] != -1) { return dpxian[L][R]; } int ans = 0; if (L == R) { ans = arr[L]; } else if (L == R - 1) { ans = Math.max(arr[L], arr[R]); } else { int p1 = arr[L] + hou2(arr, L + 1, R, dpxian, dphou); int p2 = arr[R] + hou2(arr, L, R - 1, dpxian, dphou); ans = Math.max(p1, p2); } dpxian[L][R] = ans; return ans; } public static int hou2(int[] arr, int L, int R, int[][] dpxian, int[][] dphou) { if (dphou[L][R] != -1) { return dphou[L][R]; } int ans = 0; if (L == R) { ans = 0; } else if (L == R - 1) { ans = Math.min(arr[L], arr[R]); } else { int p1 = xian2(arr, L + 1, R, dpxian, dphou); int p2 = xian2(arr, L, R - 1, dpxian, dphou); ans = Math.min(p1, p2); } dphou[L][R] = ans; return ans; } // // 根据规则,返回获胜者的分数 // public static int win1(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int first = f1(arr, 0, arr.length - 1); // int second = g1(arr, 0, arr.length - 1); // return Math.max(first, second); // } // // // arr[L..R],先手获得的最好分数返回 // public static int f1(int[] arr, int L, int R) { // if (L == R) { // return arr[L]; // } // int p1 = arr[L] + g1(arr, L + 1, R); // int p2 = arr[R] + g1(arr, L, R - 1); // return Math.max(p1, p2); // } // // // // arr[L..R],后手获得的最好分数返回 // public static int g1(int[] arr, int L, int R) { // if (L == R) { // return 0; // } // int p1 = f1(arr, L + 1, R); // 对手拿走了L位置的数 // int p2 = f1(arr, L, R - 1); // 对手拿走了R位置的数 // return Math.min(p1, p2); // } // // public static int win2(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int N = arr.length; // int[][] fmap = new int[N][N]; // int[][] gmap = new int[N][N]; // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // fmap[i][j] = -1; // gmap[i][j] = -1; // } // } // int first = f2(arr, 0, arr.length - 1, fmap, gmap); // int second = g2(arr, 0, arr.length - 1, fmap, gmap); // return Math.max(first, second); // } // // // arr[L..R],先手获得的最好分数返回 // public static int f2(int[] arr, int L, int R, int[][] fmap, int[][] gmap) { // if (fmap[L][R] != -1) { // return fmap[L][R]; // } // int ans = 0; // if (L == R) { // ans = arr[L]; // } else { // int p1 = arr[L] + g2(arr, L + 1, R, fmap, gmap); // int p2 = arr[R] + g2(arr, L, R - 1, fmap, gmap); // ans = Math.max(p1, p2); // } // fmap[L][R] = ans; // return ans; // } // // // // arr[L..R],后手获得的最好分数返回 // public static int g2(int[] arr, int L, int R, int[][] fmap, int[][] gmap) { // if (gmap[L][R] != -1) { // return gmap[L][R]; // } // int ans = 0; // if (L != R) { // int p1 = f2(arr, L + 1, R, fmap, gmap); // 对手拿走了L位置的数 // int p2 = f2(arr, L, R - 1, fmap, gmap); // 对手拿走了R位置的数 // ans = Math.min(p1, p2); // } // gmap[L][R] = ans; // return ans; // } // // public static int win3(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int N = arr.length; // int[][] fmap = new int[N][N]; // int[][] gmap = new int[N][N]; // for (int i = 0; i < N; i++) { // fmap[i][i] = arr[i]; // } // for (int startCol = 1; startCol < N; startCol++) { // int L = 0; // int R = startCol; // while (R < N) { // fmap[L][R] = Math.max(arr[L] + gmap[L + 1][R], arr[R] + gmap[L][R - 1]); // gmap[L][R] = Math.min(fmap[L + 1][R], fmap[L][R - 1]); // L++; // R++; // } // } // return Math.max(fmap[0][N - 1], gmap[0][N - 1]); // } public static void main(String[] args) { int[] arr = { 5, 7, 4, 5, 8, 1, 6, 0, 3, 4, 6, 1, 7 }; System.out.println(getWinnerScore(arr)); System.out.println(getWinnerScore2(arr)); } }
algorithmzuo/mca-algorithm-problems
第01期/mca_08_dp/Code05_CardsInLine.java
2,686
// L..R上,不止两张牌
line_comment
zh-cn
package mca_08_dp; public class Code05_CardsInLine { public static int getWinnerScore(int[] arr) { int xian = xian(arr, 0, arr.length - 1); int hou = hou(arr, 0, arr.length - 1); return Math.max(xian, hou); } // 目前,是在arr[L...R]这个范围上玩牌! // 返回,先手最终的最大得分 public static int xian(int[] arr, int L, int R) { if (L == R) { return arr[L]; } if (L == R - 1) { return Math.max(arr[L], arr[R]); } // L...R上,不止两张牌! // 可能性1:拿走L位置的牌 int p1 = arr[L] + hou(arr, L + 1, R); // 可能性2:拿走R位置的牌 int p2 = arr[R] + hou(arr, L, R - 1); return Math.max(p1, p2); } // 目前,是在arr[L...R]这个范围上玩牌! // 返回,后手最终的最大得分 public static int hou(int[] arr, int L, int R) { if (L == R) { return 0; } if (L == R - 1) { return Math.min(arr[L], arr[R]); } // L. <SUF> // 后手! // 可能性1:对手,先手,拿走L位置的牌,接下来!你就可以在L+1..R上先手了! int p1 = xian(arr, L + 1, R); // 可能性2:对手,先手,拿走R位置的牌,接下来!你就可以在L..R-1上先手了! int p2 = xian(arr, L, R - 1); return Math.min(p1, p2); } public static int getWinnerScore2(int[] arr) { int n = arr.length; int[][] dpxian = new int[n][n]; int[][] dphou = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dpxian[i][j] = -1; dphou[i][j] = -1; } } int xian = xian2(arr, 0, arr.length - 1, dpxian, dphou); int hou = hou2(arr, 0, arr.length - 1, dpxian, dphou); return Math.max(xian, hou); } public static int xian2(int[] arr, int L, int R, int[][] dpxian, int[][] dphou) { if (dpxian[L][R] != -1) { return dpxian[L][R]; } int ans = 0; if (L == R) { ans = arr[L]; } else if (L == R - 1) { ans = Math.max(arr[L], arr[R]); } else { int p1 = arr[L] + hou2(arr, L + 1, R, dpxian, dphou); int p2 = arr[R] + hou2(arr, L, R - 1, dpxian, dphou); ans = Math.max(p1, p2); } dpxian[L][R] = ans; return ans; } public static int hou2(int[] arr, int L, int R, int[][] dpxian, int[][] dphou) { if (dphou[L][R] != -1) { return dphou[L][R]; } int ans = 0; if (L == R) { ans = 0; } else if (L == R - 1) { ans = Math.min(arr[L], arr[R]); } else { int p1 = xian2(arr, L + 1, R, dpxian, dphou); int p2 = xian2(arr, L, R - 1, dpxian, dphou); ans = Math.min(p1, p2); } dphou[L][R] = ans; return ans; } // // 根据规则,返回获胜者的分数 // public static int win1(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int first = f1(arr, 0, arr.length - 1); // int second = g1(arr, 0, arr.length - 1); // return Math.max(first, second); // } // // // arr[L..R],先手获得的最好分数返回 // public static int f1(int[] arr, int L, int R) { // if (L == R) { // return arr[L]; // } // int p1 = arr[L] + g1(arr, L + 1, R); // int p2 = arr[R] + g1(arr, L, R - 1); // return Math.max(p1, p2); // } // // // // arr[L..R],后手获得的最好分数返回 // public static int g1(int[] arr, int L, int R) { // if (L == R) { // return 0; // } // int p1 = f1(arr, L + 1, R); // 对手拿走了L位置的数 // int p2 = f1(arr, L, R - 1); // 对手拿走了R位置的数 // return Math.min(p1, p2); // } // // public static int win2(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int N = arr.length; // int[][] fmap = new int[N][N]; // int[][] gmap = new int[N][N]; // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // fmap[i][j] = -1; // gmap[i][j] = -1; // } // } // int first = f2(arr, 0, arr.length - 1, fmap, gmap); // int second = g2(arr, 0, arr.length - 1, fmap, gmap); // return Math.max(first, second); // } // // // arr[L..R],先手获得的最好分数返回 // public static int f2(int[] arr, int L, int R, int[][] fmap, int[][] gmap) { // if (fmap[L][R] != -1) { // return fmap[L][R]; // } // int ans = 0; // if (L == R) { // ans = arr[L]; // } else { // int p1 = arr[L] + g2(arr, L + 1, R, fmap, gmap); // int p2 = arr[R] + g2(arr, L, R - 1, fmap, gmap); // ans = Math.max(p1, p2); // } // fmap[L][R] = ans; // return ans; // } // // // // arr[L..R],后手获得的最好分数返回 // public static int g2(int[] arr, int L, int R, int[][] fmap, int[][] gmap) { // if (gmap[L][R] != -1) { // return gmap[L][R]; // } // int ans = 0; // if (L != R) { // int p1 = f2(arr, L + 1, R, fmap, gmap); // 对手拿走了L位置的数 // int p2 = f2(arr, L, R - 1, fmap, gmap); // 对手拿走了R位置的数 // ans = Math.min(p1, p2); // } // gmap[L][R] = ans; // return ans; // } // // public static int win3(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int N = arr.length; // int[][] fmap = new int[N][N]; // int[][] gmap = new int[N][N]; // for (int i = 0; i < N; i++) { // fmap[i][i] = arr[i]; // } // for (int startCol = 1; startCol < N; startCol++) { // int L = 0; // int R = startCol; // while (R < N) { // fmap[L][R] = Math.max(arr[L] + gmap[L + 1][R], arr[R] + gmap[L][R - 1]); // gmap[L][R] = Math.min(fmap[L + 1][R], fmap[L][R - 1]); // L++; // R++; // } // } // return Math.max(fmap[0][N - 1], gmap[0][N - 1]); // } public static void main(String[] args) { int[] arr = { 5, 7, 4, 5, 8, 1, 6, 0, 3, 4, 6, 1, 7 }; System.out.println(getWinnerScore(arr)); System.out.println(getWinnerScore2(arr)); } }
false
2,274
9
2,686
11
2,574
10
2,686
11
2,971
13
false
false
false
false
false
true
64208_13
package class140; // 来自华为OD // 一支n个士兵的军队正在趁夜色逃亡,途中遇到一条湍急的大河 // 敌军在T的时长后到达河面,没到过对岸的士兵都会被消灭 // 现在军队只找到了1只小船,这船最多能同时坐上2个士兵。 // 1) 当1个士兵划船过河,用时为a[i] // 2) 当2个士兵坐船同时划船过河时, 用时为max(a[j],a[i])两士兵中用时最长的 // 3) 当2个士兵坐船只有1个士兵划船时, 用时为a[i] * 10, a[i]为划船士兵用时 // 请帮忙给出一种解决方案,保证存活的士兵最多,且过河用时最短 // 我们先看一下如下的题,再讲一下华为OD的扩展 // 测试链接 : https://www.luogu.com.cn/problem/P1809 // 有一个大晴天, Oliver与同学们一共N人出游, 他们走到一条河的东岸边,想要过河到西岸 // 而东岸边有一条小船。船太小了,一次只能乘坐两人,每个人都有一个渡河时间T // 船划到对岸的时间等于船上渡河时间较长的人所用时间 // 现在已知N个人的渡河时间Ti // Oliver 想要你告诉他,他们最少要花费多少时间,才能使所有人都过河 // 注意,只有船在东岸(西岸)的人才能坐上船划到对岸。 // 请同学们务必参考如下代码中关于输入、输出的处理 // 这是输入输出处理效率很高的写法 // 提交以下的code,提交时请把类名改成"Main" import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class Code03_CrossRiver { public static int MAXN = 100001; public static int[] arr = new int[MAXN]; public static int[] dp = new int[MAXN]; public static int n; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); while (in.nextToken() != StreamTokenizer.TT_EOF) { n = (int) in.nval; for (int i = 0; i < n; i++) { in.nextToken(); arr[i] = (int) in.nval; } int ans = minCost(); out.println(ans); out.flush(); } } public static int minCost() { Arrays.sort(arr, 0, n); if (n >= 1) { dp[0] = arr[0]; } if (n >= 2) { dp[1] = arr[1]; } if (n >= 3) { dp[2] = arr[0] + arr[1] + arr[2]; } for (int i = 3; i < n; i++) { dp[i] = Math.min( dp[i - 2] + arr[1] + arr[0] + arr[i] + arr[1], dp[i - 1] + arr[i] + arr[0]); } return dp[n - 1]; } }
algorithmzuo/publicclass2020
src/class140/Code03_CrossRiver.java
1,011
// 现在已知N个人的渡河时间Ti
line_comment
zh-cn
package class140; // 来自华为OD // 一支n个士兵的军队正在趁夜色逃亡,途中遇到一条湍急的大河 // 敌军在T的时长后到达河面,没到过对岸的士兵都会被消灭 // 现在军队只找到了1只小船,这船最多能同时坐上2个士兵。 // 1) 当1个士兵划船过河,用时为a[i] // 2) 当2个士兵坐船同时划船过河时, 用时为max(a[j],a[i])两士兵中用时最长的 // 3) 当2个士兵坐船只有1个士兵划船时, 用时为a[i] * 10, a[i]为划船士兵用时 // 请帮忙给出一种解决方案,保证存活的士兵最多,且过河用时最短 // 我们先看一下如下的题,再讲一下华为OD的扩展 // 测试链接 : https://www.luogu.com.cn/problem/P1809 // 有一个大晴天, Oliver与同学们一共N人出游, 他们走到一条河的东岸边,想要过河到西岸 // 而东岸边有一条小船。船太小了,一次只能乘坐两人,每个人都有一个渡河时间T // 船划到对岸的时间等于船上渡河时间较长的人所用时间 // 现在 <SUF> // Oliver 想要你告诉他,他们最少要花费多少时间,才能使所有人都过河 // 注意,只有船在东岸(西岸)的人才能坐上船划到对岸。 // 请同学们务必参考如下代码中关于输入、输出的处理 // 这是输入输出处理效率很高的写法 // 提交以下的code,提交时请把类名改成"Main" import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.Arrays; public class Code03_CrossRiver { public static int MAXN = 100001; public static int[] arr = new int[MAXN]; public static int[] dp = new int[MAXN]; public static int n; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StreamTokenizer in = new StreamTokenizer(br); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); while (in.nextToken() != StreamTokenizer.TT_EOF) { n = (int) in.nval; for (int i = 0; i < n; i++) { in.nextToken(); arr[i] = (int) in.nval; } int ans = minCost(); out.println(ans); out.flush(); } } public static int minCost() { Arrays.sort(arr, 0, n); if (n >= 1) { dp[0] = arr[0]; } if (n >= 2) { dp[1] = arr[1]; } if (n >= 3) { dp[2] = arr[0] + arr[1] + arr[2]; } for (int i = 3; i < n; i++) { dp[i] = Math.min( dp[i - 2] + arr[1] + arr[0] + arr[i] + arr[1], dp[i - 1] + arr[i] + arr[0]); } return dp[n - 1]; } }
false
809
14
1,011
13
901
12
1,011
13
1,242
16
false
false
false
false
false
true
36111_1
package videocode; public class Code04_EatGrass { // n 一开始的份数 // 先手、后手,先后:1,4,16,64,.... // 返回,在先手和后手都做出对自己最优决策的时候,谁会赢? // "先手", "后手" // n == 0 先最先遇到0 后手赢 // n == 1 先直接拿走1, 先手赢 // n == 2 先 1 后1, 后手赢 // n == 3 先 1 后 1 先 1 先手赢 // n == 4 先 4 先手赢 public static String winner1(int n) { if (n < 5) { // base case return (n == 0 || n == 2) ? "后手" : "先手"; } // n >= 5 // 此时的递归过程 // 先拿 : 先手 // 后拿 : 后手 int base = 1; // 此时的先手,决定拿的份数 while (base <= n) { // 如果先手拿base份,会赢的话,直接返回先手赢 // 此时的先手,如果拿了base份 // 下一步轮到后手拿,面对 n - base // 下一步:winner1(n - base) 返回的是后手赢! // 下一步的先手是:此时这个函数里的后手 // 下一步的后手是:此时这个函数里的先手 if (winner1(n - base).equals("后手")) { return "先手"; } if (base > n / 4) { // 防止溢出 break; } base *= 4; } return "后手"; } public static String winner2(int n) { if (n % 5 == 0 || n % 5 == 2) { return "后手"; } else { return "先手"; } } public static void main(String[] args) { for (int i = 0; i <= 50; i++) { System.out.println(i + " : " + winner1(i)); } } }
algorithmzuo/videocode
src/videocode/Code04_EatGrass.java
614
// 先手、后手,先后:1,4,16,64,....
line_comment
zh-cn
package videocode; public class Code04_EatGrass { // n 一开始的份数 // 先手 <SUF> // 返回,在先手和后手都做出对自己最优决策的时候,谁会赢? // "先手", "后手" // n == 0 先最先遇到0 后手赢 // n == 1 先直接拿走1, 先手赢 // n == 2 先 1 后1, 后手赢 // n == 3 先 1 后 1 先 1 先手赢 // n == 4 先 4 先手赢 public static String winner1(int n) { if (n < 5) { // base case return (n == 0 || n == 2) ? "后手" : "先手"; } // n >= 5 // 此时的递归过程 // 先拿 : 先手 // 后拿 : 后手 int base = 1; // 此时的先手,决定拿的份数 while (base <= n) { // 如果先手拿base份,会赢的话,直接返回先手赢 // 此时的先手,如果拿了base份 // 下一步轮到后手拿,面对 n - base // 下一步:winner1(n - base) 返回的是后手赢! // 下一步的先手是:此时这个函数里的后手 // 下一步的后手是:此时这个函数里的先手 if (winner1(n - base).equals("后手")) { return "先手"; } if (base > n / 4) { // 防止溢出 break; } base *= 4; } return "后手"; } public static String winner2(int n) { if (n % 5 == 0 || n % 5 == 2) { return "后手"; } else { return "先手"; } } public static void main(String[] args) { for (int i = 0; i <= 50; i++) { System.out.println(i + " : " + winner1(i)); } } }
false
565
21
614
22
565
19
614
22
763
22
false
false
false
false
false
true
27636_16
package class_2022_08_3_week; // 来自学员问题 // 给定怪兽的血量为hp // 第i回合如果用刀砍,怪兽在这回合会直接掉血,没有后续效果 // 第i回合如果用毒,怪兽在这回合不会掉血, // 但是之后每回合都会掉血,并且所有中毒的后续效果会叠加 // 给定的两个数组cuts、poisons,两个数组等长,长度都是n // 表示你在n回合内的行动, // 每一回合的刀砍的效果由cuts[i]表示 // 每一回合的中毒的效果由poisons[i]表示 // 如果你在n个回合内没有直接杀死怪兽,意味着你已经无法有新的行动了 // 但是怪兽如果有中毒效果的话,那么怪兽依然会在hp耗尽的那回合死掉 // 返回你最快能在多少回合内将怪兽杀死 // 数据范围 : // 1 <= n <= 10的5次方 // 1 <= hp <= 10的9次方 // 1 <= cuts[i]、poisons[i] <= 10的9次方 public class Code02_CutOrPoison { // 不算好的方法 // 为了验证 public static int fast1(int[] cuts, int[] poisons, int hp) { int sum = 0; for (int num : poisons) { sum += num; } int[][][] dp = new int[cuts.length][hp + 1][sum + 1]; return process1(cuts, poisons, 0, hp, 0, dp); } public static int process1(int[] cuts, int[] poisons, int index, int restHp, int poisonEffect, int[][][] dp) { restHp -= poisonEffect; if (restHp <= 0) { return index + 1; } // restHp > 0 if (index == cuts.length) { if (poisonEffect == 0) { return Integer.MAX_VALUE; } else { return cuts.length + 1 + (restHp + poisonEffect - 1) / poisonEffect; } } if (dp[index][restHp][poisonEffect] != 0) { return dp[index][restHp][poisonEffect]; } int p1 = restHp <= cuts[index] ? (index + 1) : process1(cuts, poisons, index + 1, restHp - cuts[index], poisonEffect, dp); int p2 = process1(cuts, poisons, index + 1, restHp, poisonEffect + poisons[index], dp); int ans = Math.min(p1, p2); dp[index][restHp][poisonEffect] = ans; return ans; } // 真正想实现的方法 // O(N * log(hp)) public static int fast2(int[] cuts, int[] poisons, int hp) { // 怪兽可能的最快死亡回合 int l = 1; // 怪兽可能的最晚死亡回合 int r = hp + 1; int m = 0; int ans = Integer.MAX_VALUE; while (l <= r) { m = l + ((r - l) >> 1); if (ok(cuts, poisons, hp, m)) { ans = m; r = m - 1; } else { l = m + 1; } } return ans; } public static boolean ok(int[] cuts, int[] posions, long hp, int limit) { int n = Math.min(cuts.length, limit); for (int i = 0, j = 1; i < n; i++, j++) { hp -= Math.max((long) cuts[i], (long) (limit - j) * (long) posions[i]); if (hp <= 0) { return true; } } return false; } // 为了测试 public static int[] randomArray(int n, int v) { int[] ans = new int[n]; for (int i = 0; i < n; i++) { ans[i] = (int) (Math.random() * v) + 1; } return ans; } // 为了测试 public static void main(String[] args) { int N = 30; int cutV = 20; int posionV = 10; int hpV = 200; int testTimes = 10000; System.out.println("测试开始"); for (int i = 0; i < testTimes; i++) { int n = (int) (Math.random() * N) + 1; int[] cuts = randomArray(n, cutV); int[] posions = randomArray(n, posionV); int hp = (int) (Math.random() * hpV) + 1; int ans1 = fast1(cuts, posions, hp); int ans2 = fast2(cuts, posions, hp); if (ans1 != ans2) { System.out.println("出错了!"); } } System.out.println("测试结束"); } }
algorithmzuo/weekly-problems
src/class_2022_08_3_week/Code02_CutOrPoison.java
1,427
// 不算好的方法
line_comment
zh-cn
package class_2022_08_3_week; // 来自学员问题 // 给定怪兽的血量为hp // 第i回合如果用刀砍,怪兽在这回合会直接掉血,没有后续效果 // 第i回合如果用毒,怪兽在这回合不会掉血, // 但是之后每回合都会掉血,并且所有中毒的后续效果会叠加 // 给定的两个数组cuts、poisons,两个数组等长,长度都是n // 表示你在n回合内的行动, // 每一回合的刀砍的效果由cuts[i]表示 // 每一回合的中毒的效果由poisons[i]表示 // 如果你在n个回合内没有直接杀死怪兽,意味着你已经无法有新的行动了 // 但是怪兽如果有中毒效果的话,那么怪兽依然会在hp耗尽的那回合死掉 // 返回你最快能在多少回合内将怪兽杀死 // 数据范围 : // 1 <= n <= 10的5次方 // 1 <= hp <= 10的9次方 // 1 <= cuts[i]、poisons[i] <= 10的9次方 public class Code02_CutOrPoison { // 不算 <SUF> // 为了验证 public static int fast1(int[] cuts, int[] poisons, int hp) { int sum = 0; for (int num : poisons) { sum += num; } int[][][] dp = new int[cuts.length][hp + 1][sum + 1]; return process1(cuts, poisons, 0, hp, 0, dp); } public static int process1(int[] cuts, int[] poisons, int index, int restHp, int poisonEffect, int[][][] dp) { restHp -= poisonEffect; if (restHp <= 0) { return index + 1; } // restHp > 0 if (index == cuts.length) { if (poisonEffect == 0) { return Integer.MAX_VALUE; } else { return cuts.length + 1 + (restHp + poisonEffect - 1) / poisonEffect; } } if (dp[index][restHp][poisonEffect] != 0) { return dp[index][restHp][poisonEffect]; } int p1 = restHp <= cuts[index] ? (index + 1) : process1(cuts, poisons, index + 1, restHp - cuts[index], poisonEffect, dp); int p2 = process1(cuts, poisons, index + 1, restHp, poisonEffect + poisons[index], dp); int ans = Math.min(p1, p2); dp[index][restHp][poisonEffect] = ans; return ans; } // 真正想实现的方法 // O(N * log(hp)) public static int fast2(int[] cuts, int[] poisons, int hp) { // 怪兽可能的最快死亡回合 int l = 1; // 怪兽可能的最晚死亡回合 int r = hp + 1; int m = 0; int ans = Integer.MAX_VALUE; while (l <= r) { m = l + ((r - l) >> 1); if (ok(cuts, poisons, hp, m)) { ans = m; r = m - 1; } else { l = m + 1; } } return ans; } public static boolean ok(int[] cuts, int[] posions, long hp, int limit) { int n = Math.min(cuts.length, limit); for (int i = 0, j = 1; i < n; i++, j++) { hp -= Math.max((long) cuts[i], (long) (limit - j) * (long) posions[i]); if (hp <= 0) { return true; } } return false; } // 为了测试 public static int[] randomArray(int n, int v) { int[] ans = new int[n]; for (int i = 0; i < n; i++) { ans[i] = (int) (Math.random() * v) + 1; } return ans; } // 为了测试 public static void main(String[] args) { int N = 30; int cutV = 20; int posionV = 10; int hpV = 200; int testTimes = 10000; System.out.println("测试开始"); for (int i = 0; i < testTimes; i++) { int n = (int) (Math.random() * N) + 1; int[] cuts = randomArray(n, cutV); int[] posions = randomArray(n, posionV); int hp = (int) (Math.random() * hpV) + 1; int ans1 = fast1(cuts, posions, hp); int ans2 = fast2(cuts, posions, hp); if (ans1 != ans2) { System.out.println("出错了!"); } } System.out.println("测试结束"); } }
false
1,209
5
1,427
5
1,297
5
1,427
5
1,699
8
false
false
false
false
false
true
6015_20
package com.alibaba.android.arouter.utils; // Copy from galaxy sdk ${com.alibaba.android.galaxy.utils.ClassUtils} import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Build; import android.util.Log; import com.alibaba.android.arouter.launcher.ARouter; import com.alibaba.android.arouter.thread.DefaultPoolExecutor; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; import dalvik.system.DexFile; /** * Scanner, find out class with any conditions, copy from google source code. * * @author 正纬 <a href="mailto:zhilong.liu@aliyun.com">Contact me.</a> * @version 1.0 * @since 16/6/27 下午10:58 */ public class ClassUtils { private static final String EXTRACTED_NAME_EXT = ".classes"; private static final String EXTRACTED_SUFFIX = ".zip"; private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator + "secondary-dexes"; private static final String PREFS_FILE = "multidex.version"; private static final String KEY_DEX_NUMBER = "dex.number"; private static final int VM_WITH_MULTIDEX_VERSION_MAJOR = 2; private static final int VM_WITH_MULTIDEX_VERSION_MINOR = 1; private static SharedPreferences getMultiDexPreferences(Context context) { return context.getSharedPreferences(PREFS_FILE, Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? Context.MODE_PRIVATE : Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); } /** * 通过指定包名,扫描包下面包含的所有的ClassName * * @param context U know * @param packageName 包名 * @return 所有class的集合 */ public static Set<String> getFileNameByPackageName(Context context, final String packageName) throws PackageManager.NameNotFoundException, IOException, InterruptedException { final Set<String> classNames = new HashSet<>(); List<String> paths = getSourcePaths(context); final CountDownLatch parserCtl = new CountDownLatch(paths.size()); for (final String path : paths) { DefaultPoolExecutor.getInstance().execute(new Runnable() { @Override public void run() { DexFile dexfile = null; try { if (path.endsWith(EXTRACTED_SUFFIX)) { //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache" dexfile = DexFile.loadDex(path, path + ".tmp", 0); } else { dexfile = new DexFile(path); } Enumeration<String> dexEntries = dexfile.entries(); while (dexEntries.hasMoreElements()) { String className = dexEntries.nextElement(); if (className.startsWith(packageName)) { classNames.add(className); } } } catch (Throwable ignore) { Log.e("ARouter", "Scan map file in dex files made error.", ignore); } finally { if (null != dexfile) { try { dexfile.close(); } catch (Throwable ignore) { } } parserCtl.countDown(); } } }); } parserCtl.await(); Log.d(Consts.TAG, "Filter " + classNames.size() + " classes by packageName <" + packageName + ">"); return classNames; } /** * get all the dex path * * @param context the application context * @return all the dex path * @throws PackageManager.NameNotFoundException * @throws IOException */ public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); File sourceApk = new File(applicationInfo.sourceDir); List<String> sourcePaths = new ArrayList<>(); sourcePaths.add(applicationInfo.sourceDir); //add the default apk path //the prefix of extracted file, ie: test.classes String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT; // 如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了 // 通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的 if (!isVMMultidexCapable()) { //the total dex numbers int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1); File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME); for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) { //for each dex file, ie: test.classes2.zip, test.classes3.zip... String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX; File extractedFile = new File(dexDir, fileName); if (extractedFile.isFile()) { sourcePaths.add(extractedFile.getAbsolutePath()); //we ignore the verify zip part } else { throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'"); } } } if (ARouter.debuggable()) { // Search instant run support only debuggable sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo)); } return sourcePaths; } /** * Get instant run dex path, used to catch the branch usingApkSplits=false. */ private static List<String> tryLoadInstantRunDexFile(ApplicationInfo applicationInfo) { List<String> instantRunSourcePaths = new ArrayList<>(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && null != applicationInfo.splitSourceDirs) { // add the split apk, normally for InstantRun, and newest version. instantRunSourcePaths.addAll(Arrays.asList(applicationInfo.splitSourceDirs)); Log.d(Consts.TAG, "Found InstantRun support"); } else { try { // This man is reflection from Google instant run sdk, he will tell me where the dex files go. Class pathsByInstantRun = Class.forName("com.android.tools.fd.runtime.Paths"); Method getDexFileDirectory = pathsByInstantRun.getMethod("getDexFileDirectory", String.class); String instantRunDexPath = (String) getDexFileDirectory.invoke(null, applicationInfo.packageName); File instantRunFilePath = new File(instantRunDexPath); if (instantRunFilePath.exists() && instantRunFilePath.isDirectory()) { File[] dexFile = instantRunFilePath.listFiles(); for (File file : dexFile) { if (null != file && file.exists() && file.isFile() && file.getName().endsWith(".dex")) { instantRunSourcePaths.add(file.getAbsolutePath()); } } Log.d(Consts.TAG, "Found InstantRun support"); } } catch (Exception e) { Log.e(Consts.TAG, "InstantRun support error, " + e.getMessage()); } } return instantRunSourcePaths; } /** * Identifies if the current VM has a native support for multidex, meaning there is no need for * additional installation by this library. * * @return true if the VM handles multidex */ private static boolean isVMMultidexCapable() { boolean isMultidexCapable = false; String vmName = null; try { if (isYunOS()) { // YunOS需要特殊判断 vmName = "'YunOS'"; isMultidexCapable = Integer.valueOf(System.getProperty("ro.build.version.sdk")) >= 21; } else { // 非YunOS原生Android vmName = "'Android'"; String versionString = System.getProperty("java.vm.version"); if (versionString != null) { Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(versionString); if (matcher.matches()) { try { int major = Integer.parseInt(matcher.group(1)); int minor = Integer.parseInt(matcher.group(2)); isMultidexCapable = (major > VM_WITH_MULTIDEX_VERSION_MAJOR) || ((major == VM_WITH_MULTIDEX_VERSION_MAJOR) && (minor >= VM_WITH_MULTIDEX_VERSION_MINOR)); } catch (NumberFormatException ignore) { // let isMultidexCapable be false } } } } } catch (Exception ignore) { } Log.i(Consts.TAG, "VM with name " + vmName + (isMultidexCapable ? " has multidex support" : " does not have multidex support")); return isMultidexCapable; } /** * 判断系统是否为YunOS系统 */ private static boolean isYunOS() { try { String version = System.getProperty("ro.yunos.version"); String vmName = System.getProperty("java.vm.name"); return (vmName != null && vmName.toLowerCase().contains("lemur")) || (version != null && version.trim().length() > 0); } catch (Exception ignore) { return false; } } }
alibaba/ARouter
arouter-api/src/main/java/com/alibaba/android/arouter/utils/ClassUtils.java
2,287
/** * 判断系统是否为YunOS系统 */
block_comment
zh-cn
package com.alibaba.android.arouter.utils; // Copy from galaxy sdk ${com.alibaba.android.galaxy.utils.ClassUtils} import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Build; import android.util.Log; import com.alibaba.android.arouter.launcher.ARouter; import com.alibaba.android.arouter.thread.DefaultPoolExecutor; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; import dalvik.system.DexFile; /** * Scanner, find out class with any conditions, copy from google source code. * * @author 正纬 <a href="mailto:zhilong.liu@aliyun.com">Contact me.</a> * @version 1.0 * @since 16/6/27 下午10:58 */ public class ClassUtils { private static final String EXTRACTED_NAME_EXT = ".classes"; private static final String EXTRACTED_SUFFIX = ".zip"; private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator + "secondary-dexes"; private static final String PREFS_FILE = "multidex.version"; private static final String KEY_DEX_NUMBER = "dex.number"; private static final int VM_WITH_MULTIDEX_VERSION_MAJOR = 2; private static final int VM_WITH_MULTIDEX_VERSION_MINOR = 1; private static SharedPreferences getMultiDexPreferences(Context context) { return context.getSharedPreferences(PREFS_FILE, Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? Context.MODE_PRIVATE : Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); } /** * 通过指定包名,扫描包下面包含的所有的ClassName * * @param context U know * @param packageName 包名 * @return 所有class的集合 */ public static Set<String> getFileNameByPackageName(Context context, final String packageName) throws PackageManager.NameNotFoundException, IOException, InterruptedException { final Set<String> classNames = new HashSet<>(); List<String> paths = getSourcePaths(context); final CountDownLatch parserCtl = new CountDownLatch(paths.size()); for (final String path : paths) { DefaultPoolExecutor.getInstance().execute(new Runnable() { @Override public void run() { DexFile dexfile = null; try { if (path.endsWith(EXTRACTED_SUFFIX)) { //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache" dexfile = DexFile.loadDex(path, path + ".tmp", 0); } else { dexfile = new DexFile(path); } Enumeration<String> dexEntries = dexfile.entries(); while (dexEntries.hasMoreElements()) { String className = dexEntries.nextElement(); if (className.startsWith(packageName)) { classNames.add(className); } } } catch (Throwable ignore) { Log.e("ARouter", "Scan map file in dex files made error.", ignore); } finally { if (null != dexfile) { try { dexfile.close(); } catch (Throwable ignore) { } } parserCtl.countDown(); } } }); } parserCtl.await(); Log.d(Consts.TAG, "Filter " + classNames.size() + " classes by packageName <" + packageName + ">"); return classNames; } /** * get all the dex path * * @param context the application context * @return all the dex path * @throws PackageManager.NameNotFoundException * @throws IOException */ public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0); File sourceApk = new File(applicationInfo.sourceDir); List<String> sourcePaths = new ArrayList<>(); sourcePaths.add(applicationInfo.sourceDir); //add the default apk path //the prefix of extracted file, ie: test.classes String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT; // 如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了 // 通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的 if (!isVMMultidexCapable()) { //the total dex numbers int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1); File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME); for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) { //for each dex file, ie: test.classes2.zip, test.classes3.zip... String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX; File extractedFile = new File(dexDir, fileName); if (extractedFile.isFile()) { sourcePaths.add(extractedFile.getAbsolutePath()); //we ignore the verify zip part } else { throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'"); } } } if (ARouter.debuggable()) { // Search instant run support only debuggable sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo)); } return sourcePaths; } /** * Get instant run dex path, used to catch the branch usingApkSplits=false. */ private static List<String> tryLoadInstantRunDexFile(ApplicationInfo applicationInfo) { List<String> instantRunSourcePaths = new ArrayList<>(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && null != applicationInfo.splitSourceDirs) { // add the split apk, normally for InstantRun, and newest version. instantRunSourcePaths.addAll(Arrays.asList(applicationInfo.splitSourceDirs)); Log.d(Consts.TAG, "Found InstantRun support"); } else { try { // This man is reflection from Google instant run sdk, he will tell me where the dex files go. Class pathsByInstantRun = Class.forName("com.android.tools.fd.runtime.Paths"); Method getDexFileDirectory = pathsByInstantRun.getMethod("getDexFileDirectory", String.class); String instantRunDexPath = (String) getDexFileDirectory.invoke(null, applicationInfo.packageName); File instantRunFilePath = new File(instantRunDexPath); if (instantRunFilePath.exists() && instantRunFilePath.isDirectory()) { File[] dexFile = instantRunFilePath.listFiles(); for (File file : dexFile) { if (null != file && file.exists() && file.isFile() && file.getName().endsWith(".dex")) { instantRunSourcePaths.add(file.getAbsolutePath()); } } Log.d(Consts.TAG, "Found InstantRun support"); } } catch (Exception e) { Log.e(Consts.TAG, "InstantRun support error, " + e.getMessage()); } } return instantRunSourcePaths; } /** * Identifies if the current VM has a native support for multidex, meaning there is no need for * additional installation by this library. * * @return true if the VM handles multidex */ private static boolean isVMMultidexCapable() { boolean isMultidexCapable = false; String vmName = null; try { if (isYunOS()) { // YunOS需要特殊判断 vmName = "'YunOS'"; isMultidexCapable = Integer.valueOf(System.getProperty("ro.build.version.sdk")) >= 21; } else { // 非YunOS原生Android vmName = "'Android'"; String versionString = System.getProperty("java.vm.version"); if (versionString != null) { Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(versionString); if (matcher.matches()) { try { int major = Integer.parseInt(matcher.group(1)); int minor = Integer.parseInt(matcher.group(2)); isMultidexCapable = (major > VM_WITH_MULTIDEX_VERSION_MAJOR) || ((major == VM_WITH_MULTIDEX_VERSION_MAJOR) && (minor >= VM_WITH_MULTIDEX_VERSION_MINOR)); } catch (NumberFormatException ignore) { // let isMultidexCapable be false } } } } } catch (Exception ignore) { } Log.i(Consts.TAG, "VM with name " + vmName + (isMultidexCapable ? " has multidex support" : " does not have multidex support")); return isMultidexCapable; } /** * 判断系 <SUF>*/ private static boolean isYunOS() { try { String version = System.getProperty("ro.yunos.version"); String vmName = System.getProperty("java.vm.name"); return (vmName != null && vmName.toLowerCase().contains("lemur")) || (version != null && version.trim().length() > 0); } catch (Exception ignore) { return false; } } }
false
2,039
15
2,287
13
2,420
14
2,287
13
2,846
20
false
false
false
false
false
true
12667_10
package com.cicada.player.demo.view.gesture; import android.app.Activity; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import com.cicada.player.demo.util.ScreenUtils; /* * Copyright (C) 2010-2018 Alibaba Group Holding Limited. */ /** * 播放控手势控制。通过对view的GestureDetector事件做监听,判断水平滑动还是垂直滑动。 * 最后的结果通过{@link GestureView.GestureListener}返回出去。 * 主要在{@link GestureView}中使用到此类。 */ public class GestureControl { private static final String TAG = GestureControl.class.getSimpleName(); /** * 播放控制层 **/ private View mGesturebleView; /** * 是否允许触摸 //TODO 可以删掉 */ private boolean isGestureEnable = true; //是否水平 private boolean isInHorizenalGesture = false; //是否右边垂直 private boolean isInRightGesture = false; //是否左边垂直 private boolean isInLeftGesture = false; //手势决定器 private GestureDetector mGestureDetector; //手势监听 private GestureView.GestureListener mGestureListener; /** * @param gestureView 播放控制层 */ public GestureControl( View gestureView) { this.mGesturebleView = gestureView; init(); } private void init() { mGestureDetector = new GestureDetector(mGesturebleView.getContext().getApplicationContext(), mOnGestureListener); mGesturebleView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: //对结束事件的监听 if (mGestureListener != null) { mGestureListener.onGestureEnd(); } isInLeftGesture = false; isInRightGesture = false; isInHorizenalGesture = false; break; default: break; } //其他的事件交给GestureDetector。 return mGestureDetector.onTouchEvent(event); } }); //GestureDetector增加双击事件的监听。。里面包含了单击事件 mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() { @Override public boolean onSingleTapConfirmed(MotionEvent e) { // 处理点击事件 if (mGestureListener != null) { mGestureListener.onSingleTap(); } return false; } @Override public boolean onDoubleTap(MotionEvent e) { return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { if (mGestureListener != null) { mGestureListener.onDoubleTap(); } return false; } }); } /** * 开启关闭手势控制。 * @param enable 开启 */ void enableGesture(boolean enable) { this.isGestureEnable = enable; } /** * 设置手势监听事件 * @param mGestureListener 手势监听事件 */ void setOnGestureControlListener(GestureView.GestureListener mGestureListener) { this.mGestureListener = mGestureListener; } /** * 绑定到GestureDetector的。 */ private final OnGestureListener mOnGestureListener = new OnGestureListener() { private float mXDown; @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { //如果关闭了手势。则不处理。 if (!isGestureEnable || e1 == null || e2 == null) { return false; } if (Math.abs(distanceX) > Math.abs(distanceY)) { //水平滑动 if (isInLeftGesture || isInRightGesture) { //此前已经是竖直滑动了,不管 } else { isInHorizenalGesture = true; } } else { //垂直滑动 if (isInHorizenalGesture) { } else { } } if (isInHorizenalGesture) { if (mGestureListener != null) { mGestureListener.onHorizontalDistance(e1.getX(), e2.getX()); } } else { if (ScreenUtils.isInLeft((Activity) mGesturebleView.getContext(), (int) mXDown)) { isInLeftGesture = true; if (mGestureListener != null) { mGestureListener.onLeftVerticalDistance(e1.getY(), e2.getY()); } } else if (ScreenUtils.isInRight((Activity) mGesturebleView.getContext(), (int) mXDown)) { isInRightGesture = true; if (mGestureListener != null) { mGestureListener.onRightVerticalDistance(e1.getY(), e2.getY()); } } } return true; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } @Override public boolean onDown(MotionEvent e) { this.mXDown = e.getX(); return true; } }; }
alibaba/CicadaPlayer
platform/Android/source/paasApp/src/main/java/com/cicada/player/demo/view/gesture/GestureControl.java
1,330
//对结束事件的监听
line_comment
zh-cn
package com.cicada.player.demo.view.gesture; import android.app.Activity; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import com.cicada.player.demo.util.ScreenUtils; /* * Copyright (C) 2010-2018 Alibaba Group Holding Limited. */ /** * 播放控手势控制。通过对view的GestureDetector事件做监听,判断水平滑动还是垂直滑动。 * 最后的结果通过{@link GestureView.GestureListener}返回出去。 * 主要在{@link GestureView}中使用到此类。 */ public class GestureControl { private static final String TAG = GestureControl.class.getSimpleName(); /** * 播放控制层 **/ private View mGesturebleView; /** * 是否允许触摸 //TODO 可以删掉 */ private boolean isGestureEnable = true; //是否水平 private boolean isInHorizenalGesture = false; //是否右边垂直 private boolean isInRightGesture = false; //是否左边垂直 private boolean isInLeftGesture = false; //手势决定器 private GestureDetector mGestureDetector; //手势监听 private GestureView.GestureListener mGestureListener; /** * @param gestureView 播放控制层 */ public GestureControl( View gestureView) { this.mGesturebleView = gestureView; init(); } private void init() { mGestureDetector = new GestureDetector(mGesturebleView.getContext().getApplicationContext(), mOnGestureListener); mGesturebleView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: //对结 <SUF> if (mGestureListener != null) { mGestureListener.onGestureEnd(); } isInLeftGesture = false; isInRightGesture = false; isInHorizenalGesture = false; break; default: break; } //其他的事件交给GestureDetector。 return mGestureDetector.onTouchEvent(event); } }); //GestureDetector增加双击事件的监听。。里面包含了单击事件 mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() { @Override public boolean onSingleTapConfirmed(MotionEvent e) { // 处理点击事件 if (mGestureListener != null) { mGestureListener.onSingleTap(); } return false; } @Override public boolean onDoubleTap(MotionEvent e) { return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { if (mGestureListener != null) { mGestureListener.onDoubleTap(); } return false; } }); } /** * 开启关闭手势控制。 * @param enable 开启 */ void enableGesture(boolean enable) { this.isGestureEnable = enable; } /** * 设置手势监听事件 * @param mGestureListener 手势监听事件 */ void setOnGestureControlListener(GestureView.GestureListener mGestureListener) { this.mGestureListener = mGestureListener; } /** * 绑定到GestureDetector的。 */ private final OnGestureListener mOnGestureListener = new OnGestureListener() { private float mXDown; @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { //如果关闭了手势。则不处理。 if (!isGestureEnable || e1 == null || e2 == null) { return false; } if (Math.abs(distanceX) > Math.abs(distanceY)) { //水平滑动 if (isInLeftGesture || isInRightGesture) { //此前已经是竖直滑动了,不管 } else { isInHorizenalGesture = true; } } else { //垂直滑动 if (isInHorizenalGesture) { } else { } } if (isInHorizenalGesture) { if (mGestureListener != null) { mGestureListener.onHorizontalDistance(e1.getX(), e2.getX()); } } else { if (ScreenUtils.isInLeft((Activity) mGesturebleView.getContext(), (int) mXDown)) { isInLeftGesture = true; if (mGestureListener != null) { mGestureListener.onLeftVerticalDistance(e1.getY(), e2.getY()); } } else if (ScreenUtils.isInRight((Activity) mGesturebleView.getContext(), (int) mXDown)) { isInRightGesture = true; if (mGestureListener != null) { mGestureListener.onRightVerticalDistance(e1.getY(), e2.getY()); } } } return true; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } @Override public boolean onDown(MotionEvent e) { this.mXDown = e.getX(); return true; } }; }
false
1,206
6
1,330
6
1,385
6
1,330
6
1,753
15
false
false
false
false
false
true
6934_11
package com.alibaba.datax.plugin.reader.otsreader.utils; import com.alibaba.datax.plugin.reader.otsreader.model.OTSPrimaryKeyColumn; import com.alibaba.datax.plugin.reader.otsreader.model.OTSRange; import com.alicloud.openservices.tablestore.model.PrimaryKeyColumn; import com.alicloud.openservices.tablestore.model.PrimaryKeyType; import com.alicloud.openservices.tablestore.model.PrimaryKeyValue; import com.alicloud.openservices.tablestore.model.TableMeta; import java.math.BigInteger; import java.util.*; /** * 主要提供对范围的解析 */ public class RangeSplit { private static String bigIntegerToString(BigInteger baseValue, BigInteger bValue, BigInteger multi, int lenOfString) { BigInteger tmp = bValue; StringBuilder sb = new StringBuilder(); for (int tmpLength = 0; tmpLength < lenOfString; tmpLength++) { sb.insert(0, (char) (baseValue.add(tmp.remainder(multi)).intValue())); tmp = tmp.divide(multi); } return sb.toString(); } /** * 切分String的Unicode Unit * * 注意:该方法只支持begin小于end * * @param begin * @param end * @param count * @return */ private static List<String> splitCodePoint(int begin, int end, int count) { if (begin >= end) { throw new IllegalArgumentException("Only support begin < end."); } List<String> results = new ArrayList<String>(); BigInteger beginBig = BigInteger.valueOf(begin); BigInteger endBig = BigInteger.valueOf(end); BigInteger countBig = BigInteger.valueOf(count); BigInteger multi = endBig.subtract(beginBig).add(BigInteger.ONE); BigInteger range = endBig.subtract(beginBig); BigInteger interval = BigInteger.ZERO; int length = 1; BigInteger tmpBegin = BigInteger.ZERO; BigInteger tmpEnd = endBig.subtract(beginBig); // 扩大之后的数值 BigInteger realBegin = tmpBegin; BigInteger realEnd = tmpEnd; while (range.compareTo(countBig) < 0) { // 不够切分 realEnd = realEnd.multiply(multi).add(tmpEnd); range = realEnd.subtract(realBegin); length++; } interval = range.divide(countBig); BigInteger cur = realBegin; for (int i = 0; i < (count - 1); i++) { results.add(bigIntegerToString(beginBig, cur, multi, length)); cur = cur.add(interval); } results.add(bigIntegerToString(beginBig, realEnd, multi, length)); return results; } /** * 注意: 当begin和end相等时,函数将返回空的List * * @param begin * @param end * @param count * @return */ public static List<String> splitStringRange(String begin, String end, int count) { if (count <= 1) { throw new IllegalArgumentException("Input count <= 1 ."); } List<String> results = new ArrayList<String>(); int beginValue = 0; if (!begin.isEmpty()) { beginValue = begin.codePointAt(0); } int endValue = 0; if (!end.isEmpty()) { endValue = end.codePointAt(0); } int cmp = beginValue - endValue; if (cmp == 0) { return results; } results.add(begin); Comparator<String> comparator = new Comparator<String>(){ public int compare(String arg0, String arg1) { return arg0.compareTo(arg1); } }; List<String> tmp = null; if (cmp > 0) { // 如果是逆序,则 reverse Comparator comparator = Collections.reverseOrder(comparator); tmp = splitCodePoint(endValue, beginValue, count); } else { // 正序 tmp = splitCodePoint(beginValue, endValue, count); } Collections.sort(tmp, comparator); for (String value : tmp) { if (comparator.compare(value, begin) > 0 && comparator.compare(value, end) < 0) { results.add(value); } } results.add(end); return results; } /** * begin 一定要小于 end * @param bigBegin * @param bigEnd * @param bigCount * @return */ private static List<Long> splitIntegerRange(BigInteger bigBegin, BigInteger bigEnd, BigInteger bigCount) { List<Long> is = new ArrayList<Long>(); BigInteger interval = (bigEnd.subtract(bigBegin)).divide(bigCount); BigInteger cur = bigBegin; BigInteger i = BigInteger.ZERO; while (cur.compareTo(bigEnd) < 0 && i.compareTo(bigCount) < 0) { is.add(cur.longValue()); cur = cur.add(interval); i = i.add(BigInteger.ONE); } is.add(bigEnd.longValue()); return is; } /** * 切分数值类型 注意: 当begin和end相等时,函数将返回空的List * * @param begin * @param end * @param count * @return */ public static List<Long> splitIntegerRange(long begin, long end, int count) { if (count <= 1) { throw new IllegalArgumentException("Input count <= 1 ."); } List<Long> is = new ArrayList<Long>(); BigInteger bigBegin = BigInteger.valueOf(begin); BigInteger bigEnd = BigInteger.valueOf(end); BigInteger bigCount = BigInteger.valueOf(count); BigInteger abs = (bigEnd.subtract(bigBegin)).abs(); if (abs.compareTo(BigInteger.ZERO) == 0) { // partition key 相等的情况 return is; } if (bigCount.compareTo(abs) > 0) { bigCount = abs; } if (bigEnd.subtract(bigBegin).compareTo(BigInteger.ZERO) > 0) { // 正向 return splitIntegerRange(bigBegin, bigEnd, bigCount); } else { // 逆向 List<Long> tmp = splitIntegerRange(bigEnd, bigBegin, bigCount); Comparator<Long> comparator = new Comparator<Long>(){ public int compare(Long arg0, Long arg1) { return arg0.compareTo(arg1); } }; Collections.sort(tmp,Collections.reverseOrder(comparator)); return tmp; } } public static List<PrimaryKeyValue> splitRangeByPrimaryKeyType( PrimaryKeyType type, PrimaryKeyValue begin, PrimaryKeyValue end, int count) { List<PrimaryKeyValue> result = new ArrayList<PrimaryKeyValue>(); if (type == PrimaryKeyType.STRING) { List<String> points = splitStringRange(begin.asString(), end.asString(), count); for (String s : points) { result.add(PrimaryKeyValue.fromString(s)); } } else { List<Long> points = splitIntegerRange(begin.asLong(), end.asLong(), count); for (Long l : points) { result.add(PrimaryKeyValue.fromLong(l)); } } return result; } public static List<OTSRange> rangeSplitByCount(TableMeta meta, List<PrimaryKeyColumn> begin, List<PrimaryKeyColumn> end, int count) { List<OTSRange> results = new ArrayList<OTSRange>(); OTSPrimaryKeyColumn partitionKey = Common.getPartitionKey(meta); Map<String, PrimaryKeyValue> beginMap = new HashMap<>(); Map<String, PrimaryKeyValue> endMap = new HashMap<>(); for(PrimaryKeyColumn primaryKeyColumn : begin){ beginMap.put(primaryKeyColumn.getName(), primaryKeyColumn.getValue()); } for(PrimaryKeyColumn primaryKeyColumn : end){ endMap.put(primaryKeyColumn.getName(), primaryKeyColumn.getValue()); } PrimaryKeyValue beginPartitionKey = beginMap.get( partitionKey.getName()); PrimaryKeyValue endPartitionKey = endMap.get( partitionKey.getName()); // 第一,先对PartitionKey列进行拆分 List<PrimaryKeyValue> ranges = RangeSplit.splitRangeByPrimaryKeyType( partitionKey.getType(true), beginPartitionKey, endPartitionKey, count); if (ranges.isEmpty()) { return results; } int size = ranges.size(); for (int i = 0; i < size - 1; i++) { List<PrimaryKeyColumn> bPk = new ArrayList<>(); List<PrimaryKeyColumn> ePk = new ArrayList<>(); bPk.add(new PrimaryKeyColumn(partitionKey.getName(), ranges.get(i))); ePk.add(new PrimaryKeyColumn(partitionKey.getName(), ranges.get(i + 1))); OTSRange range = new OTSRange(); range.setBegin(bPk); range.setEnd(ePk); results.add(range); } // 第二,填充非PartitionKey的ParimaryKey列 // 注意:在填充过程中,需要使用用户给定的Begin和End来替换切分出来的第一个Range // 的Begin和最后一个Range的End List<String> keys = new ArrayList<String>(meta.getPrimaryKeyMap().size()); keys.addAll(meta.getPrimaryKeyMap().keySet()); for (int i = 0; i < results.size(); i++) { for (int j = 1; j < keys.size(); j++) { OTSRange c = results.get(i); List<PrimaryKeyColumn> beginPK = c.getBegin(); List<PrimaryKeyColumn> endPK = c.getEnd(); String key = keys.get(j); if (i == 0) { // 第一行 beginPK.add(new PrimaryKeyColumn(key, beginMap.get(key))); endPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); } else if (i == results.size() - 1) {// 最后一行 beginPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); endPK.add(new PrimaryKeyColumn(key, endMap.get(key))); } else { beginPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); endPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); } } } return results; } }
alibaba/DataX
otsreader/src/main/java/com/alibaba/datax/plugin/reader/otsreader/utils/RangeSplit.java
2,448
// 注意:在填充过程中,需要使用用户给定的Begin和End来替换切分出来的第一个Range
line_comment
zh-cn
package com.alibaba.datax.plugin.reader.otsreader.utils; import com.alibaba.datax.plugin.reader.otsreader.model.OTSPrimaryKeyColumn; import com.alibaba.datax.plugin.reader.otsreader.model.OTSRange; import com.alicloud.openservices.tablestore.model.PrimaryKeyColumn; import com.alicloud.openservices.tablestore.model.PrimaryKeyType; import com.alicloud.openservices.tablestore.model.PrimaryKeyValue; import com.alicloud.openservices.tablestore.model.TableMeta; import java.math.BigInteger; import java.util.*; /** * 主要提供对范围的解析 */ public class RangeSplit { private static String bigIntegerToString(BigInteger baseValue, BigInteger bValue, BigInteger multi, int lenOfString) { BigInteger tmp = bValue; StringBuilder sb = new StringBuilder(); for (int tmpLength = 0; tmpLength < lenOfString; tmpLength++) { sb.insert(0, (char) (baseValue.add(tmp.remainder(multi)).intValue())); tmp = tmp.divide(multi); } return sb.toString(); } /** * 切分String的Unicode Unit * * 注意:该方法只支持begin小于end * * @param begin * @param end * @param count * @return */ private static List<String> splitCodePoint(int begin, int end, int count) { if (begin >= end) { throw new IllegalArgumentException("Only support begin < end."); } List<String> results = new ArrayList<String>(); BigInteger beginBig = BigInteger.valueOf(begin); BigInteger endBig = BigInteger.valueOf(end); BigInteger countBig = BigInteger.valueOf(count); BigInteger multi = endBig.subtract(beginBig).add(BigInteger.ONE); BigInteger range = endBig.subtract(beginBig); BigInteger interval = BigInteger.ZERO; int length = 1; BigInteger tmpBegin = BigInteger.ZERO; BigInteger tmpEnd = endBig.subtract(beginBig); // 扩大之后的数值 BigInteger realBegin = tmpBegin; BigInteger realEnd = tmpEnd; while (range.compareTo(countBig) < 0) { // 不够切分 realEnd = realEnd.multiply(multi).add(tmpEnd); range = realEnd.subtract(realBegin); length++; } interval = range.divide(countBig); BigInteger cur = realBegin; for (int i = 0; i < (count - 1); i++) { results.add(bigIntegerToString(beginBig, cur, multi, length)); cur = cur.add(interval); } results.add(bigIntegerToString(beginBig, realEnd, multi, length)); return results; } /** * 注意: 当begin和end相等时,函数将返回空的List * * @param begin * @param end * @param count * @return */ public static List<String> splitStringRange(String begin, String end, int count) { if (count <= 1) { throw new IllegalArgumentException("Input count <= 1 ."); } List<String> results = new ArrayList<String>(); int beginValue = 0; if (!begin.isEmpty()) { beginValue = begin.codePointAt(0); } int endValue = 0; if (!end.isEmpty()) { endValue = end.codePointAt(0); } int cmp = beginValue - endValue; if (cmp == 0) { return results; } results.add(begin); Comparator<String> comparator = new Comparator<String>(){ public int compare(String arg0, String arg1) { return arg0.compareTo(arg1); } }; List<String> tmp = null; if (cmp > 0) { // 如果是逆序,则 reverse Comparator comparator = Collections.reverseOrder(comparator); tmp = splitCodePoint(endValue, beginValue, count); } else { // 正序 tmp = splitCodePoint(beginValue, endValue, count); } Collections.sort(tmp, comparator); for (String value : tmp) { if (comparator.compare(value, begin) > 0 && comparator.compare(value, end) < 0) { results.add(value); } } results.add(end); return results; } /** * begin 一定要小于 end * @param bigBegin * @param bigEnd * @param bigCount * @return */ private static List<Long> splitIntegerRange(BigInteger bigBegin, BigInteger bigEnd, BigInteger bigCount) { List<Long> is = new ArrayList<Long>(); BigInteger interval = (bigEnd.subtract(bigBegin)).divide(bigCount); BigInteger cur = bigBegin; BigInteger i = BigInteger.ZERO; while (cur.compareTo(bigEnd) < 0 && i.compareTo(bigCount) < 0) { is.add(cur.longValue()); cur = cur.add(interval); i = i.add(BigInteger.ONE); } is.add(bigEnd.longValue()); return is; } /** * 切分数值类型 注意: 当begin和end相等时,函数将返回空的List * * @param begin * @param end * @param count * @return */ public static List<Long> splitIntegerRange(long begin, long end, int count) { if (count <= 1) { throw new IllegalArgumentException("Input count <= 1 ."); } List<Long> is = new ArrayList<Long>(); BigInteger bigBegin = BigInteger.valueOf(begin); BigInteger bigEnd = BigInteger.valueOf(end); BigInteger bigCount = BigInteger.valueOf(count); BigInteger abs = (bigEnd.subtract(bigBegin)).abs(); if (abs.compareTo(BigInteger.ZERO) == 0) { // partition key 相等的情况 return is; } if (bigCount.compareTo(abs) > 0) { bigCount = abs; } if (bigEnd.subtract(bigBegin).compareTo(BigInteger.ZERO) > 0) { // 正向 return splitIntegerRange(bigBegin, bigEnd, bigCount); } else { // 逆向 List<Long> tmp = splitIntegerRange(bigEnd, bigBegin, bigCount); Comparator<Long> comparator = new Comparator<Long>(){ public int compare(Long arg0, Long arg1) { return arg0.compareTo(arg1); } }; Collections.sort(tmp,Collections.reverseOrder(comparator)); return tmp; } } public static List<PrimaryKeyValue> splitRangeByPrimaryKeyType( PrimaryKeyType type, PrimaryKeyValue begin, PrimaryKeyValue end, int count) { List<PrimaryKeyValue> result = new ArrayList<PrimaryKeyValue>(); if (type == PrimaryKeyType.STRING) { List<String> points = splitStringRange(begin.asString(), end.asString(), count); for (String s : points) { result.add(PrimaryKeyValue.fromString(s)); } } else { List<Long> points = splitIntegerRange(begin.asLong(), end.asLong(), count); for (Long l : points) { result.add(PrimaryKeyValue.fromLong(l)); } } return result; } public static List<OTSRange> rangeSplitByCount(TableMeta meta, List<PrimaryKeyColumn> begin, List<PrimaryKeyColumn> end, int count) { List<OTSRange> results = new ArrayList<OTSRange>(); OTSPrimaryKeyColumn partitionKey = Common.getPartitionKey(meta); Map<String, PrimaryKeyValue> beginMap = new HashMap<>(); Map<String, PrimaryKeyValue> endMap = new HashMap<>(); for(PrimaryKeyColumn primaryKeyColumn : begin){ beginMap.put(primaryKeyColumn.getName(), primaryKeyColumn.getValue()); } for(PrimaryKeyColumn primaryKeyColumn : end){ endMap.put(primaryKeyColumn.getName(), primaryKeyColumn.getValue()); } PrimaryKeyValue beginPartitionKey = beginMap.get( partitionKey.getName()); PrimaryKeyValue endPartitionKey = endMap.get( partitionKey.getName()); // 第一,先对PartitionKey列进行拆分 List<PrimaryKeyValue> ranges = RangeSplit.splitRangeByPrimaryKeyType( partitionKey.getType(true), beginPartitionKey, endPartitionKey, count); if (ranges.isEmpty()) { return results; } int size = ranges.size(); for (int i = 0; i < size - 1; i++) { List<PrimaryKeyColumn> bPk = new ArrayList<>(); List<PrimaryKeyColumn> ePk = new ArrayList<>(); bPk.add(new PrimaryKeyColumn(partitionKey.getName(), ranges.get(i))); ePk.add(new PrimaryKeyColumn(partitionKey.getName(), ranges.get(i + 1))); OTSRange range = new OTSRange(); range.setBegin(bPk); range.setEnd(ePk); results.add(range); } // 第二,填充非PartitionKey的ParimaryKey列 // 注意 <SUF> // 的Begin和最后一个Range的End List<String> keys = new ArrayList<String>(meta.getPrimaryKeyMap().size()); keys.addAll(meta.getPrimaryKeyMap().keySet()); for (int i = 0; i < results.size(); i++) { for (int j = 1; j < keys.size(); j++) { OTSRange c = results.get(i); List<PrimaryKeyColumn> beginPK = c.getBegin(); List<PrimaryKeyColumn> endPK = c.getEnd(); String key = keys.get(j); if (i == 0) { // 第一行 beginPK.add(new PrimaryKeyColumn(key, beginMap.get(key))); endPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); } else if (i == results.size() - 1) {// 最后一行 beginPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); endPK.add(new PrimaryKeyColumn(key, endMap.get(key))); } else { beginPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); endPK.add(new PrimaryKeyColumn(key, PrimaryKeyValue.INF_MIN)); } } } return results; } }
false
2,194
23
2,448
25
2,663
22
2,448
25
3,004
42
false
false
false
false
false
true
65242_1
package com.taobao.listitem.sample.model; /** * */ public class Movie { public String name; //影片名称 public String director; //导演 public String leadingRole; //主演 public String poster; //海报 public String type; //类型 public String country; //国家 public short duration; //片长(分钟) }
alibaba/ListItem
app/src/main/java/com/taobao/listitem/sample/model/Movie.java
97
//片长(分钟)
line_comment
zh-cn
package com.taobao.listitem.sample.model; /** * */ public class Movie { public String name; //影片名称 public String director; //导演 public String leadingRole; //主演 public String poster; //海报 public String type; //类型 public String country; //国家 public short duration; //片长 <SUF> }
false
85
6
97
7
95
6
97
7
116
9
false
false
false
false
false
true
8344_6
/* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.fragment; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.taobao.luaview.fun.mapper.ui.UIViewGroupMethodMapper; import com.taobao.luaview.global.LuaViewManager; import com.taobao.luaview.userdata.base.UDLuaTable; import com.taobao.luaview.userdata.ui.UDView; import com.taobao.luaview.userdata.ui.UDViewGroup; import com.taobao.luaview.userdata.ui.UDViewPager; import com.taobao.luaview.view.LVViewGroup; import org.luaj.vm2.Globals; /** * ViewPager 的 Fragment * * @author song * @date 15/9/18 */ @SuppressLint("ValidFragment") public class LVPageFragment extends Fragment { private Globals mGlobals; private UDViewPager mInitProps; private int mPosInViewPager; public LVPageFragment(Globals globals, UDViewPager mInitProps, int posInViewPager) { this.mGlobals = globals; this.mInitProps = mInitProps; this.mPosInViewPager = posInViewPager; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //View封装 final UDView page = new UDViewGroup(createPageLayout(), mGlobals, null);//TODO 为什么用mLuaUserData.getmetatable()不行 //对外数据封装,必须使用LuaTable final UDLuaTable pageData = new UDLuaTable(page); final View pageView = pageData.getView(); //初始化View initView(pageData, mPosInViewPager); //绘制数据 renderView(pageData, mPosInViewPager); return pageView; } /** * 调用LuaView的Init方法进行Cell的初始化 * * @param position * @return */ private void initView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageInit(page, position); this.mGlobals.restoreContainer(); } /** * 调用LuaView的Layout方法进行数据填充 * * @param page * @param position */ private void renderView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageLayout(page, position); this.mGlobals.restoreContainer(); } /** * 创建 cell 的布局 * * @return */ private LVViewGroup createPageLayout() { return new LVViewGroup(mGlobals, mInitProps.getmetatable(), null); } }
alibaba/LuaViewSDK
Android/LuaViewSDK/src/com/taobao/luaview/fragment/LVPageFragment.java
765
//绘制数据
line_comment
zh-cn
/* * Created by LuaView. * Copyright (c) 2017, Alibaba Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.taobao.luaview.fragment; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.taobao.luaview.fun.mapper.ui.UIViewGroupMethodMapper; import com.taobao.luaview.global.LuaViewManager; import com.taobao.luaview.userdata.base.UDLuaTable; import com.taobao.luaview.userdata.ui.UDView; import com.taobao.luaview.userdata.ui.UDViewGroup; import com.taobao.luaview.userdata.ui.UDViewPager; import com.taobao.luaview.view.LVViewGroup; import org.luaj.vm2.Globals; /** * ViewPager 的 Fragment * * @author song * @date 15/9/18 */ @SuppressLint("ValidFragment") public class LVPageFragment extends Fragment { private Globals mGlobals; private UDViewPager mInitProps; private int mPosInViewPager; public LVPageFragment(Globals globals, UDViewPager mInitProps, int posInViewPager) { this.mGlobals = globals; this.mInitProps = mInitProps; this.mPosInViewPager = posInViewPager; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //View封装 final UDView page = new UDViewGroup(createPageLayout(), mGlobals, null);//TODO 为什么用mLuaUserData.getmetatable()不行 //对外数据封装,必须使用LuaTable final UDLuaTable pageData = new UDLuaTable(page); final View pageView = pageData.getView(); //初始化View initView(pageData, mPosInViewPager); //绘制 <SUF> renderView(pageData, mPosInViewPager); return pageView; } /** * 调用LuaView的Init方法进行Cell的初始化 * * @param position * @return */ private void initView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageInit(page, position); this.mGlobals.restoreContainer(); } /** * 调用LuaView的Layout方法进行数据填充 * * @param page * @param position */ private void renderView(UDLuaTable page, int position) { this.mGlobals.saveContainer(page.getLVViewGroup()); this.mInitProps.callPageLayout(page, position); this.mGlobals.restoreContainer(); } /** * 创建 cell 的布局 * * @return */ private LVViewGroup createPageLayout() { return new LVViewGroup(mGlobals, mInitProps.getmetatable(), null); } }
false
661
3
765
4
779
3
765
4
945
7
false
false
false
false
false
true
6696_4
package com.ql.util.express; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.ql.util.express.config.QLExpressTimer; import com.ql.util.express.exception.QLException; import com.ql.util.express.exception.QLTimeoutException; import com.ql.util.express.instruction.FunctionInstructionSet; import com.ql.util.express.instruction.OperateDataCacheManager; import com.ql.util.express.instruction.detail.Instruction; import com.ql.util.express.instruction.detail.InstructionCallSelfDefineFunction; import com.ql.util.express.instruction.detail.InstructionConstData; import com.ql.util.express.instruction.detail.InstructionLoadAttr; import com.ql.util.express.instruction.detail.InstructionNewVirClass; import com.ql.util.express.instruction.detail.InstructionOperator; import com.ql.util.express.instruction.opdata.OperateDataLocalVar; /** * 表达式执行编译后形成的指令集合 * * @author qhlhl2010@gmail.com */ public class InstructionSet { public static final String TYPE_CLASS = "VClass"; public static final String TYPE_FUNCTION = "function"; public static final String TYPE_MACRO = "macro"; private final String type; private String name; private String globeName; /** * 指令 */ private Instruction[] instructionList = new Instruction[0]; /** * 函数和宏定义 */ private final Map<String, FunctionInstructionSet> functionDefine = new HashMap<>(); /** * 为了增加性能,开始的时候缓存为数组 */ private Map<String, Object> cacheFunctionSet = null; private final List<ExportItem> exportVar = new ArrayList<>(); /** * 函数参数定义 */ private final List<OperateDataLocalVar> parameterList = new ArrayList<>(); public InstructionSet(String type) { this.type = type; } public String[] getOutFunctionNames() { Map<String, String> result = new TreeMap<>(); for (Instruction instruction : instructionList) { if (instruction instanceof InstructionCallSelfDefineFunction) { String functionName = ((InstructionCallSelfDefineFunction)instruction).getFunctionName(); if (!functionDefine.containsKey(functionName)) { result.put(functionName, null); } } } return result.keySet().toArray(new String[0]); } public String[] getVirClasses() { Map<String, String> result = new TreeMap<>(); for (Instruction instruction : instructionList) { if (instruction instanceof InstructionNewVirClass) { String functionName = ((InstructionNewVirClass)instruction).getClassName(); result.put(functionName, null); } } return result.keySet().toArray(new String[0]); } public String[] getOutAttrNames() throws Exception { Map<String, String> result = new TreeMap<>(); for (Instruction instruction : instructionList) { if (instruction instanceof InstructionLoadAttr) { if ("null".equals(((InstructionLoadAttr)instruction).getAttrName())) { continue; } result.put(((InstructionLoadAttr)instruction).getAttrName(), null); } } //剔除本地变量定义和别名定义 for (int i = 0; i < instructionList.length; i++) { Instruction instruction = instructionList[i]; if (instruction instanceof InstructionOperator) { String opName = ((InstructionOperator)instruction).getOperator().getName(); //addOperator(op)中op.name有可能为空 if (opName != null) { if ("def".equalsIgnoreCase(opName) || "exportDef".equalsIgnoreCase(opName)) { String varLocalName = (String)((InstructionConstData)instructionList[i - 1]).getOperateData() .getObject(null); result.remove(varLocalName); } else if ("alias".equalsIgnoreCase(opName) || "exportAlias".equalsIgnoreCase(opName)) { String varLocalName = (String)((InstructionConstData)instructionList[i - 2]).getOperateData() .getObject(null); result.remove(varLocalName); } } } } return result.keySet().toArray(new String[0]); } /** * 添加指令,为了提高运行期的效率,指令集用数组存储 * * @param item */ private void addArrayItem(Instruction item) { Instruction[] newArray = new Instruction[this.instructionList.length + 1]; System.arraycopy(this.instructionList, 0, newArray, 0, this.instructionList.length); newArray[this.instructionList.length] = item; this.instructionList = newArray; } /** * 插入数据 * * @param point * @param item */ private void insertArrayItem(int point, Instruction item) { Instruction[] newArray = new Instruction[this.instructionList.length + 1]; System.arraycopy(this.instructionList, 0, newArray, 0, point); System.arraycopy(this.instructionList, point, newArray, point + 1, this.instructionList.length - point); newArray[point] = item; this.instructionList = newArray; } /** * @param environment * @param context * @param errorList * @param isReturnLastData 是否最后的结果,主要是在执行宏定义的时候需要 * @return * @throws Exception */ public CallResult execute(RunEnvironment environment, InstructionSetContext context, List<String> errorList, boolean isReturnLastData) throws Exception { //将函数export到上下文中,这儿就是重入也没有关系,不需要考虑并发 if (cacheFunctionSet == null) { Map<String, Object> tempMap = new HashMap<>(); for (FunctionInstructionSet s : this.functionDefine.values()) { tempMap.put(s.name, s.instructionSet); } cacheFunctionSet = tempMap; } context.addSymbol(cacheFunctionSet); this.executeInnerOriginalInstruction(environment, errorList); // 是在执行完所有的指令后结束的代码 if (!environment.isExit()) { if (environment.getDataStackSize() > 0) { OperateData tmpObject = environment.pop(); if (tmpObject == null) { environment.quitExpress(null); } else { if (isReturnLastData) { if (tmpObject.getType(context) != null && tmpObject.getType(context).equals(void.class)) { environment.quitExpress(null); } else { environment.quitExpress(tmpObject.getObject(context)); } } else { environment.quitExpress(tmpObject); } } } } if (environment.getDataStackSize() > 1) { throw new QLException("在表达式执行完毕后,堆栈中还存在多个数据"); } return OperateDataCacheManager.fetchCallResult(environment.getReturnValue(), environment.isExit()); } public void executeInnerOriginalInstruction(RunEnvironment environment, List<String> errorList) throws Exception { Instruction instruction = null; try { while (environment.programPoint < this.instructionList.length) { if (environment.isExecuteTimeout()) { throw new QLTimeoutException("运行QLExpress脚本的下一条指令超过了限定时间:" + environment.getExecuteTimeOut().getTimeoutMillis() + "ms"); } instruction = this.instructionList[environment.programPoint]; instruction.execute(environment, errorList); } } catch (Exception e) { throw e; } } public int getInstructionLength() { return this.instructionList.length; } public void addMacroDefine(String macroName, FunctionInstructionSet functionInstructionSet) { this.functionDefine.put(macroName, functionInstructionSet); } public FunctionInstructionSet getMacroDefine(String macroName) { return this.functionDefine.get(macroName); } public FunctionInstructionSet[] getFunctionInstructionSets() { return this.functionDefine.values().toArray(new FunctionInstructionSet[0]); } public void addExportDef(ExportItem e) { this.exportVar.add(e); } public List<ExportItem> getExportDef() { return new ArrayList<>(this.exportVar); } public OperateDataLocalVar[] getParameters() { return this.parameterList.toArray(new OperateDataLocalVar[0]); } public void addParameter(OperateDataLocalVar localVar) { this.parameterList.add(localVar); } public void addInstruction(Instruction instruction) { this.addArrayItem(instruction); } public void insertInstruction(int point, Instruction instruction) { this.insertArrayItem(point, instruction); } public Instruction getInstruction(int point) { return this.instructionList[point]; } public int getCurrentPoint() { return this.instructionList.length - 1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGlobeName() { return globeName; } public void setGlobeName(String globeName) { this.globeName = globeName; } public boolean hasMain() { return this.instructionList.length > 0; } public String getType() { return type; } public void appendSpace(StringBuilder stringBuilder, int level) { for (int i = 0; i < level; i++) { stringBuilder.append(" "); } } @Override public String toString() { return "\n" + toString(0); } public String toString(int level) { try { StringBuilder stringBuilder = new StringBuilder(); // 输出宏定义 for (FunctionInstructionSet set : this.functionDefine.values()) { appendSpace(stringBuilder, level); stringBuilder.append(set.type).append(":").append(set.name).append("("); for (int i = 0; i < set.instructionSet.parameterList.size(); i++) { OperateDataLocalVar operateDataLocalVar = set.instructionSet.parameterList.get(i); if (i > 0) { stringBuilder.append(","); } stringBuilder.append(operateDataLocalVar.getType(null).getName()).append(" ") .append(operateDataLocalVar.getName()); } stringBuilder.append("){\n"); stringBuilder.append(set.instructionSet.toString(level + 1)); appendSpace(stringBuilder, level); stringBuilder.append("}\n"); } for (int i = 0; i < this.instructionList.length; i++) { appendSpace(stringBuilder, level); stringBuilder.append(i + 1).append(":").append(this.instructionList[i]).append("\n"); } return stringBuilder.toString(); } catch (Exception e) { throw new RuntimeException(e); } } }
alibaba/QLExpress
src/main/java/com/ql/util/express/InstructionSet.java
2,568
/** * 函数参数定义 */
block_comment
zh-cn
package com.ql.util.express; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.ql.util.express.config.QLExpressTimer; import com.ql.util.express.exception.QLException; import com.ql.util.express.exception.QLTimeoutException; import com.ql.util.express.instruction.FunctionInstructionSet; import com.ql.util.express.instruction.OperateDataCacheManager; import com.ql.util.express.instruction.detail.Instruction; import com.ql.util.express.instruction.detail.InstructionCallSelfDefineFunction; import com.ql.util.express.instruction.detail.InstructionConstData; import com.ql.util.express.instruction.detail.InstructionLoadAttr; import com.ql.util.express.instruction.detail.InstructionNewVirClass; import com.ql.util.express.instruction.detail.InstructionOperator; import com.ql.util.express.instruction.opdata.OperateDataLocalVar; /** * 表达式执行编译后形成的指令集合 * * @author qhlhl2010@gmail.com */ public class InstructionSet { public static final String TYPE_CLASS = "VClass"; public static final String TYPE_FUNCTION = "function"; public static final String TYPE_MACRO = "macro"; private final String type; private String name; private String globeName; /** * 指令 */ private Instruction[] instructionList = new Instruction[0]; /** * 函数和宏定义 */ private final Map<String, FunctionInstructionSet> functionDefine = new HashMap<>(); /** * 为了增加性能,开始的时候缓存为数组 */ private Map<String, Object> cacheFunctionSet = null; private final List<ExportItem> exportVar = new ArrayList<>(); /** * 函数参 <SUF>*/ private final List<OperateDataLocalVar> parameterList = new ArrayList<>(); public InstructionSet(String type) { this.type = type; } public String[] getOutFunctionNames() { Map<String, String> result = new TreeMap<>(); for (Instruction instruction : instructionList) { if (instruction instanceof InstructionCallSelfDefineFunction) { String functionName = ((InstructionCallSelfDefineFunction)instruction).getFunctionName(); if (!functionDefine.containsKey(functionName)) { result.put(functionName, null); } } } return result.keySet().toArray(new String[0]); } public String[] getVirClasses() { Map<String, String> result = new TreeMap<>(); for (Instruction instruction : instructionList) { if (instruction instanceof InstructionNewVirClass) { String functionName = ((InstructionNewVirClass)instruction).getClassName(); result.put(functionName, null); } } return result.keySet().toArray(new String[0]); } public String[] getOutAttrNames() throws Exception { Map<String, String> result = new TreeMap<>(); for (Instruction instruction : instructionList) { if (instruction instanceof InstructionLoadAttr) { if ("null".equals(((InstructionLoadAttr)instruction).getAttrName())) { continue; } result.put(((InstructionLoadAttr)instruction).getAttrName(), null); } } //剔除本地变量定义和别名定义 for (int i = 0; i < instructionList.length; i++) { Instruction instruction = instructionList[i]; if (instruction instanceof InstructionOperator) { String opName = ((InstructionOperator)instruction).getOperator().getName(); //addOperator(op)中op.name有可能为空 if (opName != null) { if ("def".equalsIgnoreCase(opName) || "exportDef".equalsIgnoreCase(opName)) { String varLocalName = (String)((InstructionConstData)instructionList[i - 1]).getOperateData() .getObject(null); result.remove(varLocalName); } else if ("alias".equalsIgnoreCase(opName) || "exportAlias".equalsIgnoreCase(opName)) { String varLocalName = (String)((InstructionConstData)instructionList[i - 2]).getOperateData() .getObject(null); result.remove(varLocalName); } } } } return result.keySet().toArray(new String[0]); } /** * 添加指令,为了提高运行期的效率,指令集用数组存储 * * @param item */ private void addArrayItem(Instruction item) { Instruction[] newArray = new Instruction[this.instructionList.length + 1]; System.arraycopy(this.instructionList, 0, newArray, 0, this.instructionList.length); newArray[this.instructionList.length] = item; this.instructionList = newArray; } /** * 插入数据 * * @param point * @param item */ private void insertArrayItem(int point, Instruction item) { Instruction[] newArray = new Instruction[this.instructionList.length + 1]; System.arraycopy(this.instructionList, 0, newArray, 0, point); System.arraycopy(this.instructionList, point, newArray, point + 1, this.instructionList.length - point); newArray[point] = item; this.instructionList = newArray; } /** * @param environment * @param context * @param errorList * @param isReturnLastData 是否最后的结果,主要是在执行宏定义的时候需要 * @return * @throws Exception */ public CallResult execute(RunEnvironment environment, InstructionSetContext context, List<String> errorList, boolean isReturnLastData) throws Exception { //将函数export到上下文中,这儿就是重入也没有关系,不需要考虑并发 if (cacheFunctionSet == null) { Map<String, Object> tempMap = new HashMap<>(); for (FunctionInstructionSet s : this.functionDefine.values()) { tempMap.put(s.name, s.instructionSet); } cacheFunctionSet = tempMap; } context.addSymbol(cacheFunctionSet); this.executeInnerOriginalInstruction(environment, errorList); // 是在执行完所有的指令后结束的代码 if (!environment.isExit()) { if (environment.getDataStackSize() > 0) { OperateData tmpObject = environment.pop(); if (tmpObject == null) { environment.quitExpress(null); } else { if (isReturnLastData) { if (tmpObject.getType(context) != null && tmpObject.getType(context).equals(void.class)) { environment.quitExpress(null); } else { environment.quitExpress(tmpObject.getObject(context)); } } else { environment.quitExpress(tmpObject); } } } } if (environment.getDataStackSize() > 1) { throw new QLException("在表达式执行完毕后,堆栈中还存在多个数据"); } return OperateDataCacheManager.fetchCallResult(environment.getReturnValue(), environment.isExit()); } public void executeInnerOriginalInstruction(RunEnvironment environment, List<String> errorList) throws Exception { Instruction instruction = null; try { while (environment.programPoint < this.instructionList.length) { if (environment.isExecuteTimeout()) { throw new QLTimeoutException("运行QLExpress脚本的下一条指令超过了限定时间:" + environment.getExecuteTimeOut().getTimeoutMillis() + "ms"); } instruction = this.instructionList[environment.programPoint]; instruction.execute(environment, errorList); } } catch (Exception e) { throw e; } } public int getInstructionLength() { return this.instructionList.length; } public void addMacroDefine(String macroName, FunctionInstructionSet functionInstructionSet) { this.functionDefine.put(macroName, functionInstructionSet); } public FunctionInstructionSet getMacroDefine(String macroName) { return this.functionDefine.get(macroName); } public FunctionInstructionSet[] getFunctionInstructionSets() { return this.functionDefine.values().toArray(new FunctionInstructionSet[0]); } public void addExportDef(ExportItem e) { this.exportVar.add(e); } public List<ExportItem> getExportDef() { return new ArrayList<>(this.exportVar); } public OperateDataLocalVar[] getParameters() { return this.parameterList.toArray(new OperateDataLocalVar[0]); } public void addParameter(OperateDataLocalVar localVar) { this.parameterList.add(localVar); } public void addInstruction(Instruction instruction) { this.addArrayItem(instruction); } public void insertInstruction(int point, Instruction instruction) { this.insertArrayItem(point, instruction); } public Instruction getInstruction(int point) { return this.instructionList[point]; } public int getCurrentPoint() { return this.instructionList.length - 1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGlobeName() { return globeName; } public void setGlobeName(String globeName) { this.globeName = globeName; } public boolean hasMain() { return this.instructionList.length > 0; } public String getType() { return type; } public void appendSpace(StringBuilder stringBuilder, int level) { for (int i = 0; i < level; i++) { stringBuilder.append(" "); } } @Override public String toString() { return "\n" + toString(0); } public String toString(int level) { try { StringBuilder stringBuilder = new StringBuilder(); // 输出宏定义 for (FunctionInstructionSet set : this.functionDefine.values()) { appendSpace(stringBuilder, level); stringBuilder.append(set.type).append(":").append(set.name).append("("); for (int i = 0; i < set.instructionSet.parameterList.size(); i++) { OperateDataLocalVar operateDataLocalVar = set.instructionSet.parameterList.get(i); if (i > 0) { stringBuilder.append(","); } stringBuilder.append(operateDataLocalVar.getType(null).getName()).append(" ") .append(operateDataLocalVar.getName()); } stringBuilder.append("){\n"); stringBuilder.append(set.instructionSet.toString(level + 1)); appendSpace(stringBuilder, level); stringBuilder.append("}\n"); } for (int i = 0; i < this.instructionList.length; i++) { appendSpace(stringBuilder, level); stringBuilder.append(i + 1).append(":").append(this.instructionList[i]).append("\n"); } return stringBuilder.toString(); } catch (Exception e) { throw new RuntimeException(e); } } }
false
2,340
10
2,568
8
2,761
10
2,568
8
3,200
14
false
false
false
false
false
true
65521_0
package com.alibaba.smart.framework.engine.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by 高海军 帝奇 74394 on 2019-11-12 16:07. * * 用于标记这段代码可能是临时性方案,目前特别好的处理方法。相当于 WONT FIX . */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WorkAround { }
alibaba/SmartEngine
core/src/main/java/com/alibaba/smart/framework/engine/annotation/WorkAround.java
169
/** * Created by 高海军 帝奇 74394 on 2019-11-12 16:07. * * 用于标记这段代码可能是临时性方案,目前特别好的处理方法。相当于 WONT FIX . */
block_comment
zh-cn
package com.alibaba.smart.framework.engine.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Cre <SUF>*/ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WorkAround { }
false
129
61
169
71
153
60
169
71
202
88
false
false
false
false
false
true
7847_6
/* * Copyright 2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.android.alpha; import android.os.Handler; import android.os.Looper; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; /** * <p>这个类将一个个关联的{@code Task},组织成PERT网路图的方式进行执行。可以通过{@link Project.Builder} * 将{@code Task}组装成完整的{@code Project},该{@code Project}可以直接执行,也可以嵌套在另外一个{@code Project} * 中作为其中一个{@code Task}执行。</p> * * Created by zhangshuliang.zsl on 15/8/18. */ public abstract class Task { /** * {@code Task}执行状态,{@code Task}尚未执行 */ public static final int STATE_IDLE = 0; /** * {@code Task}执行状态,{@code Task}正在执行中 */ public static final int STATE_RUNNING = 1; /** * {@code Task}执行状态,{@code Task}已经执行完毕 */ public static final int STATE_FINISHED = 2; /** * {@code Task}执行状态,{@code Task}等待执行 */ public static final int STATE_WAIT = 3; /** * 默认的执行优先级 */ public static final int DEFAULT_EXECUTE_PRIORITY = 0; /** * 执行优先级,由于线程池是有限的,对于同一时机执行的task,其执行也可能存在先后顺序。值越小,越先执行。 */ private int mExecutePriority = DEFAULT_EXECUTE_PRIORITY; /** * 线程优先级,优先级高,则能分配到更多的cpu时间 */ private int mThreadPriority; private static ExecutorService sExecutor = AlphaConfig.getExecutor(); private static Handler sHandler = new Handler(Looper.getMainLooper()); /** * 是否在主线程执行 */ private boolean mIsInUiThread; private Runnable mInternalRunnable; protected String mName; private List<OnTaskFinishListener> mTaskFinishListeners = new ArrayList<OnTaskFinishListener>(); private volatile int mCurrentState = STATE_IDLE; private List<Task> mSuccessorList = new ArrayList<Task>(); protected Set<Task> mPredecessorSet = new HashSet<Task>(); private ExecuteMonitor mTaskExecuteMonitor; /** * 构造{@code Task}对象,必须要传入{@code name},便于确定当前是在哪一个任务中。该{@code Task}在异步线程 * 中执行。 * * @param name {@code Task}名字 */ public Task(String name) { this(name, android.os.Process.THREAD_PRIORITY_DEFAULT); } /** * 构造{@code Task}对象。 * * @param name {@code Task}名字 * @param threadPriority 线程优先级。对应的是{@link android.os.Process}里面的定义, * 例如{@link android.os.Process#THREAD_PRIORITY_DEFAULT}, * {@link android.os.Process#THREAD_PRIORITY_BACKGROUND}, * {@link android.os.Process#THREAD_PRIORITY_FOREGROUND}等。 */ public Task(String name, int threadPriority) { mName = name; mThreadPriority = threadPriority; } /** * 构造{@code Task}对象。 * * @param name {@code Task}名字 * @param isInUiThread 是否在UI线程执行,true表示在UI线程执行,false表示在非UI线程执行,默认在非UI线程执行。 * <strong>注意:如果在UI线程执行,则不能再使用{@link AlphaManager#waitUntilFinish()},否则会造成死锁。</strong> */ public Task(String name, boolean isInUiThread) { mName = name; mIsInUiThread = isInUiThread; } //============================================================================================== // PUBLIC API //============================================================================================== /** * 执行当前{@code Task}的任务,这里会调用用户自定义的{@link #run()}。 */ public synchronized void start() { if (mCurrentState != STATE_IDLE) { throw new RuntimeException("You try to run task " + mName + " twice, is there a circular dependency?"); } switchState(STATE_WAIT); if (mInternalRunnable == null) { mInternalRunnable = new Runnable() { @Override public void run() { android.os.Process.setThreadPriority(mThreadPriority); long startTime = System.currentTimeMillis(); switchState(STATE_RUNNING); Task.this.run(); switchState(STATE_FINISHED); long finishTime = System.currentTimeMillis(); recordTime((finishTime - startTime)); notifyFinished(); recycle(); } }; } if (mIsInUiThread) { sHandler.post(mInternalRunnable); } else { sExecutor.execute(mInternalRunnable); } } /** * <p>增加{@code Task}执行结束的监听,当该{@code Task}执行结束时,会回调 * {@link Task.OnTaskFinishListener#onTaskFinish(String)}。</p> * <strong>注意:</strong>回调函数在{@code Task}所在线程中回调,注意线程安全。 * * @param listener 监听{@code Task}执行结束的{@code listener} */ public void addOnTaskFinishListener(OnTaskFinishListener listener) { if (!mTaskFinishListeners.contains(listener)) { mTaskFinishListeners.add(listener); } } /** * 在其中实现该{@code Task}具体执行的逻辑。<br> * <strong>注意:</strong>该函数应该只由框架的{@link #start()}来调用。 */ public abstract void run(); /** * 查询当前该{@code Task}执行的状态。 * * @return 当前执行状态,状态码如下: * {@link #STATE_FINISHED}, {@link #STATE_IDLE}, {@link #STATE_RUNNING} */ public int getCurrentState() { return mCurrentState; } /** * 判断当前{@code Task}是否正在运行,即状态是否是{@link #STATE_RUNNING} * * @return {@code true}表示当前正在执行中,否则表示为执行或者执行已经结束。 */ public boolean isRunning() { return mCurrentState == STATE_RUNNING; } /** * 判断当前{@code Task}已经完成,即状态是否是{@link #STATE_FINISHED} * * @return {@code true}表示已经执行结束,否则表示尚未执行或者正在执行中。 */ public boolean isFinished() { return mCurrentState == STATE_FINISHED; } /** * 设置执行优先级。对于<strong>同一时机</strong>执行的{@code task},由于线程池的线程数有限, * 部分{@code task}可能不能立即执行,所以对于此种情况,需要设置执行顺序优先级。值越小,越先执行。 * * @param executePriority 执行优先级。数字越大,优先级越高,执行时机越早。 */ public void setExecutePriority(int executePriority) { mExecutePriority = executePriority; } /** * @return 同一时机执行的task的执行顺序优先级。数字越小,执行时机越早。 */ public int getExecutePriority() { return mExecutePriority; } //============================================================================================== // INNER API //============================================================================================== /** * 增加紧前{@code Task} * * @param task 紧前{@code Task} */ /*package*/ void addPredecessor(Task task) { mPredecessorSet.add(task); } /** * 移除紧前{@code Task} * * @param task 紧前{@code Task} */ /*package*/ void removePredecessor(Task task) { mPredecessorSet.remove(task); } /** * 增加紧后{@code Task} * * @param task 紧后{@code Task} */ /*package*/ void addSuccessor(Task task) { if (task == this) { throw new RuntimeException("A task should not after itself."); } task.addPredecessor(this); mSuccessorList.add(task); } /** * 通知所有紧后{@code Task}以及{@code OnTaskFinishListener}自己执行完成。 */ /*package*/ void notifyFinished() { if (!mSuccessorList.isEmpty()) { AlphaUtils.sort(mSuccessorList); for (Task task : mSuccessorList) { task.onPredecessorFinished(this); } } if (!mTaskFinishListeners.isEmpty()) { for (OnTaskFinishListener listener : mTaskFinishListeners) { listener.onTaskFinish(mName); } mTaskFinishListeners.clear(); } } /** * 某一个紧前{@code Task}执行完成,如果所有的紧前{@code Task}都执行完成,则调用自己的{@link #start()} * 执行自己的任务。<br> * 该函数由紧前{@code Task}的{@link #notifyFinished()}来调用。 */ /*package*/ synchronized void onPredecessorFinished(Task beforeTask) { if (mPredecessorSet.isEmpty()) { return; } mPredecessorSet.remove(beforeTask); if (mPredecessorSet.isEmpty()) { start(); } } /*package*/ void setName(String name) { mName = name; } /*package*/ void setThreadPriority(int threadPriority) { mThreadPriority = threadPriority; } /*package*/ void setExecuteMonitor(ExecuteMonitor monitor) { mTaskExecuteMonitor = monitor; } /** * 这个函数在执行结束时被调用,及时释放占用的资源 */ /*package*/ void recycle() { mSuccessorList.clear(); mTaskFinishListeners.clear(); } protected void recordTime(long costTime) { if (mTaskExecuteMonitor != null) { mTaskExecuteMonitor.record(mName, costTime); } } //============================================================================================== // PRIVATE METHOD //============================================================================================== private void switchState(int state) { mCurrentState = state; } //============================================================================================== // INNER CLASSES //============================================================================================== /** * 一个task完成时的回调 */ public interface OnTaskFinishListener { /** * 当task完成时,会回调这个函数。 * <strong>注意:</strong>该函数会在{@code Task}所在线程中回调,注意线程安全。 * * @param taskName 当前结束的{@code Task}名称 */ public void onTaskFinish(String taskName); } }
alibaba/alpha
alpha/src/main/java/com/alibaba/android/alpha/Task.java
2,640
/** * 默认的执行优先级 */
block_comment
zh-cn
/* * Copyright 2018 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.android.alpha; import android.os.Handler; import android.os.Looper; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; /** * <p>这个类将一个个关联的{@code Task},组织成PERT网路图的方式进行执行。可以通过{@link Project.Builder} * 将{@code Task}组装成完整的{@code Project},该{@code Project}可以直接执行,也可以嵌套在另外一个{@code Project} * 中作为其中一个{@code Task}执行。</p> * * Created by zhangshuliang.zsl on 15/8/18. */ public abstract class Task { /** * {@code Task}执行状态,{@code Task}尚未执行 */ public static final int STATE_IDLE = 0; /** * {@code Task}执行状态,{@code Task}正在执行中 */ public static final int STATE_RUNNING = 1; /** * {@code Task}执行状态,{@code Task}已经执行完毕 */ public static final int STATE_FINISHED = 2; /** * {@code Task}执行状态,{@code Task}等待执行 */ public static final int STATE_WAIT = 3; /** * 默认的 <SUF>*/ public static final int DEFAULT_EXECUTE_PRIORITY = 0; /** * 执行优先级,由于线程池是有限的,对于同一时机执行的task,其执行也可能存在先后顺序。值越小,越先执行。 */ private int mExecutePriority = DEFAULT_EXECUTE_PRIORITY; /** * 线程优先级,优先级高,则能分配到更多的cpu时间 */ private int mThreadPriority; private static ExecutorService sExecutor = AlphaConfig.getExecutor(); private static Handler sHandler = new Handler(Looper.getMainLooper()); /** * 是否在主线程执行 */ private boolean mIsInUiThread; private Runnable mInternalRunnable; protected String mName; private List<OnTaskFinishListener> mTaskFinishListeners = new ArrayList<OnTaskFinishListener>(); private volatile int mCurrentState = STATE_IDLE; private List<Task> mSuccessorList = new ArrayList<Task>(); protected Set<Task> mPredecessorSet = new HashSet<Task>(); private ExecuteMonitor mTaskExecuteMonitor; /** * 构造{@code Task}对象,必须要传入{@code name},便于确定当前是在哪一个任务中。该{@code Task}在异步线程 * 中执行。 * * @param name {@code Task}名字 */ public Task(String name) { this(name, android.os.Process.THREAD_PRIORITY_DEFAULT); } /** * 构造{@code Task}对象。 * * @param name {@code Task}名字 * @param threadPriority 线程优先级。对应的是{@link android.os.Process}里面的定义, * 例如{@link android.os.Process#THREAD_PRIORITY_DEFAULT}, * {@link android.os.Process#THREAD_PRIORITY_BACKGROUND}, * {@link android.os.Process#THREAD_PRIORITY_FOREGROUND}等。 */ public Task(String name, int threadPriority) { mName = name; mThreadPriority = threadPriority; } /** * 构造{@code Task}对象。 * * @param name {@code Task}名字 * @param isInUiThread 是否在UI线程执行,true表示在UI线程执行,false表示在非UI线程执行,默认在非UI线程执行。 * <strong>注意:如果在UI线程执行,则不能再使用{@link AlphaManager#waitUntilFinish()},否则会造成死锁。</strong> */ public Task(String name, boolean isInUiThread) { mName = name; mIsInUiThread = isInUiThread; } //============================================================================================== // PUBLIC API //============================================================================================== /** * 执行当前{@code Task}的任务,这里会调用用户自定义的{@link #run()}。 */ public synchronized void start() { if (mCurrentState != STATE_IDLE) { throw new RuntimeException("You try to run task " + mName + " twice, is there a circular dependency?"); } switchState(STATE_WAIT); if (mInternalRunnable == null) { mInternalRunnable = new Runnable() { @Override public void run() { android.os.Process.setThreadPriority(mThreadPriority); long startTime = System.currentTimeMillis(); switchState(STATE_RUNNING); Task.this.run(); switchState(STATE_FINISHED); long finishTime = System.currentTimeMillis(); recordTime((finishTime - startTime)); notifyFinished(); recycle(); } }; } if (mIsInUiThread) { sHandler.post(mInternalRunnable); } else { sExecutor.execute(mInternalRunnable); } } /** * <p>增加{@code Task}执行结束的监听,当该{@code Task}执行结束时,会回调 * {@link Task.OnTaskFinishListener#onTaskFinish(String)}。</p> * <strong>注意:</strong>回调函数在{@code Task}所在线程中回调,注意线程安全。 * * @param listener 监听{@code Task}执行结束的{@code listener} */ public void addOnTaskFinishListener(OnTaskFinishListener listener) { if (!mTaskFinishListeners.contains(listener)) { mTaskFinishListeners.add(listener); } } /** * 在其中实现该{@code Task}具体执行的逻辑。<br> * <strong>注意:</strong>该函数应该只由框架的{@link #start()}来调用。 */ public abstract void run(); /** * 查询当前该{@code Task}执行的状态。 * * @return 当前执行状态,状态码如下: * {@link #STATE_FINISHED}, {@link #STATE_IDLE}, {@link #STATE_RUNNING} */ public int getCurrentState() { return mCurrentState; } /** * 判断当前{@code Task}是否正在运行,即状态是否是{@link #STATE_RUNNING} * * @return {@code true}表示当前正在执行中,否则表示为执行或者执行已经结束。 */ public boolean isRunning() { return mCurrentState == STATE_RUNNING; } /** * 判断当前{@code Task}已经完成,即状态是否是{@link #STATE_FINISHED} * * @return {@code true}表示已经执行结束,否则表示尚未执行或者正在执行中。 */ public boolean isFinished() { return mCurrentState == STATE_FINISHED; } /** * 设置执行优先级。对于<strong>同一时机</strong>执行的{@code task},由于线程池的线程数有限, * 部分{@code task}可能不能立即执行,所以对于此种情况,需要设置执行顺序优先级。值越小,越先执行。 * * @param executePriority 执行优先级。数字越大,优先级越高,执行时机越早。 */ public void setExecutePriority(int executePriority) { mExecutePriority = executePriority; } /** * @return 同一时机执行的task的执行顺序优先级。数字越小,执行时机越早。 */ public int getExecutePriority() { return mExecutePriority; } //============================================================================================== // INNER API //============================================================================================== /** * 增加紧前{@code Task} * * @param task 紧前{@code Task} */ /*package*/ void addPredecessor(Task task) { mPredecessorSet.add(task); } /** * 移除紧前{@code Task} * * @param task 紧前{@code Task} */ /*package*/ void removePredecessor(Task task) { mPredecessorSet.remove(task); } /** * 增加紧后{@code Task} * * @param task 紧后{@code Task} */ /*package*/ void addSuccessor(Task task) { if (task == this) { throw new RuntimeException("A task should not after itself."); } task.addPredecessor(this); mSuccessorList.add(task); } /** * 通知所有紧后{@code Task}以及{@code OnTaskFinishListener}自己执行完成。 */ /*package*/ void notifyFinished() { if (!mSuccessorList.isEmpty()) { AlphaUtils.sort(mSuccessorList); for (Task task : mSuccessorList) { task.onPredecessorFinished(this); } } if (!mTaskFinishListeners.isEmpty()) { for (OnTaskFinishListener listener : mTaskFinishListeners) { listener.onTaskFinish(mName); } mTaskFinishListeners.clear(); } } /** * 某一个紧前{@code Task}执行完成,如果所有的紧前{@code Task}都执行完成,则调用自己的{@link #start()} * 执行自己的任务。<br> * 该函数由紧前{@code Task}的{@link #notifyFinished()}来调用。 */ /*package*/ synchronized void onPredecessorFinished(Task beforeTask) { if (mPredecessorSet.isEmpty()) { return; } mPredecessorSet.remove(beforeTask); if (mPredecessorSet.isEmpty()) { start(); } } /*package*/ void setName(String name) { mName = name; } /*package*/ void setThreadPriority(int threadPriority) { mThreadPriority = threadPriority; } /*package*/ void setExecuteMonitor(ExecuteMonitor monitor) { mTaskExecuteMonitor = monitor; } /** * 这个函数在执行结束时被调用,及时释放占用的资源 */ /*package*/ void recycle() { mSuccessorList.clear(); mTaskFinishListeners.clear(); } protected void recordTime(long costTime) { if (mTaskExecuteMonitor != null) { mTaskExecuteMonitor.record(mName, costTime); } } //============================================================================================== // PRIVATE METHOD //============================================================================================== private void switchState(int state) { mCurrentState = state; } //============================================================================================== // INNER CLASSES //============================================================================================== /** * 一个task完成时的回调 */ public interface OnTaskFinishListener { /** * 当task完成时,会回调这个函数。 * <strong>注意:</strong>该函数会在{@code Task}所在线程中回调,注意线程安全。 * * @param taskName 当前结束的{@code Task}名称 */ public void onTaskFinish(String taskName); } }
false
2,503
11
2,640
10
2,854
12
2,640
10
3,885
22
false
false
false
false
false
true
7357_3
package com.taobao.atlas.update.model; import android.taobao.atlas.runtime.RuntimeVariables; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by wuzhong on 2016/11/23. */ public class UpdateInfo implements Serializable { /** * 当前的客户端版本 */ public String baseVersion; /** * 更新后的客户端版本 */ public String updateVersion; public boolean dexPatch; public boolean lowDisk = false; /** * 更新的模块列表信息 */ public List<Item> updateBundles; public File workDir = new File(RuntimeVariables.androidApplication.getCacheDir(), "atlas_update"); /** * 更新的模块信息 */ public static class Item implements Serializable { public static final int PATCH_DYNAMIC_ = 0; public static final int PATCH_DEX_COLD = 1; public static final int PATCH_DEX_HOT = 2; public static final int PATCH_DEX_C_AND_H = 3; /** * 是不是主dex */ public boolean isMainDex; /** * bundle 的名称 */ public String name; /** * bundle 版本信息 */ // public String version; // /** // * bundle 的代码仓库对应的版本 // */ // public String srcVersion; public String unitTag; public String srcUnitTag; /** * this version is compatible with new app version * no need to update */ public boolean inherit = false; /** * 依赖的 bundle 列表 */ public List<String> dependency; public int patchType; public boolean resetHotPatch = false; public long dexpatchVersion = -1; public boolean reset = false; public static Item makeCopy(Item origin) { Item item = new Item(); item.isMainDex = origin.isMainDex; item.name = origin.name; item.unitTag = origin.unitTag; item.srcUnitTag = origin.srcUnitTag; item.inherit = origin.inherit; item.patchType = origin.patchType; item.dexpatchVersion = origin.dexpatchVersion; item.reset = origin.reset; item.resetHotPatch = origin.resetHotPatch; if (null != origin.dependency) { List<String> copyDependency = new ArrayList<>(origin.dependency.size()); copyDependency.addAll(origin.dependency); item.dependency = copyDependency; } return item; } } }
alibaba/atlas
atlas-update/src/main/java/com/taobao/atlas/update/model/UpdateInfo.java
613
/** * 更新的模块列表信息 */
block_comment
zh-cn
package com.taobao.atlas.update.model; import android.taobao.atlas.runtime.RuntimeVariables; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by wuzhong on 2016/11/23. */ public class UpdateInfo implements Serializable { /** * 当前的客户端版本 */ public String baseVersion; /** * 更新后的客户端版本 */ public String updateVersion; public boolean dexPatch; public boolean lowDisk = false; /** * 更新的 <SUF>*/ public List<Item> updateBundles; public File workDir = new File(RuntimeVariables.androidApplication.getCacheDir(), "atlas_update"); /** * 更新的模块信息 */ public static class Item implements Serializable { public static final int PATCH_DYNAMIC_ = 0; public static final int PATCH_DEX_COLD = 1; public static final int PATCH_DEX_HOT = 2; public static final int PATCH_DEX_C_AND_H = 3; /** * 是不是主dex */ public boolean isMainDex; /** * bundle 的名称 */ public String name; /** * bundle 版本信息 */ // public String version; // /** // * bundle 的代码仓库对应的版本 // */ // public String srcVersion; public String unitTag; public String srcUnitTag; /** * this version is compatible with new app version * no need to update */ public boolean inherit = false; /** * 依赖的 bundle 列表 */ public List<String> dependency; public int patchType; public boolean resetHotPatch = false; public long dexpatchVersion = -1; public boolean reset = false; public static Item makeCopy(Item origin) { Item item = new Item(); item.isMainDex = origin.isMainDex; item.name = origin.name; item.unitTag = origin.unitTag; item.srcUnitTag = origin.srcUnitTag; item.inherit = origin.inherit; item.patchType = origin.patchType; item.dexpatchVersion = origin.dexpatchVersion; item.reset = origin.reset; item.resetHotPatch = origin.resetHotPatch; if (null != origin.dependency) { List<String> copyDependency = new ArrayList<>(origin.dependency.size()); copyDependency.addAll(origin.dependency); item.dependency = copyDependency; } return item; } } }
false
563
11
613
10
668
12
613
10
780
19
false
false
false
false
false
true
59705_18
package com.alibaba.pokemon.bulbasaur.core; import com.alibaba.pokemon.bulbasaur.core.model.KeyWords; import com.alibaba.pokemon.bulbasaur.core.model.Definition; import com.alibaba.pokemon.bulbasaur.core.model.StateLike; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * 一个流程实例 ,与状态绑定,非单例 * * @author yunche.ch@taobao.com * @since 2012-12-11 上午10:23:39 */ public class Machine { private final static Logger logger = LoggerFactory.getLogger(Machine.class); // 上下文 protected Map<String, Object> context = new HashMap<String, Object>(); // 当前节点 protected String currentStateName = null; // 流程定义 protected Definition definition = null; private Place place; /** * protected的构造方法,不对外开放,请使用newInstance方法获取实例 * * @param processName 流程名 * @param processVersion 流程版本号 */ protected Machine(String processName, int processVersion, Place place) { if (place == null) { place = Bulbasaur.getInnerBeanFactory().getBean("place", Place.class); } // 要单例 this.place = place; definition = place.getDefinition(processName, processVersion); currentStateName = definition.getFirst(); context.put(KeyWords.CURRENT_PROCESS_NAME, definition.getName()); context.put(KeyWords.CURRENT_STATE_NAME, currentStateName); } /** * 返回一个只读版本的上下文map,所有在此返回上的修改都是无效的 * * @return unmodifiableMap */ public Map<String, Object> getContext() { // 返回只读的context 版本 return Collections.unmodifiableMap(context); } // run from current state public void run() { run(currentStateName); } public void run(String stateName) { run(stateName, null); } public void run(String stateName, String outGoing) { if (CoreModule.getInstance().isShutDown()) { throw new IllegalStateException("bulbasaur is shutdown now, no more machine request allowed"); } // 查找现在的状态 StateLike currentState = run0_findCurrent(stateName); while (currentState != null) { // 开始执行 logger.debug("run state:" + currentState.getStateName()); if (StringUtils.isNotBlank(outGoing)) { currentState.setOutGoing(outGoing); outGoing = null; } Result result; try { result = run_atom(currentState); } catch (RuntimeException e) { // 如果出错了 要把状态回滚回去 currentStateName = currentState.getStateName(); context.put(KeyWords.CURRENT_STATE_NAME, currentStateName); throw e; } if (result.needContinue()) { // 如果需要继续执行 就获取下一个节点作为当前节点 如果流程已经结束 那么这里获取到的是null currentState = result.getState(); } else { // 否则直接置为null currentState = null; } } } /** * 做事务的时候,原子性,子类中重写 * * @param currentState * @return Result * @since 2012-12-27 */ protected Result run_atom(StateLike currentState) { return run0(currentState); } /** * 一个节点进来,先执行自己的execute方法,再算出下一个节点,并执行下一个节点的prepare方法 * * @param currentState * @return Result * @since 2012-12-12 */ final protected Result run0(StateLike currentState) { // setp1:执行当前节点的execute 方法 if (!run0_execute(currentState)) { // 执行失败 logger.error("节点的execute方法执行失败!节点:" + currentState.getStateName()); // 出错 暂停执行 return new Result(false); } else { // 执行完本次节点,替换成下一个节点,并把下一个节点的 prepare执行掉 StateLike nextState = run0_calcNext(currentState); if (nextState == null) { // 没有下一个节点 意味着流程结束了 但也是正常状态 return new Result(true); } else { currentStateName = nextState.getStateName(); context.put(KeyWords.CURRENT_STATE_NAME, currentStateName); // 执行下一个节点的prepare方法 return new Result(run0_prepare(nextState), nextState); } } } /** * 节点前置方法 * * @return void * @author: yunche.ch@taobao.com * @since 2012-12-12 下午9:19:29 */ protected boolean run0_prepare(StateLike currentState) { Result result = currentState.prepare(context); // merge 下返回的context mergeContext(result.getModels()); return result.needContinue(); } /** * 将执行的结果merge到context * * @return void * @author: yunche.ch@taobao.com * @since 2012-12-14 下午02:24:03 */ protected Map<String, Object> mergeContext(Map<String, Object> incrMap) { if (incrMap != null && !incrMap.isEmpty() && incrMap != context) { context.putAll(incrMap); } return context; } /** * 计算下一个节点 * * @return void * @throws Throwable * @author: yunche.ch@taobao.com * @since 2012-12-12 下午8:51:48 */ protected StateLike run0_calcNext(StateLike currentState) { //判断是否有直接跳转 String next = null; if (currentState.getJumpTo() != null) { next = currentState.getJumpTo(); } else { next = currentState.willGo(context); } if (!StringUtils.isBlank(next)) { // 不为空,则有下一节点 return definition.getState(next); } return null; } /** * 节点execute方法 * * @return boolean * @throws Throwable * @author: yunche.ch@taobao.com * @since 2012-12-12 下午8:22:53 */ protected boolean run0_execute(StateLike currentState) { // 执行当前节点 Result result = currentState.execute(context); mergeContext(result.getModels()); return result.needContinue(); } /** * 获得当前节点 * * @return State * @author: yunche.ch@taobao.com * @since 2012-12-11 下午8:57:45 */ protected StateLike run0_findCurrent(String stateName) { return definition.getState(stateName); } public String getProcessName() { return definition.getName(); } public int getProcessVersion() { return definition.getVersion(); } public Definition getDefinition() { return definition; } public String getCurrentStateName() { return currentStateName; } // CRUD context start public void addContext(String key, Object value) { this.context.put(key, value); } public void addContext(Map<String, Object> map) { this.context.putAll(map); } public void removeContext(String key) { this.context.remove(key); } public Object getContext(String key) { return context.get(key); } }
alibaba/bulbasaur
core/src/main/java/com/alibaba/pokemon/bulbasaur/core/Machine.java
1,904
// 出错 暂停执行
line_comment
zh-cn
package com.alibaba.pokemon.bulbasaur.core; import com.alibaba.pokemon.bulbasaur.core.model.KeyWords; import com.alibaba.pokemon.bulbasaur.core.model.Definition; import com.alibaba.pokemon.bulbasaur.core.model.StateLike; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * 一个流程实例 ,与状态绑定,非单例 * * @author yunche.ch@taobao.com * @since 2012-12-11 上午10:23:39 */ public class Machine { private final static Logger logger = LoggerFactory.getLogger(Machine.class); // 上下文 protected Map<String, Object> context = new HashMap<String, Object>(); // 当前节点 protected String currentStateName = null; // 流程定义 protected Definition definition = null; private Place place; /** * protected的构造方法,不对外开放,请使用newInstance方法获取实例 * * @param processName 流程名 * @param processVersion 流程版本号 */ protected Machine(String processName, int processVersion, Place place) { if (place == null) { place = Bulbasaur.getInnerBeanFactory().getBean("place", Place.class); } // 要单例 this.place = place; definition = place.getDefinition(processName, processVersion); currentStateName = definition.getFirst(); context.put(KeyWords.CURRENT_PROCESS_NAME, definition.getName()); context.put(KeyWords.CURRENT_STATE_NAME, currentStateName); } /** * 返回一个只读版本的上下文map,所有在此返回上的修改都是无效的 * * @return unmodifiableMap */ public Map<String, Object> getContext() { // 返回只读的context 版本 return Collections.unmodifiableMap(context); } // run from current state public void run() { run(currentStateName); } public void run(String stateName) { run(stateName, null); } public void run(String stateName, String outGoing) { if (CoreModule.getInstance().isShutDown()) { throw new IllegalStateException("bulbasaur is shutdown now, no more machine request allowed"); } // 查找现在的状态 StateLike currentState = run0_findCurrent(stateName); while (currentState != null) { // 开始执行 logger.debug("run state:" + currentState.getStateName()); if (StringUtils.isNotBlank(outGoing)) { currentState.setOutGoing(outGoing); outGoing = null; } Result result; try { result = run_atom(currentState); } catch (RuntimeException e) { // 如果出错了 要把状态回滚回去 currentStateName = currentState.getStateName(); context.put(KeyWords.CURRENT_STATE_NAME, currentStateName); throw e; } if (result.needContinue()) { // 如果需要继续执行 就获取下一个节点作为当前节点 如果流程已经结束 那么这里获取到的是null currentState = result.getState(); } else { // 否则直接置为null currentState = null; } } } /** * 做事务的时候,原子性,子类中重写 * * @param currentState * @return Result * @since 2012-12-27 */ protected Result run_atom(StateLike currentState) { return run0(currentState); } /** * 一个节点进来,先执行自己的execute方法,再算出下一个节点,并执行下一个节点的prepare方法 * * @param currentState * @return Result * @since 2012-12-12 */ final protected Result run0(StateLike currentState) { // setp1:执行当前节点的execute 方法 if (!run0_execute(currentState)) { // 执行失败 logger.error("节点的execute方法执行失败!节点:" + currentState.getStateName()); // 出错 <SUF> return new Result(false); } else { // 执行完本次节点,替换成下一个节点,并把下一个节点的 prepare执行掉 StateLike nextState = run0_calcNext(currentState); if (nextState == null) { // 没有下一个节点 意味着流程结束了 但也是正常状态 return new Result(true); } else { currentStateName = nextState.getStateName(); context.put(KeyWords.CURRENT_STATE_NAME, currentStateName); // 执行下一个节点的prepare方法 return new Result(run0_prepare(nextState), nextState); } } } /** * 节点前置方法 * * @return void * @author: yunche.ch@taobao.com * @since 2012-12-12 下午9:19:29 */ protected boolean run0_prepare(StateLike currentState) { Result result = currentState.prepare(context); // merge 下返回的context mergeContext(result.getModels()); return result.needContinue(); } /** * 将执行的结果merge到context * * @return void * @author: yunche.ch@taobao.com * @since 2012-12-14 下午02:24:03 */ protected Map<String, Object> mergeContext(Map<String, Object> incrMap) { if (incrMap != null && !incrMap.isEmpty() && incrMap != context) { context.putAll(incrMap); } return context; } /** * 计算下一个节点 * * @return void * @throws Throwable * @author: yunche.ch@taobao.com * @since 2012-12-12 下午8:51:48 */ protected StateLike run0_calcNext(StateLike currentState) { //判断是否有直接跳转 String next = null; if (currentState.getJumpTo() != null) { next = currentState.getJumpTo(); } else { next = currentState.willGo(context); } if (!StringUtils.isBlank(next)) { // 不为空,则有下一节点 return definition.getState(next); } return null; } /** * 节点execute方法 * * @return boolean * @throws Throwable * @author: yunche.ch@taobao.com * @since 2012-12-12 下午8:22:53 */ protected boolean run0_execute(StateLike currentState) { // 执行当前节点 Result result = currentState.execute(context); mergeContext(result.getModels()); return result.needContinue(); } /** * 获得当前节点 * * @return State * @author: yunche.ch@taobao.com * @since 2012-12-11 下午8:57:45 */ protected StateLike run0_findCurrent(String stateName) { return definition.getState(stateName); } public String getProcessName() { return definition.getName(); } public int getProcessVersion() { return definition.getVersion(); } public Definition getDefinition() { return definition; } public String getCurrentStateName() { return currentStateName; } // CRUD context start public void addContext(String key, Object value) { this.context.put(key, value); } public void addContext(Map<String, Object> map) { this.context.putAll(map); } public void removeContext(String key) { this.context.remove(key); } public Object getContext(String key) { return context.get(key); } }
false
1,752
9
1,904
9
2,003
6
1,904
9
2,448
15
false
false
false
false
false
true
27769_1
package com.alibaba.otter.canal.sink.entry.group; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.otter.canal.protocol.CanalEntry.EntryType; import com.alibaba.otter.canal.sink.exception.CanalSinkException; import com.alibaba.otter.canal.store.model.Event; /** * 相比于{@linkplain TimelineBarrier},增加了按事务支持,会按照事务进行分库合并处理 * * @author jianghang 2012-10-18 下午05:18:38 * @version 1.0.0 */ public class TimelineTransactionBarrier extends TimelineBarrier { private ThreadLocal<Boolean> inTransaction = ThreadLocal.withInitial(() -> false); /** * <pre> * 几种状态: * 0:初始状态,允许大家竞争 * 1: 事务数据处理中 * 2: 非事务数据处理中 * </pre> */ private AtomicInteger txState = new AtomicInteger(0); public TimelineTransactionBarrier(int groupSize){ super(groupSize); } public void await(Event event) throws InterruptedException { try { super.await(event); } catch (InterruptedException e) { // 出现线程中断,可能是因为关闭或者主备切换 // 主备切换对应的事务尾会未正常发送,需要强制设置为事务结束,允许其他队列通过 reset(); throw e; } } public void await(Event event, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { try { super.await(event, timeout, unit); } catch (InterruptedException e) { // 出现线程中断,可能是因为关闭或者主备切换 // 主备切换对应的事务尾会未正常发送,需要强制设置为事务结束,允许其他队列通过 reset(); throw e; } } public void clear(Event event) { super.clear(event); // 应该先判断2,再判断是否是事务尾,因为事务尾也可以导致txState的状态为2 // 如果先判断事务尾,那么2的状态可能永远没机会被修改了,系统出现死锁 // CanalSinkException被注释的代码是不是可以放开??我们内部使用的时候已经放开了,从代码逻辑的分析上以及实践效果来看,应该抛异常 if (txState.intValue() == 2) {// 非事务中 boolean result = txState.compareAndSet(2, 0); if (result == false) { throw new CanalSinkException("state is not correct in non-transaction"); } } else if (isTransactionEnd(event)) { inTransaction.set(false); // 事务结束并且已经成功写入store,清理标记,进入重新排队判断,允许新的事务进入 boolean result = txState.compareAndSet(1, 0); if (result == false) { throw new CanalSinkException("state is not correct in transaction"); } } } protected boolean isPermit(Event event, long state) { if (txState.intValue() == 1 && inTransaction.get()) { // 如果处于事务中,直接允许通过。因为事务头已经做过判断 return true; } else if (txState.intValue() == 0) { boolean result = super.isPermit(event, state); if (result) { // 可能第一条送过来的数据不为Begin,需要做判断处理,如果非事务,允许直接通过,比如DDL语句 if (isTransactionBegin(event)) { if (txState.compareAndSet(0, 1)) { inTransaction.set(true); return true; // 事务允许通过 } } else if (txState.compareAndSet(0, 2)) { // 非事务保护中 // 当基于zk-cursor启动的时候,拿到的第一个Event是TransactionEnd return true; // DDL/DCL/TransactionEnd允许通过 } } } return false; } public void interrupt() { super.interrupt(); reset(); } // 重新设置状态 private void reset() { inTransaction.remove(); txState.set(0);// 重新置位 } private boolean isTransactionBegin(Event event) { return event.getEntryType() == EntryType.TRANSACTIONBEGIN; } private boolean isTransactionEnd(Event event) { return event.getEntryType() == EntryType.TRANSACTIONEND; } }
alibaba/canal
sink/src/main/java/com/alibaba/otter/canal/sink/entry/group/TimelineTransactionBarrier.java
1,065
/** * <pre> * 几种状态: * 0:初始状态,允许大家竞争 * 1: 事务数据处理中 * 2: 非事务数据处理中 * </pre> */
block_comment
zh-cn
package com.alibaba.otter.canal.sink.entry.group; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.otter.canal.protocol.CanalEntry.EntryType; import com.alibaba.otter.canal.sink.exception.CanalSinkException; import com.alibaba.otter.canal.store.model.Event; /** * 相比于{@linkplain TimelineBarrier},增加了按事务支持,会按照事务进行分库合并处理 * * @author jianghang 2012-10-18 下午05:18:38 * @version 1.0.0 */ public class TimelineTransactionBarrier extends TimelineBarrier { private ThreadLocal<Boolean> inTransaction = ThreadLocal.withInitial(() -> false); /** * <pr <SUF>*/ private AtomicInteger txState = new AtomicInteger(0); public TimelineTransactionBarrier(int groupSize){ super(groupSize); } public void await(Event event) throws InterruptedException { try { super.await(event); } catch (InterruptedException e) { // 出现线程中断,可能是因为关闭或者主备切换 // 主备切换对应的事务尾会未正常发送,需要强制设置为事务结束,允许其他队列通过 reset(); throw e; } } public void await(Event event, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { try { super.await(event, timeout, unit); } catch (InterruptedException e) { // 出现线程中断,可能是因为关闭或者主备切换 // 主备切换对应的事务尾会未正常发送,需要强制设置为事务结束,允许其他队列通过 reset(); throw e; } } public void clear(Event event) { super.clear(event); // 应该先判断2,再判断是否是事务尾,因为事务尾也可以导致txState的状态为2 // 如果先判断事务尾,那么2的状态可能永远没机会被修改了,系统出现死锁 // CanalSinkException被注释的代码是不是可以放开??我们内部使用的时候已经放开了,从代码逻辑的分析上以及实践效果来看,应该抛异常 if (txState.intValue() == 2) {// 非事务中 boolean result = txState.compareAndSet(2, 0); if (result == false) { throw new CanalSinkException("state is not correct in non-transaction"); } } else if (isTransactionEnd(event)) { inTransaction.set(false); // 事务结束并且已经成功写入store,清理标记,进入重新排队判断,允许新的事务进入 boolean result = txState.compareAndSet(1, 0); if (result == false) { throw new CanalSinkException("state is not correct in transaction"); } } } protected boolean isPermit(Event event, long state) { if (txState.intValue() == 1 && inTransaction.get()) { // 如果处于事务中,直接允许通过。因为事务头已经做过判断 return true; } else if (txState.intValue() == 0) { boolean result = super.isPermit(event, state); if (result) { // 可能第一条送过来的数据不为Begin,需要做判断处理,如果非事务,允许直接通过,比如DDL语句 if (isTransactionBegin(event)) { if (txState.compareAndSet(0, 1)) { inTransaction.set(true); return true; // 事务允许通过 } } else if (txState.compareAndSet(0, 2)) { // 非事务保护中 // 当基于zk-cursor启动的时候,拿到的第一个Event是TransactionEnd return true; // DDL/DCL/TransactionEnd允许通过 } } } return false; } public void interrupt() { super.interrupt(); reset(); } // 重新设置状态 private void reset() { inTransaction.remove(); txState.set(0);// 重新置位 } private boolean isTransactionBegin(Event event) { return event.getEntryType() == EntryType.TRANSACTIONBEGIN; } private boolean isTransactionEnd(Event event) { return event.getEntryType() == EntryType.TRANSACTIONEND; } }
false
994
56
1,065
54
1,112
57
1,065
54
1,495
81
false
false
false
false
false
true
5800_5
/* * Copyright 1999-2012 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.cobar.net; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Selector; /** * @author xianmao.hexm */ public interface NIOConnection { /** * 注册网络事件 */ void register(Selector selector) throws IOException; /** * 读取数据 */ void read() throws IOException; /** * 处理数据 */ void handle(byte[] data); /** * 写出一块缓存数据 */ void write(ByteBuffer buffer); /** * 基于处理器队列的方式写数据 */ void writeByQueue() throws IOException; /** * 基于监听事件的方式写数据 */ void writeByEvent() throws IOException; /** * 发生错误 */ void error(int errCode, Throwable t); /** * 关闭连接 */ boolean close(); }
alibaba/cobar
server/src/main/net/com/alibaba/cobar/net/NIOConnection.java
367
/** * 写出一块缓存数据 */
block_comment
zh-cn
/* * Copyright 1999-2012 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.cobar.net; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Selector; /** * @author xianmao.hexm */ public interface NIOConnection { /** * 注册网络事件 */ void register(Selector selector) throws IOException; /** * 读取数据 */ void read() throws IOException; /** * 处理数据 */ void handle(byte[] data); /** * 写出一 <SUF>*/ void write(ByteBuffer buffer); /** * 基于处理器队列的方式写数据 */ void writeByQueue() throws IOException; /** * 基于监听事件的方式写数据 */ void writeByEvent() throws IOException; /** * 发生错误 */ void error(int errCode, Throwable t); /** * 关闭连接 */ boolean close(); }
false
347
13
367
12
391
12
367
12
488
20
false
false
false
false
false
true
50_44
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.util; /** * Java: 无回路有向图(Directed Acyclic Graph)的拓扑排序 * 该DAG图是通过邻接表实现的。 * <p> * author skywang * date 2014/04/22 */ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class ListDG { public static class Edge { public Object from; public Object to; public Edge(Object from, Object to) { this.from = from; this.to = to; } } // 邻接表中表对应的链表的顶点 private static class ENode { int ivex; // 该边所指向的顶点的位置 ENode nextEdge; // 指向下一条弧的指针 } // 邻接表中表的顶点 private static class VNode { Object data; // 顶点信息 ENode firstEdge; // 指向第一条依附该顶点的弧 } private List<VNode> mVexs; // 顶点数组 /* * 创建图(用已提供的矩阵) * * 参数说明: * vexs -- 顶点数组 * edges -- 边数组 */ public ListDG(List vexs, List<Edge> edges) { // 初始化"顶点数"和"边数" int vlen = vexs.size(); int elen = edges.size(); // 初始化"顶点" mVexs = new ArrayList<VNode>(); for (int i = 0; i < vlen; i++) { // 新建VNode VNode vnode = new VNode(); vnode.data = vexs.get(i); vnode.firstEdge = null; // 将vnode添加到数组mVexs中 mVexs.add(vnode); } // 初始化"边" for (int i = 0; i < elen; i++) { // 读取边的起始顶点和结束顶点 Object c1 = edges.get(i).from; Object c2 = edges.get(i).to; // 读取边的起始顶点和结束顶点 int p1 = getPosition(edges.get(i).from); int p2 = getPosition(edges.get(i).to); // 初始化node1 ENode node1 = new ENode(); node1.ivex = p2; // 将node1链接到"p1所在链表的末尾" if (mVexs.get(p1).firstEdge == null) { mVexs.get(p1).firstEdge = node1; } else { linkLast(mVexs.get(p1).firstEdge, node1); } } } /* * 将node节点链接到list的最后 */ private void linkLast(ENode list, ENode node) { ENode p = list; while (p.nextEdge != null) { p = p.nextEdge; } p.nextEdge = node; } /* * 返回ch位置 */ private int getPosition(Object ch) { for (int i = 0; i < mVexs.size(); i++) { if (mVexs.get(i).data == ch) { return i; } } return -1; } /* * 深度优先搜索遍历图的递归实现 */ private void DFS(int i, boolean[] visited) { ENode node; visited[i] = true; node = mVexs.get(i).firstEdge; while (node != null) { if (!visited[node.ivex]) { DFS(node.ivex, visited); } node = node.nextEdge; } } /* * 深度优先搜索遍历图 */ public void DFS() { boolean[] visited = new boolean[mVexs.size()]; // 顶点访问标记 // 初始化所有顶点都没有被访问 for (int i = 0; i < mVexs.size(); i++) { visited[i] = false; } for (int i = 0; i < mVexs.size(); i++) { if (!visited[i]) { DFS(i, visited); } } } /* * 广度优先搜索(类似于树的层次遍历) */ public void BFS() { int head = 0; int rear = 0; int[] queue = new int[mVexs.size()]; // 辅组队列 boolean[] visited = new boolean[mVexs.size()]; // 顶点访问标记 for (int i = 0; i < mVexs.size(); i++) { visited[i] = false; } for (int i = 0; i < mVexs.size(); i++) { if (!visited[i]) { visited[i] = true; System.out.printf("%c ", mVexs.get(i).data); queue[rear++] = i; // 入队列 } while (head != rear) { int j = queue[head++]; // 出队列 ENode node = mVexs.get(j).firstEdge; while (node != null) { int k = node.ivex; if (!visited[k]) { visited[k] = true; System.out.printf("%c ", mVexs.get(k).data); queue[rear++] = k; } node = node.nextEdge; } } } } /* * 打印矩阵队列图 */ public void print() { System.out.print("== List Graph:\n"); for (int i = 0; i < mVexs.size(); i++) { System.out.printf("%d(%c): ", i, mVexs.get(i).data); ENode node = mVexs.get(i).firstEdge; while (node != null) { System.out.printf("%d(%c) ", node.ivex, mVexs.get(node.ivex).data); node = node.nextEdge; } } } public boolean topologicalSort() { return topologicalSort(new Object[mVexs.size()]); } /* * 拓扑排序 * * 返回值: * true 成功排序,并输入结果 * false 失败(该有向图是有环的) */ public boolean topologicalSort(Object[] tops) { int index = 0; int num = mVexs.size(); int[] ins; // 入度数组 //Object[] tops; // 拓扑排序结果数组,记录每个节点的排序后的序号。 Queue<Integer> queue; // 辅组队列 ins = new int[num]; //tops = new Object[num]; queue = new LinkedList<Integer>(); // 统计每个顶点的入度数 for (int i = 0; i < num; i++) { ENode node = mVexs.get(i).firstEdge; while (node != null) { ins[node.ivex]++; node = node.nextEdge; } } // 将所有入度为0的顶点入队列 for (int i = 0; i < num; i++) { if (ins[i] == 0) { queue.offer(i); // 入队列 } } while (!queue.isEmpty()) { // 队列非空 int j = queue.poll().intValue(); // 出队列。j是顶点的序号 tops[index++] = mVexs.get(j).data; // 将该顶点添加到tops中,tops是排序结果 ENode node = mVexs.get(j).firstEdge; // 获取以该顶点为起点的出边队列 // 将与"node"关联的节点的入度减1; // 若减1之后,该节点的入度为0;则将该节点添加到队列中。 while (node != null) { // 将节点(序号为node.ivex)的入度减1。 ins[node.ivex]--; // 若节点的入度为0,则将其"入队列" if (ins[node.ivex] == 0) { queue.offer(node.ivex); // 入队列 } node = node.nextEdge; } } if (index != num) { return false; } return true; } // public static void main(String[] args) { // Object[] vexs = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; // Edge[] edges = new Edge[]{ // new Edge(vexs[0], vexs[6]), // new Edge(vexs[1], vexs[0]), // new Edge(vexs[1], vexs[3]), // new Edge(vexs[2], vexs[5]), // new Edge(vexs[2], vexs[6]), // new Edge(vexs[3], vexs[4]), // new Edge(vexs[3], vexs[5])}; // ListDG pG; // // // 自定义"图"(输入矩阵队列) // //pG = new ListDG(); // // 采用已有的"图" // pG = new ListDG(Arrays.asList(vexs), Arrays.asList(edges)); // // pG.print(); // 打印图 // //pG.DFS(); // 深度优先遍历 // //pG.BFS(); // 广度优先遍历 // pG.topologicalSort(); // 拓扑排序 // } }
alibaba/druid
core/src/main/java/com/alibaba/druid/util/ListDG.java
2,538
// 若减1之后,该节点的入度为0;则将该节点添加到队列中。
line_comment
zh-cn
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.util; /** * Java: 无回路有向图(Directed Acyclic Graph)的拓扑排序 * 该DAG图是通过邻接表实现的。 * <p> * author skywang * date 2014/04/22 */ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class ListDG { public static class Edge { public Object from; public Object to; public Edge(Object from, Object to) { this.from = from; this.to = to; } } // 邻接表中表对应的链表的顶点 private static class ENode { int ivex; // 该边所指向的顶点的位置 ENode nextEdge; // 指向下一条弧的指针 } // 邻接表中表的顶点 private static class VNode { Object data; // 顶点信息 ENode firstEdge; // 指向第一条依附该顶点的弧 } private List<VNode> mVexs; // 顶点数组 /* * 创建图(用已提供的矩阵) * * 参数说明: * vexs -- 顶点数组 * edges -- 边数组 */ public ListDG(List vexs, List<Edge> edges) { // 初始化"顶点数"和"边数" int vlen = vexs.size(); int elen = edges.size(); // 初始化"顶点" mVexs = new ArrayList<VNode>(); for (int i = 0; i < vlen; i++) { // 新建VNode VNode vnode = new VNode(); vnode.data = vexs.get(i); vnode.firstEdge = null; // 将vnode添加到数组mVexs中 mVexs.add(vnode); } // 初始化"边" for (int i = 0; i < elen; i++) { // 读取边的起始顶点和结束顶点 Object c1 = edges.get(i).from; Object c2 = edges.get(i).to; // 读取边的起始顶点和结束顶点 int p1 = getPosition(edges.get(i).from); int p2 = getPosition(edges.get(i).to); // 初始化node1 ENode node1 = new ENode(); node1.ivex = p2; // 将node1链接到"p1所在链表的末尾" if (mVexs.get(p1).firstEdge == null) { mVexs.get(p1).firstEdge = node1; } else { linkLast(mVexs.get(p1).firstEdge, node1); } } } /* * 将node节点链接到list的最后 */ private void linkLast(ENode list, ENode node) { ENode p = list; while (p.nextEdge != null) { p = p.nextEdge; } p.nextEdge = node; } /* * 返回ch位置 */ private int getPosition(Object ch) { for (int i = 0; i < mVexs.size(); i++) { if (mVexs.get(i).data == ch) { return i; } } return -1; } /* * 深度优先搜索遍历图的递归实现 */ private void DFS(int i, boolean[] visited) { ENode node; visited[i] = true; node = mVexs.get(i).firstEdge; while (node != null) { if (!visited[node.ivex]) { DFS(node.ivex, visited); } node = node.nextEdge; } } /* * 深度优先搜索遍历图 */ public void DFS() { boolean[] visited = new boolean[mVexs.size()]; // 顶点访问标记 // 初始化所有顶点都没有被访问 for (int i = 0; i < mVexs.size(); i++) { visited[i] = false; } for (int i = 0; i < mVexs.size(); i++) { if (!visited[i]) { DFS(i, visited); } } } /* * 广度优先搜索(类似于树的层次遍历) */ public void BFS() { int head = 0; int rear = 0; int[] queue = new int[mVexs.size()]; // 辅组队列 boolean[] visited = new boolean[mVexs.size()]; // 顶点访问标记 for (int i = 0; i < mVexs.size(); i++) { visited[i] = false; } for (int i = 0; i < mVexs.size(); i++) { if (!visited[i]) { visited[i] = true; System.out.printf("%c ", mVexs.get(i).data); queue[rear++] = i; // 入队列 } while (head != rear) { int j = queue[head++]; // 出队列 ENode node = mVexs.get(j).firstEdge; while (node != null) { int k = node.ivex; if (!visited[k]) { visited[k] = true; System.out.printf("%c ", mVexs.get(k).data); queue[rear++] = k; } node = node.nextEdge; } } } } /* * 打印矩阵队列图 */ public void print() { System.out.print("== List Graph:\n"); for (int i = 0; i < mVexs.size(); i++) { System.out.printf("%d(%c): ", i, mVexs.get(i).data); ENode node = mVexs.get(i).firstEdge; while (node != null) { System.out.printf("%d(%c) ", node.ivex, mVexs.get(node.ivex).data); node = node.nextEdge; } } } public boolean topologicalSort() { return topologicalSort(new Object[mVexs.size()]); } /* * 拓扑排序 * * 返回值: * true 成功排序,并输入结果 * false 失败(该有向图是有环的) */ public boolean topologicalSort(Object[] tops) { int index = 0; int num = mVexs.size(); int[] ins; // 入度数组 //Object[] tops; // 拓扑排序结果数组,记录每个节点的排序后的序号。 Queue<Integer> queue; // 辅组队列 ins = new int[num]; //tops = new Object[num]; queue = new LinkedList<Integer>(); // 统计每个顶点的入度数 for (int i = 0; i < num; i++) { ENode node = mVexs.get(i).firstEdge; while (node != null) { ins[node.ivex]++; node = node.nextEdge; } } // 将所有入度为0的顶点入队列 for (int i = 0; i < num; i++) { if (ins[i] == 0) { queue.offer(i); // 入队列 } } while (!queue.isEmpty()) { // 队列非空 int j = queue.poll().intValue(); // 出队列。j是顶点的序号 tops[index++] = mVexs.get(j).data; // 将该顶点添加到tops中,tops是排序结果 ENode node = mVexs.get(j).firstEdge; // 获取以该顶点为起点的出边队列 // 将与"node"关联的节点的入度减1; // 若减 <SUF> while (node != null) { // 将节点(序号为node.ivex)的入度减1。 ins[node.ivex]--; // 若节点的入度为0,则将其"入队列" if (ins[node.ivex] == 0) { queue.offer(node.ivex); // 入队列 } node = node.nextEdge; } } if (index != num) { return false; } return true; } // public static void main(String[] args) { // Object[] vexs = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; // Edge[] edges = new Edge[]{ // new Edge(vexs[0], vexs[6]), // new Edge(vexs[1], vexs[0]), // new Edge(vexs[1], vexs[3]), // new Edge(vexs[2], vexs[5]), // new Edge(vexs[2], vexs[6]), // new Edge(vexs[3], vexs[4]), // new Edge(vexs[3], vexs[5])}; // ListDG pG; // // // 自定义"图"(输入矩阵队列) // //pG = new ListDG(); // // 采用已有的"图" // pG = new ListDG(Arrays.asList(vexs), Arrays.asList(edges)); // // pG.print(); // 打印图 // //pG.DFS(); // 深度优先遍历 // //pG.BFS(); // 广度优先遍历 // pG.topologicalSort(); // 拓扑排序 // } }
false
2,394
24
2,538
24
2,634
22
2,538
24
3,217
33
false
false
false
false
false
true
416_1
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.parser; import java.io.CharArrayReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.math.MathContext; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.util.IOUtils; //这个类,为了性能优化做了很多特别处理,一切都是为了性能!!! /** * @author wenshao[szujobs@hotmail.com] */ public final class JSONReaderScanner extends JSONLexerBase { private final static ThreadLocal<char[]> BUF_LOCAL = new ThreadLocal<char[]>(); private Reader reader; private char[] buf; private int bufLength; public JSONReaderScanner(String input){ this(input, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(String input, int features){ this(new StringReader(input), features); } public JSONReaderScanner(char[] input, int inputLength){ this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(Reader reader){ this(reader, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(Reader reader, int features){ super(features); this.reader = reader; buf = BUF_LOCAL.get(); if (buf != null) { BUF_LOCAL.set(null); } if (buf == null) { buf = new char[1024 * 16]; } try { bufLength = reader.read(buf); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } bp = -1; next(); if (ch == 65279) { // utf8 bom next(); } } public JSONReaderScanner(char[] input, int inputLength, int features){ this(new CharArrayReader(input, 0, inputLength), features); } public final char charAt(int index) { if (index >= bufLength) { if (bufLength == -1) { if (index < sp) { return buf[index]; } return EOI; } if (bp == 0) { char[] buf = new char[(this.buf.length * 3) / 2]; System.arraycopy(this.buf, bp, buf, 0, bufLength); int rest = buf.length - bufLength; try { int len = reader.read(buf, bufLength, rest); bufLength += len; this.buf = buf; } catch (IOException e) { throw new JSONException(e.getMessage(), e); } } else { int rest = bufLength - bp; if (rest > 0) { System.arraycopy(buf, bp, buf, 0, rest); } try { bufLength = reader.read(buf, rest, buf.length - rest); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } if (bufLength == 0) { throw new JSONException("illegal state, textLength is zero"); } if (bufLength == -1) { return EOI; } bufLength += rest; index -= bp; np -= bp; bp = 0; } } return buf[index]; } public final int indexOf(char ch, int startIndex) { int offset = startIndex - bp; for (;; ++offset) { final int index = bp + offset; char chLoal = charAt(index); if (ch == chLoal) { return offset + bp; } if (chLoal == EOI) { return -1; } } } public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) { return symbolTable.addSymbol(buf, offset, len, hash); } public final char next() { int index = ++bp; if (index >= bufLength) { if (bufLength == -1) { return EOI; } if (sp > 0) { int offset; offset = bufLength - sp; if (ch == '"' && offset > 0) { offset--; } System.arraycopy(buf, offset, buf, 0, sp); } np = -1; index = bp = sp; try { int startPos = bp; int readLength = buf.length - startPos; if (readLength == 0) { char[] newBuf = new char[buf.length * 2]; System.arraycopy(buf, 0, newBuf, 0, buf.length); buf = newBuf; readLength = buf.length - startPos; } bufLength = reader.read(buf, bp, readLength); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } if (bufLength == 0) { throw new JSONException("illegal stat, textLength is zero"); } if (bufLength == -1) { return ch = EOI; } bufLength += bp; } return ch = buf[index]; } protected final void copyTo(int offset, int count, char[] dest) { System.arraycopy(buf, offset, dest, 0, count); } public final boolean charArrayCompare(char[] chars) { for (int i = 0; i < chars.length; ++i) { if (charAt(bp + i) != chars[i]) { return false; } } return true; } public byte[] bytesValue() { if (token == JSONToken.HEX) { throw new JSONException("TODO"); } return IOUtils.decodeBase64(buf, np + 1, sp); } protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) { System.arraycopy(buf, srcPos, dest, destPos, length); } /** * The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed. */ public final String stringVal() { if (!hasSpecial) { int offset = np + 1; if (offset < 0) { throw new IllegalStateException(); } if (offset > buf.length - sp) { throw new IllegalStateException(); } return new String(buf, offset, sp); // return text.substring(np + 1, np + 1 + sp); } else { return new String(sbuf, 0, sp); } } public final String subString(int offset, int count) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } return new String(buf, offset, count); // return text.substring(offset, offset + count); } public final char[] sub_chars(int offset, int count) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset == 0) { return buf; } char[] chars = new char[count]; System.arraycopy(buf, offset, chars, 0, count); return chars; } public final String numberString() { int offset = np; if (offset == -1) { offset = 0; } char chLocal = charAt(offset + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } String value = new String(buf, offset, sp); return value; } public final BigDecimal decimalValue() { int offset = np; if (offset == -1) { offset = 0; } char chLocal = charAt(offset + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } if (sp > 65535) { throw new JSONException("decimal overflow"); } return new BigDecimal(buf, offset, sp, MathContext.UNLIMITED); } public void close() { super.close(); if (buf.length <= 1024 * 64) { BUF_LOCAL.set(buf); } this.buf = null; IOUtils.close(reader); } @Override public boolean isEOF() { return bufLength == -1 || bp == buf.length || ch == EOI && bp + 1 >= buf.length; } public final boolean isBlankInput() { for (int i = 0;; ++i) { char chLocal = buf[i]; if (chLocal == EOI) { token = JSONToken.EOF; break; } if (!isWhitespace(chLocal)) { return false; } } return true; } }
alibaba/fastjson
src/main/java/com/alibaba/fastjson/parser/JSONReaderScanner.java
2,312
//这个类,为了性能优化做了很多特别处理,一切都是为了性能!!!
line_comment
zh-cn
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.parser; import java.io.CharArrayReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.math.MathContext; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.util.IOUtils; //这个 <SUF> /** * @author wenshao[szujobs@hotmail.com] */ public final class JSONReaderScanner extends JSONLexerBase { private final static ThreadLocal<char[]> BUF_LOCAL = new ThreadLocal<char[]>(); private Reader reader; private char[] buf; private int bufLength; public JSONReaderScanner(String input){ this(input, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(String input, int features){ this(new StringReader(input), features); } public JSONReaderScanner(char[] input, int inputLength){ this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(Reader reader){ this(reader, JSON.DEFAULT_PARSER_FEATURE); } public JSONReaderScanner(Reader reader, int features){ super(features); this.reader = reader; buf = BUF_LOCAL.get(); if (buf != null) { BUF_LOCAL.set(null); } if (buf == null) { buf = new char[1024 * 16]; } try { bufLength = reader.read(buf); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } bp = -1; next(); if (ch == 65279) { // utf8 bom next(); } } public JSONReaderScanner(char[] input, int inputLength, int features){ this(new CharArrayReader(input, 0, inputLength), features); } public final char charAt(int index) { if (index >= bufLength) { if (bufLength == -1) { if (index < sp) { return buf[index]; } return EOI; } if (bp == 0) { char[] buf = new char[(this.buf.length * 3) / 2]; System.arraycopy(this.buf, bp, buf, 0, bufLength); int rest = buf.length - bufLength; try { int len = reader.read(buf, bufLength, rest); bufLength += len; this.buf = buf; } catch (IOException e) { throw new JSONException(e.getMessage(), e); } } else { int rest = bufLength - bp; if (rest > 0) { System.arraycopy(buf, bp, buf, 0, rest); } try { bufLength = reader.read(buf, rest, buf.length - rest); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } if (bufLength == 0) { throw new JSONException("illegal state, textLength is zero"); } if (bufLength == -1) { return EOI; } bufLength += rest; index -= bp; np -= bp; bp = 0; } } return buf[index]; } public final int indexOf(char ch, int startIndex) { int offset = startIndex - bp; for (;; ++offset) { final int index = bp + offset; char chLoal = charAt(index); if (ch == chLoal) { return offset + bp; } if (chLoal == EOI) { return -1; } } } public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) { return symbolTable.addSymbol(buf, offset, len, hash); } public final char next() { int index = ++bp; if (index >= bufLength) { if (bufLength == -1) { return EOI; } if (sp > 0) { int offset; offset = bufLength - sp; if (ch == '"' && offset > 0) { offset--; } System.arraycopy(buf, offset, buf, 0, sp); } np = -1; index = bp = sp; try { int startPos = bp; int readLength = buf.length - startPos; if (readLength == 0) { char[] newBuf = new char[buf.length * 2]; System.arraycopy(buf, 0, newBuf, 0, buf.length); buf = newBuf; readLength = buf.length - startPos; } bufLength = reader.read(buf, bp, readLength); } catch (IOException e) { throw new JSONException(e.getMessage(), e); } if (bufLength == 0) { throw new JSONException("illegal stat, textLength is zero"); } if (bufLength == -1) { return ch = EOI; } bufLength += bp; } return ch = buf[index]; } protected final void copyTo(int offset, int count, char[] dest) { System.arraycopy(buf, offset, dest, 0, count); } public final boolean charArrayCompare(char[] chars) { for (int i = 0; i < chars.length; ++i) { if (charAt(bp + i) != chars[i]) { return false; } } return true; } public byte[] bytesValue() { if (token == JSONToken.HEX) { throw new JSONException("TODO"); } return IOUtils.decodeBase64(buf, np + 1, sp); } protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) { System.arraycopy(buf, srcPos, dest, destPos, length); } /** * The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed. */ public final String stringVal() { if (!hasSpecial) { int offset = np + 1; if (offset < 0) { throw new IllegalStateException(); } if (offset > buf.length - sp) { throw new IllegalStateException(); } return new String(buf, offset, sp); // return text.substring(np + 1, np + 1 + sp); } else { return new String(sbuf, 0, sp); } } public final String subString(int offset, int count) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } return new String(buf, offset, count); // return text.substring(offset, offset + count); } public final char[] sub_chars(int offset, int count) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset == 0) { return buf; } char[] chars = new char[count]; System.arraycopy(buf, offset, chars, 0, count); return chars; } public final String numberString() { int offset = np; if (offset == -1) { offset = 0; } char chLocal = charAt(offset + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } String value = new String(buf, offset, sp); return value; } public final BigDecimal decimalValue() { int offset = np; if (offset == -1) { offset = 0; } char chLocal = charAt(offset + sp - 1); int sp = this.sp; if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') { sp--; } if (sp > 65535) { throw new JSONException("decimal overflow"); } return new BigDecimal(buf, offset, sp, MathContext.UNLIMITED); } public void close() { super.close(); if (buf.length <= 1024 * 64) { BUF_LOCAL.set(buf); } this.buf = null; IOUtils.close(reader); } @Override public boolean isEOF() { return bufLength == -1 || bp == buf.length || ch == EOI && bp + 1 >= buf.length; } public final boolean isBlankInput() { for (int i = 0;; ++i) { char chLocal = buf[i]; if (chLocal == EOI) { token = JSONToken.EOF; break; } if (!isWhitespace(chLocal)) { return false; } } return true; } }
false
2,100
18
2,302
22
2,524
18
2,302
22
2,778
40
false
false
false
false
false
true
32408_11
package com.alibaba.jvm.sandbox.api.listener.ext; import com.alibaba.jvm.sandbox.api.event.Event; import com.alibaba.jvm.sandbox.api.event.InvokeEvent; import com.alibaba.jvm.sandbox.api.util.LazyGet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 行为通知 * * @author luanjia@taobao.com * @since {@code sandbox-api:1.0.10} */ public class Advice implements Attachment { private final int processId; private final int invokeId; private final ClassLoader loader; private final LazyGet<Behavior> behaviorLazyGet; private final Object[] parameterArray; private final Object target; private Object returnObj; private Throwable throwable; private Object attachment; private final Set<String> marks = new HashSet<>(); private Advice top = this; private Advice parent = this; private Event.Type state = Event.Type.BEFORE; /** * 构造通知 * * @param processId {@link InvokeEvent#processId} * @param invokeId {@link InvokeEvent#invokeId} * @param behaviorLazyGet 触发事件的行为(懒加载) * @param loader 触发事件的行为所在ClassLoader * @param parameterArray 触发事件的行为入参 * @param target 触发事件所归属的对象实例 */ Advice(final int processId, final int invokeId, final LazyGet<Behavior> behaviorLazyGet, final ClassLoader loader, final Object[] parameterArray, final Object target) { this.processId = processId; this.invokeId = invokeId; this.behaviorLazyGet = behaviorLazyGet; this.loader = loader; this.parameterArray = parameterArray; this.target = target; } /** * 应用BEFORE * * @param top 集联顶层调用的通知 * @param parent 集联上一个调用的通知 * @return this */ @SuppressWarnings("UnusedReturnValue") Advice applyBefore(final Advice top, final Advice parent) { this.top = top; this.parent = parent; return this; } /** * 应用返回结果,应用返回结果之后,通知将变为返回通知 * * @param returnObj 行为返回的对象 * @return this */ Advice applyReturn(final Object returnObj) { this.returnObj = returnObj; this.state = Event.Type.RETURN; return this; } /** * 应用行为抛出的异常,应用异常之后,通知将变为异常通知 * * @param throwable 行为抛出的异常 * @return this */ Advice applyThrows(final Throwable throwable) { this.throwable = throwable; this.state = Event.Type.THROWS; return this; } public boolean isReturn() { return this.state == Event.Type.RETURN; } public boolean isThrows() { return this.state == Event.Type.THROWS; } /** * 改变方法入参 * * @param index 方法入参编号(从0开始) * @param changeValue 改变的值 * @return this */ public Advice changeParameter(final int index, final Object changeValue) { parameterArray[index] = changeValue; return this; } /** * @return InvokeEvent#processId */ public int getProcessId() { return processId; } /** * @return InvokeEvent#invokeId */ public int getInvokeId() { return invokeId; } /** * 获取触发事件的行为 * <p> * 一般而言能触发事件的行为是:普通方法和构造函数 * </p> * * @return 触发事件的行为 */ public Behavior getBehavior() { return behaviorLazyGet.get(); } /** * 获取触发事件的行为所在的ClassLoader * * @return 触发事件的行为所在的ClassLoader * @since {@code sandbox-api:1.2.2} */ public ClassLoader getLoader() { return loader; } /** * 获取触发事件的行为入参 * * @return 触发事件的行为入参 */ public Object[] getParameterArray() { return parameterArray; } /** * 获取触发事件所归属的对象实例 * * @return 触发事件所归属的对象实例 */ public Object getTarget() { return target; } /** * 获取行为的返回结果 * <ul> * <li>如果是构造函数,返回当前对象的实例</li> * <li>如果是普通方法,返回方法的返回值</li> * </ul> * * @return 行为的返回结果 */ public Object getReturnObj() { return returnObj; } /** * 获取行为抛出的异常 * * @return 行为抛出的异常 */ public Throwable getThrowable() { return throwable; } @Override public void attach(final Object attachment) { this.attachment = attachment; } @SuppressWarnings("unchecked") @Override public <E> E attachment() { return (E) attachment; } @Override public int hashCode() { return processId + invokeId; } @Override public boolean equals(Object obj) { if (obj instanceof Advice) { final Advice advice = (Advice) obj; return processId == advice.processId && invokeId == advice.invokeId; } else { return false; } } /** * 对通知进行标记 * * @param mark 标记 */ public void mark(final String mark) { marks.add(mark); } /** * 通知是否拥有期待的标记 * * @param exceptMark 期待删除的标记 * @return TRUE:拥有;FALSE:不拥有 */ public boolean hasMark(final String exceptMark) { return marks.contains(exceptMark); } /** * 删除标记 * * @param mark 要删除的标记 * @return TRUE:标记曾经存在,现已删;FALSE:标记从未存在,现已删; */ public boolean unMark(final String mark) { return marks.remove(mark); } /** * 添加附件并打上标记 * * @param attachment 附件 * @param mark 标记 */ public void attach(final Object attachment, final String mark) { attach(attachment); mark(mark); } /** * 是否整个递进调用过程中的顶层通知 * * @return TRUE:是;FALSE:否 */ public boolean isProcessTop() { return parent == this; } /** * 获取调用顶层通知 * * @return 调用顶层通知 */ public Advice getProcessTop() { return top; } /** * 列出调用链路上所有拥有期待标记的调用通知 * * @param exceptMark 期待标记 * @return 调用链路上所有拥有期待标记的调用通知 */ public List<Advice> listHasMarkOnChain(final String exceptMark) { final List<Advice> advices = new ArrayList<>(); if (hasMark(exceptMark)) { advices.add(this); } if (!isProcessTop()) { advices.addAll(parent.listHasMarkOnChain(exceptMark)); } return advices; } }
alibaba/jvm-sandbox
sandbox-api/src/main/java/com/alibaba/jvm/sandbox/api/listener/ext/Advice.java
1,780
/** * 获取触发事件所归属的对象实例 * * @return 触发事件所归属的对象实例 */
block_comment
zh-cn
package com.alibaba.jvm.sandbox.api.listener.ext; import com.alibaba.jvm.sandbox.api.event.Event; import com.alibaba.jvm.sandbox.api.event.InvokeEvent; import com.alibaba.jvm.sandbox.api.util.LazyGet; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 行为通知 * * @author luanjia@taobao.com * @since {@code sandbox-api:1.0.10} */ public class Advice implements Attachment { private final int processId; private final int invokeId; private final ClassLoader loader; private final LazyGet<Behavior> behaviorLazyGet; private final Object[] parameterArray; private final Object target; private Object returnObj; private Throwable throwable; private Object attachment; private final Set<String> marks = new HashSet<>(); private Advice top = this; private Advice parent = this; private Event.Type state = Event.Type.BEFORE; /** * 构造通知 * * @param processId {@link InvokeEvent#processId} * @param invokeId {@link InvokeEvent#invokeId} * @param behaviorLazyGet 触发事件的行为(懒加载) * @param loader 触发事件的行为所在ClassLoader * @param parameterArray 触发事件的行为入参 * @param target 触发事件所归属的对象实例 */ Advice(final int processId, final int invokeId, final LazyGet<Behavior> behaviorLazyGet, final ClassLoader loader, final Object[] parameterArray, final Object target) { this.processId = processId; this.invokeId = invokeId; this.behaviorLazyGet = behaviorLazyGet; this.loader = loader; this.parameterArray = parameterArray; this.target = target; } /** * 应用BEFORE * * @param top 集联顶层调用的通知 * @param parent 集联上一个调用的通知 * @return this */ @SuppressWarnings("UnusedReturnValue") Advice applyBefore(final Advice top, final Advice parent) { this.top = top; this.parent = parent; return this; } /** * 应用返回结果,应用返回结果之后,通知将变为返回通知 * * @param returnObj 行为返回的对象 * @return this */ Advice applyReturn(final Object returnObj) { this.returnObj = returnObj; this.state = Event.Type.RETURN; return this; } /** * 应用行为抛出的异常,应用异常之后,通知将变为异常通知 * * @param throwable 行为抛出的异常 * @return this */ Advice applyThrows(final Throwable throwable) { this.throwable = throwable; this.state = Event.Type.THROWS; return this; } public boolean isReturn() { return this.state == Event.Type.RETURN; } public boolean isThrows() { return this.state == Event.Type.THROWS; } /** * 改变方法入参 * * @param index 方法入参编号(从0开始) * @param changeValue 改变的值 * @return this */ public Advice changeParameter(final int index, final Object changeValue) { parameterArray[index] = changeValue; return this; } /** * @return InvokeEvent#processId */ public int getProcessId() { return processId; } /** * @return InvokeEvent#invokeId */ public int getInvokeId() { return invokeId; } /** * 获取触发事件的行为 * <p> * 一般而言能触发事件的行为是:普通方法和构造函数 * </p> * * @return 触发事件的行为 */ public Behavior getBehavior() { return behaviorLazyGet.get(); } /** * 获取触发事件的行为所在的ClassLoader * * @return 触发事件的行为所在的ClassLoader * @since {@code sandbox-api:1.2.2} */ public ClassLoader getLoader() { return loader; } /** * 获取触发事件的行为入参 * * @return 触发事件的行为入参 */ public Object[] getParameterArray() { return parameterArray; } /** * 获取触 <SUF>*/ public Object getTarget() { return target; } /** * 获取行为的返回结果 * <ul> * <li>如果是构造函数,返回当前对象的实例</li> * <li>如果是普通方法,返回方法的返回值</li> * </ul> * * @return 行为的返回结果 */ public Object getReturnObj() { return returnObj; } /** * 获取行为抛出的异常 * * @return 行为抛出的异常 */ public Throwable getThrowable() { return throwable; } @Override public void attach(final Object attachment) { this.attachment = attachment; } @SuppressWarnings("unchecked") @Override public <E> E attachment() { return (E) attachment; } @Override public int hashCode() { return processId + invokeId; } @Override public boolean equals(Object obj) { if (obj instanceof Advice) { final Advice advice = (Advice) obj; return processId == advice.processId && invokeId == advice.invokeId; } else { return false; } } /** * 对通知进行标记 * * @param mark 标记 */ public void mark(final String mark) { marks.add(mark); } /** * 通知是否拥有期待的标记 * * @param exceptMark 期待删除的标记 * @return TRUE:拥有;FALSE:不拥有 */ public boolean hasMark(final String exceptMark) { return marks.contains(exceptMark); } /** * 删除标记 * * @param mark 要删除的标记 * @return TRUE:标记曾经存在,现已删;FALSE:标记从未存在,现已删; */ public boolean unMark(final String mark) { return marks.remove(mark); } /** * 添加附件并打上标记 * * @param attachment 附件 * @param mark 标记 */ public void attach(final Object attachment, final String mark) { attach(attachment); mark(mark); } /** * 是否整个递进调用过程中的顶层通知 * * @return TRUE:是;FALSE:否 */ public boolean isProcessTop() { return parent == this; } /** * 获取调用顶层通知 * * @return 调用顶层通知 */ public Advice getProcessTop() { return top; } /** * 列出调用链路上所有拥有期待标记的调用通知 * * @param exceptMark 期待标记 * @return 调用链路上所有拥有期待标记的调用通知 */ public List<Advice> listHasMarkOnChain(final String exceptMark) { final List<Advice> advices = new ArrayList<>(); if (hasMark(exceptMark)) { advices.add(this); } if (!isProcessTop()) { advices.addAll(parent.listHasMarkOnChain(exceptMark)); } return advices; } }
false
1,720
28
1,780
29
1,954
31
1,780
29
2,427
51
false
false
false
false
false
true
11108_9
package com.taobao.loganalyzer.input.tanxclick.parser; import com.taobao.loganalyzer.input.tanxclick.common.LogField; import com.taobao.loganalyzer.input.tanxclick.common.LogParser; import com.taobao.loganalyzer.input.tanxclick.common.LogRecord; import com.taobao.loganalyzer.input.tanxclick.common.SectionParser; /** * Section 5: 推广Section05解析类 * @see <a href="http://sps.corp.alimama.com/ad/ADExchange/DocLib/Tan(X)%E7%B3%BB%E7%BB%9F%E6%97%A5%E5%BF%97%E8%AE%BE%E8%AE%A1.pdf">点击日志格式</a> * @author kangtian * */ public class TaokeSectionParser implements SectionParser { /** * 对推广Section05进行解析(版本1.0不记录) *section5-推广section为空(不记录)--------允许 */ public boolean parse(LogParser lp, LogRecord lr) { if (lp.isCurCharCA()) { if (!lp.hasNextChar()) return false; } else { //部署类型 lr.addField("DeployType", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //宝贝价格 lr.addField("ItemPrice", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //价格佣金率 lr.addField("PriceComRate", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //实际佣金率 lr.addField("ActualComRate", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //店铺佣金率 lr.addField("ShopComRate", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //origintype lr.addField("OriginType", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //展示模式 lr.addField("ShowMode", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //推广方式相应的id lr.addField("PromotionType", new LogField(LogField.TYPE_STRING, lp.getNextCA())); } if (lp.isError()) { return false; } return true; } }
alibaba/mdrill
trunk/adhoc-internal/src/main/java/com/taobao/loganalyzer/input/tanxclick/parser/TaokeSectionParser.java
605
//推广方式相应的id
line_comment
zh-cn
package com.taobao.loganalyzer.input.tanxclick.parser; import com.taobao.loganalyzer.input.tanxclick.common.LogField; import com.taobao.loganalyzer.input.tanxclick.common.LogParser; import com.taobao.loganalyzer.input.tanxclick.common.LogRecord; import com.taobao.loganalyzer.input.tanxclick.common.SectionParser; /** * Section 5: 推广Section05解析类 * @see <a href="http://sps.corp.alimama.com/ad/ADExchange/DocLib/Tan(X)%E7%B3%BB%E7%BB%9F%E6%97%A5%E5%BF%97%E8%AE%BE%E8%AE%A1.pdf">点击日志格式</a> * @author kangtian * */ public class TaokeSectionParser implements SectionParser { /** * 对推广Section05进行解析(版本1.0不记录) *section5-推广section为空(不记录)--------允许 */ public boolean parse(LogParser lp, LogRecord lr) { if (lp.isCurCharCA()) { if (!lp.hasNextChar()) return false; } else { //部署类型 lr.addField("DeployType", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //宝贝价格 lr.addField("ItemPrice", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //价格佣金率 lr.addField("PriceComRate", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //实际佣金率 lr.addField("ActualComRate", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //店铺佣金率 lr.addField("ShopComRate", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //origintype lr.addField("OriginType", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //展示模式 lr.addField("ShowMode", new LogField(LogField.TYPE_STRING, lp.getNextCB())); //推广 <SUF> lr.addField("PromotionType", new LogField(LogField.TYPE_STRING, lp.getNextCA())); } if (lp.isError()) { return false; } return true; } }
false
495
6
600
8
603
6
600
8
753
12
false
false
false
false
false
true
7411_12
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.weex.util; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.Rect; import android.os.Build; import android.os.Environment; import android.support.annotation.Nullable; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.Window; import android.widget.ScrollView; import com.taobao.weex.ui.view.listview.WXRecyclerView; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; /** * Created by huabing.thb on 15-10-27. */ public class ScreenShot { public static View rootView; public static ArrayList<View> allViews = new ArrayList<View>(); public static View firstScrollView = null; public static View firstListView = null; public static View findFirstScrollerByRootView(View rootView){ View firstScrollView = null; if(null != rootView){ allViews = ViewUtil.getAllChildViews(rootView); for (View view:allViews ) { if(view instanceof ScrollView){ firstScrollView = view; break; } } } return firstScrollView; } public static View findFirstListByRootView(View rootView){ View firstListView = null; if(null != rootView){ allViews = ViewUtil.getAllChildViews(rootView); for (View view:allViews ) { if(view instanceof WXRecyclerView){ firstListView = view; break; } } } return firstListView; } private static Bitmap doSanpForListOrScroller(View sanpView){ Bitmap b = null; if(sanpView!=null){ int[] location = new int[2]; sanpView.getLocationInWindow(location); int x = location[0]; int y = location[1]; sanpView = rootView; sanpView.setDrawingCacheEnabled(true); sanpView.buildDrawingCache(); // sanpView = ((View)sanpView.getParent().getParent()); Bitmap bitmap = sanpView.getDrawingCache(); // sanpView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), // View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); // sanpView.layout(0, 0, sanpView.getMeasuredWidth(), sanpView.getMeasuredHeight()); // sanpView.buildDrawingCache(); // Bitmap bitmap = sanpView.getDrawingCache(); // b = bitmap; int sanpWidth = sanpView.getWidth(); Log.e("weex_test", "sanpView.getWidth=="+ sanpWidth); int snapHeight = sanpView.getHeight(); Log.e("weex_test", "sanpView.getHeight==" + snapHeight); // bitmap = Bitmap.createBitmap(sanpWidth+x, snapHeight+x,Bitmap.Config.ARGB_8888); // int width = activity.getWindowManager().getDefaultDisplay().getWidth(); // int height = activity.getWindowManager().getDefaultDisplay().getHeight(); int baseWidth = 750; int baseHeight = 1134; // 计算缩放因子 // float heightScale = ((float) baseHeight) / scrollerHeight; float widthScale = ((float) baseWidth) / sanpWidth; // 新建立矩阵 按照宽度缩放因子自适应缩放 Matrix matrix = new Matrix(); matrix.postScale(widthScale, widthScale); Log.e("weex_test", "widthScale=="+widthScale+ "|"+ "Real sanpWidth==" + sanpWidth*widthScale +"|" + "Real snapHeight==" + widthScale*snapHeight + "|" + "sanpView.x=" + x + "|" + "sanpView.y= " + y); b = Bitmap.createBitmap(bitmap, 0, 0, sanpWidth, snapHeight); // b = Bitmap.createBitmap(bitmap, 0, 0, rootView.getWidth(), rootView.getHeight()); // 缩放 // Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh, // Bitmap.Config.ARGB_4444); b = Bitmap.createBitmap(bitmap,0, 0, sanpWidth, snapHeight, matrix, true); // b = Bitmap.createBitmap(bitmap, 0, 0, scrollerWidth, // scrollerHeight, matrix, true); // b = Bitmap.createBitmap(bitmap, 0, statusBarHeight + actionBarHeight, width, // height - statusBarHeight - actionBarHeight, matrix, true); sanpView.destroyDrawingCache(); }else { Log.e("weex_test", "snapshot view is " + sanpView); } return b; } // Gets the Activity screenshots, save to png file private static Bitmap takeScreenShot(Activity activity) { Context ctx = activity.getApplicationContext(); String screenShotDir = getWeexScreenShotDir(ctx); View view = activity.getWindow().getDecorView(); rootView = view; firstScrollView = findFirstScrollerByRootView(rootView); firstListView = findFirstListByRootView(rootView); Bitmap snapBitmap = null; // 优先scroller ->list->root if(null !=firstScrollView ){ snapBitmap = doSanpForListOrScroller(firstScrollView); } else { Log.e("weex_test", "firstScrollView is " + firstScrollView); if (null != firstListView){ snapBitmap = doSanpForListOrScroller(firstListView); }else { Log.e("weex_test", "firstListView is " + firstListView); if(null != rootView){ // snapBitmap = doSanpForListOrScroller(rootView); } } } return snapBitmap; } public static Bitmap convertViewToBitmap(View view){ view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); return bitmap; } private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void saveToSD(Bitmap bmp, String dirName,String fileName) throws IOException { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(dirName); if(!dir.exists()){ dir.mkdirs(); } File file = new File(dirName + fileName); Log.d("AssetsFileUtil", dirName + fileName); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (fos != null) { bmp.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void shoot(Activity activity, String pathName) throws IOException { if(SdCardHelper.isHasSdcard()){ // ScreenShot.saveToSD(ScreenShot.takeScreenShot(activity), SdCardHelper.SDCardRoot + "WeexTest/ScreenShot/", pathName /*+System.currentTimeMillis()*/ + ".png"); ScreenShot.saveToSD(ScreenShot.takeScreenShot(activity), getWeexScreenShotDir(activity.getApplicationContext()) + File.separator , pathName /*+System.currentTimeMillis()*/ + ".png"); } } // public static void shootAllViews(Activity activity, String pathName) throws IOException { // ScreenShot.saveToSD(ScreenShot.takeScreenShotIncludeDialog(activity, pathName), "sdcard/WeexTest/ScreenShot/", pathName /*+System.currentTimeMillis()*/ + ".png"); // // } public static void takeScreenShotIncludeDialog(Activity activity, String file){ if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(getWeexScreenShotDir(activity.getApplicationContext()) ); if(!dir.exists()){ dir.mkdirs(); } File filePic = new File(getWeexScreenShotDir(activity.getApplicationContext()) + File.separator + file + ".png"); if (!filePic.exists()) { try { filePic.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Falcon.takeScreenshot(activity, filePic); } } public static int getActionBarHeight(Activity activity) { int actionBarHeight = 0; if(activity.getActionBar()!= null){ actionBarHeight = activity.getActionBar().getHeight(); } if (actionBarHeight != 0) return actionBarHeight; final TypedValue tv = new TypedValue(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (activity.getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true)){ actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics()); Log.e("actionBarHeight==",actionBarHeight + "android.support.v7.appcompat.R.attr.actionBarSize"); } else if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)){ actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics()); Log.e("actionBarHeight==",actionBarHeight + "actionBarHeight is android.R.attr.actionBarSize"); } } return actionBarHeight; } public static int getStatusBarHeight1(Activity activity){ int result = 0; int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = activity.getResources().getDimensionPixelSize(resourceId); } Log.e("StatusBarHeight==", "StatusBar Height= " + result); return result; } public static int getStatusBarHeight(Activity activity) { int result = 0; Rect rect = new Rect(); Window window = activity.getWindow(); if (window != null) { window.getDecorView().getWindowVisibleDisplayFrame(rect); View v = window.findViewById(Window.ID_ANDROID_CONTENT); android.view.Display display = ((android.view.WindowManager) activity.getSystemService(activity.WINDOW_SERVICE)).getDefaultDisplay(); //return result title bar height int result1 = display.getHeight() - v.getBottom() + rect.top; int result2 = display.getHeight() - v.getBottom(); int result3 = v.getTop() - rect.top; int result4 = display.getHeight() - v.getHeight(); Log.e("StatusBarHeight==", "result1== " + result1 +" result2 = " + result2 + "result3=" + result3 + "result4=" +result4 ) ; } return result; } /** * getDiskCacheDir * @param context * @return */ @Nullable public static String getWeexScreenShotDir(Context context) { if (context == null) { return null; } String cachePath; String extDir = "" ; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { cachePath = context.getExternalCacheDir().getPath(); extDir = context.getExternalFilesDir(null).getPath(); File screenShotFileDir = new File(extDir, "WeexTest" + File.separator + "ScreenShot"); if (!screenShotFileDir.exists()){ screenShotFileDir.mkdirs(); } return screenShotFileDir.getPath(); // File file = new File(context.getExternalFilesDir(null), "DemoFile.jpg"); } else { cachePath = context.getCacheDir().getPath(); } Log.e("weex_test","cachePath==" + cachePath); Log.e("weex_test","extDir==" + extDir); return cachePath; } }
alibaba/weex
playground/android/playground/src/androidTest/java/org/apache/weex/util/ScreenShot.java
3,278
// 计算缩放因子
line_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.weex.util; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.Rect; import android.os.Build; import android.os.Environment; import android.support.annotation.Nullable; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.Window; import android.widget.ScrollView; import com.taobao.weex.ui.view.listview.WXRecyclerView; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; /** * Created by huabing.thb on 15-10-27. */ public class ScreenShot { public static View rootView; public static ArrayList<View> allViews = new ArrayList<View>(); public static View firstScrollView = null; public static View firstListView = null; public static View findFirstScrollerByRootView(View rootView){ View firstScrollView = null; if(null != rootView){ allViews = ViewUtil.getAllChildViews(rootView); for (View view:allViews ) { if(view instanceof ScrollView){ firstScrollView = view; break; } } } return firstScrollView; } public static View findFirstListByRootView(View rootView){ View firstListView = null; if(null != rootView){ allViews = ViewUtil.getAllChildViews(rootView); for (View view:allViews ) { if(view instanceof WXRecyclerView){ firstListView = view; break; } } } return firstListView; } private static Bitmap doSanpForListOrScroller(View sanpView){ Bitmap b = null; if(sanpView!=null){ int[] location = new int[2]; sanpView.getLocationInWindow(location); int x = location[0]; int y = location[1]; sanpView = rootView; sanpView.setDrawingCacheEnabled(true); sanpView.buildDrawingCache(); // sanpView = ((View)sanpView.getParent().getParent()); Bitmap bitmap = sanpView.getDrawingCache(); // sanpView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), // View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); // sanpView.layout(0, 0, sanpView.getMeasuredWidth(), sanpView.getMeasuredHeight()); // sanpView.buildDrawingCache(); // Bitmap bitmap = sanpView.getDrawingCache(); // b = bitmap; int sanpWidth = sanpView.getWidth(); Log.e("weex_test", "sanpView.getWidth=="+ sanpWidth); int snapHeight = sanpView.getHeight(); Log.e("weex_test", "sanpView.getHeight==" + snapHeight); // bitmap = Bitmap.createBitmap(sanpWidth+x, snapHeight+x,Bitmap.Config.ARGB_8888); // int width = activity.getWindowManager().getDefaultDisplay().getWidth(); // int height = activity.getWindowManager().getDefaultDisplay().getHeight(); int baseWidth = 750; int baseHeight = 1134; // 计算 <SUF> // float heightScale = ((float) baseHeight) / scrollerHeight; float widthScale = ((float) baseWidth) / sanpWidth; // 新建立矩阵 按照宽度缩放因子自适应缩放 Matrix matrix = new Matrix(); matrix.postScale(widthScale, widthScale); Log.e("weex_test", "widthScale=="+widthScale+ "|"+ "Real sanpWidth==" + sanpWidth*widthScale +"|" + "Real snapHeight==" + widthScale*snapHeight + "|" + "sanpView.x=" + x + "|" + "sanpView.y= " + y); b = Bitmap.createBitmap(bitmap, 0, 0, sanpWidth, snapHeight); // b = Bitmap.createBitmap(bitmap, 0, 0, rootView.getWidth(), rootView.getHeight()); // 缩放 // Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh, // Bitmap.Config.ARGB_4444); b = Bitmap.createBitmap(bitmap,0, 0, sanpWidth, snapHeight, matrix, true); // b = Bitmap.createBitmap(bitmap, 0, 0, scrollerWidth, // scrollerHeight, matrix, true); // b = Bitmap.createBitmap(bitmap, 0, statusBarHeight + actionBarHeight, width, // height - statusBarHeight - actionBarHeight, matrix, true); sanpView.destroyDrawingCache(); }else { Log.e("weex_test", "snapshot view is " + sanpView); } return b; } // Gets the Activity screenshots, save to png file private static Bitmap takeScreenShot(Activity activity) { Context ctx = activity.getApplicationContext(); String screenShotDir = getWeexScreenShotDir(ctx); View view = activity.getWindow().getDecorView(); rootView = view; firstScrollView = findFirstScrollerByRootView(rootView); firstListView = findFirstListByRootView(rootView); Bitmap snapBitmap = null; // 优先scroller ->list->root if(null !=firstScrollView ){ snapBitmap = doSanpForListOrScroller(firstScrollView); } else { Log.e("weex_test", "firstScrollView is " + firstScrollView); if (null != firstListView){ snapBitmap = doSanpForListOrScroller(firstListView); }else { Log.e("weex_test", "firstListView is " + firstListView); if(null != rootView){ // snapBitmap = doSanpForListOrScroller(rootView); } } } return snapBitmap; } public static Bitmap convertViewToBitmap(View view){ view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); return bitmap; } private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void saveToSD(Bitmap bmp, String dirName,String fileName) throws IOException { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(dirName); if(!dir.exists()){ dir.mkdirs(); } File file = new File(dirName + fileName); Log.d("AssetsFileUtil", dirName + fileName); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (fos != null) { bmp.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void shoot(Activity activity, String pathName) throws IOException { if(SdCardHelper.isHasSdcard()){ // ScreenShot.saveToSD(ScreenShot.takeScreenShot(activity), SdCardHelper.SDCardRoot + "WeexTest/ScreenShot/", pathName /*+System.currentTimeMillis()*/ + ".png"); ScreenShot.saveToSD(ScreenShot.takeScreenShot(activity), getWeexScreenShotDir(activity.getApplicationContext()) + File.separator , pathName /*+System.currentTimeMillis()*/ + ".png"); } } // public static void shootAllViews(Activity activity, String pathName) throws IOException { // ScreenShot.saveToSD(ScreenShot.takeScreenShotIncludeDialog(activity, pathName), "sdcard/WeexTest/ScreenShot/", pathName /*+System.currentTimeMillis()*/ + ".png"); // // } public static void takeScreenShotIncludeDialog(Activity activity, String file){ if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(getWeexScreenShotDir(activity.getApplicationContext()) ); if(!dir.exists()){ dir.mkdirs(); } File filePic = new File(getWeexScreenShotDir(activity.getApplicationContext()) + File.separator + file + ".png"); if (!filePic.exists()) { try { filePic.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Falcon.takeScreenshot(activity, filePic); } } public static int getActionBarHeight(Activity activity) { int actionBarHeight = 0; if(activity.getActionBar()!= null){ actionBarHeight = activity.getActionBar().getHeight(); } if (actionBarHeight != 0) return actionBarHeight; final TypedValue tv = new TypedValue(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (activity.getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true)){ actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics()); Log.e("actionBarHeight==",actionBarHeight + "android.support.v7.appcompat.R.attr.actionBarSize"); } else if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)){ actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics()); Log.e("actionBarHeight==",actionBarHeight + "actionBarHeight is android.R.attr.actionBarSize"); } } return actionBarHeight; } public static int getStatusBarHeight1(Activity activity){ int result = 0; int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = activity.getResources().getDimensionPixelSize(resourceId); } Log.e("StatusBarHeight==", "StatusBar Height= " + result); return result; } public static int getStatusBarHeight(Activity activity) { int result = 0; Rect rect = new Rect(); Window window = activity.getWindow(); if (window != null) { window.getDecorView().getWindowVisibleDisplayFrame(rect); View v = window.findViewById(Window.ID_ANDROID_CONTENT); android.view.Display display = ((android.view.WindowManager) activity.getSystemService(activity.WINDOW_SERVICE)).getDefaultDisplay(); //return result title bar height int result1 = display.getHeight() - v.getBottom() + rect.top; int result2 = display.getHeight() - v.getBottom(); int result3 = v.getTop() - rect.top; int result4 = display.getHeight() - v.getHeight(); Log.e("StatusBarHeight==", "result1== " + result1 +" result2 = " + result2 + "result3=" + result3 + "result4=" +result4 ) ; } return result; } /** * getDiskCacheDir * @param context * @return */ @Nullable public static String getWeexScreenShotDir(Context context) { if (context == null) { return null; } String cachePath; String extDir = "" ; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { cachePath = context.getExternalCacheDir().getPath(); extDir = context.getExternalFilesDir(null).getPath(); File screenShotFileDir = new File(extDir, "WeexTest" + File.separator + "ScreenShot"); if (!screenShotFileDir.exists()){ screenShotFileDir.mkdirs(); } return screenShotFileDir.getPath(); // File file = new File(context.getExternalFilesDir(null), "DemoFile.jpg"); } else { cachePath = context.getCacheDir().getPath(); } Log.e("weex_test","cachePath==" + cachePath); Log.e("weex_test","extDir==" + extDir); return cachePath; } }
false
2,879
7
3,282
7
3,439
4
3,278
7
3,898
10
false
false
false
false
false
true
8118_3
package com.taobao.yugong.common.db; import java.lang.reflect.Array; import java.math.BigDecimal; import java.text.MessageFormat; import java.util.Date; import java.util.List; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.taobao.yugong.common.audit.RecordDumper; import com.taobao.yugong.common.db.meta.ColumnValue; import com.taobao.yugong.common.model.record.Record; import com.taobao.yugong.exception.YuGongException; /** * 记录对比 * * @author agapple 2013-9-29 下午2:56:39 */ public class RecordDiffer { private static final String SEP = SystemUtils.LINE_SEPARATOR; private static String record_format = null; private static final Logger diffLogger = LoggerFactory.getLogger("check"); static { record_format = SEP + "-----------------" + SEP; record_format += "- Schema: {0} , Table: {1}" + SEP; record_format += "-----------------" + SEP; record_format += "---Pks" + SEP; record_format += "{2}" + SEP; record_format += "---diff" + SEP; record_format += "\t{3}" + SEP; } public static void diff(Record record1, Record record2) { if (record2 == null) { diffLogger.info(diffMessage(record1.getSchemaName(), record1.getTableName(), record1.getPrimaryKeys(), "record not found")); return; } if (record1.getColumns().size() > record2.getColumns().size()) { diffLogger.info(diffMessage(record1.getSchemaName(), record1.getTableName(), record1.getPrimaryKeys(), "column size is great than target column size")); return; } StringBuilder diff = new StringBuilder(); boolean same = true; int size = record1.getColumns().size(); for (int i = 0; i < size; i++) { ColumnValue column = record1.getColumns().get(i); same &= campareOneColumn(column, getColumn(record2, column.getColumn().getName()), diff); } if (!same) { diffLogger.info(diffMessage(record1.getSchemaName(), record2.getTableName(), record1.getPrimaryKeys(), diff.toString())); } } private static boolean campareOneColumn(ColumnValue column1, ColumnValue column2, StringBuilder diff) { if (!column1.isCheck() || !column2.isCheck()) { return true;// 可能不需要做对比,忽略 } Object value1 = column1.getValue(); Object value2 = column2.getValue(); if (value1 == null && value2 == null) { return true; } StringBuilder message = new StringBuilder(); message.append(column1.getColumn()) .append(" , values : [") .append(ObjectUtils.toString(value1)) .append("] vs [") .append(ObjectUtils.toString(value2)) .append("]\n\t"); if ((value1 == null && value2 != null) || (value1 != null && value2 == null)) { diff.append(message); return false; } if (!value1.equals(value2)) { // custom define if (value1 instanceof java.util.Date && value2 instanceof java.util.Date) { boolean result = dateValueEquals((java.util.Date) value1, (java.util.Date) value2); if (!result) { String v1 = value1.toString(); String v2 = value2.toString(); // 2012-02-02 02:02:02 与 2012-02-02 肯定是一种包含关系 if (v1.contains(v2) || v2.contains(v1)) { return true; } } else { return true; } } else if (Number.class.isAssignableFrom(value1.getClass()) && Number.class.isAssignableFrom(value2.getClass())) { String v1 = null; String v2 = null; v1 = getNumberString(value1); v2 = getNumberString(value2); boolean result = v1.equals(v2); if (result) { return true; } } else if (value1.getClass().isArray() && value2.getClass().isArray()) { boolean result = true; if (Array.getLength(value1) == Array.getLength(value2)) { int length = Array.getLength(value1); for (int i = 0; i < length; i++) { result &= ObjectUtils.equals(Array.get(value1, i), Array.get(value2, i)); } if (result) { return true; } } } // 其他情况为false diff.append(message); return false; } else { return true; } } private static String getNumberString(Object value1) { String v1; if (value1 instanceof BigDecimal) { v1 = ((BigDecimal) value1).toPlainString(); if (StringUtils.indexOf(v1, ".") != -1) { v1 = StringUtils.stripEnd(v1, "0");// 如果0是末尾,则删除之 v1 = StringUtils.stripEnd(v1, ".");// 如果.是末尾,则删除之 } } else { v1 = value1.toString(); } return v1; } private static boolean dateValueEquals(Date source, Date target) { return source.getTime() == target.getTime(); } private static ColumnValue getColumn(Record record, String columnName) { for (ColumnValue column : record.getColumns()) { if (StringUtils.equalsIgnoreCase(columnName, column.getColumn().getName())) { return column; } } throw new YuGongException("column[" + columnName + "] is not found."); } private static String diffMessage(String schemaName, String tableName, List<ColumnValue> primaryKeys, String message) { return MessageFormat.format(record_format, schemaName, tableName, RecordDumper.dumpRecordColumns(primaryKeys), message); } }
alibaba/yugong
src/main/java/com/taobao/yugong/common/db/RecordDiffer.java
1,555
// 2012-02-02 02:02:02 与 2012-02-02 肯定是一种包含关系
line_comment
zh-cn
package com.taobao.yugong.common.db; import java.lang.reflect.Array; import java.math.BigDecimal; import java.text.MessageFormat; import java.util.Date; import java.util.List; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.taobao.yugong.common.audit.RecordDumper; import com.taobao.yugong.common.db.meta.ColumnValue; import com.taobao.yugong.common.model.record.Record; import com.taobao.yugong.exception.YuGongException; /** * 记录对比 * * @author agapple 2013-9-29 下午2:56:39 */ public class RecordDiffer { private static final String SEP = SystemUtils.LINE_SEPARATOR; private static String record_format = null; private static final Logger diffLogger = LoggerFactory.getLogger("check"); static { record_format = SEP + "-----------------" + SEP; record_format += "- Schema: {0} , Table: {1}" + SEP; record_format += "-----------------" + SEP; record_format += "---Pks" + SEP; record_format += "{2}" + SEP; record_format += "---diff" + SEP; record_format += "\t{3}" + SEP; } public static void diff(Record record1, Record record2) { if (record2 == null) { diffLogger.info(diffMessage(record1.getSchemaName(), record1.getTableName(), record1.getPrimaryKeys(), "record not found")); return; } if (record1.getColumns().size() > record2.getColumns().size()) { diffLogger.info(diffMessage(record1.getSchemaName(), record1.getTableName(), record1.getPrimaryKeys(), "column size is great than target column size")); return; } StringBuilder diff = new StringBuilder(); boolean same = true; int size = record1.getColumns().size(); for (int i = 0; i < size; i++) { ColumnValue column = record1.getColumns().get(i); same &= campareOneColumn(column, getColumn(record2, column.getColumn().getName()), diff); } if (!same) { diffLogger.info(diffMessage(record1.getSchemaName(), record2.getTableName(), record1.getPrimaryKeys(), diff.toString())); } } private static boolean campareOneColumn(ColumnValue column1, ColumnValue column2, StringBuilder diff) { if (!column1.isCheck() || !column2.isCheck()) { return true;// 可能不需要做对比,忽略 } Object value1 = column1.getValue(); Object value2 = column2.getValue(); if (value1 == null && value2 == null) { return true; } StringBuilder message = new StringBuilder(); message.append(column1.getColumn()) .append(" , values : [") .append(ObjectUtils.toString(value1)) .append("] vs [") .append(ObjectUtils.toString(value2)) .append("]\n\t"); if ((value1 == null && value2 != null) || (value1 != null && value2 == null)) { diff.append(message); return false; } if (!value1.equals(value2)) { // custom define if (value1 instanceof java.util.Date && value2 instanceof java.util.Date) { boolean result = dateValueEquals((java.util.Date) value1, (java.util.Date) value2); if (!result) { String v1 = value1.toString(); String v2 = value2.toString(); // 20 <SUF> if (v1.contains(v2) || v2.contains(v1)) { return true; } } else { return true; } } else if (Number.class.isAssignableFrom(value1.getClass()) && Number.class.isAssignableFrom(value2.getClass())) { String v1 = null; String v2 = null; v1 = getNumberString(value1); v2 = getNumberString(value2); boolean result = v1.equals(v2); if (result) { return true; } } else if (value1.getClass().isArray() && value2.getClass().isArray()) { boolean result = true; if (Array.getLength(value1) == Array.getLength(value2)) { int length = Array.getLength(value1); for (int i = 0; i < length; i++) { result &= ObjectUtils.equals(Array.get(value1, i), Array.get(value2, i)); } if (result) { return true; } } } // 其他情况为false diff.append(message); return false; } else { return true; } } private static String getNumberString(Object value1) { String v1; if (value1 instanceof BigDecimal) { v1 = ((BigDecimal) value1).toPlainString(); if (StringUtils.indexOf(v1, ".") != -1) { v1 = StringUtils.stripEnd(v1, "0");// 如果0是末尾,则删除之 v1 = StringUtils.stripEnd(v1, ".");// 如果.是末尾,则删除之 } } else { v1 = value1.toString(); } return v1; } private static boolean dateValueEquals(Date source, Date target) { return source.getTime() == target.getTime(); } private static ColumnValue getColumn(Record record, String columnName) { for (ColumnValue column : record.getColumns()) { if (StringUtils.equalsIgnoreCase(columnName, column.getColumn().getName())) { return column; } } throw new YuGongException("column[" + columnName + "] is not found."); } private static String diffMessage(String schemaName, String tableName, List<ColumnValue> primaryKeys, String message) { return MessageFormat.format(record_format, schemaName, tableName, RecordDumper.dumpRecordColumns(primaryKeys), message); } }
false
1,350
41
1,555
42
1,650
38
1,555
42
1,822
48
false
false
false
false
false
true
12022_1
package com.same.androidclass.service; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.IBinder; import android.support.annotation.Nullable; import com.same.androidclass.R; import com.same.androidclass.presenter.ExtraServicePresenter; import com.same.androidclass.util.NetWorkUtils; import com.same.androidclass.view.activity.MainActivity; /** * 额外服务ExtraService * Created by alic on 16-5-19. */ public class ExtraService extends Service implements ExtraServiceDo { private ExtraServicePresenter presenter; @Nullable @Override public IBinder onBind(Intent intent) { return null; } //该方法只执行一次 @Override public void onCreate() { super.onCreate(); // Toast.makeText(this, "ExtraService已经启动", Toast.LENGTH_SHORT).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { initService(); // System.out.println("嘿 我在执行 定时呢"); return super.onStartCommand(intent, flags, startId); } public void initService() { presenter = new ExtraServicePresenter(this, this); //需要定时启动 -----here 时间在user xml 通SP获取 presenter.doShowNotification(); //没什么 new Thread(new Runnable() { @Override public void run() { if (NetWorkUtils.isNetworkConnected(ExtraService.this)) presenter.doGetCurrentWeek(); } }).start(); } //定时提醒 @Override public void showNotification() { //定义一个PendingIntent点击Notification后启动一个Activity Intent it = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, it, 0); String tip = "嘿嘿~ 明天还有" + presenter.doGetCurrentWeekCourseCount() + "节课要上( ⊙o⊙ )哇"; Notification.Builder builder = new Notification.Builder(this); //没课就不提示啦 if (!presenter.doGetCurrentWeekCourseCount().equals("0")) { builder.setContentTitle("我是校园助手 Alic派过来的( ⊙o⊙ )哇") .setContentText("") .setSubText(tip) //内容下面的一小段文字 .setTicker("收到MyScse助手的信息~") //收到信息后状态栏显示的文字信息 .setWhen(System.currentTimeMillis()) //设置通知时间 .setSmallIcon(R.drawable.app_icon) //设置小图标 .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.app_icon)) //设置大图标 .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND) //设置默认的三色灯与振动器 .setAutoCancel(true) //设置点击后取消Notification .setContentIntent(pendingIntent); Notification notification = builder.build(); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.notify(0x11, notification); } } }
alicfeng/sise
androidclass/src/main/java/com/same/androidclass/service/ExtraService.java
795
//该方法只执行一次
line_comment
zh-cn
package com.same.androidclass.service; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.IBinder; import android.support.annotation.Nullable; import com.same.androidclass.R; import com.same.androidclass.presenter.ExtraServicePresenter; import com.same.androidclass.util.NetWorkUtils; import com.same.androidclass.view.activity.MainActivity; /** * 额外服务ExtraService * Created by alic on 16-5-19. */ public class ExtraService extends Service implements ExtraServiceDo { private ExtraServicePresenter presenter; @Nullable @Override public IBinder onBind(Intent intent) { return null; } //该方 <SUF> @Override public void onCreate() { super.onCreate(); // Toast.makeText(this, "ExtraService已经启动", Toast.LENGTH_SHORT).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { initService(); // System.out.println("嘿 我在执行 定时呢"); return super.onStartCommand(intent, flags, startId); } public void initService() { presenter = new ExtraServicePresenter(this, this); //需要定时启动 -----here 时间在user xml 通SP获取 presenter.doShowNotification(); //没什么 new Thread(new Runnable() { @Override public void run() { if (NetWorkUtils.isNetworkConnected(ExtraService.this)) presenter.doGetCurrentWeek(); } }).start(); } //定时提醒 @Override public void showNotification() { //定义一个PendingIntent点击Notification后启动一个Activity Intent it = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, it, 0); String tip = "嘿嘿~ 明天还有" + presenter.doGetCurrentWeekCourseCount() + "节课要上( ⊙o⊙ )哇"; Notification.Builder builder = new Notification.Builder(this); //没课就不提示啦 if (!presenter.doGetCurrentWeekCourseCount().equals("0")) { builder.setContentTitle("我是校园助手 Alic派过来的( ⊙o⊙ )哇") .setContentText("") .setSubText(tip) //内容下面的一小段文字 .setTicker("收到MyScse助手的信息~") //收到信息后状态栏显示的文字信息 .setWhen(System.currentTimeMillis()) //设置通知时间 .setSmallIcon(R.drawable.app_icon) //设置小图标 .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.app_icon)) //设置大图标 .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND) //设置默认的三色灯与振动器 .setAutoCancel(true) //设置点击后取消Notification .setContentIntent(pendingIntent); Notification notification = builder.build(); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.notify(0x11, notification); } } }
false
674
6
795
6
804
6
795
6
986
11
false
false
false
false
false
true
9258_12
package com.yl.recyclerview.adapter; import android.content.Context; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.yl.recyclerview.R; import java.util.List; /** * 上拉加载更多 * Created by yangle on 2017/10/12. */ public class LoadMoreAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<String> dataList; // 普通布局 private final int TYPE_ITEM = 1; // 脚布局 private final int TYPE_FOOTER = 2; // 当前加载状态,默认为加载完成 private int loadState = 2; // 正在加载 public final int LOADING = 1; // 加载完成 public final int LOADING_COMPLETE = 2; // 加载到底 public final int LOADING_END = 3; public LoadMoreAdapter(List<String> dataList) { this.dataList = dataList; } @Override public int getItemViewType(int position) { // 最后一个item设置为FooterView if (position + 1 == getItemCount()) { return TYPE_FOOTER; } else { return TYPE_ITEM; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // 通过判断显示类型,来创建不同的View if (viewType == TYPE_ITEM) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_recyclerview, parent, false); return new RecyclerViewHolder(view); } else if (viewType == TYPE_FOOTER) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_refresh_footer, parent, false); return new FootViewHolder(view); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof RecyclerViewHolder) { RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder; recyclerViewHolder.tvItem.setText(dataList.get(position)); } else if (holder instanceof FootViewHolder) { FootViewHolder footViewHolder = (FootViewHolder) holder; switch (loadState) { case LOADING: // 正在加载 footViewHolder.pbLoading.setVisibility(View.VISIBLE); footViewHolder.tvLoading.setVisibility(View.VISIBLE); footViewHolder.llEnd.setVisibility(View.GONE); break; case LOADING_COMPLETE: // 加载完成 footViewHolder.pbLoading.setVisibility(View.INVISIBLE); footViewHolder.tvLoading.setVisibility(View.INVISIBLE); footViewHolder.llEnd.setVisibility(View.GONE); break; case LOADING_END: // 加载到底 footViewHolder.pbLoading.setVisibility(View.GONE); footViewHolder.tvLoading.setVisibility(View.GONE); footViewHolder.llEnd.setVisibility(View.VISIBLE); break; default: break; } } } @Override public int getItemCount() { return dataList.size() + 1; } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager instanceof GridLayoutManager) { final GridLayoutManager gridManager = ((GridLayoutManager) manager); gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // 如果当前是footer的位置,那么该item占据2个单元格,正常情况下占据1个单元格 return getItemViewType(position) == TYPE_FOOTER ? gridManager.getSpanCount() : 1; } }); } } private class RecyclerViewHolder extends RecyclerView.ViewHolder { TextView tvItem; RecyclerViewHolder(View itemView) { super(itemView); tvItem = (TextView) itemView.findViewById(R.id.tv_item); } } private class FootViewHolder extends RecyclerView.ViewHolder { ProgressBar pbLoading; TextView tvLoading; LinearLayout llEnd; FootViewHolder(View itemView) { super(itemView); pbLoading = (ProgressBar) itemView.findViewById(R.id.pb_loading); tvLoading = (TextView) itemView.findViewById(R.id.tv_loading); llEnd = (LinearLayout) itemView.findViewById(R.id.ll_end); } } /** * 设置上拉加载状态 * * @param loadState 0.正在加载 1.加载完成 2.加载到底 */ public void setLoadState(int loadState) { this.loadState = loadState; notifyDataSetChanged(); } }
alidili/Demos
RecyclerViewRefreshDemo/app/src/main/java/com/yl/recyclerview/adapter/LoadMoreAdapter.java
1,148
// 如果当前是footer的位置,那么该item占据2个单元格,正常情况下占据1个单元格
line_comment
zh-cn
package com.yl.recyclerview.adapter; import android.content.Context; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.yl.recyclerview.R; import java.util.List; /** * 上拉加载更多 * Created by yangle on 2017/10/12. */ public class LoadMoreAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<String> dataList; // 普通布局 private final int TYPE_ITEM = 1; // 脚布局 private final int TYPE_FOOTER = 2; // 当前加载状态,默认为加载完成 private int loadState = 2; // 正在加载 public final int LOADING = 1; // 加载完成 public final int LOADING_COMPLETE = 2; // 加载到底 public final int LOADING_END = 3; public LoadMoreAdapter(List<String> dataList) { this.dataList = dataList; } @Override public int getItemViewType(int position) { // 最后一个item设置为FooterView if (position + 1 == getItemCount()) { return TYPE_FOOTER; } else { return TYPE_ITEM; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // 通过判断显示类型,来创建不同的View if (viewType == TYPE_ITEM) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_recyclerview, parent, false); return new RecyclerViewHolder(view); } else if (viewType == TYPE_FOOTER) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_refresh_footer, parent, false); return new FootViewHolder(view); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof RecyclerViewHolder) { RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder; recyclerViewHolder.tvItem.setText(dataList.get(position)); } else if (holder instanceof FootViewHolder) { FootViewHolder footViewHolder = (FootViewHolder) holder; switch (loadState) { case LOADING: // 正在加载 footViewHolder.pbLoading.setVisibility(View.VISIBLE); footViewHolder.tvLoading.setVisibility(View.VISIBLE); footViewHolder.llEnd.setVisibility(View.GONE); break; case LOADING_COMPLETE: // 加载完成 footViewHolder.pbLoading.setVisibility(View.INVISIBLE); footViewHolder.tvLoading.setVisibility(View.INVISIBLE); footViewHolder.llEnd.setVisibility(View.GONE); break; case LOADING_END: // 加载到底 footViewHolder.pbLoading.setVisibility(View.GONE); footViewHolder.tvLoading.setVisibility(View.GONE); footViewHolder.llEnd.setVisibility(View.VISIBLE); break; default: break; } } } @Override public int getItemCount() { return dataList.size() + 1; } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager instanceof GridLayoutManager) { final GridLayoutManager gridManager = ((GridLayoutManager) manager); gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // 如果 <SUF> return getItemViewType(position) == TYPE_FOOTER ? gridManager.getSpanCount() : 1; } }); } } private class RecyclerViewHolder extends RecyclerView.ViewHolder { TextView tvItem; RecyclerViewHolder(View itemView) { super(itemView); tvItem = (TextView) itemView.findViewById(R.id.tv_item); } } private class FootViewHolder extends RecyclerView.ViewHolder { ProgressBar pbLoading; TextView tvLoading; LinearLayout llEnd; FootViewHolder(View itemView) { super(itemView); pbLoading = (ProgressBar) itemView.findViewById(R.id.pb_loading); tvLoading = (TextView) itemView.findViewById(R.id.tv_loading); llEnd = (LinearLayout) itemView.findViewById(R.id.ll_end); } } /** * 设置上拉加载状态 * * @param loadState 0.正在加载 1.加载完成 2.加载到底 */ public void setLoadState(int loadState) { this.loadState = loadState; notifyDataSetChanged(); } }
false
982
23
1,148
26
1,207
23
1,148
26
1,471
42
false
false
false
false
false
true
33886_3
package com.jayqqaa12.abase.kit.sys; import java.lang.reflect.Field; import android.app.admin.DevicePolicyManager; import android.os.Build; import android.os.PowerManager; import android.view.View; import android.widget.Toast; import com.jayqqaa12.abase.core.Abase; import com.jayqqaa12.abase.kit.ManageKit; /** * 系统 工具 * @author jayqqaa12 * @date 2013-5-15 */ public class SysKit { /** * 获得 手机 系统的 相关 信息 * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static String getSysInfo() throws IllegalArgumentException, IllegalAccessException { StringBuffer sb = new StringBuffer(); // 2.获取手机的硬件信息. Field[] fields = Build.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); String name = fields[i].getName(); sb.append(name + " = "); String value = fields[i].get(null).toString(); sb.append(value); sb.append("\n"); } return sb.toString(); } /** * 恢复出厂设置 可用于 更新 */ public static void recovery() { PowerManager pm = ManageKit.getPowerManager(); pm.reboot("recovery"); } /** * 自杀 */ public static void killMyself() { // 完成自杀的操作 android.os.Process.killProcess(android.os.Process.myPid()); } /** * 恢复 出厂模式! */ public static void wipeData() { DevicePolicyManager manager = ManageKit.getDevicePolicyManager(); manager.wipeData(0); } /** * 无权限 重启 手机 记得 必需在 主线程显示 写个 线程 发消息 发个几万次 就差不多了 * */ public static void reboot() { Toast toast = new Toast(Abase.getContext()); View view = new View(Abase.getContext()); toast.setView(view); toast.show(); } }
alien6u/graduation-reader
abase/abase/com/jayqqaa12/abase/kit/sys/SysKit.java
596
/** * 恢复出厂设置 可用于 更新 */
block_comment
zh-cn
package com.jayqqaa12.abase.kit.sys; import java.lang.reflect.Field; import android.app.admin.DevicePolicyManager; import android.os.Build; import android.os.PowerManager; import android.view.View; import android.widget.Toast; import com.jayqqaa12.abase.core.Abase; import com.jayqqaa12.abase.kit.ManageKit; /** * 系统 工具 * @author jayqqaa12 * @date 2013-5-15 */ public class SysKit { /** * 获得 手机 系统的 相关 信息 * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static String getSysInfo() throws IllegalArgumentException, IllegalAccessException { StringBuffer sb = new StringBuffer(); // 2.获取手机的硬件信息. Field[] fields = Build.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); String name = fields[i].getName(); sb.append(name + " = "); String value = fields[i].get(null).toString(); sb.append(value); sb.append("\n"); } return sb.toString(); } /** * 恢复出 <SUF>*/ public static void recovery() { PowerManager pm = ManageKit.getPowerManager(); pm.reboot("recovery"); } /** * 自杀 */ public static void killMyself() { // 完成自杀的操作 android.os.Process.killProcess(android.os.Process.myPid()); } /** * 恢复 出厂模式! */ public static void wipeData() { DevicePolicyManager manager = ManageKit.getDevicePolicyManager(); manager.wipeData(0); } /** * 无权限 重启 手机 记得 必需在 主线程显示 写个 线程 发消息 发个几万次 就差不多了 * */ public static void reboot() { Toast toast = new Toast(Abase.getContext()); View view = new View(Abase.getContext()); toast.setView(view); toast.show(); } }
false
506
15
596
15
598
14
596
15
752
23
false
false
false
false
false
true
61052_2
/* * 1. Java 规范的三种注释方式: * 单行注释 * 多行注释 * 文档注释(Java特有) * @author 指定Java程序的作者 * @version * * 2. 单行注释和多行注释的作用: * * 对所写的程序进行解释说明,增强可读性,方便自己,方便别人 * * 调试所写的代码 * * 3. 特点: * 单行注释和多行注释,注释了的内容不参与编译 * 换句话说,编译以后生成的.class结尾的字节码文件中不包含注释掉的信息 * * 4. 文档注释的使用: * 注释内容可以被JDK提供的工具 javadoc 所解析,生成一套以网页文件形式体现的该程序的说明文档 * javadoc -d J035 -author -version J035_Java注释.java * * 5. 多行注释不可以嵌套 */ /** * 文档注释 * @author James Liu * @version 1.0 * * 这是第一个 Java 程序! */ public class J035_Java注释 { /* * 多行注释 * 如下的main方法是程序的入口! * main的格式是固定的! */ /** * 如下的方法是 main()。作用:程序的入口。 * @param args */ public static void main(String[] args) { // 单行注释: 如下的语句表示输出到控制台 System.out.println("Hello Java World"); } }
alifespace/java-learning
basic_Video/J035_Java注释.java
401
/* * 多行注释 * 如下的main方法是程序的入口! * main的格式是固定的! */
block_comment
zh-cn
/* * 1. Java 规范的三种注释方式: * 单行注释 * 多行注释 * 文档注释(Java特有) * @author 指定Java程序的作者 * @version * * 2. 单行注释和多行注释的作用: * * 对所写的程序进行解释说明,增强可读性,方便自己,方便别人 * * 调试所写的代码 * * 3. 特点: * 单行注释和多行注释,注释了的内容不参与编译 * 换句话说,编译以后生成的.class结尾的字节码文件中不包含注释掉的信息 * * 4. 文档注释的使用: * 注释内容可以被JDK提供的工具 javadoc 所解析,生成一套以网页文件形式体现的该程序的说明文档 * javadoc -d J035 -author -version J035_Java注释.java * * 5. 多行注释不可以嵌套 */ /** * 文档注释 * @author James Liu * @version 1.0 * * 这是第一个 Java 程序! */ public class J035_Java注释 { /* * 多行注 <SUF>*/ /** * 如下的方法是 main()。作用:程序的入口。 * @param args */ public static void main(String[] args) { // 单行注释: 如下的语句表示输出到控制台 System.out.println("Hello Java World"); } }
false
406
34
401
33
385
34
401
33
590
46
false
false
false
false
false
true
46469_1
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 直播间领取惊喜福卡或万能福 * * @author auto create * @since 1.0, 2021-01-14 17:25:11 */ public class AlipayFundCouponWufuLiveAcceptModel extends AlipayObject { private static final long serialVersionUID = 3626145271476379884L; /** * 发卡类型:WAN_NENG_FU-万能福,SURPRISE_CARD-惊喜福卡 */ @ApiField("card_type") private String cardType; /** * 业务流水号 */ @ApiField("front_biz_no") private String frontBizNo; /** * 淘宝主播ID */ @ApiField("scene") private String scene; /** * 淘宝用户ID */ @ApiField("taobao_id") private String taobaoId; public String getCardType() { return this.cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getFrontBizNo() { return this.frontBizNo; } public void setFrontBizNo(String frontBizNo) { this.frontBizNo = frontBizNo; } public String getScene() { return this.scene; } public void setScene(String scene) { this.scene = scene; } public String getTaobaoId() { return this.taobaoId; } public void setTaobaoId(String taobaoId) { this.taobaoId = taobaoId; } }
alipay/alipay-sdk-java-all
v2/src/main/java/com/alipay/api/domain/AlipayFundCouponWufuLiveAcceptModel.java
493
/** * 发卡类型:WAN_NENG_FU-万能福,SURPRISE_CARD-惊喜福卡 */
block_comment
zh-cn
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 直播间领取惊喜福卡或万能福 * * @author auto create * @since 1.0, 2021-01-14 17:25:11 */ public class AlipayFundCouponWufuLiveAcceptModel extends AlipayObject { private static final long serialVersionUID = 3626145271476379884L; /** * 发卡类 <SUF>*/ @ApiField("card_type") private String cardType; /** * 业务流水号 */ @ApiField("front_biz_no") private String frontBizNo; /** * 淘宝主播ID */ @ApiField("scene") private String scene; /** * 淘宝用户ID */ @ApiField("taobao_id") private String taobaoId; public String getCardType() { return this.cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getFrontBizNo() { return this.frontBizNo; } public void setFrontBizNo(String frontBizNo) { this.frontBizNo = frontBizNo; } public String getScene() { return this.scene; } public void setScene(String scene) { this.scene = scene; } public String getTaobaoId() { return this.taobaoId; } public void setTaobaoId(String taobaoId) { this.taobaoId = taobaoId; } }
false
388
29
491
33
461
29
491
33
562
45
false
false
false
false
false
true
23662_5
// This file is auto-generated, don't edit it. Thanks. package com.antgroup.antchain.openapi.twc.models; import com.aliyun.tea.*; public class ApplyFlowEvidenceRequest extends TeaModel { // OAuth模式下的授权token @NameInMap("auth_token") public String authToken; @NameInMap("product_instance_id") public String productInstanceId; // 流程id @NameInMap("flow_id") @Validation(required = true) public String flowId; // 证据包类型,默认为ChainEvidencePack(链上证据包),按需填写,目前支持ChainEvidencePack(链上证据包),其他包括LocalEvidencePack(链下证据包),链下证据包前置依赖链上证据包,因此填写链下证据包会先生成链上证据包。 // 链上证据包,即全流程所有阶段存证关系链上固化,生成全流程链上证据统一txHash; // 链下证据包,即全流程所有内容生成链下压缩包文件。 @NameInMap("evidence_pack_type") @Validation(required = true) public String evidencePackType; public static ApplyFlowEvidenceRequest build(java.util.Map<String, ?> map) throws Exception { ApplyFlowEvidenceRequest self = new ApplyFlowEvidenceRequest(); return TeaModel.build(map, self); } public ApplyFlowEvidenceRequest setAuthToken(String authToken) { this.authToken = authToken; return this; } public String getAuthToken() { return this.authToken; } public ApplyFlowEvidenceRequest setProductInstanceId(String productInstanceId) { this.productInstanceId = productInstanceId; return this; } public String getProductInstanceId() { return this.productInstanceId; } public ApplyFlowEvidenceRequest setFlowId(String flowId) { this.flowId = flowId; return this; } public String getFlowId() { return this.flowId; } public ApplyFlowEvidenceRequest setEvidencePackType(String evidencePackType) { this.evidencePackType = evidencePackType; return this; } public String getEvidencePackType() { return this.evidencePackType; } }
alipay/antchain-openapi-prod-sdk
twc/java/src/main/java/com/antgroup/antchain/openapi/twc/models/ApplyFlowEvidenceRequest.java
529
// 链下证据包,即全流程所有内容生成链下压缩包文件。
line_comment
zh-cn
// This file is auto-generated, don't edit it. Thanks. package com.antgroup.antchain.openapi.twc.models; import com.aliyun.tea.*; public class ApplyFlowEvidenceRequest extends TeaModel { // OAuth模式下的授权token @NameInMap("auth_token") public String authToken; @NameInMap("product_instance_id") public String productInstanceId; // 流程id @NameInMap("flow_id") @Validation(required = true) public String flowId; // 证据包类型,默认为ChainEvidencePack(链上证据包),按需填写,目前支持ChainEvidencePack(链上证据包),其他包括LocalEvidencePack(链下证据包),链下证据包前置依赖链上证据包,因此填写链下证据包会先生成链上证据包。 // 链上证据包,即全流程所有阶段存证关系链上固化,生成全流程链上证据统一txHash; // 链下 <SUF> @NameInMap("evidence_pack_type") @Validation(required = true) public String evidencePackType; public static ApplyFlowEvidenceRequest build(java.util.Map<String, ?> map) throws Exception { ApplyFlowEvidenceRequest self = new ApplyFlowEvidenceRequest(); return TeaModel.build(map, self); } public ApplyFlowEvidenceRequest setAuthToken(String authToken) { this.authToken = authToken; return this; } public String getAuthToken() { return this.authToken; } public ApplyFlowEvidenceRequest setProductInstanceId(String productInstanceId) { this.productInstanceId = productInstanceId; return this; } public String getProductInstanceId() { return this.productInstanceId; } public ApplyFlowEvidenceRequest setFlowId(String flowId) { this.flowId = flowId; return this; } public String getFlowId() { return this.flowId; } public ApplyFlowEvidenceRequest setEvidencePackType(String evidencePackType) { this.evidencePackType = evidencePackType; return this; } public String getEvidencePackType() { return this.evidencePackType; } }
false
474
19
529
20
546
18
529
20
741
38
false
false
false
false
false
true
56847_8
package com.aliyun.roompaas.live; import android.support.annotation.NonNull; import com.alibaba.dingpaas.base.DPSError; import com.alibaba.dingpaas.live.ContinuePlaybackTimingCb; import com.alibaba.dingpaas.live.ContinuePlaybackTimingReq; import com.alibaba.dingpaas.live.ContinuePlaybackTimingRsp; import com.alibaba.dingpaas.live.EndLiveTimingCb; import com.alibaba.dingpaas.live.EndLiveTimingReq; import com.alibaba.dingpaas.live.EndLiveTimingRsp; import com.alibaba.dingpaas.live.EndPlaybackTimingCb; import com.alibaba.dingpaas.live.EndPlaybackTimingReq; import com.alibaba.dingpaas.live.EndPlaybackTimingRsp; import com.alibaba.dingpaas.live.GetLiveDetailCb; import com.alibaba.dingpaas.live.GetLiveDetailReq; import com.alibaba.dingpaas.live.GetLiveDetailRsp; import com.alibaba.dingpaas.live.LiveModule; import com.alibaba.dingpaas.live.LiveRpcInterface; import com.alibaba.dingpaas.live.PublishLiveCb; import com.alibaba.dingpaas.live.PublishLiveReq; import com.alibaba.dingpaas.live.PublishLiveRsp; import com.alibaba.dingpaas.live.StartLiveTimingCb; import com.alibaba.dingpaas.live.StartLiveTimingReq; import com.alibaba.dingpaas.live.StartLiveTimingRsp; import com.alibaba.dingpaas.live.StartPlaybackTimingCb; import com.alibaba.dingpaas.live.StartPlaybackTimingReq; import com.alibaba.dingpaas.live.StartPlaybackTimingRsp; import com.alibaba.dingpaas.monitorhub.MonitorhubField; import com.alibaba.dingpaas.room.CreateLiveCb; import com.alibaba.dingpaas.room.CreateLiveReq; import com.alibaba.dingpaas.room.CreateLiveRsp; import com.alibaba.dingpaas.room.RoomDetail; import com.alibaba.dingpaas.room.RoomExtInterface; import com.alibaba.dingpaas.room.RoomInfo; import com.alibaba.dingpaas.room.RoomModule; import com.alibaba.dingpaas.room.RoomRpcInterface; import com.alibaba.fastjson.JSON; import com.aliyun.roompaas.base.PluginManager; import com.aliyun.roompaas.base.RoomContext; import com.aliyun.roompaas.base.exposable.Callback; import com.aliyun.roompaas.base.log.Logger; import com.aliyun.roompaas.base.monitor.MonitorHubChannel; import com.aliyun.roompaas.base.util.CollectionUtil; import com.aliyun.roompaas.base.util.Utils; import com.aliyun.roompaas.live.exposable.BusinessOptions; import java.util.List; /** * 直播辅助类<hr/> * {@link LiveServiceImpl} 和 {@link LiveInnerServiceImpl} 两个服务都需要要调用的代码部分, 单独抽取出来 * * @author puke * @version 2021/6/24 */ class LiveHelper { private static final String TAG = LiveHelper.class.getSimpleName(); private final RoomContext roomContext; private final String userId; private final RoomRpcInterface roomRpcInterface; private final RoomExtInterface roomExtInterface; private final LiveRpcInterface liveRpcInterface; private final PluginManager pluginManager; public LiveHelper(RoomContext roomContext) { this.roomContext = roomContext; userId = roomContext.getUserId(); String roomId = roomContext.getRoomId(); pluginManager = roomContext.getPluginManager(); roomRpcInterface = RoomModule.getModule(userId).getRpcInterface(); roomExtInterface = RoomModule.getModule(userId).getExtInterface(); liveRpcInterface = LiveModule.getModule(userId).getRpcInterface(); } public void getPushStreamUrl(@NonNull final Callback<String> callback) { getPushStreamUrl(null, callback); } public void getPushStreamUrl(BusinessOptions options, @NonNull final Callback<String> callback) { // 查询房间直播 List<String> liveIds = pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID); // 取出第一个 final String liveId = CollectionUtil.getFirst(liveIds); if (liveId != null) { // 有直播 getPushStreamUrlById(liveId, callback); } else { // 无直播, 先创建 CreateLiveReq req = new CreateLiveReq(); req.anchorId = userId; req.roomId = roomContext.getRoomId(); RoomDetail roomDetail = roomContext.getRoomDetail(); if (roomDetail != null) { RoomInfo roomInfo = roomDetail.roomInfo; if (roomInfo != null) { req.title = roomInfo.title; } } if (options != null) { req.preStartDate = options.liveStartTime; req.preEndDate = options.liveEndTime; req.coverUrl = options.liveCoverUrl; req.userDefineField = options.extension; } roomExtInterface.createLive(req, new CreateLiveCb() { @Override public void onSuccess(CreateLiveRsp rsp) { // 创建成功后, 存下liveId, 然后start pluginManager.addInstanceId(LiveServiceImpl.PLUGIN_ID, rsp.liveId); getPushStreamUrlById(rsp.liveId, callback); } @Override public void onFailure(DPSError dpsError) { Utils.callErrorWithDps(callback, dpsError); } }); } } private void getPushStreamUrlById(String liveId, @NonNull final Callback<String> callback) { GetLiveDetailReq req = new GetLiveDetailReq(); req.uuid = liveId; liveRpcInterface.getLiveDetail(req, new GetLiveDetailCb() { @Override public void onSuccess(GetLiveDetailRsp liveDetail) { Logger.i(TAG, "get live detail, " + JSON.toJSONString(liveDetail.live)); callback.onSuccess(liveDetail.live.pushUrl); } @Override public void onFailure(DPSError dpsError) { Utils.callErrorWithDps(callback, dpsError); } }); MonitorHubChannel.setBizId(liveId); } public void reportLiveStatus() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { PublishLiveReq req = new PublishLiveReq(); req.uuid = pushedLiveId; liveRpcInterface.publishLive(req, new PublishLiveCb() { @Override public void onSuccess(PublishLiveRsp publishLiveRsp) { Logger.i(TAG, "publishLive success"); MonitorHubChannel.publishLive(MonitorhubField.MFFIELD_COMMON_RTMP, MonitorHubChannel.REPORT_EVENT_SUCCESS_CODE, null); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, "publishLive error: " + dpsError.reason); MonitorHubChannel.publishLive(MonitorhubField.MFFIELD_COMMON_RTMP, dpsError.code, dpsError.reason); } }); } } /** * 观众-开始观看直播数据上报 */ public void startLiveTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { StartLiveTimingReq req = new StartLiveTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.startLiveTiming(req, new StartLiveTimingCb() { @Override public void onSuccess(StartLiveTimingRsp startLiveTimingRsp) { Logger.i(TAG, "startLiveTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, String.format("startLiveTiming error. code: %d, reason: %s", dpsError.code, dpsError.reason)); } }); } } /** * 观众-结束直播观看数据上报 */ public void endLiveTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { EndLiveTimingReq req = new EndLiveTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.endLiveTiming(req, new EndLiveTimingCb() { @Override public void onSuccess(EndLiveTimingRsp endLiveTimingRsp) { Logger.i(TAG, "endLiveTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, String.format("endLiveTiming error. code: %d, reason: %s", dpsError.code, dpsError.reason)); } }); } } /** * 观众-开始观看回放数据上报 */ public void startPlaybackTiming(String transId) { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { StartPlaybackTimingReq req = new StartPlaybackTimingReq(); req.uuid = pushedLiveId; req.transId = transId; liveRpcInterface.startPlaybackTiming(req, new StartPlaybackTimingCb() { @Override public void onSuccess(StartPlaybackTimingRsp startPlaybackTimingRsp) { Logger.i(TAG, "startPlaybackTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, String.format("startPlaybackTiming error. code: %d, reason: %s", dpsError.code, dpsError.reason)); } }); } } /** * 观众-观看过程中间隔数据上报 */ public void continuePlaybackTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { ContinuePlaybackTimingReq req = new ContinuePlaybackTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.continuePlaybackTiming(req, new ContinuePlaybackTimingCb() { @Override public void onSuccess(ContinuePlaybackTimingRsp continuePlaybackTimingRsp) { Logger.i(TAG, "continuePlaybackTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, "continuePlaybackTiming error: " + dpsError.reason); } }); } } /** * 观众-结束回放观看时数据上报 */ public void endPlaybackTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { EndPlaybackTimingReq req = new EndPlaybackTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.endPlaybackTiming(req, new EndPlaybackTimingCb() { @Override public void onSuccess(EndPlaybackTimingRsp endPlaybackTimingRsp) { Logger.i(TAG, "endPlaybackTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, "endPlaybackTiming error: " + dpsError.reason); } }); } } }
aliyun/alibabacloud-AliIMPInteractiveLive-Demo
Android/SDK/live/src/main/java/com/aliyun/roompaas/live/LiveHelper.java
2,726
/** * 观众-开始观看回放数据上报 */
block_comment
zh-cn
package com.aliyun.roompaas.live; import android.support.annotation.NonNull; import com.alibaba.dingpaas.base.DPSError; import com.alibaba.dingpaas.live.ContinuePlaybackTimingCb; import com.alibaba.dingpaas.live.ContinuePlaybackTimingReq; import com.alibaba.dingpaas.live.ContinuePlaybackTimingRsp; import com.alibaba.dingpaas.live.EndLiveTimingCb; import com.alibaba.dingpaas.live.EndLiveTimingReq; import com.alibaba.dingpaas.live.EndLiveTimingRsp; import com.alibaba.dingpaas.live.EndPlaybackTimingCb; import com.alibaba.dingpaas.live.EndPlaybackTimingReq; import com.alibaba.dingpaas.live.EndPlaybackTimingRsp; import com.alibaba.dingpaas.live.GetLiveDetailCb; import com.alibaba.dingpaas.live.GetLiveDetailReq; import com.alibaba.dingpaas.live.GetLiveDetailRsp; import com.alibaba.dingpaas.live.LiveModule; import com.alibaba.dingpaas.live.LiveRpcInterface; import com.alibaba.dingpaas.live.PublishLiveCb; import com.alibaba.dingpaas.live.PublishLiveReq; import com.alibaba.dingpaas.live.PublishLiveRsp; import com.alibaba.dingpaas.live.StartLiveTimingCb; import com.alibaba.dingpaas.live.StartLiveTimingReq; import com.alibaba.dingpaas.live.StartLiveTimingRsp; import com.alibaba.dingpaas.live.StartPlaybackTimingCb; import com.alibaba.dingpaas.live.StartPlaybackTimingReq; import com.alibaba.dingpaas.live.StartPlaybackTimingRsp; import com.alibaba.dingpaas.monitorhub.MonitorhubField; import com.alibaba.dingpaas.room.CreateLiveCb; import com.alibaba.dingpaas.room.CreateLiveReq; import com.alibaba.dingpaas.room.CreateLiveRsp; import com.alibaba.dingpaas.room.RoomDetail; import com.alibaba.dingpaas.room.RoomExtInterface; import com.alibaba.dingpaas.room.RoomInfo; import com.alibaba.dingpaas.room.RoomModule; import com.alibaba.dingpaas.room.RoomRpcInterface; import com.alibaba.fastjson.JSON; import com.aliyun.roompaas.base.PluginManager; import com.aliyun.roompaas.base.RoomContext; import com.aliyun.roompaas.base.exposable.Callback; import com.aliyun.roompaas.base.log.Logger; import com.aliyun.roompaas.base.monitor.MonitorHubChannel; import com.aliyun.roompaas.base.util.CollectionUtil; import com.aliyun.roompaas.base.util.Utils; import com.aliyun.roompaas.live.exposable.BusinessOptions; import java.util.List; /** * 直播辅助类<hr/> * {@link LiveServiceImpl} 和 {@link LiveInnerServiceImpl} 两个服务都需要要调用的代码部分, 单独抽取出来 * * @author puke * @version 2021/6/24 */ class LiveHelper { private static final String TAG = LiveHelper.class.getSimpleName(); private final RoomContext roomContext; private final String userId; private final RoomRpcInterface roomRpcInterface; private final RoomExtInterface roomExtInterface; private final LiveRpcInterface liveRpcInterface; private final PluginManager pluginManager; public LiveHelper(RoomContext roomContext) { this.roomContext = roomContext; userId = roomContext.getUserId(); String roomId = roomContext.getRoomId(); pluginManager = roomContext.getPluginManager(); roomRpcInterface = RoomModule.getModule(userId).getRpcInterface(); roomExtInterface = RoomModule.getModule(userId).getExtInterface(); liveRpcInterface = LiveModule.getModule(userId).getRpcInterface(); } public void getPushStreamUrl(@NonNull final Callback<String> callback) { getPushStreamUrl(null, callback); } public void getPushStreamUrl(BusinessOptions options, @NonNull final Callback<String> callback) { // 查询房间直播 List<String> liveIds = pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID); // 取出第一个 final String liveId = CollectionUtil.getFirst(liveIds); if (liveId != null) { // 有直播 getPushStreamUrlById(liveId, callback); } else { // 无直播, 先创建 CreateLiveReq req = new CreateLiveReq(); req.anchorId = userId; req.roomId = roomContext.getRoomId(); RoomDetail roomDetail = roomContext.getRoomDetail(); if (roomDetail != null) { RoomInfo roomInfo = roomDetail.roomInfo; if (roomInfo != null) { req.title = roomInfo.title; } } if (options != null) { req.preStartDate = options.liveStartTime; req.preEndDate = options.liveEndTime; req.coverUrl = options.liveCoverUrl; req.userDefineField = options.extension; } roomExtInterface.createLive(req, new CreateLiveCb() { @Override public void onSuccess(CreateLiveRsp rsp) { // 创建成功后, 存下liveId, 然后start pluginManager.addInstanceId(LiveServiceImpl.PLUGIN_ID, rsp.liveId); getPushStreamUrlById(rsp.liveId, callback); } @Override public void onFailure(DPSError dpsError) { Utils.callErrorWithDps(callback, dpsError); } }); } } private void getPushStreamUrlById(String liveId, @NonNull final Callback<String> callback) { GetLiveDetailReq req = new GetLiveDetailReq(); req.uuid = liveId; liveRpcInterface.getLiveDetail(req, new GetLiveDetailCb() { @Override public void onSuccess(GetLiveDetailRsp liveDetail) { Logger.i(TAG, "get live detail, " + JSON.toJSONString(liveDetail.live)); callback.onSuccess(liveDetail.live.pushUrl); } @Override public void onFailure(DPSError dpsError) { Utils.callErrorWithDps(callback, dpsError); } }); MonitorHubChannel.setBizId(liveId); } public void reportLiveStatus() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { PublishLiveReq req = new PublishLiveReq(); req.uuid = pushedLiveId; liveRpcInterface.publishLive(req, new PublishLiveCb() { @Override public void onSuccess(PublishLiveRsp publishLiveRsp) { Logger.i(TAG, "publishLive success"); MonitorHubChannel.publishLive(MonitorhubField.MFFIELD_COMMON_RTMP, MonitorHubChannel.REPORT_EVENT_SUCCESS_CODE, null); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, "publishLive error: " + dpsError.reason); MonitorHubChannel.publishLive(MonitorhubField.MFFIELD_COMMON_RTMP, dpsError.code, dpsError.reason); } }); } } /** * 观众-开始观看直播数据上报 */ public void startLiveTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { StartLiveTimingReq req = new StartLiveTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.startLiveTiming(req, new StartLiveTimingCb() { @Override public void onSuccess(StartLiveTimingRsp startLiveTimingRsp) { Logger.i(TAG, "startLiveTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, String.format("startLiveTiming error. code: %d, reason: %s", dpsError.code, dpsError.reason)); } }); } } /** * 观众-结束直播观看数据上报 */ public void endLiveTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { EndLiveTimingReq req = new EndLiveTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.endLiveTiming(req, new EndLiveTimingCb() { @Override public void onSuccess(EndLiveTimingRsp endLiveTimingRsp) { Logger.i(TAG, "endLiveTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, String.format("endLiveTiming error. code: %d, reason: %s", dpsError.code, dpsError.reason)); } }); } } /** * 观众- <SUF>*/ public void startPlaybackTiming(String transId) { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { StartPlaybackTimingReq req = new StartPlaybackTimingReq(); req.uuid = pushedLiveId; req.transId = transId; liveRpcInterface.startPlaybackTiming(req, new StartPlaybackTimingCb() { @Override public void onSuccess(StartPlaybackTimingRsp startPlaybackTimingRsp) { Logger.i(TAG, "startPlaybackTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, String.format("startPlaybackTiming error. code: %d, reason: %s", dpsError.code, dpsError.reason)); } }); } } /** * 观众-观看过程中间隔数据上报 */ public void continuePlaybackTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { ContinuePlaybackTimingReq req = new ContinuePlaybackTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.continuePlaybackTiming(req, new ContinuePlaybackTimingCb() { @Override public void onSuccess(ContinuePlaybackTimingRsp continuePlaybackTimingRsp) { Logger.i(TAG, "continuePlaybackTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, "continuePlaybackTiming error: " + dpsError.reason); } }); } } /** * 观众-结束回放观看时数据上报 */ public void endPlaybackTiming() { String pushedLiveId = CollectionUtil.getFirst( pluginManager.getInstanceIds(LiveServiceImpl.PLUGIN_ID)); if (pushedLiveId != null) { EndPlaybackTimingReq req = new EndPlaybackTimingReq(); req.uuid = pushedLiveId; liveRpcInterface.endPlaybackTiming(req, new EndPlaybackTimingCb() { @Override public void onSuccess(EndPlaybackTimingRsp endPlaybackTimingRsp) { Logger.i(TAG, "endPlaybackTiming success"); } @Override public void onFailure(DPSError dpsError) { Logger.e(TAG, "endPlaybackTiming error: " + dpsError.reason); } }); } } }
false
2,387
16
2,726
17
2,853
17
2,726
17
3,443
29
false
false
false
false
false
true
45111_45
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sdk.service.dt_oc_info20220829.models; import com.aliyun.core.annotation.*; import darabonba.core.RequestModel; import darabonba.core.TeaModel; import com.aliyun.sdk.gateway.pop.models.*; /** * {@link GetOcJusticeJudgementDocResponseBody} extends {@link TeaModel} * * <p>GetOcJusticeJudgementDocResponseBody</p> */ public class GetOcJusticeJudgementDocResponseBody extends TeaModel { @NameInMap("Code") private String code; @NameInMap("Data") private java.util.List < Data> data; @NameInMap("Message") private String message; @NameInMap("PageIndex") private Integer pageIndex; @NameInMap("PageNum") private Integer pageNum; @NameInMap("RequestId") private String requestId; @NameInMap("Success") private Boolean success; @NameInMap("TotalNum") private Integer totalNum; private GetOcJusticeJudgementDocResponseBody(Builder builder) { this.code = builder.code; this.data = builder.data; this.message = builder.message; this.pageIndex = builder.pageIndex; this.pageNum = builder.pageNum; this.requestId = builder.requestId; this.success = builder.success; this.totalNum = builder.totalNum; } public static Builder builder() { return new Builder(); } public static GetOcJusticeJudgementDocResponseBody create() { return builder().build(); } /** * @return code */ public String getCode() { return this.code; } /** * @return data */ public java.util.List < Data> getData() { return this.data; } /** * @return message */ public String getMessage() { return this.message; } /** * @return pageIndex */ public Integer getPageIndex() { return this.pageIndex; } /** * @return pageNum */ public Integer getPageNum() { return this.pageNum; } /** * @return requestId */ public String getRequestId() { return this.requestId; } /** * @return success */ public Boolean getSuccess() { return this.success; } /** * @return totalNum */ public Integer getTotalNum() { return this.totalNum; } public static final class Builder { private String code; private java.util.List < Data> data; private String message; private Integer pageIndex; private Integer pageNum; private String requestId; private Boolean success; private Integer totalNum; /** * Code. */ public Builder code(String code) { this.code = code; return this; } /** * Data. */ public Builder data(java.util.List < Data> data) { this.data = data; return this; } /** * Message. */ public Builder message(String message) { this.message = message; return this; } /** * PageIndex. */ public Builder pageIndex(Integer pageIndex) { this.pageIndex = pageIndex; return this; } /** * PageNum. */ public Builder pageNum(Integer pageNum) { this.pageNum = pageNum; return this; } /** * RequestId. */ public Builder requestId(String requestId) { this.requestId = requestId; return this; } /** * Success. */ public Builder success(Boolean success) { this.success = success; return this; } /** * TotalNum. */ public Builder totalNum(Integer totalNum) { this.totalNum = totalNum; return this; } public GetOcJusticeJudgementDocResponseBody build() { return new GetOcJusticeJudgementDocResponseBody(this); } } public static class Data extends TeaModel { @NameInMap("CaseFlow") private String caseFlow; @NameInMap("CaseNum") private String caseNum; @NameInMap("CaseType") private String caseType; @NameInMap("CauseAction") private String causeAction; @NameInMap("Court") private String court; @NameInMap("Defendant") private String defendant; @NameInMap("JudgeDate") private String judgeDate; @NameInMap("JudgeResult") private String judgeResult; @NameInMap("JudgeType") private String judgeType; @NameInMap("Party") private String party; @NameInMap("Plaintiff") private String plaintiff; @NameInMap("PublicDate") private String publicDate; @NameInMap("Role") private String role; @NameInMap("SubAmount") private String subAmount; @NameInMap("Title") private String title; private Data(Builder builder) { this.caseFlow = builder.caseFlow; this.caseNum = builder.caseNum; this.caseType = builder.caseType; this.causeAction = builder.causeAction; this.court = builder.court; this.defendant = builder.defendant; this.judgeDate = builder.judgeDate; this.judgeResult = builder.judgeResult; this.judgeType = builder.judgeType; this.party = builder.party; this.plaintiff = builder.plaintiff; this.publicDate = builder.publicDate; this.role = builder.role; this.subAmount = builder.subAmount; this.title = builder.title; } public static Builder builder() { return new Builder(); } public static Data create() { return builder().build(); } /** * @return caseFlow */ public String getCaseFlow() { return this.caseFlow; } /** * @return caseNum */ public String getCaseNum() { return this.caseNum; } /** * @return caseType */ public String getCaseType() { return this.caseType; } /** * @return causeAction */ public String getCauseAction() { return this.causeAction; } /** * @return court */ public String getCourt() { return this.court; } /** * @return defendant */ public String getDefendant() { return this.defendant; } /** * @return judgeDate */ public String getJudgeDate() { return this.judgeDate; } /** * @return judgeResult */ public String getJudgeResult() { return this.judgeResult; } /** * @return judgeType */ public String getJudgeType() { return this.judgeType; } /** * @return party */ public String getParty() { return this.party; } /** * @return plaintiff */ public String getPlaintiff() { return this.plaintiff; } /** * @return publicDate */ public String getPublicDate() { return this.publicDate; } /** * @return role */ public String getRole() { return this.role; } /** * @return subAmount */ public String getSubAmount() { return this.subAmount; } /** * @return title */ public String getTitle() { return this.title; } public static final class Builder { private String caseFlow; private String caseNum; private String caseType; private String causeAction; private String court; private String defendant; private String judgeDate; private String judgeResult; private String judgeType; private String party; private String plaintiff; private String publicDate; private String role; private String subAmount; private String title; /** * 案件流程 */ public Builder caseFlow(String caseFlow) { this.caseFlow = caseFlow; return this; } /** * 案号 */ public Builder caseNum(String caseNum) { this.caseNum = caseNum; return this; } /** * 案件类型 */ public Builder caseType(String caseType) { this.caseType = caseType; return this; } /** * 案由 */ public Builder causeAction(String causeAction) { this.causeAction = causeAction; return this; } /** * 法庭 */ public Builder court(String court) { this.court = court; return this; } /** * 被告 */ public Builder defendant(String defendant) { this.defendant = defendant; return this; } /** * 判决日期 */ public Builder judgeDate(String judgeDate) { this.judgeDate = judgeDate; return this; } /** * 判决结果 */ public Builder judgeResult(String judgeResult) { this.judgeResult = judgeResult; return this; } /** * 裁判类型 */ public Builder judgeType(String judgeType) { this.judgeType = judgeType; return this; } /** * 当事人 */ public Builder party(String party) { this.party = party; return this; } /** * 原告 */ public Builder plaintiff(String plaintiff) { this.plaintiff = plaintiff; return this; } /** * 公示日期 */ public Builder publicDate(String publicDate) { this.publicDate = publicDate; return this; } /** * 身份 */ public Builder role(String role) { this.role = role; return this; } /** * 涉案金额 */ public Builder subAmount(String subAmount) { this.subAmount = subAmount; return this; } /** * 标题 */ public Builder title(String title) { this.title = title; return this; } public Data build() { return new Data(this); } } } }
aliyun/alibabacloud-java-async-sdk
dt-oc-info-20220829/src/main/java/com/aliyun/sdk/service/dt_oc_info20220829/models/GetOcJusticeJudgementDocResponseBody.java
2,434
/** * 身份 */
block_comment
zh-cn
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.sdk.service.dt_oc_info20220829.models; import com.aliyun.core.annotation.*; import darabonba.core.RequestModel; import darabonba.core.TeaModel; import com.aliyun.sdk.gateway.pop.models.*; /** * {@link GetOcJusticeJudgementDocResponseBody} extends {@link TeaModel} * * <p>GetOcJusticeJudgementDocResponseBody</p> */ public class GetOcJusticeJudgementDocResponseBody extends TeaModel { @NameInMap("Code") private String code; @NameInMap("Data") private java.util.List < Data> data; @NameInMap("Message") private String message; @NameInMap("PageIndex") private Integer pageIndex; @NameInMap("PageNum") private Integer pageNum; @NameInMap("RequestId") private String requestId; @NameInMap("Success") private Boolean success; @NameInMap("TotalNum") private Integer totalNum; private GetOcJusticeJudgementDocResponseBody(Builder builder) { this.code = builder.code; this.data = builder.data; this.message = builder.message; this.pageIndex = builder.pageIndex; this.pageNum = builder.pageNum; this.requestId = builder.requestId; this.success = builder.success; this.totalNum = builder.totalNum; } public static Builder builder() { return new Builder(); } public static GetOcJusticeJudgementDocResponseBody create() { return builder().build(); } /** * @return code */ public String getCode() { return this.code; } /** * @return data */ public java.util.List < Data> getData() { return this.data; } /** * @return message */ public String getMessage() { return this.message; } /** * @return pageIndex */ public Integer getPageIndex() { return this.pageIndex; } /** * @return pageNum */ public Integer getPageNum() { return this.pageNum; } /** * @return requestId */ public String getRequestId() { return this.requestId; } /** * @return success */ public Boolean getSuccess() { return this.success; } /** * @return totalNum */ public Integer getTotalNum() { return this.totalNum; } public static final class Builder { private String code; private java.util.List < Data> data; private String message; private Integer pageIndex; private Integer pageNum; private String requestId; private Boolean success; private Integer totalNum; /** * Code. */ public Builder code(String code) { this.code = code; return this; } /** * Data. */ public Builder data(java.util.List < Data> data) { this.data = data; return this; } /** * Message. */ public Builder message(String message) { this.message = message; return this; } /** * PageIndex. */ public Builder pageIndex(Integer pageIndex) { this.pageIndex = pageIndex; return this; } /** * PageNum. */ public Builder pageNum(Integer pageNum) { this.pageNum = pageNum; return this; } /** * RequestId. */ public Builder requestId(String requestId) { this.requestId = requestId; return this; } /** * Success. */ public Builder success(Boolean success) { this.success = success; return this; } /** * TotalNum. */ public Builder totalNum(Integer totalNum) { this.totalNum = totalNum; return this; } public GetOcJusticeJudgementDocResponseBody build() { return new GetOcJusticeJudgementDocResponseBody(this); } } public static class Data extends TeaModel { @NameInMap("CaseFlow") private String caseFlow; @NameInMap("CaseNum") private String caseNum; @NameInMap("CaseType") private String caseType; @NameInMap("CauseAction") private String causeAction; @NameInMap("Court") private String court; @NameInMap("Defendant") private String defendant; @NameInMap("JudgeDate") private String judgeDate; @NameInMap("JudgeResult") private String judgeResult; @NameInMap("JudgeType") private String judgeType; @NameInMap("Party") private String party; @NameInMap("Plaintiff") private String plaintiff; @NameInMap("PublicDate") private String publicDate; @NameInMap("Role") private String role; @NameInMap("SubAmount") private String subAmount; @NameInMap("Title") private String title; private Data(Builder builder) { this.caseFlow = builder.caseFlow; this.caseNum = builder.caseNum; this.caseType = builder.caseType; this.causeAction = builder.causeAction; this.court = builder.court; this.defendant = builder.defendant; this.judgeDate = builder.judgeDate; this.judgeResult = builder.judgeResult; this.judgeType = builder.judgeType; this.party = builder.party; this.plaintiff = builder.plaintiff; this.publicDate = builder.publicDate; this.role = builder.role; this.subAmount = builder.subAmount; this.title = builder.title; } public static Builder builder() { return new Builder(); } public static Data create() { return builder().build(); } /** * @return caseFlow */ public String getCaseFlow() { return this.caseFlow; } /** * @return caseNum */ public String getCaseNum() { return this.caseNum; } /** * @return caseType */ public String getCaseType() { return this.caseType; } /** * @return causeAction */ public String getCauseAction() { return this.causeAction; } /** * @return court */ public String getCourt() { return this.court; } /** * @return defendant */ public String getDefendant() { return this.defendant; } /** * @return judgeDate */ public String getJudgeDate() { return this.judgeDate; } /** * @return judgeResult */ public String getJudgeResult() { return this.judgeResult; } /** * @return judgeType */ public String getJudgeType() { return this.judgeType; } /** * @return party */ public String getParty() { return this.party; } /** * @return plaintiff */ public String getPlaintiff() { return this.plaintiff; } /** * @return publicDate */ public String getPublicDate() { return this.publicDate; } /** * @return role */ public String getRole() { return this.role; } /** * @return subAmount */ public String getSubAmount() { return this.subAmount; } /** * @return title */ public String getTitle() { return this.title; } public static final class Builder { private String caseFlow; private String caseNum; private String caseType; private String causeAction; private String court; private String defendant; private String judgeDate; private String judgeResult; private String judgeType; private String party; private String plaintiff; private String publicDate; private String role; private String subAmount; private String title; /** * 案件流程 */ public Builder caseFlow(String caseFlow) { this.caseFlow = caseFlow; return this; } /** * 案号 */ public Builder caseNum(String caseNum) { this.caseNum = caseNum; return this; } /** * 案件类型 */ public Builder caseType(String caseType) { this.caseType = caseType; return this; } /** * 案由 */ public Builder causeAction(String causeAction) { this.causeAction = causeAction; return this; } /** * 法庭 */ public Builder court(String court) { this.court = court; return this; } /** * 被告 */ public Builder defendant(String defendant) { this.defendant = defendant; return this; } /** * 判决日期 */ public Builder judgeDate(String judgeDate) { this.judgeDate = judgeDate; return this; } /** * 判决结果 */ public Builder judgeResult(String judgeResult) { this.judgeResult = judgeResult; return this; } /** * 裁判类型 */ public Builder judgeType(String judgeType) { this.judgeType = judgeType; return this; } /** * 当事人 */ public Builder party(String party) { this.party = party; return this; } /** * 原告 */ public Builder plaintiff(String plaintiff) { this.plaintiff = plaintiff; return this; } /** * 公示日期 */ public Builder publicDate(String publicDate) { this.publicDate = publicDate; return this; } /** * 身份 <SUF>*/ public Builder role(String role) { this.role = role; return this; } /** * 涉案金额 */ public Builder subAmount(String subAmount) { this.subAmount = subAmount; return this; } /** * 标题 */ public Builder title(String title) { this.title = title; return this; } public Data build() { return new Data(this); } } } }
false
2,315
9
2,434
7
2,730
9
2,434
7
3,088
12
false
false
false
false
false
true
57580_1
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.airticketopen20230117.models; import com.aliyun.tea.*; public class AncillarySuggestResponseBody extends TeaModel { @NameInMap("RequestId") public String requestId; @NameInMap("data") public AncillarySuggestResponseBodyData data; @NameInMap("error_code") public String errorCode; @NameInMap("error_data") public Object errorData; @NameInMap("error_msg") public String errorMsg; @NameInMap("status") public Integer status; @NameInMap("success") public Boolean success; public static AncillarySuggestResponseBody build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBody self = new AncillarySuggestResponseBody(); return TeaModel.build(map, self); } public AncillarySuggestResponseBody setRequestId(String requestId) { this.requestId = requestId; return this; } public String getRequestId() { return this.requestId; } public AncillarySuggestResponseBody setData(AncillarySuggestResponseBodyData data) { this.data = data; return this; } public AncillarySuggestResponseBodyData getData() { return this.data; } public AncillarySuggestResponseBody setErrorCode(String errorCode) { this.errorCode = errorCode; return this; } public String getErrorCode() { return this.errorCode; } public AncillarySuggestResponseBody setErrorData(Object errorData) { this.errorData = errorData; return this; } public Object getErrorData() { return this.errorData; } public AncillarySuggestResponseBody setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; return this; } public String getErrorMsg() { return this.errorMsg; } public AncillarySuggestResponseBody setStatus(Integer status) { this.status = status; return this; } public Integer getStatus() { return this.status; } public AncillarySuggestResponseBody setSuccess(Boolean success) { this.success = success; return this; } public Boolean getSuccess() { return this.success; } public static class AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary extends TeaModel { /** * <p>行李件数 取值如:3、2、1、0、-2。 -2 表示计重</p> */ @NameInMap("baggage_amount") public Integer baggageAmount; /** * <p>行李重量,0-50。isAllWeght=true 时,表示所有件数总重量。</p> */ @NameInMap("baggage_weight") public Integer baggageWeight; /** * <p>行李重量单位</p> */ @NameInMap("baggage_weight_unit") public String baggageWeightUnit; /** * <p>是否所有行李重量</p> */ @NameInMap("is_all_weight") public Boolean isAllWeight; /** * <p>总价</p> */ @NameInMap("price") public Double price; public static AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary self = new AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setBaggageAmount(Integer baggageAmount) { this.baggageAmount = baggageAmount; return this; } public Integer getBaggageAmount() { return this.baggageAmount; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setBaggageWeight(Integer baggageWeight) { this.baggageWeight = baggageWeight; return this; } public Integer getBaggageWeight() { return this.baggageWeight; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setBaggageWeightUnit(String baggageWeightUnit) { this.baggageWeightUnit = baggageWeightUnit; return this; } public String getBaggageWeightUnit() { return this.baggageWeightUnit; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setIsAllWeight(Boolean isAllWeight) { this.isAllWeight = isAllWeight; return this; } public Boolean getIsAllWeight() { return this.isAllWeight; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setPrice(Double price) { this.price = price; return this; } public Double getPrice() { return this.price; } } public static class AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary extends TeaModel { @NameInMap("ancillary_id") public String ancillaryId; @NameInMap("ancillary_type") public Integer ancillaryType; /** * <p>行李辅营详情</p> */ @NameInMap("baggage_ancillary") public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary baggageAncillary; public static AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary self = new AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary setAncillaryId(String ancillaryId) { this.ancillaryId = ancillaryId; return this; } public String getAncillaryId() { return this.ancillaryId; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary setAncillaryType(Integer ancillaryType) { this.ancillaryType = ancillaryType; return this; } public Integer getAncillaryType() { return this.ancillaryType; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary setBaggageAncillary(AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary baggageAncillary) { this.baggageAncillary = baggageAncillary; return this; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary getBaggageAncillary() { return this.baggageAncillary; } } public static class AncillarySuggestResponseBodyDataSegAncillaryMapList extends TeaModel { @NameInMap("ancillary") public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary ancillary; @NameInMap("segment_id_list") public java.util.List<String> segmentIdList; public static AncillarySuggestResponseBodyDataSegAncillaryMapList build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyDataSegAncillaryMapList self = new AncillarySuggestResponseBodyDataSegAncillaryMapList(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyDataSegAncillaryMapList setAncillary(AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary ancillary) { this.ancillary = ancillary; return this; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary getAncillary() { return this.ancillary; } public AncillarySuggestResponseBodyDataSegAncillaryMapList setSegmentIdList(java.util.List<String> segmentIdList) { this.segmentIdList = segmentIdList; return this; } public java.util.List<String> getSegmentIdList() { return this.segmentIdList; } } public static class AncillarySuggestResponseBodyData extends TeaModel { @NameInMap("seg_ancillary_map_list") public java.util.List<AncillarySuggestResponseBodyDataSegAncillaryMapList> segAncillaryMapList; @NameInMap("solution_id") public String solutionId; public static AncillarySuggestResponseBodyData build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyData self = new AncillarySuggestResponseBodyData(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyData setSegAncillaryMapList(java.util.List<AncillarySuggestResponseBodyDataSegAncillaryMapList> segAncillaryMapList) { this.segAncillaryMapList = segAncillaryMapList; return this; } public java.util.List<AncillarySuggestResponseBodyDataSegAncillaryMapList> getSegAncillaryMapList() { return this.segAncillaryMapList; } public AncillarySuggestResponseBodyData setSolutionId(String solutionId) { this.solutionId = solutionId; return this; } public String getSolutionId() { return this.solutionId; } } }
aliyun/alibabacloud-java-sdk
airticketopen-20230117/src/main/java/com/aliyun/airticketopen20230117/models/AncillarySuggestResponseBody.java
2,379
/** * <p>行李件数 取值如:3、2、1、0、-2。 -2 表示计重</p> */
block_comment
zh-cn
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.airticketopen20230117.models; import com.aliyun.tea.*; public class AncillarySuggestResponseBody extends TeaModel { @NameInMap("RequestId") public String requestId; @NameInMap("data") public AncillarySuggestResponseBodyData data; @NameInMap("error_code") public String errorCode; @NameInMap("error_data") public Object errorData; @NameInMap("error_msg") public String errorMsg; @NameInMap("status") public Integer status; @NameInMap("success") public Boolean success; public static AncillarySuggestResponseBody build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBody self = new AncillarySuggestResponseBody(); return TeaModel.build(map, self); } public AncillarySuggestResponseBody setRequestId(String requestId) { this.requestId = requestId; return this; } public String getRequestId() { return this.requestId; } public AncillarySuggestResponseBody setData(AncillarySuggestResponseBodyData data) { this.data = data; return this; } public AncillarySuggestResponseBodyData getData() { return this.data; } public AncillarySuggestResponseBody setErrorCode(String errorCode) { this.errorCode = errorCode; return this; } public String getErrorCode() { return this.errorCode; } public AncillarySuggestResponseBody setErrorData(Object errorData) { this.errorData = errorData; return this; } public Object getErrorData() { return this.errorData; } public AncillarySuggestResponseBody setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; return this; } public String getErrorMsg() { return this.errorMsg; } public AncillarySuggestResponseBody setStatus(Integer status) { this.status = status; return this; } public Integer getStatus() { return this.status; } public AncillarySuggestResponseBody setSuccess(Boolean success) { this.success = success; return this; } public Boolean getSuccess() { return this.success; } public static class AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary extends TeaModel { /** * <p> <SUF>*/ @NameInMap("baggage_amount") public Integer baggageAmount; /** * <p>行李重量,0-50。isAllWeght=true 时,表示所有件数总重量。</p> */ @NameInMap("baggage_weight") public Integer baggageWeight; /** * <p>行李重量单位</p> */ @NameInMap("baggage_weight_unit") public String baggageWeightUnit; /** * <p>是否所有行李重量</p> */ @NameInMap("is_all_weight") public Boolean isAllWeight; /** * <p>总价</p> */ @NameInMap("price") public Double price; public static AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary self = new AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setBaggageAmount(Integer baggageAmount) { this.baggageAmount = baggageAmount; return this; } public Integer getBaggageAmount() { return this.baggageAmount; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setBaggageWeight(Integer baggageWeight) { this.baggageWeight = baggageWeight; return this; } public Integer getBaggageWeight() { return this.baggageWeight; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setBaggageWeightUnit(String baggageWeightUnit) { this.baggageWeightUnit = baggageWeightUnit; return this; } public String getBaggageWeightUnit() { return this.baggageWeightUnit; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setIsAllWeight(Boolean isAllWeight) { this.isAllWeight = isAllWeight; return this; } public Boolean getIsAllWeight() { return this.isAllWeight; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary setPrice(Double price) { this.price = price; return this; } public Double getPrice() { return this.price; } } public static class AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary extends TeaModel { @NameInMap("ancillary_id") public String ancillaryId; @NameInMap("ancillary_type") public Integer ancillaryType; /** * <p>行李辅营详情</p> */ @NameInMap("baggage_ancillary") public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary baggageAncillary; public static AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary self = new AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary setAncillaryId(String ancillaryId) { this.ancillaryId = ancillaryId; return this; } public String getAncillaryId() { return this.ancillaryId; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary setAncillaryType(Integer ancillaryType) { this.ancillaryType = ancillaryType; return this; } public Integer getAncillaryType() { return this.ancillaryType; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary setBaggageAncillary(AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary baggageAncillary) { this.baggageAncillary = baggageAncillary; return this; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillaryBaggageAncillary getBaggageAncillary() { return this.baggageAncillary; } } public static class AncillarySuggestResponseBodyDataSegAncillaryMapList extends TeaModel { @NameInMap("ancillary") public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary ancillary; @NameInMap("segment_id_list") public java.util.List<String> segmentIdList; public static AncillarySuggestResponseBodyDataSegAncillaryMapList build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyDataSegAncillaryMapList self = new AncillarySuggestResponseBodyDataSegAncillaryMapList(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyDataSegAncillaryMapList setAncillary(AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary ancillary) { this.ancillary = ancillary; return this; } public AncillarySuggestResponseBodyDataSegAncillaryMapListAncillary getAncillary() { return this.ancillary; } public AncillarySuggestResponseBodyDataSegAncillaryMapList setSegmentIdList(java.util.List<String> segmentIdList) { this.segmentIdList = segmentIdList; return this; } public java.util.List<String> getSegmentIdList() { return this.segmentIdList; } } public static class AncillarySuggestResponseBodyData extends TeaModel { @NameInMap("seg_ancillary_map_list") public java.util.List<AncillarySuggestResponseBodyDataSegAncillaryMapList> segAncillaryMapList; @NameInMap("solution_id") public String solutionId; public static AncillarySuggestResponseBodyData build(java.util.Map<String, ?> map) throws Exception { AncillarySuggestResponseBodyData self = new AncillarySuggestResponseBodyData(); return TeaModel.build(map, self); } public AncillarySuggestResponseBodyData setSegAncillaryMapList(java.util.List<AncillarySuggestResponseBodyDataSegAncillaryMapList> segAncillaryMapList) { this.segAncillaryMapList = segAncillaryMapList; return this; } public java.util.List<AncillarySuggestResponseBodyDataSegAncillaryMapList> getSegAncillaryMapList() { return this.segAncillaryMapList; } public AncillarySuggestResponseBodyData setSolutionId(String solutionId) { this.solutionId = solutionId; return this; } public String getSolutionId() { return this.solutionId; } } }
false
2,033
37
2,379
36
2,243
36
2,379
36
2,933
40
false
false
false
false
false
true
58170_0
import com.aliyun.mq.http.MQClient; import com.aliyun.mq.http.MQConsumer; import com.aliyun.mq.http.common.AckMessageException; import com.aliyun.mq.http.model.Message; import java.util.ArrayList; import java.util.List; public class Consumer { public static void main(String[] args) { MQClient mqClient = new MQClient( // 设置HTTP接入域名(此处以公共云生产环境为例) "${HTTP_ENDPOINT}", // AccessKey 阿里云身份验证,在阿里云服务器管理控制台创建 "${ACCESS_KEY}", // SecretKey 阿里云身份验证,在阿里云服务器管理控制台创建 "${SECRET_KEY}" ); // 所属的 Topic final String topic = "${TOPIC}"; // 您在控制台创建的 Consumer ID(Group ID) final String groupId = "${GROUP_ID}"; // Topic所属实例ID,默认实例为空 final String instanceId = "${INSTANCE_ID}"; final MQConsumer consumer; if (instanceId != null && instanceId != "") { consumer = mqClient.getConsumer(instanceId, topic, groupId, null); } else { consumer = mqClient.getConsumer(topic, groupId); } // 在当前线程循环消费消息,建议是多开个几个线程并发消费消息 do { List<Message> messages = null; try { // 长轮询消费消息 // 长轮询表示如果topic没有消息则请求会在服务端挂住3s,3s内如果有消息可以消费则立即返回 messages = consumer.consumeMessage( 3,// 一次最多消费3条(最多可设置为16条) 3// 长轮询时间3秒(最多可设置为30秒) ); } catch (Throwable e) { e.printStackTrace(); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } } // 没有消息 if (messages == null || messages.isEmpty()) { System.out.println(Thread.currentThread().getName() + ": no new message, continue!"); continue; } // 处理业务逻辑 for (Message message : messages) { System.out.println("Receive message: " + message); } // Message.nextConsumeTime前若不确认消息消费成功,则消息会重复消费 // 消息句柄有时间戳,同一条消息每次消费拿到的都不一样 { List<String> handles = new ArrayList<String>(); for (Message message : messages) { handles.add(message.getReceiptHandle()); } try { consumer.ackMessage(handles); } catch (Throwable e) { // 某些消息的句柄可能超时了会导致确认不成功 if (e instanceof AckMessageException) { AckMessageException errors = (AckMessageException) e; System.out.println("Ack message fail, requestId is:" + errors.getRequestId() + ", fail handles:"); if (errors.getErrorMessages() != null) { for (String errorHandle :errors.getErrorMessages().keySet()) { System.out.println("Handle:" + errorHandle + ", ErrorCode:" + errors.getErrorMessages().get(errorHandle).getErrorCode() + ", ErrorMsg:" + errors.getErrorMessages().get(errorHandle).getErrorMessage()); } } continue; } e.printStackTrace(); } } } while (true); } }
aliyunmq/mq-http-samples
java/src/main/java/Consumer.java
816
// 设置HTTP接入域名(此处以公共云生产环境为例)
line_comment
zh-cn
import com.aliyun.mq.http.MQClient; import com.aliyun.mq.http.MQConsumer; import com.aliyun.mq.http.common.AckMessageException; import com.aliyun.mq.http.model.Message; import java.util.ArrayList; import java.util.List; public class Consumer { public static void main(String[] args) { MQClient mqClient = new MQClient( // 设置 <SUF> "${HTTP_ENDPOINT}", // AccessKey 阿里云身份验证,在阿里云服务器管理控制台创建 "${ACCESS_KEY}", // SecretKey 阿里云身份验证,在阿里云服务器管理控制台创建 "${SECRET_KEY}" ); // 所属的 Topic final String topic = "${TOPIC}"; // 您在控制台创建的 Consumer ID(Group ID) final String groupId = "${GROUP_ID}"; // Topic所属实例ID,默认实例为空 final String instanceId = "${INSTANCE_ID}"; final MQConsumer consumer; if (instanceId != null && instanceId != "") { consumer = mqClient.getConsumer(instanceId, topic, groupId, null); } else { consumer = mqClient.getConsumer(topic, groupId); } // 在当前线程循环消费消息,建议是多开个几个线程并发消费消息 do { List<Message> messages = null; try { // 长轮询消费消息 // 长轮询表示如果topic没有消息则请求会在服务端挂住3s,3s内如果有消息可以消费则立即返回 messages = consumer.consumeMessage( 3,// 一次最多消费3条(最多可设置为16条) 3// 长轮询时间3秒(最多可设置为30秒) ); } catch (Throwable e) { e.printStackTrace(); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } } // 没有消息 if (messages == null || messages.isEmpty()) { System.out.println(Thread.currentThread().getName() + ": no new message, continue!"); continue; } // 处理业务逻辑 for (Message message : messages) { System.out.println("Receive message: " + message); } // Message.nextConsumeTime前若不确认消息消费成功,则消息会重复消费 // 消息句柄有时间戳,同一条消息每次消费拿到的都不一样 { List<String> handles = new ArrayList<String>(); for (Message message : messages) { handles.add(message.getReceiptHandle()); } try { consumer.ackMessage(handles); } catch (Throwable e) { // 某些消息的句柄可能超时了会导致确认不成功 if (e instanceof AckMessageException) { AckMessageException errors = (AckMessageException) e; System.out.println("Ack message fail, requestId is:" + errors.getRequestId() + ", fail handles:"); if (errors.getErrorMessages() != null) { for (String errorHandle :errors.getErrorMessages().keySet()) { System.out.println("Handle:" + errorHandle + ", ErrorCode:" + errors.getErrorMessages().get(errorHandle).getErrorCode() + ", ErrorMsg:" + errors.getErrorMessages().get(errorHandle).getErrorMessage()); } } continue; } e.printStackTrace(); } } } while (true); } }
false
755
14
816
18
855
15
816
18
1,144
31
false
false
false
false
false
true
19354_1
package dao; import java.util.List; import entity.User; public interface UserDao { public int insert(User user); public int update(User user); public int delete(User user); public List<User> getAll(); //查询全部 public User findUser(User user);//用于登陆判断 public List<User> getUserByName(String user); }
allanzhuo/360mall
src/dao/UserDao.java
97
//用于登陆判断
line_comment
zh-cn
package dao; import java.util.List; import entity.User; public interface UserDao { public int insert(User user); public int update(User user); public int delete(User user); public List<User> getAll(); //查询全部 public User findUser(User user);//用于 <SUF> public List<User> getUserByName(String user); }
false
66
5
97
6
91
5
97
6
111
10
false
false
false
false
false
true
18334_32
package test.java; /** * 自由组合数组元素 * @author SilentNight Q:237951606 */ public class ArrayDemo { public static void main(String[] args) { // | | 3 | 1 | 0 | // |---|---|---|---| // | 1 | √ | √ | √ | // | 2 | √ | √ | √ | // | 3 | √ | | √ | // | 4 | | | √ | // // 将上述勾选项转化为二维数组,上图就是一个表格,因此使用 table 命名对应的二维数组 int[][] table = {{3,1,0},{3,1,0},{3,0},{0}}; int[][] resultArr = getResultArr(table); // 将结果数组转换为字符串形式 StringBuilder sb = new StringBuilder(); String separator = ", ";//分隔符 for (int i = 0; i < resultArr.length; i++) { for (int j = 0; j < resultArr[i].length; j++) { sb.append(resultArr[i][j]).append(separator); } sb.setLength(sb.length() - separator.length()); sb.append("\r\n"); } System.out.println(sb);//结果如下 // 3, 3, 3, 0 // 3, 1, 0, 0 // 3, 0, 3, 0 // 3, 3, 0, 0 // 3, 1, 3, 0 // 3, 0, 0, 0 // 1, 3, 3, 0 // 1, 1, 0, 0 // 1, 0, 3, 0 // 1, 3, 0, 0 // 1, 1, 3, 0 // 1, 0, 0, 0 // 0, 3, 3, 0 // 0, 1, 0, 0 // 0, 0, 3, 0 // 0, 3, 0, 0 // 0, 1, 3, 0 // 0, 0, 0, 0 } /**获取自由组合的结果数组 * @param table 源数组 * @return 结果数组 */ private static int[][] getResultArr(int[][] table) { int resultArrColCnt = table.length;//结果数组的列数 int resultArrRowCnt = 1;//结果数组的行数 // 计算最终的结果数组行数 for (int i = 0; i < table.length; i++) { resultArrRowCnt *= table[i].length; } // 确定结果数组的大小 int[][] resultArr = new int[resultArrRowCnt][resultArrColCnt]; // 填充结果数组第一列 firstCol(table, resultArrRowCnt, resultArr); // 填充结果数组的其他列(第一列之后的其他列) otherCols(table, resultArrRowCnt, resultArr); return resultArr; } /**填充结果数组第一列 * @param table 源数组 * @param resultArrRowCnt 结果数组的行数 * @param resultArr 结果数组 */ private static void firstCol(int[][] table, int resultArrRowCnt, int[][] resultArr) { int col = 0; int[] arr = table[col]; int round = arr.length;//填充多少轮 int times = resultArrRowCnt / round;//每轮填充的次数 for (int r = 0; r < round; r++) { int val = arr[r];//要填充的值 for (int t = 0; t < times; t++) { resultArr[t + (r * times)][col] = val; } } } /**填充结果数组的其他列(第一列之后的其他列) * @param table 源数组 * @param resultArrRowCnt 结果数组的行数 * @param resultArr 结果数组 */ private static void otherCols(int[][] table, int resultArrRowCnt, int[][] resultArr) { for (int col = 1; col < table.length; col++) { int[] arr = table[col]; for (int i = 0; i < resultArrRowCnt; i++) { resultArr[i][col] = arr[i % arr.length]; } } } }
allbutone/javatalk
JavaSE/ArrayDemo.java
1,095
// 计算最终的结果数组行数
line_comment
zh-cn
package test.java; /** * 自由组合数组元素 * @author SilentNight Q:237951606 */ public class ArrayDemo { public static void main(String[] args) { // | | 3 | 1 | 0 | // |---|---|---|---| // | 1 | √ | √ | √ | // | 2 | √ | √ | √ | // | 3 | √ | | √ | // | 4 | | | √ | // // 将上述勾选项转化为二维数组,上图就是一个表格,因此使用 table 命名对应的二维数组 int[][] table = {{3,1,0},{3,1,0},{3,0},{0}}; int[][] resultArr = getResultArr(table); // 将结果数组转换为字符串形式 StringBuilder sb = new StringBuilder(); String separator = ", ";//分隔符 for (int i = 0; i < resultArr.length; i++) { for (int j = 0; j < resultArr[i].length; j++) { sb.append(resultArr[i][j]).append(separator); } sb.setLength(sb.length() - separator.length()); sb.append("\r\n"); } System.out.println(sb);//结果如下 // 3, 3, 3, 0 // 3, 1, 0, 0 // 3, 0, 3, 0 // 3, 3, 0, 0 // 3, 1, 3, 0 // 3, 0, 0, 0 // 1, 3, 3, 0 // 1, 1, 0, 0 // 1, 0, 3, 0 // 1, 3, 0, 0 // 1, 1, 3, 0 // 1, 0, 0, 0 // 0, 3, 3, 0 // 0, 1, 0, 0 // 0, 0, 3, 0 // 0, 3, 0, 0 // 0, 1, 3, 0 // 0, 0, 0, 0 } /**获取自由组合的结果数组 * @param table 源数组 * @return 结果数组 */ private static int[][] getResultArr(int[][] table) { int resultArrColCnt = table.length;//结果数组的列数 int resultArrRowCnt = 1;//结果数组的行数 // 计算 <SUF> for (int i = 0; i < table.length; i++) { resultArrRowCnt *= table[i].length; } // 确定结果数组的大小 int[][] resultArr = new int[resultArrRowCnt][resultArrColCnt]; // 填充结果数组第一列 firstCol(table, resultArrRowCnt, resultArr); // 填充结果数组的其他列(第一列之后的其他列) otherCols(table, resultArrRowCnt, resultArr); return resultArr; } /**填充结果数组第一列 * @param table 源数组 * @param resultArrRowCnt 结果数组的行数 * @param resultArr 结果数组 */ private static void firstCol(int[][] table, int resultArrRowCnt, int[][] resultArr) { int col = 0; int[] arr = table[col]; int round = arr.length;//填充多少轮 int times = resultArrRowCnt / round;//每轮填充的次数 for (int r = 0; r < round; r++) { int val = arr[r];//要填充的值 for (int t = 0; t < times; t++) { resultArr[t + (r * times)][col] = val; } } } /**填充结果数组的其他列(第一列之后的其他列) * @param table 源数组 * @param resultArrRowCnt 结果数组的行数 * @param resultArr 结果数组 */ private static void otherCols(int[][] table, int resultArrRowCnt, int[][] resultArr) { for (int col = 1; col < table.length; col++) { int[] arr = table[col]; for (int i = 0; i < resultArrRowCnt; i++) { resultArr[i][col] = arr[i % arr.length]; } } } }
false
1,073
10
1,095
10
1,094
8
1,095
10
1,309
15
false
false
false
false
false
true
3717_2
package com.platform.domain.vo; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; import java.sql.Date; import java.sql.Timestamp; /** * 交易详情,按需应该存入数据库,这里存入数据库,仅供临时测试 * @author AllDataDC * @date 2023-01-27 */ @Data public class TradeVo { /** (必填)商品描述 */ @NotBlank private String body; /** (必填)商品名称 */ @NotBlank private String subject; /** (必填)商户订单号,应该由后台生成 */ @ApiModelProperty(hidden = true) private String outTradeNo; /** (必填)第三方订单号 */ @ApiModelProperty(hidden = true) private String tradeNo; /** (必填)价格 */ @NotBlank private String totalAmount; /** 订单状态,已支付,未支付,作废 */ @ApiModelProperty(hidden = true) private String state; /** 创建时间,存入数据库时需要 */ @ApiModelProperty(hidden = true) private Timestamp createTime; /** 作废时间,存入数据库时需要 */ @ApiModelProperty(hidden = true) private Date cancelTime; }
alldatacenter/alldata
studio/box/src/main/java/com/platform/domain/vo/TradeVo.java
311
/** (必填)商品名称 */
block_comment
zh-cn
package com.platform.domain.vo; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; import java.sql.Date; import java.sql.Timestamp; /** * 交易详情,按需应该存入数据库,这里存入数据库,仅供临时测试 * @author AllDataDC * @date 2023-01-27 */ @Data public class TradeVo { /** (必填)商品描述 */ @NotBlank private String body; /** (必填 <SUF>*/ @NotBlank private String subject; /** (必填)商户订单号,应该由后台生成 */ @ApiModelProperty(hidden = true) private String outTradeNo; /** (必填)第三方订单号 */ @ApiModelProperty(hidden = true) private String tradeNo; /** (必填)价格 */ @NotBlank private String totalAmount; /** 订单状态,已支付,未支付,作废 */ @ApiModelProperty(hidden = true) private String state; /** 创建时间,存入数据库时需要 */ @ApiModelProperty(hidden = true) private Timestamp createTime; /** 作废时间,存入数据库时需要 */ @ApiModelProperty(hidden = true) private Date cancelTime; }
false
270
8
303
8
317
8
303
8
438
13
false
false
false
false
false
true
870_1
package com.yl.lib.privacy_proxy; import android.os.Build; import androidx.annotation.Keep; import com.yl.lib.privacy_annotation.PrivacyClassProxy; import com.yl.lib.privacy_annotation.PrivacyFieldProxy; /** * @author yulun * @since 2022-03-03 19:42 * 注意变量的初始化是在类初始化的时候就执行了,所以这里只适合hook不可变的变量 */ @Keep @PrivacyClassProxy public class ProxyProxyField { @PrivacyFieldProxy( originalClass = android.os.Build.class, originalFieldName = "SERIAL" ) public static final String proxySerial = PrivacyProxyCall.Proxy.getSerial(); // 虽然能保证全局只读取一次,但检测机构是抓包识别的,好像也没什么用,他们好像不能检测变量的读取 @PrivacyFieldProxy( originalClass = android.os.Build.class, originalFieldName = "BRAND" ) public static final String proxyBrand = PrivacyProxyCall.Proxy.getBrand(); }
allenymt/PrivacySentry
privacy-proxy/src/main/java/com/yl/lib/privacy_proxy/ProxyProxyField.java
264
// 虽然能保证全局只读取一次,但检测机构是抓包识别的,好像也没什么用,他们好像不能检测变量的读取
line_comment
zh-cn
package com.yl.lib.privacy_proxy; import android.os.Build; import androidx.annotation.Keep; import com.yl.lib.privacy_annotation.PrivacyClassProxy; import com.yl.lib.privacy_annotation.PrivacyFieldProxy; /** * @author yulun * @since 2022-03-03 19:42 * 注意变量的初始化是在类初始化的时候就执行了,所以这里只适合hook不可变的变量 */ @Keep @PrivacyClassProxy public class ProxyProxyField { @PrivacyFieldProxy( originalClass = android.os.Build.class, originalFieldName = "SERIAL" ) public static final String proxySerial = PrivacyProxyCall.Proxy.getSerial(); // 虽然 <SUF> @PrivacyFieldProxy( originalClass = android.os.Build.class, originalFieldName = "BRAND" ) public static final String proxyBrand = PrivacyProxyCall.Proxy.getBrand(); }
false
232
34
264
36
262
31
264
36
353
70
false
false
false
false
false
true
34738_3
package com.dlzx.common.core.utils.domain; import java.util.List; /** * 类描述:请假统计返回 * @className VacationDayExcelVm * company 赛拓信息技术有限公司 * @author DongCL * @date 2021-02-07 13:29 */ public class VacationDayExcelVm { /** 驾驶员姓名 */ private String driverName; /** 在途 */ private Long way = 0L; /** 在家 */ private Long atHome = 0L; /** 请假 */ private Long leave = 0L; /** 出勤天数 */ private Long totalAttendance = 0L; /** 存放状态 */ private List<EveryDayDetailExcelVm> dVacationDayList; public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } public Long getWay() { return way; } public void setWay(Long way) { this.way = way; } public Long getAtHome() { return atHome; } public void setAtHome(Long atHome) { this.atHome = atHome; } public Long getLeave() { return leave; } public void setLeave(Long leave) { this.leave = leave; } public Long getTotalAttendance() { return totalAttendance; } public void setTotalAttendance(Long totalAttendance) { this.totalAttendance = totalAttendance; } public List<EveryDayDetailExcelVm> getdVacationDayList() { return dVacationDayList; } public void setdVacationDayList(List<EveryDayDetailExcelVm> dVacationDayList) { this.dVacationDayList = dVacationDayList; } }
alley-dong/zyhcd-dlzx
common/common-core/src/main/java/com/dlzx/common/core/utils/domain/VacationDayExcelVm.java
452
/** 在家 */
block_comment
zh-cn
package com.dlzx.common.core.utils.domain; import java.util.List; /** * 类描述:请假统计返回 * @className VacationDayExcelVm * company 赛拓信息技术有限公司 * @author DongCL * @date 2021-02-07 13:29 */ public class VacationDayExcelVm { /** 驾驶员姓名 */ private String driverName; /** 在途 */ private Long way = 0L; /** 在家 <SUF>*/ private Long atHome = 0L; /** 请假 */ private Long leave = 0L; /** 出勤天数 */ private Long totalAttendance = 0L; /** 存放状态 */ private List<EveryDayDetailExcelVm> dVacationDayList; public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } public Long getWay() { return way; } public void setWay(Long way) { this.way = way; } public Long getAtHome() { return atHome; } public void setAtHome(Long atHome) { this.atHome = atHome; } public Long getLeave() { return leave; } public void setLeave(Long leave) { this.leave = leave; } public Long getTotalAttendance() { return totalAttendance; } public void setTotalAttendance(Long totalAttendance) { this.totalAttendance = totalAttendance; } public List<EveryDayDetailExcelVm> getdVacationDayList() { return dVacationDayList; } public void setdVacationDayList(List<EveryDayDetailExcelVm> dVacationDayList) { this.dVacationDayList = dVacationDayList; } }
false
411
4
452
4
471
4
452
4
569
5
false
false
false
false
false
true
52370_4
package org.sd.dyanmicProxy; public class ProxyStar implements Star { StarHandler starHandler; public ProxyStar(StarHandler starHandler) { this.starHandler = starHandler; } /** * 面谈 */ @Override public void confer() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("confer"),null); } /** * 签合同 */ @Override public void signContract() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("signContract"),null); } /** * 订票 */ @Override public void bookTicket() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("bookTicket"),null); } /** * 唱歌 */ @Override public void sing() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("sing"),null); } /** * 收钱 */ @Override public void collectMoney() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("collectMoney"),null); } }
allinin/datasource
src/org/sd/dyanmicProxy/ProxyStar.java
267
/** * 收钱 */
block_comment
zh-cn
package org.sd.dyanmicProxy; public class ProxyStar implements Star { StarHandler starHandler; public ProxyStar(StarHandler starHandler) { this.starHandler = starHandler; } /** * 面谈 */ @Override public void confer() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("confer"),null); } /** * 签合同 */ @Override public void signContract() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("signContract"),null); } /** * 订票 */ @Override public void bookTicket() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("bookTicket"),null); } /** * 唱歌 */ @Override public void sing() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("sing"),null); } /** * 收钱 <SUF>*/ @Override public void collectMoney() throws Throwable { starHandler.invoke(this,this.getClass().getDeclaredMethod("collectMoney"),null); } }
false
253
9
267
8
296
9
267
8
360
12
false
false
false
false
false
true
53970_13
package utils; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; //注释配置Servlet @WebServlet("/CheckCode") public class CheckCode extends HttpServlet { private static final long serialVersionUID = 1L; private int width = 80; // 验证码图片的默认宽度 private int height = 20; // 验证码图片的默认高度 private int codeCount = 4; // 验证码图片的字符数 private int x = 16; private int fontHeight=16; private int codeY=18; private final char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { //构造一个类型为预定义图像类型之一的BufferedImage设置图像的宽、高和类型(TYPE_INT_RGB) BufferedImage Img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 返回Graphics2D,Graphics2D类扩展自Graphics 类,以提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制 Graphics g = Img.getGraphics(); Random random = new Random(); // 将图像填充为白色 g.setColor(Color.WHITE); //填充指定的矩形。x、y坐标均为0,宽为Ϊwidth,高为Ϊheight g.fillRect(0, 0, width, height); // 创建字体,字体大小应该根据图片的高度来定 Font font = new Font("Times new Roman", Font.PLAIN, fontHeight); g.setColor(Color.black); g.setFont(font); Color juneFont = new Color(153, 204, 102); // 随机产生130条干扰线,不易被其他程序探测 g.setColor( juneFont ); for (int i = 0; i < 130; i++) { //返回伪随机数 int x= random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(16); //80/5=16 int yl = random.nextInt(16); //在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1) 和 (x2, y2) 之间画一条线 g.drawLine(x, y, x + xl, y + yl); } // randomCode用于保存随机产生的验证码,以便用户登录后进行验证,线程安全的可变字符序列 StringBuffer randomCode = new StringBuffer(); // 随机产生codeCount数字的验证码 for (int i = 0; i < codeCount; i++) { //返回 char 参数的字符串表示形式 String strRand = String.valueOf(codeSequence[random.nextInt(36)]); // 用随机产生的颜色将验证码绘制到图像中 //创建具有指定红色、绿色和蓝色值的不透明的 sRGB 颜色,这些值都在 (0 - 255) 的范围内 g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); //使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, (i + 1) * x-4, codeY); randomCode.append(strRand); } HttpSession session = request.getSession(); // 将四位数字的验证码保存到Session中 session.setAttribute("realcode", randomCode.toString()); // 禁止浏览器缓存 response.setHeader("Pragma", "no-cache"); //HTTP 1.0 response.setHeader("Cache-Control", "no-cache");//HTTP 1.1 response.setDateHeader("Expires", 0); //在代理服务器端防止缓冲 response.setContentType("image/gif"); //设置正被发往客户端的相应的内容类型 // 将图像输出到Servlet输出流中,ServletOutputStream提供了向客户端的相应的内容类型 ServletOutputStream sos = response.getOutputStream(); ImageIO.write(Img, "gif", sos); //使用支持给定格式的任意 ImageWriter ,将一个图像写入 OutputStream sos.flush(); //刷新此输出流并强制写出所有的输出字节 sos.close(); } }
allision77/pet
src/utils/CheckCode.java
1,250
// randomCode用于保存随机产生的验证码,以便用户登录后进行验证,线程安全的可变字符序列
line_comment
zh-cn
package utils; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; //注释配置Servlet @WebServlet("/CheckCode") public class CheckCode extends HttpServlet { private static final long serialVersionUID = 1L; private int width = 80; // 验证码图片的默认宽度 private int height = 20; // 验证码图片的默认高度 private int codeCount = 4; // 验证码图片的字符数 private int x = 16; private int fontHeight=16; private int codeY=18; private final char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { //构造一个类型为预定义图像类型之一的BufferedImage设置图像的宽、高和类型(TYPE_INT_RGB) BufferedImage Img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 返回Graphics2D,Graphics2D类扩展自Graphics 类,以提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制 Graphics g = Img.getGraphics(); Random random = new Random(); // 将图像填充为白色 g.setColor(Color.WHITE); //填充指定的矩形。x、y坐标均为0,宽为Ϊwidth,高为Ϊheight g.fillRect(0, 0, width, height); // 创建字体,字体大小应该根据图片的高度来定 Font font = new Font("Times new Roman", Font.PLAIN, fontHeight); g.setColor(Color.black); g.setFont(font); Color juneFont = new Color(153, 204, 102); // 随机产生130条干扰线,不易被其他程序探测 g.setColor( juneFont ); for (int i = 0; i < 130; i++) { //返回伪随机数 int x= random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(16); //80/5=16 int yl = random.nextInt(16); //在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1) 和 (x2, y2) 之间画一条线 g.drawLine(x, y, x + xl, y + yl); } // ra <SUF> StringBuffer randomCode = new StringBuffer(); // 随机产生codeCount数字的验证码 for (int i = 0; i < codeCount; i++) { //返回 char 参数的字符串表示形式 String strRand = String.valueOf(codeSequence[random.nextInt(36)]); // 用随机产生的颜色将验证码绘制到图像中 //创建具有指定红色、绿色和蓝色值的不透明的 sRGB 颜色,这些值都在 (0 - 255) 的范围内 g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); //使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, (i + 1) * x-4, codeY); randomCode.append(strRand); } HttpSession session = request.getSession(); // 将四位数字的验证码保存到Session中 session.setAttribute("realcode", randomCode.toString()); // 禁止浏览器缓存 response.setHeader("Pragma", "no-cache"); //HTTP 1.0 response.setHeader("Cache-Control", "no-cache");//HTTP 1.1 response.setDateHeader("Expires", 0); //在代理服务器端防止缓冲 response.setContentType("image/gif"); //设置正被发往客户端的相应的内容类型 // 将图像输出到Servlet输出流中,ServletOutputStream提供了向客户端的相应的内容类型 ServletOutputStream sos = response.getOutputStream(); ImageIO.write(Img, "gif", sos); //使用支持给定格式的任意 ImageWriter ,将一个图像写入 OutputStream sos.flush(); //刷新此输出流并强制写出所有的输出字节 sos.close(); } }
false
1,139
24
1,250
25
1,253
22
1,250
25
1,690
53
false
false
false
false
false
true
23537_4
package com.ruixus.smarty4j; import static org.objectweb.asm.Opcodes.*; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.objectweb.asm.MethodVisitor; public class VariableManager { public static final int NOEXIST = -1; public static final int NOCACHE = 0; private static final int CACHE = 1; /** All variable information read in the current template, use -1 means a variable banned cache */ private Map<String, Integer> variables; /** In the case of the need for rewrite variables in use cache */ private boolean rewrite = false; public VariableManager(Engine engine) { if (engine != null && engine.isCached()) { variables = new HashMap<String, Integer>(); } } /** * 缓存使用情况查询 * * @return 是/否使用缓存 */ public boolean hasCached() { return variables != null; } /** * 阻止指定的变量进行缓存。 * * @param name * 变量名称 */ public void preventCache(String name) { if (variables != null) { variables.put(name, NOCACHE); } } /** * 阻止所有的变量进行缓存。 */ public void preventAllCache() { variables = null; } /** * 回写情况查询 * * @return 是/否强制回写 */ public boolean requiredRewrite() { return rewrite; } /** * 设置强制回写 */ public void forcedRewrite() { rewrite = true; } /** * 获取变量的缓存索引编号 * * @param name * 变量名 * @return 缓存索引编号 */ public int getIndex(String name) { if (variables != null) { Integer value = variables.get(name); if (value != null) { return value; } } return NOEXIST; } /** * 设置变量的缓存索引编号 * * @param name * 变量名 * @param value * 缓存索引编号 */ public void setIndex(String name, int value) { variables.put(name, value); } /** * 添加一次变量的使用记录。 * * @param name * 变量名 */ public void addUsedVariable(String name) { if (variables != null) { Integer value = variables.get(name); if (value == null) { variables.put(name, CACHE); } } } /** * 合并两个对象管理器 * * @param vm * 对象管理器 * @param removeNames * 不需要合并的变量名列表 */ public void merge(VariableManager vm, String... removeNames) { if (vm.variables == null) { variables = null; return; } rewrite = rewrite || vm.rewrite; Map<String, Integer> otherVariables = vm.variables; if (removeNames != null) { for (String name : removeNames) { otherVariables.remove(name); } } for (Entry<String, Integer> entry : otherVariables.entrySet()) { String key = entry.getKey(); if (variables.containsKey(key)) { if (variables.get(key) == NOCACHE) { return; } } variables.put(key, entry.getValue()); } } /** * 变量初始化转换 * * @param mv * ASM方法访问对象 * @param local * 堆栈顶点 * @return 总共的变量数量 */ int parse(MethodVisitor mv, int local) { if (variables != null) { for (Entry<String, Integer> variable : variables.entrySet()) { String key = variable.getKey(); if (variable.getValue() == CACHE) { mv.visitInsn(DUP); mv.visitLdcInsn(key); mv.visitMethodInsn(INVOKEVIRTUAL, Context.NAME, "get", "(Ljava/lang/String;)Ljava/lang/Object;"); mv.visitVarInsn(ASTORE, local); variable.setValue(local); local++; } } mv.visitInsn(POP); } return local; } }
allskystar/smarty4j
src/com/ruixus/smarty4j/VariableManager.java
1,104
/** * 阻止所有的变量进行缓存。 */
block_comment
zh-cn
package com.ruixus.smarty4j; import static org.objectweb.asm.Opcodes.*; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.objectweb.asm.MethodVisitor; public class VariableManager { public static final int NOEXIST = -1; public static final int NOCACHE = 0; private static final int CACHE = 1; /** All variable information read in the current template, use -1 means a variable banned cache */ private Map<String, Integer> variables; /** In the case of the need for rewrite variables in use cache */ private boolean rewrite = false; public VariableManager(Engine engine) { if (engine != null && engine.isCached()) { variables = new HashMap<String, Integer>(); } } /** * 缓存使用情况查询 * * @return 是/否使用缓存 */ public boolean hasCached() { return variables != null; } /** * 阻止指定的变量进行缓存。 * * @param name * 变量名称 */ public void preventCache(String name) { if (variables != null) { variables.put(name, NOCACHE); } } /** * 阻止所 <SUF>*/ public void preventAllCache() { variables = null; } /** * 回写情况查询 * * @return 是/否强制回写 */ public boolean requiredRewrite() { return rewrite; } /** * 设置强制回写 */ public void forcedRewrite() { rewrite = true; } /** * 获取变量的缓存索引编号 * * @param name * 变量名 * @return 缓存索引编号 */ public int getIndex(String name) { if (variables != null) { Integer value = variables.get(name); if (value != null) { return value; } } return NOEXIST; } /** * 设置变量的缓存索引编号 * * @param name * 变量名 * @param value * 缓存索引编号 */ public void setIndex(String name, int value) { variables.put(name, value); } /** * 添加一次变量的使用记录。 * * @param name * 变量名 */ public void addUsedVariable(String name) { if (variables != null) { Integer value = variables.get(name); if (value == null) { variables.put(name, CACHE); } } } /** * 合并两个对象管理器 * * @param vm * 对象管理器 * @param removeNames * 不需要合并的变量名列表 */ public void merge(VariableManager vm, String... removeNames) { if (vm.variables == null) { variables = null; return; } rewrite = rewrite || vm.rewrite; Map<String, Integer> otherVariables = vm.variables; if (removeNames != null) { for (String name : removeNames) { otherVariables.remove(name); } } for (Entry<String, Integer> entry : otherVariables.entrySet()) { String key = entry.getKey(); if (variables.containsKey(key)) { if (variables.get(key) == NOCACHE) { return; } } variables.put(key, entry.getValue()); } } /** * 变量初始化转换 * * @param mv * ASM方法访问对象 * @param local * 堆栈顶点 * @return 总共的变量数量 */ int parse(MethodVisitor mv, int local) { if (variables != null) { for (Entry<String, Integer> variable : variables.entrySet()) { String key = variable.getKey(); if (variable.getValue() == CACHE) { mv.visitInsn(DUP); mv.visitLdcInsn(key); mv.visitMethodInsn(INVOKEVIRTUAL, Context.NAME, "get", "(Ljava/lang/String;)Ljava/lang/Object;"); mv.visitVarInsn(ASTORE, local); variable.setValue(local); local++; } } mv.visitInsn(POP); } return local; } }
false
991
15
1,100
13
1,139
14
1,100
13
1,454
24
false
false
false
false
false
true
7937_1
package mo.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; public class InetAddressUtils { private static final Logger logger = LoggerFactory.getLogger(InetAddressUtils.class); /** * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址, * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值 * * @return ip */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); System.out.println("x-forwarded-for ip: " + ip); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个ip值,第一个ip才是真实ip if (ip.indexOf(",") != -1) { ip = ip.split(",")[0]; } } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); // System.out.println("Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); // System.out.println("WL-Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); // System.out.println("HTTP_CLIENT_IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); // System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); // System.out.println("X-Real-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); // System.out.println("getRemoteAddr ip: " + ip); } logger.info("获取客户端ip[{}]", ip); return ip; } }
alomerry/aoj
backend/main/java/mo/utils/InetAddressUtils.java
633
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
line_comment
zh-cn
package mo.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; public class InetAddressUtils { private static final Logger logger = LoggerFactory.getLogger(InetAddressUtils.class); /** * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址, * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值 * * @return ip */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); System.out.println("x-forwarded-for ip: " + ip); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { // 多次 <SUF> if (ip.indexOf(",") != -1) { ip = ip.split(",")[0]; } } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); // System.out.println("Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); // System.out.println("WL-Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); // System.out.println("HTTP_CLIENT_IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); // System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); // System.out.println("X-Real-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); // System.out.println("getRemoteAddr ip: " + ip); } logger.info("获取客户端ip[{}]", ip); return ip; } }
false
547
18
633
21
655
17
633
21
758
25
false
false
false
false
false
true
18585_19
/** * @Description: * @Author: alton_z * @Create Date Time: 2022-09-11 12:51 * @Update Date Time: 2022-09-11 12:51 * @Updated-By: alton_z * @Update-Location: */ public class KMP { public int getIndexOf(String source, String target) { /** * 边界条件: * 1. source, target 为 null * 2. source 的长度小于 target 的长度 * 返回 -1 */ if (source == null || target == null || target.length() < 1 || source.length() < target.length() ) { return -1; } // sourceC 和 targetC char 数组化 char[] sourceC = source.toCharArray(); char[] targetC = target.toCharArray(); // 初始化 source, target 开始处理位置变量 int sIndex = 0; int tIndex = 0; // O(M) m <= n int[] help = getHelp(targetC); // O(N) // 索引不越界的场景下,处理逻辑 while (sIndex < sourceC.length && tIndex < targetC.length) { // 当source 和 target 字符匹配 if (sourceC[sIndex] == targetC[tIndex]) { // sIndex, tIndex 向下移一位 sIndex++; tIndex++; } else if (help[tIndex] == -1) { // 字符不匹配,且 target 还在 0 位置时,sIndex++ // 这时候, target 首字符都未被匹配上 sIndex++; } else { // 其它场景,如果字符不匹配, tIndex 切换到 tIndex 位置能匹配的最长左边位置上 // 下一次循环, tIndex 和 sIndex 进行字符匹配 tIndex = help[tIndex]; } } // 当 tIndex 越界了,说明 target 全部匹配完成 -> 返回 sIndex - tIndex // 否则返回 -1 return tIndex == targetC.length ? sIndex - tIndex : -1; } /** * 获得 targetC 字符, help 数组 * 特性: * 1. 求 target 位置 i targetC 的每个位置获得它前面 n 位和后面 n 位字符一致 * 2. 不能将 i 位置前面所有的字符都选择完(这样没有任何意义,无法做到加速匹配的目标) * 2. 没有字符匹配的上,返回 0 * 3. 初始化 help[0] = -1, help[1] = 0 * * 要求: * 1. 求 target 位置 i * 降低时间复杂度到 O(N) * @param targetC * @return */ public int[] getHelp(char[] targetC) { int[] help = new int[targetC.length]; help[0] = -1; // base case , 如果 targetC 长度为 1, 返回 help if (help.length == 1) { return help; } // 长度大于 1 , 将 help[1] = 0 // 符合 help 预设 help[1] = 0; // 从 2 位置开始求 help 数组的值 int index = 2; // 当前是哪个位置的 targetC 字符再和 index - 1 位置的字符比较 int compareI = 0; // index 不越界的前提下 while (index < help.length) { // 首次处理时, index = 2, 这时候与 1 位置进行比较就是 compareI 为 0 的字符位 if (targetC[index - 1] == targetC[compareI]) { // 匹配的上,直接更新 help[index] 位为 compareI 的值加上 1 // 代表着有 compareI + 1 个字符符合要求 // index++ 到下一次处理的位置 help[index++] = ++compareI; } else if (compareI > 0) { // 此分支代表字符不匹配,且 compareI 大于 0 时,代表着当前 compareI 不匹配 // 将 compareI 位置更新到 help[compare] 位置上 // 什么含义呢? help[compreI] 位置是下一次进行字符匹配的点。 // 它的数量代表着上一个 compareI 有多少字符是匹配上的。 compareI = help[compareI]; } else { // 说明无法找到与 index - 1 能匹配上的字符,将 help[index] -> 0 // index 切换到下一次比较的位置, index++ help[index++] = 0; } } // 返回 help 数组 return help; } // for test public static String getRandomString(int possibilities, int size) { char[] ans = new char[(int) (Math.random() * size) + 1]; for (int i = 0; i < ans.length; i++) { ans[i] = (char) ((int) (Math.random() * possibilities) + 'a'); } return String.valueOf(ans); } public static void main(String[] args) { int possibilities = 5; int strSize = 20; int matchSize = 5; int testTimes = 5000000; System.out.println("test begin"); for (int i = 0; i < testTimes; i++) { String str = getRandomString(possibilities, strSize); String match = getRandomString(possibilities, matchSize); if (new KMP().getIndexOf(str, match) != str.indexOf(match)) { System.out.println("Oops!"); } } System.out.println("test finish"); } }
alton-zheng/data-structures-and-algorithms
Q00000/kmp/KMP.java
1,391
// 从 2 位置开始求 help 数组的值
line_comment
zh-cn
/** * @Description: * @Author: alton_z * @Create Date Time: 2022-09-11 12:51 * @Update Date Time: 2022-09-11 12:51 * @Updated-By: alton_z * @Update-Location: */ public class KMP { public int getIndexOf(String source, String target) { /** * 边界条件: * 1. source, target 为 null * 2. source 的长度小于 target 的长度 * 返回 -1 */ if (source == null || target == null || target.length() < 1 || source.length() < target.length() ) { return -1; } // sourceC 和 targetC char 数组化 char[] sourceC = source.toCharArray(); char[] targetC = target.toCharArray(); // 初始化 source, target 开始处理位置变量 int sIndex = 0; int tIndex = 0; // O(M) m <= n int[] help = getHelp(targetC); // O(N) // 索引不越界的场景下,处理逻辑 while (sIndex < sourceC.length && tIndex < targetC.length) { // 当source 和 target 字符匹配 if (sourceC[sIndex] == targetC[tIndex]) { // sIndex, tIndex 向下移一位 sIndex++; tIndex++; } else if (help[tIndex] == -1) { // 字符不匹配,且 target 还在 0 位置时,sIndex++ // 这时候, target 首字符都未被匹配上 sIndex++; } else { // 其它场景,如果字符不匹配, tIndex 切换到 tIndex 位置能匹配的最长左边位置上 // 下一次循环, tIndex 和 sIndex 进行字符匹配 tIndex = help[tIndex]; } } // 当 tIndex 越界了,说明 target 全部匹配完成 -> 返回 sIndex - tIndex // 否则返回 -1 return tIndex == targetC.length ? sIndex - tIndex : -1; } /** * 获得 targetC 字符, help 数组 * 特性: * 1. 求 target 位置 i targetC 的每个位置获得它前面 n 位和后面 n 位字符一致 * 2. 不能将 i 位置前面所有的字符都选择完(这样没有任何意义,无法做到加速匹配的目标) * 2. 没有字符匹配的上,返回 0 * 3. 初始化 help[0] = -1, help[1] = 0 * * 要求: * 1. 求 target 位置 i * 降低时间复杂度到 O(N) * @param targetC * @return */ public int[] getHelp(char[] targetC) { int[] help = new int[targetC.length]; help[0] = -1; // base case , 如果 targetC 长度为 1, 返回 help if (help.length == 1) { return help; } // 长度大于 1 , 将 help[1] = 0 // 符合 help 预设 help[1] = 0; // 从 <SUF> int index = 2; // 当前是哪个位置的 targetC 字符再和 index - 1 位置的字符比较 int compareI = 0; // index 不越界的前提下 while (index < help.length) { // 首次处理时, index = 2, 这时候与 1 位置进行比较就是 compareI 为 0 的字符位 if (targetC[index - 1] == targetC[compareI]) { // 匹配的上,直接更新 help[index] 位为 compareI 的值加上 1 // 代表着有 compareI + 1 个字符符合要求 // index++ 到下一次处理的位置 help[index++] = ++compareI; } else if (compareI > 0) { // 此分支代表字符不匹配,且 compareI 大于 0 时,代表着当前 compareI 不匹配 // 将 compareI 位置更新到 help[compare] 位置上 // 什么含义呢? help[compreI] 位置是下一次进行字符匹配的点。 // 它的数量代表着上一个 compareI 有多少字符是匹配上的。 compareI = help[compareI]; } else { // 说明无法找到与 index - 1 能匹配上的字符,将 help[index] -> 0 // index 切换到下一次比较的位置, index++ help[index++] = 0; } } // 返回 help 数组 return help; } // for test public static String getRandomString(int possibilities, int size) { char[] ans = new char[(int) (Math.random() * size) + 1]; for (int i = 0; i < ans.length; i++) { ans[i] = (char) ((int) (Math.random() * possibilities) + 'a'); } return String.valueOf(ans); } public static void main(String[] args) { int possibilities = 5; int strSize = 20; int matchSize = 5; int testTimes = 5000000; System.out.println("test begin"); for (int i = 0; i < testTimes; i++) { String str = getRandomString(possibilities, strSize); String match = getRandomString(possibilities, matchSize); if (new KMP().getIndexOf(str, match) != str.indexOf(match)) { System.out.println("Oops!"); } } System.out.println("test finish"); } }
false
1,380
14
1,391
12
1,437
11
1,391
12
1,798
17
false
false
false
false
false
true
44908_5
package sample; import java.sql.Time; import java.util.Date; public class Schedule { private int schedule_id; //演出计划ID号,primary_key不能设置value private int play_id; //演出的剧目ID号 private int studio_id; //演出的放映厅ID号 private Date date; //演出日期 private Time time; //演出时间 private int seat_count; //座位数量 public Schedule(){} public Schedule(int play_id, int studio_id, Date date,Time time,int seat_count) { this.play_id = play_id; this.studio_id = studio_id; this.date = date; this.time = time; this.seat_count = seat_count; } public int getSchedule_id() { return schedule_id; } public int getPlay_id() { return play_id; } public int getStudio_id() { return studio_id; } public Date getDate() { return date; } public Time getTime() { return time; } public int getSeat_count() { return seat_count; } public void setPlay_id(int play_id) { this.play_id = play_id; } public void setStudio_id(int studio_id) { this.studio_id = studio_id; } public void setDate(Date date) { this.date = date; } public void setTime(Time time) { this.time = time; } public void setSeat_count(int seat_count) { this.seat_count = seat_count; } }
always0108/JAVA
JavaFx/oneschedule/src/sample/Schedule.java
407
//座位数量
line_comment
zh-cn
package sample; import java.sql.Time; import java.util.Date; public class Schedule { private int schedule_id; //演出计划ID号,primary_key不能设置value private int play_id; //演出的剧目ID号 private int studio_id; //演出的放映厅ID号 private Date date; //演出日期 private Time time; //演出时间 private int seat_count; //座位 <SUF> public Schedule(){} public Schedule(int play_id, int studio_id, Date date,Time time,int seat_count) { this.play_id = play_id; this.studio_id = studio_id; this.date = date; this.time = time; this.seat_count = seat_count; } public int getSchedule_id() { return schedule_id; } public int getPlay_id() { return play_id; } public int getStudio_id() { return studio_id; } public Date getDate() { return date; } public Time getTime() { return time; } public int getSeat_count() { return seat_count; } public void setPlay_id(int play_id) { this.play_id = play_id; } public void setStudio_id(int studio_id) { this.studio_id = studio_id; } public void setDate(Date date) { this.date = date; } public void setTime(Time time) { this.time = time; } public void setSeat_count(int seat_count) { this.seat_count = seat_count; } }
false
345
3
407
4
444
3
407
4
503
5
false
false
false
false
false
true
61193_3
package com.nba.collection; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class Data extends Activity { private ListView listview; private int cur_pos = 0;// 当前显示的一行 private String[] items_text = { "迈克尔·乔丹", "科比-布莱恩特 ", "特雷西·麦克格雷迪", "德怀恩·韦德","阿伦·埃泽尔·艾弗森","凯文·加内特" }; private int[] items_img = { R.drawable.nbaplayer, R.drawable.nbaplayer, R.drawable.nbaplayer, R.drawable.nbaplayer,R.drawable.nbaplayer, R.drawable.nbaplayer }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.data); listview = (ListView) findViewById(R.id.listview); final MyAdapter adapter = new MyAdapter(this); listview.setAdapter(adapter); listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);// 一定要设置这个属性,否则ListView不会刷新 listview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) { cur_pos = position;// 更新当前行 } }); } private class MyAdapter extends BaseAdapter { private LayoutInflater inflater; public MyAdapter(Context context) { inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return items_text.length; } public Object getItem(int position) { return items_text[position]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { Log.e("TEST", "refresh once"); convertView = inflater.inflate(R.layout.listplayer, null, false); ImageView img = (ImageView) convertView .findViewById(R.id.list_child_img);// 用于显示图片 TextView tv = (TextView) convertView .findViewById(R.id.list_child_text);// 显示文字 tv.setText(items_text[position]); img.setImageResource(items_img[position]); if (position == cur_pos) {// 如果当前的行就是ListView中选中的一行,就更改显示样式 convertView.setBackgroundColor(Color.LTGRAY);//更改整行的背景色 tv.setTextColor(Color.RED);// 更改字体颜色 } return convertView; } } }
alwaysonline28/NBACollection
src/com/nba/collection/Data.java
788
// 用于显示图片
line_comment
zh-cn
package com.nba.collection; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class Data extends Activity { private ListView listview; private int cur_pos = 0;// 当前显示的一行 private String[] items_text = { "迈克尔·乔丹", "科比-布莱恩特 ", "特雷西·麦克格雷迪", "德怀恩·韦德","阿伦·埃泽尔·艾弗森","凯文·加内特" }; private int[] items_img = { R.drawable.nbaplayer, R.drawable.nbaplayer, R.drawable.nbaplayer, R.drawable.nbaplayer,R.drawable.nbaplayer, R.drawable.nbaplayer }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.data); listview = (ListView) findViewById(R.id.listview); final MyAdapter adapter = new MyAdapter(this); listview.setAdapter(adapter); listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);// 一定要设置这个属性,否则ListView不会刷新 listview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) { cur_pos = position;// 更新当前行 } }); } private class MyAdapter extends BaseAdapter { private LayoutInflater inflater; public MyAdapter(Context context) { inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return items_text.length; } public Object getItem(int position) { return items_text[position]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { Log.e("TEST", "refresh once"); convertView = inflater.inflate(R.layout.listplayer, null, false); ImageView img = (ImageView) convertView .findViewById(R.id.list_child_img);// 用于 <SUF> TextView tv = (TextView) convertView .findViewById(R.id.list_child_text);// 显示文字 tv.setText(items_text[position]); img.setImageResource(items_img[position]); if (position == cur_pos) {// 如果当前的行就是ListView中选中的一行,就更改显示样式 convertView.setBackgroundColor(Color.LTGRAY);//更改整行的背景色 tv.setTextColor(Color.RED);// 更改字体颜色 } return convertView; } } }
false
590
5
788
5
740
4
788
5
969
8
false
false
false
false
false
true
63844_1
package ACM.Quadtrees; import java.util.Arrays; import java.util.LinkedList; /** * Created with IntelliJ IDEA. * User:ChengLiang * Date:2017/5/23 * Time:18:40 * <p> * 如图6-8所示,可以用四分树来表示一个黑白图像,方法是用根结点表示整幅图像,然 * 后把行列各分成两等分,按照图中的方式编号,从左到右对应4个子结点。如果某子结点对 * 应的区域全黑或者全白,则直接用一个黑结点或者白结点表示;如果既有黑又有白,则用一 * 个灰结点表示,并且为这个区域递归建树。 * <p> * 给出两棵四分树的先序遍历,求二者合并之后(黑色部分合并)黑色像素的个数。p表 * 示中间结点,f表示黑色(full),e表示白色(empty)。 * 样例输入: * 3 * ppeeefpffeefe * pefepeefe * peeef * peefe * peeef * peepefefe * 样例输出: * There are 640 black pixels. * There are 512 black pixels. * There are 384 black pixels. * <p> * Quadtrees, UVa 297 * <p> * 原题:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=233 * <p> * 建议看原题,有一个关键点:图片是32*32=1024个像素的 */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); solution.case1(); } private void case1() { String[][] trees = {{"ppeeefpffeefe", "pefepeefe"}, {"peeef", "peefe"}, {"peeef", "peepefefe"}}; for (String[] tree : trees) { pixel(tree); System.out.println("---------------------------------------------------------------------"); } } private void pixel(String[] trees) { System.out.println(Arrays.toString(trees)); Quadtree left = createTree(trees[0]); Quadtree right = createTree(trees[1]); Quadtree sum = left.plus(right); System.out.println("There are " + sum.countBlack() + " black pixels."); } private Quadtree createTree(String treeDesc) { char[] chars = treeDesc.toCharArray(); LinkedList<Character> nodeList = new LinkedList<>(); for (char c : chars) { nodeList.add(c); } Quadtree tree = new Quadtree(); Node root = new Node(nodeList.pollFirst()); tree.setRoot(root); createTree(root, nodeList); return tree; } private static final char key = 'p'; private static final int measure = 32; /** * 先序遍历,反向构建四叉树 */ private void createTree(Node root, LinkedList<Character> treeList) { if (treeList.isEmpty()) { return; } Character rightUpValue = treeList.pollFirst(); Node rightUp = new Node(rightUpValue); root.setRightUp(rightUp); if (rightUpValue == key) { createTree(rightUp, treeList); } Character leftUpValue = treeList.pollFirst(); Node leftUp = new Node(leftUpValue); root.setLeftUp(leftUp); if (leftUpValue == key) { createTree(leftUp, treeList); } Character leftDownValue = treeList.pollFirst(); Node leftDown = new Node(leftDownValue); root.setLeftDown(leftDown); if (leftDownValue == key) { createTree(leftDown, treeList); } Character rightDownValue = treeList.pollFirst(); Node rightDown = new Node(rightDownValue); root.setRightDown(rightDown); if (rightDownValue == key) { createTree(rightDown, treeList); } } private class Quadtree { private Node root; public void setRoot(Node root) { this.root = root; } public Node getRoot() { return root; } public Quadtree plus(Quadtree other) { //this-left other-right Quadtree result = new Quadtree(); result.setRoot(this.getRoot().plus(other.getRoot())); return result; } public int countBlack() { int sum = 0; return this.getRoot().countBlack(sum, measure); } } private class Node { private Boolean color;//null=中间节点,true=黑色,false=白色; private Node rightUp; private Node leftUp; private Node leftDown; private Node rightDown; public Node(Boolean color) { this.color = color; } public Node(char color) { if (color == 'p') { this.color = null; } else if (color == 'f') { this.color = true; } else if (color == 'e') { this.color = false; } } public void setRightUp(Node rightUp) { this.rightUp = rightUp; } public void setLeftUp(Node leftUp) { this.leftUp = leftUp; } public void setLeftDown(Node leftDown) { this.leftDown = leftDown; } public void setRightDown(Node rightDown) { this.rightDown = rightDown; } public Node getRightUp() { return rightUp != null ? rightUp : new Node(this.color); } public Node getLeftUp() { return leftUp != null ? leftUp : new Node(this.color); } public Node getLeftDown() { return leftDown != null ? leftDown : new Node(this.color); } public Node getRightDown() { return rightDown != null ? rightDown : new Node(this.color); } public boolean isBlack() { return this.color != null && this.color; } public boolean isWhite() { return this.color != null && !this.color; } public Node plus(Node other) { if (this.isBlack() || other.isBlack()) { return new Node(true); } if (this.isWhite() && other.isWhite()) { return new Node(false); } Node node = new Node(null); node.setRightUp(this.getRightUp().plus(other.getRightUp())); node.setLeftUp(this.getLeftUp().plus(other.getLeftUp())); node.setLeftDown(this.getLeftDown().plus(other.getLeftDown())); node.setRightDown(this.getRightDown().plus(other.getRightDown())); return node; } public int countBlack(int sum, int measure) { if (this.isBlack()) { sum += measure * measure; return sum; } if (this.isWhite()) { return sum; } sum += this.getRightUp().countBlack(0, measure >> 1); sum += this.getLeftUp().countBlack(0, measure >> 1); sum += this.getLeftDown().countBlack(0, measure >> 1); sum += this.getRightDown().countBlack(0, measure >> 1); return sum; } } }
amao12580/algorithm
src/main/java/ACM/Quadtrees/Solution.java
1,806
/** * 先序遍历,反向构建四叉树 */
block_comment
zh-cn
package ACM.Quadtrees; import java.util.Arrays; import java.util.LinkedList; /** * Created with IntelliJ IDEA. * User:ChengLiang * Date:2017/5/23 * Time:18:40 * <p> * 如图6-8所示,可以用四分树来表示一个黑白图像,方法是用根结点表示整幅图像,然 * 后把行列各分成两等分,按照图中的方式编号,从左到右对应4个子结点。如果某子结点对 * 应的区域全黑或者全白,则直接用一个黑结点或者白结点表示;如果既有黑又有白,则用一 * 个灰结点表示,并且为这个区域递归建树。 * <p> * 给出两棵四分树的先序遍历,求二者合并之后(黑色部分合并)黑色像素的个数。p表 * 示中间结点,f表示黑色(full),e表示白色(empty)。 * 样例输入: * 3 * ppeeefpffeefe * pefepeefe * peeef * peefe * peeef * peepefefe * 样例输出: * There are 640 black pixels. * There are 512 black pixels. * There are 384 black pixels. * <p> * Quadtrees, UVa 297 * <p> * 原题:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=233 * <p> * 建议看原题,有一个关键点:图片是32*32=1024个像素的 */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); solution.case1(); } private void case1() { String[][] trees = {{"ppeeefpffeefe", "pefepeefe"}, {"peeef", "peefe"}, {"peeef", "peepefefe"}}; for (String[] tree : trees) { pixel(tree); System.out.println("---------------------------------------------------------------------"); } } private void pixel(String[] trees) { System.out.println(Arrays.toString(trees)); Quadtree left = createTree(trees[0]); Quadtree right = createTree(trees[1]); Quadtree sum = left.plus(right); System.out.println("There are " + sum.countBlack() + " black pixels."); } private Quadtree createTree(String treeDesc) { char[] chars = treeDesc.toCharArray(); LinkedList<Character> nodeList = new LinkedList<>(); for (char c : chars) { nodeList.add(c); } Quadtree tree = new Quadtree(); Node root = new Node(nodeList.pollFirst()); tree.setRoot(root); createTree(root, nodeList); return tree; } private static final char key = 'p'; private static final int measure = 32; /** * 先序遍 <SUF>*/ private void createTree(Node root, LinkedList<Character> treeList) { if (treeList.isEmpty()) { return; } Character rightUpValue = treeList.pollFirst(); Node rightUp = new Node(rightUpValue); root.setRightUp(rightUp); if (rightUpValue == key) { createTree(rightUp, treeList); } Character leftUpValue = treeList.pollFirst(); Node leftUp = new Node(leftUpValue); root.setLeftUp(leftUp); if (leftUpValue == key) { createTree(leftUp, treeList); } Character leftDownValue = treeList.pollFirst(); Node leftDown = new Node(leftDownValue); root.setLeftDown(leftDown); if (leftDownValue == key) { createTree(leftDown, treeList); } Character rightDownValue = treeList.pollFirst(); Node rightDown = new Node(rightDownValue); root.setRightDown(rightDown); if (rightDownValue == key) { createTree(rightDown, treeList); } } private class Quadtree { private Node root; public void setRoot(Node root) { this.root = root; } public Node getRoot() { return root; } public Quadtree plus(Quadtree other) { //this-left other-right Quadtree result = new Quadtree(); result.setRoot(this.getRoot().plus(other.getRoot())); return result; } public int countBlack() { int sum = 0; return this.getRoot().countBlack(sum, measure); } } private class Node { private Boolean color;//null=中间节点,true=黑色,false=白色; private Node rightUp; private Node leftUp; private Node leftDown; private Node rightDown; public Node(Boolean color) { this.color = color; } public Node(char color) { if (color == 'p') { this.color = null; } else if (color == 'f') { this.color = true; } else if (color == 'e') { this.color = false; } } public void setRightUp(Node rightUp) { this.rightUp = rightUp; } public void setLeftUp(Node leftUp) { this.leftUp = leftUp; } public void setLeftDown(Node leftDown) { this.leftDown = leftDown; } public void setRightDown(Node rightDown) { this.rightDown = rightDown; } public Node getRightUp() { return rightUp != null ? rightUp : new Node(this.color); } public Node getLeftUp() { return leftUp != null ? leftUp : new Node(this.color); } public Node getLeftDown() { return leftDown != null ? leftDown : new Node(this.color); } public Node getRightDown() { return rightDown != null ? rightDown : new Node(this.color); } public boolean isBlack() { return this.color != null && this.color; } public boolean isWhite() { return this.color != null && !this.color; } public Node plus(Node other) { if (this.isBlack() || other.isBlack()) { return new Node(true); } if (this.isWhite() && other.isWhite()) { return new Node(false); } Node node = new Node(null); node.setRightUp(this.getRightUp().plus(other.getRightUp())); node.setLeftUp(this.getLeftUp().plus(other.getLeftUp())); node.setLeftDown(this.getLeftDown().plus(other.getLeftDown())); node.setRightDown(this.getRightDown().plus(other.getRightDown())); return node; } public int countBlack(int sum, int measure) { if (this.isBlack()) { sum += measure * measure; return sum; } if (this.isWhite()) { return sum; } sum += this.getRightUp().countBlack(0, measure >> 1); sum += this.getLeftUp().countBlack(0, measure >> 1); sum += this.getLeftDown().countBlack(0, measure >> 1); sum += this.getRightDown().countBlack(0, measure >> 1); return sum; } } }
false
1,628
18
1,806
16
1,918
17
1,806
16
2,164
28
false
false
false
false
false
true
24953_11
package com.amapv2.apis.geocoder; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.amap.api.maps.AMap; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.MapView; import com.amap.api.maps.model.BitmapDescriptorFactory; import com.amap.api.maps.model.Marker; import com.amap.api.maps.model.MarkerOptions; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.geocoder.GeocodeAddress; import com.amap.api.services.geocoder.GeocodeQuery; import com.amap.api.services.geocoder.GeocodeResult; import com.amap.api.services.geocoder.GeocodeSearch; import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener; import com.amap.api.services.geocoder.RegeocodeQuery; import com.amap.api.services.geocoder.RegeocodeResult; import com.amapv2.apis.R; import com.amapv2.apis.util.AMapUtil; import com.amapv2.apis.util.ToastUtil; /** * 地理编码与逆地理编码功能介绍 */ public class GeocoderActivity extends Activity implements OnGeocodeSearchListener, OnClickListener { private ProgressDialog progDialog = null; private GeocodeSearch geocoderSearch; private String addressName; private AMap aMap; private MapView mapView; private LatLonPoint latLonPoint = new LatLonPoint(39.90865, 116.39751); private Marker geoMarker; private Marker regeoMarker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.geocoder_activity); /* * 设置离线地图存储目录,在下载离线地图或初始化地图设置; * 使用过程中可自行设置, 若自行设置了离线地图存储的路径, * 则需要在离线地图下载和使用地图页面都进行路径设置 * */ //Demo中为了其他界面可以使用下载的离线地图,使用默认位置存储,屏蔽了自定义设置 // MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this); mapView = (MapView) findViewById(R.id.map); mapView.onCreate(savedInstanceState);// 此方法必须重写 init(); } /** * 初始化AMap对象 */ private void init() { if (aMap == null) { aMap = mapView.getMap(); geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED))); } Button geoButton = (Button) findViewById(R.id.geoButton); geoButton.setOnClickListener(this); Button regeoButton = (Button) findViewById(R.id.regeoButton); regeoButton.setOnClickListener(this); geocoderSearch = new GeocodeSearch(this); geocoderSearch.setOnGeocodeSearchListener(this); progDialog = new ProgressDialog(this); } /** * 方法必须重写 */ @Override protected void onResume() { super.onResume(); mapView.onResume(); } /** * 方法必须重写 */ @Override protected void onPause() { super.onPause(); mapView.onPause(); } /** * 方法必须重写 */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } /** * 方法必须重写 */ @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } /** * 显示进度条对话框 */ public void showDialog() { progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progDialog.setIndeterminate(false); progDialog.setCancelable(true); progDialog.setMessage("正在获取地址"); progDialog.show(); } /** * 隐藏进度条对话框 */ public void dismissDialog() { if (progDialog != null) { progDialog.dismiss(); } } /** * 响应地理编码 */ public void getLatlon(final String name) { showDialog(); GeocodeQuery query = new GeocodeQuery(name, "010");// 第一个参数表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode, geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求 } /** * 响应逆地理编码 */ public void getAddress(final LatLonPoint latLonPoint) { showDialog(); RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng,第二参数表示范围多少米,第三个参数表示是火系坐标系还是GPS原生坐标系 geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求 } /** * 地理编码查询回调 */ @Override public void onGeocodeSearched(GeocodeResult result, int rCode) { dismissDialog(); if (rCode == 0) { if (result != null && result.getGeocodeAddressList() != null && result.getGeocodeAddressList().size() > 0) { GeocodeAddress address = result.getGeocodeAddressList().get(0); aMap.animateCamera(CameraUpdateFactory.newLatLngZoom( AMapUtil.convertToLatLng(address.getLatLonPoint()), 15)); geoMarker.setPosition(AMapUtil.convertToLatLng(address .getLatLonPoint())); addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:" + address.getFormatAddress(); ToastUtil.show(GeocoderActivity.this, addressName); } else { ToastUtil.show(GeocoderActivity.this, R.string.no_result); } } else if (rCode == 27) { ToastUtil.show(GeocoderActivity.this, R.string.error_network); } else if (rCode == 32) { ToastUtil.show(GeocoderActivity.this, R.string.error_key); } else { ToastUtil.show(GeocoderActivity.this, getString(R.string.error_other) + rCode); } } /** * 逆地理编码回调 */ @Override public void onRegeocodeSearched(RegeocodeResult result, int rCode) { dismissDialog(); if (rCode == 0) { if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) { addressName = result.getRegeocodeAddress().getFormatAddress() + "附近"; aMap.animateCamera(CameraUpdateFactory.newLatLngZoom( AMapUtil.convertToLatLng(latLonPoint), 15)); regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint)); ToastUtil.show(GeocoderActivity.this, addressName); } else { ToastUtil.show(GeocoderActivity.this, R.string.no_result); } } else if (rCode == 27) { ToastUtil.show(GeocoderActivity.this, R.string.error_network); } else if (rCode == 32) { ToastUtil.show(GeocoderActivity.this, R.string.error_key); } else { ToastUtil.show(GeocoderActivity.this, getString(R.string.error_other) + rCode); } } @Override public void onClick(View v) { switch (v.getId()) { /** * 响应地理编码按钮 */ case R.id.geoButton: getLatlon("方恒国际中心"); break; /** * 响应逆地理编码按钮 */ case R.id.regeoButton: getAddress(latLonPoint); break; default: break; } } }
amapapi/Android_3D_Demo
src/com/amapv2/apis/geocoder/GeocoderActivity.java
2,229
/** * 隐藏进度条对话框 */
block_comment
zh-cn
package com.amapv2.apis.geocoder; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.amap.api.maps.AMap; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.MapView; import com.amap.api.maps.model.BitmapDescriptorFactory; import com.amap.api.maps.model.Marker; import com.amap.api.maps.model.MarkerOptions; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.geocoder.GeocodeAddress; import com.amap.api.services.geocoder.GeocodeQuery; import com.amap.api.services.geocoder.GeocodeResult; import com.amap.api.services.geocoder.GeocodeSearch; import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener; import com.amap.api.services.geocoder.RegeocodeQuery; import com.amap.api.services.geocoder.RegeocodeResult; import com.amapv2.apis.R; import com.amapv2.apis.util.AMapUtil; import com.amapv2.apis.util.ToastUtil; /** * 地理编码与逆地理编码功能介绍 */ public class GeocoderActivity extends Activity implements OnGeocodeSearchListener, OnClickListener { private ProgressDialog progDialog = null; private GeocodeSearch geocoderSearch; private String addressName; private AMap aMap; private MapView mapView; private LatLonPoint latLonPoint = new LatLonPoint(39.90865, 116.39751); private Marker geoMarker; private Marker regeoMarker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.geocoder_activity); /* * 设置离线地图存储目录,在下载离线地图或初始化地图设置; * 使用过程中可自行设置, 若自行设置了离线地图存储的路径, * 则需要在离线地图下载和使用地图页面都进行路径设置 * */ //Demo中为了其他界面可以使用下载的离线地图,使用默认位置存储,屏蔽了自定义设置 // MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this); mapView = (MapView) findViewById(R.id.map); mapView.onCreate(savedInstanceState);// 此方法必须重写 init(); } /** * 初始化AMap对象 */ private void init() { if (aMap == null) { aMap = mapView.getMap(); geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_RED))); } Button geoButton = (Button) findViewById(R.id.geoButton); geoButton.setOnClickListener(this); Button regeoButton = (Button) findViewById(R.id.regeoButton); regeoButton.setOnClickListener(this); geocoderSearch = new GeocodeSearch(this); geocoderSearch.setOnGeocodeSearchListener(this); progDialog = new ProgressDialog(this); } /** * 方法必须重写 */ @Override protected void onResume() { super.onResume(); mapView.onResume(); } /** * 方法必须重写 */ @Override protected void onPause() { super.onPause(); mapView.onPause(); } /** * 方法必须重写 */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } /** * 方法必须重写 */ @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } /** * 显示进度条对话框 */ public void showDialog() { progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progDialog.setIndeterminate(false); progDialog.setCancelable(true); progDialog.setMessage("正在获取地址"); progDialog.show(); } /** * 隐藏进 <SUF>*/ public void dismissDialog() { if (progDialog != null) { progDialog.dismiss(); } } /** * 响应地理编码 */ public void getLatlon(final String name) { showDialog(); GeocodeQuery query = new GeocodeQuery(name, "010");// 第一个参数表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode, geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求 } /** * 响应逆地理编码 */ public void getAddress(final LatLonPoint latLonPoint) { showDialog(); RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng,第二参数表示范围多少米,第三个参数表示是火系坐标系还是GPS原生坐标系 geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求 } /** * 地理编码查询回调 */ @Override public void onGeocodeSearched(GeocodeResult result, int rCode) { dismissDialog(); if (rCode == 0) { if (result != null && result.getGeocodeAddressList() != null && result.getGeocodeAddressList().size() > 0) { GeocodeAddress address = result.getGeocodeAddressList().get(0); aMap.animateCamera(CameraUpdateFactory.newLatLngZoom( AMapUtil.convertToLatLng(address.getLatLonPoint()), 15)); geoMarker.setPosition(AMapUtil.convertToLatLng(address .getLatLonPoint())); addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:" + address.getFormatAddress(); ToastUtil.show(GeocoderActivity.this, addressName); } else { ToastUtil.show(GeocoderActivity.this, R.string.no_result); } } else if (rCode == 27) { ToastUtil.show(GeocoderActivity.this, R.string.error_network); } else if (rCode == 32) { ToastUtil.show(GeocoderActivity.this, R.string.error_key); } else { ToastUtil.show(GeocoderActivity.this, getString(R.string.error_other) + rCode); } } /** * 逆地理编码回调 */ @Override public void onRegeocodeSearched(RegeocodeResult result, int rCode) { dismissDialog(); if (rCode == 0) { if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) { addressName = result.getRegeocodeAddress().getFormatAddress() + "附近"; aMap.animateCamera(CameraUpdateFactory.newLatLngZoom( AMapUtil.convertToLatLng(latLonPoint), 15)); regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint)); ToastUtil.show(GeocoderActivity.this, addressName); } else { ToastUtil.show(GeocoderActivity.this, R.string.no_result); } } else if (rCode == 27) { ToastUtil.show(GeocoderActivity.this, R.string.error_network); } else if (rCode == 32) { ToastUtil.show(GeocoderActivity.this, R.string.error_key); } else { ToastUtil.show(GeocoderActivity.this, getString(R.string.error_other) + rCode); } } @Override public void onClick(View v) { switch (v.getId()) { /** * 响应地理编码按钮 */ case R.id.geoButton: getLatlon("方恒国际中心"); break; /** * 响应逆地理编码按钮 */ case R.id.regeoButton: getAddress(latLonPoint); break; default: break; } } }
false
1,822
13
2,229
13
2,191
12
2,229
13
2,832
20
false
false
false
false
false
true
51893_3
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.deepcolor.deepred; public final class R { public static final class attr { } public static final class color { public static final int red=0x7f040000; public static final int shot_button_pressed=0x7f040002; /** 拍摄按钮的颜色 */ public static final int shot_button_unpress=0x7f040001; } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f050000; public static final int activity_vertical_margin=0x7f050001; /** 闪光灯的大小 */ public static final int flash_view_size=0x7f050008; /** live photo开关大小 */ public static final int live_photo_check_box_size=0x7f050007; /** 小图的预览控件大小 */ public static final int pic_preview_view_size=0x7f050006; public static final int shot_button_bg_radius=0x7f050005; public static final int shot_button_bg_size=0x7f050004; public static final int shot_button_radius=0x7f050003; /** 拍摄按钮的大小 <dimen name="shot_button_width">76dp</dimen> <dimen name="shot_button_height">76dp</dimen> */ public static final int shot_button_size=0x7f050002; } public static final class drawable { public static final int flash_auto=0x7f020000; public static final int flash_off=0x7f020001; public static final int flash_on=0x7f020002; public static final int focus=0x7f020003; public static final int ic_launcher=0x7f020004; public static final int live_photo_off=0x7f020005; public static final int live_photo_on=0x7f020006; public static final int live_photo_selector=0x7f020007; public static final int shape=0x7f020008; public static final int shot_bg=0x7f020009; public static final int shot_pressed=0x7f02000a; public static final int shot_selector=0x7f02000b; public static final int shot_unpress=0x7f02000c; } public static final class id { public static final int action_settings=0x7f090007; public static final int baffle_bg_view=0x7f090002; public static final int baffle_view=0x7f090003; public static final int camera_view=0x7f090000; public static final int flash_view=0x7f090005; public static final int focus_view=0x7f090001; public static final int live_photo_check_box=0x7f090004; public static final int shot_button=0x7f090006; } public static final class layout { public static final int main_activity=0x7f030000; } public static final class menu { public static final int main=0x7f080000; } public static final class string { public static final int action_settings=0x7f060002; public static final int app_name=0x7f060000; public static final int hello_world=0x7f060001; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f070000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f070001; } }
amazingyyc/DeepRed
gen/com/deepcolor/deepred/R.java
1,381
/** 闪光灯的大小 */
block_comment
zh-cn
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.deepcolor.deepred; public final class R { public static final class attr { } public static final class color { public static final int red=0x7f040000; public static final int shot_button_pressed=0x7f040002; /** 拍摄按钮的颜色 */ public static final int shot_button_unpress=0x7f040001; } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f050000; public static final int activity_vertical_margin=0x7f050001; /** 闪光灯 <SUF>*/ public static final int flash_view_size=0x7f050008; /** live photo开关大小 */ public static final int live_photo_check_box_size=0x7f050007; /** 小图的预览控件大小 */ public static final int pic_preview_view_size=0x7f050006; public static final int shot_button_bg_radius=0x7f050005; public static final int shot_button_bg_size=0x7f050004; public static final int shot_button_radius=0x7f050003; /** 拍摄按钮的大小 <dimen name="shot_button_width">76dp</dimen> <dimen name="shot_button_height">76dp</dimen> */ public static final int shot_button_size=0x7f050002; } public static final class drawable { public static final int flash_auto=0x7f020000; public static final int flash_off=0x7f020001; public static final int flash_on=0x7f020002; public static final int focus=0x7f020003; public static final int ic_launcher=0x7f020004; public static final int live_photo_off=0x7f020005; public static final int live_photo_on=0x7f020006; public static final int live_photo_selector=0x7f020007; public static final int shape=0x7f020008; public static final int shot_bg=0x7f020009; public static final int shot_pressed=0x7f02000a; public static final int shot_selector=0x7f02000b; public static final int shot_unpress=0x7f02000c; } public static final class id { public static final int action_settings=0x7f090007; public static final int baffle_bg_view=0x7f090002; public static final int baffle_view=0x7f090003; public static final int camera_view=0x7f090000; public static final int flash_view=0x7f090005; public static final int focus_view=0x7f090001; public static final int live_photo_check_box=0x7f090004; public static final int shot_button=0x7f090006; } public static final class layout { public static final int main_activity=0x7f030000; } public static final class menu { public static final int main=0x7f080000; } public static final class string { public static final int action_settings=0x7f060002; public static final int app_name=0x7f060000; public static final int hello_world=0x7f060001; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f070000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f070001; } }
false
1,302
10
1,381
12
1,458
10
1,381
12
1,535
16
false
false
false
false
false
true
42431_0
/** * 问题描述: * 给定包含4 300 000 000个32位整数的顺序文件, * 如何找出一个至少出现两次的整数 */ public class FindTwice { /** * 由于4 300 000 000 >2^32,所以必然存在重复的整数 * 考虑到内存的问题,可以先读取一部分,然后查找 * 这里假设一次读取10个 */ public static void main(String[] args) { int[] arr = {2,3,4,5,7,11,12,12,13,14,15}; int iCount=0; int increase=arr[0]; for(;iCount<arr.length;iCount++){ if(arr[iCount]>iCount+increase){ increase+=(arr[iCount]-iCount-increase); continue; } if(arr[iCount]<iCount+increase){ System.out.println("重复的数字是:"+arr[iCount]); break; } } } }
amberlife/learnProcess
src/FindTwice.java
266
/** * 问题描述: * 给定包含4 300 000 000个32位整数的顺序文件, * 如何找出一个至少出现两次的整数 */
block_comment
zh-cn
/** * 问题描 <SUF>*/ public class FindTwice { /** * 由于4 300 000 000 >2^32,所以必然存在重复的整数 * 考虑到内存的问题,可以先读取一部分,然后查找 * 这里假设一次读取10个 */ public static void main(String[] args) { int[] arr = {2,3,4,5,7,11,12,12,13,14,15}; int iCount=0; int increase=arr[0]; for(;iCount<arr.length;iCount++){ if(arr[iCount]>iCount+increase){ increase+=(arr[iCount]-iCount-increase); continue; } if(arr[iCount]<iCount+increase){ System.out.println("重复的数字是:"+arr[iCount]); break; } } } }
false
254
47
266
51
276
46
266
51
357
77
false
false
false
false
false
true
55991_1
package com.pigeon.spring.entity; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity(name="T_SENSOR") public class T_SENSOR { private String obj_id;//主键 private String ring_code;//鸽环IMEI private int ring_mode;//飞行状态:1--走路,2--爬升,3--飞行,4--下降 private Timestamp sensor_time;//状态记录时间 @Id @Column(name="obj_id",nullable=false,length = 32) @GeneratedValue(generator="hibernate-uuid") @GenericGenerator(name = "hibernate-uuid", strategy = "uuid") public String getObj_id() { return obj_id; } public void setObj_id(String obj_id) { this.obj_id = obj_id; } public String getRing_code() { return ring_code; } public void setRing_code(String ring_code) { this.ring_code = ring_code; } public int getRing_mode() { return ring_mode; } public void setRing_mode(int ring_mode) { this.ring_mode = ring_mode; } public Timestamp getSensor_time() { return sensor_time; } public void setSensor_time(Timestamp sensor_time) { this.sensor_time = sensor_time; } }
amosigeda/pigeonAppServer
src/com/pigeon/spring/entity/T_SENSOR.java
405
//飞行状态:1--走路,2--爬升,3--飞行,4--下降
line_comment
zh-cn
package com.pigeon.spring.entity; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity(name="T_SENSOR") public class T_SENSOR { private String obj_id;//主键 private String ring_code;//鸽环IMEI private int ring_mode;//飞行 <SUF> private Timestamp sensor_time;//状态记录时间 @Id @Column(name="obj_id",nullable=false,length = 32) @GeneratedValue(generator="hibernate-uuid") @GenericGenerator(name = "hibernate-uuid", strategy = "uuid") public String getObj_id() { return obj_id; } public void setObj_id(String obj_id) { this.obj_id = obj_id; } public String getRing_code() { return ring_code; } public void setRing_code(String ring_code) { this.ring_code = ring_code; } public int getRing_mode() { return ring_mode; } public void setRing_mode(int ring_mode) { this.ring_mode = ring_mode; } public Timestamp getSensor_time() { return sensor_time; } public void setSensor_time(Timestamp sensor_time) { this.sensor_time = sensor_time; } }
false
291
20
405
25
401
20
405
25
465
37
false
false
false
false
false
true
5390_2
package auboo.soft.smallrest.ui.me.bean; import java.util.List; /** * 笑话大全数据bean * Created by amos on 2018/6/29. */ public class JokeBean { /** * reason : Success * result : {"data":[{"content":"健身房来了一个老叔,一来就玩大重量的杠铃,他扛着杠铃青筋暴起,表情狰狞,咬紧牙关还真让他给扛起来了!然后,他扔下杠铃,表情凝重。我:\u201c叔,腰闪着了吗?\u201d他吐出一颗牙齿:\u201c腰没事,刚刚咬太大力了,牙齿没扛住!\u201d","hashId":"20cf3408a3a70b042a1de6ddeb9ead1c","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"七年没见的大学同学突然管我借钱,我张口就回:二十万够么?不够了在说话\u201d同学乐开了花立马回复:\u201c够用,还是老哥你有办法啊,你放心,我以后一定还给你,七年多没见了你现在干啥呢,这么有钱?\u201d我呵呵一笑:\u201c没事,不够用您尽管说话,俺现在在做抵押贷款呢!\u201d.....","hashId":"bd6395aea1c4af8c03f9ac1e122437ad","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"捉迷藏绝对堪称是最血腥最暴力的游戏了。记忆中,那是多年前的一个晚上,镇上的王叔在他隔壁邻居家里玩捉迷藏,结果就被找了出来,回来后一条腿已经是断了的\u2026\u2026从那时,我才知道捉迷藏这个游戏,输了的人是要被打断腿的!","hashId":"7e71bf256f052c3f18ddadf05d3ab504","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"侄子最近考了三十几分,回家找他妈妈签名,他妈气的,直接揍一顿,哭哭啼啼过来找我,我笑笑跟他说:没事,以后上课多用心,叔叔帮你签名。小侄子边哭边说:叔叔,我过来想问问你,你小时候考零分怎么度过的?","hashId":"e72ff1d053024e60c0d7858f12478fbc","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"今天相亲,女孩子长发飘飘,举止得体,落落大方,尤其是她那灿烂的笑容,让我的心里与她无丝毫距离感!我在想如果我足够幸运,我一定会好好的珍惜眼前这个女孩!\u201c我能跟你拍张合照吗?\u201d我一听这话,兴奋的马上说好!拍完后她站起身来:\u201c我根本不想相亲的,看了你我的合照,我想我爸妈肯定再不会哔我相亲了,今天就这样吧,这桌子菜买过单了,您慢吃,拜拜\u2026\u2026\u201d","hashId":"214f2f7654aa514fb03ec8458e637eb6","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"下班了,我却迟迟不敢回家,站在家门口,想着妻子殷切的眼神,更是犹豫不绝,听着妻子切菜的声音更是让我心胆俱碎,硬着头皮,壮着胆子,猛的推开门大声对着妻子喊到:\u201c老婆,今天中午太热了,我多花了一块钱!\u201d","hashId":"badc7667b754368eec4916464c77e0b7","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"今天去逛超市,突然有一个妹子朝我招手,大声对我叫道:\u201c帅哥帅哥,你过来一下!\u201d 我走过去问她有什么事?那妹子指着身旁的一袋米对我说:\u201c帅哥,我想让你帮我把这袋米扛到超市门口外面去\u2026\u2026\u201d我一时些犯犹豫,正想着要不要帮她这个忙? 那妹子见我没有立时答应,似乎很不爽,说:\u201c你怎么不知好歹啊?你知不知道,你其实长得一点都不帅,根本称不上什么帅哥!可我不还是叫你帅哥不是?可你却这么不通人情,叫你帮一下忙,还要犹犹豫豫的!\u2026\u2026\u201d我:\u2026\u2026","hashId":"fc840520cce36b157f0f8eef3f7d622b","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"去男友家,我跟男友在房间里玩儿,叔叔在厨房里做饭,不大会儿,听到叔叔喊\u201c宝贝儿,你最爱吃的红烧肉出锅了\u201d我跟男友说\u201c叔叔真可爱,你都这么大了,他还喊你宝贝儿\u201d男友白我一眼说\u201c你开门去看看\u201d 打开房门看到阿姨美滋滋的端着红烧肉从厨房出来了\u2026\u2026","hashId":"5031c25fe4d3a1b3bac9479ca3eaf15e","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"邻居有一熊孩子老爱用小石子在别人家车上乱刻,教育多少次了就是不听。那天又淘气了不是,人家又找他老爸告状去了,他老爸各种赔不是,等那人走了马上就火了,一巴掌就甩过去:狗日的,给老子出来,以后再给人家车上乱搞老子不抽死你,你说你刻就刻吧,你每次都刻个老子名字是什么意思?","hashId":"74cb1bcd3ed7822cb98398991f238412","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"几个男人在一起谈论自己家的母老虎。这时一个男人道:\u201c难道你们就没有当家做主的时候?\u201d其他男人不约而同反问:\u201c难道你有?\u201d男人:\u201c我当然有啊,我老婆买衣服就必须征得我同意。\u201d其他男人:\u201c为什么?\u201d男人:\u201c因为她要是买浅色衣服,我是洗不干净的。\u201d","hashId":"f99188b17774312e2a5cf38973eb42e5","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"}]} * error_code : 0 */ private String reason; private ResultBean result; private int error_code; public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public static class ResultBean { private List<DataBean> data; public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { /** * content : 健身房来了一个老叔,一来就玩大重量的杠铃,他扛着杠铃青筋暴起,表情狰狞,咬紧牙关还真让他给扛起来了!然后,他扔下杠铃,表情凝重。我:“叔,腰闪着了吗?”他吐出一颗牙齿:“腰没事,刚刚咬太大力了,牙齿没扛住!” * hashId : 20cf3408a3a70b042a1de6ddeb9ead1c * unixtime : 1530251700 * updatetime : 2018-06-29 13:55:00 */ private String content; private String hashId; private int unixtime; private String updatetime; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getHashId() { return hashId; } public void setHashId(String hashId) { this.hashId = hashId; } public int getUnixtime() { return unixtime; } public void setUnixtime(int unixtime) { this.unixtime = unixtime; } public String getUpdatetime() { return updatetime; } public void setUpdatetime(String updatetime) { this.updatetime = updatetime; } } } }
amosxb/SmallRest
app/src/main/java/auboo/soft/smallrest/ui/me/bean/JokeBean.java
3,006
/** * content : 健身房来了一个老叔,一来就玩大重量的杠铃,他扛着杠铃青筋暴起,表情狰狞,咬紧牙关还真让他给扛起来了!然后,他扔下杠铃,表情凝重。我:“叔,腰闪着了吗?”他吐出一颗牙齿:“腰没事,刚刚咬太大力了,牙齿没扛住!” * hashId : 20cf3408a3a70b042a1de6ddeb9ead1c * unixtime : 1530251700 * updatetime : 2018-06-29 13:55:00 */
block_comment
zh-cn
package auboo.soft.smallrest.ui.me.bean; import java.util.List; /** * 笑话大全数据bean * Created by amos on 2018/6/29. */ public class JokeBean { /** * reason : Success * result : {"data":[{"content":"健身房来了一个老叔,一来就玩大重量的杠铃,他扛着杠铃青筋暴起,表情狰狞,咬紧牙关还真让他给扛起来了!然后,他扔下杠铃,表情凝重。我:\u201c叔,腰闪着了吗?\u201d他吐出一颗牙齿:\u201c腰没事,刚刚咬太大力了,牙齿没扛住!\u201d","hashId":"20cf3408a3a70b042a1de6ddeb9ead1c","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"七年没见的大学同学突然管我借钱,我张口就回:二十万够么?不够了在说话\u201d同学乐开了花立马回复:\u201c够用,还是老哥你有办法啊,你放心,我以后一定还给你,七年多没见了你现在干啥呢,这么有钱?\u201d我呵呵一笑:\u201c没事,不够用您尽管说话,俺现在在做抵押贷款呢!\u201d.....","hashId":"bd6395aea1c4af8c03f9ac1e122437ad","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"捉迷藏绝对堪称是最血腥最暴力的游戏了。记忆中,那是多年前的一个晚上,镇上的王叔在他隔壁邻居家里玩捉迷藏,结果就被找了出来,回来后一条腿已经是断了的\u2026\u2026从那时,我才知道捉迷藏这个游戏,输了的人是要被打断腿的!","hashId":"7e71bf256f052c3f18ddadf05d3ab504","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"侄子最近考了三十几分,回家找他妈妈签名,他妈气的,直接揍一顿,哭哭啼啼过来找我,我笑笑跟他说:没事,以后上课多用心,叔叔帮你签名。小侄子边哭边说:叔叔,我过来想问问你,你小时候考零分怎么度过的?","hashId":"e72ff1d053024e60c0d7858f12478fbc","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"今天相亲,女孩子长发飘飘,举止得体,落落大方,尤其是她那灿烂的笑容,让我的心里与她无丝毫距离感!我在想如果我足够幸运,我一定会好好的珍惜眼前这个女孩!\u201c我能跟你拍张合照吗?\u201d我一听这话,兴奋的马上说好!拍完后她站起身来:\u201c我根本不想相亲的,看了你我的合照,我想我爸妈肯定再不会哔我相亲了,今天就这样吧,这桌子菜买过单了,您慢吃,拜拜\u2026\u2026\u201d","hashId":"214f2f7654aa514fb03ec8458e637eb6","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"下班了,我却迟迟不敢回家,站在家门口,想着妻子殷切的眼神,更是犹豫不绝,听着妻子切菜的声音更是让我心胆俱碎,硬着头皮,壮着胆子,猛的推开门大声对着妻子喊到:\u201c老婆,今天中午太热了,我多花了一块钱!\u201d","hashId":"badc7667b754368eec4916464c77e0b7","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"今天去逛超市,突然有一个妹子朝我招手,大声对我叫道:\u201c帅哥帅哥,你过来一下!\u201d 我走过去问她有什么事?那妹子指着身旁的一袋米对我说:\u201c帅哥,我想让你帮我把这袋米扛到超市门口外面去\u2026\u2026\u201d我一时些犯犹豫,正想着要不要帮她这个忙? 那妹子见我没有立时答应,似乎很不爽,说:\u201c你怎么不知好歹啊?你知不知道,你其实长得一点都不帅,根本称不上什么帅哥!可我不还是叫你帅哥不是?可你却这么不通人情,叫你帮一下忙,还要犹犹豫豫的!\u2026\u2026\u201d我:\u2026\u2026","hashId":"fc840520cce36b157f0f8eef3f7d622b","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"去男友家,我跟男友在房间里玩儿,叔叔在厨房里做饭,不大会儿,听到叔叔喊\u201c宝贝儿,你最爱吃的红烧肉出锅了\u201d我跟男友说\u201c叔叔真可爱,你都这么大了,他还喊你宝贝儿\u201d男友白我一眼说\u201c你开门去看看\u201d 打开房门看到阿姨美滋滋的端着红烧肉从厨房出来了\u2026\u2026","hashId":"5031c25fe4d3a1b3bac9479ca3eaf15e","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"邻居有一熊孩子老爱用小石子在别人家车上乱刻,教育多少次了就是不听。那天又淘气了不是,人家又找他老爸告状去了,他老爸各种赔不是,等那人走了马上就火了,一巴掌就甩过去:狗日的,给老子出来,以后再给人家车上乱搞老子不抽死你,你说你刻就刻吧,你每次都刻个老子名字是什么意思?","hashId":"74cb1bcd3ed7822cb98398991f238412","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"},{"content":"几个男人在一起谈论自己家的母老虎。这时一个男人道:\u201c难道你们就没有当家做主的时候?\u201d其他男人不约而同反问:\u201c难道你有?\u201d男人:\u201c我当然有啊,我老婆买衣服就必须征得我同意。\u201d其他男人:\u201c为什么?\u201d男人:\u201c因为她要是买浅色衣服,我是洗不干净的。\u201d","hashId":"f99188b17774312e2a5cf38973eb42e5","unixtime":1530251700,"updatetime":"2018-06-29 13:55:00"}]} * error_code : 0 */ private String reason; private ResultBean result; private int error_code; public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public static class ResultBean { private List<DataBean> data; public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { /** * con <SUF>*/ private String content; private String hashId; private int unixtime; private String updatetime; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getHashId() { return hashId; } public void setHashId(String hashId) { this.hashId = hashId; } public int getUnixtime() { return unixtime; } public void setUnixtime(int unixtime) { this.unixtime = unixtime; } public String getUpdatetime() { return updatetime; } public void setUpdatetime(String updatetime) { this.updatetime = updatetime; } } } }
false
2,448
169
3,006
211
2,593
166
3,006
211
3,814
269
false
false
false
false
false
true
36645_1
import javax.swing.*; import java.awt.*; // 颜色选择列表 public class Colorlist extends JPanel { static final long serialVersionUID = 1471001741; public Colorlist() { // 得到监听器实例 EventListener el = EventListener.getInstance(); // 为列表使用二行四列的栅格布局 this.setLayout(new GridLayout(2, 4, 2, 2)); // 通过颜色数组快速构建前七个按钮 Color[] colorArray = { Color.BLACK, Color.BLUE, Color.YELLOW, Color.GREEN, Color.PINK, Color.RED, Color.CYAN }; for (Color item : colorArray) { JButton tmp = new JButton(); tmp.setBackground(item); // 为该按钮添加点击监听,详见EventListener->actionPerformed tmp.addActionListener(el); this.add(tmp); } // 最后一个按钮是自定义颜色 JButton customColor = new JButton(); customColor.setBackground(Color.WHITE); // 为该按钮加入与其它按钮相同的监听 customColor.addActionListener(el); // 点击弹出颜色对话框,将选中颜色设置为背景色 // 注意:经过测试,多个ActionListener的情况下会优先执行后添加的 customColor.addActionListener(e -> { Color selectedColor = JColorChooser.showDialog(null, "自定义颜色", Color.BLACK); if (selectedColor == null) { selectedColor = Color.WHITE; } customColor.setBackground(selectedColor); }); this.add(customColor); } }
amtoaer/java-drawing-board
src/Colorlist.java
362
// 得到监听器实例
line_comment
zh-cn
import javax.swing.*; import java.awt.*; // 颜色选择列表 public class Colorlist extends JPanel { static final long serialVersionUID = 1471001741; public Colorlist() { // 得到 <SUF> EventListener el = EventListener.getInstance(); // 为列表使用二行四列的栅格布局 this.setLayout(new GridLayout(2, 4, 2, 2)); // 通过颜色数组快速构建前七个按钮 Color[] colorArray = { Color.BLACK, Color.BLUE, Color.YELLOW, Color.GREEN, Color.PINK, Color.RED, Color.CYAN }; for (Color item : colorArray) { JButton tmp = new JButton(); tmp.setBackground(item); // 为该按钮添加点击监听,详见EventListener->actionPerformed tmp.addActionListener(el); this.add(tmp); } // 最后一个按钮是自定义颜色 JButton customColor = new JButton(); customColor.setBackground(Color.WHITE); // 为该按钮加入与其它按钮相同的监听 customColor.addActionListener(el); // 点击弹出颜色对话框,将选中颜色设置为背景色 // 注意:经过测试,多个ActionListener的情况下会优先执行后添加的 customColor.addActionListener(e -> { Color selectedColor = JColorChooser.showDialog(null, "自定义颜色", Color.BLACK); if (selectedColor == null) { selectedColor = Color.WHITE; } customColor.setBackground(selectedColor); }); this.add(customColor); } }
false
336
7
362
6
378
5
362
6
535
13
false
false
false
false
false
true
29149_2
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * 在线性时间内抽取主题类(新闻、博客等)网页的正文。 * 采用了<b>基于行块分布函数</b>的方法,为保持通用性没有针对特定网站编写规则。 * </p> * @author Chen Xin(xchen@ir.hit.edu.cn) * Created on 2009-1-11 * Updated on 2010-08-09 */ public class TextExtract { private List<String> lines; private final static int blocksWidth=3; private int threshold; private String html; private boolean flag; private int start; private int end; private StringBuilder text; private ArrayList<Integer> indexDistribution; public TextExtract() { lines = new ArrayList<String>(); indexDistribution = new ArrayList<Integer>(); text = new StringBuilder(); flag = false; /* 当待抽取的网页正文中遇到成块的新闻标题未剔除时,只要增大此阈值即可。*/ /* 阈值增大,准确率提升,召回率下降;值变小,噪声会大,但可以保证抽到只有一句话的正文 */ threshold = -1; } /** * 抽取网页正文,不判断该网页是否是目录型。即已知传入的肯定是可以抽取正文的主题类网页。 * * @param _html 网页HTML字符串 * * @return 网页正文string */ public String parse(String _html) { return parse(_html, false); } /** * 判断传入HTML,若是主题类网页,则抽取正文;否则输出<b>"unkown"</b>。 * * @param _html 网页HTML字符串 * @param _flag true进行主题类判断, 省略此参数则默认为false * * @return 网页正文string */ public String parse(String _html, boolean _flag) { flag = _flag; html = _html; html = preProcess(html); // System.out.println(html); return getText(); } private static int FREQUENT_URL = 30; private static Pattern links = Pattern.compile("<[aA]\\s+[Hh][Rr][Ee][Ff]=[\"|\']?([^>\"\' ]+)[\"|\']?\\s*[^>]*>([^>]+)</a>(\\s*.{0,"+FREQUENT_URL+"}\\s*<a\\s+href=[\"|\']?([^>\"\' ]+)[\"|\']?\\s*[^>]*>([^>]+)</[aA]>){2,100}", Pattern.DOTALL); private static String preProcess(String source) { source = source.replaceAll("(?is)<!DOCTYPE.*?>", ""); source = source.replaceAll("(?is)<!--.*?-->", ""); // remove html comment source = source.replaceAll("(?is)<script.*?>.*?</script>", ""); // remove javascript source = source.replaceAll("(?is)<style.*?>.*?</style>", ""); // remove css source = source.replaceAll("&.{2,5};|&#.{2,5};", " "); // remove special char //剔除连续成片的超链接文本(认为是,广告或噪音),超链接多藏于span中 source = source.replaceAll("<[sS][pP][aA][nN].*?>", ""); source = source.replaceAll("</[sS][pP][aA][nN]>", ""); int len = source.length(); while ((source = links.matcher(source).replaceAll("")).length() != len) { len = source.length(); } ;//continue; //source = links.matcher(source).replaceAll(""); //防止html中在<>中包括大于号的判断 source = source.replaceAll("<[^>'\"]*['\"].*['\"].*?>", ""); source = source.replaceAll("<.*?>", ""); source = source.replaceAll("<.*?>", ""); source = source.replaceAll("\r\n", "\n"); return source; } private String getText() { lines = Arrays.asList(html.split("\n")); indexDistribution.clear(); int empty = 0;//空行的数量 for (int i = 0; i < lines.size() - blocksWidth; i++) { if (lines.get(i).length() == 0) { empty++; } int wordsNum = 0; for (int j = i; j < i + blocksWidth; j++) { lines.set(j, lines.get(j).replaceAll("\\s+", "")); wordsNum += lines.get(j).length(); } indexDistribution.add(wordsNum); //System.out.println(wordsNum); } int sum = 0; for (int i=0; i< indexDistribution.size(); i++) { sum += indexDistribution.get(i); } threshold = Math.min(100, (sum/indexDistribution.size())<<(empty/(lines.size()-empty)>>>1)); threshold = Math.max(50, threshold); start = -1; end = -1; boolean boolstart = false, boolend = false; boolean firstMatch = true;//前面的标题块往往比较小,应该减小与它匹配的阈值 text.setLength(0); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < indexDistribution.size() - 1; i++) { if(firstMatch && ! boolstart) { if (indexDistribution.get(i) > (threshold/2) && ! boolstart) { if (indexDistribution.get(i+1).intValue() != 0 || indexDistribution.get(i+2).intValue() != 0) { firstMatch = false; boolstart = true; start = i; continue; } } } if (indexDistribution.get(i) > threshold && ! boolstart) { if (indexDistribution.get(i+1).intValue() != 0 || indexDistribution.get(i+2).intValue() != 0 || indexDistribution.get(i+3).intValue() != 0) { boolstart = true; start = i; continue; } } if (boolstart) { if (indexDistribution.get(i).intValue() == 0 || indexDistribution.get(i+1).intValue() == 0) { end = i; boolend = true; } } if (boolend) { buffer.setLength(0); //System.out.println(start+1 + "\t\t" + end+1); for (int ii = start; ii <= end; ii++) { if (lines.get(ii).length() < 5) continue; buffer.append(lines.get(ii) + "\n"); } String str = buffer.toString(); //System.out.println(str); if (str.contains("Copyright") || str.contains("版权所有") ) continue; text.append(str); boolstart = boolend = false; } } if (start > end) { buffer.setLength(0); int size_1 = lines.size()-1; for (int ii = start; ii <= size_1; ii++) { if (lines.get(ii).length() < 5) continue; buffer.append(lines.get(ii) + "\n"); } String str = buffer.toString(); //System.out.println(str); if ((!str.contains("Copyright")) || (!str.contains("版权所有")) ) { text.append(str); } } return text.toString(); } public static void main(String[] args) { System.out.println("==============="); String s = "<img class='fit-image' onload='javascript:if(this.width>498)this.width=498;' />hello"; //source = source.replaceAll("<[^'\"]*['\"].*['\"].*?>", ""); System.out.println(TextExtract.preProcess(s)); } }
amumu-dev/cx-extractor
src/Java/TextExtract.java
2,146
/* 阈值增大,准确率提升,召回率下降;值变小,噪声会大,但可以保证抽到只有一句话的正文 */
block_comment
zh-cn
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * 在线性时间内抽取主题类(新闻、博客等)网页的正文。 * 采用了<b>基于行块分布函数</b>的方法,为保持通用性没有针对特定网站编写规则。 * </p> * @author Chen Xin(xchen@ir.hit.edu.cn) * Created on 2009-1-11 * Updated on 2010-08-09 */ public class TextExtract { private List<String> lines; private final static int blocksWidth=3; private int threshold; private String html; private boolean flag; private int start; private int end; private StringBuilder text; private ArrayList<Integer> indexDistribution; public TextExtract() { lines = new ArrayList<String>(); indexDistribution = new ArrayList<Integer>(); text = new StringBuilder(); flag = false; /* 当待抽取的网页正文中遇到成块的新闻标题未剔除时,只要增大此阈值即可。*/ /* 阈值增 <SUF>*/ threshold = -1; } /** * 抽取网页正文,不判断该网页是否是目录型。即已知传入的肯定是可以抽取正文的主题类网页。 * * @param _html 网页HTML字符串 * * @return 网页正文string */ public String parse(String _html) { return parse(_html, false); } /** * 判断传入HTML,若是主题类网页,则抽取正文;否则输出<b>"unkown"</b>。 * * @param _html 网页HTML字符串 * @param _flag true进行主题类判断, 省略此参数则默认为false * * @return 网页正文string */ public String parse(String _html, boolean _flag) { flag = _flag; html = _html; html = preProcess(html); // System.out.println(html); return getText(); } private static int FREQUENT_URL = 30; private static Pattern links = Pattern.compile("<[aA]\\s+[Hh][Rr][Ee][Ff]=[\"|\']?([^>\"\' ]+)[\"|\']?\\s*[^>]*>([^>]+)</a>(\\s*.{0,"+FREQUENT_URL+"}\\s*<a\\s+href=[\"|\']?([^>\"\' ]+)[\"|\']?\\s*[^>]*>([^>]+)</[aA]>){2,100}", Pattern.DOTALL); private static String preProcess(String source) { source = source.replaceAll("(?is)<!DOCTYPE.*?>", ""); source = source.replaceAll("(?is)<!--.*?-->", ""); // remove html comment source = source.replaceAll("(?is)<script.*?>.*?</script>", ""); // remove javascript source = source.replaceAll("(?is)<style.*?>.*?</style>", ""); // remove css source = source.replaceAll("&.{2,5};|&#.{2,5};", " "); // remove special char //剔除连续成片的超链接文本(认为是,广告或噪音),超链接多藏于span中 source = source.replaceAll("<[sS][pP][aA][nN].*?>", ""); source = source.replaceAll("</[sS][pP][aA][nN]>", ""); int len = source.length(); while ((source = links.matcher(source).replaceAll("")).length() != len) { len = source.length(); } ;//continue; //source = links.matcher(source).replaceAll(""); //防止html中在<>中包括大于号的判断 source = source.replaceAll("<[^>'\"]*['\"].*['\"].*?>", ""); source = source.replaceAll("<.*?>", ""); source = source.replaceAll("<.*?>", ""); source = source.replaceAll("\r\n", "\n"); return source; } private String getText() { lines = Arrays.asList(html.split("\n")); indexDistribution.clear(); int empty = 0;//空行的数量 for (int i = 0; i < lines.size() - blocksWidth; i++) { if (lines.get(i).length() == 0) { empty++; } int wordsNum = 0; for (int j = i; j < i + blocksWidth; j++) { lines.set(j, lines.get(j).replaceAll("\\s+", "")); wordsNum += lines.get(j).length(); } indexDistribution.add(wordsNum); //System.out.println(wordsNum); } int sum = 0; for (int i=0; i< indexDistribution.size(); i++) { sum += indexDistribution.get(i); } threshold = Math.min(100, (sum/indexDistribution.size())<<(empty/(lines.size()-empty)>>>1)); threshold = Math.max(50, threshold); start = -1; end = -1; boolean boolstart = false, boolend = false; boolean firstMatch = true;//前面的标题块往往比较小,应该减小与它匹配的阈值 text.setLength(0); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < indexDistribution.size() - 1; i++) { if(firstMatch && ! boolstart) { if (indexDistribution.get(i) > (threshold/2) && ! boolstart) { if (indexDistribution.get(i+1).intValue() != 0 || indexDistribution.get(i+2).intValue() != 0) { firstMatch = false; boolstart = true; start = i; continue; } } } if (indexDistribution.get(i) > threshold && ! boolstart) { if (indexDistribution.get(i+1).intValue() != 0 || indexDistribution.get(i+2).intValue() != 0 || indexDistribution.get(i+3).intValue() != 0) { boolstart = true; start = i; continue; } } if (boolstart) { if (indexDistribution.get(i).intValue() == 0 || indexDistribution.get(i+1).intValue() == 0) { end = i; boolend = true; } } if (boolend) { buffer.setLength(0); //System.out.println(start+1 + "\t\t" + end+1); for (int ii = start; ii <= end; ii++) { if (lines.get(ii).length() < 5) continue; buffer.append(lines.get(ii) + "\n"); } String str = buffer.toString(); //System.out.println(str); if (str.contains("Copyright") || str.contains("版权所有") ) continue; text.append(str); boolstart = boolend = false; } } if (start > end) { buffer.setLength(0); int size_1 = lines.size()-1; for (int ii = start; ii <= size_1; ii++) { if (lines.get(ii).length() < 5) continue; buffer.append(lines.get(ii) + "\n"); } String str = buffer.toString(); //System.out.println(str); if ((!str.contains("Copyright")) || (!str.contains("版权所有")) ) { text.append(str); } } return text.toString(); } public static void main(String[] args) { System.out.println("==============="); String s = "<img class='fit-image' onload='javascript:if(this.width>498)this.width=498;' />hello"; //source = source.replaceAll("<[^'\"]*['\"].*['\"].*?>", ""); System.out.println(TextExtract.preProcess(s)); } }
false
1,848
34
2,131
44
2,126
35
2,131
44
2,747
72
false
false
false
false
false
true
33342_0
/* * @lc app=leetcode.cn id=150 lang=java * * [150] 逆波兰表达式求值 * * https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/description/ * * algorithms * Medium (50.11%) * Likes: 154 * Dislikes: 0 * Total Accepted: 43.2K * Total Submissions: 85.9K * Testcase Example: '["2","1","+","3","*"]' * * 根据 逆波兰表示法,求表达式的值。 * * 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 * * * * 说明: * * * 整数除法只保留整数部分。 * 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。 * * * * * 示例 1: * * 输入: ["2", "1", "+", "3", "*"] * 输出: 9 * 解释: 该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9 * * * 示例 2: * * 输入: ["4", "13", "5", "/", "+"] * 输出: 6 * 解释: 该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6 * * * 示例 3: * * 输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] * 输出: 22 * 解释: * 该算式转化为常见的中缀算术表达式为: * ⁠ ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 * = ((10 * (6 / (12 * -11))) + 17) + 5 * = ((10 * (6 / -132)) + 17) + 5 * = ((10 * 0) + 17) + 5 * = (0 + 17) + 5 * = 17 + 5 * = 22 * * * * 逆波兰表达式: * * 逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。 * * * 平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。 * 该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。 * * * 逆波兰表达式主要有以下两个优点: * * * 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。 * 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。 * * */ // @lc code=start class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<>(); for (String token : tokens) { if ("+-*/".contains(token)) { int right = stack.pop(); int left = stack.pop(); if ("+".equals(token)) { stack.push(left + right); } else if ("-".equals(token)) { stack.push(left - right); } else if ("*".equals(token)) { stack.push(left * right); } else if ("/".equals(token)) { stack.push(left / right); } } else { stack.push(Integer.valueOf(token)); } } return stack.pop(); } } // @lc code=end
andavid/leetcode-java
zh/150.逆波兰表达式求值.java
1,024
/* * @lc app=leetcode.cn id=150 lang=java * * [150] 逆波兰表达式求值 * * https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/description/ * * algorithms * Medium (50.11%) * Likes: 154 * Dislikes: 0 * Total Accepted: 43.2K * Total Submissions: 85.9K * Testcase Example: '["2","1","+","3","*"]' * * 根据 逆波兰表示法,求表达式的值。 * * 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 * * * * 说明: * * * 整数除法只保留整数部分。 * 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。 * * * * * 示例 1: * * 输入: ["2", "1", "+", "3", "*"] * 输出: 9 * 解释: 该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9 * * * 示例 2: * * 输入: ["4", "13", "5", "/", "+"] * 输出: 6 * 解释: 该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6 * * * 示例 3: * * 输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] * 输出: 22 * 解释: * 该算式转化为常见的中缀算术表达式为: * ⁠ ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 * = ((10 * (6 / (12 * -11))) + 17) + 5 * = ((10 * (6 / -132)) + 17) + 5 * = ((10 * 0) + 17) + 5 * = (0 + 17) + 5 * = 17 + 5 * = 22 * * * * 逆波兰表达式: * * 逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。 * * * 平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。 * 该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。 * * * 逆波兰表达式主要有以下两个优点: * * * 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。 * 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。 * * */
block_comment
zh-cn
/* * @lc <SUF>*/ // @lc code=start class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<>(); for (String token : tokens) { if ("+-*/".contains(token)) { int right = stack.pop(); int left = stack.pop(); if ("+".equals(token)) { stack.push(left + right); } else if ("-".equals(token)) { stack.push(left - right); } else if ("*".equals(token)) { stack.push(left * right); } else if ("/".equals(token)) { stack.push(left / right); } } else { stack.push(Integer.valueOf(token)); } } return stack.pop(); } } // @lc code=end
false
893
733
1,024
834
976
766
1,024
834
1,265
1,049
true
true
true
true
true
false
13750_16
package com.example; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; public class MyGreenDAOGenerator { public static void main(String[] args) throws Exception { // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。 // 两个参数分别代表:数据库版本号与自动生成代码的包路径。 Schema schema = new Schema(1, "org.zarroboogs.maps.beans"); schema.setDefaultJavaPackageDao("org.zarroboogs.maps.dao"); //当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示: //Schema schema = new Schema(1, "me.itangqi.bean"); //schema.setDefaultJavaPackageDao("me.itangqi.dao"); // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。 // schema2.enableActiveEntitiesByDefault(); // schema2.enableKeepSectionsByDefault(); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addCameraTable(schema); addPoiSearchTipTable(schema); // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录(既之前创建的 java-gen)。 // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。 new DaoGenerator().generateAll(schema, "app/src/main/java-gen"); } private static void addCameraTable(Schema schema) { // 一个实体(类)就关联到数据库中的一张表,此处表名为「Note」(既类名) Entity camera = schema.addEntity("BJCamera"); // 你也可以重新给表命名 // note.setTableName("NODE"); // greenDAO 会自动根据实体类的属性值来创建表字段,并赋予默认值 // 接下来你便可以设置表中的字段: // 与在 Java 中使用驼峰命名法不同,默认数据库中的命名是使用大写和下划线来分割单词的。 // For example, a property called “creationDate” will become a database column “CREATION_DATE”. camera.addIdProperty().autoincrement(); camera.addStringProperty("name").notNull(); camera.addStringProperty("address"); camera.addDoubleProperty("latitude"); camera.addDoubleProperty("longtitude"); camera.addStringProperty("direction"); } private static void addPoiSearchTipTable(Schema schema){ Entity tip = schema.addEntity("PoiSearchTip"); tip.addStringProperty("name"); tip.addStringProperty("district"); tip.addStringProperty("adcode"); } }
andforce/Maps
greendaogenerator/src/main/java/com/example/MyGreenDAOGenerator.java
697
// 与在 Java 中使用驼峰命名法不同,默认数据库中的命名是使用大写和下划线来分割单词的。
line_comment
zh-cn
package com.example; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Schema; public class MyGreenDAOGenerator { public static void main(String[] args) throws Exception { // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。 // 两个参数分别代表:数据库版本号与自动生成代码的包路径。 Schema schema = new Schema(1, "org.zarroboogs.maps.beans"); schema.setDefaultJavaPackageDao("org.zarroboogs.maps.dao"); //当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示: //Schema schema = new Schema(1, "me.itangqi.bean"); //schema.setDefaultJavaPackageDao("me.itangqi.dao"); // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。 // schema2.enableActiveEntitiesByDefault(); // schema2.enableKeepSectionsByDefault(); // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。 addCameraTable(schema); addPoiSearchTipTable(schema); // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录(既之前创建的 java-gen)。 // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。 new DaoGenerator().generateAll(schema, "app/src/main/java-gen"); } private static void addCameraTable(Schema schema) { // 一个实体(类)就关联到数据库中的一张表,此处表名为「Note」(既类名) Entity camera = schema.addEntity("BJCamera"); // 你也可以重新给表命名 // note.setTableName("NODE"); // greenDAO 会自动根据实体类的属性值来创建表字段,并赋予默认值 // 接下来你便可以设置表中的字段: // 与在 <SUF> // For example, a property called “creationDate” will become a database column “CREATION_DATE”. camera.addIdProperty().autoincrement(); camera.addStringProperty("name").notNull(); camera.addStringProperty("address"); camera.addDoubleProperty("latitude"); camera.addDoubleProperty("longtitude"); camera.addStringProperty("direction"); } private static void addPoiSearchTipTable(Schema schema){ Entity tip = schema.addEntity("PoiSearchTip"); tip.addStringProperty("name"); tip.addStringProperty("district"); tip.addStringProperty("adcode"); } }
false
625
29
697
34
683
29
697
34
954
52
false
false
false
false
false
true
34754_32
package com.andieguo.poi.util; import java.io.File; import java.io.FileInputStream; import java.util.List; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONObject; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.andieguo.poi.dao.CityDao; import com.andieguo.poi.dao.POIDao; import com.andieguo.poi.pojo.POI; public class RestDownload { private Logger logger; private static volatile int count = 0;//线程安全 public RestDownload() throws Exception{ //从类路径下加载配置文件 PropertyConfigurator.configure(this.getClass().getClassLoader().getResourceAsStream("log4j/log4j.properties")); logger = Logger.getLogger(RestDownload.class); } @SuppressWarnings("resource") public static void main(String[] args) { try { RestDownload restDownload = new RestDownload(); ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); POIDao poiDao = (POIDao) context.getBean("poiDao"); CityDao cityDao = (CityDao) context.getBean("cityDao"); restDownload.executeJob(poiDao,cityDao); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized int downPage(POI poi,String city,Integer page) throws Exception { int sum = 0; String query = poi.getPoikey(); String type = poi.getPoivalue(); String result = Rest.poiRest(query, 20, page, city); JSONObject resultJSON = new JSONObject(result);//JSON格式化 String message = resultJSON.getString("message"); if(message.equals("ok") ){//获取数据成功 int total = resultJSON.getInt("total"); if(total > 0){ sum = total/20 + 1; File dataMkdir = new File(Constants.DATAPATH); if(!dataMkdir.exists()){ dataMkdir.mkdir(); } File cityMkdir = new File(dataMkdir.getPath()+File.separator+city); if(!cityMkdir.exists()){ cityMkdir.mkdir(); } File typeMkdir = new File(cityMkdir.getPath()+File.separator+type); if(!typeMkdir.exists()){ typeMkdir.mkdir(); } //保存到文本 File file = new File(typeMkdir.getPath()+File.separator+city+"-"+type+"-"+page+".json"); if(!file.exists()){ FileUtil.saveJSON(resultJSON.toString().getBytes(), file.getPath()); logger.info("成功下载:"+file.getPath()); }else{ logger.info("文件已存在:"+file.getPath()); } } }else{ count ++ ; logger.info("---------------------------------->拒绝访问:"+count); if(count > 100) System.exit(0); } return sum; } public class SkipRunnable implements Runnable{ public Exchanger<Integer> exchanger; public CountDownLatch downLatch; public int num; public SkipRunnable(CountDownLatch downLatch,Exchanger<Integer> exchanger,int num){ this.exchanger = exchanger; this.downLatch = downLatch; this.num = num; } @Override public void run() { // TODO Auto-generated method stub try { downLatch.countDown();// 计数减少1 exchanger.exchange(num);// 与主线程交换信息 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class QueryRunnable implements Runnable{ public Properties properties; public CountDownLatch downLatch; public CountDownLatch cityDownLatch; public Exchanger<Integer> exchanger; public POI poi; public String city; public QueryRunnable(Properties properties,POI poi,String city,CountDownLatch downLatch,CountDownLatch cityDownLatch,Exchanger<Integer> exchanger){ this.properties = properties; this.poi = poi; this.downLatch = downLatch; this.cityDownLatch = cityDownLatch; this.exchanger = exchanger; this.city = city; } @Override public void run() { // TODO Auto-generated method stub try { if(properties.getProperty(city+"&"+poi.getPoivalue()) == null){//城市配置文件中不存在记录 int sum = downPage(poi,city, 0); if(sum >= 1){ for (int i = 1; i < sum; i++) { downPage(poi,city, i); } logger.info(city+"--->"+poi.getPoivalue()+"-->下载结束"); properties.setProperty(city+"&"+poi.getPoivalue(), "done"); }else{ logger.info(city+"--->"+poi.getPoivalue()+"-->下载失败"); } }else{ logger.info(city+"--->"+poi.getPoivalue()+"-->已经下载"); } exchanger.exchange(1);// 与主线程交换信息 cityDownLatch.countDown(); downLatch.countDown();// 计数减少1 } catch (Exception e) { e.printStackTrace(); logger.error("",e); } } } public class CityJobRunable implements Runnable{ public String city; public Properties properties; public Properties globalProperties; public File globalFile; public File file; public CountDownLatch downLatch; public ExecutorService service; public CityJobRunable(String city,CountDownLatch downLatch,Properties globalProperties,File globalFile,Properties properties,File file,ExecutorService service){ this.city = city; this.downLatch = downLatch; this.globalProperties = globalProperties; this.globalFile = globalFile; this.properties = properties; this.file = file; this.service = service; } @Override public void run() { // TODO Auto-generated method stub try { logger.info(city+"--->在等待所有的爬取Baidu POI线程执行完毕!"); this.downLatch.await(); PropertiesUtil.store(properties,file); globalProperties.setProperty(city, "done");//记录断点 PropertiesUtil.store(globalProperties, globalFile); logger.info(city+"--->保存记录点到日志文件!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class FinnishJobRunable implements Runnable{ public CountDownLatch downLatch; public FinnishJobRunable(CountDownLatch downLatch){ this.downLatch = downLatch; } @Override public void run() { // TODO Auto-generated method stub try { logger.info("FinnishJobRunable在等待所有的读历史数据线程执行完毕!"); this.downLatch.await(); logger.info("FinnishJobRunable释放连接资源!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void executeJob(POIDao poiDao,CityDao cityDao){ try{ ExecutorService service = Executors.newSingleThreadExecutor(); //创建线程池:区别newSingleThreadExecutor与newCachedThreadPool Exchanger<Integer> exchanger = new Exchanger<Integer>();//子线程与主线程交换数据 List<POI> poiList = poiDao.findByType(0); List<String> cityList = cityDao.findAll(); int sum = poiList.size()*cityList.size(); CountDownLatch downLatch = new CountDownLatch(sum); CountDownLatch cityDownLatch = new CountDownLatch(poiList.size()); //创建家目录文件夹 File home = new File(Constants.MKDIRPATH); if(!home.exists()) home.mkdirs(); //在家目录生成全局配置文件 File globalFile = new File(Constants.MKDIRPATH + File.separator+"local_update_global.properties"); if(!globalFile.exists()) globalFile.createNewFile(); Properties globalProperties = PropertiesUtil.loadFromInputStream(new FileInputStream(globalFile)); for(String city:cityList){ if(globalProperties.getProperty(city, null) == null){//值为NULL则继续,值为done则跳过 //在家目录生成城市配置文件 File file = new File(Constants.MKDIRPATH + File.separator+"local_update_"+city+".properties"); if(!file.exists()) file.createNewFile(); Properties properties = PropertiesUtil.loadFromInputStream(new FileInputStream(file)); for (POI poi : poiList) { QueryRunnable queryRunnable = new QueryRunnable(properties,poi,city,downLatch,cityDownLatch,exchanger); service.execute(queryRunnable);// 为线程池添加任务 } //每次遍历完一次城市都要执行CityJobRunable CityJobRunable cityJobRunable = new CityJobRunable(city,cityDownLatch,globalProperties,globalFile,properties,file,service); service.execute(cityJobRunable); }else{//执行skip线程,将任务数减(1*poiList.size())个,其中countdown是没有处理的 SkipRunnable skipRunnable = new SkipRunnable(downLatch, exchanger, poiList.size()); service.execute(skipRunnable); } } FinnishJobRunable finnishJobRunable = new FinnishJobRunable(downLatch); service.execute(finnishJobRunable);// 为线程池添加任务 //主线程交换数据 Integer totalResult = Integer.valueOf(0); for(int i=0;i<sum;i++){ //当主线程调用Exchange对象的exchange()方法后,他会陷入阻塞状态 //直到queryRunnable线程也调用了exchange()方法,然后以线程安全的方式交换数据,之后主线程继续运行 Integer partialResult = exchanger.exchange(Integer.valueOf(0)); if (partialResult != 0) { totalResult = totalResult + partialResult; //更新进度条 logger.info(String.format("Progress: %s/%s",totalResult, sum)); } } service.shutdown();//关闭线程池 }catch(Exception e){ e.printStackTrace(); logger.error("",e); } } }
andieguo/poi-parent
poi-local/src/main/java/com/andieguo/poi/util/RestDownload.java
2,711
//更新进度条
line_comment
zh-cn
package com.andieguo.poi.util; import java.io.File; import java.io.FileInputStream; import java.util.List; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.json.JSONObject; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.andieguo.poi.dao.CityDao; import com.andieguo.poi.dao.POIDao; import com.andieguo.poi.pojo.POI; public class RestDownload { private Logger logger; private static volatile int count = 0;//线程安全 public RestDownload() throws Exception{ //从类路径下加载配置文件 PropertyConfigurator.configure(this.getClass().getClassLoader().getResourceAsStream("log4j/log4j.properties")); logger = Logger.getLogger(RestDownload.class); } @SuppressWarnings("resource") public static void main(String[] args) { try { RestDownload restDownload = new RestDownload(); ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); POIDao poiDao = (POIDao) context.getBean("poiDao"); CityDao cityDao = (CityDao) context.getBean("cityDao"); restDownload.executeJob(poiDao,cityDao); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized int downPage(POI poi,String city,Integer page) throws Exception { int sum = 0; String query = poi.getPoikey(); String type = poi.getPoivalue(); String result = Rest.poiRest(query, 20, page, city); JSONObject resultJSON = new JSONObject(result);//JSON格式化 String message = resultJSON.getString("message"); if(message.equals("ok") ){//获取数据成功 int total = resultJSON.getInt("total"); if(total > 0){ sum = total/20 + 1; File dataMkdir = new File(Constants.DATAPATH); if(!dataMkdir.exists()){ dataMkdir.mkdir(); } File cityMkdir = new File(dataMkdir.getPath()+File.separator+city); if(!cityMkdir.exists()){ cityMkdir.mkdir(); } File typeMkdir = new File(cityMkdir.getPath()+File.separator+type); if(!typeMkdir.exists()){ typeMkdir.mkdir(); } //保存到文本 File file = new File(typeMkdir.getPath()+File.separator+city+"-"+type+"-"+page+".json"); if(!file.exists()){ FileUtil.saveJSON(resultJSON.toString().getBytes(), file.getPath()); logger.info("成功下载:"+file.getPath()); }else{ logger.info("文件已存在:"+file.getPath()); } } }else{ count ++ ; logger.info("---------------------------------->拒绝访问:"+count); if(count > 100) System.exit(0); } return sum; } public class SkipRunnable implements Runnable{ public Exchanger<Integer> exchanger; public CountDownLatch downLatch; public int num; public SkipRunnable(CountDownLatch downLatch,Exchanger<Integer> exchanger,int num){ this.exchanger = exchanger; this.downLatch = downLatch; this.num = num; } @Override public void run() { // TODO Auto-generated method stub try { downLatch.countDown();// 计数减少1 exchanger.exchange(num);// 与主线程交换信息 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class QueryRunnable implements Runnable{ public Properties properties; public CountDownLatch downLatch; public CountDownLatch cityDownLatch; public Exchanger<Integer> exchanger; public POI poi; public String city; public QueryRunnable(Properties properties,POI poi,String city,CountDownLatch downLatch,CountDownLatch cityDownLatch,Exchanger<Integer> exchanger){ this.properties = properties; this.poi = poi; this.downLatch = downLatch; this.cityDownLatch = cityDownLatch; this.exchanger = exchanger; this.city = city; } @Override public void run() { // TODO Auto-generated method stub try { if(properties.getProperty(city+"&"+poi.getPoivalue()) == null){//城市配置文件中不存在记录 int sum = downPage(poi,city, 0); if(sum >= 1){ for (int i = 1; i < sum; i++) { downPage(poi,city, i); } logger.info(city+"--->"+poi.getPoivalue()+"-->下载结束"); properties.setProperty(city+"&"+poi.getPoivalue(), "done"); }else{ logger.info(city+"--->"+poi.getPoivalue()+"-->下载失败"); } }else{ logger.info(city+"--->"+poi.getPoivalue()+"-->已经下载"); } exchanger.exchange(1);// 与主线程交换信息 cityDownLatch.countDown(); downLatch.countDown();// 计数减少1 } catch (Exception e) { e.printStackTrace(); logger.error("",e); } } } public class CityJobRunable implements Runnable{ public String city; public Properties properties; public Properties globalProperties; public File globalFile; public File file; public CountDownLatch downLatch; public ExecutorService service; public CityJobRunable(String city,CountDownLatch downLatch,Properties globalProperties,File globalFile,Properties properties,File file,ExecutorService service){ this.city = city; this.downLatch = downLatch; this.globalProperties = globalProperties; this.globalFile = globalFile; this.properties = properties; this.file = file; this.service = service; } @Override public void run() { // TODO Auto-generated method stub try { logger.info(city+"--->在等待所有的爬取Baidu POI线程执行完毕!"); this.downLatch.await(); PropertiesUtil.store(properties,file); globalProperties.setProperty(city, "done");//记录断点 PropertiesUtil.store(globalProperties, globalFile); logger.info(city+"--->保存记录点到日志文件!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class FinnishJobRunable implements Runnable{ public CountDownLatch downLatch; public FinnishJobRunable(CountDownLatch downLatch){ this.downLatch = downLatch; } @Override public void run() { // TODO Auto-generated method stub try { logger.info("FinnishJobRunable在等待所有的读历史数据线程执行完毕!"); this.downLatch.await(); logger.info("FinnishJobRunable释放连接资源!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void executeJob(POIDao poiDao,CityDao cityDao){ try{ ExecutorService service = Executors.newSingleThreadExecutor(); //创建线程池:区别newSingleThreadExecutor与newCachedThreadPool Exchanger<Integer> exchanger = new Exchanger<Integer>();//子线程与主线程交换数据 List<POI> poiList = poiDao.findByType(0); List<String> cityList = cityDao.findAll(); int sum = poiList.size()*cityList.size(); CountDownLatch downLatch = new CountDownLatch(sum); CountDownLatch cityDownLatch = new CountDownLatch(poiList.size()); //创建家目录文件夹 File home = new File(Constants.MKDIRPATH); if(!home.exists()) home.mkdirs(); //在家目录生成全局配置文件 File globalFile = new File(Constants.MKDIRPATH + File.separator+"local_update_global.properties"); if(!globalFile.exists()) globalFile.createNewFile(); Properties globalProperties = PropertiesUtil.loadFromInputStream(new FileInputStream(globalFile)); for(String city:cityList){ if(globalProperties.getProperty(city, null) == null){//值为NULL则继续,值为done则跳过 //在家目录生成城市配置文件 File file = new File(Constants.MKDIRPATH + File.separator+"local_update_"+city+".properties"); if(!file.exists()) file.createNewFile(); Properties properties = PropertiesUtil.loadFromInputStream(new FileInputStream(file)); for (POI poi : poiList) { QueryRunnable queryRunnable = new QueryRunnable(properties,poi,city,downLatch,cityDownLatch,exchanger); service.execute(queryRunnable);// 为线程池添加任务 } //每次遍历完一次城市都要执行CityJobRunable CityJobRunable cityJobRunable = new CityJobRunable(city,cityDownLatch,globalProperties,globalFile,properties,file,service); service.execute(cityJobRunable); }else{//执行skip线程,将任务数减(1*poiList.size())个,其中countdown是没有处理的 SkipRunnable skipRunnable = new SkipRunnable(downLatch, exchanger, poiList.size()); service.execute(skipRunnable); } } FinnishJobRunable finnishJobRunable = new FinnishJobRunable(downLatch); service.execute(finnishJobRunable);// 为线程池添加任务 //主线程交换数据 Integer totalResult = Integer.valueOf(0); for(int i=0;i<sum;i++){ //当主线程调用Exchange对象的exchange()方法后,他会陷入阻塞状态 //直到queryRunnable线程也调用了exchange()方法,然后以线程安全的方式交换数据,之后主线程继续运行 Integer partialResult = exchanger.exchange(Integer.valueOf(0)); if (partialResult != 0) { totalResult = totalResult + partialResult; //更新 <SUF> logger.info(String.format("Progress: %s/%s",totalResult, sum)); } } service.shutdown();//关闭线程池 }catch(Exception e){ e.printStackTrace(); logger.error("",e); } } }
false
2,282
4
2,709
5
2,619
4
2,711
5
3,633
6
false
false
false
false
false
true
36419_7
package net.kaicong.ipcam.view; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.text.Editable; import android.text.Html; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import net.kaicong.ipcam.R; import net.kaicong.ipcam.utils.StringUtils; /** * Author: lu_qwen * Intro: * Time: 2015/3/24. */ public class PicCommentDialog extends Dialog { public static final int MAX_COUNT = 200; public static final int MODE_COMMENT = 1;//评论 public static final int MODE_REPLY = 2;//回复 public static final int MODE_DISMISS = 3;//取消 public static final int MODE_COMMENT_TEXT = 4;//纯文字评论 public static final int MODE_COMMENT_IMAGE = 5;//截图评论 private EditText commonEditText; protected ImageView commentImage; private TextView commonHide; private TextView commonCommit; private OnPicCommitListener onPicCommitListener; private onPreviewListener onPreviewListener; private int mode; private String username; private Context context; private CheckBox checkBox; private TextView inputTextNum; //回复的字符长度 private int re_Len = 0; private int position = 0; public PicCommentDialog(Context context, int style, OnPicCommitListener onCommitListener, onPreviewListener onPreviewListener) { super(context, style); this.onPicCommitListener = onCommitListener; this.onPreviewListener = onPreviewListener; this.context = context; init(context); } public void setPosition(int position) { this.position = position; } public void setMode(int mode, String username) { this.mode = mode; this.username = username; if (mode == MODE_COMMENT_IMAGE) { commentImage.setVisibility(View.VISIBLE); checkBox.setVisibility(View.VISIBLE); checkBox.setChecked(true); } else if (mode == MODE_COMMENT_TEXT) { commentImage.setVisibility(View.GONE); checkBox.setVisibility(View.INVISIBLE); } else if (mode == MODE_REPLY) { commentImage.setVisibility(View.GONE); checkBox.setVisibility(View.INVISIBLE); commonEditText.setText(Html.fromHtml(context.getString(R.string.see_world_reply_notice, username))); } } private void init(final Context context) { View convertView = LayoutInflater.from(context).inflate(R.layout.dialog_piccomment_edit_dialog, null); setContentView(convertView); commentImage = (ImageView) convertView.findViewById(R.id.picCommon_pic); commonEditText = (EditText) convertView.findViewById(R.id.picCommon_edittext); commonHide = (TextView) convertView.findViewById(R.id.picCommon_hide); commonCommit = (TextView) convertView.findViewById(R.id.picCommon_commit); checkBox = (CheckBox) convertView.findViewById(R.id.picCheckBox); inputTextNum = (TextView) convertView.findViewById(R.id.edit_text_input_num); checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { commentImage.setVisibility(View.VISIBLE); mode = MODE_COMMENT_IMAGE; } else { commentImage.setVisibility(View.GONE); mode = MODE_COMMENT_TEXT; } } }); commentImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onPreviewListener != null) { onPreviewListener.doPreview(); } } }); commonCommit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (StringUtils.isEmpty(commonEditText.getText().toString())) { Toast.makeText(context, context.getString(R.string.common_input_not_empty), Toast.LENGTH_LONG).show(); return; } else if (mode == MODE_REPLY) { if (commonEditText.getText().toString().length() <= re_Len) { Toast.makeText(context, context.getString(R.string.common_input_not_empty), Toast.LENGTH_LONG).show(); return; } } if (onPicCommitListener != null) { onPicCommitListener.onPicCommentCommit(mode, commonEditText.getText().toString(), position); } dismiss(); } }); commonHide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onPicCommitListener != null) { onPicCommitListener.onPicCommentCommit(MODE_DISMISS, "", position); } } }); commonEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { int editStart = commonEditText.getSelectionStart(); int editEnd = commonEditText.getSelectionEnd(); // 先去掉监听器,否则会出现栈溢出 commonEditText.removeTextChangedListener(this); // 注意这里只能每次都对整个EditText的内容求长度,不能对删除的单个字符求长度 // 因为是中英文混合,单个字符而言,calculateLength函数都会返回1 while (calculateLength(editable.toString()) > MAX_COUNT) { // 当输入字符个数超过限制的大小时,进行截断操作 editable.delete(editStart - 1, editEnd); editStart--; editEnd--; } // mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了,多谢@ainiyidiandian的提醒 commonEditText.setSelection(editStart); // 恢复监听器 commonEditText.addTextChangedListener(this); setLeftCount(); } }); commonEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL) { if (mode == MODE_REPLY && commonEditText.getText().toString().length() == re_Len) { return true; } } return false; } }); } /** * 计算分享内容的字数,一个汉字=两个英文字母,一个中文标点=两个英文标点 注意:该函数的不适用于对单个字符进行计算,因为单个字符四舍五入后都是1 * * @param c * @return */ private long calculateLength(CharSequence c) { double len = 0; for (int i = 0; i < c.length(); i++) { int tmp = (int) c.charAt(i); if (tmp > 0 && tmp < 127) { len += 0.5; } else { len++; } } return Math.round(len); } /** * 刷新剩余输入字数,最大值新浪微博是140个字,人人网是200个字 */ private void setLeftCount() { inputTextNum.setText(String.valueOf((MAX_COUNT - getInputCount()))); } /** * 获取用户输入的分享内容字数 * * @return */ private long getInputCount() { return calculateLength(commonEditText.getText().toString()); } public void setImage(Bitmap bitmap) { commentImage.setImageBitmap(bitmap); } public interface OnPicCommitListener { public void onPicCommentCommit(int mode, String editStr, int position); } public interface onPreviewListener { public void doPreview(); } public void clearText() { if (commonEditText != null) { commonEditText.setText(""); } } public void setCursorPosition(int index) { commonEditText.setSelection(index); re_Len = index; } @Override public void dismiss() { super.dismiss(); // if (commonEditText != null) { // commonEditText.setText(""); // } } }
andrchu/IpCam
IpCam/src/net/kaicong/ipcam/view/PicCommentDialog.java
2,027
// 当输入字符个数超过限制的大小时,进行截断操作
line_comment
zh-cn
package net.kaicong.ipcam.view; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.text.Editable; import android.text.Html; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import net.kaicong.ipcam.R; import net.kaicong.ipcam.utils.StringUtils; /** * Author: lu_qwen * Intro: * Time: 2015/3/24. */ public class PicCommentDialog extends Dialog { public static final int MAX_COUNT = 200; public static final int MODE_COMMENT = 1;//评论 public static final int MODE_REPLY = 2;//回复 public static final int MODE_DISMISS = 3;//取消 public static final int MODE_COMMENT_TEXT = 4;//纯文字评论 public static final int MODE_COMMENT_IMAGE = 5;//截图评论 private EditText commonEditText; protected ImageView commentImage; private TextView commonHide; private TextView commonCommit; private OnPicCommitListener onPicCommitListener; private onPreviewListener onPreviewListener; private int mode; private String username; private Context context; private CheckBox checkBox; private TextView inputTextNum; //回复的字符长度 private int re_Len = 0; private int position = 0; public PicCommentDialog(Context context, int style, OnPicCommitListener onCommitListener, onPreviewListener onPreviewListener) { super(context, style); this.onPicCommitListener = onCommitListener; this.onPreviewListener = onPreviewListener; this.context = context; init(context); } public void setPosition(int position) { this.position = position; } public void setMode(int mode, String username) { this.mode = mode; this.username = username; if (mode == MODE_COMMENT_IMAGE) { commentImage.setVisibility(View.VISIBLE); checkBox.setVisibility(View.VISIBLE); checkBox.setChecked(true); } else if (mode == MODE_COMMENT_TEXT) { commentImage.setVisibility(View.GONE); checkBox.setVisibility(View.INVISIBLE); } else if (mode == MODE_REPLY) { commentImage.setVisibility(View.GONE); checkBox.setVisibility(View.INVISIBLE); commonEditText.setText(Html.fromHtml(context.getString(R.string.see_world_reply_notice, username))); } } private void init(final Context context) { View convertView = LayoutInflater.from(context).inflate(R.layout.dialog_piccomment_edit_dialog, null); setContentView(convertView); commentImage = (ImageView) convertView.findViewById(R.id.picCommon_pic); commonEditText = (EditText) convertView.findViewById(R.id.picCommon_edittext); commonHide = (TextView) convertView.findViewById(R.id.picCommon_hide); commonCommit = (TextView) convertView.findViewById(R.id.picCommon_commit); checkBox = (CheckBox) convertView.findViewById(R.id.picCheckBox); inputTextNum = (TextView) convertView.findViewById(R.id.edit_text_input_num); checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { commentImage.setVisibility(View.VISIBLE); mode = MODE_COMMENT_IMAGE; } else { commentImage.setVisibility(View.GONE); mode = MODE_COMMENT_TEXT; } } }); commentImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onPreviewListener != null) { onPreviewListener.doPreview(); } } }); commonCommit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (StringUtils.isEmpty(commonEditText.getText().toString())) { Toast.makeText(context, context.getString(R.string.common_input_not_empty), Toast.LENGTH_LONG).show(); return; } else if (mode == MODE_REPLY) { if (commonEditText.getText().toString().length() <= re_Len) { Toast.makeText(context, context.getString(R.string.common_input_not_empty), Toast.LENGTH_LONG).show(); return; } } if (onPicCommitListener != null) { onPicCommitListener.onPicCommentCommit(mode, commonEditText.getText().toString(), position); } dismiss(); } }); commonHide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onPicCommitListener != null) { onPicCommitListener.onPicCommentCommit(MODE_DISMISS, "", position); } } }); commonEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { int editStart = commonEditText.getSelectionStart(); int editEnd = commonEditText.getSelectionEnd(); // 先去掉监听器,否则会出现栈溢出 commonEditText.removeTextChangedListener(this); // 注意这里只能每次都对整个EditText的内容求长度,不能对删除的单个字符求长度 // 因为是中英文混合,单个字符而言,calculateLength函数都会返回1 while (calculateLength(editable.toString()) > MAX_COUNT) { // 当输 <SUF> editable.delete(editStart - 1, editEnd); editStart--; editEnd--; } // mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了,多谢@ainiyidiandian的提醒 commonEditText.setSelection(editStart); // 恢复监听器 commonEditText.addTextChangedListener(this); setLeftCount(); } }); commonEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL) { if (mode == MODE_REPLY && commonEditText.getText().toString().length() == re_Len) { return true; } } return false; } }); } /** * 计算分享内容的字数,一个汉字=两个英文字母,一个中文标点=两个英文标点 注意:该函数的不适用于对单个字符进行计算,因为单个字符四舍五入后都是1 * * @param c * @return */ private long calculateLength(CharSequence c) { double len = 0; for (int i = 0; i < c.length(); i++) { int tmp = (int) c.charAt(i); if (tmp > 0 && tmp < 127) { len += 0.5; } else { len++; } } return Math.round(len); } /** * 刷新剩余输入字数,最大值新浪微博是140个字,人人网是200个字 */ private void setLeftCount() { inputTextNum.setText(String.valueOf((MAX_COUNT - getInputCount()))); } /** * 获取用户输入的分享内容字数 * * @return */ private long getInputCount() { return calculateLength(commonEditText.getText().toString()); } public void setImage(Bitmap bitmap) { commentImage.setImageBitmap(bitmap); } public interface OnPicCommitListener { public void onPicCommentCommit(int mode, String editStr, int position); } public interface onPreviewListener { public void doPreview(); } public void clearText() { if (commonEditText != null) { commonEditText.setText(""); } } public void setCursorPosition(int index) { commonEditText.setSelection(index); re_Len = index; } @Override public void dismiss() { super.dismiss(); // if (commonEditText != null) { // commonEditText.setText(""); // } } }
false
1,752
16
2,027
15
2,168
14
2,027
15
2,600
26
false
false
false
false
false
true
64411_4
package com.aidex.system.service.impl; import com.aidex.system.dto.UserMedicalCardDTO; import com.aidex.system.dto.param.UserMedicalCardParam; import com.aidex.system.dto.param.UserMedicalCardUpdateParam; import com.aidex.system.entity.UserMedicalCard; import com.aidex.system.entity.UserMedicalCardExample; import com.aidex.system.entity.UserMedicalCardRelation; import com.aidex.system.entity.UserMedicalCardRelationExample; import com.aidex.system.mapper.UserMedicalCardMapper; import com.aidex.system.mapper.UserMedicalCardRelationMapper; import com.aidex.system.service.IUserMedicalCardService; import com.github.pagehelper.PageHelper; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @author YuJian95 clj9509@163.com * @date 2020/2/3 */ @Service public class UserMedicalCardServiceImpl implements IUserMedicalCardService { private static final int BOY = 1; private static final int GIRL = 2; @Resource private UserMedicalCardMapper medicalCardMapper; @Resource private UserMedicalCardRelationMapper relationMapper; /** * 添加医疗卡 * * @param accountId 账号编号 * @param param 就诊卡参数 * @return 是否成功 */ @Override public boolean insert(Long accountId, UserMedicalCardParam param) { // 就诊卡,存在 if (countIdentificationNumber(param.getIdentificationNumber())) { Optional<UserMedicalCard> cardOptional = getOptional(param.getIdentificationNumber()); if (cardOptional.isPresent()) { return insertRelation(accountId, param.getType(), cardOptional.get().getId()); } } // 就诊卡,不存在 if (insertCard(param)) { // 获取就诊卡信息 Optional<UserMedicalCard> cardOptional2 = getOptional(param.getIdentificationNumber()); // 插入关系 return cardOptional2.filter(userMedicalCard -> insertRelation(accountId, param.getType(), userMedicalCard.getId())) .isPresent(); } return false; } /** * 更新医疗卡(关系类型、姓名、电话) * * @param relationId 关系编号 * @param param 就诊卡更新参数 * @return 是否成功 */ @Override public boolean update(Long relationId, UserMedicalCardUpdateParam param) { int count = 0; // 更新关系 if (param.getType() != null) { UserMedicalCardRelation relation = new UserMedicalCardRelation(); BeanUtils.copyProperties(param, relation); relation.setId(relationId); relation.setGmtModified(new Date()); count = relationMapper.updateByPrimaryKeySelective(relation); } // 更新信息参数 UserMedicalCard card = new UserMedicalCard(); BeanUtils.copyProperties(param, card); card.setId(relationMapper.selectByPrimaryKey(relationId).getCardId()); card.setGmtModified(new Date()); count += medicalCardMapper.updateByPrimaryKeySelective(card); return count > 0; } /** * 获取患者名称 * * @param id 就诊卡编号 * @return 患者名称,或未知 */ @Override public String getName(Long id) { return getOptional(id).map(UserMedicalCard::getName).orElse("未知"); } /** * 获取就诊卡信息 * * @param id 就诊卡编号 * @return 就诊卡信息 */ @Override public Optional<UserMedicalCard> getOptional(Long id) { return Optional.ofNullable(medicalCardMapper.selectByPrimaryKey(id)); } /** * 通过身份证号码,获取就诊卡信息 * * @param identificationNumber 身份证号码 * @return 就诊卡信息 */ private Optional<UserMedicalCard> getOptional(String identificationNumber) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdentificationNumberEqualTo(identificationNumber); return Optional.ofNullable(medicalCardMapper.selectByExample(example).get(0)); } /** * 删除医疗卡 * * @param relationId 关系编号 * @return 是否成功 */ @Override public boolean delete(Long relationId) { return relationMapper.deleteByPrimaryKey(relationId) > 0; } /** * 查找就诊卡信息 * * @param name 姓名 * @param phone 手机号 * @param gender 性别( 0 所有,1 男,2 女) * @param pageNum 第几页 * @param pageSize 页大小 * @return 就诊卡列表 */ @Override public List<UserMedicalCard> list(String name, String phone, Integer gender, Integer pageNum, Integer pageSize) { PageHelper.startPage(pageNum, pageSize); UserMedicalCardExample example = new UserMedicalCardExample(); UserMedicalCardExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(name)) { criteria.andNameLike("%" + name + "%"); } if (!StringUtils.isEmpty(phone)) { criteria.andPhoneLike("%" + phone + "%"); } if (gender == BOY || gender == GIRL) { criteria.andGenderEqualTo(gender); } return medicalCardMapper.selectByExample(example); } /** * 根据就诊卡编号 * * @param idList 就诊卡编号 * @return 用户就诊信息 */ @Override public List<UserMedicalCard> list(List<Long> idList) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdIn(idList); return medicalCardMapper.selectByExample(example); } /** * 通过账号编号,获取就诊卡信息 * * @param accountId 账号编号 * @return 就诊卡列表 */ @Override public List<UserMedicalCardDTO> list(Long accountId) { UserMedicalCardRelationExample example = new UserMedicalCardRelationExample(); example.createCriteria() .andAccountIdEqualTo(accountId); return relationMapper.selectByExample(example).stream() .map(this::covert) .collect(Collectors.toList()); } private UserMedicalCardDTO covert(UserMedicalCardRelation relation) { UserMedicalCardDTO dto = new UserMedicalCardDTO(); // 获取就诊卡信息 Optional<UserMedicalCard> cardOptional = getOptional(relation.getCardId()); // 复制就诊卡信息 cardOptional.ifPresent(card -> BeanUtils.copyProperties(card, dto)); // 复制关系相关字段 BeanUtils.copyProperties(relation, dto); // 补充卡号 dto.setId(relation.getCardId()); dto.setRelationId(relation.getId()); return dto; } /** * 判断关系编号是否存在 * * @param relationId 关系编号 * @return 是否存在 */ @Override public boolean countRelation(Long relationId) { UserMedicalCardRelationExample example = new UserMedicalCardRelationExample(); example.createCriteria() .andIdEqualTo(relationId); return relationMapper.countByExample(example) > 0; } /** * 统计用户绑定的就诊卡数量 * * @param accountId 账号编号 * @return 就诊卡数量 */ @Override public long count(Long accountId) { UserMedicalCardRelationExample example = new UserMedicalCardRelationExample(); example.createCriteria() .andAccountIdEqualTo(accountId); return relationMapper.countByExample(example); } /** * 判断就诊卡信息是否存在 * * @param identificationNumber 身份证编号 * @return 是否存在 */ @Override public boolean countIdentificationNumber(String identificationNumber) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdentificationNumberEqualTo(identificationNumber); return medicalCardMapper.countByExample(example) > 0; } /** * 判断就诊卡号是否存在 * * @param cardId 就诊卡号 * @return 是否存在 */ @Override public boolean countCardId(Long cardId) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdEqualTo(cardId); return medicalCardMapper.countByExample(example) > 0; } /** * 插入就诊卡关系 * * @param accountId 用户账号编号 * @param type 关系类型 0:本人,1:父母,2:兄弟/姐妹,3:伴侣,4:子女,5:同事/朋友,6:其他 * @param cardId 就诊卡 * @return 是否成功 */ private boolean insertRelation(Long accountId, Integer type, Long cardId) { UserMedicalCardRelation relation = new UserMedicalCardRelation(); relation.setCardId(cardId); relation.setType(type); relation.setAccountId(accountId); relation.setGmtCreate(new Date()); relation.setGmtModified(new Date()); return relationMapper.insertSelective(relation) > 0; } /** * 添加医疗卡信息 * * @param param 就诊卡参数 * @return 是否成功 */ private boolean insertCard(UserMedicalCardParam param) { UserMedicalCard card = new UserMedicalCard(); BeanUtils.copyProperties(param, card); card.setGmtCreate(new Date()); card.setGmtModified(new Date()); return medicalCardMapper.insertSelective(card) > 0; } }
andream7/Yaren_clinic
aidex-system/src/main/java/com/aidex/system/service/impl/UserMedicalCardServiceImpl.java
2,399
// 获取就诊卡信息
line_comment
zh-cn
package com.aidex.system.service.impl; import com.aidex.system.dto.UserMedicalCardDTO; import com.aidex.system.dto.param.UserMedicalCardParam; import com.aidex.system.dto.param.UserMedicalCardUpdateParam; import com.aidex.system.entity.UserMedicalCard; import com.aidex.system.entity.UserMedicalCardExample; import com.aidex.system.entity.UserMedicalCardRelation; import com.aidex.system.entity.UserMedicalCardRelationExample; import com.aidex.system.mapper.UserMedicalCardMapper; import com.aidex.system.mapper.UserMedicalCardRelationMapper; import com.aidex.system.service.IUserMedicalCardService; import com.github.pagehelper.PageHelper; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @author YuJian95 clj9509@163.com * @date 2020/2/3 */ @Service public class UserMedicalCardServiceImpl implements IUserMedicalCardService { private static final int BOY = 1; private static final int GIRL = 2; @Resource private UserMedicalCardMapper medicalCardMapper; @Resource private UserMedicalCardRelationMapper relationMapper; /** * 添加医疗卡 * * @param accountId 账号编号 * @param param 就诊卡参数 * @return 是否成功 */ @Override public boolean insert(Long accountId, UserMedicalCardParam param) { // 就诊卡,存在 if (countIdentificationNumber(param.getIdentificationNumber())) { Optional<UserMedicalCard> cardOptional = getOptional(param.getIdentificationNumber()); if (cardOptional.isPresent()) { return insertRelation(accountId, param.getType(), cardOptional.get().getId()); } } // 就诊卡,不存在 if (insertCard(param)) { // 获取 <SUF> Optional<UserMedicalCard> cardOptional2 = getOptional(param.getIdentificationNumber()); // 插入关系 return cardOptional2.filter(userMedicalCard -> insertRelation(accountId, param.getType(), userMedicalCard.getId())) .isPresent(); } return false; } /** * 更新医疗卡(关系类型、姓名、电话) * * @param relationId 关系编号 * @param param 就诊卡更新参数 * @return 是否成功 */ @Override public boolean update(Long relationId, UserMedicalCardUpdateParam param) { int count = 0; // 更新关系 if (param.getType() != null) { UserMedicalCardRelation relation = new UserMedicalCardRelation(); BeanUtils.copyProperties(param, relation); relation.setId(relationId); relation.setGmtModified(new Date()); count = relationMapper.updateByPrimaryKeySelective(relation); } // 更新信息参数 UserMedicalCard card = new UserMedicalCard(); BeanUtils.copyProperties(param, card); card.setId(relationMapper.selectByPrimaryKey(relationId).getCardId()); card.setGmtModified(new Date()); count += medicalCardMapper.updateByPrimaryKeySelective(card); return count > 0; } /** * 获取患者名称 * * @param id 就诊卡编号 * @return 患者名称,或未知 */ @Override public String getName(Long id) { return getOptional(id).map(UserMedicalCard::getName).orElse("未知"); } /** * 获取就诊卡信息 * * @param id 就诊卡编号 * @return 就诊卡信息 */ @Override public Optional<UserMedicalCard> getOptional(Long id) { return Optional.ofNullable(medicalCardMapper.selectByPrimaryKey(id)); } /** * 通过身份证号码,获取就诊卡信息 * * @param identificationNumber 身份证号码 * @return 就诊卡信息 */ private Optional<UserMedicalCard> getOptional(String identificationNumber) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdentificationNumberEqualTo(identificationNumber); return Optional.ofNullable(medicalCardMapper.selectByExample(example).get(0)); } /** * 删除医疗卡 * * @param relationId 关系编号 * @return 是否成功 */ @Override public boolean delete(Long relationId) { return relationMapper.deleteByPrimaryKey(relationId) > 0; } /** * 查找就诊卡信息 * * @param name 姓名 * @param phone 手机号 * @param gender 性别( 0 所有,1 男,2 女) * @param pageNum 第几页 * @param pageSize 页大小 * @return 就诊卡列表 */ @Override public List<UserMedicalCard> list(String name, String phone, Integer gender, Integer pageNum, Integer pageSize) { PageHelper.startPage(pageNum, pageSize); UserMedicalCardExample example = new UserMedicalCardExample(); UserMedicalCardExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(name)) { criteria.andNameLike("%" + name + "%"); } if (!StringUtils.isEmpty(phone)) { criteria.andPhoneLike("%" + phone + "%"); } if (gender == BOY || gender == GIRL) { criteria.andGenderEqualTo(gender); } return medicalCardMapper.selectByExample(example); } /** * 根据就诊卡编号 * * @param idList 就诊卡编号 * @return 用户就诊信息 */ @Override public List<UserMedicalCard> list(List<Long> idList) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdIn(idList); return medicalCardMapper.selectByExample(example); } /** * 通过账号编号,获取就诊卡信息 * * @param accountId 账号编号 * @return 就诊卡列表 */ @Override public List<UserMedicalCardDTO> list(Long accountId) { UserMedicalCardRelationExample example = new UserMedicalCardRelationExample(); example.createCriteria() .andAccountIdEqualTo(accountId); return relationMapper.selectByExample(example).stream() .map(this::covert) .collect(Collectors.toList()); } private UserMedicalCardDTO covert(UserMedicalCardRelation relation) { UserMedicalCardDTO dto = new UserMedicalCardDTO(); // 获取就诊卡信息 Optional<UserMedicalCard> cardOptional = getOptional(relation.getCardId()); // 复制就诊卡信息 cardOptional.ifPresent(card -> BeanUtils.copyProperties(card, dto)); // 复制关系相关字段 BeanUtils.copyProperties(relation, dto); // 补充卡号 dto.setId(relation.getCardId()); dto.setRelationId(relation.getId()); return dto; } /** * 判断关系编号是否存在 * * @param relationId 关系编号 * @return 是否存在 */ @Override public boolean countRelation(Long relationId) { UserMedicalCardRelationExample example = new UserMedicalCardRelationExample(); example.createCriteria() .andIdEqualTo(relationId); return relationMapper.countByExample(example) > 0; } /** * 统计用户绑定的就诊卡数量 * * @param accountId 账号编号 * @return 就诊卡数量 */ @Override public long count(Long accountId) { UserMedicalCardRelationExample example = new UserMedicalCardRelationExample(); example.createCriteria() .andAccountIdEqualTo(accountId); return relationMapper.countByExample(example); } /** * 判断就诊卡信息是否存在 * * @param identificationNumber 身份证编号 * @return 是否存在 */ @Override public boolean countIdentificationNumber(String identificationNumber) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdentificationNumberEqualTo(identificationNumber); return medicalCardMapper.countByExample(example) > 0; } /** * 判断就诊卡号是否存在 * * @param cardId 就诊卡号 * @return 是否存在 */ @Override public boolean countCardId(Long cardId) { UserMedicalCardExample example = new UserMedicalCardExample(); example.createCriteria() .andIdEqualTo(cardId); return medicalCardMapper.countByExample(example) > 0; } /** * 插入就诊卡关系 * * @param accountId 用户账号编号 * @param type 关系类型 0:本人,1:父母,2:兄弟/姐妹,3:伴侣,4:子女,5:同事/朋友,6:其他 * @param cardId 就诊卡 * @return 是否成功 */ private boolean insertRelation(Long accountId, Integer type, Long cardId) { UserMedicalCardRelation relation = new UserMedicalCardRelation(); relation.setCardId(cardId); relation.setType(type); relation.setAccountId(accountId); relation.setGmtCreate(new Date()); relation.setGmtModified(new Date()); return relationMapper.insertSelective(relation) > 0; } /** * 添加医疗卡信息 * * @param param 就诊卡参数 * @return 是否成功 */ private boolean insertCard(UserMedicalCardParam param) { UserMedicalCard card = new UserMedicalCard(); BeanUtils.copyProperties(param, card); card.setGmtCreate(new Date()); card.setGmtModified(new Date()); return medicalCardMapper.insertSelective(card) > 0; } }
false
2,187
5
2,399
7
2,511
6
2,399
7
3,211
13
false
false
false
false
false
true
43686_7
/* 冒泡算法 冒泡排序是最简单的排序之一,通过与相邻元素的比较和交换来把小的数交换到最前面。请完成实现swap方法,来完成冒泡算法 */ public static void swap(int[] arr,int pre,int next){ int temp=arr[pre]; arr[pre]=arr[next]; arr[next]=temp; } /* 计算π的值 在数学中,我们可以通过π=4╳(1-1/3+1/5-1/7+1/9-......1/(2╳n+1)) 来计算,n越大,计算值越靠近。输入正整数n来计算π。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); double ans=0; for(int i=0;i<x;++i) { if(i%2==1) ans-=1.0/(2*i+1); else ans+=1.0/(2*i+1); } System.out.println(4.0f*ans); } } /* 求圆柱的面积和体积 输入圆柱的底面半径r和高l(double类型),输出圆柱的底面积和体积(double类型)。注意:计算中的π来自于Math。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); double r=reader.nextDouble(); double l=reader.nextDouble(); System.out.println("The area is "+r*r*Math.PI); System.out.println("The volume is "+r*r*Math.PI*l); } } /* 判断奇偶 输入一个整数,判断其奇偶性 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); if(x%2==1) System.out.println(x+" is odd."); else System.out.println(x+" is even."); } } /* 华氏度转摄氏度 本题要求编写程序,计算华氏温度对应的摄氏温度。计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为取整(舍去小数部分)后整型。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); System.out.println(5*(x-32)/9); } } /* 华氏度转摄氏度(四舍五入) 本题要求编写程序,计算华氏温度对应的摄氏温度。计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为四舍五入取整后整型。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); double x=reader.nextDouble(); System.out.println(Math.round(5*(x-32)/9)); } } /* 中国生肖年 输入一个年份,输出该年的生肖属相。注:十二生肖为鼠、牛、虎、兔、龙、蛇、马、羊、猴、鸡、狗、猪。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); x=x%12; char sx[]={'鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'}; System.out.println(sx[(x+8)%12]); } } /* 打印乘法表 输出10以内的乘法表,输入为1-20的整数,输出请参照输出样例。打印的时候,一个数占4位。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); for(int i=1;i<=x;++i) { for(int j=1;j<=x;++j) System.out.printf("%4d",i*j); System.out.println(""); } } }
andream7/cuit_sharing
JAVA/PTA作业及考试/第2,3章.java
1,194
/* 打印乘法表 输出10以内的乘法表,输入为1-20的整数,输出请参照输出样例。打印的时候,一个数占4位。 */
block_comment
zh-cn
/* 冒泡算法 冒泡排序是最简单的排序之一,通过与相邻元素的比较和交换来把小的数交换到最前面。请完成实现swap方法,来完成冒泡算法 */ public static void swap(int[] arr,int pre,int next){ int temp=arr[pre]; arr[pre]=arr[next]; arr[next]=temp; } /* 计算π的值 在数学中,我们可以通过π=4╳(1-1/3+1/5-1/7+1/9-......1/(2╳n+1)) 来计算,n越大,计算值越靠近。输入正整数n来计算π。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); double ans=0; for(int i=0;i<x;++i) { if(i%2==1) ans-=1.0/(2*i+1); else ans+=1.0/(2*i+1); } System.out.println(4.0f*ans); } } /* 求圆柱的面积和体积 输入圆柱的底面半径r和高l(double类型),输出圆柱的底面积和体积(double类型)。注意:计算中的π来自于Math。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); double r=reader.nextDouble(); double l=reader.nextDouble(); System.out.println("The area is "+r*r*Math.PI); System.out.println("The volume is "+r*r*Math.PI*l); } } /* 判断奇偶 输入一个整数,判断其奇偶性 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); if(x%2==1) System.out.println(x+" is odd."); else System.out.println(x+" is even."); } } /* 华氏度转摄氏度 本题要求编写程序,计算华氏温度对应的摄氏温度。计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为取整(舍去小数部分)后整型。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); System.out.println(5*(x-32)/9); } } /* 华氏度转摄氏度(四舍五入) 本题要求编写程序,计算华氏温度对应的摄氏温度。计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为四舍五入取整后整型。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); double x=reader.nextDouble(); System.out.println(Math.round(5*(x-32)/9)); } } /* 中国生肖年 输入一个年份,输出该年的生肖属相。注:十二生肖为鼠、牛、虎、兔、龙、蛇、马、羊、猴、鸡、狗、猪。 */ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); x=x%12; char sx[]={'鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪'}; System.out.println(sx[(x+8)%12]); } } /* 打印乘 <SUF>*/ import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner reader = new Scanner(System.in); int x=reader.nextInt(); for(int i=1;i<=x;++i) { for(int j=1;j<=x;++j) System.out.printf("%4d",i*j); System.out.println(""); } } }
false
959
42
1,194
46
1,148
43
1,194
46
1,453
69
false
false
false
false
false
true
19333_15
package com.example.note.mynote; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; //实现顶部tabLayout布局 public class TopTab extends AppCompatActivity { private TabLayout mTabLayout; private ViewPager mViewPager; private LayoutInflater mInflater; private List<String> mTitleList = new ArrayList<String>();//页卡标题集合 private View view1, view2;//页卡视图 private List<View> mViewList = new ArrayList<>();//页卡视图集合 private Button backButton; private ListView msgListView; private List<String> title,titles; private List<String> content,contents; private List<String> time,times; private int num = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_top_tab); ActionBar actionBar = getSupportActionBar(); if(actionBar!=null){ actionBar.hide(); } initial(); msgListView = (ListView) findViewById(R.id.msg_listView); final MyBaseAdapters myBaseAdapters = new MyBaseAdapters(); msgListView.setAdapter(myBaseAdapters); backButton = (Button) findViewById(R.id.backs); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mViewPager = (ViewPager) findViewById(R.id.vp_view); mTabLayout = (TabLayout) findViewById(R.id.tabs); mInflater = LayoutInflater.from(this); view1 = new View(getApplicationContext()); view2 = new View(getApplicationContext()); //添加页卡视图 mViewList.add(view1); mViewList.add(view2); //添加页卡标题 mTitleList.add("消息"); mTitleList.add("通知"); //添加tab选项卡,默认第一个选中 mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)), true); mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1))); MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList); //给ViewPager设置适配器 mViewPager.setAdapter(mAdapter); //将TabLayout和ViewPager关联起来 mTabLayout.setupWithViewPager(mViewPager); //给Tabs设置适配器 mTabLayout.setTabsFromPagerAdapter(mAdapter); mTabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { num = tab.getPosition(); myBaseAdapters.notifyDataSetChanged(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } public void initial(){ title = new ArrayList<String>(); content = new ArrayList<String>(); time = new ArrayList<String>(); title.add("1004惹的祸"); content.add("回顾百期,我们整理了一份特别的礼物,一周微信收藏100期特别排行榜"); time.add("2018-12-12"); title.add("马云爸爸发红包啦!"); content.add("打开支付宝首页搜“570321008”领红包,领到大红包的小伙伴赶紧使用哦!"); time.add("2018-12-24"); title.add("要想抓住TA的心,得先抓住TA的胃!"); content.add("米家新品小饭煲,要比情敌先下手!"); time.add("2018-12-26"); titles = new ArrayList<String>(); contents = new ArrayList<String>(); times = new ArrayList<String>(); titles.add("1005发生的大事"); contents.add("这周有大事要发生了呢,哈哈哈哈"); times.add("2018-11-11"); titles.add("有人@你"); contents.add("点击回复"); times.add("2018-12-12"); titles.add("[MyNote]新款App上架啦!"); contents.add("给你全新的笔记APP体验,是兄弟,就来下载我!"); times.add("2018-11-13"); } //ViewPager适配器 class MyPagerAdapter extends PagerAdapter { private List<View> mViewList; public MyPagerAdapter(List<View> mViewList) { this.mViewList = mViewList; } @Override public int getCount() { return mViewList.size();//页卡数 } @Override public boolean isViewFromObject(View view, Object object) { return view == object;//官方推荐写法 } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mViewList.get(position));//添加页卡 return mViewList.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mViewList.get(position));//删除页卡 } @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position);//页卡标题 } } class MyBaseAdapters extends BaseAdapter{ @Override public Object getItem(int position) { return title.get(position); } @Override public int getCount() { return title.size(); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(convertView==null){ convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.msg_list,parent,false); viewHolder = new ViewHolder(); viewHolder.msgTitle = (TextView) convertView.findViewById(R.id.the_title); viewHolder.msgContent = (TextView) convertView.findViewById(R.id.the_content); viewHolder.msgTime = (TextView) convertView.findViewById(R.id.the_time); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } if(num==0) { viewHolder.msgTitle.setText(title.get(position)); viewHolder.msgContent.setText(content.get(position)); viewHolder.msgTime.setText(time.get(position)); } else if(num==1){ viewHolder.msgTitle.setText(titles.get(position)); viewHolder.msgContent.setText(contents.get(position)); viewHolder.msgTime.setText(times.get(position)); } return convertView; } } class ViewHolder{ TextView msgTitle; TextView msgContent; TextView msgTime; } }
android-app-development-course/2018_26_CloudNote
app/src/main/java/com/example/note/mynote/TopTab.java
1,812
//页卡标题
line_comment
zh-cn
package com.example.note.mynote; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; //实现顶部tabLayout布局 public class TopTab extends AppCompatActivity { private TabLayout mTabLayout; private ViewPager mViewPager; private LayoutInflater mInflater; private List<String> mTitleList = new ArrayList<String>();//页卡标题集合 private View view1, view2;//页卡视图 private List<View> mViewList = new ArrayList<>();//页卡视图集合 private Button backButton; private ListView msgListView; private List<String> title,titles; private List<String> content,contents; private List<String> time,times; private int num = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_top_tab); ActionBar actionBar = getSupportActionBar(); if(actionBar!=null){ actionBar.hide(); } initial(); msgListView = (ListView) findViewById(R.id.msg_listView); final MyBaseAdapters myBaseAdapters = new MyBaseAdapters(); msgListView.setAdapter(myBaseAdapters); backButton = (Button) findViewById(R.id.backs); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mViewPager = (ViewPager) findViewById(R.id.vp_view); mTabLayout = (TabLayout) findViewById(R.id.tabs); mInflater = LayoutInflater.from(this); view1 = new View(getApplicationContext()); view2 = new View(getApplicationContext()); //添加页卡视图 mViewList.add(view1); mViewList.add(view2); //添加页卡标题 mTitleList.add("消息"); mTitleList.add("通知"); //添加tab选项卡,默认第一个选中 mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)), true); mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1))); MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList); //给ViewPager设置适配器 mViewPager.setAdapter(mAdapter); //将TabLayout和ViewPager关联起来 mTabLayout.setupWithViewPager(mViewPager); //给Tabs设置适配器 mTabLayout.setTabsFromPagerAdapter(mAdapter); mTabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { num = tab.getPosition(); myBaseAdapters.notifyDataSetChanged(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } public void initial(){ title = new ArrayList<String>(); content = new ArrayList<String>(); time = new ArrayList<String>(); title.add("1004惹的祸"); content.add("回顾百期,我们整理了一份特别的礼物,一周微信收藏100期特别排行榜"); time.add("2018-12-12"); title.add("马云爸爸发红包啦!"); content.add("打开支付宝首页搜“570321008”领红包,领到大红包的小伙伴赶紧使用哦!"); time.add("2018-12-24"); title.add("要想抓住TA的心,得先抓住TA的胃!"); content.add("米家新品小饭煲,要比情敌先下手!"); time.add("2018-12-26"); titles = new ArrayList<String>(); contents = new ArrayList<String>(); times = new ArrayList<String>(); titles.add("1005发生的大事"); contents.add("这周有大事要发生了呢,哈哈哈哈"); times.add("2018-11-11"); titles.add("有人@你"); contents.add("点击回复"); times.add("2018-12-12"); titles.add("[MyNote]新款App上架啦!"); contents.add("给你全新的笔记APP体验,是兄弟,就来下载我!"); times.add("2018-11-13"); } //ViewPager适配器 class MyPagerAdapter extends PagerAdapter { private List<View> mViewList; public MyPagerAdapter(List<View> mViewList) { this.mViewList = mViewList; } @Override public int getCount() { return mViewList.size();//页卡数 } @Override public boolean isViewFromObject(View view, Object object) { return view == object;//官方推荐写法 } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mViewList.get(position));//添加页卡 return mViewList.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mViewList.get(position));//删除页卡 } @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position);//页卡 <SUF> } } class MyBaseAdapters extends BaseAdapter{ @Override public Object getItem(int position) { return title.get(position); } @Override public int getCount() { return title.size(); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(convertView==null){ convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.msg_list,parent,false); viewHolder = new ViewHolder(); viewHolder.msgTitle = (TextView) convertView.findViewById(R.id.the_title); viewHolder.msgContent = (TextView) convertView.findViewById(R.id.the_content); viewHolder.msgTime = (TextView) convertView.findViewById(R.id.the_time); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } if(num==0) { viewHolder.msgTitle.setText(title.get(position)); viewHolder.msgContent.setText(content.get(position)); viewHolder.msgTime.setText(time.get(position)); } else if(num==1){ viewHolder.msgTitle.setText(titles.get(position)); viewHolder.msgContent.setText(contents.get(position)); viewHolder.msgTime.setText(times.get(position)); } return convertView; } } class ViewHolder{ TextView msgTitle; TextView msgContent; TextView msgTime; } }
false
1,491
4
1,812
4
1,843
4
1,812
4
2,221
7
false
false
false
false
false
true
29545_8
package com.tomato830.note_fjm; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.tomato830.note_fjm.note.note; import com.tomato830.note_fjm.noteUtil.MySQLiteHelper; import java.text.SimpleDateFormat; import java.util.ArrayList; public class myRVAdapter extends RecyclerView.Adapter<myRVAdapter.myTVHolder> { private ArrayList<note> mArray; private final LayoutInflater mLayoutInflater; private final Context mContext; public myRVAdapter(Context context,ArrayList<note> mArray){ //mArray = context.getResources().getStringArray(R.array.testArray); this.mArray = mArray; mLayoutInflater = LayoutInflater.from(context); mContext = context; } @NonNull @Override public myRVAdapter.myTVHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new myTVHolder(mLayoutInflater.inflate(R.layout.item_cardview,parent,false)); } @Override public void onBindViewHolder(@NonNull final myTVHolder holder, final int position) { //holder.checkBox.setTag(position); //holder.item_titile.setText(mArray[position]); MySQLiteHelper helper = new MySQLiteHelper(mContext,1); final SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase(); holder.item_titile.setText(mArray.get(position).getTitle()); holder.item_body.setText(mArray.get(position).getContent()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd|HH:mm"); holder.item_time.setText(sdf.format(mArray.get(position).getCreationTime().getTime())); if (mArray.get(position).isDone()){//在已完成界面,如果完成就打上勾,打勾选项在监听器前 holder.checkBox.setChecked(true); } else { holder.checkBox.setChecked(false); } //救命!我懵逼了:在todo中勾选的item在下一次登入应用时时才能在finished中显示 holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContentValues values = new ContentValues(); if (mArray.get(position).isDone()){//点击之后改变,编成相反的 values.put("isDone", "0"); mArray.get(position).setDone(false); } else { values.put("isDone", "1"); mArray.get(position).setDone(true); } String[] whereArgs = {String.valueOf(mArray.get(position).getId())};//获取此表项的id //将此项从list中删除 mArray.remove(position); //更新数据库 sqLiteDatabase.update("todolist",values,"id=?",whereArgs); //更新recyclerView notifyItemRemoved(position);//显示删除动画 //notifyDataSetChanged(); notifyItemRangeChanged(position,mArray.size()-position);//修改mArray中数据的相对位置 } }); } @Override public int getItemCount() { return mArray == null ? 0:mArray.size(); } public class myTVHolder extends RecyclerView.ViewHolder{ TextView item_titile; TextView item_body; TextView item_time; CheckBox checkBox; public myTVHolder(@NonNull View itemView) { super(itemView); item_titile = (TextView) itemView.findViewById(R.id.carditem_title); item_body = (TextView)itemView.findViewById(R.id.carditem_body); item_time = (TextView) itemView.findViewById(R.id.carditem_time); checkBox = (CheckBox) itemView.findViewById(R.id.finished_to_check); } } }
android-app-development-course/2019-a5-note
app/src/main/java/com/tomato830/note_fjm/myRVAdapter.java
975
//更新数据库
line_comment
zh-cn
package com.tomato830.note_fjm; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.tomato830.note_fjm.note.note; import com.tomato830.note_fjm.noteUtil.MySQLiteHelper; import java.text.SimpleDateFormat; import java.util.ArrayList; public class myRVAdapter extends RecyclerView.Adapter<myRVAdapter.myTVHolder> { private ArrayList<note> mArray; private final LayoutInflater mLayoutInflater; private final Context mContext; public myRVAdapter(Context context,ArrayList<note> mArray){ //mArray = context.getResources().getStringArray(R.array.testArray); this.mArray = mArray; mLayoutInflater = LayoutInflater.from(context); mContext = context; } @NonNull @Override public myRVAdapter.myTVHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new myTVHolder(mLayoutInflater.inflate(R.layout.item_cardview,parent,false)); } @Override public void onBindViewHolder(@NonNull final myTVHolder holder, final int position) { //holder.checkBox.setTag(position); //holder.item_titile.setText(mArray[position]); MySQLiteHelper helper = new MySQLiteHelper(mContext,1); final SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase(); holder.item_titile.setText(mArray.get(position).getTitle()); holder.item_body.setText(mArray.get(position).getContent()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd|HH:mm"); holder.item_time.setText(sdf.format(mArray.get(position).getCreationTime().getTime())); if (mArray.get(position).isDone()){//在已完成界面,如果完成就打上勾,打勾选项在监听器前 holder.checkBox.setChecked(true); } else { holder.checkBox.setChecked(false); } //救命!我懵逼了:在todo中勾选的item在下一次登入应用时时才能在finished中显示 holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContentValues values = new ContentValues(); if (mArray.get(position).isDone()){//点击之后改变,编成相反的 values.put("isDone", "0"); mArray.get(position).setDone(false); } else { values.put("isDone", "1"); mArray.get(position).setDone(true); } String[] whereArgs = {String.valueOf(mArray.get(position).getId())};//获取此表项的id //将此项从list中删除 mArray.remove(position); //更新 <SUF> sqLiteDatabase.update("todolist",values,"id=?",whereArgs); //更新recyclerView notifyItemRemoved(position);//显示删除动画 //notifyDataSetChanged(); notifyItemRangeChanged(position,mArray.size()-position);//修改mArray中数据的相对位置 } }); } @Override public int getItemCount() { return mArray == null ? 0:mArray.size(); } public class myTVHolder extends RecyclerView.ViewHolder{ TextView item_titile; TextView item_body; TextView item_time; CheckBox checkBox; public myTVHolder(@NonNull View itemView) { super(itemView); item_titile = (TextView) itemView.findViewById(R.id.carditem_title); item_body = (TextView)itemView.findViewById(R.id.carditem_body); item_time = (TextView) itemView.findViewById(R.id.carditem_time); checkBox = (CheckBox) itemView.findViewById(R.id.finished_to_check); } } }
false
788
3
975
3
1,013
3
975
3
1,180
6
false
false
false
false
false
true
18818_7
package elitedj.me.todo.discover; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.github.siyamed.shapeimageview.RoundedImageView; import com.lzy.ninegrid.NineGridView; import java.util.ArrayList; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobUser; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.DownloadFileListener; import elitedj.me.todo.bean.User; import elitedj.me.todo.me.Setting; import elitedj.me.todo.me.SettingDB; import elitedj.me.todo.utils.NativeBarHeight; import elitedj.me.todo.R; public class DiscoverActivity extends AppCompatActivity implements View.OnClickListener{ private ArrayList<Moment> moments = new ArrayList<>(); private RecyclerView momentList; private ImageButton newEdit; private TextView nickName; private RoundedImageView face; private User user; private MomentListAdapter momentListAdapter; private SettingDB DB; private SQLiteDatabase dbread; private Setting set; @Override protected void onCreate(Bundle savedInstanceState) { DB = new SettingDB(this); dbread = DB.getReadableDatabase(); set = new Setting(); inittheme(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_discover); Bmob.initialize(this, "270e4c5889c9b50d64c82ef459cbcee4"); discoverViewInit(); newEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { newEditFun(); } }); } public void discoverViewInit(){ // 设置朋友圈的titleBar的margin,让它在系统状态栏底部,适配所有手机 LinearLayout titleBar = findViewById(R.id.linearlayout1); // LinearLayout 表示该控件在LinearLayout里面,其他控件用法类似 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(titleBar.getLayoutParams()); lp.setMargins(0,new NativeBarHeight().getNativeBarHeight(this)+16,0,0); titleBar.setLayoutParams(lp); newEdit = findViewById(R.id.newedit); newEdit.setOnClickListener(this); //设置appbar AppBarLayout appBarLayout = findViewById(R.id.appBar); appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int i) { RoundedImageView face = findViewById(R.id.myFace); CoordinatorLayout bg = findViewById(R.id.discoverViewBG); if(Math.abs(i) >= appBarLayout.getTotalScrollRange()) { //折叠 face.setVisibility(View.GONE); } else { //未折叠 bg.setBackgroundColor(getResources().getColor(R.color.white)); face.setVisibility(View.VISIBLE); } } }); //获取用户名和头像控件 nickName = findViewById(R.id.nickname); face = findViewById(R.id.myFace); //设置头像 Glide.with(this) .load("http://photocdn.sohu.com/20131128/Img390959345.jpg") .asBitmap() .into(face); //获取登录的用户信息 if(BmobUser.isLogin()) { //获取登录用户 user = BmobUser.getCurrentUser(User.class); //设置nickName nickName.setText(user.getNickName()); //下载头像 // BmobFile bf = user.getFace(); // bf.download(new DownloadFileListener() { // @Override // public void done(String s, BmobException e) { // if(e==null) { // Glide.with(DiscoverActivity.this) // .load(s) // .asBitmap() // .into(face); // }else { // Log.e("--->", "done: discover face download fail"+e, null); // } // } // // @Override // public void onProgress(Integer integer, long l) { // // } // }); } else { Log.e("--->", "discoverViewInit: discover not get face and nickname", null); } // 朋友圈的列表 momentList = findViewById(R.id.momentlist); initMomentList(); momentList.setLayoutManager(new LinearLayoutManager(this)); momentListAdapter = new MomentListAdapter(this, moments, getLayoutInflater()); momentList.setAdapter(momentListAdapter); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.newedit: newEditFun(); break; default: break; } } private void newEditFun(){ Intent intent = new Intent(this, EditNewMomentActivity.class); getParent().startActivityForResult(intent, 1); //startActivity(intent); } // //在AppMainActivity里面的onActivityResult函数里面处理结果 // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // Log.e("--->", "onActivityResult: hello", null); // switch (resultCode) { // case 1: // Moment m = (Moment) data.getSerializableExtra("newMoment"); // Log.e("--->", "onActivityResult: "+m.getName(), null); // momentListAdapter.addItem(0, m); // break; // // default: break; // } // } public void inittheme() { Cursor cursor = dbread.query("Setting", null, null, null, null,null, null); cursor.moveToNext(); set.setTheme(cursor.getInt(cursor.getColumnIndex("theme"))); switch (set.getTheme()) { case 0: setTheme(R.style.GreenAppTheme); break; case 1: setTheme(R.style.BlueAppTheme); break; case 2: setTheme(R.style.PurpleAppTheme); break; case 3: setTheme(R.style.BronzeAppTheme); break; case 4: setTheme(R.style.PinkAppTheme); break; case 5: setTheme(R.style.OrAppTheme); break; default: break; } cursor.close(); } public void initMomentList() { Moment m; ArrayList<Picture> p; //刘强东 m = new Moment(); m.setFace("http://5b0988e595225.cdn.sohucs.com/images/20180904/a5501e9c02bf44a89ec9474d18e17f95.jpeg"); m.setName("刘强东"); m.setContent("脱下西裤,套上囚服,奥利给!"); p = new ArrayList<>(); p.add(new Picture("https://wx4.sinaimg.cn/large/006fT3Elgy1fuwksvst0sj30l90byqck.jpg")); p.add(new Picture("http://5b0988e595225.cdn.sohucs.com/images/20180904/a5501e9c02bf44a89ec9474d18e17f95.jpeg")); m.setPictures(p); moments.add(m); //马云 m = new Moment(); m.setFace("http://n.sinaimg.cn/finance/transform/20161231/ypok-fxzencv2934675.jpg"); m.setName("马云"); m.setContent("我对钱没有兴趣!"); p = new ArrayList<>(); p.add(new Picture("http://i5.hexun.com/2018-10-10/194692903.jpg")); p.add(new Picture("http://i8.hexun.com/2018-10-10/194692904.jpg")); p.add(new Picture("http://i3.hexun.com/2018-10-10/194692905.jpg")); m.setPictures(p); moments.add(m); //马化腾坐公交 m = new Moment(); m.setFace("http://photocdn.sohu.com/20131128/Img390959345.jpg"); m.setName("马化腾"); m.setContent("今天穷到坐公交了"); p = new ArrayList<>(); p.add(new Picture("http://img.chenpe.com/8d/cc/a5/2b/8dcca52b982ffcae2d299453248f2b78size_580x370_size.jpg")); p.add(new Picture("http://5b0988e595225.cdn.sohucs.com/images/20170914/08bcb01ba73647ad9145a76cbac9cb8a.jpg")); m.setPictures(p); moments.add(m); //李彦宏 m = new Moment(); m.setFace("http://www.sx.chinanews.com/news/2011/0427/U71P8T1D36722F5DT20110427165123.jpg"); m.setName("李彦宏"); m.setContent("What's your problem?"); p = new ArrayList<>(); p.add(new Picture("https://wx4.sinaimg.cn/mw690/007MC2Nagy1g4nn901xx2j306b05lt8o.jpg")); m.setPictures(p); moments.add(m); //蔡徐坤 m = new Moment(); m.setFace("http://5b0988e595225.cdn.sohucs.com/q_70,c_zoom,w_640/images/20190418/24e27baac15748759f2080aadbd99cc8.jpeg"); m.setName("蔡徐坤(篮球之神)"); m.setContent("欧文都学不会我的运球, 哦哦哦哦哦~"); p = new ArrayList<>(); p.add(new Picture("http://n.sinaimg.cn/front/253/w619h434/20190403/5kjK-hvcmeuy0880454.jpg")); p.add(new Picture("http://n.sinaimg.cn/front/231/w607h424/20190403/m0bK-hvcmeuy0880599.jpg")); p.add(new Picture("http://n.sinaimg.cn/sinacn09/300/w440h660/20180416/ce89-fzcyxmv2121495.jpg")); m.setPictures(p); moments.add(m); //PDD m = new Moment(); m.setFace("http://img1.dwstatic.com/lol/1701/348197040731/348197144646.jpeg"); m.setName("PDD"); m.setContent("英雄联盟全球总决赛两届的FMVP都是从我这里出去的,很多人都说我被Ning和Tian演了,开玩笑我可是PDD,谁能演我,只有李现能演我。有人说韩商言的原型是我,我去专门看了那部剧,确实挺像的,都创办了俱乐部,都没有夺冠,都是冷酷的帅哥。"); p = new ArrayList<>(); p.add(new Picture("http://img1.gtimg.com/gamezone/pics/hv1/78/82/2222/144506538.png")); p.add(new Picture("http://img1.gtimg.com/gamezone/pics/hv1/77/82/2222/144506537.png")); p.add(new Picture("https://04imgmini.eastday.com/mobile/20191224/20191224001414_819daf8f344b29ee65d47b732abbcbe4_1.jpeg")); m.setPictures(p); moments.add(m); } }
android-app-development-course/2019_a13_ToDo
ToDo/app/src/main/java/elitedj/me/todo/discover/DiscoverActivity.java
3,419
//获取登录的用户信息
line_comment
zh-cn
package elitedj.me.todo.discover; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.github.siyamed.shapeimageview.RoundedImageView; import com.lzy.ninegrid.NineGridView; import java.util.ArrayList; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobUser; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.DownloadFileListener; import elitedj.me.todo.bean.User; import elitedj.me.todo.me.Setting; import elitedj.me.todo.me.SettingDB; import elitedj.me.todo.utils.NativeBarHeight; import elitedj.me.todo.R; public class DiscoverActivity extends AppCompatActivity implements View.OnClickListener{ private ArrayList<Moment> moments = new ArrayList<>(); private RecyclerView momentList; private ImageButton newEdit; private TextView nickName; private RoundedImageView face; private User user; private MomentListAdapter momentListAdapter; private SettingDB DB; private SQLiteDatabase dbread; private Setting set; @Override protected void onCreate(Bundle savedInstanceState) { DB = new SettingDB(this); dbread = DB.getReadableDatabase(); set = new Setting(); inittheme(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_discover); Bmob.initialize(this, "270e4c5889c9b50d64c82ef459cbcee4"); discoverViewInit(); newEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { newEditFun(); } }); } public void discoverViewInit(){ // 设置朋友圈的titleBar的margin,让它在系统状态栏底部,适配所有手机 LinearLayout titleBar = findViewById(R.id.linearlayout1); // LinearLayout 表示该控件在LinearLayout里面,其他控件用法类似 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(titleBar.getLayoutParams()); lp.setMargins(0,new NativeBarHeight().getNativeBarHeight(this)+16,0,0); titleBar.setLayoutParams(lp); newEdit = findViewById(R.id.newedit); newEdit.setOnClickListener(this); //设置appbar AppBarLayout appBarLayout = findViewById(R.id.appBar); appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int i) { RoundedImageView face = findViewById(R.id.myFace); CoordinatorLayout bg = findViewById(R.id.discoverViewBG); if(Math.abs(i) >= appBarLayout.getTotalScrollRange()) { //折叠 face.setVisibility(View.GONE); } else { //未折叠 bg.setBackgroundColor(getResources().getColor(R.color.white)); face.setVisibility(View.VISIBLE); } } }); //获取用户名和头像控件 nickName = findViewById(R.id.nickname); face = findViewById(R.id.myFace); //设置头像 Glide.with(this) .load("http://photocdn.sohu.com/20131128/Img390959345.jpg") .asBitmap() .into(face); //获取 <SUF> if(BmobUser.isLogin()) { //获取登录用户 user = BmobUser.getCurrentUser(User.class); //设置nickName nickName.setText(user.getNickName()); //下载头像 // BmobFile bf = user.getFace(); // bf.download(new DownloadFileListener() { // @Override // public void done(String s, BmobException e) { // if(e==null) { // Glide.with(DiscoverActivity.this) // .load(s) // .asBitmap() // .into(face); // }else { // Log.e("--->", "done: discover face download fail"+e, null); // } // } // // @Override // public void onProgress(Integer integer, long l) { // // } // }); } else { Log.e("--->", "discoverViewInit: discover not get face and nickname", null); } // 朋友圈的列表 momentList = findViewById(R.id.momentlist); initMomentList(); momentList.setLayoutManager(new LinearLayoutManager(this)); momentListAdapter = new MomentListAdapter(this, moments, getLayoutInflater()); momentList.setAdapter(momentListAdapter); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.newedit: newEditFun(); break; default: break; } } private void newEditFun(){ Intent intent = new Intent(this, EditNewMomentActivity.class); getParent().startActivityForResult(intent, 1); //startActivity(intent); } // //在AppMainActivity里面的onActivityResult函数里面处理结果 // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // Log.e("--->", "onActivityResult: hello", null); // switch (resultCode) { // case 1: // Moment m = (Moment) data.getSerializableExtra("newMoment"); // Log.e("--->", "onActivityResult: "+m.getName(), null); // momentListAdapter.addItem(0, m); // break; // // default: break; // } // } public void inittheme() { Cursor cursor = dbread.query("Setting", null, null, null, null,null, null); cursor.moveToNext(); set.setTheme(cursor.getInt(cursor.getColumnIndex("theme"))); switch (set.getTheme()) { case 0: setTheme(R.style.GreenAppTheme); break; case 1: setTheme(R.style.BlueAppTheme); break; case 2: setTheme(R.style.PurpleAppTheme); break; case 3: setTheme(R.style.BronzeAppTheme); break; case 4: setTheme(R.style.PinkAppTheme); break; case 5: setTheme(R.style.OrAppTheme); break; default: break; } cursor.close(); } public void initMomentList() { Moment m; ArrayList<Picture> p; //刘强东 m = new Moment(); m.setFace("http://5b0988e595225.cdn.sohucs.com/images/20180904/a5501e9c02bf44a89ec9474d18e17f95.jpeg"); m.setName("刘强东"); m.setContent("脱下西裤,套上囚服,奥利给!"); p = new ArrayList<>(); p.add(new Picture("https://wx4.sinaimg.cn/large/006fT3Elgy1fuwksvst0sj30l90byqck.jpg")); p.add(new Picture("http://5b0988e595225.cdn.sohucs.com/images/20180904/a5501e9c02bf44a89ec9474d18e17f95.jpeg")); m.setPictures(p); moments.add(m); //马云 m = new Moment(); m.setFace("http://n.sinaimg.cn/finance/transform/20161231/ypok-fxzencv2934675.jpg"); m.setName("马云"); m.setContent("我对钱没有兴趣!"); p = new ArrayList<>(); p.add(new Picture("http://i5.hexun.com/2018-10-10/194692903.jpg")); p.add(new Picture("http://i8.hexun.com/2018-10-10/194692904.jpg")); p.add(new Picture("http://i3.hexun.com/2018-10-10/194692905.jpg")); m.setPictures(p); moments.add(m); //马化腾坐公交 m = new Moment(); m.setFace("http://photocdn.sohu.com/20131128/Img390959345.jpg"); m.setName("马化腾"); m.setContent("今天穷到坐公交了"); p = new ArrayList<>(); p.add(new Picture("http://img.chenpe.com/8d/cc/a5/2b/8dcca52b982ffcae2d299453248f2b78size_580x370_size.jpg")); p.add(new Picture("http://5b0988e595225.cdn.sohucs.com/images/20170914/08bcb01ba73647ad9145a76cbac9cb8a.jpg")); m.setPictures(p); moments.add(m); //李彦宏 m = new Moment(); m.setFace("http://www.sx.chinanews.com/news/2011/0427/U71P8T1D36722F5DT20110427165123.jpg"); m.setName("李彦宏"); m.setContent("What's your problem?"); p = new ArrayList<>(); p.add(new Picture("https://wx4.sinaimg.cn/mw690/007MC2Nagy1g4nn901xx2j306b05lt8o.jpg")); m.setPictures(p); moments.add(m); //蔡徐坤 m = new Moment(); m.setFace("http://5b0988e595225.cdn.sohucs.com/q_70,c_zoom,w_640/images/20190418/24e27baac15748759f2080aadbd99cc8.jpeg"); m.setName("蔡徐坤(篮球之神)"); m.setContent("欧文都学不会我的运球, 哦哦哦哦哦~"); p = new ArrayList<>(); p.add(new Picture("http://n.sinaimg.cn/front/253/w619h434/20190403/5kjK-hvcmeuy0880454.jpg")); p.add(new Picture("http://n.sinaimg.cn/front/231/w607h424/20190403/m0bK-hvcmeuy0880599.jpg")); p.add(new Picture("http://n.sinaimg.cn/sinacn09/300/w440h660/20180416/ce89-fzcyxmv2121495.jpg")); m.setPictures(p); moments.add(m); //PDD m = new Moment(); m.setFace("http://img1.dwstatic.com/lol/1701/348197040731/348197144646.jpeg"); m.setName("PDD"); m.setContent("英雄联盟全球总决赛两届的FMVP都是从我这里出去的,很多人都说我被Ning和Tian演了,开玩笑我可是PDD,谁能演我,只有李现能演我。有人说韩商言的原型是我,我去专门看了那部剧,确实挺像的,都创办了俱乐部,都没有夺冠,都是冷酷的帅哥。"); p = new ArrayList<>(); p.add(new Picture("http://img1.gtimg.com/gamezone/pics/hv1/78/82/2222/144506538.png")); p.add(new Picture("http://img1.gtimg.com/gamezone/pics/hv1/77/82/2222/144506537.png")); p.add(new Picture("https://04imgmini.eastday.com/mobile/20191224/20191224001414_819daf8f344b29ee65d47b732abbcbe4_1.jpeg")); m.setPictures(p); moments.add(m); } }
false
2,855
6
3,419
6
3,441
5
3,419
6
3,921
10
false
false
false
false
false
true
37605_3
package com.example.a84121.bao_diet; /** * Created by 84121 on 2019/11/23. */ import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import static android.app.Activity.RESULT_OK; /** * Created by 黎活宝 on 2019/11/20. */ public class Fragment3 extends Fragment { MyApplication application; private View view; private RecyclerView recyclerView; // private List<Javabean> data =new ArrayList<>(); private BeautyAdapter adapter; private int flag=0; StaggeredGridLayoutManager recyclerViewLayoutManager; /**加载图片前的时间**/ Long mLoadStart = 0L; /**加载图片完成的时间**/ Long mLoadEndt = 0L; /**读取进度**/ public final static int LOAD_PROGRESS =0; private SQLiteDatabase database; ArrayList<Javabean> CITY; SwipeRefreshLayout swipeRefreshView; /**标志读取进度结束**/ public final static int LOAD_COMPLETE = 1; // Handler handler = new Handler(){ // public void handleMessage(Message msg){ // switch(msg.what){ // case LOAD_PROGRESS: // break; // case LOAD_COMPLETE: // data = (List<Javabean>) msg.obj; // break; // } // super.handleMessage(msg); // } // }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { application = (MyApplication)getActivity().getApplication(); view = inflater.inflate(R.layout.community_page, container, false); swipeRefreshView = (SwipeRefreshLayout)view.findViewById(R.id.refresh); // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色,因为都是int值容易搞混 // 设置下拉进度的背景颜色,默认就是白色的 swipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white); // 设置下拉进度的主题颜色 swipeRefreshView.setColorSchemeResources(R.color.round_green, R.color.colorPrimary, R.color.colorPrimaryDark); // LoadImage(); database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null); getCity(); // initRecyclerView(); database.close(); // initData(); initRecyclerView(); shuaxin(); return view; } private void getCity() { Javabean beauty; Cursor cur = database.rawQuery("SELECT * FROM community2", null); if (cur != null) { if (cur.moveToFirst()) { do { String user = cur.getString(cur.getColumnIndex("user")); String text = cur.getString(cur.getColumnIndex("community_text")); String id = cur.getString(cur.getColumnIndex("head")); String pic = cur.getString(cur.getColumnIndex("community_pic")); Log.d("获取数据",pic); Log.d("获取数据",id); int pic_int=getImageResourceId(pic); int id_int=getImageResourceId(id); beauty = new Javabean(text, pic_int,id_int, user); // beauty = new Javabean("嘿嘿真好吃", R.drawable.food3, R.drawable.xiaozhu, "佩奇"); Log.d("beauty的值",beauty.output()); application.data.add(0, beauty); // taxicity.add(city); } while (cur.moveToNext()); } // return taxicity; } } public void shuaxin(){ final Handler handler = new Handler(); // 下拉时触发SwipeRefreshLayout的下拉动画,动画完毕之后就会回调这个方法 swipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Log.d("再刷新哦","成功"); // 开始刷新,设置当前为刷新状态 //swipeRefreshLayout.setRefreshing(true); // 这里是主线程 // 一些比较耗时的操作,比如联网获取数据,需要放到子线程去执行 new Thread(){ @Override public void run () { super.run(); //同步加载网络数据 //加载数据 完毕后 关闭刷新状态 切回主线程 handler.postDelayed(new Runnable() { @Override public void run() { Log.d("再刷新哦111","成功"); database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null); application.data.clear(); getCity(); // initRecyclerView(); database.close(); initRecyclerView(); // 加载完数据设置为不刷新状态,将下拉进度收起来 swipeRefreshView.setRefreshing(false); } }, 100); } }.start(); } }); } public int getImageResourceId(String name) { R.drawable drawables=new R.drawable(); //默认的id int resId=0x7f02000b; try { //根据字符串字段名,取字段//根据资源的ID的变量名获得Field的对象,使用反射机制来实现的 java.lang.reflect.Field field=R.drawable.class.getField(name); //取值 resId=(Integer)field.get(drawables); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return resId; } @Override public void onDestroy() { super.onDestroy(); application.data.clear(); application.data = null; } void initData() { Javabean beauty; beauty = new Javabean("今天的午餐今天的午餐今天的午餐今天不当回事酒吧的实打阿萨德擦拭成大事的西安市西安市西安市实的国语歌对于诶按对的hiU盾和的呀UI大UI等于IE有多少嘎达打他答复他是否他对她上大学阿方大同是飞机向对方水电费他发烧的风雅的答复他衣服也挺帅的反弹撒地方鱼头豆腐大师多喜爱是的擦似懂非懂完全的午餐今天的午餐今天的午餐今天的午餐今天的午餐今天的午餐", R.drawable.food4, R.drawable.wwb, "天线宝宝"); application.data.add(beauty); beauty = new Javabean("嘿嘿真好吃", R.drawable.food3, R.drawable.xiaozhu, "佩奇"); application.data.add(beauty); beauty = new Javabean("姐姐做的早餐", R.drawable.jianshen, R.drawable.xiaozhu2, "乔治"); application.data.add(beauty); beauty = new Javabean("每日分享", R.drawable.food2, R.drawable.wwb, "天线宝宝"); application.data.add(beauty); beauty = new Javabean("嘿嘿", R.drawable.food1, R.drawable.star, "派大星"); application.data.add(beauty); beauty = new Javabean("马甲线练成计划", R.drawable.majiaxian, R.drawable.xiaozhu, "佩奇"); application.data.add(beauty); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } private void initRecyclerView() { recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); recyclerViewLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recyclerView.setLayoutManager(recyclerViewLayoutManager); adapter = new BeautyAdapter(application.data, getActivity()); //设置adapter recyclerView.setAdapter(adapter); adapter.setOnItemClickListener(new BeautyAdapter.OnItemClickListener() { @Override public void OnItemClick(View view, Javabean data) { //此处进行监听事件的业务处理 Log.d("Fra","这zale"); Log.d("点赞数",String.valueOf(data.like)); // Toast.makeText(getActivity(), data.getName(), Toast.LENGTH_SHORT).show(); // Intent intent = new Intent(getActivity(), CommunityDetail.class); Intent intent = new Intent(getActivity(), CommunityDetail.class); intent.putExtra("position",recyclerView.getChildAdapterPosition(view)); intent.putExtra("data", data); Log.d("Fra","这没问题"); startActivityForResult(intent,1); } }); } public void onActivityResult(int requestCode, int resultCode, Intent thisdata) { switch (requestCode){ case 1: if(resultCode==RESULT_OK){ boolean likeFlag = thisdata.getBooleanExtra("likeFlag",false); boolean collectFlag = thisdata.getBooleanExtra("collectFlag",false); int position=thisdata.getIntExtra("position",-1); Log.d("位置",String.valueOf(position)); Javabean p=application.data.get(position); if(likeFlag)p.addLike(); if(collectFlag)p.addCollect(); } break; default: } } }
android-app-development-course/2019_a29_DIET
app/src/main/java/com/example/a84121/bao_diet/Fragment3.java
2,520
/**加载图片前的时间**/
block_comment
zh-cn
package com.example.a84121.bao_diet; /** * Created by 84121 on 2019/11/23. */ import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import static android.app.Activity.RESULT_OK; /** * Created by 黎活宝 on 2019/11/20. */ public class Fragment3 extends Fragment { MyApplication application; private View view; private RecyclerView recyclerView; // private List<Javabean> data =new ArrayList<>(); private BeautyAdapter adapter; private int flag=0; StaggeredGridLayoutManager recyclerViewLayoutManager; /**加载图 <SUF>*/ Long mLoadStart = 0L; /**加载图片完成的时间**/ Long mLoadEndt = 0L; /**读取进度**/ public final static int LOAD_PROGRESS =0; private SQLiteDatabase database; ArrayList<Javabean> CITY; SwipeRefreshLayout swipeRefreshView; /**标志读取进度结束**/ public final static int LOAD_COMPLETE = 1; // Handler handler = new Handler(){ // public void handleMessage(Message msg){ // switch(msg.what){ // case LOAD_PROGRESS: // break; // case LOAD_COMPLETE: // data = (List<Javabean>) msg.obj; // break; // } // super.handleMessage(msg); // } // }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { application = (MyApplication)getActivity().getApplication(); view = inflater.inflate(R.layout.community_page, container, false); swipeRefreshView = (SwipeRefreshLayout)view.findViewById(R.id.refresh); // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色,因为都是int值容易搞混 // 设置下拉进度的背景颜色,默认就是白色的 swipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white); // 设置下拉进度的主题颜色 swipeRefreshView.setColorSchemeResources(R.color.round_green, R.color.colorPrimary, R.color.colorPrimaryDark); // LoadImage(); database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null); getCity(); // initRecyclerView(); database.close(); // initData(); initRecyclerView(); shuaxin(); return view; } private void getCity() { Javabean beauty; Cursor cur = database.rawQuery("SELECT * FROM community2", null); if (cur != null) { if (cur.moveToFirst()) { do { String user = cur.getString(cur.getColumnIndex("user")); String text = cur.getString(cur.getColumnIndex("community_text")); String id = cur.getString(cur.getColumnIndex("head")); String pic = cur.getString(cur.getColumnIndex("community_pic")); Log.d("获取数据",pic); Log.d("获取数据",id); int pic_int=getImageResourceId(pic); int id_int=getImageResourceId(id); beauty = new Javabean(text, pic_int,id_int, user); // beauty = new Javabean("嘿嘿真好吃", R.drawable.food3, R.drawable.xiaozhu, "佩奇"); Log.d("beauty的值",beauty.output()); application.data.add(0, beauty); // taxicity.add(city); } while (cur.moveToNext()); } // return taxicity; } } public void shuaxin(){ final Handler handler = new Handler(); // 下拉时触发SwipeRefreshLayout的下拉动画,动画完毕之后就会回调这个方法 swipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Log.d("再刷新哦","成功"); // 开始刷新,设置当前为刷新状态 //swipeRefreshLayout.setRefreshing(true); // 这里是主线程 // 一些比较耗时的操作,比如联网获取数据,需要放到子线程去执行 new Thread(){ @Override public void run () { super.run(); //同步加载网络数据 //加载数据 完毕后 关闭刷新状态 切回主线程 handler.postDelayed(new Runnable() { @Override public void run() { Log.d("再刷新哦111","成功"); database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/" + DBManager.DB_NAME, null); application.data.clear(); getCity(); // initRecyclerView(); database.close(); initRecyclerView(); // 加载完数据设置为不刷新状态,将下拉进度收起来 swipeRefreshView.setRefreshing(false); } }, 100); } }.start(); } }); } public int getImageResourceId(String name) { R.drawable drawables=new R.drawable(); //默认的id int resId=0x7f02000b; try { //根据字符串字段名,取字段//根据资源的ID的变量名获得Field的对象,使用反射机制来实现的 java.lang.reflect.Field field=R.drawable.class.getField(name); //取值 resId=(Integer)field.get(drawables); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return resId; } @Override public void onDestroy() { super.onDestroy(); application.data.clear(); application.data = null; } void initData() { Javabean beauty; beauty = new Javabean("今天的午餐今天的午餐今天的午餐今天不当回事酒吧的实打阿萨德擦拭成大事的西安市西安市西安市实的国语歌对于诶按对的hiU盾和的呀UI大UI等于IE有多少嘎达打他答复他是否他对她上大学阿方大同是飞机向对方水电费他发烧的风雅的答复他衣服也挺帅的反弹撒地方鱼头豆腐大师多喜爱是的擦似懂非懂完全的午餐今天的午餐今天的午餐今天的午餐今天的午餐今天的午餐", R.drawable.food4, R.drawable.wwb, "天线宝宝"); application.data.add(beauty); beauty = new Javabean("嘿嘿真好吃", R.drawable.food3, R.drawable.xiaozhu, "佩奇"); application.data.add(beauty); beauty = new Javabean("姐姐做的早餐", R.drawable.jianshen, R.drawable.xiaozhu2, "乔治"); application.data.add(beauty); beauty = new Javabean("每日分享", R.drawable.food2, R.drawable.wwb, "天线宝宝"); application.data.add(beauty); beauty = new Javabean("嘿嘿", R.drawable.food1, R.drawable.star, "派大星"); application.data.add(beauty); beauty = new Javabean("马甲线练成计划", R.drawable.majiaxian, R.drawable.xiaozhu, "佩奇"); application.data.add(beauty); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } private void initRecyclerView() { recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); recyclerViewLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recyclerView.setLayoutManager(recyclerViewLayoutManager); adapter = new BeautyAdapter(application.data, getActivity()); //设置adapter recyclerView.setAdapter(adapter); adapter.setOnItemClickListener(new BeautyAdapter.OnItemClickListener() { @Override public void OnItemClick(View view, Javabean data) { //此处进行监听事件的业务处理 Log.d("Fra","这zale"); Log.d("点赞数",String.valueOf(data.like)); // Toast.makeText(getActivity(), data.getName(), Toast.LENGTH_SHORT).show(); // Intent intent = new Intent(getActivity(), CommunityDetail.class); Intent intent = new Intent(getActivity(), CommunityDetail.class); intent.putExtra("position",recyclerView.getChildAdapterPosition(view)); intent.putExtra("data", data); Log.d("Fra","这没问题"); startActivityForResult(intent,1); } }); } public void onActivityResult(int requestCode, int resultCode, Intent thisdata) { switch (requestCode){ case 1: if(resultCode==RESULT_OK){ boolean likeFlag = thisdata.getBooleanExtra("likeFlag",false); boolean collectFlag = thisdata.getBooleanExtra("collectFlag",false); int position=thisdata.getIntExtra("position",-1); Log.d("位置",String.valueOf(position)); Javabean p=application.data.get(position); if(likeFlag)p.addLike(); if(collectFlag)p.addCollect(); } break; default: } } }
false
2,021
7
2,520
6
2,445
6
2,520
6
3,180
11
false
false
false
false
false
true
15009_2
package com.cjj; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.View; /** * Created by cjj on 2016/2/20. */ public class SunFaceView extends View { private static final String Tag = SunFaceView.class.getSimpleName(); private static final int DEFAULT_SUN_RADIUS = 12;//太阳的半径 private static final int DEFAULT_EYES_RADIUS = 2;//眼睛的半径 private int mHeight, mWidth; private Paint mCirclePaint;//画圆的画笔 private int mSunRadius;//sun radius private int mEyesRadius = DEFAULT_EYES_RADIUS; private Rect debugRect; private RectF mouthRect; private int mSunColor;//sun color private boolean isDrawFace = true; private int mouthStro = 3; public SunFaceView(Context context) { this(context, null); } public SunFaceView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SunFaceView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { Log.i(Tag, "init"); mSunRadius = changeDp(DEFAULT_SUN_RADIUS); mEyesRadius = changeDp(DEFAULT_EYES_RADIUS); //圆的配置 mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(Color.RED); mCirclePaint.setStyle(Paint.Style.FILL); debugRect = new Rect(); mouthRect = new RectF(); } /** * 设置太阳半径 * * @param sunRadius */ public void setSunRadius(int sunRadius) { mSunRadius = changeDp(sunRadius); invalidate(); } /** * 设置眼睛大小 * @param eyesSize */ public void setEyesSize(int eyesSize){ mEyesRadius = changeDp(eyesSize); invalidate(); } /** * 设置嘴巴粗细 * @param mouthStro */ public void setMouthStro(int mouthStro){ this.mouthStro = mouthStro; invalidate(); } /** * 刷新用的效果 * @param sunRadius * @param per */ public void setPerView(int sunRadius ,float per){ sunRadius = changeDp(sunRadius); if(per>=0.8){ isDrawFace = true; }else { isDrawFace = false; } per = Math.min(per,1); float tempRadius = sunRadius*per; mSunRadius = (int) tempRadius; mCirclePaint.setAlpha((int)per*255); invalidate(); } /** * 设置sun color * * @param sunColor */ public void setSunColor(int sunColor) { mSunColor = sunColor; invalidate(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); Log.i(Tag, "w---->" + w + " ------- h----->" + h); mWidth = w; mHeight = h; debugRect.left = mWidth / 2 - mSunRadius; debugRect.right = mWidth / 2 + mSunRadius; debugRect.top = mHeight / 2 - mSunRadius; debugRect.bottom = mHeight / 2 + mSunRadius; mouthRect.left = mWidth / 2 - mSunRadius / 2; mouthRect.right = mWidth / 2 + mSunRadius / 2; mouthRect.top = mHeight / 2 - mSunRadius / 2; mouthRect.bottom = mHeight / 2 + mSunRadius / 2; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.i(Tag, "onMeasure"); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else { width = mSunRadius * 2 + getPaddingRight() + getPaddingLeft(); } if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else { height = mSunRadius * 2 + getPaddingTop() + getPaddingBottom(); } setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawCircle(canvas); mCirclePaint.setStyle(Paint.Style.STROKE); // canvas.drawRect(debugRect, mCirclePaint); // canvas.drawRect(mouthRect, mCirclePaint); } private void drawCircle(Canvas canvas) { mCirclePaint.setColor(mSunColor); mCirclePaint.setStyle(Paint.Style.FILL); canvas.drawCircle(mWidth / 2, mHeight / 2, mSunRadius, mCirclePaint); mCirclePaint.setColor(Color.WHITE); if(isDrawFace) { canvas.save(); canvas.drawCircle(mWidth / 2 - mSunRadius / 2 + mEyesRadius, mHeight / 2 - mSunRadius / 2 + mEyesRadius, mEyesRadius, mCirclePaint); canvas.drawCircle(mWidth / 2 + mSunRadius / 2 - mEyesRadius, mHeight / 2 - mSunRadius / 2 + mEyesRadius, mEyesRadius, mCirclePaint); mCirclePaint.setStyle(Paint.Style.STROKE); mCirclePaint.setStrokeWidth(mouthStro); canvas.drawArc(mouthRect, 20, 140, false, mCirclePaint); canvas.restore(); } } public int changeDp(int value) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics()); } }
android-cjj/Android-MaterialRefreshLayout
library/src/main/java/com/cjj/SunFaceView.java
1,562
//眼睛的半径
line_comment
zh-cn
package com.cjj; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.View; /** * Created by cjj on 2016/2/20. */ public class SunFaceView extends View { private static final String Tag = SunFaceView.class.getSimpleName(); private static final int DEFAULT_SUN_RADIUS = 12;//太阳的半径 private static final int DEFAULT_EYES_RADIUS = 2;//眼睛 <SUF> private int mHeight, mWidth; private Paint mCirclePaint;//画圆的画笔 private int mSunRadius;//sun radius private int mEyesRadius = DEFAULT_EYES_RADIUS; private Rect debugRect; private RectF mouthRect; private int mSunColor;//sun color private boolean isDrawFace = true; private int mouthStro = 3; public SunFaceView(Context context) { this(context, null); } public SunFaceView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SunFaceView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { Log.i(Tag, "init"); mSunRadius = changeDp(DEFAULT_SUN_RADIUS); mEyesRadius = changeDp(DEFAULT_EYES_RADIUS); //圆的配置 mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(Color.RED); mCirclePaint.setStyle(Paint.Style.FILL); debugRect = new Rect(); mouthRect = new RectF(); } /** * 设置太阳半径 * * @param sunRadius */ public void setSunRadius(int sunRadius) { mSunRadius = changeDp(sunRadius); invalidate(); } /** * 设置眼睛大小 * @param eyesSize */ public void setEyesSize(int eyesSize){ mEyesRadius = changeDp(eyesSize); invalidate(); } /** * 设置嘴巴粗细 * @param mouthStro */ public void setMouthStro(int mouthStro){ this.mouthStro = mouthStro; invalidate(); } /** * 刷新用的效果 * @param sunRadius * @param per */ public void setPerView(int sunRadius ,float per){ sunRadius = changeDp(sunRadius); if(per>=0.8){ isDrawFace = true; }else { isDrawFace = false; } per = Math.min(per,1); float tempRadius = sunRadius*per; mSunRadius = (int) tempRadius; mCirclePaint.setAlpha((int)per*255); invalidate(); } /** * 设置sun color * * @param sunColor */ public void setSunColor(int sunColor) { mSunColor = sunColor; invalidate(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); Log.i(Tag, "w---->" + w + " ------- h----->" + h); mWidth = w; mHeight = h; debugRect.left = mWidth / 2 - mSunRadius; debugRect.right = mWidth / 2 + mSunRadius; debugRect.top = mHeight / 2 - mSunRadius; debugRect.bottom = mHeight / 2 + mSunRadius; mouthRect.left = mWidth / 2 - mSunRadius / 2; mouthRect.right = mWidth / 2 + mSunRadius / 2; mouthRect.top = mHeight / 2 - mSunRadius / 2; mouthRect.bottom = mHeight / 2 + mSunRadius / 2; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.i(Tag, "onMeasure"); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else { width = mSunRadius * 2 + getPaddingRight() + getPaddingLeft(); } if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else { height = mSunRadius * 2 + getPaddingTop() + getPaddingBottom(); } setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawCircle(canvas); mCirclePaint.setStyle(Paint.Style.STROKE); // canvas.drawRect(debugRect, mCirclePaint); // canvas.drawRect(mouthRect, mCirclePaint); } private void drawCircle(Canvas canvas) { mCirclePaint.setColor(mSunColor); mCirclePaint.setStyle(Paint.Style.FILL); canvas.drawCircle(mWidth / 2, mHeight / 2, mSunRadius, mCirclePaint); mCirclePaint.setColor(Color.WHITE); if(isDrawFace) { canvas.save(); canvas.drawCircle(mWidth / 2 - mSunRadius / 2 + mEyesRadius, mHeight / 2 - mSunRadius / 2 + mEyesRadius, mEyesRadius, mCirclePaint); canvas.drawCircle(mWidth / 2 + mSunRadius / 2 - mEyesRadius, mHeight / 2 - mSunRadius / 2 + mEyesRadius, mEyesRadius, mCirclePaint); mCirclePaint.setStyle(Paint.Style.STROKE); mCirclePaint.setStrokeWidth(mouthStro); canvas.drawArc(mouthRect, 20, 140, false, mCirclePaint); canvas.restore(); } } public int changeDp(int value) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics()); } }
false
1,402
5
1,563
7
1,641
5
1,562
7
1,912
14
false
false
false
false
false
true
28052_1
package com.cjj.bb.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.cjj.bb.fragment.BangumiFragment; import com.cjj.bb.fragment.DonghuaFragment; import com.cjj.bb.fragment.FragmentLogin; import com.cjj.bb.fragment.FramentTime; import com.cjj.bb.fragment.GamesCenterFragment; import com.cjj.bb.fragment.HomePageFragment2; import com.cjj.bb.fragment.SubareaFragment; /** * FragmentPager适配器 * * @author wwj_748 * @2014/8/9 */ public class MainTabAdapter extends FragmentPagerAdapter { // 内容标题 public static final String[] DONG_HUA_TITLE = new String[] { "个人中心","首页", "分区导航", "新番专题", "游戏中心","放松时间表" }; public HomePageFragment2 homepage = new HomePageFragment2(); public SubareaFragment subarea = new SubareaFragment(); public MainTabAdapter(FragmentManager fm) { super(fm); // TODO Auto-generated constructor stub } // 获取项 @Override public Fragment getItem(int position) { System.out.println("Fragment position:" + position); switch (position) { case 0: return new FragmentLogin(); case 1: return homepage; case 2: return subarea; case 3: return new BangumiFragment(); case 4: return new GamesCenterFragment(); case 5: return new FramentTime(); default: return new DonghuaFragment(33); } // MainFragment fragment = new MainFragment(position); // return fragment; } @Override public CharSequence getPageTitle(int position) { // 返回页面标题 return DONG_HUA_TITLE[position % DONG_HUA_TITLE.length].toUpperCase(); } @Override public int getCount() { // 页面个数 return DONG_HUA_TITLE.length; } }
android-cjj/BiliClient
app/src/main/java/com/cjj/bb/adapter/MainTabAdapter.java
565
// 内容标题
line_comment
zh-cn
package com.cjj.bb.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.cjj.bb.fragment.BangumiFragment; import com.cjj.bb.fragment.DonghuaFragment; import com.cjj.bb.fragment.FragmentLogin; import com.cjj.bb.fragment.FramentTime; import com.cjj.bb.fragment.GamesCenterFragment; import com.cjj.bb.fragment.HomePageFragment2; import com.cjj.bb.fragment.SubareaFragment; /** * FragmentPager适配器 * * @author wwj_748 * @2014/8/9 */ public class MainTabAdapter extends FragmentPagerAdapter { // 内容 <SUF> public static final String[] DONG_HUA_TITLE = new String[] { "个人中心","首页", "分区导航", "新番专题", "游戏中心","放松时间表" }; public HomePageFragment2 homepage = new HomePageFragment2(); public SubareaFragment subarea = new SubareaFragment(); public MainTabAdapter(FragmentManager fm) { super(fm); // TODO Auto-generated constructor stub } // 获取项 @Override public Fragment getItem(int position) { System.out.println("Fragment position:" + position); switch (position) { case 0: return new FragmentLogin(); case 1: return homepage; case 2: return subarea; case 3: return new BangumiFragment(); case 4: return new GamesCenterFragment(); case 5: return new FramentTime(); default: return new DonghuaFragment(33); } // MainFragment fragment = new MainFragment(position); // return fragment; } @Override public CharSequence getPageTitle(int position) { // 返回页面标题 return DONG_HUA_TITLE[position % DONG_HUA_TITLE.length].toUpperCase(); } @Override public int getCount() { // 页面个数 return DONG_HUA_TITLE.length; } }
false
445
5
565
4
552
3
565
4
662
6
false
false
false
false
false
true
59312_0
package com.cjj.sva.utils; import android.util.Log; /** * 这是一个神奇的类,神奇就是它可以打log,而你,不可以打我! * */ public final class LogHelper { public static final boolean mIsDebugMode = true;// 获取堆栈信息会影响性能,发布应用时记得关闭DebugMode private static final String TAG = "JJSearchView"; private static final String CLASS_METHOD_LINE_FORMAT = "%s.%s()_%s"; public static void trace(String str) { if (mIsDebugMode) { StackTraceElement traceElement = Thread.currentThread() .getStackTrace()[3];// 从堆栈信息中获取当前被调用的方法信息 String className = traceElement.getClassName(); className = className.substring(className.lastIndexOf(".") + 1); String logText = String.format(CLASS_METHOD_LINE_FORMAT, className, traceElement.getMethodName(), String.valueOf(traceElement.getLineNumber())); Log.i(TAG, logText + "->" + str);// 打印Log } } public static void printStackTrace(Throwable throwable) { if (mIsDebugMode) { Log.w(TAG, "", throwable); } } }
android-cjj/JJSearchViewAnim
library/src/main/java/com/cjj/sva/utils/LogHelper.java
293
/** * 这是一个神奇的类,神奇就是它可以打log,而你,不可以打我! * */
block_comment
zh-cn
package com.cjj.sva.utils; import android.util.Log; /** * 这是一 <SUF>*/ public final class LogHelper { public static final boolean mIsDebugMode = true;// 获取堆栈信息会影响性能,发布应用时记得关闭DebugMode private static final String TAG = "JJSearchView"; private static final String CLASS_METHOD_LINE_FORMAT = "%s.%s()_%s"; public static void trace(String str) { if (mIsDebugMode) { StackTraceElement traceElement = Thread.currentThread() .getStackTrace()[3];// 从堆栈信息中获取当前被调用的方法信息 String className = traceElement.getClassName(); className = className.substring(className.lastIndexOf(".") + 1); String logText = String.format(CLASS_METHOD_LINE_FORMAT, className, traceElement.getMethodName(), String.valueOf(traceElement.getLineNumber())); Log.i(TAG, logText + "->" + str);// 打印Log } } public static void printStackTrace(Throwable throwable) { if (mIsDebugMode) { Log.w(TAG, "", throwable); } } }
false
255
25
293
31
302
27
293
31
387
38
false
false
false
false
false
true
7533_0
package com.rengwuxian.daggerdemo.model; import java.util.Random; import javax.inject.Inject; import javax.inject.Singleton; /** * 老板:要求每个员工写够一定的代码 */ @Singleton public class Boss { private static final int GOAL = 10; private static final String[] ALTERNATIVE_NAMES = {"Jeff", "老王", "扔物线"}; // 老板的姓名将从三个备选中选出 public String name; @Inject public Boss() { name = ALTERNATIVE_NAMES[new Random().nextInt(3)]; // 随机选出一个名字 } /** * 老板查看程序员写的代码行数后,给出评价 * @param codeCount 代码行数 * @return 老板的评价 */ public String check(int codeCount) { if (codeCount < GOAL) { return String.format("老板%s:快点写!不写够%s行代码不准下班!", name, GOAL); } else { return String.format("老板%s:嗯,不错,下班吧!", name); } } }
android-cn/android-open-project-demo
dagger-demo/app/src/main/java/com/rengwuxian/daggerdemo/model/Boss.java
290
/** * 老板:要求每个员工写够一定的代码 */
block_comment
zh-cn
package com.rengwuxian.daggerdemo.model; import java.util.Random; import javax.inject.Inject; import javax.inject.Singleton; /** * 老板: <SUF>*/ @Singleton public class Boss { private static final int GOAL = 10; private static final String[] ALTERNATIVE_NAMES = {"Jeff", "老王", "扔物线"}; // 老板的姓名将从三个备选中选出 public String name; @Inject public Boss() { name = ALTERNATIVE_NAMES[new Random().nextInt(3)]; // 随机选出一个名字 } /** * 老板查看程序员写的代码行数后,给出评价 * @param codeCount 代码行数 * @return 老板的评价 */ public String check(int codeCount) { if (codeCount < GOAL) { return String.format("老板%s:快点写!不写够%s行代码不准下班!", name, GOAL); } else { return String.format("老板%s:嗯,不错,下班吧!", name); } } }
false
254
16
290
18
275
15
290
18
379
26
false
false
false
false
false
true
29837_2
package com.wanjian.demo; import android.app.Application; import android.content.Intent; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.widget.Toast; import com.wanjian.cockroach.Cockroach; import com.wanjian.cockroach.ExceptionHandler; import com.wanjian.demo.support.CrashLog; import com.wanjian.demo.support.DebugSafeModeTipActivity; import com.wanjian.demo.support.DebugSafeModeUI; /** * Created by wanjian on 2018/5/19. */ public class App extends Application { @Override public void onCreate() { super.onCreate(); install(); } private void install() { final Thread.UncaughtExceptionHandler sysExcepHandler = Thread.getDefaultUncaughtExceptionHandler(); final Toast toast = Toast.makeText(this, "", Toast.LENGTH_SHORT); DebugSafeModeUI.init(this); Cockroach.install(this, new ExceptionHandler() { @Override protected void onUncaughtExceptionHappened(Thread thread, Throwable throwable) { Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:" + thread + "<---", throwable); CrashLog.saveCrashLog(getApplicationContext(), throwable); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { toast.setText(R.string.safe_mode_excep_tips); toast.show(); } }); } @Override protected void onBandageExceptionHappened(Throwable throwable) { throwable.printStackTrace();//打印警告级别log,该throwable可能是最开始的bug导致的,无需关心 toast.setText("Cockroach Worked"); toast.show(); } @Override protected void onEnterSafeMode() { int tips = R.string.safe_mode_tips; Toast.makeText(App.this, getResources().getString(tips), Toast.LENGTH_LONG).show(); DebugSafeModeUI.showSafeModeUI(); if (BuildConfig.DEBUG) { Intent intent = new Intent(App.this, DebugSafeModeTipActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } } @Override protected void onMayBeBlackScreen(Throwable e) { Thread thread = Looper.getMainLooper().getThread(); Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:" + thread + "<---", e); //黑屏时建议直接杀死app sysExcepHandler.uncaughtException(thread, new RuntimeException("black screen")); } }); } }
android-notes/Cockroach
demo/src/main/java/com/wanjian/demo/App.java
630
//黑屏时建议直接杀死app
line_comment
zh-cn
package com.wanjian.demo; import android.app.Application; import android.content.Intent; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.widget.Toast; import com.wanjian.cockroach.Cockroach; import com.wanjian.cockroach.ExceptionHandler; import com.wanjian.demo.support.CrashLog; import com.wanjian.demo.support.DebugSafeModeTipActivity; import com.wanjian.demo.support.DebugSafeModeUI; /** * Created by wanjian on 2018/5/19. */ public class App extends Application { @Override public void onCreate() { super.onCreate(); install(); } private void install() { final Thread.UncaughtExceptionHandler sysExcepHandler = Thread.getDefaultUncaughtExceptionHandler(); final Toast toast = Toast.makeText(this, "", Toast.LENGTH_SHORT); DebugSafeModeUI.init(this); Cockroach.install(this, new ExceptionHandler() { @Override protected void onUncaughtExceptionHappened(Thread thread, Throwable throwable) { Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:" + thread + "<---", throwable); CrashLog.saveCrashLog(getApplicationContext(), throwable); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { toast.setText(R.string.safe_mode_excep_tips); toast.show(); } }); } @Override protected void onBandageExceptionHappened(Throwable throwable) { throwable.printStackTrace();//打印警告级别log,该throwable可能是最开始的bug导致的,无需关心 toast.setText("Cockroach Worked"); toast.show(); } @Override protected void onEnterSafeMode() { int tips = R.string.safe_mode_tips; Toast.makeText(App.this, getResources().getString(tips), Toast.LENGTH_LONG).show(); DebugSafeModeUI.showSafeModeUI(); if (BuildConfig.DEBUG) { Intent intent = new Intent(App.this, DebugSafeModeTipActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } } @Override protected void onMayBeBlackScreen(Throwable e) { Thread thread = Looper.getMainLooper().getThread(); Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:" + thread + "<---", e); //黑屏 <SUF> sysExcepHandler.uncaughtException(thread, new RuntimeException("black screen")); } }); } }
false
540
8
630
9
658
8
630
9
787
19
false
false
false
false
false
true
66708_9
package com.wanjian.scrollscreenshots; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by wanjian on 2018/1/3. */ public class AutoScreenShotsAct extends Activity { private ListView listView; private ImageView img; private ViewGroup container; private List<Bitmap> bitmaps = new ArrayList<>(); private boolean isScreenShots = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auto_scroll_demo); listView = findViewById(R.id.listview); img = findViewById(R.id.img); container = findViewById(R.id.container); setAdapter(); findViewById(R.id.start).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bitmaps.clear(); img.setImageBitmap(null); isScreenShots = true; autoScroll(); } }); findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isScreenShots = false; } }); } private void autoScroll() { final int delay = 16;//延时16毫秒分发滑动事件 final int step = 10;//每次滑动距离5像素,可以根据需要调整(若卡顿的话实际滚动距离可能小于5) final MotionEvent motionEvent = MotionEvent.obtain(SystemClock.uptimeMillis() , SystemClock.uptimeMillis() , MotionEvent.ACTION_DOWN , listView.getWidth() / 2 , listView.getHeight() / 2 , 0); //先分发 MotionEvent.ACTION_DOWN 事件,我们指定为按下位置是listview的中间位置,当然其他位置也可以 listView.dispatchTouchEvent(motionEvent); /* 注意: 查看Listview源码可知 滑动距离大于ViewConfiguration.get(view.getContext()).getScaledTouchSlop()时listview才开始滚动 private boolean startScrollIfNeeded(int x, int y, MotionEvent vtev) { // Check if we have moved far enough that it looks more like a // scroll than a tap final int deltaY = y - mMotionY; final int distance = Math.abs(deltaY); final boolean overscroll = mScrollY != 0; if ((overscroll || distance > mTouchSlop) && (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) { ... return true; } return false; } */ motionEvent.setAction(MotionEvent.ACTION_MOVE); motionEvent.setLocation(motionEvent.getX(), motionEvent.getY() - (ViewConfiguration.get(listView.getContext()).getScaledTouchSlop())); listView.dispatchTouchEvent(motionEvent); final int startScrollY = (int) motionEvent.getY(); listView.postDelayed(new Runnable() { @Override public void run() { if (isScreenShots == false) {//注意:我们无法通过滚动距离来判断是否滚动到了最后,所以需要通过其他方式停止滚动 drawRemainAndAssemble(startScrollY, (int) motionEvent.getY()); return; } //滚动刚好一整屏时画到bitmap上 drawIfNeeded(startScrollY, (int) motionEvent.getY()); motionEvent.setAction(MotionEvent.ACTION_MOVE); //延时分发 MotionEvent.ACTION_MOVE 事件 /* 改变motionEvent的y坐标,nextStep越大滚动越快,但太大可能会导致掉帧,导致实际滚动距离小于我们滑动的距离 因为我们是根据(curScrollY - startScrollY) % container.getHeight() == 0来判定是否刚好滚动了一屏幕的, 所以快要滚动到刚好一屏幕位置时,修改nextStep的值,使下次滚动后刚好是一屏幕的距离。 当然nextStep也可以一直是1,这时就不需要凑整了,但这样会导致滚动的特别慢 */ int nextStep; int gap = (startScrollY - (int) motionEvent.getY() + step) % container.getHeight(); if (gap > 0 && gap < step) { nextStep = step - gap; } else { nextStep = step; } motionEvent.setLocation((int) motionEvent.getX(), (int) motionEvent.getY() - nextStep); listView.dispatchTouchEvent(motionEvent); listView.postDelayed(this, delay); } }, delay); } private void drawRemainAndAssemble(int startScrollY, int curScrollY) { //最后的可能不足一屏幕,需要单独处理 if ((curScrollY - startScrollY) % container.getHeight() != 0) { Bitmap film = Bitmap.createBitmap(container.getWidth(), container.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(); canvas.setBitmap(film); container.draw(canvas); int part = (startScrollY - curScrollY) / container.getHeight(); int remainHeight = startScrollY - curScrollY - container.getHeight() * part; Bitmap remainBmp = Bitmap.createBitmap(film, 0, container.getHeight() - remainHeight, container.getWidth(), remainHeight); bitmaps.add(remainBmp); } assembleBmp(); } private void assembleBmp() { int h = 0; for (Bitmap bitmap : bitmaps) { h += bitmap.getHeight(); } Bitmap bitmap = Bitmap.createBitmap(container.getWidth(), h, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); for (Bitmap b : bitmaps) { canvas.drawBitmap(b, 0, 0, null); canvas.translate(0, b.getHeight()); } ViewGroup.LayoutParams params = img.getLayoutParams(); params.width = bitmap.getWidth() * 2; params.height = bitmap.getHeight() * 2; img.requestLayout(); img.setImageBitmap(bitmap); } private void drawIfNeeded(int startScrollY, int curScrollY) { if ((curScrollY - startScrollY) % container.getHeight() == 0) { //正好滚动满一屏 //为了更通用,我们是把ListView的父布局(和ListView宽高相同)画到了bitmap上 Bitmap film = Bitmap.createBitmap(container.getWidth(), container.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(); canvas.setBitmap(film); container.draw(canvas); bitmaps.add(film); } } private void setAdapter() { listView.setAdapter(new BaseAdapter() { @Override public int getCount() { return 100; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, listView, false); convertView.setTag(R.id.index, convertView.findViewById(R.id.index)); } ((TextView) convertView.getTag(R.id.index)).setText(position + ""); return convertView; } }); } }
android-notes/auto-scroll-capture
app/src/main/java/com/wanjian/scrollscreenshots/AutoScreenShotsAct.java
1,863
//最后的可能不足一屏幕,需要单独处理
line_comment
zh-cn
package com.wanjian.scrollscreenshots; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by wanjian on 2018/1/3. */ public class AutoScreenShotsAct extends Activity { private ListView listView; private ImageView img; private ViewGroup container; private List<Bitmap> bitmaps = new ArrayList<>(); private boolean isScreenShots = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auto_scroll_demo); listView = findViewById(R.id.listview); img = findViewById(R.id.img); container = findViewById(R.id.container); setAdapter(); findViewById(R.id.start).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bitmaps.clear(); img.setImageBitmap(null); isScreenShots = true; autoScroll(); } }); findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isScreenShots = false; } }); } private void autoScroll() { final int delay = 16;//延时16毫秒分发滑动事件 final int step = 10;//每次滑动距离5像素,可以根据需要调整(若卡顿的话实际滚动距离可能小于5) final MotionEvent motionEvent = MotionEvent.obtain(SystemClock.uptimeMillis() , SystemClock.uptimeMillis() , MotionEvent.ACTION_DOWN , listView.getWidth() / 2 , listView.getHeight() / 2 , 0); //先分发 MotionEvent.ACTION_DOWN 事件,我们指定为按下位置是listview的中间位置,当然其他位置也可以 listView.dispatchTouchEvent(motionEvent); /* 注意: 查看Listview源码可知 滑动距离大于ViewConfiguration.get(view.getContext()).getScaledTouchSlop()时listview才开始滚动 private boolean startScrollIfNeeded(int x, int y, MotionEvent vtev) { // Check if we have moved far enough that it looks more like a // scroll than a tap final int deltaY = y - mMotionY; final int distance = Math.abs(deltaY); final boolean overscroll = mScrollY != 0; if ((overscroll || distance > mTouchSlop) && (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) { ... return true; } return false; } */ motionEvent.setAction(MotionEvent.ACTION_MOVE); motionEvent.setLocation(motionEvent.getX(), motionEvent.getY() - (ViewConfiguration.get(listView.getContext()).getScaledTouchSlop())); listView.dispatchTouchEvent(motionEvent); final int startScrollY = (int) motionEvent.getY(); listView.postDelayed(new Runnable() { @Override public void run() { if (isScreenShots == false) {//注意:我们无法通过滚动距离来判断是否滚动到了最后,所以需要通过其他方式停止滚动 drawRemainAndAssemble(startScrollY, (int) motionEvent.getY()); return; } //滚动刚好一整屏时画到bitmap上 drawIfNeeded(startScrollY, (int) motionEvent.getY()); motionEvent.setAction(MotionEvent.ACTION_MOVE); //延时分发 MotionEvent.ACTION_MOVE 事件 /* 改变motionEvent的y坐标,nextStep越大滚动越快,但太大可能会导致掉帧,导致实际滚动距离小于我们滑动的距离 因为我们是根据(curScrollY - startScrollY) % container.getHeight() == 0来判定是否刚好滚动了一屏幕的, 所以快要滚动到刚好一屏幕位置时,修改nextStep的值,使下次滚动后刚好是一屏幕的距离。 当然nextStep也可以一直是1,这时就不需要凑整了,但这样会导致滚动的特别慢 */ int nextStep; int gap = (startScrollY - (int) motionEvent.getY() + step) % container.getHeight(); if (gap > 0 && gap < step) { nextStep = step - gap; } else { nextStep = step; } motionEvent.setLocation((int) motionEvent.getX(), (int) motionEvent.getY() - nextStep); listView.dispatchTouchEvent(motionEvent); listView.postDelayed(this, delay); } }, delay); } private void drawRemainAndAssemble(int startScrollY, int curScrollY) { //最后 <SUF> if ((curScrollY - startScrollY) % container.getHeight() != 0) { Bitmap film = Bitmap.createBitmap(container.getWidth(), container.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(); canvas.setBitmap(film); container.draw(canvas); int part = (startScrollY - curScrollY) / container.getHeight(); int remainHeight = startScrollY - curScrollY - container.getHeight() * part; Bitmap remainBmp = Bitmap.createBitmap(film, 0, container.getHeight() - remainHeight, container.getWidth(), remainHeight); bitmaps.add(remainBmp); } assembleBmp(); } private void assembleBmp() { int h = 0; for (Bitmap bitmap : bitmaps) { h += bitmap.getHeight(); } Bitmap bitmap = Bitmap.createBitmap(container.getWidth(), h, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); for (Bitmap b : bitmaps) { canvas.drawBitmap(b, 0, 0, null); canvas.translate(0, b.getHeight()); } ViewGroup.LayoutParams params = img.getLayoutParams(); params.width = bitmap.getWidth() * 2; params.height = bitmap.getHeight() * 2; img.requestLayout(); img.setImageBitmap(bitmap); } private void drawIfNeeded(int startScrollY, int curScrollY) { if ((curScrollY - startScrollY) % container.getHeight() == 0) { //正好滚动满一屏 //为了更通用,我们是把ListView的父布局(和ListView宽高相同)画到了bitmap上 Bitmap film = Bitmap.createBitmap(container.getWidth(), container.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(); canvas.setBitmap(film); container.draw(canvas); bitmaps.add(film); } } private void setAdapter() { listView.setAdapter(new BaseAdapter() { @Override public int getCount() { return 100; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, listView, false); convertView.setTag(R.id.index, convertView.findViewById(R.id.index)); } ((TextView) convertView.getTag(R.id.index)).setText(position + ""); return convertView; } }); } }
false
1,607
11
1,863
14
1,921
10
1,863
14
2,421
24
false
false
false
false
false
true
54361_5
package io.innofang.musicplayer.utils; import android.content.Context; import android.database.Cursor; import android.provider.MediaStore; import java.util.ArrayList; import java.util.List; import io.innofang.musicplayer.bean.Song; /** * Author: Inno Fang * Time: 2018/1/8 20:04 * Description: * * 获取所有音乐文件 */ public class AudioUtils { /** * 获取sd卡所有的音乐文件 * * @return * @throws Exception */ public static List<Song> getAllSongs(Context context) { List<Song> songs = null; Cursor cursor = context.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media.DATA }, MediaStore.Audio.Media.MIME_TYPE + "=? or " + MediaStore.Audio.Media.MIME_TYPE + "=?", new String[] { "audio/mpeg", "audio/x-ms-wma" }, null); songs = new ArrayList<Song>(); if (cursor.moveToFirst()) { Song song = null; do { song = new Song(); // 文件名 song.setFileName(cursor.getString(1)); // 歌曲名 song.setTitle(cursor.getString(2)); // 时长 song.setDuration(cursor.getInt(3)); // 歌手名 song.setSinger(cursor.getString(4)); // 专辑名 song.setAlbum(cursor.getString(5)); // 年代 if (cursor.getString(6) != null) { song.setYear(cursor.getString(6)); } else { song.setYear("未知"); } // 歌曲格式 if ("audio/mpeg".equals(cursor.getString(7).trim())) { song.setType("mp3"); } else if ("audio/x-ms-wma".equals(cursor.getString(7).trim())) { song.setType("wma"); } // 文件大小 if (cursor.getString(8) != null) { float size = cursor.getInt(8) / 1024f / 1024f; song.setSize((size + "").substring(0, 4) + "M"); } else { song.setSize("未知"); } // 文件路径 if (cursor.getString(9) != null) { song.setFileUrl(cursor.getString(9)); } songs.add(song); } while (cursor.moveToNext()); cursor.close(); } return songs; } }
android-nuc/MusicPlayer
app/src/main/java/io/innofang/musicplayer/utils/AudioUtils.java
730
// 专辑名
line_comment
zh-cn
package io.innofang.musicplayer.utils; import android.content.Context; import android.database.Cursor; import android.provider.MediaStore; import java.util.ArrayList; import java.util.List; import io.innofang.musicplayer.bean.Song; /** * Author: Inno Fang * Time: 2018/1/8 20:04 * Description: * * 获取所有音乐文件 */ public class AudioUtils { /** * 获取sd卡所有的音乐文件 * * @return * @throws Exception */ public static List<Song> getAllSongs(Context context) { List<Song> songs = null; Cursor cursor = context.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media.DATA }, MediaStore.Audio.Media.MIME_TYPE + "=? or " + MediaStore.Audio.Media.MIME_TYPE + "=?", new String[] { "audio/mpeg", "audio/x-ms-wma" }, null); songs = new ArrayList<Song>(); if (cursor.moveToFirst()) { Song song = null; do { song = new Song(); // 文件名 song.setFileName(cursor.getString(1)); // 歌曲名 song.setTitle(cursor.getString(2)); // 时长 song.setDuration(cursor.getInt(3)); // 歌手名 song.setSinger(cursor.getString(4)); // 专辑 <SUF> song.setAlbum(cursor.getString(5)); // 年代 if (cursor.getString(6) != null) { song.setYear(cursor.getString(6)); } else { song.setYear("未知"); } // 歌曲格式 if ("audio/mpeg".equals(cursor.getString(7).trim())) { song.setType("mp3"); } else if ("audio/x-ms-wma".equals(cursor.getString(7).trim())) { song.setType("wma"); } // 文件大小 if (cursor.getString(8) != null) { float size = cursor.getInt(8) / 1024f / 1024f; song.setSize((size + "").substring(0, 4) + "M"); } else { song.setSize("未知"); } // 文件路径 if (cursor.getString(9) != null) { song.setFileUrl(cursor.getString(9)); } songs.add(song); } while (cursor.moveToNext()); cursor.close(); } return songs; } }
false
618
4
730
5
758
4
730
5
885
7
false
false
false
false
false
true
49961_8
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cms.v20190321.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ImageData extends AbstractModel{ /** * 是否恶意 0:正常 1:可疑 */ @SerializedName("EvilFlag") @Expose private Long EvilFlag; /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 */ @SerializedName("EvilType") @Expose private Long EvilType; /** * 图片二维码详情 */ @SerializedName("CodeDetect") @Expose private CodeDetect CodeDetect; /** * 图片性感详情 */ @SerializedName("HotDetect") @Expose private ImageHotDetect HotDetect; /** * 图片违法详情 */ @SerializedName("IllegalDetect") @Expose private ImageIllegalDetect IllegalDetect; /** * logo详情 */ @SerializedName("LogoDetect") @Expose private LogoDetail LogoDetect; /** * 图片OCR详情 */ @SerializedName("OCRDetect") @Expose private OCRDetect OCRDetect; /** * 图片涉政详情 */ @SerializedName("PolityDetect") @Expose private ImagePolityDetect PolityDetect; /** * 图片涉黄详情 */ @SerializedName("PornDetect") @Expose private ImagePornDetect PornDetect; /** * 图片相似度详情 */ @SerializedName("Similar") @Expose private Similar Similar; /** * 图片暴恐详情 */ @SerializedName("TerrorDetect") @Expose private ImageTerrorDetect TerrorDetect; /** * Get 是否恶意 0:正常 1:可疑 * @return EvilFlag 是否恶意 0:正常 1:可疑 */ public Long getEvilFlag() { return this.EvilFlag; } /** * Set 是否恶意 0:正常 1:可疑 * @param EvilFlag 是否恶意 0:正常 1:可疑 */ public void setEvilFlag(Long EvilFlag) { this.EvilFlag = EvilFlag; } /** * Get 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 * @return EvilType 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 */ public Long getEvilType() { return this.EvilType; } /** * Set 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 * @param EvilType 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 */ public void setEvilType(Long EvilType) { this.EvilType = EvilType; } /** * Get 图片二维码详情 * @return CodeDetect 图片二维码详情 */ public CodeDetect getCodeDetect() { return this.CodeDetect; } /** * Set 图片二维码详情 * @param CodeDetect 图片二维码详情 */ public void setCodeDetect(CodeDetect CodeDetect) { this.CodeDetect = CodeDetect; } /** * Get 图片性感详情 * @return HotDetect 图片性感详情 */ public ImageHotDetect getHotDetect() { return this.HotDetect; } /** * Set 图片性感详情 * @param HotDetect 图片性感详情 */ public void setHotDetect(ImageHotDetect HotDetect) { this.HotDetect = HotDetect; } /** * Get 图片违法详情 * @return IllegalDetect 图片违法详情 */ public ImageIllegalDetect getIllegalDetect() { return this.IllegalDetect; } /** * Set 图片违法详情 * @param IllegalDetect 图片违法详情 */ public void setIllegalDetect(ImageIllegalDetect IllegalDetect) { this.IllegalDetect = IllegalDetect; } /** * Get logo详情 * @return LogoDetect logo详情 */ public LogoDetail getLogoDetect() { return this.LogoDetect; } /** * Set logo详情 * @param LogoDetect logo详情 */ public void setLogoDetect(LogoDetail LogoDetect) { this.LogoDetect = LogoDetect; } /** * Get 图片OCR详情 * @return OCRDetect 图片OCR详情 */ public OCRDetect getOCRDetect() { return this.OCRDetect; } /** * Set 图片OCR详情 * @param OCRDetect 图片OCR详情 */ public void setOCRDetect(OCRDetect OCRDetect) { this.OCRDetect = OCRDetect; } /** * Get 图片涉政详情 * @return PolityDetect 图片涉政详情 */ public ImagePolityDetect getPolityDetect() { return this.PolityDetect; } /** * Set 图片涉政详情 * @param PolityDetect 图片涉政详情 */ public void setPolityDetect(ImagePolityDetect PolityDetect) { this.PolityDetect = PolityDetect; } /** * Get 图片涉黄详情 * @return PornDetect 图片涉黄详情 */ public ImagePornDetect getPornDetect() { return this.PornDetect; } /** * Set 图片涉黄详情 * @param PornDetect 图片涉黄详情 */ public void setPornDetect(ImagePornDetect PornDetect) { this.PornDetect = PornDetect; } /** * Get 图片相似度详情 * @return Similar 图片相似度详情 */ public Similar getSimilar() { return this.Similar; } /** * Set 图片相似度详情 * @param Similar 图片相似度详情 */ public void setSimilar(Similar Similar) { this.Similar = Similar; } /** * Get 图片暴恐详情 * @return TerrorDetect 图片暴恐详情 */ public ImageTerrorDetect getTerrorDetect() { return this.TerrorDetect; } /** * Set 图片暴恐详情 * @param TerrorDetect 图片暴恐详情 */ public void setTerrorDetect(ImageTerrorDetect TerrorDetect) { this.TerrorDetect = TerrorDetect; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "EvilFlag", this.EvilFlag); this.setParamSimple(map, prefix + "EvilType", this.EvilType); this.setParamObj(map, prefix + "CodeDetect.", this.CodeDetect); this.setParamObj(map, prefix + "HotDetect.", this.HotDetect); this.setParamObj(map, prefix + "IllegalDetect.", this.IllegalDetect); this.setParamObj(map, prefix + "LogoDetect.", this.LogoDetect); this.setParamObj(map, prefix + "OCRDetect.", this.OCRDetect); this.setParamObj(map, prefix + "PolityDetect.", this.PolityDetect); this.setParamObj(map, prefix + "PornDetect.", this.PornDetect); this.setParamObj(map, prefix + "Similar.", this.Similar); this.setParamObj(map, prefix + "TerrorDetect.", this.TerrorDetect); } }
androidYZ/TestProject
TxOcr/src/main/java/com/tencentcloudapi/cms/v20190321/models/ImageData.java
2,234
/** * 图片涉政详情 */
block_comment
zh-cn
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cms.v20190321.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ImageData extends AbstractModel{ /** * 是否恶意 0:正常 1:可疑 */ @SerializedName("EvilFlag") @Expose private Long EvilFlag; /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 */ @SerializedName("EvilType") @Expose private Long EvilType; /** * 图片二维码详情 */ @SerializedName("CodeDetect") @Expose private CodeDetect CodeDetect; /** * 图片性感详情 */ @SerializedName("HotDetect") @Expose private ImageHotDetect HotDetect; /** * 图片违法详情 */ @SerializedName("IllegalDetect") @Expose private ImageIllegalDetect IllegalDetect; /** * logo详情 */ @SerializedName("LogoDetect") @Expose private LogoDetail LogoDetect; /** * 图片OCR详情 */ @SerializedName("OCRDetect") @Expose private OCRDetect OCRDetect; /** * 图片涉 <SUF>*/ @SerializedName("PolityDetect") @Expose private ImagePolityDetect PolityDetect; /** * 图片涉黄详情 */ @SerializedName("PornDetect") @Expose private ImagePornDetect PornDetect; /** * 图片相似度详情 */ @SerializedName("Similar") @Expose private Similar Similar; /** * 图片暴恐详情 */ @SerializedName("TerrorDetect") @Expose private ImageTerrorDetect TerrorDetect; /** * Get 是否恶意 0:正常 1:可疑 * @return EvilFlag 是否恶意 0:正常 1:可疑 */ public Long getEvilFlag() { return this.EvilFlag; } /** * Set 是否恶意 0:正常 1:可疑 * @param EvilFlag 是否恶意 0:正常 1:可疑 */ public void setEvilFlag(Long EvilFlag) { this.EvilFlag = EvilFlag; } /** * Get 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 * @return EvilType 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 */ public Long getEvilType() { return this.EvilType; } /** * Set 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 * @param EvilType 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 */ public void setEvilType(Long EvilType) { this.EvilType = EvilType; } /** * Get 图片二维码详情 * @return CodeDetect 图片二维码详情 */ public CodeDetect getCodeDetect() { return this.CodeDetect; } /** * Set 图片二维码详情 * @param CodeDetect 图片二维码详情 */ public void setCodeDetect(CodeDetect CodeDetect) { this.CodeDetect = CodeDetect; } /** * Get 图片性感详情 * @return HotDetect 图片性感详情 */ public ImageHotDetect getHotDetect() { return this.HotDetect; } /** * Set 图片性感详情 * @param HotDetect 图片性感详情 */ public void setHotDetect(ImageHotDetect HotDetect) { this.HotDetect = HotDetect; } /** * Get 图片违法详情 * @return IllegalDetect 图片违法详情 */ public ImageIllegalDetect getIllegalDetect() { return this.IllegalDetect; } /** * Set 图片违法详情 * @param IllegalDetect 图片违法详情 */ public void setIllegalDetect(ImageIllegalDetect IllegalDetect) { this.IllegalDetect = IllegalDetect; } /** * Get logo详情 * @return LogoDetect logo详情 */ public LogoDetail getLogoDetect() { return this.LogoDetect; } /** * Set logo详情 * @param LogoDetect logo详情 */ public void setLogoDetect(LogoDetail LogoDetect) { this.LogoDetect = LogoDetect; } /** * Get 图片OCR详情 * @return OCRDetect 图片OCR详情 */ public OCRDetect getOCRDetect() { return this.OCRDetect; } /** * Set 图片OCR详情 * @param OCRDetect 图片OCR详情 */ public void setOCRDetect(OCRDetect OCRDetect) { this.OCRDetect = OCRDetect; } /** * Get 图片涉政详情 * @return PolityDetect 图片涉政详情 */ public ImagePolityDetect getPolityDetect() { return this.PolityDetect; } /** * Set 图片涉政详情 * @param PolityDetect 图片涉政详情 */ public void setPolityDetect(ImagePolityDetect PolityDetect) { this.PolityDetect = PolityDetect; } /** * Get 图片涉黄详情 * @return PornDetect 图片涉黄详情 */ public ImagePornDetect getPornDetect() { return this.PornDetect; } /** * Set 图片涉黄详情 * @param PornDetect 图片涉黄详情 */ public void setPornDetect(ImagePornDetect PornDetect) { this.PornDetect = PornDetect; } /** * Get 图片相似度详情 * @return Similar 图片相似度详情 */ public Similar getSimilar() { return this.Similar; } /** * Set 图片相似度详情 * @param Similar 图片相似度详情 */ public void setSimilar(Similar Similar) { this.Similar = Similar; } /** * Get 图片暴恐详情 * @return TerrorDetect 图片暴恐详情 */ public ImageTerrorDetect getTerrorDetect() { return this.TerrorDetect; } /** * Set 图片暴恐详情 * @param TerrorDetect 图片暴恐详情 */ public void setTerrorDetect(ImageTerrorDetect TerrorDetect) { this.TerrorDetect = TerrorDetect; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "EvilFlag", this.EvilFlag); this.setParamSimple(map, prefix + "EvilType", this.EvilType); this.setParamObj(map, prefix + "CodeDetect.", this.CodeDetect); this.setParamObj(map, prefix + "HotDetect.", this.HotDetect); this.setParamObj(map, prefix + "IllegalDetect.", this.IllegalDetect); this.setParamObj(map, prefix + "LogoDetect.", this.LogoDetect); this.setParamObj(map, prefix + "OCRDetect.", this.OCRDetect); this.setParamObj(map, prefix + "PolityDetect.", this.PolityDetect); this.setParamObj(map, prefix + "PornDetect.", this.PornDetect); this.setParamObj(map, prefix + "Similar.", this.Similar); this.setParamObj(map, prefix + "TerrorDetect.", this.TerrorDetect); } }
false
2,082
11
2,234
11
2,291
11
2,234
11
3,105
18
false
false
false
false
false
true
52683_1
package com.smartsite.netsdk.lib.enumeration; /** * @author : 291189 * @since : Created in 2021/6/30 11:01 * 人脸表情 */ public enum EM_SECURITYGATE_EXPRESSION_TYPE { EM_SECURITYGATE_EXPRESSION_UNKNOWN(-1,"未知"), // 未知 EM_SECURITYGATE_EXPRESSION_UNDEFINE(0,"未识别"), // 未识别 EM_SECURITYGATE_EXPRESSION_ANGER(1,"生气"), // 生气 EM_SECURITYGATE_EXPRESSION_SAD(2,"悲伤"), // 悲伤 EM_SECURITYGATE_EXPRESSION_DISGUST(3,"厌恶"), // 厌恶 EM_SECURITYGATE_EXPRESSION_FEAR(4,"恐惧"), // 恐惧 EM_SECURITYGATE_EXPRESSION_SURPRISED(5,"诧异"), // 诧异 EM_SECURITYGATE_EXPRESSION_CALM(6,"平静"), // 平静 EM_SECURITYGATE_EXPRESSION_SMILE(7,"微笑"), // 微笑 EM_SECURITYGATE_EXPRESSION_LAUGH(8,"大笑"), // 大笑 EM_SECURITYGATE_EXPRESSION_HAPPY(9,"高兴"), // 高兴 EM_SECURITYGATE_EXPRESSION_CONFUSE(10,"困惑"), // 困惑 EM_SECURITYGATE_EXPRESSION_SCREAM(11,"尖叫"); // 尖叫 private final int value; private final String note; EM_SECURITYGATE_EXPRESSION_TYPE(int givenValue, String note) { this.value = givenValue; this.note = note; } public String getNote() { return note; } public int getValue() { return value; } public static String getNoteByValue(int givenValue) { for (EM_SECURITYGATE_EXPRESSION_TYPE enumType : EM_SECURITYGATE_EXPRESSION_TYPE.values()) { if (givenValue == enumType.getValue()) { return enumType.getNote(); } } return null; } public static int getValueByNote(String givenNote) { for (EM_SECURITYGATE_EXPRESSION_TYPE enumType : EM_SECURITYGATE_EXPRESSION_TYPE.values()) { if (givenNote.equals(enumType.getNote())) { return enumType.getValue(); } } return -1; } public static EM_SECURITYGATE_EXPRESSION_TYPE getEnum(int value) { for (EM_SECURITYGATE_EXPRESSION_TYPE e : EM_SECURITYGATE_EXPRESSION_TYPE.values()) { if (e.getValue() == value) return e; } return EM_SECURITYGATE_EXPRESSION_TYPE.EM_SECURITYGATE_EXPRESSION_UNKNOWN; } }
androidxiaohaozi/dahua-netsdk
src/main/java/com/smartsite/netsdk/lib/enumeration/EM_SECURITYGATE_EXPRESSION_TYPE.java
689
// 未识别
line_comment
zh-cn
package com.smartsite.netsdk.lib.enumeration; /** * @author : 291189 * @since : Created in 2021/6/30 11:01 * 人脸表情 */ public enum EM_SECURITYGATE_EXPRESSION_TYPE { EM_SECURITYGATE_EXPRESSION_UNKNOWN(-1,"未知"), // 未知 EM_SECURITYGATE_EXPRESSION_UNDEFINE(0,"未识别"), // 未识 <SUF> EM_SECURITYGATE_EXPRESSION_ANGER(1,"生气"), // 生气 EM_SECURITYGATE_EXPRESSION_SAD(2,"悲伤"), // 悲伤 EM_SECURITYGATE_EXPRESSION_DISGUST(3,"厌恶"), // 厌恶 EM_SECURITYGATE_EXPRESSION_FEAR(4,"恐惧"), // 恐惧 EM_SECURITYGATE_EXPRESSION_SURPRISED(5,"诧异"), // 诧异 EM_SECURITYGATE_EXPRESSION_CALM(6,"平静"), // 平静 EM_SECURITYGATE_EXPRESSION_SMILE(7,"微笑"), // 微笑 EM_SECURITYGATE_EXPRESSION_LAUGH(8,"大笑"), // 大笑 EM_SECURITYGATE_EXPRESSION_HAPPY(9,"高兴"), // 高兴 EM_SECURITYGATE_EXPRESSION_CONFUSE(10,"困惑"), // 困惑 EM_SECURITYGATE_EXPRESSION_SCREAM(11,"尖叫"); // 尖叫 private final int value; private final String note; EM_SECURITYGATE_EXPRESSION_TYPE(int givenValue, String note) { this.value = givenValue; this.note = note; } public String getNote() { return note; } public int getValue() { return value; } public static String getNoteByValue(int givenValue) { for (EM_SECURITYGATE_EXPRESSION_TYPE enumType : EM_SECURITYGATE_EXPRESSION_TYPE.values()) { if (givenValue == enumType.getValue()) { return enumType.getNote(); } } return null; } public static int getValueByNote(String givenNote) { for (EM_SECURITYGATE_EXPRESSION_TYPE enumType : EM_SECURITYGATE_EXPRESSION_TYPE.values()) { if (givenNote.equals(enumType.getNote())) { return enumType.getValue(); } } return -1; } public static EM_SECURITYGATE_EXPRESSION_TYPE getEnum(int value) { for (EM_SECURITYGATE_EXPRESSION_TYPE e : EM_SECURITYGATE_EXPRESSION_TYPE.values()) { if (e.getValue() == value) return e; } return EM_SECURITYGATE_EXPRESSION_TYPE.EM_SECURITYGATE_EXPRESSION_UNKNOWN; } }
false
594
4
689
4
668
3
689
4
986
9
false
false
false
false
false
true
52152_18
package io; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Author: Chen zheng you * CreateTime: 2019-02-19 14:29 * Description: */ public class FlieOutputStreamTest { public static void main(String[] args) { } // 创建文件对象 // 与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 值的第一个字符。 // 在 UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\\'。 // File file = new File("E:"+File.separatorChar+"中文from"+File.separatorChar+".txt"); File file = new File("F:\\中文.txt"); //输出流写出方式1 //使用write(int b)方法,一次写出一个字节。 //测试:将c盘下的a.txt文件删除,发现当文件不存在时,会自动创建一个,但是创建不了多级目录。 //注意:使用write(int b)方法,虽然接收的是int类型参数,但是write 的常规协定是:向输出流写入一个字节。 //要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。 public void writFileTest() throws FileNotFoundException, IOException { if(file==null){ file.mkdir(); } // 创建文件输出流 FileOutputStream fos = new FileOutputStream(file); fos.write('中'); fos.write('h'); fos.write('e'); fos.write('n'); fos.write('z'); fos.write('h'); fos.write('e'); fos.write('n'); fos.write('g'); fos.write('y'); fos.write('o'); fos.write('u'); fos.close(); } //输出流写出方式2 //使用write(byte[] b),就是使用缓冲.提高效率. // 上述案例中的使用了OutputStram 的write方法,一次只能写一个字节。 // 成功的向文件中写入了内容。但是并不高效,如和提高效率呢?是否应该使用缓冲, // 根据字节输入流的缓冲原理,是否可以将数据保存中字节数组中。通过操作字节数组来提高效率。 // 查找API文档,在OutputStram类中找到了write(byte[] b)方法,将 b.length 个字节从指定的 byte 数组写入此输出流中。 // 如何将字节数据保存在字节数组中,以字符串为例,”hello , world” 如何转为字节数组。显然通过字符串的getBytes方法即可。 // 仔细查看a.txt文本文件发现上述程序每运行一次,老的内容就会被覆盖掉。 // 那么如何不覆盖已有信息,能够往a.txt里追加信息呢。 public void writeTxtFile() throws IOException { // 1:打开文件输出流,流的目的地是指定的文件 // 查看API文档,发现FileOutputStream类中的构造方法中有一个构造可以 // 实现追加的功能FileOutputStream(File file, boolean append) // 第二个参数,append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处 FileOutputStream fos = new FileOutputStream(file,true); // 2:通过流向文件写数据 byte[] byt = "里追加信息呢".getBytes(); fos.write(byt); // 3:用完流后关闭流 fos.close(); } }
andyczy/czy-study-java-commons-utils
java-8/src/main/java/io/FlieOutputStreamTest.java
858
// 仔细查看a.txt文本文件发现上述程序每运行一次,老的内容就会被覆盖掉。
line_comment
zh-cn
package io; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Author: Chen zheng you * CreateTime: 2019-02-19 14:29 * Description: */ public class FlieOutputStreamTest { public static void main(String[] args) { } // 创建文件对象 // 与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 值的第一个字符。 // 在 UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\\'。 // File file = new File("E:"+File.separatorChar+"中文from"+File.separatorChar+".txt"); File file = new File("F:\\中文.txt"); //输出流写出方式1 //使用write(int b)方法,一次写出一个字节。 //测试:将c盘下的a.txt文件删除,发现当文件不存在时,会自动创建一个,但是创建不了多级目录。 //注意:使用write(int b)方法,虽然接收的是int类型参数,但是write 的常规协定是:向输出流写入一个字节。 //要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。 public void writFileTest() throws FileNotFoundException, IOException { if(file==null){ file.mkdir(); } // 创建文件输出流 FileOutputStream fos = new FileOutputStream(file); fos.write('中'); fos.write('h'); fos.write('e'); fos.write('n'); fos.write('z'); fos.write('h'); fos.write('e'); fos.write('n'); fos.write('g'); fos.write('y'); fos.write('o'); fos.write('u'); fos.close(); } //输出流写出方式2 //使用write(byte[] b),就是使用缓冲.提高效率. // 上述案例中的使用了OutputStram 的write方法,一次只能写一个字节。 // 成功的向文件中写入了内容。但是并不高效,如和提高效率呢?是否应该使用缓冲, // 根据字节输入流的缓冲原理,是否可以将数据保存中字节数组中。通过操作字节数组来提高效率。 // 查找API文档,在OutputStram类中找到了write(byte[] b)方法,将 b.length 个字节从指定的 byte 数组写入此输出流中。 // 如何将字节数据保存在字节数组中,以字符串为例,”hello , world” 如何转为字节数组。显然通过字符串的getBytes方法即可。 // 仔细 <SUF> // 那么如何不覆盖已有信息,能够往a.txt里追加信息呢。 public void writeTxtFile() throws IOException { // 1:打开文件输出流,流的目的地是指定的文件 // 查看API文档,发现FileOutputStream类中的构造方法中有一个构造可以 // 实现追加的功能FileOutputStream(File file, boolean append) // 第二个参数,append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处 FileOutputStream fos = new FileOutputStream(file,true); // 2:通过流向文件写数据 byte[] byt = "里追加信息呢".getBytes(); fos.write(byt); // 3:用完流后关闭流 fos.close(); } }
false
794
22
858
26
851
23
858
26
1,207
48
false
false
false
false
false
true
64603_5
package com.example; import com.alibaba.fastjson.annotation.JSONField; /** * Created by admin on 2017/4/13. */ public class GameDate { //排序 @JSONField(ordinal = 1) private int channelID; @JSONField(ordinal = 2) private String dataTime; @JSONField(ordinal = 3) private String productIDName; // private String productName; @JSONField(ordinal = 4) private int apkPackageID; @JSONField(ordinal = 5) private String apkPackageName; @JSONField(ordinal = 6) private int clickNum;//点击数 @JSONField(ordinal = 7) private int acceleratorNum;//加速器激活人数 @JSONField(ordinal = 8) private int apkActivationNumber;//apk 激活人数 @JSONField(ordinal = 9) private int newRegisterNumber;//新增注册人 @JSONField(ordinal = 10) private int moneyDay;//当日付钱 public int getChannelID() { return channelID; } public void setChannelID(int channelID) { this.channelID = channelID; } public String getDataTime() { return dataTime; } public void setDataTime(String dataTime) { this.dataTime = dataTime; } public String getProductIDName() { return productIDName; } public void setProductIDName(String productIDName) { this.productIDName = productIDName; } public int getClickNum() { return clickNum; } public void setClickNum(int clickNum) { this.clickNum = clickNum; } // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } public int getApkPackageID() { return apkPackageID; } public void setApkPackageID(int apkPackageID) { this.apkPackageID = apkPackageID; } public String getApkPackageName() { return apkPackageName; } public void setApkPackageName(String apkPackageName) { this.apkPackageName = apkPackageName; } public int getAcceleratorNum() { return acceleratorNum; } public void setAcceleratorNum(int acceleratorNum) { this.acceleratorNum = acceleratorNum; } public int getApkActivationNumber() { return apkActivationNumber; } public void setApkActivationNumber(int apkActivationNumber) { this.apkActivationNumber = apkActivationNumber; } public int getNewRegisterNumber() { return newRegisterNumber; } public void setNewRegisterNumber(int newRegisterNumber) { this.newRegisterNumber = newRegisterNumber; } public int getMoneyDay() { return moneyDay; } public void setMoneyDay(int moneyDay) { this.moneyDay = moneyDay; } }
andyfun/WeiWen
testjavalib/src/main/java/com/example/GameDate.java
725
//新增注册人
line_comment
zh-cn
package com.example; import com.alibaba.fastjson.annotation.JSONField; /** * Created by admin on 2017/4/13. */ public class GameDate { //排序 @JSONField(ordinal = 1) private int channelID; @JSONField(ordinal = 2) private String dataTime; @JSONField(ordinal = 3) private String productIDName; // private String productName; @JSONField(ordinal = 4) private int apkPackageID; @JSONField(ordinal = 5) private String apkPackageName; @JSONField(ordinal = 6) private int clickNum;//点击数 @JSONField(ordinal = 7) private int acceleratorNum;//加速器激活人数 @JSONField(ordinal = 8) private int apkActivationNumber;//apk 激活人数 @JSONField(ordinal = 9) private int newRegisterNumber;//新增 <SUF> @JSONField(ordinal = 10) private int moneyDay;//当日付钱 public int getChannelID() { return channelID; } public void setChannelID(int channelID) { this.channelID = channelID; } public String getDataTime() { return dataTime; } public void setDataTime(String dataTime) { this.dataTime = dataTime; } public String getProductIDName() { return productIDName; } public void setProductIDName(String productIDName) { this.productIDName = productIDName; } public int getClickNum() { return clickNum; } public void setClickNum(int clickNum) { this.clickNum = clickNum; } // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } public int getApkPackageID() { return apkPackageID; } public void setApkPackageID(int apkPackageID) { this.apkPackageID = apkPackageID; } public String getApkPackageName() { return apkPackageName; } public void setApkPackageName(String apkPackageName) { this.apkPackageName = apkPackageName; } public int getAcceleratorNum() { return acceleratorNum; } public void setAcceleratorNum(int acceleratorNum) { this.acceleratorNum = acceleratorNum; } public int getApkActivationNumber() { return apkActivationNumber; } public void setApkActivationNumber(int apkActivationNumber) { this.apkActivationNumber = apkActivationNumber; } public int getNewRegisterNumber() { return newRegisterNumber; } public void setNewRegisterNumber(int newRegisterNumber) { this.newRegisterNumber = newRegisterNumber; } public int getMoneyDay() { return moneyDay; } public void setMoneyDay(int moneyDay) { this.moneyDay = moneyDay; } }
false
677
4
725
4
781
4
725
4
901
10
false
false
false
false
false
true
36515_2
import java.util.Scanner; public class Second { // %餘數 // /整數 public static void main(String[] args) { //給定一個句子,請判斷它是不是迴文,即正著讀或反著讀都一樣的句子。例如:【上海自來水來自海上】是迴文。其他例子: //(1) 喜歡的少年是你,你是年少的歡喜 //(2) 小巷殘月凝天空,親人故土鄉情濃,笑聲猶在空懷舊,憔心客愁滿蒼穹,穹蒼滿愁客心憔,舊懷空在猶聲笑,濃情鄉土故人親,空天凝月殘巷小 String test = "喜歡的少年是你,你是年少的歡喜"; boolean palindrome = false; for(int i =0;i<test.length()/2;i++) { if (test.charAt(i) == test.charAt(test.length() - 1 - i)) { palindrome = true; } } if(palindrome){ System.out.println("是回文"); } else{ System.out.println("不是回文"); } } }
andyloveathena/which-days-leap-year-or-not-owl-file-palindrome-or-not-java-file-
java/Second.java
345
//(1) 喜歡的少年是你,你是年少的歡喜
line_comment
zh-cn
import java.util.Scanner; public class Second { // %餘數 // /整數 public static void main(String[] args) { //給定一個句子,請判斷它是不是迴文,即正著讀或反著讀都一樣的句子。例如:【上海自來水來自海上】是迴文。其他例子: //(1 <SUF> //(2) 小巷殘月凝天空,親人故土鄉情濃,笑聲猶在空懷舊,憔心客愁滿蒼穹,穹蒼滿愁客心憔,舊懷空在猶聲笑,濃情鄉土故人親,空天凝月殘巷小 String test = "喜歡的少年是你,你是年少的歡喜"; boolean palindrome = false; for(int i =0;i<test.length()/2;i++) { if (test.charAt(i) == test.charAt(test.length() - 1 - i)) { palindrome = true; } } if(palindrome){ System.out.println("是回文"); } else{ System.out.println("不是回文"); } } }
false
266
17
345
22
289
13
345
22
448
24
false
false
false
false
false
true
66459_4
package com.example.verificationcodejavademo.widget; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.example.verificationcodejavademo.R; import com.example.verificationcodejavademo.utils.DisplayUtil; /** * Date:2020/5/19 * author:wuyan */ public class DragImageView extends FrameLayout implements SeekBar.OnSeekBarChangeListener { private SeekBar drag_sb; private FrameLayout drag_fl_content; private ImageView drag_iv_cover; private ImageView drag_iv_block; private View drag_v_flash; private DiyStyleTextView drag_tv_tips; private TextView drag_tv_tips2; private Bitmap cover; private Bitmap block; private Long animeTime = 333L; private float timeUse = 0.0f; private Long timeTemp = 0l; private Handler handler = new Handler(); public DragImageView(@NonNull Context context) { super(context); init(); } public DragImageView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DragImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { View.inflate(getContext(), R.layout.drag_view, this); drag_sb = findViewById(R.id.drag_sb); drag_sb.setOnSeekBarChangeListener(this); drag_fl_content = findViewById(R.id.drag_fl_content); drag_iv_cover = findViewById(R.id.drag_iv_cover); drag_iv_block = findViewById(R.id.drag_iv_block); drag_v_flash = findViewById(R.id.drag_v_flash); drag_tv_tips = findViewById(R.id.drag_tv_tips); drag_tv_tips2 = findViewById(R.id.drag_tv_tips2); drag_sb.setMax(getContext().getResources().getDisplayMetrics().widthPixels); reset(); } //重置 public void reset() { int position = drag_sb.getProgress(); if (position != 0) { ValueAnimator animator = ValueAnimator.ofFloat(1f, 0.0f); animator.setDuration(animeTime).start(); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float f = (float) animation.getAnimatedValue(); drag_sb.setProgress((int) (position * f)); } }); } tipsShowAnime(false); tips2ShowAnime(true); setSbThumb(R.drawable.drag_btn_n); drag_sb.setEnabled(true); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); drag_iv_block.setVisibility(VISIBLE); } /** * 设置资源 * * @param cover 拼图 * @param block 滑块 */ public void setUp(Bitmap cover, Bitmap block) { this.cover = cover; this.block = block; int w = cover.getWidth(); int h = cover.getHeight(); LayoutParams l = (LayoutParams) drag_iv_cover.getLayoutParams(); l.width = DisplayUtil.dip2px(getContext(), (float) w); l.height = DisplayUtil.dip2px(getContext(), (float) h); drag_iv_cover.setLayoutParams(l); drag_iv_cover.setImageBitmap(cover); LayoutParams layoutParams2 = (LayoutParams) drag_iv_block.getLayoutParams(); layoutParams2.width = DisplayUtil.dip2px(getContext(), (float) block.getWidth()); layoutParams2.height = DisplayUtil.dip2px(getContext(), (float) block.getHeight()); drag_iv_block.setLayoutParams(layoutParams2); drag_iv_block.setImageBitmap(block); setLocation(1f * cover.getWidth() / cover.getHeight(), cover.getWidth()); } //设置容器宽高 private void setLocation(float cover_wph, int cover_w) { int w = cover_w; int h = (int) (w / cover_wph); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) drag_fl_content.getLayoutParams(); layoutParams.width = DisplayUtil.dip2px(getContext(), (float) w); layoutParams.height = DisplayUtil.dip2px(getContext(), (float) h); drag_fl_content.setLayoutParams(layoutParams); } //验证成功:滑块隐藏,成功提示语,滑块不能滑动,设置setSbThumb,SeekBar的背景 public void ok() { blockHideAnime(); int penset; if (timeUse > 1) { penset = (int) (99 - (timeUse - 1) / 0.1f); } else { penset = (int) (99 - 0 / 0.1f); } if (penset < 1) penset = 1; drag_tv_tips.setText(String.format("拼图成功: 耗时%.1f秒,打败了%d%%的用户!", timeUse, penset)); tipsShowAnime(true); handler.postDelayed(new Runnable() { @Override public void run() { tipsShowAnime(false); tips2ShowAnime(true); drag_sb.setEnabled(true); int position = drag_sb.getProgress(); ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f); animator.setDuration(animeTime).start(); animator.addUpdateListener(animation -> { float f = (float) animation.getAnimatedValue(); drag_sb.setProgress((int) (position * f)); setSbThumb(R.drawable.drag_btn_n); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); }); } },1500); drag_sb.setEnabled(false); setSbThumb(R.drawable.drag_btn_success); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress_success)); } //成功完成拼图滑块消失 private void blockHideAnime() { AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f); alphaAnimation.setDuration(animeTime); drag_iv_block.setAnimation(alphaAnimation); drag_iv_block.setVisibility(GONE); } //验证失败 public void fail() { drag_tv_tips.setText("拼图失败: 请重新拖曳滑块到正确的位置!"); tipsShowAnime(true); handler.postDelayed(new Runnable() { @Override public void run() { tipsShowAnime(false); tips2ShowAnime(true); drag_sb.setEnabled(true); int position = drag_sb.getProgress(); ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f); animator.setDuration(animeTime).start(); animator.addUpdateListener(animation -> { float f = (float) animation.getAnimatedValue(); drag_sb.setProgress((int) (position * f)); setSbThumb(R.drawable.drag_btn_n); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); }); } },1500); drag_sb.setEnabled(false); setSbThumb(R.drawable.drag_btn_error); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress_fail)); } //弹出提示语是否显示 private void tipsShowAnime(boolean isShow) { TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, isShow ? 1f : 0f, Animation.RELATIVE_TO_SELF, isShow ? 0f : 1f); translateAnimation.setDuration(animeTime); drag_tv_tips.setAnimation(translateAnimation); drag_tv_tips.setVisibility(isShow ? VISIBLE : GONE); } //seekBar上面的提示语是否显示 private void tips2ShowAnime(boolean isShow) { AlphaAnimation alphaAnimation = new AlphaAnimation(isShow ? 0f : 1f, isShow ? 1f : 0f); alphaAnimation.setDuration(animeTime); drag_tv_tips2.setAnimation(alphaAnimation); drag_tv_tips2.setVisibility(isShow ? VISIBLE : GONE); } //===================seekbar监听=================== @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int cw = drag_iv_cover.getMeasuredWidth(); int bw = drag_iv_block.getMeasuredWidth(); ViewGroup.MarginLayoutParams l = (MarginLayoutParams) drag_iv_block.getLayoutParams(); l.leftMargin = (cw - bw) * progress / seekBar.getMax(); drag_iv_block.setLayoutParams(l); } @Override public void onStartTrackingTouch(SeekBar seekBar) { setSbThumb(R.drawable.drag_btn_n); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); drag_iv_block.setVisibility(VISIBLE); drag_iv_cover.setImageBitmap(cover); tips2ShowAnime(false); timeTemp = System.currentTimeMillis(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { timeUse = (System.currentTimeMillis() - timeTemp) / 1000f;//滑动滑块所花的时间,单位s if (dragListenner != null) { dragListenner.onDrag(DisplayUtil.px2dip( getContext(), (drag_iv_cover.getMeasuredWidth() - drag_iv_block.getMeasuredWidth()) * 1f * seekBar.getProgress() / seekBar.getMax() )); } } //设置seekBar的Thumb private void setSbThumb(int id) { Drawable drawable = getResources().getDrawable(id); drawable.setBounds(drag_sb.getThumb().getBounds()); drag_sb.setThumb(drawable); drag_sb.setThumbOffset(0); } //设置seekBar是否可以滑动 public void setSBUnMove(boolean isMove) { drag_sb.setEnabled(isMove); } //设置滑动监听 private DragListenner dragListenner; interface DragListenner { void onDrag(double position); } public void setDragListenner(DragListenner dragListenner) { this.dragListenner = dragListenner; } }
anji-plus/captcha
view/android/VerificationCodeJavaDemo/app/src/main/java/com/example/verificationcodejavademo/widget/DragImageView.java
2,716
//成功完成拼图滑块消失
line_comment
zh-cn
package com.example.verificationcodejavademo.widget; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.example.verificationcodejavademo.R; import com.example.verificationcodejavademo.utils.DisplayUtil; /** * Date:2020/5/19 * author:wuyan */ public class DragImageView extends FrameLayout implements SeekBar.OnSeekBarChangeListener { private SeekBar drag_sb; private FrameLayout drag_fl_content; private ImageView drag_iv_cover; private ImageView drag_iv_block; private View drag_v_flash; private DiyStyleTextView drag_tv_tips; private TextView drag_tv_tips2; private Bitmap cover; private Bitmap block; private Long animeTime = 333L; private float timeUse = 0.0f; private Long timeTemp = 0l; private Handler handler = new Handler(); public DragImageView(@NonNull Context context) { super(context); init(); } public DragImageView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DragImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { View.inflate(getContext(), R.layout.drag_view, this); drag_sb = findViewById(R.id.drag_sb); drag_sb.setOnSeekBarChangeListener(this); drag_fl_content = findViewById(R.id.drag_fl_content); drag_iv_cover = findViewById(R.id.drag_iv_cover); drag_iv_block = findViewById(R.id.drag_iv_block); drag_v_flash = findViewById(R.id.drag_v_flash); drag_tv_tips = findViewById(R.id.drag_tv_tips); drag_tv_tips2 = findViewById(R.id.drag_tv_tips2); drag_sb.setMax(getContext().getResources().getDisplayMetrics().widthPixels); reset(); } //重置 public void reset() { int position = drag_sb.getProgress(); if (position != 0) { ValueAnimator animator = ValueAnimator.ofFloat(1f, 0.0f); animator.setDuration(animeTime).start(); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float f = (float) animation.getAnimatedValue(); drag_sb.setProgress((int) (position * f)); } }); } tipsShowAnime(false); tips2ShowAnime(true); setSbThumb(R.drawable.drag_btn_n); drag_sb.setEnabled(true); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); drag_iv_block.setVisibility(VISIBLE); } /** * 设置资源 * * @param cover 拼图 * @param block 滑块 */ public void setUp(Bitmap cover, Bitmap block) { this.cover = cover; this.block = block; int w = cover.getWidth(); int h = cover.getHeight(); LayoutParams l = (LayoutParams) drag_iv_cover.getLayoutParams(); l.width = DisplayUtil.dip2px(getContext(), (float) w); l.height = DisplayUtil.dip2px(getContext(), (float) h); drag_iv_cover.setLayoutParams(l); drag_iv_cover.setImageBitmap(cover); LayoutParams layoutParams2 = (LayoutParams) drag_iv_block.getLayoutParams(); layoutParams2.width = DisplayUtil.dip2px(getContext(), (float) block.getWidth()); layoutParams2.height = DisplayUtil.dip2px(getContext(), (float) block.getHeight()); drag_iv_block.setLayoutParams(layoutParams2); drag_iv_block.setImageBitmap(block); setLocation(1f * cover.getWidth() / cover.getHeight(), cover.getWidth()); } //设置容器宽高 private void setLocation(float cover_wph, int cover_w) { int w = cover_w; int h = (int) (w / cover_wph); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) drag_fl_content.getLayoutParams(); layoutParams.width = DisplayUtil.dip2px(getContext(), (float) w); layoutParams.height = DisplayUtil.dip2px(getContext(), (float) h); drag_fl_content.setLayoutParams(layoutParams); } //验证成功:滑块隐藏,成功提示语,滑块不能滑动,设置setSbThumb,SeekBar的背景 public void ok() { blockHideAnime(); int penset; if (timeUse > 1) { penset = (int) (99 - (timeUse - 1) / 0.1f); } else { penset = (int) (99 - 0 / 0.1f); } if (penset < 1) penset = 1; drag_tv_tips.setText(String.format("拼图成功: 耗时%.1f秒,打败了%d%%的用户!", timeUse, penset)); tipsShowAnime(true); handler.postDelayed(new Runnable() { @Override public void run() { tipsShowAnime(false); tips2ShowAnime(true); drag_sb.setEnabled(true); int position = drag_sb.getProgress(); ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f); animator.setDuration(animeTime).start(); animator.addUpdateListener(animation -> { float f = (float) animation.getAnimatedValue(); drag_sb.setProgress((int) (position * f)); setSbThumb(R.drawable.drag_btn_n); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); }); } },1500); drag_sb.setEnabled(false); setSbThumb(R.drawable.drag_btn_success); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress_success)); } //成功 <SUF> private void blockHideAnime() { AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f); alphaAnimation.setDuration(animeTime); drag_iv_block.setAnimation(alphaAnimation); drag_iv_block.setVisibility(GONE); } //验证失败 public void fail() { drag_tv_tips.setText("拼图失败: 请重新拖曳滑块到正确的位置!"); tipsShowAnime(true); handler.postDelayed(new Runnable() { @Override public void run() { tipsShowAnime(false); tips2ShowAnime(true); drag_sb.setEnabled(true); int position = drag_sb.getProgress(); ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f); animator.setDuration(animeTime).start(); animator.addUpdateListener(animation -> { float f = (float) animation.getAnimatedValue(); drag_sb.setProgress((int) (position * f)); setSbThumb(R.drawable.drag_btn_n); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); }); } },1500); drag_sb.setEnabled(false); setSbThumb(R.drawable.drag_btn_error); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress_fail)); } //弹出提示语是否显示 private void tipsShowAnime(boolean isShow) { TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, isShow ? 1f : 0f, Animation.RELATIVE_TO_SELF, isShow ? 0f : 1f); translateAnimation.setDuration(animeTime); drag_tv_tips.setAnimation(translateAnimation); drag_tv_tips.setVisibility(isShow ? VISIBLE : GONE); } //seekBar上面的提示语是否显示 private void tips2ShowAnime(boolean isShow) { AlphaAnimation alphaAnimation = new AlphaAnimation(isShow ? 0f : 1f, isShow ? 1f : 0f); alphaAnimation.setDuration(animeTime); drag_tv_tips2.setAnimation(alphaAnimation); drag_tv_tips2.setVisibility(isShow ? VISIBLE : GONE); } //===================seekbar监听=================== @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int cw = drag_iv_cover.getMeasuredWidth(); int bw = drag_iv_block.getMeasuredWidth(); ViewGroup.MarginLayoutParams l = (MarginLayoutParams) drag_iv_block.getLayoutParams(); l.leftMargin = (cw - bw) * progress / seekBar.getMax(); drag_iv_block.setLayoutParams(l); } @Override public void onStartTrackingTouch(SeekBar seekBar) { setSbThumb(R.drawable.drag_btn_n); drag_sb.setProgressDrawable(getResources().getDrawable(R.drawable.drag_seek_progress)); drag_iv_block.setVisibility(VISIBLE); drag_iv_cover.setImageBitmap(cover); tips2ShowAnime(false); timeTemp = System.currentTimeMillis(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { timeUse = (System.currentTimeMillis() - timeTemp) / 1000f;//滑动滑块所花的时间,单位s if (dragListenner != null) { dragListenner.onDrag(DisplayUtil.px2dip( getContext(), (drag_iv_cover.getMeasuredWidth() - drag_iv_block.getMeasuredWidth()) * 1f * seekBar.getProgress() / seekBar.getMax() )); } } //设置seekBar的Thumb private void setSbThumb(int id) { Drawable drawable = getResources().getDrawable(id); drawable.setBounds(drag_sb.getThumb().getBounds()); drag_sb.setThumb(drawable); drag_sb.setThumbOffset(0); } //设置seekBar是否可以滑动 public void setSBUnMove(boolean isMove) { drag_sb.setEnabled(isMove); } //设置滑动监听 private DragListenner dragListenner; interface DragListenner { void onDrag(double position); } public void setDragListenner(DragListenner dragListenner) { this.dragListenner = dragListenner; } }
false
2,245
8
2,720
10
2,816
8
2,716
10
3,325
17
false
false
false
false
false
true
37841_29
package cn.xeblog.plugin.game.sudoku; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.StrUtil; import cn.xeblog.commons.util.ThreadUtils; import cn.xeblog.plugin.game.sudoku.algorithm.Generator; import cn.xeblog.plugin.game.sudoku.algorithm.Grid; import cn.xeblog.plugin.game.sudoku.algorithm.Solver; import cn.xeblog.plugin.game.sudoku.enums.Level; import cn.xeblog.plugin.game.sudoku.enums.PanelSize; import cn.xeblog.plugin.game.sudoku.enums.RealTimeTip; import cn.xeblog.plugin.game.sudoku.enums.Theme; import javax.swing.*; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.List; import java.util.*; /** * 功能描述: 数独UI页面 * * @author ☆程序员鼓励师☆ * @date 2022/8/12 11:34 */ public class SudokuGui extends JPanel implements ActionListener { // 主题 private final Theme theme; // 题面 private int[][] puzzleInts; // 题解 private int[][] solutionInts; // 用户解题数据 private final Grid checkGrid = Grid.emptyGrid(); // 输入字符串最大长度 private final int maxLength = 1; // 缓存下所有格子的初始化背景色 private final Map<String, Color> colorMap = new HashMap<>(81); // 数据模块 private final JTextField[][] chessBoard = new JTextField[9][9]; public SudokuGui(Level level, PanelSize panelSize, RealTimeTip realTimeTip, Theme theme) { this.theme = theme; initData(level); initJPanel(panelSize, realTimeTip); repaint(); } private void initData(Level level) { // 题面 puzzleInts = new Generator().generate(level.getBlank()).toArray(); } public void doSolution(List<JButton> buttonList) { TimeInterval timer = DateUtil.timer(); // 题解 Grid grid = Grid.of(puzzleInts); new Solver().solve(grid); solutionInts = grid.toArray(); //System.out.println("算法耗时[" + timer.interval() + "]ms"); // 刷新按钮 buttonList.forEach(b -> { b.setEnabled(true); b.repaint(); }); } private void initJPanel(PanelSize panelSize, RealTimeTip realTimeTip) { this.setPreferredSize(new Dimension(panelSize.getTableWidth(), panelSize.getTableHeight())); this.setLayout(new GridLayout(9, 9)); this.setVisible(true); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { // 设置JTextField的内容 JTextField jTextField = new JTextField(); chessBoard[i][j] = jTextField; this.add(jTextField); jTextField.setVisible(true); jTextField.setFont(new Font("", Font.BOLD, panelSize.getFontSize())); jTextField.setHorizontalAlignment(JTextField.CENTER); setBackgroundColor(i, j); // 文本填入处理 jTextField.setDocument(generatePlainDocument()); // 实时检测 if (realTimeTip.isEnabled()) { jTextField.addFocusListener(generateFocusListener(i, j)); } if (puzzleInts[i][j] == 0) { jTextField.setForeground(theme.getPuzzleForeground()); } else { jTextField.setForeground(theme.getSolutionForeground()); jTextField.setText(Integer.toString(puzzleInts[i][j])); jTextField.setFocusable(false); // 设置是否可获得焦点 } colorMap.put(i + "-" + j, jTextField.getForeground()); } } } // 文本填入处理 限制只允许输入一个数字,后填的数字覆盖前面的 private PlainDocument generatePlainDocument() { return new PlainDocument() { @Override public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (StrUtil.isEmpty(str)) { return; } int length = 0; char[] s = str.toCharArray(); for (int i = 0; i < s.length; i++) { // 过滤非数字 if ((s[i] >= '0') && (s[i] <= '9')) { s[length++] = s[i]; } } if (length > 0) { remove(0, getLength()); // 直接截取过滤后的 maxLength 长度的字符 String text = new String(s, 0, length).substring(0, maxLength); super.insertString(0, text, attr); } } }; } private void setBackgroundColor(int row, int col) { // 设置九宫格的背景颜色 贴近深色系统 // TODO: 2022/8/12 后面可以升级兼容浅色系统 if ((row / 3 == 0 && col / 3 == 0) || (row / 3 == 1 && col / 3 == 1) || (row / 3 == 2 && col / 3 == 2) || (row / 3 == 0 && col / 3 == 2) || (row / 3 == 2 && col / 3 == 0)) { chessBoard[row][col].setBackground(theme.getBackgroundColorUnit1()); } else { chessBoard[row][col].setBackground(theme.getBackgroundColorUnit2()); } } public JButton getCommitJButton() { JButton commit = new JButton("提交"); commit.addActionListener(e -> { refreshCheckInts(); int errorCount = checkSelfValues(checkGrid); if (errorCount > 0) { String failureInfo = "很遗憾,你填错了" + errorCount + "个格子!"; JOptionPane.showMessageDialog(null, failureInfo, "挑战失败!", JOptionPane.INFORMATION_MESSAGE); } else { String successInfo = "干得漂亮!完全正确!"; JOptionPane.showMessageDialog(null, successInfo, "挑战成功!", JOptionPane.INFORMATION_MESSAGE); } }); return commit; } // 用户解题数据 private void refreshCheckInts() { for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { String text = chessBoard[row][column].getText(); int defaultValue = -1; if (StrUtil.isNotEmpty(text) && Integer.parseInt(text) != 0) { defaultValue = Integer.parseInt(text); } checkGrid.getCell(row, column).setValue(defaultValue); } } } public JButton getTipsJButton() { JButton tips = new JButton("提示"); tips.addActionListener(e -> { refreshCheckInts(); int[][] checkInts = checkGrid.toArray(); for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { // 如果chessBoard内的文本与答案不相同 if (checkInts[row][column] != solutionInts[row][column]) { chessBoard[row][column].setForeground(theme.getTipForegroundResult()); chessBoard[row][column].setText(Integer.toString(solutionInts[row][column])); } // 刷新背景色 colorMap.put(row + "-" + column, chessBoard[row][column].getForeground()); } } }); return tips; } // 数据自检 返回true就是数据有问题 这个方法略微耗时 以后可以优化 private int checkSelfValues(Grid checkGrid) { int errorCount = 0; for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { Grid.Cell cell = checkGrid.getCell(row, column); int checkValue = cell.getValue(); // 如果是题面直接跳过 if (checkValue == puzzleInts[row][column]) { continue; } // 将待检查的位置数据替换为0 假装正要填下 进行自检 cell.setValue(0); if (checkValue == -1 || !checkGrid.isValidValueForCell(cell, checkValue) && checkValue != solutionInts[row][column]) { errorCount++; } cell.setValue(checkValue); } } return errorCount; } @Override public void actionPerformed(ActionEvent e) { } /** * 判断是否合法 * * @param board 数据集 * @param row 行索引 * @param column 列索引 * @param val 校验待的数 */ public Set<String> getConflictSet(int[][] board, int row, int column, int val) { Set<String> conflictSet = new HashSet<>(); // 列校验 for (int i = 0; i < 9; i++) { if (board[i][column] == val) conflictSet.add(i + "-" + column); } // 行校验 for (int j = 0; j < 9; j++) { if (board[row][j] == val) conflictSet.add(row + "-" + j); } // 3 * 3 单元校验 for (int x = row / 3 * 3, i = x; i < x + 3; i++) { for (int y = column / 3 * 3, j = y; j < y + 3; j++) { if (board[i][j] == val) conflictSet.add(i + "-" + j); } } // 不标记当前位置 if (conflictSet.size() == 1) { conflictSet.remove(row + "-" + column); } return conflictSet; } // 添加离焦监听 失去焦点后检测当前值是否冲突 private FocusListener generateFocusListener(int row, int column) { return new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { JTextField jTextField = (JTextField) e.getComponent(); checkValue(row, column, jTextField.getText()); } }; } // 校验当前填的值是否有冲突,冲突就高亮处理 private void checkValue(int row, int column, String text) { if ("".equals(text)) { return; } refreshCheckInts(); Set<String> conflictSet = getConflictSet(checkGrid.toArray(), row, column, Integer.parseInt(text)); // 冲突上色 conflictSet.forEach(s -> { String[] xy = s.split("-"); JTextField jTextField = chessBoard[Integer.parseInt(xy[0])][Integer.parseInt(xy[1])]; jTextField.setForeground(theme.getTipForegroundReal()); jTextField.repaint(); }); // 还原成原来的颜色 ThreadUtil.execAsync(() -> { ThreadUtils.spinMoment(3000); conflictSet.forEach(s -> { String[] xy = s.split("-"); JTextField jTextField = chessBoard[Integer.parseInt(xy[0])][Integer.parseInt(xy[1])]; jTextField.setForeground(colorMap.get(s)); jTextField.repaint(); }); }); } }
anlingyi/xechat-idea
xechat-plugin/src/main/java/cn/xeblog/plugin/game/sudoku/SudokuGui.java
2,820
// 还原成原来的颜色
line_comment
zh-cn
package cn.xeblog.plugin.game.sudoku; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.StrUtil; import cn.xeblog.commons.util.ThreadUtils; import cn.xeblog.plugin.game.sudoku.algorithm.Generator; import cn.xeblog.plugin.game.sudoku.algorithm.Grid; import cn.xeblog.plugin.game.sudoku.algorithm.Solver; import cn.xeblog.plugin.game.sudoku.enums.Level; import cn.xeblog.plugin.game.sudoku.enums.PanelSize; import cn.xeblog.plugin.game.sudoku.enums.RealTimeTip; import cn.xeblog.plugin.game.sudoku.enums.Theme; import javax.swing.*; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.List; import java.util.*; /** * 功能描述: 数独UI页面 * * @author ☆程序员鼓励师☆ * @date 2022/8/12 11:34 */ public class SudokuGui extends JPanel implements ActionListener { // 主题 private final Theme theme; // 题面 private int[][] puzzleInts; // 题解 private int[][] solutionInts; // 用户解题数据 private final Grid checkGrid = Grid.emptyGrid(); // 输入字符串最大长度 private final int maxLength = 1; // 缓存下所有格子的初始化背景色 private final Map<String, Color> colorMap = new HashMap<>(81); // 数据模块 private final JTextField[][] chessBoard = new JTextField[9][9]; public SudokuGui(Level level, PanelSize panelSize, RealTimeTip realTimeTip, Theme theme) { this.theme = theme; initData(level); initJPanel(panelSize, realTimeTip); repaint(); } private void initData(Level level) { // 题面 puzzleInts = new Generator().generate(level.getBlank()).toArray(); } public void doSolution(List<JButton> buttonList) { TimeInterval timer = DateUtil.timer(); // 题解 Grid grid = Grid.of(puzzleInts); new Solver().solve(grid); solutionInts = grid.toArray(); //System.out.println("算法耗时[" + timer.interval() + "]ms"); // 刷新按钮 buttonList.forEach(b -> { b.setEnabled(true); b.repaint(); }); } private void initJPanel(PanelSize panelSize, RealTimeTip realTimeTip) { this.setPreferredSize(new Dimension(panelSize.getTableWidth(), panelSize.getTableHeight())); this.setLayout(new GridLayout(9, 9)); this.setVisible(true); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { // 设置JTextField的内容 JTextField jTextField = new JTextField(); chessBoard[i][j] = jTextField; this.add(jTextField); jTextField.setVisible(true); jTextField.setFont(new Font("", Font.BOLD, panelSize.getFontSize())); jTextField.setHorizontalAlignment(JTextField.CENTER); setBackgroundColor(i, j); // 文本填入处理 jTextField.setDocument(generatePlainDocument()); // 实时检测 if (realTimeTip.isEnabled()) { jTextField.addFocusListener(generateFocusListener(i, j)); } if (puzzleInts[i][j] == 0) { jTextField.setForeground(theme.getPuzzleForeground()); } else { jTextField.setForeground(theme.getSolutionForeground()); jTextField.setText(Integer.toString(puzzleInts[i][j])); jTextField.setFocusable(false); // 设置是否可获得焦点 } colorMap.put(i + "-" + j, jTextField.getForeground()); } } } // 文本填入处理 限制只允许输入一个数字,后填的数字覆盖前面的 private PlainDocument generatePlainDocument() { return new PlainDocument() { @Override public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (StrUtil.isEmpty(str)) { return; } int length = 0; char[] s = str.toCharArray(); for (int i = 0; i < s.length; i++) { // 过滤非数字 if ((s[i] >= '0') && (s[i] <= '9')) { s[length++] = s[i]; } } if (length > 0) { remove(0, getLength()); // 直接截取过滤后的 maxLength 长度的字符 String text = new String(s, 0, length).substring(0, maxLength); super.insertString(0, text, attr); } } }; } private void setBackgroundColor(int row, int col) { // 设置九宫格的背景颜色 贴近深色系统 // TODO: 2022/8/12 后面可以升级兼容浅色系统 if ((row / 3 == 0 && col / 3 == 0) || (row / 3 == 1 && col / 3 == 1) || (row / 3 == 2 && col / 3 == 2) || (row / 3 == 0 && col / 3 == 2) || (row / 3 == 2 && col / 3 == 0)) { chessBoard[row][col].setBackground(theme.getBackgroundColorUnit1()); } else { chessBoard[row][col].setBackground(theme.getBackgroundColorUnit2()); } } public JButton getCommitJButton() { JButton commit = new JButton("提交"); commit.addActionListener(e -> { refreshCheckInts(); int errorCount = checkSelfValues(checkGrid); if (errorCount > 0) { String failureInfo = "很遗憾,你填错了" + errorCount + "个格子!"; JOptionPane.showMessageDialog(null, failureInfo, "挑战失败!", JOptionPane.INFORMATION_MESSAGE); } else { String successInfo = "干得漂亮!完全正确!"; JOptionPane.showMessageDialog(null, successInfo, "挑战成功!", JOptionPane.INFORMATION_MESSAGE); } }); return commit; } // 用户解题数据 private void refreshCheckInts() { for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { String text = chessBoard[row][column].getText(); int defaultValue = -1; if (StrUtil.isNotEmpty(text) && Integer.parseInt(text) != 0) { defaultValue = Integer.parseInt(text); } checkGrid.getCell(row, column).setValue(defaultValue); } } } public JButton getTipsJButton() { JButton tips = new JButton("提示"); tips.addActionListener(e -> { refreshCheckInts(); int[][] checkInts = checkGrid.toArray(); for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { // 如果chessBoard内的文本与答案不相同 if (checkInts[row][column] != solutionInts[row][column]) { chessBoard[row][column].setForeground(theme.getTipForegroundResult()); chessBoard[row][column].setText(Integer.toString(solutionInts[row][column])); } // 刷新背景色 colorMap.put(row + "-" + column, chessBoard[row][column].getForeground()); } } }); return tips; } // 数据自检 返回true就是数据有问题 这个方法略微耗时 以后可以优化 private int checkSelfValues(Grid checkGrid) { int errorCount = 0; for (int row = 0; row < 9; row++) { for (int column = 0; column < 9; column++) { Grid.Cell cell = checkGrid.getCell(row, column); int checkValue = cell.getValue(); // 如果是题面直接跳过 if (checkValue == puzzleInts[row][column]) { continue; } // 将待检查的位置数据替换为0 假装正要填下 进行自检 cell.setValue(0); if (checkValue == -1 || !checkGrid.isValidValueForCell(cell, checkValue) && checkValue != solutionInts[row][column]) { errorCount++; } cell.setValue(checkValue); } } return errorCount; } @Override public void actionPerformed(ActionEvent e) { } /** * 判断是否合法 * * @param board 数据集 * @param row 行索引 * @param column 列索引 * @param val 校验待的数 */ public Set<String> getConflictSet(int[][] board, int row, int column, int val) { Set<String> conflictSet = new HashSet<>(); // 列校验 for (int i = 0; i < 9; i++) { if (board[i][column] == val) conflictSet.add(i + "-" + column); } // 行校验 for (int j = 0; j < 9; j++) { if (board[row][j] == val) conflictSet.add(row + "-" + j); } // 3 * 3 单元校验 for (int x = row / 3 * 3, i = x; i < x + 3; i++) { for (int y = column / 3 * 3, j = y; j < y + 3; j++) { if (board[i][j] == val) conflictSet.add(i + "-" + j); } } // 不标记当前位置 if (conflictSet.size() == 1) { conflictSet.remove(row + "-" + column); } return conflictSet; } // 添加离焦监听 失去焦点后检测当前值是否冲突 private FocusListener generateFocusListener(int row, int column) { return new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { JTextField jTextField = (JTextField) e.getComponent(); checkValue(row, column, jTextField.getText()); } }; } // 校验当前填的值是否有冲突,冲突就高亮处理 private void checkValue(int row, int column, String text) { if ("".equals(text)) { return; } refreshCheckInts(); Set<String> conflictSet = getConflictSet(checkGrid.toArray(), row, column, Integer.parseInt(text)); // 冲突上色 conflictSet.forEach(s -> { String[] xy = s.split("-"); JTextField jTextField = chessBoard[Integer.parseInt(xy[0])][Integer.parseInt(xy[1])]; jTextField.setForeground(theme.getTipForegroundReal()); jTextField.repaint(); }); // 还原 <SUF> ThreadUtil.execAsync(() -> { ThreadUtils.spinMoment(3000); conflictSet.forEach(s -> { String[] xy = s.split("-"); JTextField jTextField = chessBoard[Integer.parseInt(xy[0])][Integer.parseInt(xy[1])]; jTextField.setForeground(colorMap.get(s)); jTextField.repaint(); }); }); } }
false
2,527
7
2,820
8
2,939
6
2,820
8
3,619
12
false
false
false
false
false
true
66469_5
//0020-有效的括号 //思路:暴力法;栈 //暴力法:思路简单,检测并替换成对括号为空串,最后判断字符串是否为空;但耗时过长 //栈:借鉴栈的应用中对四则运算的处理,成对弹出 //暴力法: /* 算法: - 每次检测是否有最里侧的成对某种括号,若有,则替换所有成对括号为空字符串,直到检测不到相邻的成对括号 - 遍历完成后,如果是有效表达式,则最后的字符串会只剩下空串,判断是否==空串 - 法一:在while小括号中判断: - while每次判断是否有相邻括号,如果有,则进入循环并进行替换操作 - 不用先判断是否为空,因为while判断包含 - 法二:在while的循环体中判断: - while(true)无限循环替换动作并在最后判断字符串长度是否改变,如果没有,break。 - 需要先判断是否为空,否则直接进入while循环 - 法二比法一稍快 - 经测试,法一超出时间限制,法二耗时100ms,超过5%的用户 */ //暴力法1:超时 class Solution { public boolean isValid(String s) { while(s.contains("()") || s.contains("[]") || s.contains("{}")){ //判断写在循环条件中,则每次循环都进行三次判断 s.replace("()",""); s.replace("[]",""); s.replace("{}",""); } //找不到相邻的成对括号时,检查字符串是否为空,为空则为有效,否则无效 return s.length() == 0; } } /* 注:Python代码未超时 class Solution: def isValid(self, s): while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == '' */ //暴力法2:耗时100ms,超过5%的用户 class Solution { public boolean isValid(String s) { //因为循环为true,因此循环前进行一次判断,避免不符合条件但直接进入循环造成浪费 if(s.isEmpty()) return true; while(true){ //设置一个flag对字符串在替换前后的变化进行监测 int length = s.length(); s = s.replace("()",""); s = s.replace("[]",""); s = s.replace("{}",""); //针对上述方法进行简化,将判断过程放在循环体中,减少了时间复杂度 if(length == s.length()) break; } //找不到相邻的成对括号时,检查字符串是否为空,为空则为有效,否则无效 return s.length() == 0; } } //栈:耗时3ms,打败58%的用户 /* 算法: - 初始化哈希表 char型 - 初始化栈 char型 - 遍历字符串,每次对遍历到的字符进行判断 - 压栈:遇到开括号,将其推到栈上。 - 弹栈:否则,当栈非空,且当前字符串的字符与栈顶元素配对成功时,弹栈 - 无效:否则,表达式无效。 - 最后,若栈非空,则表达式无效。 */ class Solution { public boolean isValid(String s) { //首先对一定true或一定false的情况进行判断 if(s == null || s.length() == 0) return true; if(s.length() % 2 != 0) return false; //创建哈希表并初始化 Map<Character, Character> map = new HashMap<>(); //后期如果想要根据key找是否存在对应的value,最好key右括号,value左括号 //注意:如果定义为char类型,要用单引号 map.put(')','('); map.put(']','['); map.put('}','{'); //创建栈并初始化 Stack<Character> stack = new Stack<>(); //遍历字符串s并依次判断:符合条件的分别压栈弹栈,不符合条件的return false for(int i=0; i<s.length(); i++){ //压栈的情况:当字符串遍历到左边括号时,可以进栈 if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){ stack.push(s.charAt(i)); } //弹栈的情况:栈非空,且当前字符串的字符与栈顶元素配对成功时,弹栈 else if(!stack.empty() && ( map.get(s.charAt(i)) == stack.peek() ) ){ stack.pop(); } //非法的情况:否则,返回false else return false; } //遍历结束后,若栈非空,返回false return stack.empty(); } }
anliux/PracticePool
LeetCode/src/0020-valid-parentheses.java
1,217
/* 算法: - 每次检测是否有最里侧的成对某种括号,若有,则替换所有成对括号为空字符串,直到检测不到相邻的成对括号 - 遍历完成后,如果是有效表达式,则最后的字符串会只剩下空串,判断是否==空串 - 法一:在while小括号中判断: - while每次判断是否有相邻括号,如果有,则进入循环并进行替换操作 - 不用先判断是否为空,因为while判断包含 - 法二:在while的循环体中判断: - while(true)无限循环替换动作并在最后判断字符串长度是否改变,如果没有,break。 - 需要先判断是否为空,否则直接进入while循环 - 法二比法一稍快 - 经测试,法一超出时间限制,法二耗时100ms,超过5%的用户 */
block_comment
zh-cn
//0020-有效的括号 //思路:暴力法;栈 //暴力法:思路简单,检测并替换成对括号为空串,最后判断字符串是否为空;但耗时过长 //栈:借鉴栈的应用中对四则运算的处理,成对弹出 //暴力法: /* 算法: <SUF>*/ //暴力法1:超时 class Solution { public boolean isValid(String s) { while(s.contains("()") || s.contains("[]") || s.contains("{}")){ //判断写在循环条件中,则每次循环都进行三次判断 s.replace("()",""); s.replace("[]",""); s.replace("{}",""); } //找不到相邻的成对括号时,检查字符串是否为空,为空则为有效,否则无效 return s.length() == 0; } } /* 注:Python代码未超时 class Solution: def isValid(self, s): while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == '' */ //暴力法2:耗时100ms,超过5%的用户 class Solution { public boolean isValid(String s) { //因为循环为true,因此循环前进行一次判断,避免不符合条件但直接进入循环造成浪费 if(s.isEmpty()) return true; while(true){ //设置一个flag对字符串在替换前后的变化进行监测 int length = s.length(); s = s.replace("()",""); s = s.replace("[]",""); s = s.replace("{}",""); //针对上述方法进行简化,将判断过程放在循环体中,减少了时间复杂度 if(length == s.length()) break; } //找不到相邻的成对括号时,检查字符串是否为空,为空则为有效,否则无效 return s.length() == 0; } } //栈:耗时3ms,打败58%的用户 /* 算法: - 初始化哈希表 char型 - 初始化栈 char型 - 遍历字符串,每次对遍历到的字符进行判断 - 压栈:遇到开括号,将其推到栈上。 - 弹栈:否则,当栈非空,且当前字符串的字符与栈顶元素配对成功时,弹栈 - 无效:否则,表达式无效。 - 最后,若栈非空,则表达式无效。 */ class Solution { public boolean isValid(String s) { //首先对一定true或一定false的情况进行判断 if(s == null || s.length() == 0) return true; if(s.length() % 2 != 0) return false; //创建哈希表并初始化 Map<Character, Character> map = new HashMap<>(); //后期如果想要根据key找是否存在对应的value,最好key右括号,value左括号 //注意:如果定义为char类型,要用单引号 map.put(')','('); map.put(']','['); map.put('}','{'); //创建栈并初始化 Stack<Character> stack = new Stack<>(); //遍历字符串s并依次判断:符合条件的分别压栈弹栈,不符合条件的return false for(int i=0; i<s.length(); i++){ //压栈的情况:当字符串遍历到左边括号时,可以进栈 if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){ stack.push(s.charAt(i)); } //弹栈的情况:栈非空,且当前字符串的字符与栈顶元素配对成功时,弹栈 else if(!stack.empty() && ( map.get(s.charAt(i)) == stack.peek() ) ){ stack.pop(); } //非法的情况:否则,返回false else return false; } //遍历结束后,若栈非空,返回false return stack.empty(); } }
false
1,108
211
1,216
220
1,218
206
1,217
220
1,831
350
false
false
false
false
false
true
22720_0
package _java; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import base.Base; public class _0073SetMatrixZeros extends Base { private abstract static class Solution { public abstract void setZeroes(int[][] matrix); } // 状态机 , 1ms beats 100% 但是理论上是不可以的这个 private static class Solution1 extends Solution { public void setZeroes(int[][] matrix) { final int m = matrix.length; final int n = matrix[0].length; // 一个用了 +1 理论上这个数是可能会有的,只是testcase覆盖不到. int tag = Integer.MIN_VALUE + 1; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { //fill tag for (int r = 0; r < m; ++r) { if (matrix[r][j] != 0) { matrix[r][j] = tag; } } for (int c = 0; c < n; ++c) { if (matrix[i][c] != 0) { matrix[i][c] = tag; } } } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == tag) { matrix[i][j] = 0; } } } } } // 这个更聪明,有效的利用了规律 private static class Solution2 extends Solution { public void setZeroes(int[][] matrix) { final int m = matrix.length, n = matrix[0].length; boolean r0 = false, c0 = false; for (int i = 0; i < m; ++i) { if (matrix[i][0] == 0) { // 第0列是0 c0 = true; break; } } for (int j = 0; j < n; ++j) { if (matrix[0][j] == 0) { // 第0行是0 r0 = true; break; } } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } // 将行首为0的行置0 for (int i = 1; i < m; ++i) { if (matrix[i][0] == 0) { Arrays.fill(matrix[i], 0); } } // 将列首为0的列置0 for (int i = 1; i < n; ++i) { if (matrix[0][i] == 0) { for (int j = 0; j < m; ++j) { matrix[j][i] = 0; } } } if (r0) { Arrays.fill(matrix[0], 0); } if (c0) { for (int i = 0; i < m; ++i) { matrix[i][0] = 0; } } } } // 3ms 17.62; private static class Solution3 extends Solution { public void setZeroes(int[][] matrix) { final int r = matrix.length, c = matrix[0].length; Set<Integer> rowSet = new HashSet<>(r); Set<Integer> colSet = new HashSet<>(c); for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if (matrix[i][j] == 0) { rowSet.add(i); colSet.add(j); } } } for (int i = 0; i < r; ++i) { if (rowSet.contains(i)) { Arrays.fill(matrix[i], 0); } } for (int i = 0; i < c; ++i) { if (colSet.contains(i)) { for (int j = 0; j < r; ++j) { matrix[j][i] = 0; } } } } } // 数组代替set 1ms private static class Solution4 extends Solution { public void setZeroes(int[][] matrix) { final int r = matrix.length, c = matrix[0].length; boolean[] rowSet = new boolean[r]; boolean[] colSet = new boolean[c]; for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if (matrix[i][j] == 0) { rowSet[i] = true; colSet[j] = true; } } } for (int i = 0; i < r; ++i) { if (rowSet[i]) { Arrays.fill(matrix[i], 0); } } for (int i = 0; i < c; ++i) { if (colSet[i]) { for (int j = 0; j < r; ++j) { matrix[j][i] = 0; } } } } } public static void main(String[] args) { int[][] m1 = new int[][]{ {1, 1, 1}, {1, 0, 1}, {1, 1, 1} }; int[][] m2 = new int[][]{ {0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5} }; Solution s = new Solution4(); s.setZeroes(m1); print2DArr(m1); s.setZeroes(m2); print2DArr(m2); } }
anmingyu11/AlgorithmsUnion
LeetCode/src/_java/_0073SetMatrixZeros.java
1,498
// 状态机 , 1ms beats 100% 但是理论上是不可以的这个
line_comment
zh-cn
package _java; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import base.Base; public class _0073SetMatrixZeros extends Base { private abstract static class Solution { public abstract void setZeroes(int[][] matrix); } // 状态 <SUF> private static class Solution1 extends Solution { public void setZeroes(int[][] matrix) { final int m = matrix.length; final int n = matrix[0].length; // 一个用了 +1 理论上这个数是可能会有的,只是testcase覆盖不到. int tag = Integer.MIN_VALUE + 1; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) { //fill tag for (int r = 0; r < m; ++r) { if (matrix[r][j] != 0) { matrix[r][j] = tag; } } for (int c = 0; c < n; ++c) { if (matrix[i][c] != 0) { matrix[i][c] = tag; } } } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == tag) { matrix[i][j] = 0; } } } } } // 这个更聪明,有效的利用了规律 private static class Solution2 extends Solution { public void setZeroes(int[][] matrix) { final int m = matrix.length, n = matrix[0].length; boolean r0 = false, c0 = false; for (int i = 0; i < m; ++i) { if (matrix[i][0] == 0) { // 第0列是0 c0 = true; break; } } for (int j = 0; j < n; ++j) { if (matrix[0][j] == 0) { // 第0行是0 r0 = true; break; } } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } // 将行首为0的行置0 for (int i = 1; i < m; ++i) { if (matrix[i][0] == 0) { Arrays.fill(matrix[i], 0); } } // 将列首为0的列置0 for (int i = 1; i < n; ++i) { if (matrix[0][i] == 0) { for (int j = 0; j < m; ++j) { matrix[j][i] = 0; } } } if (r0) { Arrays.fill(matrix[0], 0); } if (c0) { for (int i = 0; i < m; ++i) { matrix[i][0] = 0; } } } } // 3ms 17.62; private static class Solution3 extends Solution { public void setZeroes(int[][] matrix) { final int r = matrix.length, c = matrix[0].length; Set<Integer> rowSet = new HashSet<>(r); Set<Integer> colSet = new HashSet<>(c); for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if (matrix[i][j] == 0) { rowSet.add(i); colSet.add(j); } } } for (int i = 0; i < r; ++i) { if (rowSet.contains(i)) { Arrays.fill(matrix[i], 0); } } for (int i = 0; i < c; ++i) { if (colSet.contains(i)) { for (int j = 0; j < r; ++j) { matrix[j][i] = 0; } } } } } // 数组代替set 1ms private static class Solution4 extends Solution { public void setZeroes(int[][] matrix) { final int r = matrix.length, c = matrix[0].length; boolean[] rowSet = new boolean[r]; boolean[] colSet = new boolean[c]; for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if (matrix[i][j] == 0) { rowSet[i] = true; colSet[j] = true; } } } for (int i = 0; i < r; ++i) { if (rowSet[i]) { Arrays.fill(matrix[i], 0); } } for (int i = 0; i < c; ++i) { if (colSet[i]) { for (int j = 0; j < r; ++j) { matrix[j][i] = 0; } } } } } public static void main(String[] args) { int[][] m1 = new int[][]{ {1, 1, 1}, {1, 0, 1}, {1, 1, 1} }; int[][] m2 = new int[][]{ {0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5} }; Solution s = new Solution4(); s.setZeroes(m1); print2DArr(m1); s.setZeroes(m2); print2DArr(m2); } }
false
1,419
22
1,495
26
1,636
21
1,495
26
1,779
34
false
false
false
false
false
true
28229_1
package java_bean.day02; /** * @ClassName: Father.java * @Author: anpeng * @Date: 2023/11/1 9:57 */ public class Father { public int constant = 1013; public final void notOverride(){//final修饰的方法不可被重写。 System.out.println("not override"); } public void date(){//约会 System.out.println("爸爸约吃饭"); } public void greeting(){ System.out.println("拥抱"); } public static void method(){ System.out.println("Father method"); } public static void func(){ System.out.println("Father.func"); } }
anpeng1013/SongHongKang2023
src/java_bean/day02/Father.java
184
//final修饰的方法不可被重写。
line_comment
zh-cn
package java_bean.day02; /** * @ClassName: Father.java * @Author: anpeng * @Date: 2023/11/1 9:57 */ public class Father { public int constant = 1013; public final void notOverride(){//fi <SUF> System.out.println("not override"); } public void date(){//约会 System.out.println("爸爸约吃饭"); } public void greeting(){ System.out.println("拥抱"); } public static void method(){ System.out.println("Father method"); } public static void func(){ System.out.println("Father.func"); } }
false
151
9
184
11
185
10
184
11
219
15
false
false
false
false
false
true
22368_12
package dp; import java.util.*; /** * Developed by Lee Happily. * <p> * 有 n 个城市通过一些航班连接。给你一个数组 flights ,其中 flights[i] = [fromi, toi, pricei] ,表示该航班都从城市 fromi 开始,以价格 toi 抵达 pricei。 * <p> * 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到出一条最多经过 k 站中转的路线,使得从 src 到 dst 的 价格最便宜 ,并返回该价格。 如果不存在这样的路线,则输出 -1。 */ public class CheapestFlights { // dst ==> src,price private Map<Integer, List<int[]>> priceMap = new HashMap<>(); public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { k++; for (int[] flight : flights) { int from = flight[0]; int to = flight[1]; int price = flight[2]; priceMap.putIfAbsent(to, new LinkedList<>()); priceMap.get(to).add(new int[]{from, price}); } int[][] memos = new int[n][k + 1]; for (int[] row : memos) { Arrays.fill(row, -888); } return dp(memos, src, dst, k); } public int findCheapestPriceV2(int n, int[][] flights, int src, int dst, int k) { // 这里需要注意:因为是要在 k 次中转内,从 src 到达 dst,所以在图上遍历的边数就是 k+1 条,所以下面都是k+1 int K = k + 1; // dp 定义还同之前一样,dp[dst][k] 代表从原点出发在k步内到dst的代价 int[][] dp = new int[n][K + 1]; // 初始化 dp for (int[] ddp : dp) { Arrays.fill(ddp, Integer.MAX_VALUE); } for (int i = 0; i <= K; i++) { // src -> src 在 k 步内的代价都是 0 dp[src][i] = 0; } for (int i = 1; i <= K; i++) { for (int[] flight : flights) { int s = flight[0]; int d = flight[1]; int price = flight[2]; if (dp[s][i - 1] != Integer.MAX_VALUE) { dp[d][i] = Math.min(dp[d][i], dp[s][i - 1] + price); } } } return dp[dst][K] == Integer.MAX_VALUE ? -1 : dp[dst][K]; } // 这一版本由于递归深度会超时 private int dp(int[][] memos, int src, int dst, int k) { if (src == dst) { return 0; } if (k == 0) { // 没有转机次数 return -1; } if (memos[dst][k] > 0) { return memos[dst][k]; } int min = Integer.MAX_VALUE; List<int[]> pathList = priceMap.get(dst); if (pathList == null) { return -1; } for (int[] fromPrice : pathList) { int from = fromPrice[0]; int price = fromPrice[1]; int subProblem = dp(memos, src, from, k - 1); if (subProblem == -1) { // 没有路线 continue; } min = Math.min(subProblem + price, min); } memos[dst][k] = min == Integer.MAX_VALUE ? -1 : min; return memos[dst][k]; } } // 动态规划关键在于定好状态转移方程。 // 刚开始由于定义不准确,导致路线错误。如何定义 dp 还是需要多加练习。 // 经历了一晚上加一早上的努力,终于 accepted 了,这种刚开始进入一个陌生的体系的时候,死磕还是有必要的,因为死磕过程中, // 你会有很多疑问。伴随着这些疑问的解答,慢慢就找到感觉了。
anriclee/leetcode
java/solution/src/main/java/dp/CheapestFlights.java
1,087
// 你会有很多疑问。伴随着这些疑问的解答,慢慢就找到感觉了。
line_comment
zh-cn
package dp; import java.util.*; /** * Developed by Lee Happily. * <p> * 有 n 个城市通过一些航班连接。给你一个数组 flights ,其中 flights[i] = [fromi, toi, pricei] ,表示该航班都从城市 fromi 开始,以价格 toi 抵达 pricei。 * <p> * 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到出一条最多经过 k 站中转的路线,使得从 src 到 dst 的 价格最便宜 ,并返回该价格。 如果不存在这样的路线,则输出 -1。 */ public class CheapestFlights { // dst ==> src,price private Map<Integer, List<int[]>> priceMap = new HashMap<>(); public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { k++; for (int[] flight : flights) { int from = flight[0]; int to = flight[1]; int price = flight[2]; priceMap.putIfAbsent(to, new LinkedList<>()); priceMap.get(to).add(new int[]{from, price}); } int[][] memos = new int[n][k + 1]; for (int[] row : memos) { Arrays.fill(row, -888); } return dp(memos, src, dst, k); } public int findCheapestPriceV2(int n, int[][] flights, int src, int dst, int k) { // 这里需要注意:因为是要在 k 次中转内,从 src 到达 dst,所以在图上遍历的边数就是 k+1 条,所以下面都是k+1 int K = k + 1; // dp 定义还同之前一样,dp[dst][k] 代表从原点出发在k步内到dst的代价 int[][] dp = new int[n][K + 1]; // 初始化 dp for (int[] ddp : dp) { Arrays.fill(ddp, Integer.MAX_VALUE); } for (int i = 0; i <= K; i++) { // src -> src 在 k 步内的代价都是 0 dp[src][i] = 0; } for (int i = 1; i <= K; i++) { for (int[] flight : flights) { int s = flight[0]; int d = flight[1]; int price = flight[2]; if (dp[s][i - 1] != Integer.MAX_VALUE) { dp[d][i] = Math.min(dp[d][i], dp[s][i - 1] + price); } } } return dp[dst][K] == Integer.MAX_VALUE ? -1 : dp[dst][K]; } // 这一版本由于递归深度会超时 private int dp(int[][] memos, int src, int dst, int k) { if (src == dst) { return 0; } if (k == 0) { // 没有转机次数 return -1; } if (memos[dst][k] > 0) { return memos[dst][k]; } int min = Integer.MAX_VALUE; List<int[]> pathList = priceMap.get(dst); if (pathList == null) { return -1; } for (int[] fromPrice : pathList) { int from = fromPrice[0]; int price = fromPrice[1]; int subProblem = dp(memos, src, from, k - 1); if (subProblem == -1) { // 没有路线 continue; } min = Math.min(subProblem + price, min); } memos[dst][k] = min == Integer.MAX_VALUE ? -1 : min; return memos[dst][k]; } } // 动态规划关键在于定好状态转移方程。 // 刚开始由于定义不准确,导致路线错误。如何定义 dp 还是需要多加练习。 // 经历了一晚上加一早上的努力,终于 accepted 了,这种刚开始进入一个陌生的体系的时候,死磕还是有必要的,因为死磕过程中, // 你会 <SUF>
false
980
18
1,087
28
1,065
18
1,087
28
1,364
54
false
false
false
false
false
true
63205_37
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import org.weixin4j.model.sns.SnsAccessToken; import org.weixin4j.http.Response; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.apache.commons.lang.StringUtils; import org.weixin4j.Configuration; import org.weixin4j.model.sns.SnsUser; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; /** * 网页授权获取用户基本信息 * * @author yangqisheng * @since 0.1.0 */ public class SnsComponent extends AbstractComponent { /** * 默认授权请求URL */ private String authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize"; /** * 网页授权基础支持 * * @param weixin 微信对象 */ public SnsComponent(Weixin weixin) { super(weixin); } /** * 开放的网页授权基础支持 * * @param weixin 微信对象 * @param authorize_url 第三方网页授权开发URL */ public SnsComponent(Weixin weixin, String authorize_url) { super(weixin); this.authorize_url = authorize_url; } /** * 静默授权获取openid * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @return 静默授权链接 */ public String getOAuth2CodeBaseUrl(String redirect_uri) { return getOAuth2CodeUrl(redirect_uri, "snsapi_base", "DEFAULT"); } /** * 网页安全授权获取用户信息 * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @return 网页安全授权链接 */ public String getOAuth2CodeUserInfoUrl(String redirect_uri) { return getOAuth2CodeUrl(redirect_uri, "snsapi_userinfo", "DEFAULT"); } /** * 获取授权链接 * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @param scope 应用授权作用域,snsapi_base * (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo * (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) * @param state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节 * @return 授权链接 */ public String getOAuth2CodeUrl(String redirect_uri, String scope, String state) { try { return authorize_url + "?appid=" + weixin.getAppId() + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&response_type=code&scope=" + scope + "&state=" + state + "&connect_redirect=1#wechat_redirect"; } catch (UnsupportedEncodingException ex) { return ""; } } /** * 获取微信用户OpenId * * @param code 仅能使用一次 * @return 微信用户OpenId * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public String getOpenId(String code) throws WeixinException { SnsAccessToken snsAccessToken = getSnsOAuth2AccessToken(code); return snsAccessToken.getOpenid(); } /** * 获取网页授权AccessToken * * @param code 换取身份唯一凭证 * @return 网页授权AccessToken * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public SnsAccessToken getSnsOAuth2AccessToken(String code) throws WeixinException { if (StringUtils.isEmpty(code)) { throw new IllegalArgumentException("code can't be null or empty"); } //拼接参数 String param = "?appid=" + weixin.getAppId() + "&secret=" + weixin.getSecret() + "&code=" + code + "&grant_type=authorization_code"; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/oauth2/access_token" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { return null; } if (Configuration.isDebug()) { System.out.println("getSnsOAuth2AccessToken返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } return new SnsAccessToken(jsonObj); } /** * 检验授权凭证(access_token)是否有效 * * @param access_token 网页授权接口调用凭证 * @param openid 用户的唯一标识 * @return 可用返回true,否则返回false * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public boolean validateAccessToken(String access_token, String openid) throws WeixinException { if (StringUtils.isEmpty(access_token)) { throw new IllegalArgumentException("access_token can't be null or empty"); } if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } //拼接参数 String param = "?access_token=" + access_token + "&openid=" + openid; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/auth" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("validateAccessToken返回json:" + jsonObj.toString()); } return jsonObj.getIntValue("errcode") == 0; } return false; } /** * 刷新用户网页授权AccessToken * * @param refresh_token 用户刷新access_token * @return 刷新后的用户网页授权AccessToken * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public SnsAccessToken refreshToken(String refresh_token) throws WeixinException { if (StringUtils.isEmpty(refresh_token)) { throw new IllegalArgumentException("refresh_token can't be null or empty"); } //拼接参数 String param = "?appid=" + weixin.getAppId() + "&refresh_token=" + refresh_token + "&grant_type=refresh_token"; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/oauth2/refresh_token" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("refreshToken返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //判断是否登录成功,并判断过期时间 Object obj = jsonObj.get("access_token"); //登录成功,设置accessToken和过期时间 if (obj != null) { //设置凭证 return new SnsAccessToken(jsonObj); } } return null; } /** * 拉取用户信息 * * @param code 换取身份唯一凭证 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SnsUser getSnsUserByCode(String code) throws WeixinException { //默认简体中文 return getSnsUserByCode(code, "zh_CN"); } /** * 拉取用户信息 * * @param code 换取身份唯一凭证 * @param lang 国家地区语言版本 zh_CN 简体,zh_TW 繁体,en 英语 * @return 网页授权用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SnsUser getSnsUserByCode(String code, String lang) throws WeixinException { if (StringUtils.isEmpty(code)) { throw new IllegalArgumentException("code can't be null or empty"); } if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } SnsAccessToken snsAccessToken = getSnsOAuth2AccessToken(code); return getSnsUser(snsAccessToken.getAccess_token(), snsAccessToken.getOpenid(), lang); } /** * 拉取用户信息 * * @param access_token 网页授权接口调用凭证 * @param openid 用户的唯一标识 * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ private SnsUser getSnsUser(String access_token, String openid, String lang) throws WeixinException { if (StringUtils.isEmpty(access_token)) { throw new IllegalArgumentException("access_token can't be null or empty"); } if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } SnsUser user = null; //拼接参数 String param = "?access_token=" + access_token + "&openid=" + openid + "&lang=" + lang; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/userinfo" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("getSnsUser返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //设置公众号信息 user = (SnsUser) JSONObject.toJavaObject(jsonObj, SnsUser.class); } return user; } }
ansitech/weixin4j
src/main/java/org/weixin4j/component/SnsComponent.java
2,805
//拼接参数
line_comment
zh-cn
/* * 微信公众平台(JAVA) SDK * * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved. * * http://www.weixin4j.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.weixin4j.component; import com.alibaba.fastjson.JSONObject; import org.weixin4j.model.sns.SnsAccessToken; import org.weixin4j.http.Response; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.apache.commons.lang.StringUtils; import org.weixin4j.Configuration; import org.weixin4j.model.sns.SnsUser; import org.weixin4j.Weixin; import org.weixin4j.WeixinException; import org.weixin4j.http.HttpsClient; /** * 网页授权获取用户基本信息 * * @author yangqisheng * @since 0.1.0 */ public class SnsComponent extends AbstractComponent { /** * 默认授权请求URL */ private String authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize"; /** * 网页授权基础支持 * * @param weixin 微信对象 */ public SnsComponent(Weixin weixin) { super(weixin); } /** * 开放的网页授权基础支持 * * @param weixin 微信对象 * @param authorize_url 第三方网页授权开发URL */ public SnsComponent(Weixin weixin, String authorize_url) { super(weixin); this.authorize_url = authorize_url; } /** * 静默授权获取openid * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @return 静默授权链接 */ public String getOAuth2CodeBaseUrl(String redirect_uri) { return getOAuth2CodeUrl(redirect_uri, "snsapi_base", "DEFAULT"); } /** * 网页安全授权获取用户信息 * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @return 网页安全授权链接 */ public String getOAuth2CodeUserInfoUrl(String redirect_uri) { return getOAuth2CodeUrl(redirect_uri, "snsapi_userinfo", "DEFAULT"); } /** * 获取授权链接 * * @param redirect_uri 授权后重定向的回调链接地址(不用编码) * @param scope 应用授权作用域,snsapi_base * (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo * (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 ) * @param state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节 * @return 授权链接 */ public String getOAuth2CodeUrl(String redirect_uri, String scope, String state) { try { return authorize_url + "?appid=" + weixin.getAppId() + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&response_type=code&scope=" + scope + "&state=" + state + "&connect_redirect=1#wechat_redirect"; } catch (UnsupportedEncodingException ex) { return ""; } } /** * 获取微信用户OpenId * * @param code 仅能使用一次 * @return 微信用户OpenId * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public String getOpenId(String code) throws WeixinException { SnsAccessToken snsAccessToken = getSnsOAuth2AccessToken(code); return snsAccessToken.getOpenid(); } /** * 获取网页授权AccessToken * * @param code 换取身份唯一凭证 * @return 网页授权AccessToken * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public SnsAccessToken getSnsOAuth2AccessToken(String code) throws WeixinException { if (StringUtils.isEmpty(code)) { throw new IllegalArgumentException("code can't be null or empty"); } //拼接参数 String param = "?appid=" + weixin.getAppId() + "&secret=" + weixin.getSecret() + "&code=" + code + "&grant_type=authorization_code"; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/oauth2/access_token" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj == null) { return null; } if (Configuration.isDebug()) { System.out.println("getSnsOAuth2AccessToken返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } return new SnsAccessToken(jsonObj); } /** * 检验授权凭证(access_token)是否有效 * * @param access_token 网页授权接口调用凭证 * @param openid 用户的唯一标识 * @return 可用返回true,否则返回false * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public boolean validateAccessToken(String access_token, String openid) throws WeixinException { if (StringUtils.isEmpty(access_token)) { throw new IllegalArgumentException("access_token can't be null or empty"); } if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } //拼接参数 String param = "?access_token=" + access_token + "&openid=" + openid; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/auth" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("validateAccessToken返回json:" + jsonObj.toString()); } return jsonObj.getIntValue("errcode") == 0; } return false; } /** * 刷新用户网页授权AccessToken * * @param refresh_token 用户刷新access_token * @return 刷新后的用户网页授权AccessToken * @throws org.weixin4j.WeixinException 微信操作异常 * @since 0.1.0 */ public SnsAccessToken refreshToken(String refresh_token) throws WeixinException { if (StringUtils.isEmpty(refresh_token)) { throw new IllegalArgumentException("refresh_token can't be null or empty"); } //拼接参数 String param = "?appid=" + weixin.getAppId() + "&refresh_token=" + refresh_token + "&grant_type=refresh_token"; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/oauth2/refresh_token" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("refreshToken返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //判断是否登录成功,并判断过期时间 Object obj = jsonObj.get("access_token"); //登录成功,设置accessToken和过期时间 if (obj != null) { //设置凭证 return new SnsAccessToken(jsonObj); } } return null; } /** * 拉取用户信息 * * @param code 换取身份唯一凭证 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SnsUser getSnsUserByCode(String code) throws WeixinException { //默认简体中文 return getSnsUserByCode(code, "zh_CN"); } /** * 拉取用户信息 * * @param code 换取身份唯一凭证 * @param lang 国家地区语言版本 zh_CN 简体,zh_TW 繁体,en 英语 * @return 网页授权用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ public SnsUser getSnsUserByCode(String code, String lang) throws WeixinException { if (StringUtils.isEmpty(code)) { throw new IllegalArgumentException("code can't be null or empty"); } if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } SnsAccessToken snsAccessToken = getSnsOAuth2AccessToken(code); return getSnsUser(snsAccessToken.getAccess_token(), snsAccessToken.getOpenid(), lang); } /** * 拉取用户信息 * * @param access_token 网页授权接口调用凭证 * @param openid 用户的唯一标识 * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @return 用户对象 * @throws org.weixin4j.WeixinException 微信操作异常 */ private SnsUser getSnsUser(String access_token, String openid, String lang) throws WeixinException { if (StringUtils.isEmpty(access_token)) { throw new IllegalArgumentException("access_token can't be null or empty"); } if (StringUtils.isEmpty(openid)) { throw new IllegalArgumentException("openid can't be null or empty"); } if (StringUtils.isEmpty(lang)) { throw new IllegalArgumentException("lang can't be null or empty"); } SnsUser user = null; //拼接 <SUF> String param = "?access_token=" + access_token + "&openid=" + openid + "&lang=" + lang; //创建请求对象 HttpsClient http = new HttpsClient(); //调用获取access_token接口 Response res = http.get("https://api.weixin.qq.com/sns/userinfo" + param); //根据请求结果判定,是否验证成功 JSONObject jsonObj = res.asJSONObject(); if (jsonObj != null) { if (Configuration.isDebug()) { System.out.println("getSnsUser返回json:" + jsonObj.toString()); } Object errcode = jsonObj.get("errcode"); if (errcode != null) { //返回异常信息 throw new WeixinException(getCause(jsonObj.getIntValue("errcode"))); } //设置公众号信息 user = (SnsUser) JSONObject.toJavaObject(jsonObj, SnsUser.class); } return user; } }
false
2,628
4
2,805
5
2,941
3
2,805
5
3,905
7
false
false
false
false
false
true
59831_3
package love.cq.domain; import love.cq.util.AnsjArrays; public class Branch implements WoodInterface { /** * status 此字的状态1,继续 2,是个词语但是还可以继续 ,3确定 nature 词语性质 */ WoodInterface[] branches = null; private char c; // 状态 private byte status = 1; // 单独查找出来的对象 WoodInterface branch = null; // 词典后的参数 private String[] param = null; public WoodInterface add(WoodInterface branch) { if (branches == null) { branches = new WoodInterface[0]; } int bs = AnsjArrays.binarySearch(branches, branch.getC()); if (bs >= 0) { this.branch = this.branches[bs]; switch (branch.getStatus()) { case -1: this.branch.setStatus(1); break; case 1: if (this.branch.getStatus() == 3) { this.branch.setStatus(2); } break; case 3: if (this.branch.getStatus() != 3) { this.branch.setStatus(2); } this.branch.setParam(branch.getParams()); } return this.branch; } else { WoodInterface[] newBranches = new WoodInterface[branches.length + 1]; int insert = -(bs + 1); System.arraycopy(branches, 0, newBranches, 0, insert); System.arraycopy(branches, insert, newBranches, insert + 1, branches.length - insert); newBranches[insert] = branch; branches = newBranches; return branch; } } public Branch(char c, int status, String[] param) { this.c = c; this.status = (byte) status; this.param = param; } public WoodInterface get(char c) { if (this.branches == null) { return null; } int i = AnsjArrays.binarySearch(this.branches, c); if (i < 0) { return null; } return this.branches[i]; } public boolean contains(char c) { if (this.branches == null) { return false; } return AnsjArrays.binarySearch(this.branches, c) > -1; } public int compareTo(char c) { if (this.c > c) return 1; if (this.c < c) { return -1; } return 0; } public boolean equals(char c) { return this.c == c; } @Override public int hashCode() { return this.c; } public byte getStatus() { return this.status; } public void setStatus(int status) { this.status = (byte) status; } public char getC() { return this.c; } public String[] getParams() { return this.param; } /** * 得道第几个参数 * * @param i * @return */ public String getParam(int i) { if (param != null && param.length > i) { return param[i]; } return null; } public void setParam(String[] param) { this.param = param; } }
ansjsun/tree_split
src/main/java/love/cq/domain/Branch.java
889
// 词典后的参数
line_comment
zh-cn
package love.cq.domain; import love.cq.util.AnsjArrays; public class Branch implements WoodInterface { /** * status 此字的状态1,继续 2,是个词语但是还可以继续 ,3确定 nature 词语性质 */ WoodInterface[] branches = null; private char c; // 状态 private byte status = 1; // 单独查找出来的对象 WoodInterface branch = null; // 词典 <SUF> private String[] param = null; public WoodInterface add(WoodInterface branch) { if (branches == null) { branches = new WoodInterface[0]; } int bs = AnsjArrays.binarySearch(branches, branch.getC()); if (bs >= 0) { this.branch = this.branches[bs]; switch (branch.getStatus()) { case -1: this.branch.setStatus(1); break; case 1: if (this.branch.getStatus() == 3) { this.branch.setStatus(2); } break; case 3: if (this.branch.getStatus() != 3) { this.branch.setStatus(2); } this.branch.setParam(branch.getParams()); } return this.branch; } else { WoodInterface[] newBranches = new WoodInterface[branches.length + 1]; int insert = -(bs + 1); System.arraycopy(branches, 0, newBranches, 0, insert); System.arraycopy(branches, insert, newBranches, insert + 1, branches.length - insert); newBranches[insert] = branch; branches = newBranches; return branch; } } public Branch(char c, int status, String[] param) { this.c = c; this.status = (byte) status; this.param = param; } public WoodInterface get(char c) { if (this.branches == null) { return null; } int i = AnsjArrays.binarySearch(this.branches, c); if (i < 0) { return null; } return this.branches[i]; } public boolean contains(char c) { if (this.branches == null) { return false; } return AnsjArrays.binarySearch(this.branches, c) > -1; } public int compareTo(char c) { if (this.c > c) return 1; if (this.c < c) { return -1; } return 0; } public boolean equals(char c) { return this.c == c; } @Override public int hashCode() { return this.c; } public byte getStatus() { return this.status; } public void setStatus(int status) { this.status = (byte) status; } public char getC() { return this.c; } public String[] getParams() { return this.param; } /** * 得道第几个参数 * * @param i * @return */ public String getParam(int i) { if (param != null && param.length > i) { return param[i]; } return null; } public void setParam(String[] param) { this.param = param; } }
false
725
7
888
7
873
6
888
7
1,092
11
false
false
false
false
false
true
32104_0
package 面向对象中级.homework; public class Homework11 { public static void main(String[] args) { Person2[] p2 = new Person2[4]; p2[0] = new Student1("yang",'男',24,"120224"); p2[1] = new Student1("yan",'男',32,"120224"); p2[2] = new Teacher1("ya",'女',33,5); p2[3] = new Teacher1("y",'女',56,10); Student1 student1 = new Student1("xiao", 'n', 12, "00020003"); student1.printInfo(); Teacher1 teacher1 = new Teacher1("las", 'n', 33, 20); teacher1.printInfo(); Homework11 homework11 = new Homework11(); homework11.bubbleSort(p2); for (int i = 0; i < p2.length; i++) { System.out.println(p2[i].toString()); } //遍历多态数组 System.out.println("========"); for (int i = 0; i < p2.length; i++) { homework11.test(p2[i]); } } public void test(Person2 person2) { if (person2 instanceof Student1) { ((Student1) person2).study(); } else if (person2 instanceof Teacher1) { ((Teacher1) person2).teach(); } else { System.out.println("do nothing"); } } public void bubbleSort(Person2[] p2) { Person2 temp = null; for (int i = 0; i < p2.length - 1; i++) { for (int j = 0; j < p2.length - 1 - i; j++) { if (p2[j].getAge() < p2[j + 1].getAge()) { temp = p2[j]; p2[j] = p2[j + 1]; p2[j + 1] = temp; } } } } } class Person2 { private String name; private char sex; private int age; public Person2(String name, char sex, int age) { this.name = name; this.sex = sex; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String play() { return name + "玩游戏"; } public String basicInfo() { return "姓名" + name + "\n年龄" + age + "\n性别" + sex; } @Override public String toString() { return "Person2{" + "name='" + name + '\'' + ", sex=" + sex + ", age=" + age + '}'; } } class Student1 extends Person2{ private String stuid; public Student1(String name, char sex, int age, String stuid) { super(name, sex, age); this.stuid = stuid; } public String getStuid() { return stuid; } public void setStuid(String stuid) { this.stuid = stuid; } @Override public String toString() { return "Student1{" + "stuid='" + stuid + '\'' + '}' + super.toString(); } public void study() { System.out.println(getName() + "承认 我会好好学习"); } public String paly() { return super.play() + "爱玩足球"; } public void printInfo() { System.out.println("学 生的信息"); System.out.println(super.basicInfo()); System.out.println("学号" + stuid); study(); System.out.println(paly()); } } class Teacher1 extends Person2{ private int workage; public Teacher1(String name, char sex, int age, int workage) { super(name, sex, age); this.workage = workage; } public int getWorkage() { return workage; } public void setWorkage(int workage) { this.workage = workage; } @Override public String toString() { return "Teacher1{" + "workage=" + workage + '}' + super.toString(); } public void teach() { System.out.println(getName() + "承认 我会认真教学"); } public String play() { return super.play() + "爱玩象棋"; } public void printInfo() { System.out.println("老师的信息"); System.out.println(super.basicInfo()); System.out.println("工龄" + workage); teach(); System.out.println(play()); } }
anteisuba/daily-jp
7章面对对象编程-中级/Homework/Homework11.java
1,259
//遍历多态数组
line_comment
zh-cn
package 面向对象中级.homework; public class Homework11 { public static void main(String[] args) { Person2[] p2 = new Person2[4]; p2[0] = new Student1("yang",'男',24,"120224"); p2[1] = new Student1("yan",'男',32,"120224"); p2[2] = new Teacher1("ya",'女',33,5); p2[3] = new Teacher1("y",'女',56,10); Student1 student1 = new Student1("xiao", 'n', 12, "00020003"); student1.printInfo(); Teacher1 teacher1 = new Teacher1("las", 'n', 33, 20); teacher1.printInfo(); Homework11 homework11 = new Homework11(); homework11.bubbleSort(p2); for (int i = 0; i < p2.length; i++) { System.out.println(p2[i].toString()); } //遍历 <SUF> System.out.println("========"); for (int i = 0; i < p2.length; i++) { homework11.test(p2[i]); } } public void test(Person2 person2) { if (person2 instanceof Student1) { ((Student1) person2).study(); } else if (person2 instanceof Teacher1) { ((Teacher1) person2).teach(); } else { System.out.println("do nothing"); } } public void bubbleSort(Person2[] p2) { Person2 temp = null; for (int i = 0; i < p2.length - 1; i++) { for (int j = 0; j < p2.length - 1 - i; j++) { if (p2[j].getAge() < p2[j + 1].getAge()) { temp = p2[j]; p2[j] = p2[j + 1]; p2[j + 1] = temp; } } } } } class Person2 { private String name; private char sex; private int age; public Person2(String name, char sex, int age) { this.name = name; this.sex = sex; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String play() { return name + "玩游戏"; } public String basicInfo() { return "姓名" + name + "\n年龄" + age + "\n性别" + sex; } @Override public String toString() { return "Person2{" + "name='" + name + '\'' + ", sex=" + sex + ", age=" + age + '}'; } } class Student1 extends Person2{ private String stuid; public Student1(String name, char sex, int age, String stuid) { super(name, sex, age); this.stuid = stuid; } public String getStuid() { return stuid; } public void setStuid(String stuid) { this.stuid = stuid; } @Override public String toString() { return "Student1{" + "stuid='" + stuid + '\'' + '}' + super.toString(); } public void study() { System.out.println(getName() + "承认 我会好好学习"); } public String paly() { return super.play() + "爱玩足球"; } public void printInfo() { System.out.println("学 生的信息"); System.out.println(super.basicInfo()); System.out.println("学号" + stuid); study(); System.out.println(paly()); } } class Teacher1 extends Person2{ private int workage; public Teacher1(String name, char sex, int age, int workage) { super(name, sex, age); this.workage = workage; } public int getWorkage() { return workage; } public void setWorkage(int workage) { this.workage = workage; } @Override public String toString() { return "Teacher1{" + "workage=" + workage + '}' + super.toString(); } public void teach() { System.out.println(getName() + "承认 我会认真教学"); } public String play() { return super.play() + "爱玩象棋"; } public void printInfo() { System.out.println("老师的信息"); System.out.println(super.basicInfo()); System.out.println("工龄" + workage); teach(); System.out.println(play()); } }
false
1,146
6
1,259
5
1,362
5
1,259
5
1,504
11
false
false
false
false
false
true
20746_0
package designmode.facade; /*门面模式: 外部与一个子系统的通信必须通过一个统一的门面(Facade)对象来进行 * 1. 举例: * 医院(子系统角色): 挂号,门诊,划价,化验,收费,取药各个子系统 * 病人: 需要和医院的各个子系统打交道 * 门面(门面角色):相当于接待员,病人和接待员打交道,接待员和医院内部各个子系统通信 * * 2. 使用 * (1)为一个复杂的系统提供一个简单的接口 * (2)提高子系统的独立性 * */ public class Facade { private ICook icook; private IWaiter iwaiter; private IPayment ipay; public Facade() { ipay = new PaymentImp(); icook = new CookImp(); iwaiter = new WaiterImp(); } public void serve() { String food = ipay.pay(); food = icook.cook(food); iwaiter.serve(food); } }
anty-zhang/programing_language
java/designmode/facade/Facade.java
296
/*门面模式: 外部与一个子系统的通信必须通过一个统一的门面(Facade)对象来进行 * 1. 举例: * 医院(子系统角色): 挂号,门诊,划价,化验,收费,取药各个子系统 * 病人: 需要和医院的各个子系统打交道 * 门面(门面角色):相当于接待员,病人和接待员打交道,接待员和医院内部各个子系统通信 * * 2. 使用 * (1)为一个复杂的系统提供一个简单的接口 * (2)提高子系统的独立性 * */
block_comment
zh-cn
package designmode.facade; /*门面模 <SUF>*/ public class Facade { private ICook icook; private IWaiter iwaiter; private IPayment ipay; public Facade() { ipay = new PaymentImp(); icook = new CookImp(); iwaiter = new WaiterImp(); } public void serve() { String food = ipay.pay(); food = icook.cook(food); iwaiter.serve(food); } }
false
251
150
296
174
272
150
296
174
400
259
false
false
false
false
false
true
20738_17
/** * @Copyright: Copyright (c) 2015-2-14 * @Company: 智慧云康(北京)数据科技有限公司 */ package com.chd.hrp.sys.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.springframework.dao.DataAccessException; import com.chd.base.SqlMapper; import com.chd.hrp.sys.entity.Emp; /** * @Title. @Description. * @Author: LiuYingDuo * @email: bell@s-chd.com * @Version: 1.0 */ public interface EmpMapper extends SqlMapper{ /** * @Description 查询刚查询序列号 * @param * @return long * @throws DataAccessException */ public long queryCurrentSequence()throws DataAccessException; /** * @Description 添加Emp * @param Emp entityMap * @return int * @throws DataAccessException */ public int addEmp(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 批量添加Emp * @param Emp entityMap * @return int * @throws DataAccessException */ public int addBatchEmp(List<Map<String, Object>> entityMap)throws DataAccessException; /** * @Description 查询Emp分页 * @param entityMap RowBounds * @return List<Emp> * @throws DataAccessException */ public List<Emp> queryEmp(Map<String,Object> entityMap, RowBounds rowBounds) throws DataAccessException; /** * @Description 查询Emp所有数据 * @param entityMap * @return List<Emp> * @throws DataAccessException */ public List<Emp> queryEmp(Map<String,Object> entityMap) throws DataAccessException; /** * @Description 查询EmpByCode * @param entityMap * @return int * @throws DataAccessException */ public Emp queryEmpByCode(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 删除Emp * @param entityMap * @return int * @throws DataAccessException */ public int deleteEmp(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 批量删除Emp * @param entityMap * @return int * @throws DataAccessException */ public int deleteBatchEmp(List<Map<String, Object>> entityMap)throws DataAccessException; /** * @Description 更新Emp * @param entityMap * @return int * @throws DataAccessException */ public int updateEmp(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 更新EmpName * @param entityMap * @return int * @throws DataAccessException */ public int updateEmpName(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 更新EmpCode * @param entityMap * @return int * @throws DataAccessException */ public int updateEmpCode(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 查询序列 * @param * @return int * @throws DataAccessException */ public int queryEmpSeqNextVal()throws DataAccessException; /** * @Description 批量更新Emp * @param entityMap * @return int * @throws DataAccessException */ public int updateBatchEmp(List<Map<String, Object>> entityMap)throws DataAccessException; /** * 查询当前集团、医院下 职工的最大排序号 * @param entityMap * @return */ public Emp queryMaxEmp_sort(Map<String, Object> entityMap)throws DataAccessException; /** * 查询当前集团、医院下 与输入职工 排序号 相同的职工记录 (判断排序号是否已存在) * @param entityMap * @return * @throws DataAccessException */ public Emp queryEmp_sort(Map<String, Object> entityMap)throws DataAccessException; /** * 添加、修改时 根据输入的 职工编码查询 当前集团、医院 下 与其相同的 职工记录 (判断职工编码是否存在) * @param entityMap * @return */ public Emp queryEmpById(Map<String, Object> entityMap); public int addBatchHosEmp(List<Map<String,Object>> entityList)throws DataAccessException; public abstract int addEmpChange(Map<String, Object> paramMap) throws DataAccessException; public abstract List<Emp> queryEmpChangeRemark(Map<String, Object> paramMap) throws DataAccessException; }
anxinHub/chdHRP
src/com/chd/hrp/sys/dao/EmpMapper.java
1,144
/** * 添加、修改时 根据输入的 职工编码查询 当前集团、医院 下 与其相同的 职工记录 (判断职工编码是否存在) * @param entityMap * @return */
block_comment
zh-cn
/** * @Copyright: Copyright (c) 2015-2-14 * @Company: 智慧云康(北京)数据科技有限公司 */ package com.chd.hrp.sys.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.springframework.dao.DataAccessException; import com.chd.base.SqlMapper; import com.chd.hrp.sys.entity.Emp; /** * @Title. @Description. * @Author: LiuYingDuo * @email: bell@s-chd.com * @Version: 1.0 */ public interface EmpMapper extends SqlMapper{ /** * @Description 查询刚查询序列号 * @param * @return long * @throws DataAccessException */ public long queryCurrentSequence()throws DataAccessException; /** * @Description 添加Emp * @param Emp entityMap * @return int * @throws DataAccessException */ public int addEmp(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 批量添加Emp * @param Emp entityMap * @return int * @throws DataAccessException */ public int addBatchEmp(List<Map<String, Object>> entityMap)throws DataAccessException; /** * @Description 查询Emp分页 * @param entityMap RowBounds * @return List<Emp> * @throws DataAccessException */ public List<Emp> queryEmp(Map<String,Object> entityMap, RowBounds rowBounds) throws DataAccessException; /** * @Description 查询Emp所有数据 * @param entityMap * @return List<Emp> * @throws DataAccessException */ public List<Emp> queryEmp(Map<String,Object> entityMap) throws DataAccessException; /** * @Description 查询EmpByCode * @param entityMap * @return int * @throws DataAccessException */ public Emp queryEmpByCode(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 删除Emp * @param entityMap * @return int * @throws DataAccessException */ public int deleteEmp(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 批量删除Emp * @param entityMap * @return int * @throws DataAccessException */ public int deleteBatchEmp(List<Map<String, Object>> entityMap)throws DataAccessException; /** * @Description 更新Emp * @param entityMap * @return int * @throws DataAccessException */ public int updateEmp(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 更新EmpName * @param entityMap * @return int * @throws DataAccessException */ public int updateEmpName(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 更新EmpCode * @param entityMap * @return int * @throws DataAccessException */ public int updateEmpCode(Map<String,Object> entityMap)throws DataAccessException; /** * @Description 查询序列 * @param * @return int * @throws DataAccessException */ public int queryEmpSeqNextVal()throws DataAccessException; /** * @Description 批量更新Emp * @param entityMap * @return int * @throws DataAccessException */ public int updateBatchEmp(List<Map<String, Object>> entityMap)throws DataAccessException; /** * 查询当前集团、医院下 职工的最大排序号 * @param entityMap * @return */ public Emp queryMaxEmp_sort(Map<String, Object> entityMap)throws DataAccessException; /** * 查询当前集团、医院下 与输入职工 排序号 相同的职工记录 (判断排序号是否已存在) * @param entityMap * @return * @throws DataAccessException */ public Emp queryEmp_sort(Map<String, Object> entityMap)throws DataAccessException; /** * 添加、 <SUF>*/ public Emp queryEmpById(Map<String, Object> entityMap); public int addBatchHosEmp(List<Map<String,Object>> entityList)throws DataAccessException; public abstract int addEmpChange(Map<String, Object> paramMap) throws DataAccessException; public abstract List<Emp> queryEmpChangeRemark(Map<String, Object> paramMap) throws DataAccessException; }
false
1,034
53
1,144
52
1,214
47
1,144
52
1,446
85
false
false
false
false
false
true
12517_36
package com.example.demo.pojo; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.*; /** * 患者用户档案表 * * @author Autumn * @email * @date 2019-11-03 21:27:15 */ @Table(name = "dzm_his_patient_file") public class DzmHisPatientFile implements Serializable { private static final long serialVersionUID = 1L; //主键 @Id private Integer fileId; //患者id @Column(name = "patient_id") private Integer patientId; //紧急联系人 @Column(name = "emergency_contact_name") private String emergencyContactName; //紧急联系人电话 @Column(name = "emergency_contact_mobile") private String emergencyContactMobile; //紧急联系人关系 1:爸爸 2:妈妈 3:儿子 4:女儿 5:亲戚 6:朋友 @Column(name = "emergency_contact_relation") private Integer emergencyContactRelation; //左耳听力 1:正常 2:耳聋 @Column(name = "left_ear_hearing") private Integer leftEarHearing; //右耳听力 1:正常 2:耳聋 @Column(name = "right_ear_hearing") private Integer rightEarHearing; //左眼视力 @Column(name = "left_vision") private BigDecimal leftVision; //修改时间 @Column(name = "update_time") private Integer updateTime; //右眼视力 @Column(name = "right_vision") private BigDecimal rightVision; //身高 @Column(name = "height") private BigDecimal height; //体重 @Column(name = "weight") private BigDecimal weight; //血型 1:A 2:B 3:AB 4:O Rh血型 1:阴性 2:阳性 @Column(name = "blood_type") private String bloodType; //创建时间 @Column(name = "create_time") private Integer createTime; //个人史 @Column(name = "personal_info") private String personalInfo; //家族史 @Column(name = "family_info") private String familyInfo; public DzmHisPatientFile() { super(); } public DzmHisPatientFile(Integer fileId, Integer patientId, String emergencyContactName, String emergencyContactMobile, Integer emergencyContactRelation, Integer leftEarHearing, Integer rightEarHearing, BigDecimal leftVision, Integer updateTime, BigDecimal rightVision, BigDecimal height, BigDecimal weight, String bloodType, String personalInfo, String familyInfo) { super(); this.fileId = fileId; this.patientId = patientId; this.emergencyContactName = emergencyContactName; this.emergencyContactMobile = emergencyContactMobile; this.emergencyContactRelation = emergencyContactRelation; this.leftEarHearing = leftEarHearing; this.rightEarHearing = rightEarHearing; this.leftVision = leftVision; this.updateTime = updateTime; this.rightVision = rightVision; this.height = height; this.weight = weight; this.bloodType = bloodType; this.personalInfo = personalInfo; this.familyInfo = familyInfo; } @Override public String toString() { return "DzmHisPatientFile [patientId=" + patientId + ", emergencyContactName=" + emergencyContactName + ", emergencyContactMobile=" + emergencyContactMobile + ", emergencyContactRelation=" + emergencyContactRelation + ", leftEarHearing=" + leftEarHearing + ", rightEarHearing=" + rightEarHearing + ", leftVision=" + leftVision + ", updateTime=" + updateTime + ", rightVision=" + rightVision + ", height=" + height + ", weight=" + weight + ", bloodType=" + bloodType + ", createTime=" + createTime + ", personalInfo=" + personalInfo + ", familyInfo=" + familyInfo + "]"; } /** * 设置:主键 */ public void setFileId(Integer fileId) { this.fileId = fileId; } /** * 获取:主键 */ public Integer getFileId() { return fileId; } /** * 设置:患者id */ public void setPatientId(Integer patientId) { this.patientId = patientId; } /** * 获取:患者id */ public Integer getPatientId() { return patientId; } /** * 设置:紧急联系人 */ public void setEmergencyContactName(String emergencyContactName) { this.emergencyContactName = emergencyContactName; } /** * 获取:紧急联系人 */ public String getEmergencyContactName() { return emergencyContactName; } /** * 设置:紧急联系人电话 */ public void setEmergencyContactMobile(String emergencyContactMobile) { this.emergencyContactMobile = emergencyContactMobile; } /** * 获取:紧急联系人电话 */ public String getEmergencyContactMobile() { return emergencyContactMobile; } /** * 设置:紧急联系人关系 1:爸爸 2:妈妈 3:儿子 4:女儿 5:亲戚 6:朋友 */ public void setEmergencyContactRelation(Integer emergencyContactRelation) { this.emergencyContactRelation = emergencyContactRelation; } /** * 获取:紧急联系人关系 1:爸爸 2:妈妈 3:儿子 4:女儿 5:亲戚 6:朋友 */ public Integer getEmergencyContactRelation() { return emergencyContactRelation; } /** * 设置:左耳听力 1:正常 2:耳聋 */ public void setLeftEarHearing(Integer leftEarHearing) { this.leftEarHearing = leftEarHearing; } /** * 获取:左耳听力 1:正常 2:耳聋 */ public Integer getLeftEarHearing() { return leftEarHearing; } /** * 设置:右耳听力 1:正常 2:耳聋 */ public void setRightEarHearing(Integer rightEarHearing) { this.rightEarHearing = rightEarHearing; } /** * 获取:右耳听力 1:正常 2:耳聋 */ public Integer getRightEarHearing() { return rightEarHearing; } /** * 设置:左眼视力 */ public void setLeftVision(BigDecimal leftVision) { this.leftVision = leftVision; } /** * 获取:左眼视力 */ public BigDecimal getLeftVision() { return leftVision; } /** * 设置:修改时间 */ public void setUpdateTime(Integer updateTime) { this.updateTime = updateTime; } /** * 获取:修改时间 */ public Integer getUpdateTime() { return updateTime; } /** * 设置:右眼视力 */ public void setRightVision(BigDecimal rightVision) { this.rightVision = rightVision; } /** * 获取:右眼视力 */ public BigDecimal getRightVision() { return rightVision; } /** * 设置:身高 */ public void setHeight(BigDecimal height) { this.height = height; } /** * 获取:身高 */ public BigDecimal getHeight() { return height; } /** * 设置:体重 */ public void setWeight(BigDecimal weight) { this.weight = weight; } /** * 获取:体重 */ public BigDecimal getWeight() { return weight; } /** * 设置:血型 1:A 2:B 3:AB 4:O Rh血型 1:阴性 2:阳性 */ public void setBloodType(String bloodType) { this.bloodType = bloodType; } /** * 获取:血型 1:A 2:B 3:AB 4:O Rh血型 1:阴性 2:阳性 */ public String getBloodType() { return bloodType; } /** * 设置:创建时间 */ public void setCreateTime(Integer createTime) { this.createTime = createTime; } /** * 获取:创建时间 */ public Integer getCreateTime() { return createTime; } /** * 设置:个人史 */ public void setPersonalInfo(String personalInfo) { this.personalInfo = personalInfo; } /** * 获取:个人史 */ public String getPersonalInfo() { return personalInfo; } /** * 设置:家族史 */ public void setFamilyInfo(String familyInfo) { this.familyInfo = familyInfo; } /** * 获取:家族史 */ public String getFamilyInfo() { return familyInfo; } }
anxinghei/HIS_JAVA
src/main/java/com/example/demo/pojo/DzmHisPatientFile.java
2,419
/** * 设置:体重 */
block_comment
zh-cn
package com.example.demo.pojo; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.*; /** * 患者用户档案表 * * @author Autumn * @email * @date 2019-11-03 21:27:15 */ @Table(name = "dzm_his_patient_file") public class DzmHisPatientFile implements Serializable { private static final long serialVersionUID = 1L; //主键 @Id private Integer fileId; //患者id @Column(name = "patient_id") private Integer patientId; //紧急联系人 @Column(name = "emergency_contact_name") private String emergencyContactName; //紧急联系人电话 @Column(name = "emergency_contact_mobile") private String emergencyContactMobile; //紧急联系人关系 1:爸爸 2:妈妈 3:儿子 4:女儿 5:亲戚 6:朋友 @Column(name = "emergency_contact_relation") private Integer emergencyContactRelation; //左耳听力 1:正常 2:耳聋 @Column(name = "left_ear_hearing") private Integer leftEarHearing; //右耳听力 1:正常 2:耳聋 @Column(name = "right_ear_hearing") private Integer rightEarHearing; //左眼视力 @Column(name = "left_vision") private BigDecimal leftVision; //修改时间 @Column(name = "update_time") private Integer updateTime; //右眼视力 @Column(name = "right_vision") private BigDecimal rightVision; //身高 @Column(name = "height") private BigDecimal height; //体重 @Column(name = "weight") private BigDecimal weight; //血型 1:A 2:B 3:AB 4:O Rh血型 1:阴性 2:阳性 @Column(name = "blood_type") private String bloodType; //创建时间 @Column(name = "create_time") private Integer createTime; //个人史 @Column(name = "personal_info") private String personalInfo; //家族史 @Column(name = "family_info") private String familyInfo; public DzmHisPatientFile() { super(); } public DzmHisPatientFile(Integer fileId, Integer patientId, String emergencyContactName, String emergencyContactMobile, Integer emergencyContactRelation, Integer leftEarHearing, Integer rightEarHearing, BigDecimal leftVision, Integer updateTime, BigDecimal rightVision, BigDecimal height, BigDecimal weight, String bloodType, String personalInfo, String familyInfo) { super(); this.fileId = fileId; this.patientId = patientId; this.emergencyContactName = emergencyContactName; this.emergencyContactMobile = emergencyContactMobile; this.emergencyContactRelation = emergencyContactRelation; this.leftEarHearing = leftEarHearing; this.rightEarHearing = rightEarHearing; this.leftVision = leftVision; this.updateTime = updateTime; this.rightVision = rightVision; this.height = height; this.weight = weight; this.bloodType = bloodType; this.personalInfo = personalInfo; this.familyInfo = familyInfo; } @Override public String toString() { return "DzmHisPatientFile [patientId=" + patientId + ", emergencyContactName=" + emergencyContactName + ", emergencyContactMobile=" + emergencyContactMobile + ", emergencyContactRelation=" + emergencyContactRelation + ", leftEarHearing=" + leftEarHearing + ", rightEarHearing=" + rightEarHearing + ", leftVision=" + leftVision + ", updateTime=" + updateTime + ", rightVision=" + rightVision + ", height=" + height + ", weight=" + weight + ", bloodType=" + bloodType + ", createTime=" + createTime + ", personalInfo=" + personalInfo + ", familyInfo=" + familyInfo + "]"; } /** * 设置:主键 */ public void setFileId(Integer fileId) { this.fileId = fileId; } /** * 获取:主键 */ public Integer getFileId() { return fileId; } /** * 设置:患者id */ public void setPatientId(Integer patientId) { this.patientId = patientId; } /** * 获取:患者id */ public Integer getPatientId() { return patientId; } /** * 设置:紧急联系人 */ public void setEmergencyContactName(String emergencyContactName) { this.emergencyContactName = emergencyContactName; } /** * 获取:紧急联系人 */ public String getEmergencyContactName() { return emergencyContactName; } /** * 设置:紧急联系人电话 */ public void setEmergencyContactMobile(String emergencyContactMobile) { this.emergencyContactMobile = emergencyContactMobile; } /** * 获取:紧急联系人电话 */ public String getEmergencyContactMobile() { return emergencyContactMobile; } /** * 设置:紧急联系人关系 1:爸爸 2:妈妈 3:儿子 4:女儿 5:亲戚 6:朋友 */ public void setEmergencyContactRelation(Integer emergencyContactRelation) { this.emergencyContactRelation = emergencyContactRelation; } /** * 获取:紧急联系人关系 1:爸爸 2:妈妈 3:儿子 4:女儿 5:亲戚 6:朋友 */ public Integer getEmergencyContactRelation() { return emergencyContactRelation; } /** * 设置:左耳听力 1:正常 2:耳聋 */ public void setLeftEarHearing(Integer leftEarHearing) { this.leftEarHearing = leftEarHearing; } /** * 获取:左耳听力 1:正常 2:耳聋 */ public Integer getLeftEarHearing() { return leftEarHearing; } /** * 设置:右耳听力 1:正常 2:耳聋 */ public void setRightEarHearing(Integer rightEarHearing) { this.rightEarHearing = rightEarHearing; } /** * 获取:右耳听力 1:正常 2:耳聋 */ public Integer getRightEarHearing() { return rightEarHearing; } /** * 设置:左眼视力 */ public void setLeftVision(BigDecimal leftVision) { this.leftVision = leftVision; } /** * 获取:左眼视力 */ public BigDecimal getLeftVision() { return leftVision; } /** * 设置:修改时间 */ public void setUpdateTime(Integer updateTime) { this.updateTime = updateTime; } /** * 获取:修改时间 */ public Integer getUpdateTime() { return updateTime; } /** * 设置:右眼视力 */ public void setRightVision(BigDecimal rightVision) { this.rightVision = rightVision; } /** * 获取:右眼视力 */ public BigDecimal getRightVision() { return rightVision; } /** * 设置:身高 */ public void setHeight(BigDecimal height) { this.height = height; } /** * 获取:身高 */ public BigDecimal getHeight() { return height; } /** * 设置: <SUF>*/ public void setWeight(BigDecimal weight) { this.weight = weight; } /** * 获取:体重 */ public BigDecimal getWeight() { return weight; } /** * 设置:血型 1:A 2:B 3:AB 4:O Rh血型 1:阴性 2:阳性 */ public void setBloodType(String bloodType) { this.bloodType = bloodType; } /** * 获取:血型 1:A 2:B 3:AB 4:O Rh血型 1:阴性 2:阳性 */ public String getBloodType() { return bloodType; } /** * 设置:创建时间 */ public void setCreateTime(Integer createTime) { this.createTime = createTime; } /** * 获取:创建时间 */ public Integer getCreateTime() { return createTime; } /** * 设置:个人史 */ public void setPersonalInfo(String personalInfo) { this.personalInfo = personalInfo; } /** * 获取:个人史 */ public String getPersonalInfo() { return personalInfo; } /** * 设置:家族史 */ public void setFamilyInfo(String familyInfo) { this.familyInfo = familyInfo; } /** * 获取:家族史 */ public String getFamilyInfo() { return familyInfo; } }
false
1,995
9
2,419
9
2,334
10
2,419
9
3,001
13
false
false
false
false
false
true
47004_9
package com.anxpp.designpattern.memento; //自述历史备忘录 public class MementoSelf { public static void main(String[] args) { OriginatorCaretaker originatorCaretaker = new OriginatorCaretaker();//发起人,同时为负责人 originatorCaretaker.changeState("stateOne"); //改变状态 IMemento memento = originatorCaretaker.createMemento(); //保存状态 originatorCaretaker.changeState("stateTwo"); //改变状态 originatorCaretaker.recoverMemento(memento); //恢复状态 } } interface IMemento {} //发起人兼负责人 class OriginatorCaretaker { public String state; public void changeState(String state){ this.state = state; } //创造快照 public Memento createMemento(){ return new Memento(this); } //恢复状态 public void recoverMemento(IMemento memento){ Memento m = (Memento)memento; changeState(m.state); } //内部类实现备忘录 private class Memento implements IMemento{ private String state; private Memento(OriginatorCaretaker originatorCaretaker){ this.state = originatorCaretaker.state; } } }
anxpp/JavaDesignPattern
src/com/anxpp/designpattern/memento/MementoSelf.java
349
//内部类实现备忘录
line_comment
zh-cn
package com.anxpp.designpattern.memento; //自述历史备忘录 public class MementoSelf { public static void main(String[] args) { OriginatorCaretaker originatorCaretaker = new OriginatorCaretaker();//发起人,同时为负责人 originatorCaretaker.changeState("stateOne"); //改变状态 IMemento memento = originatorCaretaker.createMemento(); //保存状态 originatorCaretaker.changeState("stateTwo"); //改变状态 originatorCaretaker.recoverMemento(memento); //恢复状态 } } interface IMemento {} //发起人兼负责人 class OriginatorCaretaker { public String state; public void changeState(String state){ this.state = state; } //创造快照 public Memento createMemento(){ return new Memento(this); } //恢复状态 public void recoverMemento(IMemento memento){ Memento m = (Memento)memento; changeState(m.state); } //内部 <SUF> private class Memento implements IMemento{ private String state; private Memento(OriginatorCaretaker originatorCaretaker){ this.state = originatorCaretaker.state; } } }
false
287
8
341
9
307
8
341
9
389
14
false
false
false
false
false
true
8849_3
/* * Copyright 2006-2023 www.anyline.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.anyline.util; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class TextUtil { /** * 相似度 * @param doc1 doc1 * @param doc2 doc2 * @return double */ public static double similarity(String doc1, String doc2) { if (doc1 != null && doc1.trim().length() > 0 && doc2 != null && doc2.trim().length() > 0) { Map<Integer, int[]> AlgorithmMap = new HashMap<Integer, int[]>(); // 将两个字符串中的中文字符以及出现的总数封装到, AlgorithmMap中 for (int i = 0; i < doc1.length(); i++) { char d1 = doc1.charAt(i); if(isHanZi(d1)){//标点和数字不处理 int charIndex = getGB2312Id(d1);//保存字符对应的GB2312编码 if(charIndex != -1){ int[] fq = AlgorithmMap.get(charIndex); if(fq != null && fq.length == 2){ fq[0]++;//已有该字符, 加1 }else { fq = new int[2]; fq[0] = 1; fq[1] = 0; AlgorithmMap.put(charIndex, fq);//新增字符入map } } } } for (int i = 0; i < doc2.length(); i++) { char d2 = doc2.charAt(i); if(isHanZi(d2)){ int charIndex = getGB2312Id(d2); if(charIndex != -1){ int[] fq = AlgorithmMap.get(charIndex); if(fq != null && fq.length == 2){ fq[1]++; }else { fq = new int[2]; fq[0] = 0; fq[1] = 1; AlgorithmMap.put(charIndex, fq); } } } } Iterator<Integer> iterator = AlgorithmMap.keySet().iterator(); double sqdoc1 = 0; double sqdoc2 = 0; double denominator = 0; while(iterator.hasNext()){ int[] c = AlgorithmMap.get(iterator.next()); denominator += c[0]*c[1]; sqdoc1 += c[0]*c[0]; sqdoc2 += c[1]*c[1]; } return denominator / Math.sqrt(sqdoc1*sqdoc2);//余弦计算 } else { throw new NullPointerException(" the Document is null or have not cahrs!!"); } } public static boolean isHanZi(char ch) { // 判断是否汉字 return (ch >= 0x4E00 && ch <= 0x9FA5); /*if (ch >= 0x4E00 && ch <= 0x9FA5) {//汉字 return true; }else{ String str = "" + ch; boolean isNum = str.matches("[0-9]+"); return isNum; }*/ /*if(Character.isLetterOrDigit(ch)){ String str = "" + ch; if (str.matches("[0-9a-zA-Z\\u4e00-\\u9fa5]+")){//非乱码 return true; }else return false; }else return false;*/ } /** * 根据输入的Unicode字符, 获取它的GB2312编码或者ascii编码, * * @param ch 输入的GB2312中文字符或者ASCII字符(128个) * @return ch在GB2312中的位置, -1表示该字符不认识 */ public static short getGB2312Id(char ch) { try { byte[] buffer = Character.toString(ch).getBytes("GB2312"); if (buffer.length != 2) { // 正常情况下buffer应该是两个字节, 否则说明ch不属于GB2312编码, 故返回'?', 此时说明不认识该字符 return -1; } int b0 = (int) (buffer[0] & 0x0FF) - 161; // 编码从A1开始, 因此减去0xA1=161 int b1 = (int) (buffer[1] & 0x0FF) - 161; return (short) (b0 * 94 + b1);// 第一个字符和最后一个字符没有汉字, 因此每个区只收16*6-2=94个汉字 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return -1; } }
anylineorg/anyline
anyline-core/src/main/java/org/anyline/util/TextUtil.java
1,274
//标点和数字不处理
line_comment
zh-cn
/* * Copyright 2006-2023 www.anyline.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.anyline.util; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class TextUtil { /** * 相似度 * @param doc1 doc1 * @param doc2 doc2 * @return double */ public static double similarity(String doc1, String doc2) { if (doc1 != null && doc1.trim().length() > 0 && doc2 != null && doc2.trim().length() > 0) { Map<Integer, int[]> AlgorithmMap = new HashMap<Integer, int[]>(); // 将两个字符串中的中文字符以及出现的总数封装到, AlgorithmMap中 for (int i = 0; i < doc1.length(); i++) { char d1 = doc1.charAt(i); if(isHanZi(d1)){//标点 <SUF> int charIndex = getGB2312Id(d1);//保存字符对应的GB2312编码 if(charIndex != -1){ int[] fq = AlgorithmMap.get(charIndex); if(fq != null && fq.length == 2){ fq[0]++;//已有该字符, 加1 }else { fq = new int[2]; fq[0] = 1; fq[1] = 0; AlgorithmMap.put(charIndex, fq);//新增字符入map } } } } for (int i = 0; i < doc2.length(); i++) { char d2 = doc2.charAt(i); if(isHanZi(d2)){ int charIndex = getGB2312Id(d2); if(charIndex != -1){ int[] fq = AlgorithmMap.get(charIndex); if(fq != null && fq.length == 2){ fq[1]++; }else { fq = new int[2]; fq[0] = 0; fq[1] = 1; AlgorithmMap.put(charIndex, fq); } } } } Iterator<Integer> iterator = AlgorithmMap.keySet().iterator(); double sqdoc1 = 0; double sqdoc2 = 0; double denominator = 0; while(iterator.hasNext()){ int[] c = AlgorithmMap.get(iterator.next()); denominator += c[0]*c[1]; sqdoc1 += c[0]*c[0]; sqdoc2 += c[1]*c[1]; } return denominator / Math.sqrt(sqdoc1*sqdoc2);//余弦计算 } else { throw new NullPointerException(" the Document is null or have not cahrs!!"); } } public static boolean isHanZi(char ch) { // 判断是否汉字 return (ch >= 0x4E00 && ch <= 0x9FA5); /*if (ch >= 0x4E00 && ch <= 0x9FA5) {//汉字 return true; }else{ String str = "" + ch; boolean isNum = str.matches("[0-9]+"); return isNum; }*/ /*if(Character.isLetterOrDigit(ch)){ String str = "" + ch; if (str.matches("[0-9a-zA-Z\\u4e00-\\u9fa5]+")){//非乱码 return true; }else return false; }else return false;*/ } /** * 根据输入的Unicode字符, 获取它的GB2312编码或者ascii编码, * * @param ch 输入的GB2312中文字符或者ASCII字符(128个) * @return ch在GB2312中的位置, -1表示该字符不认识 */ public static short getGB2312Id(char ch) { try { byte[] buffer = Character.toString(ch).getBytes("GB2312"); if (buffer.length != 2) { // 正常情况下buffer应该是两个字节, 否则说明ch不属于GB2312编码, 故返回'?', 此时说明不认识该字符 return -1; } int b0 = (int) (buffer[0] & 0x0FF) - 161; // 编码从A1开始, 因此减去0xA1=161 int b1 = (int) (buffer[1] & 0x0FF) - 161; return (short) (b0 * 94 + b1);// 第一个字符和最后一个字符没有汉字, 因此每个区只收16*6-2=94个汉字 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return -1; } }
false
1,206
7
1,274
7
1,365
7
1,274
7
1,586
9
false
false
false
false
false
true
49715_5
package com.anysoft.util; import java.util.Comparator; import java.util.Iterator; /** * 超级Set * <p>Java中的{@link java.util.Set}不支持模糊的查找(颇为想念C++STL中的Set)。超级Set则支持模糊查找,见{@link #lowerBound(Object)}.<p> * <p>超级Set通过链表实现插入,通过数组实现检索,力图达到插入效率和查找效率的平衡。</p> * @author duanyy * * @param <object> 对象的类名 */ public class SuperSet<object> { /** * 链表结构的列表 */ private SuperSetItem<object> root = new SuperSetItem<object>(); /** * 当前的对象个数 */ private int currentCount = 0; /** * 数据结构的列表 */ private SuperSetItem<object> [] array = null; /** * 数组结构和链表结构之间是否进行了同步 */ private boolean isSync = false; /** * 对象的比较器 */ private Comparator<object> comparator = null; /** * 构造函数,指定对象的比较器 * <p>如果不指定对象的比较器,则要求对象实现了{@link Comparable}接口。</p> * @param _comparator */ public SuperSet(Comparator<object> _comparator){ comparator = _comparator; } /** * 构造函数 */ public SuperSet(){ this(null); } /** * 比较两个对象的大小 * @param obj1 对象1 * @param obj2 对象2 * @return 如果相等,返回为0;如果obj1大于obj2,则返回为1;如果obj1小于obj2,则返回为-1 */ @SuppressWarnings("unchecked") private int compare(object obj1,object obj2){ if (comparator != null){ return comparator.compare(obj1, obj2); } Comparable<object> c = (Comparable<object>)obj1; return c.compareTo(obj2); } /** * 从链表结构同步到数组结构 */ @SuppressWarnings("unchecked") private void sync(){ if (currentCount <= 0) return ; if (array == null){ array = new SuperSetItem[currentCount * 2]; }else{ if (array.length < currentCount){ for (int i = 0 ; i < array.length ; i ++){ array[i] = null; } array = new SuperSetItem[currentCount * 2]; } } int index = 0; SuperSetItem<object> current = root; while (current.next != null){ array[index ++] = current.next; current = current.next; } for (;index < array.length; index++){ array[index] = null; } isSync = true; } /** * 回到第一个对象位置 * @return 迭代器 */ public Iterator<object> begin(){ return new SuperSetIterator<object>(root.next); } /** * 当前Set中对象个数 * @return 对象个数 */ public int size(){ return currentCount; } /** * 向Set中增加对象 * @param data 对象实例 */ synchronized public void add(object data){ if (data == null) return; //先找到位置 SuperSetItem<object> current = root; while (current.next != null){ int ret = compare(data,current.next.content); if (ret == 0){ //如果相等,替代他 current.next.content = data; return ; } if (ret < 0){ //找到了插入位置 break; } current = current.next; } SuperSetItem<object> newItem = new SuperSetItem<object>(); newItem.content = data; newItem.next = current.next; current.next = newItem; currentCount ++; isSync = false; } /** * 从Set中删除对象 * <p>删除的不是data对象实例本身,而是Set中"等于"该对象的对象实例。</p> * @param data 对象实例 */ synchronized public void remove(object data){ if (data == null) return ; //先找到位置 SuperSetItem<object> current = root; while (current.next != null){ int ret = compare(data,current.next.content); if (ret == 0){ current.next.content = null; current.next = current.next.next; currentCount --; isSync = false; return ; } current = current.next; } } /** * 清空Set */ synchronized public void clear(){ isSync = false; SuperSetItem<object> current = root; while (current.next != null){ current.next.content = null; current = current.next; } root.next = null; currentCount = 0; } /** * 按索引查找对象 * @param index 对象位置 * @return 对象实例 */ synchronized public object get(int index){ if (!isSync){ sync(); } if (index < 0 || index >= currentCount) return null; return array[index].content; } /** * 查找对象 * @param data 对象实例 * @return "等于"data的对象实例 */ synchronized public object get(object data){ if (!isSync){ sync(); } int iIndex = 0; int iStart = 0; int iEnd = array.length - 1; while (true){ iIndex = (iStart + iEnd) / 2; int ret = compare(data,array[iIndex].content); if (ret == 0){ return array[iIndex].content; } if (ret < 0){ iEnd = iIndex - 1; }else{ iStart = iIndex + 1; } if (iStart > iEnd){ break; } } return null; } /** * 查找最接近对象的对象实例 * @param data 对象 * @return 对象实例 */ synchronized public Iterator<object> lowerBound(object data){ if (!isSync){ sync(); } int iIndex = 0; int iStart = 0; int iEnd = currentCount - 1; SuperSetIterator<object> iterator = new SuperSetIterator<object>(null); while (true){ iIndex = (iStart + iEnd)/2; int ret = compare(data,array[iIndex].content); if (ret == 0){ iterator.item = array[iIndex]; return iterator; } if (ret < 0){ iEnd = iIndex; }else{ iStart = iIndex + 1; } if (iStart >= iEnd){ break; } } iterator.item = array[iEnd]; return iterator; } /** * Set的Item * @author duanyy * * @param <object> 对象的类名 */ static class SuperSetItem <object>{ public object content = null; public SuperSetItem<object> next = null; } /** * Set的迭代器 * @author duanyy * * @param <object> 对象的类名 */ static class SuperSetIterator<object> implements Iterator<object>{ /** * 迭代器对应的Item */ protected SuperSetItem<object> item = null; /** * 构造函数 * @param _item 迭代器对应的Item */ protected SuperSetIterator(SuperSetItem<object> _item){ item = _item; } /** * 下一个对象是否存在 */ public boolean hasNext() { return item != null; } /** * 取下一个对象 */ public object next() { if (item == null) return null; object content = item.content; item = item.next; return content; } /** * 不支持迭代器的remove */ public void remove() { throw new UnsupportedOperationException(); } } }
anylogic/alogic
alogic-common/src/main/java/com/anysoft/util/SuperSet.java
2,110
/** * 对象的比较器 */
block_comment
zh-cn
package com.anysoft.util; import java.util.Comparator; import java.util.Iterator; /** * 超级Set * <p>Java中的{@link java.util.Set}不支持模糊的查找(颇为想念C++STL中的Set)。超级Set则支持模糊查找,见{@link #lowerBound(Object)}.<p> * <p>超级Set通过链表实现插入,通过数组实现检索,力图达到插入效率和查找效率的平衡。</p> * @author duanyy * * @param <object> 对象的类名 */ public class SuperSet<object> { /** * 链表结构的列表 */ private SuperSetItem<object> root = new SuperSetItem<object>(); /** * 当前的对象个数 */ private int currentCount = 0; /** * 数据结构的列表 */ private SuperSetItem<object> [] array = null; /** * 数组结构和链表结构之间是否进行了同步 */ private boolean isSync = false; /** * 对象的 <SUF>*/ private Comparator<object> comparator = null; /** * 构造函数,指定对象的比较器 * <p>如果不指定对象的比较器,则要求对象实现了{@link Comparable}接口。</p> * @param _comparator */ public SuperSet(Comparator<object> _comparator){ comparator = _comparator; } /** * 构造函数 */ public SuperSet(){ this(null); } /** * 比较两个对象的大小 * @param obj1 对象1 * @param obj2 对象2 * @return 如果相等,返回为0;如果obj1大于obj2,则返回为1;如果obj1小于obj2,则返回为-1 */ @SuppressWarnings("unchecked") private int compare(object obj1,object obj2){ if (comparator != null){ return comparator.compare(obj1, obj2); } Comparable<object> c = (Comparable<object>)obj1; return c.compareTo(obj2); } /** * 从链表结构同步到数组结构 */ @SuppressWarnings("unchecked") private void sync(){ if (currentCount <= 0) return ; if (array == null){ array = new SuperSetItem[currentCount * 2]; }else{ if (array.length < currentCount){ for (int i = 0 ; i < array.length ; i ++){ array[i] = null; } array = new SuperSetItem[currentCount * 2]; } } int index = 0; SuperSetItem<object> current = root; while (current.next != null){ array[index ++] = current.next; current = current.next; } for (;index < array.length; index++){ array[index] = null; } isSync = true; } /** * 回到第一个对象位置 * @return 迭代器 */ public Iterator<object> begin(){ return new SuperSetIterator<object>(root.next); } /** * 当前Set中对象个数 * @return 对象个数 */ public int size(){ return currentCount; } /** * 向Set中增加对象 * @param data 对象实例 */ synchronized public void add(object data){ if (data == null) return; //先找到位置 SuperSetItem<object> current = root; while (current.next != null){ int ret = compare(data,current.next.content); if (ret == 0){ //如果相等,替代他 current.next.content = data; return ; } if (ret < 0){ //找到了插入位置 break; } current = current.next; } SuperSetItem<object> newItem = new SuperSetItem<object>(); newItem.content = data; newItem.next = current.next; current.next = newItem; currentCount ++; isSync = false; } /** * 从Set中删除对象 * <p>删除的不是data对象实例本身,而是Set中"等于"该对象的对象实例。</p> * @param data 对象实例 */ synchronized public void remove(object data){ if (data == null) return ; //先找到位置 SuperSetItem<object> current = root; while (current.next != null){ int ret = compare(data,current.next.content); if (ret == 0){ current.next.content = null; current.next = current.next.next; currentCount --; isSync = false; return ; } current = current.next; } } /** * 清空Set */ synchronized public void clear(){ isSync = false; SuperSetItem<object> current = root; while (current.next != null){ current.next.content = null; current = current.next; } root.next = null; currentCount = 0; } /** * 按索引查找对象 * @param index 对象位置 * @return 对象实例 */ synchronized public object get(int index){ if (!isSync){ sync(); } if (index < 0 || index >= currentCount) return null; return array[index].content; } /** * 查找对象 * @param data 对象实例 * @return "等于"data的对象实例 */ synchronized public object get(object data){ if (!isSync){ sync(); } int iIndex = 0; int iStart = 0; int iEnd = array.length - 1; while (true){ iIndex = (iStart + iEnd) / 2; int ret = compare(data,array[iIndex].content); if (ret == 0){ return array[iIndex].content; } if (ret < 0){ iEnd = iIndex - 1; }else{ iStart = iIndex + 1; } if (iStart > iEnd){ break; } } return null; } /** * 查找最接近对象的对象实例 * @param data 对象 * @return 对象实例 */ synchronized public Iterator<object> lowerBound(object data){ if (!isSync){ sync(); } int iIndex = 0; int iStart = 0; int iEnd = currentCount - 1; SuperSetIterator<object> iterator = new SuperSetIterator<object>(null); while (true){ iIndex = (iStart + iEnd)/2; int ret = compare(data,array[iIndex].content); if (ret == 0){ iterator.item = array[iIndex]; return iterator; } if (ret < 0){ iEnd = iIndex; }else{ iStart = iIndex + 1; } if (iStart >= iEnd){ break; } } iterator.item = array[iEnd]; return iterator; } /** * Set的Item * @author duanyy * * @param <object> 对象的类名 */ static class SuperSetItem <object>{ public object content = null; public SuperSetItem<object> next = null; } /** * Set的迭代器 * @author duanyy * * @param <object> 对象的类名 */ static class SuperSetIterator<object> implements Iterator<object>{ /** * 迭代器对应的Item */ protected SuperSetItem<object> item = null; /** * 构造函数 * @param _item 迭代器对应的Item */ protected SuperSetIterator(SuperSetItem<object> _item){ item = _item; } /** * 下一个对象是否存在 */ public boolean hasNext() { return item != null; } /** * 取下一个对象 */ public object next() { if (item == null) return null; object content = item.content; item = item.next; return content; } /** * 不支持迭代器的remove */ public void remove() { throw new UnsupportedOperationException(); } } }
false
1,911
11
2,110
9
2,162
11
2,110
9
2,786
16
false
false
false
false
false
true
47946_1
package com.javaCase; /** * N至少多大时,不等式成立:1/1+1/2+1/3+···+1/n > 6 */ public class GetN { public static void main(String[] args) { getN(); } static void getN() { double sum = 1.0; // sum是小数,默认赋值(1.0/1)的值 for (int n = 2;; n++) { // 从(1.0/2)开始 sum += 1.0 / n; // 1/1+1/2+1/3+···+1/n if (sum > 6) { // 如果总数大于6 System.out.println(n); break; // 确保"至少多大"这个条件 } } } }
anyshift/javaCase
src/com/javaCase/GetN.java
203
// sum是小数,默认赋值(1.0/1)的值
line_comment
zh-cn
package com.javaCase; /** * N至少多大时,不等式成立:1/1+1/2+1/3+···+1/n > 6 */ public class GetN { public static void main(String[] args) { getN(); } static void getN() { double sum = 1.0; // su <SUF> for (int n = 2;; n++) { // 从(1.0/2)开始 sum += 1.0 / n; // 1/1+1/2+1/3+···+1/n if (sum > 6) { // 如果总数大于6 System.out.println(n); break; // 确保"至少多大"这个条件 } } } }
false
193
17
203
16
202
15
203
16
236
21
false
false
false
false
false
true
36382_2
package shellService; /** * 通过电脑shell启动一个shell的Java程序,就可以长驻手机了,可以做远程录屏、远程控制等特殊功能。 * 使用 app_process 来调用高权限 API:https://haruue.moe/blog/2017/08/30/call-privileged-api-with-app-process/ * * 1、将整个项目编译后得到APK。 * 2、将XXX.APK 更名为 xxx.RAR; 再解压缩,得到 classes.dex 文件. * 3、手机 和 电脑 通过 USB 或 WIFI 连接成功。 ADB: https://github.com/anysou/awesome-adb * 4、adb devices * adb push classes.dex /data/local/tmp 将文件推送到 /data/local/tmp * adb shell * 前台运行:(测试用。退出,ctrl+c; usb线拔出就退出了) * cd /data/local/tmp & app_process -Djava.class.path=/data/local/tmp/classes.dex /system/bin shellService.Main * 后台运行:(usb线拔出也不会退出,退出,进入shell: ps -le | grep anysou ;找到对应PID ; 执行 kill -9 PID) * cd /data/local/tmp & nohup app_process -Djava.class.path=/data/local/tmp/classes.dex /system/bin --nice-name=shellServer shellService.Main > /dev/null 2>&1 & 前台运行:(测试用。退出,ctrl+c; usb线拔出就退出了) 将下面代码编辑成bat批出处理文件 adb push classes.dex /data/local/tmp (注意一定要先执行这句) @echo off del "temp.txt" echo export CLASSPATH=/data/local/tmp/classes.dex >> temp.txt echo exec app_process /system/bin --nice-name=shellServer shellService.Main >> temp.txt adb shell < temp.txt del "temp.txt" pause 后台运行:(usb线拔出也不会退出,退出,进入shell: ps -le | grep shellServer ;找到对应PID ; 执行 kill -9 PID)将下面代码编辑成bat批出处理文件 adb push classes.dex /data/local/tmp @echo off del "temp.txt" echo export CLASSPATH=/data/local/tmp/classes.dex >> temp.txt echo nohup app_process /system/bin --nice-name=shellServer shellService.Main ^> /dev/null 2^>^&1 ^& >> temp.txt adb shell < temp.txt del "temp.txt" pause 注意:先退出DOS,再测试有效,在断USB线。 问题:做成一个开机系统服务。 * */ public class Main { // 定义要开启的 ServerSocket 端口号 public static int PORT = 8888; public static void main(String[] args){ //==== 获取 手机的局域网ip地址 try{ // 下面三个Shell 命令都可以获得本IP String comd = "ifconfig |grep Bcast |awk -F'[ :]+' '{print $4}'"; //String comd = "ifconfig |grep \"inet addr:\" |grep -v \"127.0.0.1\" |cut -d: -f2 |awk '{print $1}'"; //String comd = "ifconfig -a |grep inet |grep -v 127.0.0.1 |grep -v inet6|awk '{print $2}' |tr -d \"addr:\""; ServiceShellUtils.ServiceShellCommandResult sr = ServiceShellUtils.execCommand(comd, false); if (sr.result == 0){ System.out.println("ServerSocket IP at : " + sr.successMsg); } else { System.out.println("Get ServerSocket IP error: " + sr.errorMsg); } }catch (Exception e){ System.out.println("###CodeError#: " + e.toString()); } System.out.println("\nI am run in shell; 我是在电脑端通过shell运行的!!!\n"); new ServiceThread(PORT).start(); while (true); } }
anysou/APP_process
app/src/main/java/shellService/Main.java
1,040
//==== 获取 手机的局域网ip地址
line_comment
zh-cn
package shellService; /** * 通过电脑shell启动一个shell的Java程序,就可以长驻手机了,可以做远程录屏、远程控制等特殊功能。 * 使用 app_process 来调用高权限 API:https://haruue.moe/blog/2017/08/30/call-privileged-api-with-app-process/ * * 1、将整个项目编译后得到APK。 * 2、将XXX.APK 更名为 xxx.RAR; 再解压缩,得到 classes.dex 文件. * 3、手机 和 电脑 通过 USB 或 WIFI 连接成功。 ADB: https://github.com/anysou/awesome-adb * 4、adb devices * adb push classes.dex /data/local/tmp 将文件推送到 /data/local/tmp * adb shell * 前台运行:(测试用。退出,ctrl+c; usb线拔出就退出了) * cd /data/local/tmp & app_process -Djava.class.path=/data/local/tmp/classes.dex /system/bin shellService.Main * 后台运行:(usb线拔出也不会退出,退出,进入shell: ps -le | grep anysou ;找到对应PID ; 执行 kill -9 PID) * cd /data/local/tmp & nohup app_process -Djava.class.path=/data/local/tmp/classes.dex /system/bin --nice-name=shellServer shellService.Main > /dev/null 2>&1 & 前台运行:(测试用。退出,ctrl+c; usb线拔出就退出了) 将下面代码编辑成bat批出处理文件 adb push classes.dex /data/local/tmp (注意一定要先执行这句) @echo off del "temp.txt" echo export CLASSPATH=/data/local/tmp/classes.dex >> temp.txt echo exec app_process /system/bin --nice-name=shellServer shellService.Main >> temp.txt adb shell < temp.txt del "temp.txt" pause 后台运行:(usb线拔出也不会退出,退出,进入shell: ps -le | grep shellServer ;找到对应PID ; 执行 kill -9 PID)将下面代码编辑成bat批出处理文件 adb push classes.dex /data/local/tmp @echo off del "temp.txt" echo export CLASSPATH=/data/local/tmp/classes.dex >> temp.txt echo nohup app_process /system/bin --nice-name=shellServer shellService.Main ^> /dev/null 2^>^&1 ^& >> temp.txt adb shell < temp.txt del "temp.txt" pause 注意:先退出DOS,再测试有效,在断USB线。 问题:做成一个开机系统服务。 * */ public class Main { // 定义要开启的 ServerSocket 端口号 public static int PORT = 8888; public static void main(String[] args){ //== <SUF> try{ // 下面三个Shell 命令都可以获得本IP String comd = "ifconfig |grep Bcast |awk -F'[ :]+' '{print $4}'"; //String comd = "ifconfig |grep \"inet addr:\" |grep -v \"127.0.0.1\" |cut -d: -f2 |awk '{print $1}'"; //String comd = "ifconfig -a |grep inet |grep -v 127.0.0.1 |grep -v inet6|awk '{print $2}' |tr -d \"addr:\""; ServiceShellUtils.ServiceShellCommandResult sr = ServiceShellUtils.execCommand(comd, false); if (sr.result == 0){ System.out.println("ServerSocket IP at : " + sr.successMsg); } else { System.out.println("Get ServerSocket IP error: " + sr.errorMsg); } }catch (Exception e){ System.out.println("###CodeError#: " + e.toString()); } System.out.println("\nI am run in shell; 我是在电脑端通过shell运行的!!!\n"); new ServiceThread(PORT).start(); while (true); } }
false
922
12
1,040
11
1,014
10
1,040
11
1,278
17
false
false
false
false
false
true
32368_22
package net.datafans.androidtimelineview; import android.content.Intent; import android.os.Bundle; import net.datafans.android.common.helper.LogHelper; import net.datafans.android.timeline.controller.TimelineViewController; import net.datafans.android.timeline.item.LineCommentItem; import net.datafans.android.timeline.item.LineItemType; import net.datafans.android.timeline.item.LineLikeItem; import net.datafans.android.timeline.item.TextImageLineItem; public class MainActivity extends TimelineViewController { @Override protected void onCreate(Bundle savedInstanceState) { addItems(); super.onCreate(savedInstanceState); LogHelper.init("## timeline ##", true); setHeader(); } @Override protected String getNavTitle() { return "朋友圈"; } private void setHeader() { String coverUrl = String.format("http://file-cdn.datafans.net/temp/12.jpg_%dx%d.jpeg", coverWidth, coverHeight); setCover(coverUrl); String userAvatarUrl = String.format("http://file-cdn.datafans.net/avatar/1.jpeg_%dx%d.jpeg", userAvatarSize, userAvatarSize); setUserAvatar(userAvatarUrl); setUserNick("Allen"); setUserSign("梦想还是要有的 万一实现了呢"); setUserId(123456); } private TextImageLineItem textImageItem3; private void addItems() { TextImageLineItem textImageItem = new TextImageLineItem(); textImageItem.itemId = 1; textImageItem.itemType = LineItemType.TextImage; textImageItem.userId = 10086; textImageItem.userAvatar = "http://file-cdn.datafans.net/avatar/1.jpeg"; textImageItem.userNick = "Allen"; textImageItem.title = ""; textImageItem.text = "你是我的小苹果 小苹果 我爱你 就像老鼠爱大米 18680551720 [亲亲]"; textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/11.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/12.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/13.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/14.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/15.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/16.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/17.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/18.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/19.jpg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/11.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/12.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/13.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/14.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/15.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/16.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/17.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/18.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/19.jpg_160x160.jpeg"); textImageItem.location = "中国 • 广州"; textImageItem.ts = System.currentTimeMillis() - 10 * 60 * 1000; LineLikeItem likeItem1_1 = new LineLikeItem(); likeItem1_1.userId = 10086; likeItem1_1.userNick = "Allen"; textImageItem.likes.add(likeItem1_1); LineLikeItem likeItem1_2 = new LineLikeItem(); likeItem1_2.userId = 10088; likeItem1_2.userNick = "奥巴马"; textImageItem.likes.add(likeItem1_2); LineCommentItem commentItem1_1 = new LineCommentItem(); commentItem1_1.commentId = 1000; commentItem1_1.userId = 10086; commentItem1_1.userNick = "习大大"; commentItem1_1.text = "精彩 大家鼓掌"; textImageItem.comments.add(commentItem1_1); LineCommentItem commentItem1_2 = new LineCommentItem(); commentItem1_2.commentId = 100980; commentItem1_2.userId = 10088; commentItem1_2.userNick = "奥巴马"; commentItem1_2.text = "欢迎来到美利坚"; commentItem1_2.replyUserId = 10086; commentItem1_2.replyUserNick = "习大大"; textImageItem.comments.add(commentItem1_2); LineCommentItem commentItem1_3 = new LineCommentItem(); commentItem1_3.commentId = 456567; commentItem1_3.userId = 10010; commentItem1_3.userNick = "神雕侠侣"; commentItem1_3.text = "呵呵"; textImageItem.comments.add(commentItem1_3); addItem(textImageItem); TextImageLineItem textImageItem2 = new TextImageLineItem(); textImageItem2.itemId = 2; textImageItem2.itemType = LineItemType.TextImage; textImageItem2.userId = 10088; textImageItem2.userAvatar = "http://file-cdn.datafans.net/avatar/2.jpg"; textImageItem2.userNick = "奥巴马"; textImageItem2.title = "发表了"; textImageItem2.text = "京东JD.COM-专业的综合网上购物商城,销售超数万品牌、4020万种商品,http://jd.com 囊括家电、手机、电脑、服装、图书、母婴、个护、食品、旅游等13大品类。秉承客户为先的理念,京东所售商品为正品行货、全国联保、机打发票。@刘强东"; textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/20.jpg"); textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/21.jpg"); textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/22.jpg"); textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/23.jpg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/20.jpg_160x160.jpeg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/21.jpg_160x160.jpeg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/22.jpg_160x160.jpeg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/23.jpg_160x160.jpeg"); LineLikeItem likeItem2_1 = new LineLikeItem(); likeItem2_1.userId = 10086; likeItem2_1.userNick = "Allen"; textImageItem2.likes.add(likeItem2_1); LineCommentItem commentItem2_1 = new LineCommentItem(); commentItem2_1.commentId = 31000; commentItem2_1.userId = 10088; commentItem2_1.userNick = "奥巴马"; commentItem2_1.text = "欢迎来到美利坚"; commentItem2_1.replyUserId = 10086; commentItem2_1.replyUserNick = "习大大"; textImageItem2.comments.add(commentItem2_1); LineCommentItem commentItem2_2 = new LineCommentItem(); commentItem2_2.commentId = 166000; commentItem2_2.userId = 10010; commentItem2_2.userNick = "神雕侠侣"; commentItem2_2.text = "大家好"; textImageItem2.comments.add(commentItem2_2); addItem(textImageItem2); textImageItem3 = new TextImageLineItem(); textImageItem3.itemId = 3; textImageItem3.itemType = LineItemType.TextImage; textImageItem3.userId = 10088; textImageItem3.userAvatar = "http://file-cdn.datafans.net/avatar/2.jpg"; textImageItem3.userNick = "奥巴马"; textImageItem3.title = "发表了"; textImageItem3.text = "京东JD.COM-专业的综合网上购物商城"; textImageItem3.srcImages.add("http://file-cdn.datafans.net/temp/21.jpg"); textImageItem3.thumbImages.add("http://file-cdn.datafans.net/temp/21.jpg_480x270.jpeg"); textImageItem3.width = 640; textImageItem3.height = 360; textImageItem3.location = "广州信息港"; addItem(textImageItem3); } @Override public void onRefresh() { super.onRefresh(); onEnd(); } @Override public void onLoadMore() { super.onLoadMore(); addItem(textImageItem3); onEnd(); } @Override protected void onCommentCreate(long itemId, long commentId, String text) { LineCommentItem commentItem = new LineCommentItem(); commentItem.commentId = System.currentTimeMillis(); commentItem.userId = 10014; commentItem.userNick = "金三胖"; commentItem.text = text; addCommentItem(commentItem, itemId, commentId); } @Override protected void onLikeCreate(long itemId) { LineLikeItem likeItem = new LineLikeItem(); likeItem.userId = 1001188; likeItem.userNick = "酸菜鱼"; addLikeItem(likeItem, itemId); } @Override protected void onUserClick(int userId) { LogHelper.debug("user-click: " + userId); Intent intent = new Intent(this, UserFeedActivity.class); startActivity(intent); } }
anyunzhong/AndroidTimelineView
app/src/main/java/net/datafans/androidtimelineview/MainActivity.java
2,963
//jd.com 囊括家电、手机、电脑、服装、图书、母婴、个护、食品、旅游等13大品类。秉承客户为先的理念,京东所售商品为正品行货、全国联保、机打发票。@刘强东";
line_comment
zh-cn
package net.datafans.androidtimelineview; import android.content.Intent; import android.os.Bundle; import net.datafans.android.common.helper.LogHelper; import net.datafans.android.timeline.controller.TimelineViewController; import net.datafans.android.timeline.item.LineCommentItem; import net.datafans.android.timeline.item.LineItemType; import net.datafans.android.timeline.item.LineLikeItem; import net.datafans.android.timeline.item.TextImageLineItem; public class MainActivity extends TimelineViewController { @Override protected void onCreate(Bundle savedInstanceState) { addItems(); super.onCreate(savedInstanceState); LogHelper.init("## timeline ##", true); setHeader(); } @Override protected String getNavTitle() { return "朋友圈"; } private void setHeader() { String coverUrl = String.format("http://file-cdn.datafans.net/temp/12.jpg_%dx%d.jpeg", coverWidth, coverHeight); setCover(coverUrl); String userAvatarUrl = String.format("http://file-cdn.datafans.net/avatar/1.jpeg_%dx%d.jpeg", userAvatarSize, userAvatarSize); setUserAvatar(userAvatarUrl); setUserNick("Allen"); setUserSign("梦想还是要有的 万一实现了呢"); setUserId(123456); } private TextImageLineItem textImageItem3; private void addItems() { TextImageLineItem textImageItem = new TextImageLineItem(); textImageItem.itemId = 1; textImageItem.itemType = LineItemType.TextImage; textImageItem.userId = 10086; textImageItem.userAvatar = "http://file-cdn.datafans.net/avatar/1.jpeg"; textImageItem.userNick = "Allen"; textImageItem.title = ""; textImageItem.text = "你是我的小苹果 小苹果 我爱你 就像老鼠爱大米 18680551720 [亲亲]"; textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/11.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/12.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/13.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/14.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/15.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/16.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/17.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/18.jpg"); textImageItem.srcImages.add("http://file-cdn.datafans.net/temp/19.jpg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/11.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/12.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/13.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/14.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/15.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/16.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/17.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/18.jpg_160x160.jpeg"); textImageItem.thumbImages.add("http://file-cdn.datafans.net/temp/19.jpg_160x160.jpeg"); textImageItem.location = "中国 • 广州"; textImageItem.ts = System.currentTimeMillis() - 10 * 60 * 1000; LineLikeItem likeItem1_1 = new LineLikeItem(); likeItem1_1.userId = 10086; likeItem1_1.userNick = "Allen"; textImageItem.likes.add(likeItem1_1); LineLikeItem likeItem1_2 = new LineLikeItem(); likeItem1_2.userId = 10088; likeItem1_2.userNick = "奥巴马"; textImageItem.likes.add(likeItem1_2); LineCommentItem commentItem1_1 = new LineCommentItem(); commentItem1_1.commentId = 1000; commentItem1_1.userId = 10086; commentItem1_1.userNick = "习大大"; commentItem1_1.text = "精彩 大家鼓掌"; textImageItem.comments.add(commentItem1_1); LineCommentItem commentItem1_2 = new LineCommentItem(); commentItem1_2.commentId = 100980; commentItem1_2.userId = 10088; commentItem1_2.userNick = "奥巴马"; commentItem1_2.text = "欢迎来到美利坚"; commentItem1_2.replyUserId = 10086; commentItem1_2.replyUserNick = "习大大"; textImageItem.comments.add(commentItem1_2); LineCommentItem commentItem1_3 = new LineCommentItem(); commentItem1_3.commentId = 456567; commentItem1_3.userId = 10010; commentItem1_3.userNick = "神雕侠侣"; commentItem1_3.text = "呵呵"; textImageItem.comments.add(commentItem1_3); addItem(textImageItem); TextImageLineItem textImageItem2 = new TextImageLineItem(); textImageItem2.itemId = 2; textImageItem2.itemType = LineItemType.TextImage; textImageItem2.userId = 10088; textImageItem2.userAvatar = "http://file-cdn.datafans.net/avatar/2.jpg"; textImageItem2.userNick = "奥巴马"; textImageItem2.title = "发表了"; textImageItem2.text = "京东JD.COM-专业的综合网上购物商城,销售超数万品牌、4020万种商品,http://jd <SUF> textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/20.jpg"); textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/21.jpg"); textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/22.jpg"); textImageItem2.srcImages.add("http://file-cdn.datafans.net/temp/23.jpg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/20.jpg_160x160.jpeg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/21.jpg_160x160.jpeg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/22.jpg_160x160.jpeg"); textImageItem2.thumbImages.add("http://file-cdn.datafans.net/temp/23.jpg_160x160.jpeg"); LineLikeItem likeItem2_1 = new LineLikeItem(); likeItem2_1.userId = 10086; likeItem2_1.userNick = "Allen"; textImageItem2.likes.add(likeItem2_1); LineCommentItem commentItem2_1 = new LineCommentItem(); commentItem2_1.commentId = 31000; commentItem2_1.userId = 10088; commentItem2_1.userNick = "奥巴马"; commentItem2_1.text = "欢迎来到美利坚"; commentItem2_1.replyUserId = 10086; commentItem2_1.replyUserNick = "习大大"; textImageItem2.comments.add(commentItem2_1); LineCommentItem commentItem2_2 = new LineCommentItem(); commentItem2_2.commentId = 166000; commentItem2_2.userId = 10010; commentItem2_2.userNick = "神雕侠侣"; commentItem2_2.text = "大家好"; textImageItem2.comments.add(commentItem2_2); addItem(textImageItem2); textImageItem3 = new TextImageLineItem(); textImageItem3.itemId = 3; textImageItem3.itemType = LineItemType.TextImage; textImageItem3.userId = 10088; textImageItem3.userAvatar = "http://file-cdn.datafans.net/avatar/2.jpg"; textImageItem3.userNick = "奥巴马"; textImageItem3.title = "发表了"; textImageItem3.text = "京东JD.COM-专业的综合网上购物商城"; textImageItem3.srcImages.add("http://file-cdn.datafans.net/temp/21.jpg"); textImageItem3.thumbImages.add("http://file-cdn.datafans.net/temp/21.jpg_480x270.jpeg"); textImageItem3.width = 640; textImageItem3.height = 360; textImageItem3.location = "广州信息港"; addItem(textImageItem3); } @Override public void onRefresh() { super.onRefresh(); onEnd(); } @Override public void onLoadMore() { super.onLoadMore(); addItem(textImageItem3); onEnd(); } @Override protected void onCommentCreate(long itemId, long commentId, String text) { LineCommentItem commentItem = new LineCommentItem(); commentItem.commentId = System.currentTimeMillis(); commentItem.userId = 10014; commentItem.userNick = "金三胖"; commentItem.text = text; addCommentItem(commentItem, itemId, commentId); } @Override protected void onLikeCreate(long itemId) { LineLikeItem likeItem = new LineLikeItem(); likeItem.userId = 1001188; likeItem.userNick = "酸菜鱼"; addLikeItem(likeItem, itemId); } @Override protected void onUserClick(int userId) { LogHelper.debug("user-click: " + userId); Intent intent = new Intent(this, UserFeedActivity.class); startActivity(intent); } }
false
2,457
58
2,963
79
2,975
66
2,963
79
3,401
107
false
false
false
false
false
true
65725_5
/* * Copyright (c) 2022 Institute of Software Chinese Academy of Sciences (ISCAS) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package space.ao.services.push.dto; import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.ArrayList; import java.util.List; import lombok.Getter; @RegisterForReflection public enum NotificationEnum { LOGOUT("下线提醒", "您的登录已失效。请重新进行扫码授权 >>","logout", AfterOpenAction.GO_ACTIVITY), MEMBER_DEL("空间注销提醒", "您的空间已被注销,将无法继续使用,请联系管理员。","member_delete", AfterOpenAction.GO_ACTIVITY), MEMBER_SELF_DEL("空间注销提醒", "您的空间已注销,将无法继续使用。","member_self_delete", AfterOpenAction.GO_ACTIVITY), REVOKE("下线提醒", "您的登录已失效。请重新进行扫码授权 >>","revoke", AfterOpenAction.GO_ACTIVITY), MEMBER_JOIN("成员加入提醒", "","member_join", AfterOpenAction.GO_ACTIVITY), LOGIN("登录提醒", "", "login", AfterOpenAction.GO_ACTIVITY), LOGIN_CONFIRM("免扫码登录", "", "login_confirm", AfterOpenAction.GO_ACTIVITY), START("盒子启动", "你的盒子已成功启动", "start", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_MOD_APPLY("账户安全提醒:", "您正在终端 %s 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全", "security_passwd_mod_apply", AfterOpenAction.GO_ACTIVITY), // 下面这条是安保专用的,非传统推送!!! SECURITY_PASSWD_PARTICULAR_MOD_ACCEPT("账户安全提醒:", "安保专用的poll推送允许结果", "security_passwd_mod_accept", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_MOD_SUCC("账户安全提醒:", "安全密码修改成功,请知晓! \n" + "若非本人操作,请在【我的-设置-安全设置】里重置安全密码", "security_passwd_mod_succ", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_RESET_APPLY("账户安全提醒:", "您正在终端 %s 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全", "security_passwd_reset_apply", AfterOpenAction.GO_ACTIVITY), // 下面这条是安保专用的,非传统推送!!! SECURITY_PASSWD_PARTICULAR_RESET_ACCEPT("账户安全提醒:", "安保专用的poll推送允许结果", "security_passwd_reset_accept", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_RESET_SUCC("账户安全提醒:", "安全密码重置成功,请知晓! \n" + "若非本人操作,请在【我的-设置-安全设置】里重置安全密码", "security_passwd_reset_succ", AfterOpenAction.GO_ACTIVITY), SECURITY_EMAIL_SET_SUCC("账户安全提醒:", """ 您已成功绑定密保邮箱 %s!\s 点击“查看详情”,查看更多信息 查看详情;""", "security_email_set_succ", AfterOpenAction.GO_ACTIVITY), SECURITY_EMAIL_MOD_SUCC("账户安全提醒:", """ 您已绑定新的密保邮箱 %s!\s 点击“查看详情”,查看更多信息 查看详情;""", "security_email_mod_succ", AfterOpenAction.GO_ACTIVITY), // 升级成功 UPGRADE_SUCCESS("系统升级提醒", "傲空间系统已经升级到最新版本啦,点击查看 >>","upgrade_success", AfterOpenAction.GO_ACTIVITY), // 下载成功 UPGRADE_DOWNLOAD_SUCCESS("已下载未安装提醒", "傲空间 %s可用于您的设备,且已经可以安装,点击去安装>>","upgrade_download_success", AfterOpenAction.GO_ACTIVITY), // 安装中 UPGRADE_INSTALLING("正在安装系统", "正在安装系统更新,傲空间设备可能无法正常访问,升级完成后将自动恢复使用 >>","upgrade_installing", AfterOpenAction.GO_ACTIVITY), // 盒子重启推送 UPGRADE_RESTART("系统升级提醒","正在重启设备,请在重启完成后使用","upgrade_restart", AfterOpenAction.GO_ACTIVITY), //备份进度和恢复进度 BACKUP_PROGRESS("","", "backup_progress", AfterOpenAction.GO_ACTIVITY), //恢复成功 RESTORE_SUCCESS("数据恢复完成","您的空间数据已完成恢复操作,如有疑问,请联系管理员。", "restore_success", AfterOpenAction.GO_ACTIVITY), TODAY_IN_HIS("历史上的今天", "小傲帮您整理了今天的一些记忆,去重温下吧~","today_in_his", AfterOpenAction.GO_ACTIVITY), MEMORIES("回忆", "小傲帮您整理了一些过往回忆,去重温下吧~","memories", AfterOpenAction.GO_ACTIVITY), ABILITY_CHANGE("平台API发生变化", "平台API发生变化","ability_change", AfterOpenAction.GO_ACTIVITY), HISTORY_RECORD("文件状态发生变化", "文件状态发生变化","HISTORY_RECORD", AfterOpenAction.GO_CUSTOM), ; private String title; private String text; private final String type; @Getter private final AfterOpenAction afterOpenAction; NotificationEnum(String title, String text, String type, AfterOpenAction afterOpenAction) { this.title = title; this.text = text; this.type = type; this.afterOpenAction = afterOpenAction; } public String getTitle() { return title; } public NotificationEnum setTitle(String title) { this.title = title; return this; } public String getText() { return text; } public NotificationEnum setText(String text) { this.text = text; return this; } public String getType() { return type; } public NotificationEnum setMemberJoin(String name){ MEMBER_JOIN.text = name + " 接受了您的邀请并创建了傲空间。点击查看 >>"; return MEMBER_JOIN; } public NotificationEnum setLogin(String name){ LOGIN.text = "您的空间已在设备:" + name +"登录,点击查看 >>"; return LOGIN; } public NotificationEnum setInnerLogin(String name){ LOGIN.text = "您的空间已在 " + name +" 登陆"; return LOGIN; } public NotificationEnum setLoginConfirm(String name, String userdomain){ LOGIN.text = name + " 申请登录您的傲空间(https://" + userdomain + "), 点击确认是否允许>>"; return LOGIN; } public NotificationEnum getSecurityPasswdModApply(String email){ SECURITY_PASSWD_MOD_APPLY.text = "您正在终端 " + email + " 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全"; return SECURITY_PASSWD_MOD_APPLY; } public NotificationEnum getSecurityPasswdResetApply(String email){ SECURITY_PASSWD_RESET_APPLY.text = "您正在终端 " + email + " 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全"; return SECURITY_PASSWD_RESET_APPLY; } public NotificationEnum getSecurityEmailSetSucc(String email){ SECURITY_EMAIL_SET_SUCC.text = "您已成功绑定密保邮箱 " + email+ "! \n" + "点击“查看详情”,查看更多信息\n"; return SECURITY_EMAIL_SET_SUCC; } public NotificationEnum getSecurityEmailModSucc(String email){ SECURITY_EMAIL_MOD_SUCC.text = "您已绑定新的密保邮箱 " + email + "! \n" + "点击“查看详情”,查看更多信息\n" + "查看详情;"; return SECURITY_EMAIL_MOD_SUCC; } public NotificationEnum getUpgradeDownloadSuccess(String version){ UPGRADE_DOWNLOAD_SUCCESS.text = "傲空间 " + version + "可用于您的设备,且已经可以安装,点击去安装>>"; return UPGRADE_DOWNLOAD_SUCCESS; } public static NotificationEnum of(String type){ for (var notification: NotificationEnum.values()){ if(notification.getType().equals(type)){ return notification; } } return null; } public static List<String> sendOnlyOnline(){ var sendOnlyOnline = new ArrayList<String>(); sendOnlyOnline.add(NotificationEnum.ABILITY_CHANGE.type); sendOnlyOnline.add(NotificationEnum.UPGRADE_RESTART.type); return sendOnlyOnline; } public static List<String> noNeedToSave(){ var noNeedToSave = new ArrayList<String>(); noNeedToSave.add(NotificationEnum.ABILITY_CHANGE.type); return noNeedToSave; } }
ao-space/space-gateway
src/main/java/space/ao/services/push/dto/NotificationEnum.java
2,326
// 安装中
line_comment
zh-cn
/* * Copyright (c) 2022 Institute of Software Chinese Academy of Sciences (ISCAS) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package space.ao.services.push.dto; import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.ArrayList; import java.util.List; import lombok.Getter; @RegisterForReflection public enum NotificationEnum { LOGOUT("下线提醒", "您的登录已失效。请重新进行扫码授权 >>","logout", AfterOpenAction.GO_ACTIVITY), MEMBER_DEL("空间注销提醒", "您的空间已被注销,将无法继续使用,请联系管理员。","member_delete", AfterOpenAction.GO_ACTIVITY), MEMBER_SELF_DEL("空间注销提醒", "您的空间已注销,将无法继续使用。","member_self_delete", AfterOpenAction.GO_ACTIVITY), REVOKE("下线提醒", "您的登录已失效。请重新进行扫码授权 >>","revoke", AfterOpenAction.GO_ACTIVITY), MEMBER_JOIN("成员加入提醒", "","member_join", AfterOpenAction.GO_ACTIVITY), LOGIN("登录提醒", "", "login", AfterOpenAction.GO_ACTIVITY), LOGIN_CONFIRM("免扫码登录", "", "login_confirm", AfterOpenAction.GO_ACTIVITY), START("盒子启动", "你的盒子已成功启动", "start", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_MOD_APPLY("账户安全提醒:", "您正在终端 %s 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全", "security_passwd_mod_apply", AfterOpenAction.GO_ACTIVITY), // 下面这条是安保专用的,非传统推送!!! SECURITY_PASSWD_PARTICULAR_MOD_ACCEPT("账户安全提醒:", "安保专用的poll推送允许结果", "security_passwd_mod_accept", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_MOD_SUCC("账户安全提醒:", "安全密码修改成功,请知晓! \n" + "若非本人操作,请在【我的-设置-安全设置】里重置安全密码", "security_passwd_mod_succ", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_RESET_APPLY("账户安全提醒:", "您正在终端 %s 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全", "security_passwd_reset_apply", AfterOpenAction.GO_ACTIVITY), // 下面这条是安保专用的,非传统推送!!! SECURITY_PASSWD_PARTICULAR_RESET_ACCEPT("账户安全提醒:", "安保专用的poll推送允许结果", "security_passwd_reset_accept", AfterOpenAction.GO_ACTIVITY), SECURITY_PASSWD_RESET_SUCC("账户安全提醒:", "安全密码重置成功,请知晓! \n" + "若非本人操作,请在【我的-设置-安全设置】里重置安全密码", "security_passwd_reset_succ", AfterOpenAction.GO_ACTIVITY), SECURITY_EMAIL_SET_SUCC("账户安全提醒:", """ 您已成功绑定密保邮箱 %s!\s 点击“查看详情”,查看更多信息 查看详情;""", "security_email_set_succ", AfterOpenAction.GO_ACTIVITY), SECURITY_EMAIL_MOD_SUCC("账户安全提醒:", """ 您已绑定新的密保邮箱 %s!\s 点击“查看详情”,查看更多信息 查看详情;""", "security_email_mod_succ", AfterOpenAction.GO_ACTIVITY), // 升级成功 UPGRADE_SUCCESS("系统升级提醒", "傲空间系统已经升级到最新版本啦,点击查看 >>","upgrade_success", AfterOpenAction.GO_ACTIVITY), // 下载成功 UPGRADE_DOWNLOAD_SUCCESS("已下载未安装提醒", "傲空间 %s可用于您的设备,且已经可以安装,点击去安装>>","upgrade_download_success", AfterOpenAction.GO_ACTIVITY), // 安装 <SUF> UPGRADE_INSTALLING("正在安装系统", "正在安装系统更新,傲空间设备可能无法正常访问,升级完成后将自动恢复使用 >>","upgrade_installing", AfterOpenAction.GO_ACTIVITY), // 盒子重启推送 UPGRADE_RESTART("系统升级提醒","正在重启设备,请在重启完成后使用","upgrade_restart", AfterOpenAction.GO_ACTIVITY), //备份进度和恢复进度 BACKUP_PROGRESS("","", "backup_progress", AfterOpenAction.GO_ACTIVITY), //恢复成功 RESTORE_SUCCESS("数据恢复完成","您的空间数据已完成恢复操作,如有疑问,请联系管理员。", "restore_success", AfterOpenAction.GO_ACTIVITY), TODAY_IN_HIS("历史上的今天", "小傲帮您整理了今天的一些记忆,去重温下吧~","today_in_his", AfterOpenAction.GO_ACTIVITY), MEMORIES("回忆", "小傲帮您整理了一些过往回忆,去重温下吧~","memories", AfterOpenAction.GO_ACTIVITY), ABILITY_CHANGE("平台API发生变化", "平台API发生变化","ability_change", AfterOpenAction.GO_ACTIVITY), HISTORY_RECORD("文件状态发生变化", "文件状态发生变化","HISTORY_RECORD", AfterOpenAction.GO_CUSTOM), ; private String title; private String text; private final String type; @Getter private final AfterOpenAction afterOpenAction; NotificationEnum(String title, String text, String type, AfterOpenAction afterOpenAction) { this.title = title; this.text = text; this.type = type; this.afterOpenAction = afterOpenAction; } public String getTitle() { return title; } public NotificationEnum setTitle(String title) { this.title = title; return this; } public String getText() { return text; } public NotificationEnum setText(String text) { this.text = text; return this; } public String getType() { return type; } public NotificationEnum setMemberJoin(String name){ MEMBER_JOIN.text = name + " 接受了您的邀请并创建了傲空间。点击查看 >>"; return MEMBER_JOIN; } public NotificationEnum setLogin(String name){ LOGIN.text = "您的空间已在设备:" + name +"登录,点击查看 >>"; return LOGIN; } public NotificationEnum setInnerLogin(String name){ LOGIN.text = "您的空间已在 " + name +" 登陆"; return LOGIN; } public NotificationEnum setLoginConfirm(String name, String userdomain){ LOGIN.text = name + " 申请登录您的傲空间(https://" + userdomain + "), 点击确认是否允许>>"; return LOGIN; } public NotificationEnum getSecurityPasswdModApply(String email){ SECURITY_PASSWD_MOD_APPLY.text = "您正在终端 " + email + " 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全"; return SECURITY_PASSWD_MOD_APPLY; } public NotificationEnum getSecurityPasswdResetApply(String email){ SECURITY_PASSWD_RESET_APPLY.text = "您正在终端 " + email + " 上进行安全密码相关操作,请及时确认 \n" + "请注意保护空间内的数据安全"; return SECURITY_PASSWD_RESET_APPLY; } public NotificationEnum getSecurityEmailSetSucc(String email){ SECURITY_EMAIL_SET_SUCC.text = "您已成功绑定密保邮箱 " + email+ "! \n" + "点击“查看详情”,查看更多信息\n"; return SECURITY_EMAIL_SET_SUCC; } public NotificationEnum getSecurityEmailModSucc(String email){ SECURITY_EMAIL_MOD_SUCC.text = "您已绑定新的密保邮箱 " + email + "! \n" + "点击“查看详情”,查看更多信息\n" + "查看详情;"; return SECURITY_EMAIL_MOD_SUCC; } public NotificationEnum getUpgradeDownloadSuccess(String version){ UPGRADE_DOWNLOAD_SUCCESS.text = "傲空间 " + version + "可用于您的设备,且已经可以安装,点击去安装>>"; return UPGRADE_DOWNLOAD_SUCCESS; } public static NotificationEnum of(String type){ for (var notification: NotificationEnum.values()){ if(notification.getType().equals(type)){ return notification; } } return null; } public static List<String> sendOnlyOnline(){ var sendOnlyOnline = new ArrayList<String>(); sendOnlyOnline.add(NotificationEnum.ABILITY_CHANGE.type); sendOnlyOnline.add(NotificationEnum.UPGRADE_RESTART.type); return sendOnlyOnline; } public static List<String> noNeedToSave(){ var noNeedToSave = new ArrayList<String>(); noNeedToSave.add(NotificationEnum.ABILITY_CHANGE.type); return noNeedToSave; } }
false
1,941
5
2,326
3
2,303
3
2,326
3
3,329
5
false
false
false
false
false
true