file_id
stringlengths
5
8
content
stringlengths
86
13.2k
repo
stringlengths
9
59
path
stringlengths
8
120
token_length
int64
31
3.28k
original_comment
stringlengths
5
1k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
87
13.2k
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
23
3.19k
comment-tokens-Qwen/Qwen2-7B
int64
2
532
file-tokens-bigcode/starcoder2-7b
int64
31
3.28k
comment-tokens-bigcode/starcoder2-7b
int64
2
654
file-tokens-google/codegemma-7b
int64
27
3.42k
comment-tokens-google/codegemma-7b
int64
2
548
file-tokens-ibm-granite/granite-8b-code-base
int64
31
3.28k
comment-tokens-ibm-granite/granite-8b-code-base
int64
2
654
file-tokens-meta-llama/CodeLlama-7b-hf
int64
37
3.93k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
992
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
42925_3
package com.qpidnetwork.livemodule.httprequest.item; public class BookInviteItem { public enum BookInviteStatus{ Unknown, Pending, //待确定 Confirmed, //已接受 Defined, //已拒绝 Missed, //错过 Canceled, //观众取消 AnchorOff, //主播缺席 AudienceOff, //观众缺席 Finished //已完成 } public BookInviteItem(){ } public BookInviteItem(String inviteId, String toId, String fromId, String oppositePhotoUrl, String oppositeNickname, boolean isReaded, int love_level, int bookInviteStatus, int bookTime, String giftId, String giftName, String giftBigImageUrl, String giftSmallImageUrl, int giftNum, int validTime, String roomId){ this.inviteId = inviteId; this.toId = toId; this.fromId = fromId; this.oppositePhotoUrl = oppositePhotoUrl; this.oppositeNickname = oppositeNickname; this.isReaded = isReaded; this.love_level = love_level; if( bookInviteStatus < 0 || bookInviteStatus >= BookInviteStatus.values().length ) { this.bookInviteStatus = BookInviteStatus.Unknown; } else { this.bookInviteStatus = BookInviteStatus.values()[bookInviteStatus]; } this.bookTime = bookTime; this.giftId = giftId; this.giftName = giftName; this.giftBigImageUrl = giftBigImageUrl; this.giftSmallImageUrl = giftSmallImageUrl; this.giftNum = giftNum; this.validTime = validTime; this.roomId = roomId; } public String inviteId; public String toId; public String fromId; public String oppositePhotoUrl; public String oppositeNickname; public boolean isReaded; public int love_level; public BookInviteStatus bookInviteStatus; public int bookTime; public String giftId; public String giftName; public String giftBigImageUrl; public String giftSmallImageUrl; public int giftNum; public int validTime; public String roomId; }
KingsleyYau/LiveClient
android/QNLiveShow/liveshowApp/src/main/java/com/qpidnetwork/livemodule/httprequest/item/BookInviteItem.java
597
//错过
line_comment
zh-cn
package com.qpidnetwork.livemodule.httprequest.item; public class BookInviteItem { public enum BookInviteStatus{ Unknown, Pending, //待确定 Confirmed, //已接受 Defined, //已拒绝 Missed, //错过 <SUF> Canceled, //观众取消 AnchorOff, //主播缺席 AudienceOff, //观众缺席 Finished //已完成 } public BookInviteItem(){ } public BookInviteItem(String inviteId, String toId, String fromId, String oppositePhotoUrl, String oppositeNickname, boolean isReaded, int love_level, int bookInviteStatus, int bookTime, String giftId, String giftName, String giftBigImageUrl, String giftSmallImageUrl, int giftNum, int validTime, String roomId){ this.inviteId = inviteId; this.toId = toId; this.fromId = fromId; this.oppositePhotoUrl = oppositePhotoUrl; this.oppositeNickname = oppositeNickname; this.isReaded = isReaded; this.love_level = love_level; if( bookInviteStatus < 0 || bookInviteStatus >= BookInviteStatus.values().length ) { this.bookInviteStatus = BookInviteStatus.Unknown; } else { this.bookInviteStatus = BookInviteStatus.values()[bookInviteStatus]; } this.bookTime = bookTime; this.giftId = giftId; this.giftName = giftName; this.giftBigImageUrl = giftBigImageUrl; this.giftSmallImageUrl = giftSmallImageUrl; this.giftNum = giftNum; this.validTime = validTime; this.roomId = roomId; } public String inviteId; public String toId; public String fromId; public String oppositePhotoUrl; public String oppositeNickname; public boolean isReaded; public int love_level; public BookInviteStatus bookInviteStatus; public int bookTime; public String giftId; public String giftName; public String giftBigImageUrl; public String giftSmallImageUrl; public int giftNum; public int validTime; public String roomId; }
false
494
3
596
4
582
3
596
4
809
4
false
false
false
false
false
true
51828_3
//54. 螺旋矩阵 //https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-interview-150 import java.util.ArrayList; import java.util.List; public class P54 { // 定义左和右,上和下,每个内层循环前先判断是否还能继续,不能就是遍历完了 public static List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return ans; int u = 0, d = matrix.length - 1; int l = 0, r = matrix[0].length - 1; while (true) { for (int i = l; i <= r; i++) { // 左->右 ans.add(matrix[u][i]); } if (++u > d) break; for (int i = u; i <= d; i++) { // 上->下 ans.add(matrix[i][r]); } if (--r < l) break; for (int i = r; i >= l; i--) { // 右->左 ans.add(matrix[d][i]); } if (--d < u) break; for (int i = d; i >= u; i--) { // 下->上 ans.add(matrix[i][l]); } if (++l > r) break; } return ans; } // 代码太过复杂,把自己都绕晕了,还是完不成所有测试用例 // public static List<Integer> spiralOrder(int[][] matrix) { // int m = matrix.length; // int n = matrix[0].length; // List<Integer> res = new ArrayList(); // int idx1 = 0, idx2 = 0; // //右下左上状态 // int status = 0; // //每个方向各已返回多少列 0:上,1:右,2:下,3:左 // int[] times = new int[4]; // for (int i = 0; i < m * n;) { // if (status == 0) { // if (!res.isEmpty()) { // idx1++; // idx2++; // } // while (idx2 < n - times[1]) { // res.add(matrix[idx1][idx2++]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[0]++; // status = 1; // } else if (status == 1) { // if (idx2 >= n) { // idx2--; // } // ++idx1; // while (idx1 < m - times[2]) { // res.add(matrix[idx1++][idx2]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[1]++; // status = 2; // } else if (status == 2) { // if (idx1 >= m) { // idx1--; // } // --idx2; // while (idx2 >= times[3]) { // res.add(matrix[idx1][idx2--]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[2]++; // status = 3; // } else if (status == 3) { // if (idx2 < 0) { // idx2++; // } // --idx1; // while (idx1 >= times[0]) { // res.add(matrix[idx1--][idx2]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[3]++; // status = 0; // } // } // return res; // } public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; //int[][] matrix = {{1, 2}, {3, 4}}; //int[][] matrix = {{1, 2}, {3, 4}, {5, 6}}; //int[][] matrix = {{2, 5, 8}, {4, 0, -1}}; System.out.println(spiralOrder(matrix)); } }
Kingsman007137/leetcode-practices
medium/P54.java
1,180
// 左->右
line_comment
zh-cn
//54. 螺旋矩阵 //https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-interview-150 import java.util.ArrayList; import java.util.List; public class P54 { // 定义左和右,上和下,每个内层循环前先判断是否还能继续,不能就是遍历完了 public static List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return ans; int u = 0, d = matrix.length - 1; int l = 0, r = matrix[0].length - 1; while (true) { for (int i = l; i <= r; i++) { // 左- <SUF> ans.add(matrix[u][i]); } if (++u > d) break; for (int i = u; i <= d; i++) { // 上->下 ans.add(matrix[i][r]); } if (--r < l) break; for (int i = r; i >= l; i--) { // 右->左 ans.add(matrix[d][i]); } if (--d < u) break; for (int i = d; i >= u; i--) { // 下->上 ans.add(matrix[i][l]); } if (++l > r) break; } return ans; } // 代码太过复杂,把自己都绕晕了,还是完不成所有测试用例 // public static List<Integer> spiralOrder(int[][] matrix) { // int m = matrix.length; // int n = matrix[0].length; // List<Integer> res = new ArrayList(); // int idx1 = 0, idx2 = 0; // //右下左上状态 // int status = 0; // //每个方向各已返回多少列 0:上,1:右,2:下,3:左 // int[] times = new int[4]; // for (int i = 0; i < m * n;) { // if (status == 0) { // if (!res.isEmpty()) { // idx1++; // idx2++; // } // while (idx2 < n - times[1]) { // res.add(matrix[idx1][idx2++]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[0]++; // status = 1; // } else if (status == 1) { // if (idx2 >= n) { // idx2--; // } // ++idx1; // while (idx1 < m - times[2]) { // res.add(matrix[idx1++][idx2]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[1]++; // status = 2; // } else if (status == 2) { // if (idx1 >= m) { // idx1--; // } // --idx2; // while (idx2 >= times[3]) { // res.add(matrix[idx1][idx2--]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[2]++; // status = 3; // } else if (status == 3) { // if (idx2 < 0) { // idx2++; // } // --idx1; // while (idx1 >= times[0]) { // res.add(matrix[idx1--][idx2]); // i++; // } // System.out.println(res + " " + idx1 + " " + idx2 + " " + status); // times[3]++; // status = 0; // } // } // return res; // } public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; //int[][] matrix = {{1, 2}, {3, 4}}; //int[][] matrix = {{1, 2}, {3, 4}, {5, 6}}; //int[][] matrix = {{2, 5, 8}, {4, 0, -1}}; System.out.println(spiralOrder(matrix)); } }
false
1,113
5
1,180
5
1,254
4
1,180
5
1,360
5
false
false
false
false
false
true
61988_0
package com.olympics.specification; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; /** * 此类用于测试根据日期、地点查询比赛项目,使用到数据映射模式、流接口模式和封装字段模式。 */ public class Sport { private String name; private int num; private String place; private Calendar date; public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setDate(Calendar date) { this.date = date; } public Calendar getDate() { return this.date; } public void setPlace(String place) { this.place = place; } public String getPlace() { return this.place; } public void showPlaceOf(String name) { this.name = name; this.num++; System.out.println(this.name + " 项目的地点在 " + this.place); } public void showDateOf(String name) { this.name = name; this.num++; DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(this.name + " 项目的日期是 " + df.format(this.date.getTime())); } public static void main(String[] args) { Sport running = new Sport(); running.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 20); running.setPlace("操场"); Sport swimming = new Sport(); swimming.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 19); swimming.setPlace("泳池"); Sport basketball = new Sport(); basketball.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 18); basketball.setPlace("篮球场"); Sport football = new Sport(); football.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 17); football.setPlace("足球场"); Sport fencing = new Sport(); fencing.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 14); fencing.setPlace("击剑馆"); Sport badminton = new Sport(); badminton.date = new GregorianCalendar(2020, Calendar.DECEMBER, 11); badminton.setPlace("羽毛球馆"); Sport hurdle = new Sport(); hurdle.date = new GregorianCalendar(2020, Calendar.DECEMBER, 2); hurdle.setPlace("操场"); running.showPlaceOf("跑步"); swimming.showPlaceOf("游泳"); swimming.showDateOf("游泳"); hurdle.showDateOf(" 跨栏"); System.out.println("游泳项目被查询过" + swimming.num + "次"); System.out.println("跑步项目被查询过" + running.num + "次"); System.out.println("跨栏项目被查询过" + hurdle.num + "次"); } }
Kingzoey/AnimalsOlympics
src/main/java/com/olympics/specification/Sport.java
806
/** * 此类用于测试根据日期、地点查询比赛项目,使用到数据映射模式、流接口模式和封装字段模式。 */
block_comment
zh-cn
package com.olympics.specification; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; /** * 此类用 <SUF>*/ public class Sport { private String name; private int num; private String place; private Calendar date; public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setDate(Calendar date) { this.date = date; } public Calendar getDate() { return this.date; } public void setPlace(String place) { this.place = place; } public String getPlace() { return this.place; } public void showPlaceOf(String name) { this.name = name; this.num++; System.out.println(this.name + " 项目的地点在 " + this.place); } public void showDateOf(String name) { this.name = name; this.num++; DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(this.name + " 项目的日期是 " + df.format(this.date.getTime())); } public static void main(String[] args) { Sport running = new Sport(); running.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 20); running.setPlace("操场"); Sport swimming = new Sport(); swimming.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 19); swimming.setPlace("泳池"); Sport basketball = new Sport(); basketball.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 18); basketball.setPlace("篮球场"); Sport football = new Sport(); football.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 17); football.setPlace("足球场"); Sport fencing = new Sport(); fencing.date = new GregorianCalendar(2020, Calendar.SEPTEMBER, 14); fencing.setPlace("击剑馆"); Sport badminton = new Sport(); badminton.date = new GregorianCalendar(2020, Calendar.DECEMBER, 11); badminton.setPlace("羽毛球馆"); Sport hurdle = new Sport(); hurdle.date = new GregorianCalendar(2020, Calendar.DECEMBER, 2); hurdle.setPlace("操场"); running.showPlaceOf("跑步"); swimming.showPlaceOf("游泳"); swimming.showDateOf("游泳"); hurdle.showDateOf(" 跨栏"); System.out.println("游泳项目被查询过" + swimming.num + "次"); System.out.println("跑步项目被查询过" + running.num + "次"); System.out.println("跨栏项目被查询过" + hurdle.num + "次"); } }
false
640
31
806
33
770
31
806
33
959
59
false
false
false
false
false
true
52554_4
package program; import java.util.Arrays; public class _1365 { public static void main(String[] args) { Solution so = new Solution(); int[] res = so.smallerNumbersThanCurrent_1(new int[]{8, 1, 2, 2, 3}); for (int re : res) { System.out.println(re); } } static class Solution { //方法1.暴力 public int[] smallerNumbersThanCurrent(int[] nums) { int[] res = new int[nums.length]; for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length; j++) { if(nums[i] > nums[j]) res[i]++; } } return res; } //方法2.排序 public int[] smallerNumbersThanCurrent_1(int[] nums) { int n = nums.length; int[][] data = new int[n][2]; //存数组元素和对应下标 int[] res = new int[n]; for (int i = 0; i < nums.length; i++) { data[i][0] = nums[i]; //存该数字 data[i][1] = i; //存该数字下标 } Arrays.sort(data, (a, b) -> a[0] - b[0]); //从小到大排序 int pre = 0; //如果有该数在数组中有多个,那么此变量将用于记录该数大于了多少数 for (int i = 0; i < n; i++) { if(i > 0 && data[i-1][0] != data[i][0]){ //如果当前数与前一个数不同,那么当前数大于了pre个数,反之pre不变 pre = i; } res[data[i][1]] = pre; } return res; } } }
Kiraaaaaaa/leet-code-algorithm-diary
src/program/_1365.java
457
//存该数字下标
line_comment
zh-cn
package program; import java.util.Arrays; public class _1365 { public static void main(String[] args) { Solution so = new Solution(); int[] res = so.smallerNumbersThanCurrent_1(new int[]{8, 1, 2, 2, 3}); for (int re : res) { System.out.println(re); } } static class Solution { //方法1.暴力 public int[] smallerNumbersThanCurrent(int[] nums) { int[] res = new int[nums.length]; for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length; j++) { if(nums[i] > nums[j]) res[i]++; } } return res; } //方法2.排序 public int[] smallerNumbersThanCurrent_1(int[] nums) { int n = nums.length; int[][] data = new int[n][2]; //存数组元素和对应下标 int[] res = new int[n]; for (int i = 0; i < nums.length; i++) { data[i][0] = nums[i]; //存该数字 data[i][1] = i; //存该 <SUF> } Arrays.sort(data, (a, b) -> a[0] - b[0]); //从小到大排序 int pre = 0; //如果有该数在数组中有多个,那么此变量将用于记录该数大于了多少数 for (int i = 0; i < n; i++) { if(i > 0 && data[i-1][0] != data[i][0]){ //如果当前数与前一个数不同,那么当前数大于了pre个数,反之pre不变 pre = i; } res[data[i][1]] = pre; } return res; } } }
false
423
6
457
6
488
6
457
6
548
7
false
false
false
false
false
true
44918_48
package xupt.se.ttms.view.table; import java.awt.Color; import java.awt.Label; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import java.util.List; import java.util.Iterator; import xupt.se.ttms.model.Seat; import xupt.se.ttms.model.Studio; import xupt.se.ttms.service.SeatSrv; import xupt.se.ttms.service.StudioSrv; import xupt.se.ttms.view.component.CircleButton; import xupt.se.ttms.view.component.CircleTextField; import xupt.se.ttms.view.tmpl.*; //class SeatTableMouseListener extends MouseAdapter { // // private JTable jt; // private static Seat seat; // // public Seat getSeat() { // return seat; // } // // public SeatTableMouseListener(JTable jt, Object[] number, Seat seat) { // this.seat = seat; // this.jt = jt; // } // // // 监听到行号,将所选行的内容依次赋到ddict对象,以便传有值对象到修改面板进行修改 // public void mouseClicked(MouseEvent event) { // int row = jt.getSelectedRow(); // seat.setId(Integer.parseInt(jt.getValueAt(row, 0).toString())); // seat.setStudioId(Integer.parseInt(jt.getValueAt(row, 1).toString())); // seat.setRow(Integer.parseInt(jt.getValueAt(row, 2).toString())); // seat.setColumn(Integer.parseInt(jt.getValueAt(row, 3).toString())); // // System.out.println(jt.getValueAt(row, 1).toString()); // } //} // //class SeatTable { // // private Seat seat; // private JTable jt = null; // // public SeatTable(Seat seat) { // this.seat = seat; // } // // // 创建JTable // public void createTable(JScrollPane jp, Object[] columnNames, List<Seat> seatList) { // try { // // Object data[][] = new Object[seatList.size()][columnNames.length]; // // Iterator<Seat> itr =seatList.iterator(); // int i = 0; // while (itr.hasNext()) { // Seat tmpSeat = itr.next(); // data[i][0] = Integer.toString(tmpSeat.getId()); // data[i][1] = Integer.toString(tmpSeat.getStudioId()); // data[i][2] = Integer.toString(tmpSeat.getRow()); // data[i][3] = Integer.toString(tmpSeat.getColumn()); // i++; // } // // // 生成JTable // jt = new JTable(data, columnNames); // jt.setBounds(0, 0, 700, 450); // // // 添加鼠标监听,监听到所选行 // SeatTableMouseListener tml = new SeatTableMouseListener(jt, columnNames, seat); // jt.addMouseListener(tml); // // // 设置可调整列宽 // jt.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); // // jp.add(jt); // jp.setViewportView(jt); // // } catch (Exception e) { // e.printStackTrace(); // } // } //} class SeatTable { /** * */ private static final long serialVersionUID = 1L; private JTable jt; public SeatTable(JScrollPane jp) { DefaultTableModel tabModel=new DefaultTableModel(){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row,int column){ return false; }; }; tabModel.addColumn("id"); tabModel.addColumn("演出厅名称"); tabModel.addColumn("座位所在行"); tabModel.addColumn("座位所在列"); tabModel.addColumn("座位状态"); //初始化列明 jt=new JTable(tabModel); //设置各列的宽度 TableColumnModel columnModel = jt.getColumnModel(); //隐藏ID这一列 TableColumn column = columnModel.getColumn(0); column.setMinWidth(0); column.setMaxWidth(0); column.setWidth(0); column.setPreferredWidth(0); column = columnModel.getColumn(1); column.setPreferredWidth(10); column = columnModel.getColumn(2); column.setPreferredWidth(10); column = columnModel.getColumn(3); column.setPreferredWidth(10); column = columnModel.getColumn(4); column.setPreferredWidth(10); jp.add(jt); jp.setViewportView(jt); } public Seat getSeat() { int rowSel=jt.getSelectedRow(); if(rowSel>=0){ Seat seat = new Seat(); seat.setId(Integer.parseInt(jt.getValueAt(rowSel, 0).toString())); //seat.setStudioId(Integer.parseInt(jt.getValueAt(rowSel, 1).toString())); List<Studio> stuList = new StudioSrv().FetchAll(); Iterator<Studio> it1 = stuList.iterator(); Studio stud = null; for(;it1.hasNext();){ stud = it1.next(); if (stud.getName().equals(jt.getValueAt(rowSel, 1).toString())){ seat.setStudioId(stud.getID()); } } seat.setRow(Integer.parseInt(jt.getValueAt(rowSel, 2).toString())); seat.setColumn(Integer.parseInt(jt.getValueAt(rowSel, 3).toString())); //seat.setSeatStatus(Integer.parseInt(jt.getValueAt(rowSel, 4).toString())); if(jt.getValueAt(rowSel, 4).toString() == "正常") { seat.setSeatStatus(1); } else if(jt.getValueAt(rowSel, 4).toString() == "损坏") { seat.setSeatStatus(0); } return seat; } else{ return null; } } // 创建JTable public void showSeatList(List<Seat> seaList,List<Studio> stuList) { try { DefaultTableModel tabModel = (DefaultTableModel) jt.getModel(); tabModel.setRowCount(0); Iterator<Seat> itr = seaList.iterator(); while (itr.hasNext()) { Seat tmpSeat = itr.next(); Object data[] = new Object[5]; data[0] = Integer.toString(tmpSeat.getId()); // //list studio Iterator<Studio> it1 = stuList.iterator(); Studio stud = null; for(;it1.hasNext();){ stud = it1.next(); if (stud.getID() == tmpSeat.getStudioId()){ data[1] = stud.getName(); } } //data[1] = Integer.toString(tmpSeat.getStudioId()); data[2] = Integer.toString(tmpSeat.getRow()); data[3] = Integer.toString(tmpSeat.getColumn()); //data[4] = Integer.toString(tmpSeat.getSeatStatus()); if(tmpSeat.getSeatStatus() == 1) { data[4] = "正常"; } else if(tmpSeat.getSeatStatus() == 0) { data[4] = "损坏"; } tabModel.addRow(data);; } jt.invalidate(); } catch (Exception e) { e.printStackTrace(); } } } public class SeatTableUI extends PopUITmplEmp { /** * */ private static final long serialVersionUID = 1L; private JLabel ca1 = null; // 界面提示 // 用来放表格的滚动控件 private JScrollPane jsc; // 查找的提示和输出 private JLabel hint; private JTextField input; // 查找,编辑和删除按钮 private JButton btnAdd, btnEdit, btnDel, btnQuery; SeatTable tms; //显示座位列表 private static String username; private static int userid; public SeatTableUI(String name,int id) { super(name,id); username = name; userid = id; initContent(); } // To be override by the detailed business block interface @Override protected void initContent() { Rectangle rect = contPan.getBounds(); this.setTitle("座位信息"); jsc = new JScrollPane(); jsc.setBounds(0, 40, rect.width, rect.height-90); contPan.add(jsc); hint = new JLabel("请输入查询信息:", JLabel.RIGHT); hint.setFont(new java.awt.Font("华文行楷", 1, 15)); hint.setBounds(150, rect.height - 45, 150, 30); contPan.add(hint); input = new CircleTextField(10); input.setBounds(310, rect.height - 45, 200, 30); contPan.add(input); // 查找 ,删除和编辑的按钮,其中含有相关的事件处理! btnQuery = new CircleButton("查找"); btnQuery.setBounds(530, rect.height - 45, 60, 30); btnQuery.setFont(new java.awt.Font("华文行楷", 1, 12)); btnQuery.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent Event) { btnQueryClicked(); } }); contPan.add(btnQuery); tms = new SeatTable(jsc); showTable(); } private void btnQueryClicked() { if (!input.getText().equals("")) { showTable(); // 还没有处理,暂时显示全部内容 } else { JOptionPane.showMessageDialog(null, "请输入检索条件"); } } // public void showTable() { // SeatTable tms = new SeatTable(seat); // Object[] in = { "id", "演出厅Id", "座位所在行", "座位所在列" }; // List<Seat> stuList = new SeatSrv().FetchAll(); // // tms.createTable(jsc, in, stuList); // jsc.repaint(); // } private void showTable() { List<Seat> seaList = new SeatSrv().FetchAll(); // List<Studio> stuList = new StudioSrv().FetchAll(); tms.showSeatList(seaList,stuList); } public static void main(String[] args) { SeatTableUI frmStuMgr = new SeatTableUI(username,userid); frmStuMgr.setVisible(true); } }
KiritoLiuyhSky/TTMS_Java
src/xupt/se/ttms/view/table/SeatTableUI.java
2,967
//隐藏ID这一列
line_comment
zh-cn
package xupt.se.ttms.view.table; import java.awt.Color; import java.awt.Label; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import java.util.List; import java.util.Iterator; import xupt.se.ttms.model.Seat; import xupt.se.ttms.model.Studio; import xupt.se.ttms.service.SeatSrv; import xupt.se.ttms.service.StudioSrv; import xupt.se.ttms.view.component.CircleButton; import xupt.se.ttms.view.component.CircleTextField; import xupt.se.ttms.view.tmpl.*; //class SeatTableMouseListener extends MouseAdapter { // // private JTable jt; // private static Seat seat; // // public Seat getSeat() { // return seat; // } // // public SeatTableMouseListener(JTable jt, Object[] number, Seat seat) { // this.seat = seat; // this.jt = jt; // } // // // 监听到行号,将所选行的内容依次赋到ddict对象,以便传有值对象到修改面板进行修改 // public void mouseClicked(MouseEvent event) { // int row = jt.getSelectedRow(); // seat.setId(Integer.parseInt(jt.getValueAt(row, 0).toString())); // seat.setStudioId(Integer.parseInt(jt.getValueAt(row, 1).toString())); // seat.setRow(Integer.parseInt(jt.getValueAt(row, 2).toString())); // seat.setColumn(Integer.parseInt(jt.getValueAt(row, 3).toString())); // // System.out.println(jt.getValueAt(row, 1).toString()); // } //} // //class SeatTable { // // private Seat seat; // private JTable jt = null; // // public SeatTable(Seat seat) { // this.seat = seat; // } // // // 创建JTable // public void createTable(JScrollPane jp, Object[] columnNames, List<Seat> seatList) { // try { // // Object data[][] = new Object[seatList.size()][columnNames.length]; // // Iterator<Seat> itr =seatList.iterator(); // int i = 0; // while (itr.hasNext()) { // Seat tmpSeat = itr.next(); // data[i][0] = Integer.toString(tmpSeat.getId()); // data[i][1] = Integer.toString(tmpSeat.getStudioId()); // data[i][2] = Integer.toString(tmpSeat.getRow()); // data[i][3] = Integer.toString(tmpSeat.getColumn()); // i++; // } // // // 生成JTable // jt = new JTable(data, columnNames); // jt.setBounds(0, 0, 700, 450); // // // 添加鼠标监听,监听到所选行 // SeatTableMouseListener tml = new SeatTableMouseListener(jt, columnNames, seat); // jt.addMouseListener(tml); // // // 设置可调整列宽 // jt.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); // // jp.add(jt); // jp.setViewportView(jt); // // } catch (Exception e) { // e.printStackTrace(); // } // } //} class SeatTable { /** * */ private static final long serialVersionUID = 1L; private JTable jt; public SeatTable(JScrollPane jp) { DefaultTableModel tabModel=new DefaultTableModel(){ private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row,int column){ return false; }; }; tabModel.addColumn("id"); tabModel.addColumn("演出厅名称"); tabModel.addColumn("座位所在行"); tabModel.addColumn("座位所在列"); tabModel.addColumn("座位状态"); //初始化列明 jt=new JTable(tabModel); //设置各列的宽度 TableColumnModel columnModel = jt.getColumnModel(); //隐藏 <SUF> TableColumn column = columnModel.getColumn(0); column.setMinWidth(0); column.setMaxWidth(0); column.setWidth(0); column.setPreferredWidth(0); column = columnModel.getColumn(1); column.setPreferredWidth(10); column = columnModel.getColumn(2); column.setPreferredWidth(10); column = columnModel.getColumn(3); column.setPreferredWidth(10); column = columnModel.getColumn(4); column.setPreferredWidth(10); jp.add(jt); jp.setViewportView(jt); } public Seat getSeat() { int rowSel=jt.getSelectedRow(); if(rowSel>=0){ Seat seat = new Seat(); seat.setId(Integer.parseInt(jt.getValueAt(rowSel, 0).toString())); //seat.setStudioId(Integer.parseInt(jt.getValueAt(rowSel, 1).toString())); List<Studio> stuList = new StudioSrv().FetchAll(); Iterator<Studio> it1 = stuList.iterator(); Studio stud = null; for(;it1.hasNext();){ stud = it1.next(); if (stud.getName().equals(jt.getValueAt(rowSel, 1).toString())){ seat.setStudioId(stud.getID()); } } seat.setRow(Integer.parseInt(jt.getValueAt(rowSel, 2).toString())); seat.setColumn(Integer.parseInt(jt.getValueAt(rowSel, 3).toString())); //seat.setSeatStatus(Integer.parseInt(jt.getValueAt(rowSel, 4).toString())); if(jt.getValueAt(rowSel, 4).toString() == "正常") { seat.setSeatStatus(1); } else if(jt.getValueAt(rowSel, 4).toString() == "损坏") { seat.setSeatStatus(0); } return seat; } else{ return null; } } // 创建JTable public void showSeatList(List<Seat> seaList,List<Studio> stuList) { try { DefaultTableModel tabModel = (DefaultTableModel) jt.getModel(); tabModel.setRowCount(0); Iterator<Seat> itr = seaList.iterator(); while (itr.hasNext()) { Seat tmpSeat = itr.next(); Object data[] = new Object[5]; data[0] = Integer.toString(tmpSeat.getId()); // //list studio Iterator<Studio> it1 = stuList.iterator(); Studio stud = null; for(;it1.hasNext();){ stud = it1.next(); if (stud.getID() == tmpSeat.getStudioId()){ data[1] = stud.getName(); } } //data[1] = Integer.toString(tmpSeat.getStudioId()); data[2] = Integer.toString(tmpSeat.getRow()); data[3] = Integer.toString(tmpSeat.getColumn()); //data[4] = Integer.toString(tmpSeat.getSeatStatus()); if(tmpSeat.getSeatStatus() == 1) { data[4] = "正常"; } else if(tmpSeat.getSeatStatus() == 0) { data[4] = "损坏"; } tabModel.addRow(data);; } jt.invalidate(); } catch (Exception e) { e.printStackTrace(); } } } public class SeatTableUI extends PopUITmplEmp { /** * */ private static final long serialVersionUID = 1L; private JLabel ca1 = null; // 界面提示 // 用来放表格的滚动控件 private JScrollPane jsc; // 查找的提示和输出 private JLabel hint; private JTextField input; // 查找,编辑和删除按钮 private JButton btnAdd, btnEdit, btnDel, btnQuery; SeatTable tms; //显示座位列表 private static String username; private static int userid; public SeatTableUI(String name,int id) { super(name,id); username = name; userid = id; initContent(); } // To be override by the detailed business block interface @Override protected void initContent() { Rectangle rect = contPan.getBounds(); this.setTitle("座位信息"); jsc = new JScrollPane(); jsc.setBounds(0, 40, rect.width, rect.height-90); contPan.add(jsc); hint = new JLabel("请输入查询信息:", JLabel.RIGHT); hint.setFont(new java.awt.Font("华文行楷", 1, 15)); hint.setBounds(150, rect.height - 45, 150, 30); contPan.add(hint); input = new CircleTextField(10); input.setBounds(310, rect.height - 45, 200, 30); contPan.add(input); // 查找 ,删除和编辑的按钮,其中含有相关的事件处理! btnQuery = new CircleButton("查找"); btnQuery.setBounds(530, rect.height - 45, 60, 30); btnQuery.setFont(new java.awt.Font("华文行楷", 1, 12)); btnQuery.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent Event) { btnQueryClicked(); } }); contPan.add(btnQuery); tms = new SeatTable(jsc); showTable(); } private void btnQueryClicked() { if (!input.getText().equals("")) { showTable(); // 还没有处理,暂时显示全部内容 } else { JOptionPane.showMessageDialog(null, "请输入检索条件"); } } // public void showTable() { // SeatTable tms = new SeatTable(seat); // Object[] in = { "id", "演出厅Id", "座位所在行", "座位所在列" }; // List<Seat> stuList = new SeatSrv().FetchAll(); // // tms.createTable(jsc, in, stuList); // jsc.repaint(); // } private void showTable() { List<Seat> seaList = new SeatSrv().FetchAll(); // List<Studio> stuList = new StudioSrv().FetchAll(); tms.showSeatList(seaList,stuList); } public static void main(String[] args) { SeatTableUI frmStuMgr = new SeatTableUI(username,userid); frmStuMgr.setVisible(true); } }
false
2,362
5
2,967
5
2,874
5
2,967
5
3,675
9
false
false
false
false
false
true
36664_2
package com.lee.shiroDemo.conroller; import com.lee.shiroDemo.dao.LoginDao; import com.lee.shiroDemo.entity.User; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; /** * Description: * User: Lzj * Date: 2020-04-28 * Time: 10:24 */ @RestController @RequestMapping("/api") public class LoginController { private LoginDao loginDao; @Autowired public LoginController(LoginDao loginDao) { this.loginDao = loginDao; } @GetMapping("index") public String index(){ return "大哥大嫂过年好……我是index"; } @PostMapping("signUp") public String signUp(@RequestBody User user, HttpServletResponse response) { if (user.getUsername() == null || user.getPassword() == null) { response.setStatus(HttpStatus.BAD_REQUEST.value()); return "注册失败"; } loginDao.signUp(user); return "注册成功"; } @PostMapping("login") public String login(@RequestBody User user) { // 拼装一个token,也就是realm中需要使用到的AuthenticationInfo UsernamePasswordToken token = new UsernamePasswordToken(); token.setUsername(user.getUsername()); token.setPassword(user.getPassword().toCharArray()); try { SecurityUtils.getSubject().login(token); } catch (AuthenticationException e) { e.printStackTrace(); // 这里还有很多子类,可以看看官网 return "登录失败"; } return "登录成功"; } }
KisetsuLee/shiro-demo
src/main/java/com/lee/shiroDemo/conroller/LoginController.java
447
// 这里还有很多子类,可以看看官网
line_comment
zh-cn
package com.lee.shiroDemo.conroller; import com.lee.shiroDemo.dao.LoginDao; import com.lee.shiroDemo.entity.User; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; /** * Description: * User: Lzj * Date: 2020-04-28 * Time: 10:24 */ @RestController @RequestMapping("/api") public class LoginController { private LoginDao loginDao; @Autowired public LoginController(LoginDao loginDao) { this.loginDao = loginDao; } @GetMapping("index") public String index(){ return "大哥大嫂过年好……我是index"; } @PostMapping("signUp") public String signUp(@RequestBody User user, HttpServletResponse response) { if (user.getUsername() == null || user.getPassword() == null) { response.setStatus(HttpStatus.BAD_REQUEST.value()); return "注册失败"; } loginDao.signUp(user); return "注册成功"; } @PostMapping("login") public String login(@RequestBody User user) { // 拼装一个token,也就是realm中需要使用到的AuthenticationInfo UsernamePasswordToken token = new UsernamePasswordToken(); token.setUsername(user.getUsername()); token.setPassword(user.getPassword().toCharArray()); try { SecurityUtils.getSubject().login(token); } catch (AuthenticationException e) { e.printStackTrace(); // 这里 <SUF> return "登录失败"; } return "登录成功"; } }
false
368
11
447
13
464
11
447
13
555
19
false
false
false
false
false
true
28488_0
package com.knziha.plod.plaindict; import static com.knziha.plod.plaindict.CMN.hotDebugMessage; import static com.knziha.plod.plaindict.CMN.hotTracingObject; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Build; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.GlobalOptions; import com.knziha.plod.dictionary.Utils.SU; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; //美滋滋 @SuppressLint({"WrongConstant"}) public class CrashHandler implements UncaughtExceptionHandler { public static final String TAG = "FatalHandler"; /** System default handler */ private UncaughtExceptionHandler mDefaultHandler; private static CrashHandler instance; //private Context mContext; private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, HH-mm-ss", Locale.CHINA); StringBuilder info_builder; private String log_path; private final boolean bSilentExitBypassingSystem; private final boolean bLogToFile; private boolean registered; private boolean turnedon; public static CrashHandler getInstance(Context contex, PDICMainAppOptions opt) { if(instance == null) instance = new CrashHandler(contex,opt); return instance; } public String getLogFile(){ return log_path; } private CrashHandler(Context contex, PDICMainAppOptions opt){ mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); bSilentExitBypassingSystem = true;//opt.getSilentExitBypassingSystem(); bLogToFile = opt.getLogToFile(); info_builder=new StringBuilder(); info_builder.setLength(0); info_builder.append(contex.getResources().getString(R.string.app_name)).append(" [").append(Build.MANUFACTURER) .append(", v").append(Build.VERSION.SDK_INT).append("_").append(Build.VERSION.CODENAME); } public void register(Context context) { if(registered) return; Thread.setDefaultUncaughtExceptionHandler(this); log_path=context.getExternalFilesDir("").getAbsolutePath()+"/logs/crash.txt"; PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); PackageInfo program_info=null; info_builder.append("] [v"); try { program_info = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES|PackageManager.GET_SIGNATURES); } catch (Exception e) { CMN.Log(e); } if (program_info != null) { info_builder.append(program_info.versionName).append(", ").append(program_info.versionCode); try{ Signature[] signatures = program_info.signatures; if(signatures!=null && signatures.length>0) { byte[] cert = signatures[0].toByteArray(); InputStream input = new ByteArrayInputStream(cert); byte[] publicKey = MessageDigest.getInstance("SHA1").digest(((X509Certificate)CertificateFactory.getInstance("X509").generateCertificate(input)).getEncoded()); // BU.printBytes(publicKey); // CMN.Log(111); // CMN.Log(new String(publicKey)); //todo ??? } } catch (Exception e){ CMN.Log(e); } } info_builder.append("]\n"); ApplicationInfo app_info = context.getApplicationInfo(); GlobalOptions.debug=SU.debug=(app_info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; registered=true; } public void unRegister(){ registered=false; if(mDefaultHandler!=null) Thread.setDefaultUncaughtExceptionHandler(mDefaultHandler); } public void TurnOn(){ turnedon=true; } public void TurnOff(){ turnedon=false; } @Override public void uncaughtException(@NonNull Thread thread, @NonNull Throwable exception) { Log.e("ODPlayer","::fatal exception : "+exception.toString()); Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); Throwable cause = exception.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.close(); String result = writer.toString(); String time = formatter.format(new Date()); info_builder.append("crash-=====Log-start=====") .append(time).append("\n"); if(hotTracingObject!=null) info_builder.append("at : ").append(hotTracingObject).append("\n"); if(hotDebugMessage!=null) info_builder.append("at : ").append(hotDebugMessage).append("\n"); ; info_builder.append(result); String trace = null; if(bLogToFile || GlobalOptions.debug){ try { File log=new File(log_path); File dir = log.getParentFile(); dir.mkdirs(); if(log.isDirectory()) log.delete(); FileOutputStream fos = new FileOutputStream(log_path); trace = info_builder.toString(); fos.write(trace.getBytes()); fos.close(); new File(dir, "lock").mkdirs(); if (GlobalOptions.debug) { fos = new FileOutputStream(new File(new File(log_path).getParentFile(), "crash_"+CMN.now()+".log")); fos.write(trace.getBytes()); fos.close(); } } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } } CMN.Log("crash catched", GlobalOptions.debug?trace:"_"+exception); postUncaughtException(thread, exception); } private void postUncaughtException(@NonNull Thread thread, @NonNull Throwable exception) { if(!turnedon || !registered || !bSilentExitBypassingSystem){ if(mDefaultHandler != null) mDefaultHandler.uncaughtException(thread, exception); unRegister(); }else { unRegister(); System.exit(1); } } public void showErrorMessage(Context context, DialogInterface.OnClickListener btnLis, boolean simulated) { String message = null; String title = "天哪,崩溃了……"; if (simulated) { title = "[模拟] "+title; try{ throw new RuntimeException(title); } catch (Exception e) { message = CMN.Log(e); } } else { File log = new File(getLogFile()); if (log.exists()) { try { byte[] buffer = new byte[Math.min((int) log.length(), 4096)]; int len = new FileInputStream(log).read(buffer); message=new String(buffer,0,len); if(GlobalOptions.debug||btnLis==null) { CMN.Log(message); } } catch (IOException e) { CMN.Log(e); } } } if (message!=null) { String finalMessage = message; View btn = new AlertDialog.Builder(context) .setMessage(message) .setPositiveButton(android.R.string.yes, btnLis) .setNeutralButton(android.R.string.copy, null) .setTitle(title) .setCancelable(btnLis == null) .show() .findViewById(android.R.id.button3); btn.setOnClickListener(v -> { if (context instanceof Toastable_Activity) { ((Toastable_Activity) context).FuzhiText(finalMessage); } }); if (simulated) { String finalTitle = title; btn.setOnLongClickListener(v -> { throw new RuntimeException(finalTitle); }); } } } }
KnIfER/PlainDictionaryAPP
PLOD/src/main/java/com/knziha/plod/PlainDict/CrashHandler.java
2,211
//美滋滋
line_comment
zh-cn
package com.knziha.plod.plaindict; import static com.knziha.plod.plaindict.CMN.hotDebugMessage; import static com.knziha.plod.plaindict.CMN.hotTracingObject; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Build; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.GlobalOptions; import com.knziha.plod.dictionary.Utils.SU; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; //美滋 <SUF> @SuppressLint({"WrongConstant"}) public class CrashHandler implements UncaughtExceptionHandler { public static final String TAG = "FatalHandler"; /** System default handler */ private UncaughtExceptionHandler mDefaultHandler; private static CrashHandler instance; //private Context mContext; private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, HH-mm-ss", Locale.CHINA); StringBuilder info_builder; private String log_path; private final boolean bSilentExitBypassingSystem; private final boolean bLogToFile; private boolean registered; private boolean turnedon; public static CrashHandler getInstance(Context contex, PDICMainAppOptions opt) { if(instance == null) instance = new CrashHandler(contex,opt); return instance; } public String getLogFile(){ return log_path; } private CrashHandler(Context contex, PDICMainAppOptions opt){ mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); bSilentExitBypassingSystem = true;//opt.getSilentExitBypassingSystem(); bLogToFile = opt.getLogToFile(); info_builder=new StringBuilder(); info_builder.setLength(0); info_builder.append(contex.getResources().getString(R.string.app_name)).append(" [").append(Build.MANUFACTURER) .append(", v").append(Build.VERSION.SDK_INT).append("_").append(Build.VERSION.CODENAME); } public void register(Context context) { if(registered) return; Thread.setDefaultUncaughtExceptionHandler(this); log_path=context.getExternalFilesDir("").getAbsolutePath()+"/logs/crash.txt"; PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); PackageInfo program_info=null; info_builder.append("] [v"); try { program_info = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES|PackageManager.GET_SIGNATURES); } catch (Exception e) { CMN.Log(e); } if (program_info != null) { info_builder.append(program_info.versionName).append(", ").append(program_info.versionCode); try{ Signature[] signatures = program_info.signatures; if(signatures!=null && signatures.length>0) { byte[] cert = signatures[0].toByteArray(); InputStream input = new ByteArrayInputStream(cert); byte[] publicKey = MessageDigest.getInstance("SHA1").digest(((X509Certificate)CertificateFactory.getInstance("X509").generateCertificate(input)).getEncoded()); // BU.printBytes(publicKey); // CMN.Log(111); // CMN.Log(new String(publicKey)); //todo ??? } } catch (Exception e){ CMN.Log(e); } } info_builder.append("]\n"); ApplicationInfo app_info = context.getApplicationInfo(); GlobalOptions.debug=SU.debug=(app_info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; registered=true; } public void unRegister(){ registered=false; if(mDefaultHandler!=null) Thread.setDefaultUncaughtExceptionHandler(mDefaultHandler); } public void TurnOn(){ turnedon=true; } public void TurnOff(){ turnedon=false; } @Override public void uncaughtException(@NonNull Thread thread, @NonNull Throwable exception) { Log.e("ODPlayer","::fatal exception : "+exception.toString()); Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); exception.printStackTrace(printWriter); Throwable cause = exception.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.close(); String result = writer.toString(); String time = formatter.format(new Date()); info_builder.append("crash-=====Log-start=====") .append(time).append("\n"); if(hotTracingObject!=null) info_builder.append("at : ").append(hotTracingObject).append("\n"); if(hotDebugMessage!=null) info_builder.append("at : ").append(hotDebugMessage).append("\n"); ; info_builder.append(result); String trace = null; if(bLogToFile || GlobalOptions.debug){ try { File log=new File(log_path); File dir = log.getParentFile(); dir.mkdirs(); if(log.isDirectory()) log.delete(); FileOutputStream fos = new FileOutputStream(log_path); trace = info_builder.toString(); fos.write(trace.getBytes()); fos.close(); new File(dir, "lock").mkdirs(); if (GlobalOptions.debug) { fos = new FileOutputStream(new File(new File(log_path).getParentFile(), "crash_"+CMN.now()+".log")); fos.write(trace.getBytes()); fos.close(); } } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } } CMN.Log("crash catched", GlobalOptions.debug?trace:"_"+exception); postUncaughtException(thread, exception); } private void postUncaughtException(@NonNull Thread thread, @NonNull Throwable exception) { if(!turnedon || !registered || !bSilentExitBypassingSystem){ if(mDefaultHandler != null) mDefaultHandler.uncaughtException(thread, exception); unRegister(); }else { unRegister(); System.exit(1); } } public void showErrorMessage(Context context, DialogInterface.OnClickListener btnLis, boolean simulated) { String message = null; String title = "天哪,崩溃了……"; if (simulated) { title = "[模拟] "+title; try{ throw new RuntimeException(title); } catch (Exception e) { message = CMN.Log(e); } } else { File log = new File(getLogFile()); if (log.exists()) { try { byte[] buffer = new byte[Math.min((int) log.length(), 4096)]; int len = new FileInputStream(log).read(buffer); message=new String(buffer,0,len); if(GlobalOptions.debug||btnLis==null) { CMN.Log(message); } } catch (IOException e) { CMN.Log(e); } } } if (message!=null) { String finalMessage = message; View btn = new AlertDialog.Builder(context) .setMessage(message) .setPositiveButton(android.R.string.yes, btnLis) .setNeutralButton(android.R.string.copy, null) .setTitle(title) .setCancelable(btnLis == null) .show() .findViewById(android.R.id.button3); btn.setOnClickListener(v -> { if (context instanceof Toastable_Activity) { ((Toastable_Activity) context).FuzhiText(finalMessage); } }); if (simulated) { String finalTitle = title; btn.setOnLongClickListener(v -> { throw new RuntimeException(finalTitle); }); } } } }
false
1,730
4
2,211
6
2,163
4
2,211
6
2,701
8
false
false
false
false
false
true
32513_10
package com.hspedu.list_; import java.util.ArrayList; import java.util.List; public class ListMethod { @SuppressWarnings({"all"}) public static void main(String[] args) { List list = new ArrayList(); list.add("张三丰"); list.add("贾宝玉"); // void add(int index, Object ele): 在index位置插入ele元素 //在index = 1的位置插入一个对象 list.add(1, "韩顺平"); System.out.println("list=" + list); // boolean addAll(int index, Collection else): 从index位置开始将else中所有元素添加进来 List list2 = new ArrayList(); list2.add("jack"); list2.add("tom"); list2.addAll(1, list2); System.out.println("list=" + list); // Object get(int index): 获取指定index位置的元素 //说过 // int index(Object obj):返回obj在集合中首次出现的位置 System.out.println(list.indexOf("tom")); //2 // int lastIndexOf(Object obj): 返回obj在当前集合中末次出现的位置 list.add("韩顺平"); System.out.println("list=" + list); System.out.println(list.lastIndexOf("韩顺平")); // Object remove(int index):移除指定index位置的元素,并返回此元素 list.remove(0); System.out.println("list=" + list); // Object set(int index, Object ele): 设置指定index位置的元素为ele,相当于替换, list.set(1, "玛丽"); System.out.println("list=" + list); // List subList(int fromIndex <= subList < toIndex): 返回从fromIndex到toIndex位置的字集合 // 注意返回的子集合 fromIdex <= subList < toIndex List returnlist = list.subList(0, 2); //左闭右开 //[ ); System.out.println("returnlist=" + returnlist); } }
Kobayashichannel/Kobayashi.github.io
chapter14/src/com/hspedu/list_/ListMethod.java
495
//左闭右开 //[ );
line_comment
zh-cn
package com.hspedu.list_; import java.util.ArrayList; import java.util.List; public class ListMethod { @SuppressWarnings({"all"}) public static void main(String[] args) { List list = new ArrayList(); list.add("张三丰"); list.add("贾宝玉"); // void add(int index, Object ele): 在index位置插入ele元素 //在index = 1的位置插入一个对象 list.add(1, "韩顺平"); System.out.println("list=" + list); // boolean addAll(int index, Collection else): 从index位置开始将else中所有元素添加进来 List list2 = new ArrayList(); list2.add("jack"); list2.add("tom"); list2.addAll(1, list2); System.out.println("list=" + list); // Object get(int index): 获取指定index位置的元素 //说过 // int index(Object obj):返回obj在集合中首次出现的位置 System.out.println(list.indexOf("tom")); //2 // int lastIndexOf(Object obj): 返回obj在当前集合中末次出现的位置 list.add("韩顺平"); System.out.println("list=" + list); System.out.println(list.lastIndexOf("韩顺平")); // Object remove(int index):移除指定index位置的元素,并返回此元素 list.remove(0); System.out.println("list=" + list); // Object set(int index, Object ele): 设置指定index位置的元素为ele,相当于替换, list.set(1, "玛丽"); System.out.println("list=" + list); // List subList(int fromIndex <= subList < toIndex): 返回从fromIndex到toIndex位置的字集合 // 注意返回的子集合 fromIdex <= subList < toIndex List returnlist = list.subList(0, 2); //左闭 <SUF> System.out.println("returnlist=" + returnlist); } }
false
428
8
495
9
501
8
495
9
601
11
false
false
false
false
false
true
31189_0
import junit.framework.TestCase; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class DATrieTest extends TestCase { public void testDATrie() { //定义词典 List<String> words = new ArrayList<String>(); words.add("清华"); words.add("清华大学"); words.add("清新"); words.add("中华"); words.add("中华人民"); words.add("华人"); words.add("学生"); words.add("大学生"); words.add("qin"); words.add("shi"); words.add("ming"); words.add("yue"); words.add("zhi"); words.add("jun"); words.add("lin"); words.add("tian"); words.add("xia"); words.add("中国"); words.add("人名"); words.add("中国人民"); words.add("人民"); words.add("孙健"); words.add("CSDN"); words.add("java"); words.add("java学习"); //制作码表,以备验证 Set<Character> codes = new HashSet<Character>(); for (String word : words) { char chars[] = word.toCharArray(); for (int i = 0; i < chars.length; i++) { codes.add(chars[i]); } } for (Character character : codes) { System.out.printf("%6s\t", character.charValue()); } System.out.println(); for (Character character : codes) { System.out.printf("%6d\t", (int)character.charValue()); } System.out.println(); //构建 Trie 树 DATrie daTrie = new DATrie(); daTrie.build(words); daTrie.printTrie(); //执行匹配 // List<Integer> result = daTrie.match("清华大学生都是华人"); // List<Integer> result = daTrie.match("中国人名识别是中国人民的一个骄傲.孙健人民在CSDN中学到了很多最早iteye是java学习笔记叫javaeye但是java123只是一部分"); List<Integer> result = daTrie.match("qinshimingyuezhijunlintianxia"); //打印匹配结果 System.out.println(); System.out.printf("Match: {"); for (int i = 0; i < result.size(); i++) { if (i == 0) { System.out.printf("%s", words.get(result.get(i))); } else { System.out.printf(", %s", words.get(result.get(i))); } } System.out.printf("}"); System.out.println(); } }
Kooooooma/DoubleArrayTrie
src/main/java/DATrieTest.java
687
//定义词典
line_comment
zh-cn
import junit.framework.TestCase; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class DATrieTest extends TestCase { public void testDATrie() { //定义 <SUF> List<String> words = new ArrayList<String>(); words.add("清华"); words.add("清华大学"); words.add("清新"); words.add("中华"); words.add("中华人民"); words.add("华人"); words.add("学生"); words.add("大学生"); words.add("qin"); words.add("shi"); words.add("ming"); words.add("yue"); words.add("zhi"); words.add("jun"); words.add("lin"); words.add("tian"); words.add("xia"); words.add("中国"); words.add("人名"); words.add("中国人民"); words.add("人民"); words.add("孙健"); words.add("CSDN"); words.add("java"); words.add("java学习"); //制作码表,以备验证 Set<Character> codes = new HashSet<Character>(); for (String word : words) { char chars[] = word.toCharArray(); for (int i = 0; i < chars.length; i++) { codes.add(chars[i]); } } for (Character character : codes) { System.out.printf("%6s\t", character.charValue()); } System.out.println(); for (Character character : codes) { System.out.printf("%6d\t", (int)character.charValue()); } System.out.println(); //构建 Trie 树 DATrie daTrie = new DATrie(); daTrie.build(words); daTrie.printTrie(); //执行匹配 // List<Integer> result = daTrie.match("清华大学生都是华人"); // List<Integer> result = daTrie.match("中国人名识别是中国人民的一个骄傲.孙健人民在CSDN中学到了很多最早iteye是java学习笔记叫javaeye但是java123只是一部分"); List<Integer> result = daTrie.match("qinshimingyuezhijunlintianxia"); //打印匹配结果 System.out.println(); System.out.printf("Match: {"); for (int i = 0; i < result.size(); i++) { if (i == 0) { System.out.printf("%s", words.get(result.get(i))); } else { System.out.printf(", %s", words.get(result.get(i))); } } System.out.printf("}"); System.out.println(); } }
false
565
4
687
4
707
4
687
4
837
7
false
false
false
false
false
true
13206_13
package org.minions.common.model.kafka; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; /** * <p> * 英雄信息 * </p> * * @author korov * @since 2021-09-07 */ @Data public class HeroInfos implements Serializable { private static final long serialVersionUID = 1L; /** * 英雄id */ @TableId private Integer heroId; /** * 英雄名称 */ private String heroName; /** * 英雄昵称 */ private String heroNickname; /** * 图片 */ private String heroImg; /** * 类型 */ private String heroType; /** * 故事 */ private String heroStory; /** * 难度 */ private String heroLevels; /** * 金币价格 */ private BigDecimal heroGoldPrice; /** * 点券价格 */ private BigDecimal heroTicketPrice; /** * 钻石价格 */ private BigDecimal heroDiamondPrice; /** * 推荐生存技能 */ private String recommendSummonerSkill; /** * 推荐铭文 */ private String recInscriptions; /** * 皮肤图片 */ private String skinImgs; /** * 大图 */ private String bigImg; /** * 历史介绍 */ private String historyIntro; /** * 技能提示 */ private String skillTips; /** * 推荐技能升级 */ private String recommendSummonerSkillTips; /** * 英雄提示 */ private String heroTips; /** * 生存提示 */ private String meleeTips; /** * 技能 */ private String skillList; /** * 装备介绍 */ private String equipChoice; /** * 关联英雄 */ private String partnerHero; /** * 克制英雄 */ private String beRestrainedHero; public static final String HERO_ID = "hero_id"; public static final String HERO_NAME = "hero_name"; public static final String HERO_NICKNAME = "hero_nickname"; public static final String HERO_IMG = "hero_img"; public static final String HERO_TYPE = "hero_type"; public static final String HERO_STORY = "hero_story"; public static final String HERO_LEVELS = "hero_levels"; public static final String HERO_GOLD_PRICE = "hero_gold_price"; public static final String HERO_TICKET_PRICE = "hero_ticket_price"; public static final String HERO_DIAMOND_PRICE = "hero_diamond_price"; public static final String RECOMMEND_SUMMONER_SKILL = "recommend_summoner_skill"; public static final String REC_INSCRIPTIONS = "rec_inscriptions"; public static final String SKIN_IMGS = "skin_imgs"; public static final String BIG_IMG = "big_img"; public static final String HISTORY_INTRO = "history_intro"; public static final String SKILL_TIPS = "skill_tips"; public static final String RECOMMEND_SUMMONER_SKILL_TIPS = "recommend_summoner_skill_tips"; public static final String HERO_TIPS = "hero_tips"; public static final String MELEE_TIPS = "melee_tips"; public static final String SKILL_LIST = "skill_list"; public static final String EQUIP_CHOICE = "equip_choice"; public static final String PARTNER_HERO = "partner_hero"; public static final String BE_RESTRAINED_HERO = "be_restrained_hero"; }
Korov/minions
common/src/main/java/org/minions/common/model/kafka/HeroInfos.java
932
/** * 皮肤图片 */
block_comment
zh-cn
package org.minions.common.model.kafka; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; /** * <p> * 英雄信息 * </p> * * @author korov * @since 2021-09-07 */ @Data public class HeroInfos implements Serializable { private static final long serialVersionUID = 1L; /** * 英雄id */ @TableId private Integer heroId; /** * 英雄名称 */ private String heroName; /** * 英雄昵称 */ private String heroNickname; /** * 图片 */ private String heroImg; /** * 类型 */ private String heroType; /** * 故事 */ private String heroStory; /** * 难度 */ private String heroLevels; /** * 金币价格 */ private BigDecimal heroGoldPrice; /** * 点券价格 */ private BigDecimal heroTicketPrice; /** * 钻石价格 */ private BigDecimal heroDiamondPrice; /** * 推荐生存技能 */ private String recommendSummonerSkill; /** * 推荐铭文 */ private String recInscriptions; /** * 皮肤图 <SUF>*/ private String skinImgs; /** * 大图 */ private String bigImg; /** * 历史介绍 */ private String historyIntro; /** * 技能提示 */ private String skillTips; /** * 推荐技能升级 */ private String recommendSummonerSkillTips; /** * 英雄提示 */ private String heroTips; /** * 生存提示 */ private String meleeTips; /** * 技能 */ private String skillList; /** * 装备介绍 */ private String equipChoice; /** * 关联英雄 */ private String partnerHero; /** * 克制英雄 */ private String beRestrainedHero; public static final String HERO_ID = "hero_id"; public static final String HERO_NAME = "hero_name"; public static final String HERO_NICKNAME = "hero_nickname"; public static final String HERO_IMG = "hero_img"; public static final String HERO_TYPE = "hero_type"; public static final String HERO_STORY = "hero_story"; public static final String HERO_LEVELS = "hero_levels"; public static final String HERO_GOLD_PRICE = "hero_gold_price"; public static final String HERO_TICKET_PRICE = "hero_ticket_price"; public static final String HERO_DIAMOND_PRICE = "hero_diamond_price"; public static final String RECOMMEND_SUMMONER_SKILL = "recommend_summoner_skill"; public static final String REC_INSCRIPTIONS = "rec_inscriptions"; public static final String SKIN_IMGS = "skin_imgs"; public static final String BIG_IMG = "big_img"; public static final String HISTORY_INTRO = "history_intro"; public static final String SKILL_TIPS = "skill_tips"; public static final String RECOMMEND_SUMMONER_SKILL_TIPS = "recommend_summoner_skill_tips"; public static final String HERO_TIPS = "hero_tips"; public static final String MELEE_TIPS = "melee_tips"; public static final String SKILL_LIST = "skill_list"; public static final String EQUIP_CHOICE = "equip_choice"; public static final String PARTNER_HERO = "partner_hero"; public static final String BE_RESTRAINED_HERO = "be_restrained_hero"; }
false
833
9
927
11
946
9
927
11
1,247
16
false
false
false
false
false
true
41466_14
package com.extrace.ui.main; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.extrace.net.OkHttpClientManager; import com.extrace.ui.R; import com.extrace.ui.entity.History; import com.extrace.ui.service.HistoryOperator; import com.extrace.ui.service.LoginService; import com.extrace.util.CustomCaptureActivity; import com.extrace.util.TitleLayout; import com.king.zxing.Intents; import com.squareup.okhttp.Request; import java.text.SimpleDateFormat; import java.util.Date; import static com.extrace.net.OkHttpClientManager.BASE_URL; public class ScanBarcodeActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "ScanBarcodeActivity"; public static final String KEY_TITLE = "key_title"; public static final String KEY_CODE = "key_code"; public static final String KEY_IS_QR_CODE = "key_code"; public static final String KEY_IS_CONTINUOUS = "key_continuous_scan"; public static final int REQUEST_CODE_SCAN_RECEIVE = 0X101; public static final int REQUEST_CODE_SCAN_SEND = 0X102; public static final int REQUEST_CODE_SCAN_SEND_UPLOAD = 0X106; //装货扫描 public static final int REQUEST_CODE_SCAN_ARRIVE = 0X103; public static final int REQUEST_CODE_SCAN_DISPATCH = 0X104; public static final int REQUEST_CODE_SCAN_SIGN = 0X105; public static final int REQUEST_CODE_PHOTO = 0X02; public static final int RC_CAMERA = 0X01; public static final int RC_READ_PHOTO = 0X02; private static final int REQUEST_CODE = 111; private LoginService loginService = new LoginService(); private LinearLayout menu_1,menu_2,menu_3,menu_4, menu_5,menu_6, menu_7, menu_8; private TextView tv_courier_name,tv_tel,tv_site,tv_courier_name_tag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_barcode); ActionBar actionBar = getSupportActionBar(); if (actionBar != null){ //隐藏自带的标题栏 actionBar.hide(); } TitleLayout titleLayout ; titleLayout = findViewById(R.id.title); titleLayout.setTitle(getResources().getString(R.string.scan_gun)); titleLayout.hideTitleEdit(); menu_1 = findViewById(R.id.ly_function1); menu_2 = findViewById(R.id.ly_function2); menu_3 = findViewById(R.id.ly_function3); menu_4 = findViewById(R.id.ly_function4); menu_5 = findViewById(R.id.ly_function5); menu_6 = findViewById(R.id.ly_function6); menu_7 = findViewById(R.id.ly_function7); menu_8 = findViewById(R.id.ly_function8); tv_courier_name = findViewById(R.id.tv_courier_name); tv_courier_name_tag = findViewById(R.id.tv_courier_name_tag); tv_tel = findViewById(R.id.tv_tel); tv_site = findViewById(R.id.tv_site); bindView(); } private void bindView() { menu_1.setOnClickListener(this); menu_2.setOnClickListener(this); menu_3.setOnClickListener(this); menu_4.setOnClickListener(this); menu_5.setOnClickListener(this); menu_6.setOnClickListener(this); menu_7.setOnClickListener(this); menu_8.setOnClickListener(this); //显示用户此前录入的数据 SharedPreferences sPreferences = getSharedPreferences("USER_INFO", MODE_PRIVATE); if (loginService.isLogined(this)) { String username = sPreferences.getString("username", ""); String tel = sPreferences.getString("telcode", ""); String dptid = sPreferences.getString("dptid", ""); String userRole = loginService.getUserRoll(this) == 1 ? "司 机":"快递员"; tv_courier_name_tag.setText(userRole); tv_courier_name.setText(username); tv_tel.setText(tel); tv_site.setText(dptid); }else { Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show(); finish(); } } private Class<?> cls; private String title; private boolean isContinuousScan; //是否连续扫码 @Override public void onClick(View v) { switch (v.getId()){ case R.id.ly_function1: this.cls = CustomCaptureActivity.class; this.title = "收件扫描"; startScan(cls,title,REQUEST_CODE_SCAN_RECEIVE); break; case R.id.ly_function2: this.cls = CustomCaptureActivity.class; this.title = "包裹打包"; isContinuousScan =false; startScan(cls,title,REQUEST_CODE_SCAN_SEND); break; case R.id.ly_function3: this.cls = CustomCaptureActivity.class; this.title = "装货上车"; isContinuousScan =true; startScan(cls,title,REQUEST_CODE_SCAN_SEND_UPLOAD); break; case R.id.ly_function4: this.cls = CustomCaptureActivity.class; this.title = "包裹拆包| 到件扫描"; isContinuousScan = true; startScan(cls,title,REQUEST_CODE_SCAN_ARRIVE); break; case R.id.ly_function5: this.cls = CustomCaptureActivity.class; this.title = "派件扫描"; isContinuousScan = true; startScan(cls,title,REQUEST_CODE_SCAN_DISPATCH); break; case R.id.ly_function6: this.cls = CustomCaptureActivity.class; this.title = "签收扫描"; isContinuousScan = true; startScan(cls,title,REQUEST_CODE_SCAN_SIGN); //Toast.makeText(this, "签收扫描", Toast.LENGTH_SHORT).show(); break; case R.id.ly_function7: Toast.makeText(this, "扫描记录~", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(ScanBarcodeActivity.this, HistoryScanActivity.class); intent.putExtra("Insert", 1); startActivity(intent); break; case R.id.ly_function8: Toast.makeText(this, "创建包裹", Toast.LENGTH_SHORT).show(); Intent intent0 = new Intent(); intent0.setClass(ScanBarcodeActivity.this, AddPackageActivity.class); startActivity(intent0); break; } } /** * 扫码 * @param cls * @param title */ private void startScan(Class<?> cls,String title, int code){ ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeCustomAnimation(this,R.anim.in,R.anim.out); Intent intent = new Intent(this, cls); intent.putExtra(KEY_TITLE,title); intent.putExtra(KEY_CODE,code); intent.putExtra(KEY_IS_CONTINUOUS,isContinuousScan); ActivityCompat.startActivityForResult(this,intent,code,optionsCompat.toBundle()); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String result = ""; String msg =""; Intent intent; if(resultCode == RESULT_OK && data!=null){ switch (requestCode){ case REQUEST_CODE_SCAN_RECEIVE: //收件扫描结果 msg = "收件扫描"; result = data.getStringExtra(Intents.Scan.RESULT); //Toast.makeText(this,"扫描到了:"+result,Toast.LENGTH_SHORT).show(); intent = new Intent(ScanBarcodeActivity.this, ExpressEditActivity.class); intent.putExtra("EXPRESS_ID",result); startActivity(intent); break; case REQUEST_CODE_SCAN_SEND: //发件扫描结果 msg = "包裹打包扫描"; result = data.getStringExtra(Intents.Scan.RESULT); Toast.makeText(this,"扫jhhhh描到了:"+result+REQUEST_CODE_SCAN_SEND,Toast.LENGTH_SHORT).show(); queryPackage(result); // intent = new Intent(ScanBarcodeActivity.this, SendExpressActivity.class); // intent.putExtra("EXPRESS_ID",result); // startActivity(intent); break; case REQUEST_CODE_SCAN_SEND_UPLOAD: msg = "装货扫描"; break; case REQUEST_CODE_SCAN_ARRIVE: //到件扫描结果 msg ="包裹拆包、到件扫描"; result = data.getStringExtra(Intents.Scan.RESULT); Toast.makeText(this,"扫描到了:"+result+REQUEST_CODE_SCAN_ARRIVE,Toast.LENGTH_SHORT).show(); break; case REQUEST_CODE_SCAN_DISPATCH: //派送扫描结果 msg = "派件扫描"; result = data.getStringExtra(Intents.Scan.RESULT); Toast.makeText(this,"扫描到了:"+result+REQUEST_CODE_SCAN_DISPATCH,Toast.LENGTH_SHORT).show(); break; case REQUEST_CODE_SCAN_SIGN: //签收扫描 msg = "签收扫描"; break; case REQUEST_CODE_PHOTO: //parsePhoto(data); break; default: break; } HistoryOperator historyOperator = new HistoryOperator(ScanBarcodeActivity.this); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss //获取当前时间 Date date = new Date(System.currentTimeMillis()); History history = new History(); history.expressId = result; history.context = "扫描方式:"+msg;//String.valueOf(requestCode); history.time = simpleDateFormat.format(date); boolean add = historyOperator.insert(history); // if (add){ // Toast.makeText(this, "记录已同步", Toast.LENGTH_SHORT).show(); // }else { // Toast.makeText(this, "扫描记录添加失败", Toast.LENGTH_SHORT).show(); // } } } // //返回页面 // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // this.finish(); // return true; // } // return super.onOptionsItemSelected(item); // } //包裹打包 REQUEST_CODE_SCAN_SEND private boolean queryPackage(final String string){ //Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); Log.d(TAG, "queryPackage: "+string); OkHttpClientManager okHttpClientManager = new OkHttpClientManager(new LoginService().userInfoSha256(this)); okHttpClientManager.getAsyn(BASE_URL +"/ExtraceSystem/queryPackage/"+string, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { //Toast.makeText(getApplicationContext(), "出错了", Toast.LENGTH_SHORT).show(); AlertDialog.Builder builder = new AlertDialog.Builder(ScanBarcodeActivity.this); builder.setTitle("扫描失败" ) ; builder.setMessage("请检查网络环境!" ) ; builder.setPositiveButton("是" , null ); builder.show(); } @Override public void onResponse(String response) { //Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(getApplicationContext(), SendExpressActivity.class); intent.putExtra("response", response); Log.e("lalal_CustomCapture",response); if ("".equals(response)){ AlertDialog.Builder builder = new AlertDialog.Builder(ScanBarcodeActivity.this); builder.setTitle("扫描失败" ) ; builder.setMessage("处理失败,该单号不存在!" ) ; builder.setPositiveButton("是" , null ); builder.show(); //restartPreviewAndDecode(); }else { Log.e(TAG, "onResponse: "+response ); startActivity(intent); finish(); } } }); return false; } }
Kris-Fan/ExpressTrace
app/src/main/java/com/extrace/ui/main/ScanBarcodeActivity.java
3,136
//签收扫描
line_comment
zh-cn
package com.extrace.ui.main; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.extrace.net.OkHttpClientManager; import com.extrace.ui.R; import com.extrace.ui.entity.History; import com.extrace.ui.service.HistoryOperator; import com.extrace.ui.service.LoginService; import com.extrace.util.CustomCaptureActivity; import com.extrace.util.TitleLayout; import com.king.zxing.Intents; import com.squareup.okhttp.Request; import java.text.SimpleDateFormat; import java.util.Date; import static com.extrace.net.OkHttpClientManager.BASE_URL; public class ScanBarcodeActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "ScanBarcodeActivity"; public static final String KEY_TITLE = "key_title"; public static final String KEY_CODE = "key_code"; public static final String KEY_IS_QR_CODE = "key_code"; public static final String KEY_IS_CONTINUOUS = "key_continuous_scan"; public static final int REQUEST_CODE_SCAN_RECEIVE = 0X101; public static final int REQUEST_CODE_SCAN_SEND = 0X102; public static final int REQUEST_CODE_SCAN_SEND_UPLOAD = 0X106; //装货扫描 public static final int REQUEST_CODE_SCAN_ARRIVE = 0X103; public static final int REQUEST_CODE_SCAN_DISPATCH = 0X104; public static final int REQUEST_CODE_SCAN_SIGN = 0X105; public static final int REQUEST_CODE_PHOTO = 0X02; public static final int RC_CAMERA = 0X01; public static final int RC_READ_PHOTO = 0X02; private static final int REQUEST_CODE = 111; private LoginService loginService = new LoginService(); private LinearLayout menu_1,menu_2,menu_3,menu_4, menu_5,menu_6, menu_7, menu_8; private TextView tv_courier_name,tv_tel,tv_site,tv_courier_name_tag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_barcode); ActionBar actionBar = getSupportActionBar(); if (actionBar != null){ //隐藏自带的标题栏 actionBar.hide(); } TitleLayout titleLayout ; titleLayout = findViewById(R.id.title); titleLayout.setTitle(getResources().getString(R.string.scan_gun)); titleLayout.hideTitleEdit(); menu_1 = findViewById(R.id.ly_function1); menu_2 = findViewById(R.id.ly_function2); menu_3 = findViewById(R.id.ly_function3); menu_4 = findViewById(R.id.ly_function4); menu_5 = findViewById(R.id.ly_function5); menu_6 = findViewById(R.id.ly_function6); menu_7 = findViewById(R.id.ly_function7); menu_8 = findViewById(R.id.ly_function8); tv_courier_name = findViewById(R.id.tv_courier_name); tv_courier_name_tag = findViewById(R.id.tv_courier_name_tag); tv_tel = findViewById(R.id.tv_tel); tv_site = findViewById(R.id.tv_site); bindView(); } private void bindView() { menu_1.setOnClickListener(this); menu_2.setOnClickListener(this); menu_3.setOnClickListener(this); menu_4.setOnClickListener(this); menu_5.setOnClickListener(this); menu_6.setOnClickListener(this); menu_7.setOnClickListener(this); menu_8.setOnClickListener(this); //显示用户此前录入的数据 SharedPreferences sPreferences = getSharedPreferences("USER_INFO", MODE_PRIVATE); if (loginService.isLogined(this)) { String username = sPreferences.getString("username", ""); String tel = sPreferences.getString("telcode", ""); String dptid = sPreferences.getString("dptid", ""); String userRole = loginService.getUserRoll(this) == 1 ? "司 机":"快递员"; tv_courier_name_tag.setText(userRole); tv_courier_name.setText(username); tv_tel.setText(tel); tv_site.setText(dptid); }else { Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show(); finish(); } } private Class<?> cls; private String title; private boolean isContinuousScan; //是否连续扫码 @Override public void onClick(View v) { switch (v.getId()){ case R.id.ly_function1: this.cls = CustomCaptureActivity.class; this.title = "收件扫描"; startScan(cls,title,REQUEST_CODE_SCAN_RECEIVE); break; case R.id.ly_function2: this.cls = CustomCaptureActivity.class; this.title = "包裹打包"; isContinuousScan =false; startScan(cls,title,REQUEST_CODE_SCAN_SEND); break; case R.id.ly_function3: this.cls = CustomCaptureActivity.class; this.title = "装货上车"; isContinuousScan =true; startScan(cls,title,REQUEST_CODE_SCAN_SEND_UPLOAD); break; case R.id.ly_function4: this.cls = CustomCaptureActivity.class; this.title = "包裹拆包| 到件扫描"; isContinuousScan = true; startScan(cls,title,REQUEST_CODE_SCAN_ARRIVE); break; case R.id.ly_function5: this.cls = CustomCaptureActivity.class; this.title = "派件扫描"; isContinuousScan = true; startScan(cls,title,REQUEST_CODE_SCAN_DISPATCH); break; case R.id.ly_function6: this.cls = CustomCaptureActivity.class; this.title = "签收扫描"; isContinuousScan = true; startScan(cls,title,REQUEST_CODE_SCAN_SIGN); //Toast.makeText(this, "签收扫描", Toast.LENGTH_SHORT).show(); break; case R.id.ly_function7: Toast.makeText(this, "扫描记录~", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(ScanBarcodeActivity.this, HistoryScanActivity.class); intent.putExtra("Insert", 1); startActivity(intent); break; case R.id.ly_function8: Toast.makeText(this, "创建包裹", Toast.LENGTH_SHORT).show(); Intent intent0 = new Intent(); intent0.setClass(ScanBarcodeActivity.this, AddPackageActivity.class); startActivity(intent0); break; } } /** * 扫码 * @param cls * @param title */ private void startScan(Class<?> cls,String title, int code){ ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeCustomAnimation(this,R.anim.in,R.anim.out); Intent intent = new Intent(this, cls); intent.putExtra(KEY_TITLE,title); intent.putExtra(KEY_CODE,code); intent.putExtra(KEY_IS_CONTINUOUS,isContinuousScan); ActivityCompat.startActivityForResult(this,intent,code,optionsCompat.toBundle()); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String result = ""; String msg =""; Intent intent; if(resultCode == RESULT_OK && data!=null){ switch (requestCode){ case REQUEST_CODE_SCAN_RECEIVE: //收件扫描结果 msg = "收件扫描"; result = data.getStringExtra(Intents.Scan.RESULT); //Toast.makeText(this,"扫描到了:"+result,Toast.LENGTH_SHORT).show(); intent = new Intent(ScanBarcodeActivity.this, ExpressEditActivity.class); intent.putExtra("EXPRESS_ID",result); startActivity(intent); break; case REQUEST_CODE_SCAN_SEND: //发件扫描结果 msg = "包裹打包扫描"; result = data.getStringExtra(Intents.Scan.RESULT); Toast.makeText(this,"扫jhhhh描到了:"+result+REQUEST_CODE_SCAN_SEND,Toast.LENGTH_SHORT).show(); queryPackage(result); // intent = new Intent(ScanBarcodeActivity.this, SendExpressActivity.class); // intent.putExtra("EXPRESS_ID",result); // startActivity(intent); break; case REQUEST_CODE_SCAN_SEND_UPLOAD: msg = "装货扫描"; break; case REQUEST_CODE_SCAN_ARRIVE: //到件扫描结果 msg ="包裹拆包、到件扫描"; result = data.getStringExtra(Intents.Scan.RESULT); Toast.makeText(this,"扫描到了:"+result+REQUEST_CODE_SCAN_ARRIVE,Toast.LENGTH_SHORT).show(); break; case REQUEST_CODE_SCAN_DISPATCH: //派送扫描结果 msg = "派件扫描"; result = data.getStringExtra(Intents.Scan.RESULT); Toast.makeText(this,"扫描到了:"+result+REQUEST_CODE_SCAN_DISPATCH,Toast.LENGTH_SHORT).show(); break; case REQUEST_CODE_SCAN_SIGN: //签收 <SUF> msg = "签收扫描"; break; case REQUEST_CODE_PHOTO: //parsePhoto(data); break; default: break; } HistoryOperator historyOperator = new HistoryOperator(ScanBarcodeActivity.this); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss //获取当前时间 Date date = new Date(System.currentTimeMillis()); History history = new History(); history.expressId = result; history.context = "扫描方式:"+msg;//String.valueOf(requestCode); history.time = simpleDateFormat.format(date); boolean add = historyOperator.insert(history); // if (add){ // Toast.makeText(this, "记录已同步", Toast.LENGTH_SHORT).show(); // }else { // Toast.makeText(this, "扫描记录添加失败", Toast.LENGTH_SHORT).show(); // } } } // //返回页面 // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // this.finish(); // return true; // } // return super.onOptionsItemSelected(item); // } //包裹打包 REQUEST_CODE_SCAN_SEND private boolean queryPackage(final String string){ //Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); Log.d(TAG, "queryPackage: "+string); OkHttpClientManager okHttpClientManager = new OkHttpClientManager(new LoginService().userInfoSha256(this)); okHttpClientManager.getAsyn(BASE_URL +"/ExtraceSystem/queryPackage/"+string, new OkHttpClientManager.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { //Toast.makeText(getApplicationContext(), "出错了", Toast.LENGTH_SHORT).show(); AlertDialog.Builder builder = new AlertDialog.Builder(ScanBarcodeActivity.this); builder.setTitle("扫描失败" ) ; builder.setMessage("请检查网络环境!" ) ; builder.setPositiveButton("是" , null ); builder.show(); } @Override public void onResponse(String response) { //Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(getApplicationContext(), SendExpressActivity.class); intent.putExtra("response", response); Log.e("lalal_CustomCapture",response); if ("".equals(response)){ AlertDialog.Builder builder = new AlertDialog.Builder(ScanBarcodeActivity.this); builder.setTitle("扫描失败" ) ; builder.setMessage("处理失败,该单号不存在!" ) ; builder.setPositiveButton("是" , null ); builder.show(); //restartPreviewAndDecode(); }else { Log.e(TAG, "onResponse: "+response ); startActivity(intent); finish(); } } }); return false; } }
false
2,518
4
3,136
4
3,293
4
3,136
4
3,916
11
false
false
false
false
false
true
58901_1
package com.ksc.cdn.model.statistic.billing; import com.ksc.cdn.KscClientException; import com.ksc.cdn.model.GeneralRequestParam; import com.ksc.cdn.model.statistic.CommonFieldRequest; import com.ksc.cdn.model.valid.CommonValidUtil; import org.apache.commons.lang3.StringUtils; import java.text.ParseException; import java.util.Map; /** * Created by JIANGYANG1 on 2017/3/21. */ public class BillingRequest extends CommonFieldRequest { /** * 区域名称, 取值为CN:中国大陆,HK:香港,TW:台湾,AS:亚洲其他,NA:北美洲,SA:南美洲,EU:欧洲,AU:大洋洲,AF:非洲,支持多区域查询,多个区域用逗号(半角)分隔,每个区域的值单独返回,缺省为 CN */ private String regions; /** * 计费方式, 取值为 peakbw:峰值计费;peak95bw:95峰值计费;averagebw:日峰值平均值计费;monthflow:流量按月,只允许输入一种计费方式,缺省为 peakbw ; */ private String billingMode; @Override public Map<String, String> buildParams() throws KscClientException, ParseException { CommonValidUtil.check(this); Map params = super.buildParams(); if (StringUtils.isNotBlank(this.getRegions())) { params.put("Regions", this.getRegions()); } if (StringUtils.isNotBlank(this.getBillingMode())) { params.put("BillingMode", this.getBillingMode()); } return params; } @Override public GeneralRequestParam getGeneralRequestParam() { return new GeneralRequestParam("GetBillingData", "2016-09-01", "/2016-09-01/statistics/GetBillingData"); } public String getRegions() { return regions; } public void setRegions(String regions) { this.regions = regions; } public String getBillingMode() { return billingMode; } public void setBillingMode(String billingMode) { this.billingMode = billingMode; } }
KscSDK/ksc-sdk-java
ksc-sdk-java-cdn/src/main/java/com/ksc/cdn/model/statistic/billing/BillingRequest.java
555
/** * 区域名称, 取值为CN:中国大陆,HK:香港,TW:台湾,AS:亚洲其他,NA:北美洲,SA:南美洲,EU:欧洲,AU:大洋洲,AF:非洲,支持多区域查询,多个区域用逗号(半角)分隔,每个区域的值单独返回,缺省为 CN */
block_comment
zh-cn
package com.ksc.cdn.model.statistic.billing; import com.ksc.cdn.KscClientException; import com.ksc.cdn.model.GeneralRequestParam; import com.ksc.cdn.model.statistic.CommonFieldRequest; import com.ksc.cdn.model.valid.CommonValidUtil; import org.apache.commons.lang3.StringUtils; import java.text.ParseException; import java.util.Map; /** * Created by JIANGYANG1 on 2017/3/21. */ public class BillingRequest extends CommonFieldRequest { /** * 区域名 <SUF>*/ private String regions; /** * 计费方式, 取值为 peakbw:峰值计费;peak95bw:95峰值计费;averagebw:日峰值平均值计费;monthflow:流量按月,只允许输入一种计费方式,缺省为 peakbw ; */ private String billingMode; @Override public Map<String, String> buildParams() throws KscClientException, ParseException { CommonValidUtil.check(this); Map params = super.buildParams(); if (StringUtils.isNotBlank(this.getRegions())) { params.put("Regions", this.getRegions()); } if (StringUtils.isNotBlank(this.getBillingMode())) { params.put("BillingMode", this.getBillingMode()); } return params; } @Override public GeneralRequestParam getGeneralRequestParam() { return new GeneralRequestParam("GetBillingData", "2016-09-01", "/2016-09-01/statistics/GetBillingData"); } public String getRegions() { return regions; } public void setRegions(String regions) { this.regions = regions; } public String getBillingMode() { return billingMode; } public void setBillingMode(String billingMode) { this.billingMode = billingMode; } }
false
482
83
555
100
563
82
555
100
711
137
false
false
false
false
false
true
32458_50
package top.kuangcp.graduate.config; /** * Created by https://github.com/kuangcp * TODO 全局异常对于JWT的使用是无效的, 怀疑就是整体和SpringMVC体系不契合,异常根本没经过这个全局异常 * @author kuangcp * @date 18-4-25 下午5:42 */ //@ControllerAdvice //public class GlobalExceptionHandler { // @ExceptionHandler(value = Exception.class) // @ResponseBody //// @ResponseStatus(value = HttpStatus.NOT_FOUND) // public String notFoundHandler(HttpServletRequest request, Exception e) { // return JsonBuilder.buildResult(1, "404", " "); // } // // //// @ExceptionHandler(value = RuntimeException.class) ////// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) //// public String internalServerErrorHandler(HttpServletRequest request, Exception e) { //// return JsonBuilder.buildResult(1, "500", " "); //// } //} //@EnableWebMvc //@RestControllerAdvice //public class GlobalExceptionHandler { // // @ExceptionHandler(value = { NoHandlerFoundException.class }) // @ResponseStatus(HttpStatus.NOT_FOUND) // public String noHandlerFoundException(Exception ex) { // // return JsonBuilder.buildResult(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase(), " "); //// return RespUtil.make(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase()); // } // // @ExceptionHandler(value = { ConstraintViolationException.class }) // @ResponseStatus(HttpStatus.BAD_REQUEST) // public String constraintViolationException(ConstraintViolationException ex) { // // return JsonBuilder.buildResult(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), " "); //// return RespUtil.make(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()); // } // // @ExceptionHandler(value = Exception.class) // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // public String defaultErrorHandler(HttpServletRequest request, Exception exception) throws Exception { // System.out.println("5 00 "); // return JsonBuilder.buildResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), " "); //// return RespUtil.make(HttpStatus.INTERNAL_SERVER_ERROR.value(), //// HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()); // } // //} //@ControllerAdvice //public class GlobalExceptionHandler { // // private Logger log = LoggerFactory.getLogger(this.getClass()); // // /** // * 拦截业务异常 // * // * @author fengshuonan // */ // @ExceptionHandler(Exception.class) // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // @ResponseBody // public String notFount(Exception e) { // log.error("业务异常:", e); // // return JsonBuilder.buildResult(500, " ", " "); // } // SignatureException // /** // * 用户未登录 // */ // @ExceptionHandler(AuthenticationException.class) // @ResponseStatus(HttpStatus.UNAUTHORIZED) // public String unAuth(AuthenticationException e) { // log.error("用户未登陆:", e); // return "/login.html"; // } // // // /** // * 拦截未知的运行时异常 // */ // @ExceptionHandler(RuntimeException.class) // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // @ResponseBody // public ErrorTip notFount(RuntimeException e) { // LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e)); // getRequest().setAttribute("tip", "服务器未知运行时异常"); // log.error("运行时异常:", e); // return new ErrorTip(BizExceptionEnum.SERVER_ERROR); // } //}
Kuangcp/Graduate
src/main/java/top/kuangcp/graduate/config/GlobalExceptionHandler.java
996
// * 拦截未知的运行时异常
line_comment
zh-cn
package top.kuangcp.graduate.config; /** * Created by https://github.com/kuangcp * TODO 全局异常对于JWT的使用是无效的, 怀疑就是整体和SpringMVC体系不契合,异常根本没经过这个全局异常 * @author kuangcp * @date 18-4-25 下午5:42 */ //@ControllerAdvice //public class GlobalExceptionHandler { // @ExceptionHandler(value = Exception.class) // @ResponseBody //// @ResponseStatus(value = HttpStatus.NOT_FOUND) // public String notFoundHandler(HttpServletRequest request, Exception e) { // return JsonBuilder.buildResult(1, "404", " "); // } // // //// @ExceptionHandler(value = RuntimeException.class) ////// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) //// public String internalServerErrorHandler(HttpServletRequest request, Exception e) { //// return JsonBuilder.buildResult(1, "500", " "); //// } //} //@EnableWebMvc //@RestControllerAdvice //public class GlobalExceptionHandler { // // @ExceptionHandler(value = { NoHandlerFoundException.class }) // @ResponseStatus(HttpStatus.NOT_FOUND) // public String noHandlerFoundException(Exception ex) { // // return JsonBuilder.buildResult(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase(), " "); //// return RespUtil.make(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.getReasonPhrase()); // } // // @ExceptionHandler(value = { ConstraintViolationException.class }) // @ResponseStatus(HttpStatus.BAD_REQUEST) // public String constraintViolationException(ConstraintViolationException ex) { // // return JsonBuilder.buildResult(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), " "); //// return RespUtil.make(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()); // } // // @ExceptionHandler(value = Exception.class) // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // public String defaultErrorHandler(HttpServletRequest request, Exception exception) throws Exception { // System.out.println("5 00 "); // return JsonBuilder.buildResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), " "); //// return RespUtil.make(HttpStatus.INTERNAL_SERVER_ERROR.value(), //// HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()); // } // //} //@ControllerAdvice //public class GlobalExceptionHandler { // // private Logger log = LoggerFactory.getLogger(this.getClass()); // // /** // * 拦截业务异常 // * // * @author fengshuonan // */ // @ExceptionHandler(Exception.class) // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // @ResponseBody // public String notFount(Exception e) { // log.error("业务异常:", e); // // return JsonBuilder.buildResult(500, " ", " "); // } // SignatureException // /** // * 用户未登录 // */ // @ExceptionHandler(AuthenticationException.class) // @ResponseStatus(HttpStatus.UNAUTHORIZED) // public String unAuth(AuthenticationException e) { // log.error("用户未登陆:", e); // return "/login.html"; // } // // // /** // * 拦截 <SUF> // */ // @ExceptionHandler(RuntimeException.class) // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // @ResponseBody // public ErrorTip notFount(RuntimeException e) { // LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e)); // getRequest().setAttribute("tip", "服务器未知运行时异常"); // log.error("运行时异常:", e); // return new ErrorTip(BizExceptionEnum.SERVER_ERROR); // } //}
false
782
12
996
12
967
10
996
12
1,194
20
false
false
false
false
false
true
65855_3
package com.github.kuangcp.caculator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * 给出一组数字,只有加减,给你一个数字判断是否能从数组中计算得到 * 最好列出等式 * 解决,耗时一个多小时,两个月没有码代码,大脑迟钝太多了! * Created by l on 2017/1/3 */ public class ListExpressionDemo { private static int[] dataArray; private static List<String> result = new ArrayList<>(); private static Map<String, String> results = new HashMap<>(); private static int num;//记录数据大小 public static void main(String[] a) { dataArray = new int[]{6, 3, 2, 4, 8, 2, 1, 2, 1, 3, 2}; num = dataArray.length; ListExpressionDemo test = new ListExpressionDemo(); test.calculate("", 0); test.calculateResult(result); System.out.println("组合结果数 :" + result.size()); Scanner sc = new Scanner(System.in); System.out.println("请输入查询结果"); String target = sc.nextLine(); System.out.println(results.getOrDefault(target, "没有该结果")); } /** * 递归求出可能的等式 */ private void calculate(String operation, int index) { if (index < num) { index++; calculate(operation + "+", index); calculate(operation + "-", index); } else { result.add(operation); } } /** * 根据等式计算出值 */ private void calculateResult(List<String> expression) { for (String row : expression) { if (row.length() >= num) { int temp = 0; StringBuilder buffer = new StringBuilder(); System.out.println("operation 长度:" + row.length()); for (int j = 0; j < row.length(); j++) { String operation = row.charAt(j) + ""; if ("+".equals(operation)) { temp += dataArray[j]; System.out.print("temp:" + temp); } else { temp -= dataArray[j]; } buffer.append(operation).append(dataArray[j]); System.out.print(operation + "" + dataArray[j]); } buffer.append(" = ").append(temp); System.out.println(" = " + temp); results.put(temp + "", buffer.toString()); } } } }
Kuangcp/JavaBase
question/src/main/java/com/github/kuangcp/caculator/ListExpressionDemo.java
631
/** * 根据等式计算出值 */
block_comment
zh-cn
package com.github.kuangcp.caculator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * 给出一组数字,只有加减,给你一个数字判断是否能从数组中计算得到 * 最好列出等式 * 解决,耗时一个多小时,两个月没有码代码,大脑迟钝太多了! * Created by l on 2017/1/3 */ public class ListExpressionDemo { private static int[] dataArray; private static List<String> result = new ArrayList<>(); private static Map<String, String> results = new HashMap<>(); private static int num;//记录数据大小 public static void main(String[] a) { dataArray = new int[]{6, 3, 2, 4, 8, 2, 1, 2, 1, 3, 2}; num = dataArray.length; ListExpressionDemo test = new ListExpressionDemo(); test.calculate("", 0); test.calculateResult(result); System.out.println("组合结果数 :" + result.size()); Scanner sc = new Scanner(System.in); System.out.println("请输入查询结果"); String target = sc.nextLine(); System.out.println(results.getOrDefault(target, "没有该结果")); } /** * 递归求出可能的等式 */ private void calculate(String operation, int index) { if (index < num) { index++; calculate(operation + "+", index); calculate(operation + "-", index); } else { result.add(operation); } } /** * 根据等 <SUF>*/ private void calculateResult(List<String> expression) { for (String row : expression) { if (row.length() >= num) { int temp = 0; StringBuilder buffer = new StringBuilder(); System.out.println("operation 长度:" + row.length()); for (int j = 0; j < row.length(); j++) { String operation = row.charAt(j) + ""; if ("+".equals(operation)) { temp += dataArray[j]; System.out.print("temp:" + temp); } else { temp -= dataArray[j]; } buffer.append(operation).append(dataArray[j]); System.out.print(operation + "" + dataArray[j]); } buffer.append(" = ").append(temp); System.out.println(" = " + temp); results.put(temp + "", buffer.toString()); } } } }
false
543
14
631
11
669
13
631
11
754
16
false
false
false
false
false
true
64490_0
package com.kunminx.architecture.ui.callback; /** * TODO 唯一可信源设计 * 我们在 V6 中继续沿用从 V3 版 "唯一可信源" 理念设计, * 确保 "事件" 发送权牢牢握在可信逻辑中枢手里,从而确保所有订阅者收到消息皆可靠且致, * <p> * 如这么说无体会,详见《吃透 LiveData 本质,享用可靠消息鉴权机制》解析: * https://xiaozhuanlan.com/topic/6017825943 * <p> * TODO 提供 Builder 选项支持 * 我们在 V6 中继续沿用 V3 版延 Builder 选项设计, * 目前提供 "是否允许发送 null" 选项。 * <p> * Create by KunMinX at 2021/6/17 */ public class UnPeekLiveData<T> extends ProtectedUnPeekLiveData<T> { public UnPeekLiveData(T value) { super(value); } public UnPeekLiveData() { super(); } @Override public void setValue(T value) { super.setValue(value); } @Override public void postValue(T value) { super.postValue(value); } public static class Builder<T> { /** * 是否允许传入 null value */ private boolean isAllowNullValue; public Builder<T> setAllowNullValue(boolean allowNullValue) { this.isAllowNullValue = allowNullValue; return this; } public UnPeekLiveData<T> create() { UnPeekLiveData<T> liveData = new UnPeekLiveData<>(); liveData.isAllowNullValue = this.isAllowNullValue; return liveData; } } }
KunMinX/UnPeek-LiveData
unpeeklivedata/src/main/java/com/kunminx/architecture/ui/callback/UnPeekLiveData.java
440
/** * TODO 唯一可信源设计 * 我们在 V6 中继续沿用从 V3 版 "唯一可信源" 理念设计, * 确保 "事件" 发送权牢牢握在可信逻辑中枢手里,从而确保所有订阅者收到消息皆可靠且致, * <p> * 如这么说无体会,详见《吃透 LiveData 本质,享用可靠消息鉴权机制》解析: * https://xiaozhuanlan.com/topic/6017825943 * <p> * TODO 提供 Builder 选项支持 * 我们在 V6 中继续沿用 V3 版延 Builder 选项设计, * 目前提供 "是否允许发送 null" 选项。 * <p> * Create by KunMinX at 2021/6/17 */
block_comment
zh-cn
package com.kunminx.architecture.ui.callback; /** * TOD <SUF>*/ public class UnPeekLiveData<T> extends ProtectedUnPeekLiveData<T> { public UnPeekLiveData(T value) { super(value); } public UnPeekLiveData() { super(); } @Override public void setValue(T value) { super.setValue(value); } @Override public void postValue(T value) { super.postValue(value); } public static class Builder<T> { /** * 是否允许传入 null value */ private boolean isAllowNullValue; public Builder<T> setAllowNullValue(boolean allowNullValue) { this.isAllowNullValue = allowNullValue; return this; } public UnPeekLiveData<T> create() { UnPeekLiveData<T> liveData = new UnPeekLiveData<>(); liveData.isAllowNullValue = this.isAllowNullValue; return liveData; } } }
false
395
189
440
223
441
191
440
223
607
319
true
true
true
true
true
false
19328_1
package g_control_language; public class TestBreakContinue { // Java的Break和Continue语句综合练习 public static void main(String[] args) { /* * 抓动物小游戏 * 每次随机出现一个动物 * 如果出现老虎,则游戏结束;如果出现老鹰,躲起来,等待下一个动物出现 * 如果出现小猫、小狗、小鸟和小乌龟,可以抓住。计数,抓住多少个动物 */ // 0-老虎 1-老鹰 2-小猫 3-小狗 4-小鸟 5-小乌龟 int total = 0; int cat = 0; int dog = 0; int bird = 0; int tortoise = 0; while (true) { int animal = (int) (Math.random() * 6); if (animal == 0) { System.out.println("老虎出现,撤退撤退!"); break; } else if (animal == 1) { System.out.println("老鹰出现,注意注意,先躲起来"); continue; } else if (animal == 2) { System.out.println("发现一只小猫,抓住"); total++; cat++; } else if (animal == 3) { System.out.println("发现一只小狗,抓住"); total++; dog++; } else if (animal == 4) { System.out.println("发现一只小鸟,抓住"); total++; bird++; } else { System.out.println("发现一只小乌龟,抓住"); total++; tortoise++; } } System.out.println("一个共抓到了" + total + "只动物"); System.out.println("一个共抓到了" + cat + "只小猫"); System.out.println("一个共抓到了" + dog + "只小狗"); System.out.println("一个共抓到了" + bird + "只小鸟"); System.out.println("一个共抓到了" + tortoise + "只小乌龟"); } }
KyLin066/Java_Start
g_control_language/TestBreakContinue.java
549
/* * 抓动物小游戏 * 每次随机出现一个动物 * 如果出现老虎,则游戏结束;如果出现老鹰,躲起来,等待下一个动物出现 * 如果出现小猫、小狗、小鸟和小乌龟,可以抓住。计数,抓住多少个动物 */
block_comment
zh-cn
package g_control_language; public class TestBreakContinue { // Java的Break和Continue语句综合练习 public static void main(String[] args) { /* * 抓动物 <SUF>*/ // 0-老虎 1-老鹰 2-小猫 3-小狗 4-小鸟 5-小乌龟 int total = 0; int cat = 0; int dog = 0; int bird = 0; int tortoise = 0; while (true) { int animal = (int) (Math.random() * 6); if (animal == 0) { System.out.println("老虎出现,撤退撤退!"); break; } else if (animal == 1) { System.out.println("老鹰出现,注意注意,先躲起来"); continue; } else if (animal == 2) { System.out.println("发现一只小猫,抓住"); total++; cat++; } else if (animal == 3) { System.out.println("发现一只小狗,抓住"); total++; dog++; } else if (animal == 4) { System.out.println("发现一只小鸟,抓住"); total++; bird++; } else { System.out.println("发现一只小乌龟,抓住"); total++; tortoise++; } } System.out.println("一个共抓到了" + total + "只动物"); System.out.println("一个共抓到了" + cat + "只小猫"); System.out.println("一个共抓到了" + dog + "只小狗"); System.out.println("一个共抓到了" + bird + "只小鸟"); System.out.println("一个共抓到了" + tortoise + "只小乌龟"); } }
false
451
69
549
85
520
69
549
85
728
141
false
false
false
false
false
true
20807_31
package com.example.mywork; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class txlFragment extends Fragment { //获取recyclerView对象并且实例化适配器 private RecyclerView recyclerView; private MyAdapter myAdapter; LinearLayout linearLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //return inflater.inflate(R.layout.fra_lx, container, false); View view; //存所有控件的视图 view=inflater.inflate(R.layout.item, container, false); //调用recycleview控件 recyclerView=view.findViewById(R.id.itemview); linearLayout=view.findViewById(R.id.linearLayout_txl); //创建数据 String[] names={"Pappy","Mommy","Sister","Little Sister","Brother","Little Brother","Roommate"}; int[] images={R.drawable.baba,R.drawable.mama,R.drawable.jiejie,R.drawable.meimei,R.drawable.gege, R.drawable.didi,R.drawable.shiyou1}; String[] phones={"123456789","123456789","123456789","123456789","123456789", "123456789","123456789"}; String[] regions={"四川 南充","四川 南充","四川 南充","四川 南充","四川 南充","四川 南充","湖北 武汉"}; String[] tags={"家人","家人","家人","家人","家人","家人","同学"}; List<Map<String,Object>> items=new ArrayList<Map<String,Object>>(); for(int i=0;i<names.length;i++){ Map<String,Object> item=new HashMap<String, Object>(); item.put("i_name",names[i]); item.put("i_image",images[i]); item.put("i_phone",phones[i]); item.put("i_region",regions[i]); item.put("i_tag",tags[i]); items.add(item); } //创建RecycleView实例和设置Adapter Context context=getContext(); myAdapter=new MyAdapter(items,context); LinearLayoutManager manager=new LinearLayoutManager(context); manager.setOrientation(recyclerView.VERTICAL); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(myAdapter); // linearLayout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(getActivity(), txlDetails.class); //// launcher.launch(intent); // startActivity(intent); // } // }); // //实现拖拽和左滑删除效果 // ItemTouchHelper itemTouchHelper=new ItemTouchHelper(new ItemTouchHelper.Callback() { // @Override // public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { // int swiped=ItemTouchHelper.LEFT; // int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; // return makeMovementFlags(dragFlags,swiped); // } // // @Override // public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { // int oldPosition = viewHolder.getAdapterPosition(); // int newPosition = target.getAdapterPosition(); // if (oldPosition < newPosition) { // for (int i = oldPosition; i < newPosition; i++) { // // 改变数据集 // Collections.swap(items, i, i +1); // } // } else { // for (int i = oldPosition; i > newPosition; i--) { // // 改变数据集 // Collections.swap(items, i, i - 1); // } // } // myAdapter.notifyItemMoved(oldPosition, newPosition); // return true; // } // // @Override // public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { // int position = viewHolder.getAdapterPosition(); // items.remove(position); // myAdapter.notifyItemRemoved(position); // } // @Override // public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { // if (actionState!=ItemTouchHelper.ACTION_STATE_IDLE){ // viewHolder.itemView.setBackgroundColor(Color.parseColor("#04BE02")); // } // } // @Override // public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { // super.clearView(recyclerView, viewHolder); // viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT); // } // }); // //关联recycleView // itemTouchHelper.attachToRecyclerView(recyclerView); return view; } }
Kylinxin/MyWork
app/src/main/java/com/example/mywork/txlFragment.java
1,424
// // 改变数据集
line_comment
zh-cn
package com.example.mywork; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class txlFragment extends Fragment { //获取recyclerView对象并且实例化适配器 private RecyclerView recyclerView; private MyAdapter myAdapter; LinearLayout linearLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //return inflater.inflate(R.layout.fra_lx, container, false); View view; //存所有控件的视图 view=inflater.inflate(R.layout.item, container, false); //调用recycleview控件 recyclerView=view.findViewById(R.id.itemview); linearLayout=view.findViewById(R.id.linearLayout_txl); //创建数据 String[] names={"Pappy","Mommy","Sister","Little Sister","Brother","Little Brother","Roommate"}; int[] images={R.drawable.baba,R.drawable.mama,R.drawable.jiejie,R.drawable.meimei,R.drawable.gege, R.drawable.didi,R.drawable.shiyou1}; String[] phones={"123456789","123456789","123456789","123456789","123456789", "123456789","123456789"}; String[] regions={"四川 南充","四川 南充","四川 南充","四川 南充","四川 南充","四川 南充","湖北 武汉"}; String[] tags={"家人","家人","家人","家人","家人","家人","同学"}; List<Map<String,Object>> items=new ArrayList<Map<String,Object>>(); for(int i=0;i<names.length;i++){ Map<String,Object> item=new HashMap<String, Object>(); item.put("i_name",names[i]); item.put("i_image",images[i]); item.put("i_phone",phones[i]); item.put("i_region",regions[i]); item.put("i_tag",tags[i]); items.add(item); } //创建RecycleView实例和设置Adapter Context context=getContext(); myAdapter=new MyAdapter(items,context); LinearLayoutManager manager=new LinearLayoutManager(context); manager.setOrientation(recyclerView.VERTICAL); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(myAdapter); // linearLayout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(getActivity(), txlDetails.class); //// launcher.launch(intent); // startActivity(intent); // } // }); // //实现拖拽和左滑删除效果 // ItemTouchHelper itemTouchHelper=new ItemTouchHelper(new ItemTouchHelper.Callback() { // @Override // public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { // int swiped=ItemTouchHelper.LEFT; // int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; // return makeMovementFlags(dragFlags,swiped); // } // // @Override // public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { // int oldPosition = viewHolder.getAdapterPosition(); // int newPosition = target.getAdapterPosition(); // if (oldPosition < newPosition) { // for (int i = oldPosition; i < newPosition; i++) { // // 改变数据集 // Collections.swap(items, i, i +1); // } // } else { // for (int i = oldPosition; i > newPosition; i--) { // // 改变 <SUF> // Collections.swap(items, i, i - 1); // } // } // myAdapter.notifyItemMoved(oldPosition, newPosition); // return true; // } // // @Override // public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { // int position = viewHolder.getAdapterPosition(); // items.remove(position); // myAdapter.notifyItemRemoved(position); // } // @Override // public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { // if (actionState!=ItemTouchHelper.ACTION_STATE_IDLE){ // viewHolder.itemView.setBackgroundColor(Color.parseColor("#04BE02")); // } // } // @Override // public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { // super.clearView(recyclerView, viewHolder); // viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT); // } // }); // //关联recycleView // itemTouchHelper.attachToRecyclerView(recyclerView); return view; } }
false
1,130
8
1,423
7
1,396
6
1,424
7
1,628
10
false
false
false
false
false
true
35093_7
package tools; public class Constant { /** * 报修类型 */ //水 public static final int SERTYPE_WATER = 1; //木 public static final int SERTYPE_WOOD = 2; //电 public static final int SERTYPE_ELECTRIC = 3; //其他 public static final int SERTYPE_ORTHER = 4; //全部 public static final int SERTYPE_ALL = 0; /** * 评价表提交标志 */ //未提交 public static final int UNSUBMIT = 0; //已提交 public static final int SUBMIT = 1; /** * 审核状态 */ //未审核 public static final int JUDGESTATE_UNCHECK = -1; //已受理 public static final int JUDGESTATE_CHECKED = 1; //已完工 public static final int JUDGESTATE_FINISH = 2; //全部 public static final int JUDGESTATE_ALL = 0; /** * 满意度选项 */ //不满意 public static final int UNSATISFIED = 1; //一般 public static final int NORMAL = 2; //满意 public static final int SATISFIED = 3; //全部 public static final int SATISFIED_ALL = 0; /** * 星级评分 */ //一星 public static final int CLASS_ONE = 1; //二星 public static final int CLASS_TWO = 2; //三星 public static final int CLASS_THREE = 3; //四星 public static final int CLASS_FOUR = 4; //五星 public static final int CLASS_FIVE = 5; //全部 public static final int CLASS_ALL = 0; /** * 默认每页显示多少条记录 */ public static final int DEFAULT_PAGE_SIZE = 7; /** * 默认显示第几页记录 */ public static final int DEFAULT_PAGE_NUM = 1; /** * HomePage默认显示几条报修单信息 */ public static final int DEFAULT_REPAIRFORM_NUM = 5; /** * HomePage默认显示几条公告栏信息 */ public static final int DEFAULT_NoticeInform_NUM = 5; }
Kyrie17/GuaranteeSystem
src/tools/Constant.java
597
//已完工
line_comment
zh-cn
package tools; public class Constant { /** * 报修类型 */ //水 public static final int SERTYPE_WATER = 1; //木 public static final int SERTYPE_WOOD = 2; //电 public static final int SERTYPE_ELECTRIC = 3; //其他 public static final int SERTYPE_ORTHER = 4; //全部 public static final int SERTYPE_ALL = 0; /** * 评价表提交标志 */ //未提交 public static final int UNSUBMIT = 0; //已提交 public static final int SUBMIT = 1; /** * 审核状态 */ //未审核 public static final int JUDGESTATE_UNCHECK = -1; //已受理 public static final int JUDGESTATE_CHECKED = 1; //已完 <SUF> public static final int JUDGESTATE_FINISH = 2; //全部 public static final int JUDGESTATE_ALL = 0; /** * 满意度选项 */ //不满意 public static final int UNSATISFIED = 1; //一般 public static final int NORMAL = 2; //满意 public static final int SATISFIED = 3; //全部 public static final int SATISFIED_ALL = 0; /** * 星级评分 */ //一星 public static final int CLASS_ONE = 1; //二星 public static final int CLASS_TWO = 2; //三星 public static final int CLASS_THREE = 3; //四星 public static final int CLASS_FOUR = 4; //五星 public static final int CLASS_FIVE = 5; //全部 public static final int CLASS_ALL = 0; /** * 默认每页显示多少条记录 */ public static final int DEFAULT_PAGE_SIZE = 7; /** * 默认显示第几页记录 */ public static final int DEFAULT_PAGE_NUM = 1; /** * HomePage默认显示几条报修单信息 */ public static final int DEFAULT_REPAIRFORM_NUM = 5; /** * HomePage默认显示几条公告栏信息 */ public static final int DEFAULT_NoticeInform_NUM = 5; }
false
529
3
597
4
633
4
597
4
759
4
false
false
false
false
false
true
48496_42
/** * License * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR * COPYRIGHT LAW IS PROHIBITED. * * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE * MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. * */ package l1j.server.server.model.identity; public class L1ItemId { //一段加速類道具 /** 自我加速藥水ン */ public static final int POTION_OF_HASTE_SELF = 40013; /** 受祝福的 自我加速藥水 */ public static final int B_POTION_OF_HASTE_SELF = 140013; /** 強化 自我加速藥水 */ public static final int POTION_OF_GREATER_HASTE_SELF = 40018; /** 受祝福的 強化 自我加速藥水 */ public static final int B_POTION_OF_GREATER_HASTE_SELF = 140018; //二段加速類道具 /** 勇敢藥水 */ public static final int POTION_OF_EMOTION_BRAVERY = 40014; /** 受祝福的勇敢藥水 */ public static final int B_POTION_OF_EMOTION_BRAVERY = 140014; /** 強化勇氣的藥水 */ public static final int POTION_OF_REINFORCED_CASE = 41415; /** 福利勇敢藥水 */ public static final int W_POTION_OF_EMOTION_BRAVERY = 49305; /** 惡魔之血 */ public static final int DEVILS_BLOOD = 40031; /** 名譽貨幣 */ public static final int COIN_OF_REPUTATION = 40733; /** 精靈餅乾 */ public static final int ELVEN_WAFER = 40068; /** 受祝福的精靈餅乾 */ public static final int B_ELVEN_WAFER = 140068; /** 福利森林藥水 */ public static final int W_POTION_OF_FOREST = 49304; /** 生命之樹果實 */ public static final int FORBIDDEN_FRUIT = 49158; //三段加速類道具 /** 巧克力蛋糕 */ public static final int CHOCOLATE_CAKE = 49138; //治癒類道具 /** 治癒藥水 */ public static final int POTION_OF_HEALING = 40010; /** 受祝福的 治癒藥水 */ public static final int B_POTION_OF_HEALING = 140010; /** 受咀咒的 治癒藥水 */ public static final int C_POTION_OF_HEALING = 240010; /** 強力治癒藥水 */ public static final int POTION_OF_EXTRA_HEALING = 40011; /** 受祝福的 強力治癒藥水 */ public static final int B_POTION_OF_EXTRA_HEALING = 140011; /** 終極治癒藥水 */ public static final int POTION_OF_GREATER_HEALING = 40012; /** 受祝福的 終極治癒藥水 */ public static final int B_POTION_OF_GREATER_HEALING = 140012; /** 濃縮體力恢復劑 */ public static final int CONDENSED_POTION_OF_HEALING = 40019; /** 濃縮強力體力恢復劑 */ public static final int CONDENSED_POTION_OF_EXTRA_HEALING = 40020; /** 濃縮終極體力恢復劑 */ public static final int CONDENSED_POTION_OF_GREATER_HEALING = 40021; //藥水類道具 /** 藍色藥水 */ public static final int POTION_OF_MANA = 40015; /** 受祝福的 藍色藥水 */ public static final int B_POTION_OF_MANA = 140015; /** 福利藍色藥水 */ public static final int W_POTION_OF_MANA = 49306; /** 慎重藥水 */ public static final int POTION_OF_EMOTION_WISDOM = 40016; /** 受祝福的 慎重藥水 */ public static final int B_POTION_OF_EMOTION_WISDOM = 140016; /** 福利慎重藥水 */ public static final int W_POTION_OF_EMOTION_WISDOM = 49307; /** 翡翠藥水 */ public static final int POTION_OF_CURE_POISON = 40017; /** 黑色藥水 */ public static final int POTION_OF_BLINDNESS = 40025; //卷軸類道具 /** 對盔甲施法的卷軸 */ public static final int SCROLL_OF_ENCHANT_ARMOR = 40074; /** 受祝福的 對盔甲施法的卷軸 */ public static final int B_SCROLL_OF_ENCHANT_ARMOR = 140074; /** 受咀咒的 對盔甲施法的卷軸 */ public static final int C_SCROLL_OF_ENCHANT_ARMOR = 240074; /** 對武器施法的卷軸 */ public static final int SCROLL_OF_ENCHANT_WEAPON = 40087; /** 受祝福的 對武器施法的卷軸 */ public static final int B_SCROLL_OF_ENCHANT_WEAPON = 140087; /** 受咀咒的 對武器施法的卷軸 */ public static final int C_SCROLL_OF_ENCHANT_WEAPON = 240087; /** 試煉卷軸 */ public static final int SCROLL_OF_ENCHANT_QUEST_WEAPON = 40660; //其他類道具 /** 150%神力藥水 */ public static final int POTION_OF_EXP_150 = 47000; /** 175%神力藥水 */ public static final int POTION_OF_EXP_175 = 47001; /** 200%神力藥水 */ public static final int POTION_OF_EXP_200 = 47002; /** 225%神力藥水 */ public static final int POTION_OF_EXP_225 = 47003; /** 250%神力藥水 */ public static final int POTION_OF_EXP_250 = 47004; /** 媽祖祝福平安符 */ public static final int BLESS_OF_MAZU = 47005; /** 戰鬥藥水 */ public static final int POTION_OF_BATTLE = 47006; /** 體力增強卷軸 */ public static final int SCROLL_FOR_STRENGTHENING_HP = 47007; /** 魔力增強卷軸 */ public static final int SCROLL_FOR_STRENGTHENING_MP = 47008; /** 強化戰鬥卷軸 */ public static final int SCROLL_FOR_ENCHANTING_BATTLE = 47009; /** 象牙塔妙藥 */ public static final int POTION_OF_WONDER_DRUG = 49315; /** 金幣 */ public static final int ADENA = 40308; }
L1J-PLUS/l1j-wk
src/l1j/server/server/model/identity/L1ItemId.java
2,380
/** 受咀咒的 對盔甲施法的卷軸 */
block_comment
zh-cn
/** * License * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR * COPYRIGHT LAW IS PROHIBITED. * * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE * MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. * */ package l1j.server.server.model.identity; public class L1ItemId { //一段加速類道具 /** 自我加速藥水ン */ public static final int POTION_OF_HASTE_SELF = 40013; /** 受祝福的 自我加速藥水 */ public static final int B_POTION_OF_HASTE_SELF = 140013; /** 強化 自我加速藥水 */ public static final int POTION_OF_GREATER_HASTE_SELF = 40018; /** 受祝福的 強化 自我加速藥水 */ public static final int B_POTION_OF_GREATER_HASTE_SELF = 140018; //二段加速類道具 /** 勇敢藥水 */ public static final int POTION_OF_EMOTION_BRAVERY = 40014; /** 受祝福的勇敢藥水 */ public static final int B_POTION_OF_EMOTION_BRAVERY = 140014; /** 強化勇氣的藥水 */ public static final int POTION_OF_REINFORCED_CASE = 41415; /** 福利勇敢藥水 */ public static final int W_POTION_OF_EMOTION_BRAVERY = 49305; /** 惡魔之血 */ public static final int DEVILS_BLOOD = 40031; /** 名譽貨幣 */ public static final int COIN_OF_REPUTATION = 40733; /** 精靈餅乾 */ public static final int ELVEN_WAFER = 40068; /** 受祝福的精靈餅乾 */ public static final int B_ELVEN_WAFER = 140068; /** 福利森林藥水 */ public static final int W_POTION_OF_FOREST = 49304; /** 生命之樹果實 */ public static final int FORBIDDEN_FRUIT = 49158; //三段加速類道具 /** 巧克力蛋糕 */ public static final int CHOCOLATE_CAKE = 49138; //治癒類道具 /** 治癒藥水 */ public static final int POTION_OF_HEALING = 40010; /** 受祝福的 治癒藥水 */ public static final int B_POTION_OF_HEALING = 140010; /** 受咀咒的 治癒藥水 */ public static final int C_POTION_OF_HEALING = 240010; /** 強力治癒藥水 */ public static final int POTION_OF_EXTRA_HEALING = 40011; /** 受祝福的 強力治癒藥水 */ public static final int B_POTION_OF_EXTRA_HEALING = 140011; /** 終極治癒藥水 */ public static final int POTION_OF_GREATER_HEALING = 40012; /** 受祝福的 終極治癒藥水 */ public static final int B_POTION_OF_GREATER_HEALING = 140012; /** 濃縮體力恢復劑 */ public static final int CONDENSED_POTION_OF_HEALING = 40019; /** 濃縮強力體力恢復劑 */ public static final int CONDENSED_POTION_OF_EXTRA_HEALING = 40020; /** 濃縮終極體力恢復劑 */ public static final int CONDENSED_POTION_OF_GREATER_HEALING = 40021; //藥水類道具 /** 藍色藥水 */ public static final int POTION_OF_MANA = 40015; /** 受祝福的 藍色藥水 */ public static final int B_POTION_OF_MANA = 140015; /** 福利藍色藥水 */ public static final int W_POTION_OF_MANA = 49306; /** 慎重藥水 */ public static final int POTION_OF_EMOTION_WISDOM = 40016; /** 受祝福的 慎重藥水 */ public static final int B_POTION_OF_EMOTION_WISDOM = 140016; /** 福利慎重藥水 */ public static final int W_POTION_OF_EMOTION_WISDOM = 49307; /** 翡翠藥水 */ public static final int POTION_OF_CURE_POISON = 40017; /** 黑色藥水 */ public static final int POTION_OF_BLINDNESS = 40025; //卷軸類道具 /** 對盔甲施法的卷軸 */ public static final int SCROLL_OF_ENCHANT_ARMOR = 40074; /** 受祝福的 對盔甲施法的卷軸 */ public static final int B_SCROLL_OF_ENCHANT_ARMOR = 140074; /** 受咀咒 <SUF>*/ public static final int C_SCROLL_OF_ENCHANT_ARMOR = 240074; /** 對武器施法的卷軸 */ public static final int SCROLL_OF_ENCHANT_WEAPON = 40087; /** 受祝福的 對武器施法的卷軸 */ public static final int B_SCROLL_OF_ENCHANT_WEAPON = 140087; /** 受咀咒的 對武器施法的卷軸 */ public static final int C_SCROLL_OF_ENCHANT_WEAPON = 240087; /** 試煉卷軸 */ public static final int SCROLL_OF_ENCHANT_QUEST_WEAPON = 40660; //其他類道具 /** 150%神力藥水 */ public static final int POTION_OF_EXP_150 = 47000; /** 175%神力藥水 */ public static final int POTION_OF_EXP_175 = 47001; /** 200%神力藥水 */ public static final int POTION_OF_EXP_200 = 47002; /** 225%神力藥水 */ public static final int POTION_OF_EXP_225 = 47003; /** 250%神力藥水 */ public static final int POTION_OF_EXP_250 = 47004; /** 媽祖祝福平安符 */ public static final int BLESS_OF_MAZU = 47005; /** 戰鬥藥水 */ public static final int POTION_OF_BATTLE = 47006; /** 體力增強卷軸 */ public static final int SCROLL_FOR_STRENGTHENING_HP = 47007; /** 魔力增強卷軸 */ public static final int SCROLL_FOR_STRENGTHENING_MP = 47008; /** 強化戰鬥卷軸 */ public static final int SCROLL_FOR_ENCHANTING_BATTLE = 47009; /** 象牙塔妙藥 */ public static final int POTION_OF_WONDER_DRUG = 49315; /** 金幣 */ public static final int ADENA = 40308; }
false
1,846
17
2,380
21
2,015
13
2,380
21
2,867
32
false
false
false
false
false
true
49611_24
package hits; import web.src.models.News; import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; import java.util.Comparator; /** * Created by L1n on 17/3/19. * 参考: http://blog.csdn.net/androidlushangderen/article/details/43311943# */ public class MyHITS { // 参与 HITS 计算的网页集 private ArrayList<News> pagesList; private int pageNum; public MyHITS(ArrayList<News> pagesList) { this.pagesList = pagesList; this.pageNum = pagesList.size(); } public static void main(String[] args) throws Exception { System.out.println("[*] 调用了 HITS 的 main 方法"); } public ArrayList<News> sortByHITSResult(String choice) { if (choice.equals("Hub")) { // 按中心值排序 Collections.sort(this.pagesList, Collections.reverseOrder(new Comparator<News>() { @Override public int compare(News o1, News o2) { return Double.compare(o1.getHub(), o2.getHub()); } })); } else if (choice.equals("Authority")) { // 开始按权威值排序 Collections.sort(this.pagesList, Collections.reverseOrder(new Comparator<News>() { @Override public int compare(News o1, News o2) { return Double.compare(o1.getAuthority(), o2.getAuthority()); } })); } return this.pagesList; } /** * 【弃用】输出结果页面,也就是 authority 权威值最高的页面 * 以下代码参考: http://blog.csdn.net/androidlushangderen/article/details/43311943 */ public ArrayList<News> hitsSort2(boolean[][] linkMatrix) { //误差值,用于收敛判断 double error = Integer.MAX_VALUE; // 初始化 resultAuthority 和 resultHub, 默认值都为 1 double[] resultAuthority = new double[pageNum];//网页Authority权威值 double[] resultHub = new double[pageNum];//网页hub中心值 Arrays.fill(resultAuthority, 1); Arrays.fill(resultHub, 1); while (error > 0.01 * pageNum) { // 迭代使用的权威值和中心值, 初始化为值 0 double[] temp_authority = new double[pageNum]; double[] temp_hub = new double[pageNum]; // resultHub 和 resultAuthority 值的更新计算 for (int i = 0; i < pageNum; i++) { for (int j = 0; j < pageNum; j++) { // i 指向了 j if (linkMatrix[i][j]) { // 页面 p 的中心值 = 所有页面 p 指向的页面的权威值之和 temp_hub[i] += resultAuthority[j]; // 页面 p 的权威值 = 所有指向页面 p 的页面的中心值之和 temp_authority[j] += resultHub[i]; } } } // 求出最大 Hub 和 Authority double maxHub = Arrays.stream(temp_authority).max().getAsDouble(); double maxAuthority = Arrays.stream(temp_hub).max().getAsDouble(); // 归一化处理 error = 0; for (int k = 0; k < pageNum; k++) { temp_authority[k] /= maxHub; temp_hub[k] /= maxAuthority; error += Math.abs(temp_authority[k] - resultHub[k]); resultHub[k] = temp_hub[k]; resultAuthority[k] = temp_authority[k]; } } System.out.println(String.format("[*] 最终收敛成功")); // 将计算得到的权威值、中心值保存到 news 之中 for (int i = 0; i < resultAuthority.length; ++i) { this.pagesList.get(i).setAuthority(resultAuthority[i]); this.pagesList.get(i).setHub(resultHub[i]); } return sortByHITSResult("Authority"); } /** * 输出结果页面,也就是 authority 权威值最高的页面 * 以下代码参考 wiki: https://en.wikipedia.org/wiki/HITS_algorithm */ public ArrayList<News> hitsSort(boolean[][] linkMatrix, String choice) { // 初始化 resultAuthority 和 resultHub, 默认值都为 1 double[] resultAuthority = new double[pageNum];//网页Authority权威值 double[] resultHub = new double[pageNum];//网页hub中心值 Arrays.fill(resultAuthority, 1); Arrays.fill(resultHub, 1); // 进行 k 次, 论文中给出的 k 值为 20 int p, q, r; for (int k = 0; k < 20; ++k) { double norm = 0.0; // 更新权威值 for (p = 0; p < pageNum; ++p) { resultAuthority[p] = 0; for (q = 0; q < pageNum; ++q) { // q 指向 p if (linkMatrix[q][p]) { resultAuthority[p] += resultHub[q]; } } norm += Math.pow(resultAuthority[p], 2); } norm = Math.sqrt(norm); for (p = 0; p < pageNum; ++p) { resultAuthority[p] = resultAuthority[p] / norm; } // 更新中心值 norm = 0.0; Arrays.fill(resultHub, 0); for (p = 0; p < pageNum; ++p) { for (r = 0; r < pageNum; ++r) { // p 指向 r if (linkMatrix[p][r]) { resultHub[p] += resultAuthority[r]; } } norm += Math.pow(resultHub[p], 2); } norm = Math.sqrt(norm); for (p = 0; p < pageNum; ++p) { resultHub[p] = resultHub[p] / norm; } } System.out.println(String.format("[*] 最终收敛成功")); // 将计算得到的权威值、中心值保存到 news 之中 for (int i = 0; i < resultAuthority.length; ++i) { this.pagesList.get(i).setAuthority(resultAuthority[i]); this.pagesList.get(i).setHub(resultHub[i]); } return sortByHITSResult(choice); } }
L1nwatch/lucene-graduation-design
src/hits/MyHITS.java
1,604
// 更新中心值
line_comment
zh-cn
package hits; import web.src.models.News; import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; import java.util.Comparator; /** * Created by L1n on 17/3/19. * 参考: http://blog.csdn.net/androidlushangderen/article/details/43311943# */ public class MyHITS { // 参与 HITS 计算的网页集 private ArrayList<News> pagesList; private int pageNum; public MyHITS(ArrayList<News> pagesList) { this.pagesList = pagesList; this.pageNum = pagesList.size(); } public static void main(String[] args) throws Exception { System.out.println("[*] 调用了 HITS 的 main 方法"); } public ArrayList<News> sortByHITSResult(String choice) { if (choice.equals("Hub")) { // 按中心值排序 Collections.sort(this.pagesList, Collections.reverseOrder(new Comparator<News>() { @Override public int compare(News o1, News o2) { return Double.compare(o1.getHub(), o2.getHub()); } })); } else if (choice.equals("Authority")) { // 开始按权威值排序 Collections.sort(this.pagesList, Collections.reverseOrder(new Comparator<News>() { @Override public int compare(News o1, News o2) { return Double.compare(o1.getAuthority(), o2.getAuthority()); } })); } return this.pagesList; } /** * 【弃用】输出结果页面,也就是 authority 权威值最高的页面 * 以下代码参考: http://blog.csdn.net/androidlushangderen/article/details/43311943 */ public ArrayList<News> hitsSort2(boolean[][] linkMatrix) { //误差值,用于收敛判断 double error = Integer.MAX_VALUE; // 初始化 resultAuthority 和 resultHub, 默认值都为 1 double[] resultAuthority = new double[pageNum];//网页Authority权威值 double[] resultHub = new double[pageNum];//网页hub中心值 Arrays.fill(resultAuthority, 1); Arrays.fill(resultHub, 1); while (error > 0.01 * pageNum) { // 迭代使用的权威值和中心值, 初始化为值 0 double[] temp_authority = new double[pageNum]; double[] temp_hub = new double[pageNum]; // resultHub 和 resultAuthority 值的更新计算 for (int i = 0; i < pageNum; i++) { for (int j = 0; j < pageNum; j++) { // i 指向了 j if (linkMatrix[i][j]) { // 页面 p 的中心值 = 所有页面 p 指向的页面的权威值之和 temp_hub[i] += resultAuthority[j]; // 页面 p 的权威值 = 所有指向页面 p 的页面的中心值之和 temp_authority[j] += resultHub[i]; } } } // 求出最大 Hub 和 Authority double maxHub = Arrays.stream(temp_authority).max().getAsDouble(); double maxAuthority = Arrays.stream(temp_hub).max().getAsDouble(); // 归一化处理 error = 0; for (int k = 0; k < pageNum; k++) { temp_authority[k] /= maxHub; temp_hub[k] /= maxAuthority; error += Math.abs(temp_authority[k] - resultHub[k]); resultHub[k] = temp_hub[k]; resultAuthority[k] = temp_authority[k]; } } System.out.println(String.format("[*] 最终收敛成功")); // 将计算得到的权威值、中心值保存到 news 之中 for (int i = 0; i < resultAuthority.length; ++i) { this.pagesList.get(i).setAuthority(resultAuthority[i]); this.pagesList.get(i).setHub(resultHub[i]); } return sortByHITSResult("Authority"); } /** * 输出结果页面,也就是 authority 权威值最高的页面 * 以下代码参考 wiki: https://en.wikipedia.org/wiki/HITS_algorithm */ public ArrayList<News> hitsSort(boolean[][] linkMatrix, String choice) { // 初始化 resultAuthority 和 resultHub, 默认值都为 1 double[] resultAuthority = new double[pageNum];//网页Authority权威值 double[] resultHub = new double[pageNum];//网页hub中心值 Arrays.fill(resultAuthority, 1); Arrays.fill(resultHub, 1); // 进行 k 次, 论文中给出的 k 值为 20 int p, q, r; for (int k = 0; k < 20; ++k) { double norm = 0.0; // 更新权威值 for (p = 0; p < pageNum; ++p) { resultAuthority[p] = 0; for (q = 0; q < pageNum; ++q) { // q 指向 p if (linkMatrix[q][p]) { resultAuthority[p] += resultHub[q]; } } norm += Math.pow(resultAuthority[p], 2); } norm = Math.sqrt(norm); for (p = 0; p < pageNum; ++p) { resultAuthority[p] = resultAuthority[p] / norm; } // 更新 <SUF> norm = 0.0; Arrays.fill(resultHub, 0); for (p = 0; p < pageNum; ++p) { for (r = 0; r < pageNum; ++r) { // p 指向 r if (linkMatrix[p][r]) { resultHub[p] += resultAuthority[r]; } } norm += Math.pow(resultHub[p], 2); } norm = Math.sqrt(norm); for (p = 0; p < pageNum; ++p) { resultHub[p] = resultHub[p] / norm; } } System.out.println(String.format("[*] 最终收敛成功")); // 将计算得到的权威值、中心值保存到 news 之中 for (int i = 0; i < resultAuthority.length; ++i) { this.pagesList.get(i).setAuthority(resultAuthority[i]); this.pagesList.get(i).setHub(resultHub[i]); } return sortByHITSResult(choice); } }
false
1,451
4
1,604
4
1,666
4
1,604
4
2,038
7
false
false
false
false
false
true
6986_7
package yuan.ssm.datacenter.datasource; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import yuan.ssm.common.util.LoggerUtil; import yuan.ssm.datacenter.common.UrlsContanst; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * ================================================== * <p/> * 版权: 软件工程.net12-1 原明卓 * <p/> * 项目: 基于用户兴趣标签的新闻推荐系统 * <p/> * 作者: 原明卓 * <p/> * 版本: 1.0 * <p/> * 创建日期: 16-5-5 下午12:46 * <p/> * 功能描述: 虎嗅-来源 * <p> * <p/> * 功能更新历史: * <p> * ================================================== */ public class HuxiuSource { //虎嗅网 private static final String HUXIUURL="http://www.huxiu.com";//主页 //虎嗅-车行 private static final String HUXIUURL_CAR="http://www.huxiu.com/mobility.html";//车与出行 //虎嗅-24小时 private static final String HUXIU_TIME="http://www.huxiu.com/whatsnew.html";//24小时 //虎嗅-娱乐影视 private static final String HUXIU_YU="http://www.huxiu.com/entertainment.html";//娱乐淘金 //虎嗅-创业 private static final String HUXIU_CHUANG="http://www.huxiu.com/startups.html";//创业维艰 //虎嗅-生活 private static final String HUXIU_SHUENGHUO="http://www.huxiu.com/lifestyle.html";//生活腔调 private static List<String> ulrs=new ArrayList<String>(); /** * 虎嗅-首次爬去,可以爬取分类信息 * @return 分类url */ public static List<String> getCateUlrs(){ ulrs.add(HUXIUURL_CAR); ulrs.add(HUXIU_TIME); ulrs.add(HUXIU_YU); ulrs.add(HUXIU_CHUANG); ulrs.add(HUXIU_SHUENGHUO); return ulrs; } /** * 主页url * @return */ public static String getHuxiuIndexUrl(){ return HUXIUURL; } /** * 测试主页爬去url * @throws IOException */ private static void testHuXiuIndexPage() throws IOException { Document doc = Jsoup.connect(HUXIUURL).timeout(100000).get(); Set<String> urls=new HashSet<String>(); Elements as = doc.select("a"); for (Element a : as) { String href = a.attr("href"); if(href.contains("/1.html")){ String url= UrlsContanst.HUXIU_BASE_URL+href; urls.add(url); } } LoggerUtil.printJSON(urls); } }
LABELNET/YuanNews
yuannews-datacenter/src/main/java/yuan/ssm/datacenter/datasource/HuxiuSource.java
867
//虎嗅-娱乐影视
line_comment
zh-cn
package yuan.ssm.datacenter.datasource; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import yuan.ssm.common.util.LoggerUtil; import yuan.ssm.datacenter.common.UrlsContanst; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * ================================================== * <p/> * 版权: 软件工程.net12-1 原明卓 * <p/> * 项目: 基于用户兴趣标签的新闻推荐系统 * <p/> * 作者: 原明卓 * <p/> * 版本: 1.0 * <p/> * 创建日期: 16-5-5 下午12:46 * <p/> * 功能描述: 虎嗅-来源 * <p> * <p/> * 功能更新历史: * <p> * ================================================== */ public class HuxiuSource { //虎嗅网 private static final String HUXIUURL="http://www.huxiu.com";//主页 //虎嗅-车行 private static final String HUXIUURL_CAR="http://www.huxiu.com/mobility.html";//车与出行 //虎嗅-24小时 private static final String HUXIU_TIME="http://www.huxiu.com/whatsnew.html";//24小时 //虎嗅 <SUF> private static final String HUXIU_YU="http://www.huxiu.com/entertainment.html";//娱乐淘金 //虎嗅-创业 private static final String HUXIU_CHUANG="http://www.huxiu.com/startups.html";//创业维艰 //虎嗅-生活 private static final String HUXIU_SHUENGHUO="http://www.huxiu.com/lifestyle.html";//生活腔调 private static List<String> ulrs=new ArrayList<String>(); /** * 虎嗅-首次爬去,可以爬取分类信息 * @return 分类url */ public static List<String> getCateUlrs(){ ulrs.add(HUXIUURL_CAR); ulrs.add(HUXIU_TIME); ulrs.add(HUXIU_YU); ulrs.add(HUXIU_CHUANG); ulrs.add(HUXIU_SHUENGHUO); return ulrs; } /** * 主页url * @return */ public static String getHuxiuIndexUrl(){ return HUXIUURL; } /** * 测试主页爬去url * @throws IOException */ private static void testHuXiuIndexPage() throws IOException { Document doc = Jsoup.connect(HUXIUURL).timeout(100000).get(); Set<String> urls=new HashSet<String>(); Elements as = doc.select("a"); for (Element a : as) { String href = a.attr("href"); if(href.contains("/1.html")){ String url= UrlsContanst.HUXIU_BASE_URL+href; urls.add(url); } } LoggerUtil.printJSON(urls); } }
false
701
6
867
12
829
6
867
12
1,054
14
false
false
false
false
false
true
61869_21
package org.fufeng.knowledge.pulsar.admin; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.packages.management.core.common.PackageMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import static org.fufeng.knowledge.pulsar.common.Common.Admin; /** * 包是用户希望在以后的操作中重用的一组元素。在 Pulsar 中,一个包可以是一组函数、源和接收器。您可以根据您的需要定义一个包。 * * Pulsar 中的包管理系统存储每个包的数据和元数据(如下表所示)并跟踪包版本。 * * 元数据 描述 * 描述 包的描述。 * 接触 包裹的联系信息。例如,开发团队的电子邮件地址。 * 创建时间 创建包的时间。 * 修改时间 包最后被修改的时间。 * 特性 用户定义的键/值映射来存储其他信息。 * * 通过提供以下信息在包管理器中创建包:类型、租户、命名空间、包名称和版本。 * * 成分 描述 * 类型 指定受支持的包类型之一:函数、接收器和源。 * 租户 指定要在其中创建包的租户。 * 名称空间 指定要在其中创建包的命名空间。 * 姓名 使用格式指定包的完整名称<tenant>/<namespace>/<package name>。 * 版本 使用数字格式指定包的版本MajorVerion.MinorVersion。 * * 您提供的信息会创建包的 URL,格式为<type>://<tenant>/<namespace>/<package name>/<version>。 * * 将元素上传到包,即您想要跨命名空间使用的函数、源和接收器。 * * 从不同的命名空间向该包应用权限。 * * 可以通过从包管理器中调用此包来使用您在包中定义的元素。包管理器通过 URL 找到它。例如, * sink://public/default/[email protected] * function://my-tenant/my-ns/[email protected] * source://my-tenant/my-ns/[email protected] * * 要使用包管理服务,请确保您的集群中已启用包管理服务,方法是在broker.conf * enablePackagesManagement=true * packagesManagementStorageProvider=org.apache.pulsar.packages.management.storage.bookkeeper.BookKeeperPackagesStorageProvider * packagesReplicas=1 * packagesManagementLedgerRootPath=/ledgers */ public class AdminPackages { private static final Logger logger = LoggerFactory.getLogger(AdminPackages.class); private static final PulsarAdmin admin = Admin(); private static final String TENANT = "public"; private static final String NAMESPACE = "public/test-namespace"; public static void main(String[] args) { try { //upload(); //download(); //delete(); //getMetadata(); //updateMetadata(); //listPackageVersions(); listPackages(); } catch (Exception e) { e.printStackTrace(); } finally { admin.close(); } } private static void listPackages() throws PulsarAdminException { //列出 //您可以使用以下命令列出命名空间下特定类型的所有包。 //bin/pulsar-admin packages list --type function public/default List<String> packages = admin.packages().listPackages("function", NAMESPACE); packages.forEach(logger::info); } private static void listPackageVersions() throws PulsarAdminException { //列出 //您可以使用以下命令列出软件包的所有版本。 //bin/pulsar-admin packages list-versions type://tenant/namespace/packageName List<String> versions = admin.packages().listPackageVersions("functions://public/default/[email protected]"); versions.forEach(logger::info); } private static void updateMetadata() throws PulsarAdminException { //更新 //您可以使用以下命令来更新包的元数据。 //bin/pulsar-admin packages update-metadata function://public/default/[email protected] --description update-description admin.packages().updateMetadata("functions://public/default/[email protected]", new PackageMetadata().toBuilder().description("update desc").build()); } private static void getMetadata() throws PulsarAdminException { //获取 //您可以使用以下命令来获取包的元数据。 //bin/pulsar-admin packages get-metadata function://public/default/test@v1 PackageMetadata metadata = admin.packages().getMetadata("functions://public/default/[email protected]"); logger.info("{}", metadata); } private static void delete() throws PulsarAdminException { //删除 //您可以使用以下命令来删除包。 //bin/pulsar-admin packages delete functions://public/default/[email protected] admin.packages().delete("functions://public/default/[email protected]"); } private static void download() throws PulsarAdminException { //下载一个 //您可以使用以下命令来下载软件包。 //bin/pulsar-admin packages download function://public/default/[email protected] --path package-file admin.packages().download("function://public/default/[email protected]", "./"); } private static void upload() throws PulsarAdminException { //上传 //您可以使用以下命令上传包。 //bin/pulsar-admin packages upload function://public/default/[email protected] --path package-file --description package-description admin.packages().upload( new PackageMetadata().toBuilder(). createTime(System.currentTimeMillis()). contact("fufeng").description("demo") .build(), "function://public/default/[email protected]", "./"); } }
LCY2013/mq-knowledge
src/main/java/org/fufeng/knowledge/pulsar/admin/AdminPackages.java
1,409
//下载一个
line_comment
zh-cn
package org.fufeng.knowledge.pulsar.admin; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.packages.management.core.common.PackageMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import static org.fufeng.knowledge.pulsar.common.Common.Admin; /** * 包是用户希望在以后的操作中重用的一组元素。在 Pulsar 中,一个包可以是一组函数、源和接收器。您可以根据您的需要定义一个包。 * * Pulsar 中的包管理系统存储每个包的数据和元数据(如下表所示)并跟踪包版本。 * * 元数据 描述 * 描述 包的描述。 * 接触 包裹的联系信息。例如,开发团队的电子邮件地址。 * 创建时间 创建包的时间。 * 修改时间 包最后被修改的时间。 * 特性 用户定义的键/值映射来存储其他信息。 * * 通过提供以下信息在包管理器中创建包:类型、租户、命名空间、包名称和版本。 * * 成分 描述 * 类型 指定受支持的包类型之一:函数、接收器和源。 * 租户 指定要在其中创建包的租户。 * 名称空间 指定要在其中创建包的命名空间。 * 姓名 使用格式指定包的完整名称<tenant>/<namespace>/<package name>。 * 版本 使用数字格式指定包的版本MajorVerion.MinorVersion。 * * 您提供的信息会创建包的 URL,格式为<type>://<tenant>/<namespace>/<package name>/<version>。 * * 将元素上传到包,即您想要跨命名空间使用的函数、源和接收器。 * * 从不同的命名空间向该包应用权限。 * * 可以通过从包管理器中调用此包来使用您在包中定义的元素。包管理器通过 URL 找到它。例如, * sink://public/default/[email protected] * function://my-tenant/my-ns/[email protected] * source://my-tenant/my-ns/[email protected] * * 要使用包管理服务,请确保您的集群中已启用包管理服务,方法是在broker.conf * enablePackagesManagement=true * packagesManagementStorageProvider=org.apache.pulsar.packages.management.storage.bookkeeper.BookKeeperPackagesStorageProvider * packagesReplicas=1 * packagesManagementLedgerRootPath=/ledgers */ public class AdminPackages { private static final Logger logger = LoggerFactory.getLogger(AdminPackages.class); private static final PulsarAdmin admin = Admin(); private static final String TENANT = "public"; private static final String NAMESPACE = "public/test-namespace"; public static void main(String[] args) { try { //upload(); //download(); //delete(); //getMetadata(); //updateMetadata(); //listPackageVersions(); listPackages(); } catch (Exception e) { e.printStackTrace(); } finally { admin.close(); } } private static void listPackages() throws PulsarAdminException { //列出 //您可以使用以下命令列出命名空间下特定类型的所有包。 //bin/pulsar-admin packages list --type function public/default List<String> packages = admin.packages().listPackages("function", NAMESPACE); packages.forEach(logger::info); } private static void listPackageVersions() throws PulsarAdminException { //列出 //您可以使用以下命令列出软件包的所有版本。 //bin/pulsar-admin packages list-versions type://tenant/namespace/packageName List<String> versions = admin.packages().listPackageVersions("functions://public/default/[email protected]"); versions.forEach(logger::info); } private static void updateMetadata() throws PulsarAdminException { //更新 //您可以使用以下命令来更新包的元数据。 //bin/pulsar-admin packages update-metadata function://public/default/[email protected] --description update-description admin.packages().updateMetadata("functions://public/default/[email protected]", new PackageMetadata().toBuilder().description("update desc").build()); } private static void getMetadata() throws PulsarAdminException { //获取 //您可以使用以下命令来获取包的元数据。 //bin/pulsar-admin packages get-metadata function://public/default/test@v1 PackageMetadata metadata = admin.packages().getMetadata("functions://public/default/[email protected]"); logger.info("{}", metadata); } private static void delete() throws PulsarAdminException { //删除 //您可以使用以下命令来删除包。 //bin/pulsar-admin packages delete functions://public/default/[email protected] admin.packages().delete("functions://public/default/[email protected]"); } private static void download() throws PulsarAdminException { //下载 <SUF> //您可以使用以下命令来下载软件包。 //bin/pulsar-admin packages download function://public/default/[email protected] --path package-file admin.packages().download("function://public/default/[email protected]", "./"); } private static void upload() throws PulsarAdminException { //上传 //您可以使用以下命令上传包。 //bin/pulsar-admin packages upload function://public/default/[email protected] --path package-file --description package-description admin.packages().upload( new PackageMetadata().toBuilder(). createTime(System.currentTimeMillis()). contact("fufeng").description("demo") .build(), "function://public/default/[email protected]", "./"); } }
false
1,292
3
1,409
3
1,421
3
1,409
3
1,863
5
false
false
false
false
false
true
58186_37
package com.fjsf.web.utils; import java.util.Date; import java.util.Properties; import java.util.Random; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MyEmail { // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 private static String myEmailAccount = "[email protected]"; private static String myEmailPassword = "qwuvqtcdgrwtbfif"; //private static String myEmailAccount = "[email protected]"; //private static String myEmailPassword = "23451617ldz"; // 发件人邮箱的 SMTP 服务器地址, 必须准确, // 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com // qq邮箱SMTP服务器地址位: smtp.qq.com //private static String myEmailSMTPHost = "smtp.163.com"; private static String myEmailSMTPHost = "smtp.qq.com"; // 收件人邮箱(替换为自己知道的有效邮箱) private static String receiveMailAccount; // 发送邮件的姓名 private static String myName = "贝壳网"; // 发送邮件的主题 private static String Subject = "验证码"; // 发送邮件的验证码 private static String code; // 发送邮件的正文 private static String Content = "[贝壳网]"+ code +" (贝壳网安全验证,用于验证身份修改密码等" + ",请勿将验证码透露给他人)"; public String getMyEmailAccount() { return myEmailAccount; } private static void setCode(String temp){ code = temp; } private static void setReceiveMailAccount(String temp){ receiveMailAccount = temp; } private static void setContent(){ Content = "[贝壳网]"+ code +" (贝壳网安全验证,用于验证身份修改密码等" + ",请勿将验证码透露给他人)"; } /** * 发送含有验证码的邮件 * @param code :验证码 * @param receiveMail : 接收者的邮箱 * @throws Exception */ public static void sendMessage(String tempCode, String receiveMail) throws Exception{ setCode(tempCode); setReceiveMailAccount(receiveMail); setContent(); // 1. 创建参数配置, 用于连接邮件服务器的参数配置 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP // 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, // 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 Session session = Session.getDefaultInstance(props); session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log // 3. 创建一封邮件 MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount); // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1) 邮箱没有开启 SMTP 服务; // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, // 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); // 7. 关闭连接 transport.close(); } /** * 创建一封只包含文本的简单邮件 * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(sendMail, myName, "UTF-8")); // 3. To: 收件人(可以增加多个收件人、抄送、密送) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8")); // 4. Subject: 邮件主题 message.setSubject(Subject, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签) message.setContent(Content, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } public static String sendIdCode(String customerMail) { String tempCode = new String(); Random random = new Random(); for (int i = 0; i < 6; i++) { tempCode += random.nextInt(9) + ""; } try { MyEmail.sendMessage(tempCode, customerMail); } catch (Exception e) { e.printStackTrace(); } return tempCode; } }
LDZZDL/CommercialCity
src/com/fjsf/web/utils/MyEmail.java
1,962
// (1) 邮箱没有开启 SMTP 服务;
line_comment
zh-cn
package com.fjsf.web.utils; import java.util.Date; import java.util.Properties; import java.util.Random; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MyEmail { // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 private static String myEmailAccount = "[email protected]"; private static String myEmailPassword = "qwuvqtcdgrwtbfif"; //private static String myEmailAccount = "[email protected]"; //private static String myEmailPassword = "23451617ldz"; // 发件人邮箱的 SMTP 服务器地址, 必须准确, // 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com // qq邮箱SMTP服务器地址位: smtp.qq.com //private static String myEmailSMTPHost = "smtp.163.com"; private static String myEmailSMTPHost = "smtp.qq.com"; // 收件人邮箱(替换为自己知道的有效邮箱) private static String receiveMailAccount; // 发送邮件的姓名 private static String myName = "贝壳网"; // 发送邮件的主题 private static String Subject = "验证码"; // 发送邮件的验证码 private static String code; // 发送邮件的正文 private static String Content = "[贝壳网]"+ code +" (贝壳网安全验证,用于验证身份修改密码等" + ",请勿将验证码透露给他人)"; public String getMyEmailAccount() { return myEmailAccount; } private static void setCode(String temp){ code = temp; } private static void setReceiveMailAccount(String temp){ receiveMailAccount = temp; } private static void setContent(){ Content = "[贝壳网]"+ code +" (贝壳网安全验证,用于验证身份修改密码等" + ",请勿将验证码透露给他人)"; } /** * 发送含有验证码的邮件 * @param code :验证码 * @param receiveMail : 接收者的邮箱 * @throws Exception */ public static void sendMessage(String tempCode, String receiveMail) throws Exception{ setCode(tempCode); setReceiveMailAccount(receiveMail); setContent(); // 1. 创建参数配置, 用于连接邮件服务器的参数配置 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP // 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, // 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 Session session = Session.getDefaultInstance(props); session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log // 3. 创建一封邮件 MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount); // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1 <SUF> // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, // 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); // 7. 关闭连接 transport.close(); } /** * 创建一封只包含文本的简单邮件 * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(sendMail, myName, "UTF-8")); // 3. To: 收件人(可以增加多个收件人、抄送、密送) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8")); // 4. Subject: 邮件主题 message.setSubject(Subject, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签) message.setContent(Content, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } public static String sendIdCode(String customerMail) { String tempCode = new String(); Random random = new Random(); for (int i = 0; i < 6; i++) { tempCode += random.nextInt(9) + ""; } try { MyEmail.sendMessage(tempCode, customerMail); } catch (Exception e) { e.printStackTrace(); } return tempCode; } }
false
1,864
14
1,962
11
1,932
11
1,962
11
3,017
23
false
false
false
false
false
true
34030_3
package search77; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //使用二分查找 —— 前提是有序数组(这里假设从小到大) public class BinarySearch { public static void main(String[] args) { int[] arr = {1, 8, 10, 89, 1000, 1234}; int index = binarySearch(arr, 0, arr.length - 1, 87); System.out.println(index); int[] arr_ = {1, 8, 10, 89, 1000, 1000, 1234}; ArrayList<Integer> list = binarySearch2(arr_, 0, arr_.length - 1, 1000); } /**二分查找 * * @param arr * @param left * @param right * @param value * @return 找不到下标返回-1 */ public static int binarySearch(int[] arr, int left, int right, int value) { int mid = (left + right) / 2; if (left > right) { //未匹配到的情况 return -1; } if (value > arr[mid]) { return binarySearch(arr, mid + 1, right, value); } else if (value < arr[mid]) { return binarySearch(arr, left, mid - 1, value); } else { return mid; } } //课后思考题,查找多个相同值 //思路分析:1、在找mid索引值时,不要马上返回; // 2、向mid的左右边扫描满足条件的下标,加入集合ArrayList // 3、将ArrayList返回 public static ArrayList binarySearch2(int[] arr, int left, int right, int value) { int mid = (left + right) / 2; if (left > right) { return null; } if (value > arr[mid]) { return binarySearch2(arr, mid + 1, right, value); } else if (value < arr[mid]) { return binarySearch2(arr, left, mid - 1, value); } else { ArrayList<Integer> list = new ArrayList<>(); list.add(mid); //向右查询 for (int i = mid + 1; i < arr.length; i++) { if (arr[i] == value) { list.add(i); } else { break; } } //向左查询 for (int i = mid - 1; i >= 0; i--) { if (arr[i] == value) { list.add(i); } else { break; } } return list; } } } //跟mid比过了,不需要再考虑mid位置的索引,浪费
LEstevalor/BaseAlgorithm
src/search77/BinarySearch.java
690
//课后思考题,查找多个相同值
line_comment
zh-cn
package search77; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //使用二分查找 —— 前提是有序数组(这里假设从小到大) public class BinarySearch { public static void main(String[] args) { int[] arr = {1, 8, 10, 89, 1000, 1234}; int index = binarySearch(arr, 0, arr.length - 1, 87); System.out.println(index); int[] arr_ = {1, 8, 10, 89, 1000, 1000, 1234}; ArrayList<Integer> list = binarySearch2(arr_, 0, arr_.length - 1, 1000); } /**二分查找 * * @param arr * @param left * @param right * @param value * @return 找不到下标返回-1 */ public static int binarySearch(int[] arr, int left, int right, int value) { int mid = (left + right) / 2; if (left > right) { //未匹配到的情况 return -1; } if (value > arr[mid]) { return binarySearch(arr, mid + 1, right, value); } else if (value < arr[mid]) { return binarySearch(arr, left, mid - 1, value); } else { return mid; } } //课后 <SUF> //思路分析:1、在找mid索引值时,不要马上返回; // 2、向mid的左右边扫描满足条件的下标,加入集合ArrayList // 3、将ArrayList返回 public static ArrayList binarySearch2(int[] arr, int left, int right, int value) { int mid = (left + right) / 2; if (left > right) { return null; } if (value > arr[mid]) { return binarySearch2(arr, mid + 1, right, value); } else if (value < arr[mid]) { return binarySearch2(arr, left, mid - 1, value); } else { ArrayList<Integer> list = new ArrayList<>(); list.add(mid); //向右查询 for (int i = mid + 1; i < arr.length; i++) { if (arr[i] == value) { list.add(i); } else { break; } } //向左查询 for (int i = mid - 1; i >= 0; i--) { if (arr[i] == value) { list.add(i); } else { break; } } return list; } } } //跟mid比过了,不需要再考虑mid位置的索引,浪费
false
654
10
690
11
736
10
690
11
834
20
false
false
false
false
false
true
17947_1
package io.github.ljwlgl.util; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * @author zqgan * @since 2018/9/1 http请求相关类 */ public class HttpUtil { private static final String DEFAULT_CHARSET = "UTF-8"; private static final PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager(); static { // 这边来设置并发 phccm.setDefaultMaxPerRoute(10); phccm.setMaxTotal(20); } private static CloseableHttpClient client = HttpClients.custom().setConnectionManager(phccm).build(); private static final RequestConfig CONFIG = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(10000).build(); public static String doGet(String uri) throws IOException { HttpGet get = new HttpGet(uri); get.setConfig(CONFIG); try (CloseableHttpResponse httpResponse = client.execute(get)) { return generateHttpResponse(httpResponse); } } public static String doGet(String url, Map<String, String> queryParam) throws IOException { URI uri = generateURLParams(url, queryParam); HttpGet get = new HttpGet(uri); get.setConfig(CONFIG); try (CloseableHttpResponse httpResponse = client.execute(get)) { return generateHttpResponse(httpResponse); } } /** * POST请求, json主体,可用于raw请求 * * @param url api * @param params query string * @param json 请求体内是json字符串 */ public static String doPost(String url, Map<String, String> params, String json) throws IOException { URI uri = generateURLParams(url, params); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); HttpEntity entity = new StringEntity(json, DEFAULT_CHARSET); post.setEntity(entity); post.setHeader("Content-Type", "application/json"); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } /** * POST请求, json主体 * * @param url api * @param params query string * @param json 请求体内是json字符串 * @param headers 请求header */ public static String doPost( String url, Map<String, String> params, String json, Map<String, String> headers) throws IOException { URI uri = generateURLParams(url, params); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); headers.entrySet().forEach(item -> post.addHeader(item.getKey(), item.getValue())); HttpEntity entity = new StringEntity(json, DEFAULT_CHARSET); post.setEntity(entity); post.setHeader("Content-Type", "application/json"); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } /** * POST请求,form主体 * * @param url api * @param form form表单 */ public static String doPost(String url, Map<String, String> form) throws IOException { URI uri = generateURLParams(url, null); List<NameValuePair> urlEncodedForm = generateUrlEncodeForm(form); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); HttpEntity entity = new UrlEncodedFormEntity(urlEncodedForm, DEFAULT_CHARSET); post.setEntity(entity); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } public static String doPost(String url) throws IOException { URI uri = generateURLParams(url, null); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } private static URI generateURLParams(String url, Map<String, String> params) { URI uri = null; try { URIBuilder uriBuilder = new URIBuilder(url); if (null != params) { for (Entry<String, String> entry : params.entrySet()) { uriBuilder.addParameter(entry.getKey(), entry.getValue()); } } uri = uriBuilder.build(); } catch (URISyntaxException e) { return uri; } return uri; } private static List<NameValuePair> generateUrlEncodeForm(Map<String, String> form) { if (form == null || form.size() == 0) { return null; } List<NameValuePair> list = new ArrayList<>(); for (Entry<String, String> entry : form.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return list; } private static String generateHttpResponse(CloseableHttpResponse httpResponse) throws IOException { if (httpResponse == null) { return null; } HttpEntity entity = null; entity = httpResponse.getEntity(); String res = EntityUtils.toString(entity, DEFAULT_CHARSET); httpResponse.close(); return res; } }
LJWLgl/CommonUtil
src/main/java/io/github/ljwlgl/util/HttpUtil.java
1,423
// 这边来设置并发
line_comment
zh-cn
package io.github.ljwlgl.util; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * @author zqgan * @since 2018/9/1 http请求相关类 */ public class HttpUtil { private static final String DEFAULT_CHARSET = "UTF-8"; private static final PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager(); static { // 这边 <SUF> phccm.setDefaultMaxPerRoute(10); phccm.setMaxTotal(20); } private static CloseableHttpClient client = HttpClients.custom().setConnectionManager(phccm).build(); private static final RequestConfig CONFIG = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(10000).build(); public static String doGet(String uri) throws IOException { HttpGet get = new HttpGet(uri); get.setConfig(CONFIG); try (CloseableHttpResponse httpResponse = client.execute(get)) { return generateHttpResponse(httpResponse); } } public static String doGet(String url, Map<String, String> queryParam) throws IOException { URI uri = generateURLParams(url, queryParam); HttpGet get = new HttpGet(uri); get.setConfig(CONFIG); try (CloseableHttpResponse httpResponse = client.execute(get)) { return generateHttpResponse(httpResponse); } } /** * POST请求, json主体,可用于raw请求 * * @param url api * @param params query string * @param json 请求体内是json字符串 */ public static String doPost(String url, Map<String, String> params, String json) throws IOException { URI uri = generateURLParams(url, params); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); HttpEntity entity = new StringEntity(json, DEFAULT_CHARSET); post.setEntity(entity); post.setHeader("Content-Type", "application/json"); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } /** * POST请求, json主体 * * @param url api * @param params query string * @param json 请求体内是json字符串 * @param headers 请求header */ public static String doPost( String url, Map<String, String> params, String json, Map<String, String> headers) throws IOException { URI uri = generateURLParams(url, params); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); headers.entrySet().forEach(item -> post.addHeader(item.getKey(), item.getValue())); HttpEntity entity = new StringEntity(json, DEFAULT_CHARSET); post.setEntity(entity); post.setHeader("Content-Type", "application/json"); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } /** * POST请求,form主体 * * @param url api * @param form form表单 */ public static String doPost(String url, Map<String, String> form) throws IOException { URI uri = generateURLParams(url, null); List<NameValuePair> urlEncodedForm = generateUrlEncodeForm(form); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); HttpEntity entity = new UrlEncodedFormEntity(urlEncodedForm, DEFAULT_CHARSET); post.setEntity(entity); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } public static String doPost(String url) throws IOException { URI uri = generateURLParams(url, null); HttpPost post = new HttpPost(uri); post.setConfig(CONFIG); try (CloseableHttpResponse httpResponse = client.execute(post)) { return generateHttpResponse(httpResponse); } } private static URI generateURLParams(String url, Map<String, String> params) { URI uri = null; try { URIBuilder uriBuilder = new URIBuilder(url); if (null != params) { for (Entry<String, String> entry : params.entrySet()) { uriBuilder.addParameter(entry.getKey(), entry.getValue()); } } uri = uriBuilder.build(); } catch (URISyntaxException e) { return uri; } return uri; } private static List<NameValuePair> generateUrlEncodeForm(Map<String, String> form) { if (form == null || form.size() == 0) { return null; } List<NameValuePair> list = new ArrayList<>(); for (Entry<String, String> entry : form.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return list; } private static String generateHttpResponse(CloseableHttpResponse httpResponse) throws IOException { if (httpResponse == null) { return null; } HttpEntity entity = null; entity = httpResponse.getEntity(); String res = EntityUtils.toString(entity, DEFAULT_CHARSET); httpResponse.close(); return res; } }
false
1,235
7
1,423
8
1,528
6
1,423
8
1,682
9
false
false
false
false
false
true
34454_13
package cn.org.cnnvd.pojo; import java.io.Serializable; import java.sql.Timestamp; public class Cnnvd implements Serializable{ private static final long serialVersionUID = 1L; //id private Integer id; //cnvd编号 private String cnnvdId; //cnvd名称 private String cnnvdName; //发布日期 private String publishDate; //更新时间 private String updateTime; //危害等级 private String harmLevel; //漏洞类型 private String bugType; //威胁类型 private String menaceType; //CVE 编号 private String cveId; //漏洞简介 private String bugSynopsis; //漏洞公告 private String bugNotice; //参考网址 private String referenceURL; //补丁 private String patches ; //影响实体 private String effectEntity; //数据库入库时间 private Timestamp timedate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCnnvdId() { return cnnvdId; } public void setCnnvdId(String cnnvdId) { this.cnnvdId = cnnvdId; } public String getPublishDate() { return publishDate; } public void setPublishDate(String publishDate) { this.publishDate = publishDate; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getHarmLevel() { return harmLevel; } public void setHarmLevel(String harmLevel) { this.harmLevel = harmLevel; } public String getBugType() { return bugType; } public void setBugType(String bugType) { this.bugType = bugType; } public String getMenaceType() { return menaceType; } public void setMenaceType(String menaceType) { this.menaceType = menaceType; } public String getCveId() { return cveId; } public void setCveId(String cveId) { this.cveId = cveId; } public String getBugSynopsis() { return bugSynopsis; } public void setBugSynopsis(String bugSynopsis) { this.bugSynopsis = bugSynopsis; } public String getBugNotice() { return bugNotice; } public void setBugNotice(String bugNotice) { this.bugNotice = bugNotice; } public String getReferenceURL() { return referenceURL; } public void setReferenceURL(String referenceURL) { this.referenceURL = referenceURL; } public String getPatches() { return patches; } public void setPatches(String patches) { this.patches = patches; } public String getEffectEntity() { return effectEntity; } public void setEffectEntity(String effectEntity) { this.effectEntity = effectEntity; } public Timestamp getTimedate() { return timedate; } public void setTimedate(Timestamp timedate) { this.timedate = timedate; } public String getCnnvdName() { return cnnvdName; } public void setCnnvdName(String cnnvdName) { this.cnnvdName = cnnvdName; } @Override public String toString() { return "Cnnvd [id=" + id + ", cnnvdId=" + cnnvdId + ", cnnvdName=" + cnnvdName + ", publishDate=" + publishDate + ", updateTime=" + updateTime + ", harmLevel=" + harmLevel + ", bugType=" + bugType + ", menaceType=" + menaceType + ", cveId=" + cveId + ", bugSynopsis=" + bugSynopsis + ", bugNotice=" + bugNotice + ", referenceURL=" + referenceURL + ", patches=" + patches + ", effectEntity=" + effectEntity + ", timedate=" + timedate + "]"; } }
LJYuan71/webmagic-spider
src/main/java/cn/org/cnnvd/pojo/Cnnvd.java
1,100
//影响实体
line_comment
zh-cn
package cn.org.cnnvd.pojo; import java.io.Serializable; import java.sql.Timestamp; public class Cnnvd implements Serializable{ private static final long serialVersionUID = 1L; //id private Integer id; //cnvd编号 private String cnnvdId; //cnvd名称 private String cnnvdName; //发布日期 private String publishDate; //更新时间 private String updateTime; //危害等级 private String harmLevel; //漏洞类型 private String bugType; //威胁类型 private String menaceType; //CVE 编号 private String cveId; //漏洞简介 private String bugSynopsis; //漏洞公告 private String bugNotice; //参考网址 private String referenceURL; //补丁 private String patches ; //影响 <SUF> private String effectEntity; //数据库入库时间 private Timestamp timedate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCnnvdId() { return cnnvdId; } public void setCnnvdId(String cnnvdId) { this.cnnvdId = cnnvdId; } public String getPublishDate() { return publishDate; } public void setPublishDate(String publishDate) { this.publishDate = publishDate; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getHarmLevel() { return harmLevel; } public void setHarmLevel(String harmLevel) { this.harmLevel = harmLevel; } public String getBugType() { return bugType; } public void setBugType(String bugType) { this.bugType = bugType; } public String getMenaceType() { return menaceType; } public void setMenaceType(String menaceType) { this.menaceType = menaceType; } public String getCveId() { return cveId; } public void setCveId(String cveId) { this.cveId = cveId; } public String getBugSynopsis() { return bugSynopsis; } public void setBugSynopsis(String bugSynopsis) { this.bugSynopsis = bugSynopsis; } public String getBugNotice() { return bugNotice; } public void setBugNotice(String bugNotice) { this.bugNotice = bugNotice; } public String getReferenceURL() { return referenceURL; } public void setReferenceURL(String referenceURL) { this.referenceURL = referenceURL; } public String getPatches() { return patches; } public void setPatches(String patches) { this.patches = patches; } public String getEffectEntity() { return effectEntity; } public void setEffectEntity(String effectEntity) { this.effectEntity = effectEntity; } public Timestamp getTimedate() { return timedate; } public void setTimedate(Timestamp timedate) { this.timedate = timedate; } public String getCnnvdName() { return cnnvdName; } public void setCnnvdName(String cnnvdName) { this.cnnvdName = cnnvdName; } @Override public String toString() { return "Cnnvd [id=" + id + ", cnnvdId=" + cnnvdId + ", cnnvdName=" + cnnvdName + ", publishDate=" + publishDate + ", updateTime=" + updateTime + ", harmLevel=" + harmLevel + ", bugType=" + bugType + ", menaceType=" + menaceType + ", cveId=" + cveId + ", bugSynopsis=" + bugSynopsis + ", bugNotice=" + bugNotice + ", referenceURL=" + referenceURL + ", patches=" + patches + ", effectEntity=" + effectEntity + ", timedate=" + timedate + "]"; } }
false
866
4
1,099
4
1,048
4
1,099
4
1,237
8
false
false
false
false
false
true
53539_12
package com.atguigu.spzx.manager.utils; import com.atguigu.spzx.model.entity.system.SysMenu; import java.util.ArrayList; import java.util.List; //封装树形菜单数据 public class MenuHelper { //递归实现封装过程 public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) { //sysMenuList所有菜单集合 //创建list集合,用于封装最终的数据 List<SysMenu> trees = new ArrayList<>(); //遍历所有菜单集合 for(SysMenu sysMenu:sysMenuList) { //找到递归操作入口,第一层的菜单 //条件: parent_id=0 if(sysMenu.getParentId().longValue()==0) { //根据第一层,找下层数据,使用递归完成 //写方法实现找下层过程, // 方法里面传递两个参数:第一个参数当前第一层菜单,第二个参数是所有菜单集合 trees.add(findChildren(sysMenu,sysMenuList)); } } return trees; } //递归查找下层菜单 public static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) { // SysMenu有属性 private List<SysMenu> children;封装下一层数据 sysMenu.setChildren(new ArrayList<>()); //递归查询 // sysMenu的id值 和 sysMenuList中parentId相同 for(SysMenu it:sysMenuList) { //判断id 和 parentid是否相同 if(sysMenu.getId().longValue() == it.getParentId().longValue()) { // it就是下层数据,进行封装 sysMenu.getChildren().add(findChildren(it,sysMenuList)); } } return sysMenu; } }
LLxy0/Sylar
MenuHelper.java
416
//递归查询
line_comment
zh-cn
package com.atguigu.spzx.manager.utils; import com.atguigu.spzx.model.entity.system.SysMenu; import java.util.ArrayList; import java.util.List; //封装树形菜单数据 public class MenuHelper { //递归实现封装过程 public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) { //sysMenuList所有菜单集合 //创建list集合,用于封装最终的数据 List<SysMenu> trees = new ArrayList<>(); //遍历所有菜单集合 for(SysMenu sysMenu:sysMenuList) { //找到递归操作入口,第一层的菜单 //条件: parent_id=0 if(sysMenu.getParentId().longValue()==0) { //根据第一层,找下层数据,使用递归完成 //写方法实现找下层过程, // 方法里面传递两个参数:第一个参数当前第一层菜单,第二个参数是所有菜单集合 trees.add(findChildren(sysMenu,sysMenuList)); } } return trees; } //递归查找下层菜单 public static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) { // SysMenu有属性 private List<SysMenu> children;封装下一层数据 sysMenu.setChildren(new ArrayList<>()); //递归 <SUF> // sysMenu的id值 和 sysMenuList中parentId相同 for(SysMenu it:sysMenuList) { //判断id 和 parentid是否相同 if(sysMenu.getId().longValue() == it.getParentId().longValue()) { // it就是下层数据,进行封装 sysMenu.getChildren().add(findChildren(it,sysMenuList)); } } return sysMenu; } }
false
390
5
413
5
421
4
413
5
602
12
false
false
false
false
false
true
20795_26
package org.lntu.online.model.entity; import org.joda.time.DateTime; import java.util.List; public class Student { private String id; // 学号 private String name; // 姓名 private String englishName; // 英文名 private String idCardType; // 证件类型 private String idCardNum; // 证件号码 private String sex; // 性别 private String college; // 学院 private String classInfo; // 班级 private String entranceExamArea; // 考区 private String entranceExamNum; // 入学准考证号码 private String foreignLanguage; // 外语语种 private DateTime admissionTime; // 入学日期 private DateTime graduationTime; // 毕业日期 private String homeAddress; // 家庭住址 private String tel; // 联系电话 private String studentInfoTableNum; // 学籍表号 private String whereaboutsAftergraduation; // 毕业去向 private String nationality; // 国籍 private String birthplace; // 籍贯 private DateTime birthday; // 出生年月日 private String politicalAffiliation; // 政治面貌 private String travelRange; // 乘车区间 private String nation; // 民族 private String major; // 专业 private String studentType; // 学生类型 private String entranceExamScore; // 高考总分 private String graduateSchool; // 毕业学校 private String admissionNum; // 入学录取证号 private String admissionType; // 入学方式 private String educationType; // 培养方式 private String zipCode; // 邮政编码 private String email; // 电子邮件 private String sourceOfStudent; // 学生来源 private String remarks; // 备注 private String photoUrl; // 头像照片url private List<EntranceExam> entranceExams; // 高考科目 private List<EducationExperience> educationExperiences; // 教育经历 private List<Family> familys; // 家人 private List<DisciplinaryAction> disciplinaryActions; // 处分 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEnglishName() { return englishName; } public void setEnglishName(String englishName) { this.englishName = englishName; } public String getIdCardType() { return idCardType; } public void setIdCardType(String idCardType) { this.idCardType = idCardType; } public String getIdCardNum() { return idCardNum; } public void setIdCardNum(String idCardNum) { this.idCardNum = idCardNum; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getCollege() { return college; } public void setCollege(String college) { this.college = college; } public String getClassInfo() { return classInfo; } public void setClassInfo(String classInfo) { this.classInfo = classInfo; } public String getEntranceExamArea() { return entranceExamArea; } public void setEntranceExamArea(String entranceExamArea) { this.entranceExamArea = entranceExamArea; } public String getEntranceExamNum() { return entranceExamNum; } public void setEntranceExamNum(String entranceExamNum) { this.entranceExamNum = entranceExamNum; } public String getForeignLanguage() { return foreignLanguage; } public void setForeignLanguage(String foreignLanguage) { this.foreignLanguage = foreignLanguage; } public DateTime getAdmissionTime() { return admissionTime; } public void setAdmissionTime(DateTime admissionTime) { this.admissionTime = admissionTime; } public DateTime getGraduationTime() { return graduationTime; } public void setGraduationTime(DateTime graduationTime) { this.graduationTime = graduationTime; } public String getHomeAddress() { return homeAddress; } public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getStudentInfoTableNum() { return studentInfoTableNum; } public void setStudentInfoTableNum(String studentInfoTableNum) { this.studentInfoTableNum = studentInfoTableNum; } public String getWhereaboutsAftergraduation() { return whereaboutsAftergraduation; } public void setWhereaboutsAftergraduation(String whereaboutsAftergraduation) { this.whereaboutsAftergraduation = whereaboutsAftergraduation; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public String getBirthplace() { return birthplace; } public void setBirthplace(String birthplace) { this.birthplace = birthplace; } public DateTime getBirthday() { return birthday; } public void setBirthday(DateTime birthday) { this.birthday = birthday; } public String getPoliticalAffiliation() { return politicalAffiliation; } public void setPoliticalAffiliation(String politicalAffiliation) { this.politicalAffiliation = politicalAffiliation; } public String getTravelRange() { return travelRange; } public void setTravelRange(String travelRange) { this.travelRange = travelRange; } public String getNation() { return nation; } public void setNation(String nation) { this.nation = nation; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getStudentType() { return studentType; } public void setStudentType(String studentType) { this.studentType = studentType; } public String getEntranceExamScore() { return entranceExamScore; } public void setEntranceExamScore(String entranceExamScore) { this.entranceExamScore = entranceExamScore; } public String getGraduateSchool() { return graduateSchool; } public void setGraduateSchool(String graduateSchool) { this.graduateSchool = graduateSchool; } public String getAdmissionNum() { return admissionNum; } public void setAdmissionNum(String admissionNum) { this.admissionNum = admissionNum; } public String getAdmissionType() { return admissionType; } public void setAdmissionType(String admissionType) { this.admissionType = admissionType; } public String getEducationType() { return educationType; } public void setEducationType(String educationType) { this.educationType = educationType; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSourceOfStudent() { return sourceOfStudent; } public void setSourceOfStudent(String sourceOfStudent) { this.sourceOfStudent = sourceOfStudent; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } public List<EntranceExam> getEntranceExams() { return entranceExams; } public void setEntranceExams(List<EntranceExam> entranceExams) { this.entranceExams = entranceExams; } public List<EducationExperience> getEducationExperiences() { return educationExperiences; } public void setEducationExperiences(List<EducationExperience> educationExperiences) { this.educationExperiences = educationExperiences; } public List<Family> getFamilys() { return familys; } public void setFamilys(List<Family> familys) { this.familys = familys; } public List<DisciplinaryAction> getDisciplinaryActions() { return disciplinaryActions; } public void setDisciplinaryActions(List<DisciplinaryAction> disciplinaryActions) { this.disciplinaryActions = disciplinaryActions; } public static class EntranceExam { private String name; private String score; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } } public static class EducationExperience { private DateTime startTime; private DateTime endTime; private String schoolInfo; private String witness; // 证明人 public DateTime getStartTime() { return startTime; } public void setStartTime(DateTime startTime) { this.startTime = startTime; } public DateTime getEndTime() { return endTime; } public void setEndTime(DateTime endTime) { this.endTime = endTime; } public String getSchoolInfo() { return schoolInfo; } public void setSchoolInfo(String schoolInfo) { this.schoolInfo = schoolInfo; } public String getWitness() { return witness; } public void setWitness(String witness) { this.witness = witness; } } public static class Family { private String name; private String relationship; private String politicalAffiliation; // 政治面貌 private String job; // 职业 private String post; // 职务 private String workLocation; // 工作地点 private String tel; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRelationship() { return relationship; } public void setRelationship(String relationship) { this.relationship = relationship; } public String getPoliticalAffiliation() { return politicalAffiliation; } public void setPoliticalAffiliation(String politicalAffiliation) { this.politicalAffiliation = politicalAffiliation; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } public String getWorkLocation() { return workLocation; } public void setWorkLocation(String workLocation) { this.workLocation = workLocation; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } } public static class DisciplinaryAction { private String level; // 处分级别 private DateTime createTime; // 处分日期 private String createReason; // 处分原因 private DateTime cancelTime; // 撤销时间 private String cancelReason; // 撤销原因 private String state; // 状态 private String remarks; // 备注 public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public DateTime getCreateTime() { return createTime; } public void setCreateTime(DateTime createTime) { this.createTime = createTime; } public String getCreateReason() { return createReason; } public void setCreateReason(String createReason) { this.createReason = createReason; } public DateTime getCancelTime() { return cancelTime; } public void setCancelTime(DateTime cancelTime) { this.cancelTime = cancelTime; } public String getCancelReason() { return cancelReason; } public void setCancelReason(String cancelReason) { this.cancelReason = cancelReason; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } } }
LNTUORG/LNTUOnline-Android
app/src/main/java/org/lntu/online/model/entity/Student.java
3,070
// 证明人
line_comment
zh-cn
package org.lntu.online.model.entity; import org.joda.time.DateTime; import java.util.List; public class Student { private String id; // 学号 private String name; // 姓名 private String englishName; // 英文名 private String idCardType; // 证件类型 private String idCardNum; // 证件号码 private String sex; // 性别 private String college; // 学院 private String classInfo; // 班级 private String entranceExamArea; // 考区 private String entranceExamNum; // 入学准考证号码 private String foreignLanguage; // 外语语种 private DateTime admissionTime; // 入学日期 private DateTime graduationTime; // 毕业日期 private String homeAddress; // 家庭住址 private String tel; // 联系电话 private String studentInfoTableNum; // 学籍表号 private String whereaboutsAftergraduation; // 毕业去向 private String nationality; // 国籍 private String birthplace; // 籍贯 private DateTime birthday; // 出生年月日 private String politicalAffiliation; // 政治面貌 private String travelRange; // 乘车区间 private String nation; // 民族 private String major; // 专业 private String studentType; // 学生类型 private String entranceExamScore; // 高考总分 private String graduateSchool; // 毕业学校 private String admissionNum; // 入学录取证号 private String admissionType; // 入学方式 private String educationType; // 培养方式 private String zipCode; // 邮政编码 private String email; // 电子邮件 private String sourceOfStudent; // 学生来源 private String remarks; // 备注 private String photoUrl; // 头像照片url private List<EntranceExam> entranceExams; // 高考科目 private List<EducationExperience> educationExperiences; // 教育经历 private List<Family> familys; // 家人 private List<DisciplinaryAction> disciplinaryActions; // 处分 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEnglishName() { return englishName; } public void setEnglishName(String englishName) { this.englishName = englishName; } public String getIdCardType() { return idCardType; } public void setIdCardType(String idCardType) { this.idCardType = idCardType; } public String getIdCardNum() { return idCardNum; } public void setIdCardNum(String idCardNum) { this.idCardNum = idCardNum; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getCollege() { return college; } public void setCollege(String college) { this.college = college; } public String getClassInfo() { return classInfo; } public void setClassInfo(String classInfo) { this.classInfo = classInfo; } public String getEntranceExamArea() { return entranceExamArea; } public void setEntranceExamArea(String entranceExamArea) { this.entranceExamArea = entranceExamArea; } public String getEntranceExamNum() { return entranceExamNum; } public void setEntranceExamNum(String entranceExamNum) { this.entranceExamNum = entranceExamNum; } public String getForeignLanguage() { return foreignLanguage; } public void setForeignLanguage(String foreignLanguage) { this.foreignLanguage = foreignLanguage; } public DateTime getAdmissionTime() { return admissionTime; } public void setAdmissionTime(DateTime admissionTime) { this.admissionTime = admissionTime; } public DateTime getGraduationTime() { return graduationTime; } public void setGraduationTime(DateTime graduationTime) { this.graduationTime = graduationTime; } public String getHomeAddress() { return homeAddress; } public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getStudentInfoTableNum() { return studentInfoTableNum; } public void setStudentInfoTableNum(String studentInfoTableNum) { this.studentInfoTableNum = studentInfoTableNum; } public String getWhereaboutsAftergraduation() { return whereaboutsAftergraduation; } public void setWhereaboutsAftergraduation(String whereaboutsAftergraduation) { this.whereaboutsAftergraduation = whereaboutsAftergraduation; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public String getBirthplace() { return birthplace; } public void setBirthplace(String birthplace) { this.birthplace = birthplace; } public DateTime getBirthday() { return birthday; } public void setBirthday(DateTime birthday) { this.birthday = birthday; } public String getPoliticalAffiliation() { return politicalAffiliation; } public void setPoliticalAffiliation(String politicalAffiliation) { this.politicalAffiliation = politicalAffiliation; } public String getTravelRange() { return travelRange; } public void setTravelRange(String travelRange) { this.travelRange = travelRange; } public String getNation() { return nation; } public void setNation(String nation) { this.nation = nation; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getStudentType() { return studentType; } public void setStudentType(String studentType) { this.studentType = studentType; } public String getEntranceExamScore() { return entranceExamScore; } public void setEntranceExamScore(String entranceExamScore) { this.entranceExamScore = entranceExamScore; } public String getGraduateSchool() { return graduateSchool; } public void setGraduateSchool(String graduateSchool) { this.graduateSchool = graduateSchool; } public String getAdmissionNum() { return admissionNum; } public void setAdmissionNum(String admissionNum) { this.admissionNum = admissionNum; } public String getAdmissionType() { return admissionType; } public void setAdmissionType(String admissionType) { this.admissionType = admissionType; } public String getEducationType() { return educationType; } public void setEducationType(String educationType) { this.educationType = educationType; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSourceOfStudent() { return sourceOfStudent; } public void setSourceOfStudent(String sourceOfStudent) { this.sourceOfStudent = sourceOfStudent; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } public List<EntranceExam> getEntranceExams() { return entranceExams; } public void setEntranceExams(List<EntranceExam> entranceExams) { this.entranceExams = entranceExams; } public List<EducationExperience> getEducationExperiences() { return educationExperiences; } public void setEducationExperiences(List<EducationExperience> educationExperiences) { this.educationExperiences = educationExperiences; } public List<Family> getFamilys() { return familys; } public void setFamilys(List<Family> familys) { this.familys = familys; } public List<DisciplinaryAction> getDisciplinaryActions() { return disciplinaryActions; } public void setDisciplinaryActions(List<DisciplinaryAction> disciplinaryActions) { this.disciplinaryActions = disciplinaryActions; } public static class EntranceExam { private String name; private String score; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } } public static class EducationExperience { private DateTime startTime; private DateTime endTime; private String schoolInfo; private String witness; // 证明 <SUF> public DateTime getStartTime() { return startTime; } public void setStartTime(DateTime startTime) { this.startTime = startTime; } public DateTime getEndTime() { return endTime; } public void setEndTime(DateTime endTime) { this.endTime = endTime; } public String getSchoolInfo() { return schoolInfo; } public void setSchoolInfo(String schoolInfo) { this.schoolInfo = schoolInfo; } public String getWitness() { return witness; } public void setWitness(String witness) { this.witness = witness; } } public static class Family { private String name; private String relationship; private String politicalAffiliation; // 政治面貌 private String job; // 职业 private String post; // 职务 private String workLocation; // 工作地点 private String tel; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRelationship() { return relationship; } public void setRelationship(String relationship) { this.relationship = relationship; } public String getPoliticalAffiliation() { return politicalAffiliation; } public void setPoliticalAffiliation(String politicalAffiliation) { this.politicalAffiliation = politicalAffiliation; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } public String getWorkLocation() { return workLocation; } public void setWorkLocation(String workLocation) { this.workLocation = workLocation; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } } public static class DisciplinaryAction { private String level; // 处分级别 private DateTime createTime; // 处分日期 private String createReason; // 处分原因 private DateTime cancelTime; // 撤销时间 private String cancelReason; // 撤销原因 private String state; // 状态 private String remarks; // 备注 public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public DateTime getCreateTime() { return createTime; } public void setCreateTime(DateTime createTime) { this.createTime = createTime; } public String getCreateReason() { return createReason; } public void setCreateReason(String createReason) { this.createReason = createReason; } public DateTime getCancelTime() { return cancelTime; } public void setCancelTime(DateTime cancelTime) { this.cancelTime = cancelTime; } public String getCancelReason() { return cancelReason; } public void setCancelReason(String cancelReason) { this.cancelReason = cancelReason; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } } }
false
2,859
4
3,070
5
3,212
4
3,070
5
3,911
7
false
false
false
false
false
true
13827_9
/** * */ package com.hspedu.encap; public class Encapsulation282 { public static void main(String[] args) { penson p1 = new penson(); //p1.name="jack";//公开的访问修饰符 可以赋予名字 // p1.age=3000;这里不行因为是private 只能再同包同类下修改,这里不同类 p1.setName("jack000000"); p1.setAge(250); p1.setSalary(5000); String res = p1.info(); System.out.println(res); // System.out.println(p1.setSalary(2000));不能通过set查看,只能通过下面的get查看 System.out.println(p1.getSalary()); System.out.println("采用构造器后======"); penson p2 = new penson("小王",242,2900); System.out.println(p2.info()); } } /* 那么在 java 中如何实现这种类似的控制呢? 请大家看一个小程序(com.hspedu.encap: Encapsulation01.java), 不能随便查看人的年龄,工资等隐私,并对设置的年龄进行合理的验证。年龄合理就设置,否则给默认 年龄, 必须在 1-120, 年龄, 工资不能直接查看 , name 的长度在 2-6 字符 之间 */ class penson{ public String name;//名字公开 private int age;//年纪隐私 private double salary;//撒那儿瑞 工资隐私 //采用构造器,传入setXxx方法 /** * @param name * @param age * @param salary */ /** * */ public penson() { // TODO 自动生成的构造函数存根 } public penson(String name, int age, double salary) { setAge(age); setName(name); setSalary(salary); } //这两个方法setXxx和getXxx方法手写太慢了 //用快捷键 alt+/生成单个get set //alt+shift+s,r 生成一对 //然后根据要求来完善我们的代码 /** * @return name */ public String getName() { return name; } /** * @return age */ public int getAge() { return age; } /** * @param age 要设置的 age */ public void setAge(int age) { if (age>=1&&age<=120) {//合理范围 this.age=age; }else { System.out.println("您输入的年纪有误"); //给一个默认年龄 this.age = 18; } // this.age = age;这里不能有return 不然输入年龄有误时 还是不会变成默认值 } /** * @return salary */ public double getSalary() { //可以增加读当前对象的权限判断 return salary; } /** * @param salary 要设置的 salary */ public void setSalary(double salary) { this.salary = salary; } /** * @param name 要设置的 name */ public void setName(String name) { //加入对数据的校验,相当于增加了雨雾逻辑 if (name.length()>=2&&name.length()<=6) { this.name=name; }else { System.out.println("你输入的名字有误"); this.name = "张三"; } // this.name = name;//这里不能有返回 不然输入有误时 不会返回张三 } //写一个方法,返回属性信息 public String info() { return "信息为 name="+name+" age="+age+" salary="+salary; } }
LOGHE/MYHOME
Encapsulation282.java
1,010
// TODO 自动生成的构造函数存根
line_comment
zh-cn
/** * */ package com.hspedu.encap; public class Encapsulation282 { public static void main(String[] args) { penson p1 = new penson(); //p1.name="jack";//公开的访问修饰符 可以赋予名字 // p1.age=3000;这里不行因为是private 只能再同包同类下修改,这里不同类 p1.setName("jack000000"); p1.setAge(250); p1.setSalary(5000); String res = p1.info(); System.out.println(res); // System.out.println(p1.setSalary(2000));不能通过set查看,只能通过下面的get查看 System.out.println(p1.getSalary()); System.out.println("采用构造器后======"); penson p2 = new penson("小王",242,2900); System.out.println(p2.info()); } } /* 那么在 java 中如何实现这种类似的控制呢? 请大家看一个小程序(com.hspedu.encap: Encapsulation01.java), 不能随便查看人的年龄,工资等隐私,并对设置的年龄进行合理的验证。年龄合理就设置,否则给默认 年龄, 必须在 1-120, 年龄, 工资不能直接查看 , name 的长度在 2-6 字符 之间 */ class penson{ public String name;//名字公开 private int age;//年纪隐私 private double salary;//撒那儿瑞 工资隐私 //采用构造器,传入setXxx方法 /** * @param name * @param age * @param salary */ /** * */ public penson() { // TO <SUF> } public penson(String name, int age, double salary) { setAge(age); setName(name); setSalary(salary); } //这两个方法setXxx和getXxx方法手写太慢了 //用快捷键 alt+/生成单个get set //alt+shift+s,r 生成一对 //然后根据要求来完善我们的代码 /** * @return name */ public String getName() { return name; } /** * @return age */ public int getAge() { return age; } /** * @param age 要设置的 age */ public void setAge(int age) { if (age>=1&&age<=120) {//合理范围 this.age=age; }else { System.out.println("您输入的年纪有误"); //给一个默认年龄 this.age = 18; } // this.age = age;这里不能有return 不然输入年龄有误时 还是不会变成默认值 } /** * @return salary */ public double getSalary() { //可以增加读当前对象的权限判断 return salary; } /** * @param salary 要设置的 salary */ public void setSalary(double salary) { this.salary = salary; } /** * @param name 要设置的 name */ public void setName(String name) { //加入对数据的校验,相当于增加了雨雾逻辑 if (name.length()>=2&&name.length()<=6) { this.name=name; }else { System.out.println("你输入的名字有误"); this.name = "张三"; } // this.name = name;//这里不能有返回 不然输入有误时 不会返回张三 } //写一个方法,返回属性信息 public String info() { return "信息为 name="+name+" age="+age+" salary="+salary; } }
false
841
8
1,010
10
977
8
1,010
10
1,315
14
false
false
false
false
false
true
44839_4
package com.lodz.android.agiledev.ui.rv.decoration; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.lodz.android.agiledev.R; import com.lodz.android.agiledev.ui.main.MainActivity; import com.lodz.android.agiledev.ui.rv.drag.LayoutManagerPopupWindow; import com.lodz.android.agiledev.ui.rv.drag.OrientationPopupWindow; import com.lodz.android.component.base.activity.BaseActivity; import com.lodz.android.component.widget.adapter.decoration.StickyFixItemDecoration; import com.lodz.android.component.widget.base.TitleBarLayout; import com.lodz.android.core.utils.ArrayUtils; import com.lodz.android.core.utils.DensityUtils; import java.util.ArrayList; import java.util.List; import androidx.annotation.StringRes; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import butterknife.BindView; import butterknife.ButterKnife; /** * RV装饰器测试类 * Created by zhouL on 2018/2/7. */ public class ItemDecorationTestActivity extends BaseActivity{ public static void start(Context context) { Intent starter = new Intent(context, ItemDecorationTestActivity.class); context.startActivity(starter); } /** 列表 */ @BindView(R.id.recycler_view) RecyclerView mRecyclerView; /** 适配器 */ private ItemDecorationTestAdapter mAdapter; private List<String> mList; /** 当前布局 */ @LayoutManagerPopupWindow.LayoutManagerType private int mCurrentLayoutManagerType = LayoutManagerPopupWindow.TYPE_LINEAR; /** 当前是否纵向 */ private boolean mIsVertical = true; @Override protected int getLayoutId() { return R.layout.activity_item_decoration_test_layout; } @Override protected void findViews(Bundle savedInstanceState) { ButterKnife.bind(this); initTitleBar(getTitleBarLayout()); initRecyclerView(); } /** 初始化标题栏 */ private void initTitleBar(TitleBarLayout titleBarLayout) { titleBarLayout.setTitleName(getIntent().getStringExtra(MainActivity.EXTRA_TITLE_NAME)); titleBarLayout.needExpandView(true); titleBarLayout.addExpandView(getExpandView()); } private void initRecyclerView() { mAdapter = new ItemDecorationTestAdapter(getContext()); mRecyclerView.setLayoutManager(getLayoutManager()); mAdapter.onAttachedToRecyclerView(mRecyclerView);// 如果使用网格布局请设置此方法 mRecyclerView.addItemDecoration(getItemDecoration()); mRecyclerView.setHasFixedSize(true); mRecyclerView.setAdapter(mAdapter); } /** 获取装饰器 */ private RecyclerView.ItemDecoration getItemDecoration() { // 外围分割线 // return RoundItemDecoration.create(getContext()) // .setTopDividerRes(3, R.color.color_9a9a9a, R.color.color_ea413c, 15) // .setBottomDividerRes(3, R.color.color_9a9a9a, R.color.white, 15) // .setLeftDividerRes(3, R.color.color_9a9a9a, R.color.color_00a0e9, 5) // .setRightDividerRes(3, R.color.color_9a9a9a, R.color.color_ff00ff, 5); // return RoundItemDecoration.createBottomDivider(getContext(), 1, R.color.color_3f51b5, 0, 15); // 网格分割线 // return GridItemDecoration.createDividerRes(getContext(), 1, R.color.color_00a0e9); // 分组 // return SectionItemDecoration.<String>create(getContext()) // .setOnSectionCallback(new SectionItemDecoration.OnSectionCallback<String>() { // @Override // public String getSourceItem(int position) { // return mList.get(position); // } // }) // .setSectionTextSize(22) // .setSectionTextTypeface(Typeface.DEFAULT_BOLD) // .setSectionTextColorRes(R.color.white) // .setSectionTextPaddingLeftDp(8) // .setSectionBgColorRes(R.color.color_ea8380); // 粘黏标签 // return StickyItemDecoration.<String>create(getContext()) // .setOnSectionCallback(new SectionItemDecoration.OnSectionCallback<String>() { // @Override // public String getSourceItem(int position) { // return mList.get(position); // } // }) // .setSectionTextSize(22) // .setSectionHeight(40) // .setSectionTextTypeface(Typeface.DEFAULT_BOLD) // .setSectionTextColorRes(R.color.white) // .setSectionTextPaddingLeftDp(8) // .setSectionBgColorRes(R.color.color_ea8380); // 固定数据 List<String> sections = ArrayUtils.arrayToList(new String[]{"曼联", "阿森纳", "切尔西", "利物浦"}); List<List<String>> source = new ArrayList<>(); source.add(ArrayUtils.arrayToList(new String[]{"贝克汉姆", "吉格斯", "斯科尔斯", "鲁尼", "费迪南德", "范德萨", "卡里克", "罗伊基恩", "埃弗拉"})); source.add(ArrayUtils.arrayToList(new String[]{"亨利", "皮雷", "博格坎普", "莱曼", "维埃拉", "罗西基", "阿什利科尔", "索尔坎贝尔"})); source.add(ArrayUtils.arrayToList(new String[]{"兰帕德", "切赫", "特里", "乔科尔", "德罗巴", "巴拉克", "舍甫琴科", "罗本"})); source.add(ArrayUtils.arrayToList(new String[]{"欧文", "杰拉德", "卡拉格", "福勒", "雷纳", "阿隆索", "库伊特", "里瑟"})); // 固定数据分组 // return SectionFixItemDecoration.create(getContext(), sections, source) // .setSectionTextSize(22) // .setSectionHeight(40) // .setSectionTextTypeface(Typeface.DEFAULT_BOLD) // .setSectionTextColorRes(R.color.white) // .setSectionTextPaddingLeftDp(8) // .setSectionBgColorRes(R.color.color_ffa630); // 固定数据粘黏 return StickyFixItemDecoration.create(getContext(), sections, source) .setSectionTextSize(22) .setSectionHeight(40) .setSectionTextTypeface(Typeface.DEFAULT_BOLD) .setSectionTextColorRes(R.color.white) .setSectionTextPaddingLeftDp(8) .setSectionBgColorRes(R.color.color_ea8380); } @Override protected void clickBackBtn() { super.clickBackBtn(); finish(); } @Override protected void setListeners() { super.setListeners(); } @Override protected void initData() { super.initData(); mList = getList(); // List<String> title = ArrayUtils.arrayToList(new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9"}); // mList = ArrayUtils.groupList(mList, title); mAdapter.setData(mList); mAdapter.notifyDataSetChanged(); showStatusCompleted(); } private List<String> getList(){ // List<String> list = new ArrayList<>(); // for (int i = 0; i < 87; i++) { // list.add((i + 1) + ""); // } List<String> list = ArrayUtils.arrayToList(new String[]{"贝克汉姆", "吉格斯", "斯科尔斯", "鲁尼", "费迪南德", "范德萨", "卡里克", "罗伊基恩", "埃弗拉" , "亨利", "皮雷", "博格坎普", "莱曼", "维埃拉", "罗西基", "阿什利科尔", "索尔坎贝尔" , "兰帕德", "切赫", "特里", "乔科尔", "德罗巴", "巴拉克", "舍甫琴科", "罗本" , "欧文", "杰拉德", "卡拉格", "福勒", "雷纳", "阿隆索", "库伊特", "里瑟"}); return list; } /** 获取扩展view */ private View getExpandView() { LinearLayout linearLayout = new LinearLayout(getContext()); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); linearLayout.setLayoutParams(layoutParams); linearLayout.setOrientation(LinearLayout.HORIZONTAL); final TextView orientationTv = getTextView(R.string.drag_orientation);//方向 orientationTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showOrientationPopupWindow(v); } }); linearLayout.addView(orientationTv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); final TextView LayoutManagerTv = getTextView(R.string.drag_layout_manager);// 布局 LayoutManagerTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showLayoutManagerPopupWindow(v); } }); linearLayout.addView(LayoutManagerTv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); return linearLayout; } /** 获取TextView */ private TextView getTextView(@StringRes int resId) { final TextView textView = new TextView(getContext()); textView.setText(resId); textView.setPadding(DensityUtils.dp2px(getContext(), 6), 0 , DensityUtils.dp2px(getContext(), 6), 0); textView.setTextColor(ContextCompat.getColor(getContext(), R.color.white)); return textView; } /** 显示方向的PopupWindow */ private void showOrientationPopupWindow(View view) { OrientationPopupWindow popupWindow = new OrientationPopupWindow(getContext()); popupWindow.setIsVertical(mIsVertical); popupWindow.getPopup().showAsDropDown(view, -50, 20); popupWindow.setListener(new OrientationPopupWindow.Listener() { @Override public void onClick(PopupWindow popupWindow, boolean isVertical) { mIsVertical = isVertical; mRecyclerView.setLayoutManager(getLayoutManager()); mAdapter.notifyDataSetChanged(); popupWindow.dismiss(); } }); } /** 显示布局的PopupWindow */ private void showLayoutManagerPopupWindow(View view) { LayoutManagerPopupWindow popupWindow = new LayoutManagerPopupWindow(getContext()); popupWindow.setLayoutManagerType(mCurrentLayoutManagerType); popupWindow.getPopup().showAsDropDown(view, 0, 20); popupWindow.setListener(new LayoutManagerPopupWindow.Listener() { @Override public void onClick(PopupWindow popupWindow, @LayoutManagerPopupWindow.LayoutManagerType int type) { mCurrentLayoutManagerType = type; mRecyclerView.setLayoutManager(getLayoutManager()); mAdapter.notifyDataSetChanged(); popupWindow.dismiss(); } }); } private RecyclerView.LayoutManager getLayoutManager() { if (mCurrentLayoutManagerType == LayoutManagerPopupWindow.TYPE_GRID){ GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4); layoutManager.setOrientation(mIsVertical ? RecyclerView.VERTICAL : RecyclerView.HORIZONTAL); return layoutManager; } if (mCurrentLayoutManagerType == LayoutManagerPopupWindow.TYPE_STAGGERED){ return new StaggeredGridLayoutManager(4, mIsVertical ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.HORIZONTAL); } LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); layoutManager.setOrientation(mIsVertical ? RecyclerView.VERTICAL : RecyclerView.HORIZONTAL); return layoutManager; } }
LZ9/AgileDev
app/src/main/java/com/lodz/android/agiledev/ui/rv/decoration/ItemDecorationTestActivity.java
3,078
/** 当前是否纵向 */
block_comment
zh-cn
package com.lodz.android.agiledev.ui.rv.decoration; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.lodz.android.agiledev.R; import com.lodz.android.agiledev.ui.main.MainActivity; import com.lodz.android.agiledev.ui.rv.drag.LayoutManagerPopupWindow; import com.lodz.android.agiledev.ui.rv.drag.OrientationPopupWindow; import com.lodz.android.component.base.activity.BaseActivity; import com.lodz.android.component.widget.adapter.decoration.StickyFixItemDecoration; import com.lodz.android.component.widget.base.TitleBarLayout; import com.lodz.android.core.utils.ArrayUtils; import com.lodz.android.core.utils.DensityUtils; import java.util.ArrayList; import java.util.List; import androidx.annotation.StringRes; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import butterknife.BindView; import butterknife.ButterKnife; /** * RV装饰器测试类 * Created by zhouL on 2018/2/7. */ public class ItemDecorationTestActivity extends BaseActivity{ public static void start(Context context) { Intent starter = new Intent(context, ItemDecorationTestActivity.class); context.startActivity(starter); } /** 列表 */ @BindView(R.id.recycler_view) RecyclerView mRecyclerView; /** 适配器 */ private ItemDecorationTestAdapter mAdapter; private List<String> mList; /** 当前布局 */ @LayoutManagerPopupWindow.LayoutManagerType private int mCurrentLayoutManagerType = LayoutManagerPopupWindow.TYPE_LINEAR; /** 当前是 <SUF>*/ private boolean mIsVertical = true; @Override protected int getLayoutId() { return R.layout.activity_item_decoration_test_layout; } @Override protected void findViews(Bundle savedInstanceState) { ButterKnife.bind(this); initTitleBar(getTitleBarLayout()); initRecyclerView(); } /** 初始化标题栏 */ private void initTitleBar(TitleBarLayout titleBarLayout) { titleBarLayout.setTitleName(getIntent().getStringExtra(MainActivity.EXTRA_TITLE_NAME)); titleBarLayout.needExpandView(true); titleBarLayout.addExpandView(getExpandView()); } private void initRecyclerView() { mAdapter = new ItemDecorationTestAdapter(getContext()); mRecyclerView.setLayoutManager(getLayoutManager()); mAdapter.onAttachedToRecyclerView(mRecyclerView);// 如果使用网格布局请设置此方法 mRecyclerView.addItemDecoration(getItemDecoration()); mRecyclerView.setHasFixedSize(true); mRecyclerView.setAdapter(mAdapter); } /** 获取装饰器 */ private RecyclerView.ItemDecoration getItemDecoration() { // 外围分割线 // return RoundItemDecoration.create(getContext()) // .setTopDividerRes(3, R.color.color_9a9a9a, R.color.color_ea413c, 15) // .setBottomDividerRes(3, R.color.color_9a9a9a, R.color.white, 15) // .setLeftDividerRes(3, R.color.color_9a9a9a, R.color.color_00a0e9, 5) // .setRightDividerRes(3, R.color.color_9a9a9a, R.color.color_ff00ff, 5); // return RoundItemDecoration.createBottomDivider(getContext(), 1, R.color.color_3f51b5, 0, 15); // 网格分割线 // return GridItemDecoration.createDividerRes(getContext(), 1, R.color.color_00a0e9); // 分组 // return SectionItemDecoration.<String>create(getContext()) // .setOnSectionCallback(new SectionItemDecoration.OnSectionCallback<String>() { // @Override // public String getSourceItem(int position) { // return mList.get(position); // } // }) // .setSectionTextSize(22) // .setSectionTextTypeface(Typeface.DEFAULT_BOLD) // .setSectionTextColorRes(R.color.white) // .setSectionTextPaddingLeftDp(8) // .setSectionBgColorRes(R.color.color_ea8380); // 粘黏标签 // return StickyItemDecoration.<String>create(getContext()) // .setOnSectionCallback(new SectionItemDecoration.OnSectionCallback<String>() { // @Override // public String getSourceItem(int position) { // return mList.get(position); // } // }) // .setSectionTextSize(22) // .setSectionHeight(40) // .setSectionTextTypeface(Typeface.DEFAULT_BOLD) // .setSectionTextColorRes(R.color.white) // .setSectionTextPaddingLeftDp(8) // .setSectionBgColorRes(R.color.color_ea8380); // 固定数据 List<String> sections = ArrayUtils.arrayToList(new String[]{"曼联", "阿森纳", "切尔西", "利物浦"}); List<List<String>> source = new ArrayList<>(); source.add(ArrayUtils.arrayToList(new String[]{"贝克汉姆", "吉格斯", "斯科尔斯", "鲁尼", "费迪南德", "范德萨", "卡里克", "罗伊基恩", "埃弗拉"})); source.add(ArrayUtils.arrayToList(new String[]{"亨利", "皮雷", "博格坎普", "莱曼", "维埃拉", "罗西基", "阿什利科尔", "索尔坎贝尔"})); source.add(ArrayUtils.arrayToList(new String[]{"兰帕德", "切赫", "特里", "乔科尔", "德罗巴", "巴拉克", "舍甫琴科", "罗本"})); source.add(ArrayUtils.arrayToList(new String[]{"欧文", "杰拉德", "卡拉格", "福勒", "雷纳", "阿隆索", "库伊特", "里瑟"})); // 固定数据分组 // return SectionFixItemDecoration.create(getContext(), sections, source) // .setSectionTextSize(22) // .setSectionHeight(40) // .setSectionTextTypeface(Typeface.DEFAULT_BOLD) // .setSectionTextColorRes(R.color.white) // .setSectionTextPaddingLeftDp(8) // .setSectionBgColorRes(R.color.color_ffa630); // 固定数据粘黏 return StickyFixItemDecoration.create(getContext(), sections, source) .setSectionTextSize(22) .setSectionHeight(40) .setSectionTextTypeface(Typeface.DEFAULT_BOLD) .setSectionTextColorRes(R.color.white) .setSectionTextPaddingLeftDp(8) .setSectionBgColorRes(R.color.color_ea8380); } @Override protected void clickBackBtn() { super.clickBackBtn(); finish(); } @Override protected void setListeners() { super.setListeners(); } @Override protected void initData() { super.initData(); mList = getList(); // List<String> title = ArrayUtils.arrayToList(new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9"}); // mList = ArrayUtils.groupList(mList, title); mAdapter.setData(mList); mAdapter.notifyDataSetChanged(); showStatusCompleted(); } private List<String> getList(){ // List<String> list = new ArrayList<>(); // for (int i = 0; i < 87; i++) { // list.add((i + 1) + ""); // } List<String> list = ArrayUtils.arrayToList(new String[]{"贝克汉姆", "吉格斯", "斯科尔斯", "鲁尼", "费迪南德", "范德萨", "卡里克", "罗伊基恩", "埃弗拉" , "亨利", "皮雷", "博格坎普", "莱曼", "维埃拉", "罗西基", "阿什利科尔", "索尔坎贝尔" , "兰帕德", "切赫", "特里", "乔科尔", "德罗巴", "巴拉克", "舍甫琴科", "罗本" , "欧文", "杰拉德", "卡拉格", "福勒", "雷纳", "阿隆索", "库伊特", "里瑟"}); return list; } /** 获取扩展view */ private View getExpandView() { LinearLayout linearLayout = new LinearLayout(getContext()); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); linearLayout.setLayoutParams(layoutParams); linearLayout.setOrientation(LinearLayout.HORIZONTAL); final TextView orientationTv = getTextView(R.string.drag_orientation);//方向 orientationTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showOrientationPopupWindow(v); } }); linearLayout.addView(orientationTv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); final TextView LayoutManagerTv = getTextView(R.string.drag_layout_manager);// 布局 LayoutManagerTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showLayoutManagerPopupWindow(v); } }); linearLayout.addView(LayoutManagerTv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); return linearLayout; } /** 获取TextView */ private TextView getTextView(@StringRes int resId) { final TextView textView = new TextView(getContext()); textView.setText(resId); textView.setPadding(DensityUtils.dp2px(getContext(), 6), 0 , DensityUtils.dp2px(getContext(), 6), 0); textView.setTextColor(ContextCompat.getColor(getContext(), R.color.white)); return textView; } /** 显示方向的PopupWindow */ private void showOrientationPopupWindow(View view) { OrientationPopupWindow popupWindow = new OrientationPopupWindow(getContext()); popupWindow.setIsVertical(mIsVertical); popupWindow.getPopup().showAsDropDown(view, -50, 20); popupWindow.setListener(new OrientationPopupWindow.Listener() { @Override public void onClick(PopupWindow popupWindow, boolean isVertical) { mIsVertical = isVertical; mRecyclerView.setLayoutManager(getLayoutManager()); mAdapter.notifyDataSetChanged(); popupWindow.dismiss(); } }); } /** 显示布局的PopupWindow */ private void showLayoutManagerPopupWindow(View view) { LayoutManagerPopupWindow popupWindow = new LayoutManagerPopupWindow(getContext()); popupWindow.setLayoutManagerType(mCurrentLayoutManagerType); popupWindow.getPopup().showAsDropDown(view, 0, 20); popupWindow.setListener(new LayoutManagerPopupWindow.Listener() { @Override public void onClick(PopupWindow popupWindow, @LayoutManagerPopupWindow.LayoutManagerType int type) { mCurrentLayoutManagerType = type; mRecyclerView.setLayoutManager(getLayoutManager()); mAdapter.notifyDataSetChanged(); popupWindow.dismiss(); } }); } private RecyclerView.LayoutManager getLayoutManager() { if (mCurrentLayoutManagerType == LayoutManagerPopupWindow.TYPE_GRID){ GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4); layoutManager.setOrientation(mIsVertical ? RecyclerView.VERTICAL : RecyclerView.HORIZONTAL); return layoutManager; } if (mCurrentLayoutManagerType == LayoutManagerPopupWindow.TYPE_STAGGERED){ return new StaggeredGridLayoutManager(4, mIsVertical ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.HORIZONTAL); } LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); layoutManager.setOrientation(mIsVertical ? RecyclerView.VERTICAL : RecyclerView.HORIZONTAL); return layoutManager; } }
false
2,540
6
3,078
7
3,032
6
3,078
7
3,772
11
false
false
false
false
false
true
65780_25
package com.jladder.entity; import com.jladder.db.annotation.Table; import java.io.Serializable; @Table("sys_service") public class DbProxy implements Serializable { /// <summary>id</summary> public String id; /// <summary>名称</summary> public String name ; /// <summary>标题</summary> public String title ; /// <summary>入口参数</summary> public String params; /// <summary>映射信息</summary> public String mappings ; /// <summary>是否可用</summary> public int enable ; /// <summary>返回处理</summary> public String returns ; /// <summary>请求方式</summary> public String method ; /// <summary>类型</summary> public String type ; /// <summary>调用者</summary> public String caller ; /// <summary>维护者</summary> public String maintainer ; /// <summary>开发语言</summary> public String language ; /// <summary>描述信息</summary> public String descr ; /// <summary>版本号</summary> public String version ; /// <summary>更新时间</summary> public String updatetime ; /// <summary>创建时间</summary> public String creaetetime; /// <summary>分属</summary> public String sort ; /// <summary>团队</summary> public String team ; /// <summary>功能信息</summary> public String funinfo ; /// <summary>上级</summary> public String superior ; /// <summary>上级</summary> public String debugging ; /// <summary> /// 重要等级 /// </summary> public String level; /// <summary> /// 日志级别 /// </summary> public int logoption; /// <summary> /// 返回样板 /// </summary> public String sample; /// <summary> /// 请求示例 /// </summary> public String example; /// <summary> /// 调用信息 /// </summary> public String callinfo; }
Ladder2020/JLadder
src/main/java/com/jladder/entity/DbProxy.java
470
/// 日志级别
line_comment
zh-cn
package com.jladder.entity; import com.jladder.db.annotation.Table; import java.io.Serializable; @Table("sys_service") public class DbProxy implements Serializable { /// <summary>id</summary> public String id; /// <summary>名称</summary> public String name ; /// <summary>标题</summary> public String title ; /// <summary>入口参数</summary> public String params; /// <summary>映射信息</summary> public String mappings ; /// <summary>是否可用</summary> public int enable ; /// <summary>返回处理</summary> public String returns ; /// <summary>请求方式</summary> public String method ; /// <summary>类型</summary> public String type ; /// <summary>调用者</summary> public String caller ; /// <summary>维护者</summary> public String maintainer ; /// <summary>开发语言</summary> public String language ; /// <summary>描述信息</summary> public String descr ; /// <summary>版本号</summary> public String version ; /// <summary>更新时间</summary> public String updatetime ; /// <summary>创建时间</summary> public String creaetetime; /// <summary>分属</summary> public String sort ; /// <summary>团队</summary> public String team ; /// <summary>功能信息</summary> public String funinfo ; /// <summary>上级</summary> public String superior ; /// <summary>上级</summary> public String debugging ; /// <summary> /// 重要等级 /// </summary> public String level; /// <summary> /// 日志 <SUF> /// </summary> public int logoption; /// <summary> /// 返回样板 /// </summary> public String sample; /// <summary> /// 请求示例 /// </summary> public String example; /// <summary> /// 调用信息 /// </summary> public String callinfo; }
false
457
4
470
4
525
4
470
4
605
10
false
false
false
false
false
true
53309_2
/* * Copyright (C) 2021 LamGC * * ContentGrabbingJi is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * ContentGrabbingJi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package net.lamgc.cgj.bot.cache; import java.util.Set; /** * 无序集合的缓存存储容器. * <p>其中, 元素是唯一的, 不会出现重复情况. * @param <E> 值类型. * @author LamGC */ public interface SetCacheStore<E> extends CollectionCacheStore<E, Set<E>> { /* * 说实话, SetCacheStore 的存在有点...奇怪, 或者可能就没有用, * 因为根据 2 代对缓存存储的使用情况来看, 用到 Set 的地方根本就没有, * 而且可能在某些方面实现起来也不是件容易事情. * 所以 SetCacheStore 可能会废弃掉(最晚也会在正式版出来前), * 或者有用的话才会为其设计相关方法. * (比如偏向 Redis 的那套进行设计, 但是我希望不要出现偏向性, 为所有实现提供一个平衡的实现复杂度) */ }
LamGC/ContentGrabbingJi
ContentGrabbingJi-CacheStore-api/src/main/java/net/lamgc/cgj/bot/cache/SetCacheStore.java
421
/* * 说实话, SetCacheStore 的存在有点...奇怪, 或者可能就没有用, * 因为根据 2 代对缓存存储的使用情况来看, 用到 Set 的地方根本就没有, * 而且可能在某些方面实现起来也不是件容易事情. * 所以 SetCacheStore 可能会废弃掉(最晚也会在正式版出来前), * 或者有用的话才会为其设计相关方法. * (比如偏向 Redis 的那套进行设计, 但是我希望不要出现偏向性, 为所有实现提供一个平衡的实现复杂度) */
block_comment
zh-cn
/* * Copyright (C) 2021 LamGC * * ContentGrabbingJi is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * ContentGrabbingJi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package net.lamgc.cgj.bot.cache; import java.util.Set; /** * 无序集合的缓存存储容器. * <p>其中, 元素是唯一的, 不会出现重复情况. * @param <E> 值类型. * @author LamGC */ public interface SetCacheStore<E> extends CollectionCacheStore<E, Set<E>> { /* * 说实话 <SUF>*/ }
false
372
135
421
152
399
134
421
152
568
236
false
false
false
false
false
true
48649_1
package cn.academy.block.tileentity; import cn.academy.ACItems; import cn.academy.block.block.ACFluids; import cn.academy.block.container.ContainerPhaseGen; import cn.academy.item.ItemMatterUnit; import cn.academy.energy.IFConstants; import cn.lambdalib2.registry.mc.RegTileEntity; import cn.lambdalib2.s11n.network.NetworkMessage; import cn.lambdalib2.s11n.network.TargetPoints; import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.*; import net.minecraftforge.fml.relauncher.Side; /** * @author WeAthFolD */ @RegTileEntity public class TilePhaseGen extends TileGeneratorBase implements IFluidHandler { // 废话~~~ public static final int SLOT_LIQUID_IN = ContainerPhaseGen.SLOT_LIQUID_IN, SLOT_LIQUID_OUT = ContainerPhaseGen.SLOT_LIQUID_OUT, SLOT_OUTPUT = ContainerPhaseGen.SLOT_OUTPUT; // TODO // @RegTileEntity.Render // @SideOnly(Side.CLIENT) // public static RenderPhaseGen renderer; // static final int CONSUME_PER_TICK = 100; static final double GEN_PER_MB = 0.5; int untilSync; public TilePhaseGen() { super("phase_gen", 3, 6000, IFConstants.LATENCY_MK1); } @Override public double getGeneration(double required) { int maxDrain = (int) Math.min(CONSUME_PER_TICK, required / GEN_PER_MB); FluidStack fs = tank.drain(maxDrain, true); return fs == null ? 0 : fs.amount * GEN_PER_MB; } @Override public void update() { super.update(); if(!getWorld().isRemote) { if(++untilSync == 10) { untilSync = 0; sync(); } ItemStack stack; { // Sink in liquid stack = getStackInSlot(SLOT_LIQUID_IN); if(!stack.isEmpty() && isPhaseLiquid(stack) && isOutputSlotAvailable() && (getTankSize() - getLiquidAmount() > PER_UNIT)) { if(stack.getCount() > 0) { tank.fill(new FluidStack(ACFluids.fluidImagProj, PER_UNIT), true); stack.shrink(1); } ItemStack output = getStackInSlot(SLOT_LIQUID_OUT); if(!output.isEmpty()) { output.grow(1); } else { this.setInventorySlotContents(SLOT_LIQUID_OUT, ACItems.matter_unit.create(ItemMatterUnit.MAT_NONE)); } } } { // Output energy stack = getStackInSlot(SLOT_OUTPUT); if(!stack.isEmpty()) this.tryChargeStack(stack); } } } // Fluid handling static final int TANK_SIZE = 8000; static final int PER_UNIT = 1000; protected FluidTank tank = new FluidTank(TANK_SIZE); public int getLiquidAmount() { return tank.getFluidAmount(); } public int getTankSize() { return tank.getCapacity(); } @Override public IFluidTankProperties[] getTankProperties() { FluidTankInfo info = tank.getInfo(); return new IFluidTankProperties[] { new FluidTankProperties(info.fluid, info.capacity) }; } @Override public int fill(FluidStack resource, boolean doFill) { if(resource.getFluid() != ACFluids.fluidImagProj) { return 0; } return tank.fill(resource, doFill); } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { if (resource.getFluid() != ACFluids.fluidImagProj) return null; return tank.drain(resource.amount, doDrain); } @Override public FluidStack drain(int maxDrain, boolean doDrain) { return tank.drain(maxDrain, doDrain); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); tank.readFromNBT(tag); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tank.writeToNBT(tag); return tag; } private void sync() { NBTTagCompound nbt = new NBTTagCompound(); writeToNBT(nbt); NetworkMessage.sendToAllAround(TargetPoints.convert(this, 15), this, "MSG_INFO_SYNC", nbt); } @NetworkMessage.Listener(channel="MSG_INFO_SYNC", side= Side.CLIENT) private void onSync(NBTTagCompound nbt) { readFromNBT(nbt); } private boolean isPhaseLiquid(ItemStack stack) { return stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_PHASE_LIQUID; } private boolean isOutputSlotAvailable() { ItemStack stack = getStackInSlot(SLOT_LIQUID_OUT); return stack.isEmpty() || (stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_NONE && stack.getCount() < stack.getMaxStackSize()); } }
LambdaInnovation/AcademyCraft
src/main/java/cn/academy/block/tileentity/TilePhaseGen.java
1,377
// 废话~~~
line_comment
zh-cn
package cn.academy.block.tileentity; import cn.academy.ACItems; import cn.academy.block.block.ACFluids; import cn.academy.block.container.ContainerPhaseGen; import cn.academy.item.ItemMatterUnit; import cn.academy.energy.IFConstants; import cn.lambdalib2.registry.mc.RegTileEntity; import cn.lambdalib2.s11n.network.NetworkMessage; import cn.lambdalib2.s11n.network.TargetPoints; import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.*; import net.minecraftforge.fml.relauncher.Side; /** * @author WeAthFolD */ @RegTileEntity public class TilePhaseGen extends TileGeneratorBase implements IFluidHandler { // 废话 <SUF> public static final int SLOT_LIQUID_IN = ContainerPhaseGen.SLOT_LIQUID_IN, SLOT_LIQUID_OUT = ContainerPhaseGen.SLOT_LIQUID_OUT, SLOT_OUTPUT = ContainerPhaseGen.SLOT_OUTPUT; // TODO // @RegTileEntity.Render // @SideOnly(Side.CLIENT) // public static RenderPhaseGen renderer; // static final int CONSUME_PER_TICK = 100; static final double GEN_PER_MB = 0.5; int untilSync; public TilePhaseGen() { super("phase_gen", 3, 6000, IFConstants.LATENCY_MK1); } @Override public double getGeneration(double required) { int maxDrain = (int) Math.min(CONSUME_PER_TICK, required / GEN_PER_MB); FluidStack fs = tank.drain(maxDrain, true); return fs == null ? 0 : fs.amount * GEN_PER_MB; } @Override public void update() { super.update(); if(!getWorld().isRemote) { if(++untilSync == 10) { untilSync = 0; sync(); } ItemStack stack; { // Sink in liquid stack = getStackInSlot(SLOT_LIQUID_IN); if(!stack.isEmpty() && isPhaseLiquid(stack) && isOutputSlotAvailable() && (getTankSize() - getLiquidAmount() > PER_UNIT)) { if(stack.getCount() > 0) { tank.fill(new FluidStack(ACFluids.fluidImagProj, PER_UNIT), true); stack.shrink(1); } ItemStack output = getStackInSlot(SLOT_LIQUID_OUT); if(!output.isEmpty()) { output.grow(1); } else { this.setInventorySlotContents(SLOT_LIQUID_OUT, ACItems.matter_unit.create(ItemMatterUnit.MAT_NONE)); } } } { // Output energy stack = getStackInSlot(SLOT_OUTPUT); if(!stack.isEmpty()) this.tryChargeStack(stack); } } } // Fluid handling static final int TANK_SIZE = 8000; static final int PER_UNIT = 1000; protected FluidTank tank = new FluidTank(TANK_SIZE); public int getLiquidAmount() { return tank.getFluidAmount(); } public int getTankSize() { return tank.getCapacity(); } @Override public IFluidTankProperties[] getTankProperties() { FluidTankInfo info = tank.getInfo(); return new IFluidTankProperties[] { new FluidTankProperties(info.fluid, info.capacity) }; } @Override public int fill(FluidStack resource, boolean doFill) { if(resource.getFluid() != ACFluids.fluidImagProj) { return 0; } return tank.fill(resource, doFill); } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { if (resource.getFluid() != ACFluids.fluidImagProj) return null; return tank.drain(resource.amount, doDrain); } @Override public FluidStack drain(int maxDrain, boolean doDrain) { return tank.drain(maxDrain, doDrain); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); tank.readFromNBT(tag); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tank.writeToNBT(tag); return tag; } private void sync() { NBTTagCompound nbt = new NBTTagCompound(); writeToNBT(nbt); NetworkMessage.sendToAllAround(TargetPoints.convert(this, 15), this, "MSG_INFO_SYNC", nbt); } @NetworkMessage.Listener(channel="MSG_INFO_SYNC", side= Side.CLIENT) private void onSync(NBTTagCompound nbt) { readFromNBT(nbt); } private boolean isPhaseLiquid(ItemStack stack) { return stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_PHASE_LIQUID; } private boolean isOutputSlotAvailable() { ItemStack stack = getStackInSlot(SLOT_LIQUID_OUT); return stack.isEmpty() || (stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_NONE && stack.getCount() < stack.getMaxStackSize()); } }
false
1,242
6
1,377
6
1,484
4
1,377
6
1,773
8
false
false
false
false
false
true
14908_0
package com.excelee.Algorithm; import java.util.NoSuchElementException; /*** * *这次作业基本是照着 caven 的抄了一遍 *有一个问题是我创建后遍历出来的总是多一个0节点 *删除删不掉 */ public class OneAlgorithm { static BiObject bioRoot = new BiObject(); //创建树 public static void create(int[] numbers){ for(int i=0;i<numbers.length;i++){ insert(numbers[i]); } } //插入值 public static void insert(int num){ if(num<bioRoot.getData()){ add(num,bioRoot,bioRoot.getLeftChild(),0); }else{ add(num,bioRoot,bioRoot.getRightChild(),1); } } /*** * * @param num 插入的值 * @param bio 父节点 * @param bioChild 子节点 * @param lor 左右节点标记 */ public static void add(int num,BiObject bio,BiObject bioChild,int lor){ if(bioChild==null){ bioChild = new BiObject(); bioChild.setData(num); System.out.print(num+"--"); if(0==lor){ bio.setLeftChild(bioChild); }else{ bio.setRightChild(bioChild); } }else{ if(num<bioChild.getData()){ add(num,bioChild,bioChild.getLeftChild(),0); }else if(num>bioChild.getData()){ add(num,bioChild,bioChild.getRightChild(),1); } } } /*** * 查找值 * @param tree * @param num * @return */ public static BiObject search(BiObject tree,int num) { if(tree==null){ throw new NoSuchElementException("值不存在"); } if(num<tree.getData()){ return search(tree.getLeftChild(), num); }else if(num>tree.getData()){ return search(tree.getRightChild(), num); }else{ return tree; } } /*** * 遍历 * @param tree */ public static void traversalTree(BiObject tree){ if(tree == null){ return; } traversalTree(tree.getLeftChild()); System.out.print(tree.getData()+"--"); traversalTree(tree.getRightChild()); } /*** * 删除 * @param num */ public static void deleteAll(int num){ delete(num, bioRoot); } public static void delete(int num,BiObject bio){ if(bio!=null){ if(num<bio.getData()){ delete(num, bio.getLeftChild()); }else if(num>bio.getData()){ delete(num, bio.getRightChild()); }else{ System.out.println("bio : = null --"+bio.getData()); bio = null; } } } public static void main(String[] args) { int nums[] = {5, 9, 2, 1, 4, 7, 6, 8}; create(nums); System.out.println("\n第1次遍历 :"); traversalTree(bioRoot); insert(3); System.out.println("\n第2次遍历 (增加3) :"); traversalTree(bioRoot); System.out.println("\n第3次遍历 :"); traversalTree(search(bioRoot,2)); System.out.println("\n第4次遍历 :"); deleteAll(1); traversalTree(bioRoot); } } /**节点对象 **/ class BiObject{ private int data; private BiObject leftChild; private BiObject rightChild; public int getData() { return data; } public void setData(int data) { this.data = data; } public BiObject getLeftChild() { return leftChild; } public void setLeftChild(BiObject leftChild) { this.leftChild = leftChild; } public BiObject getRightChild() { return rightChild; } public void setRightChild(BiObject rightChild) { this.rightChild = rightChild; } }
Learn-Algorithm/Learn-Algorithm
1-树/1-二叉查找树BST/cnexcelee/OneAlgorithm.java
1,103
/*** * *这次作业基本是照着 caven 的抄了一遍 *有一个问题是我创建后遍历出来的总是多一个0节点 *删除删不掉 */
block_comment
zh-cn
package com.excelee.Algorithm; import java.util.NoSuchElementException; /*** * *这次作 <SUF>*/ public class OneAlgorithm { static BiObject bioRoot = new BiObject(); //创建树 public static void create(int[] numbers){ for(int i=0;i<numbers.length;i++){ insert(numbers[i]); } } //插入值 public static void insert(int num){ if(num<bioRoot.getData()){ add(num,bioRoot,bioRoot.getLeftChild(),0); }else{ add(num,bioRoot,bioRoot.getRightChild(),1); } } /*** * * @param num 插入的值 * @param bio 父节点 * @param bioChild 子节点 * @param lor 左右节点标记 */ public static void add(int num,BiObject bio,BiObject bioChild,int lor){ if(bioChild==null){ bioChild = new BiObject(); bioChild.setData(num); System.out.print(num+"--"); if(0==lor){ bio.setLeftChild(bioChild); }else{ bio.setRightChild(bioChild); } }else{ if(num<bioChild.getData()){ add(num,bioChild,bioChild.getLeftChild(),0); }else if(num>bioChild.getData()){ add(num,bioChild,bioChild.getRightChild(),1); } } } /*** * 查找值 * @param tree * @param num * @return */ public static BiObject search(BiObject tree,int num) { if(tree==null){ throw new NoSuchElementException("值不存在"); } if(num<tree.getData()){ return search(tree.getLeftChild(), num); }else if(num>tree.getData()){ return search(tree.getRightChild(), num); }else{ return tree; } } /*** * 遍历 * @param tree */ public static void traversalTree(BiObject tree){ if(tree == null){ return; } traversalTree(tree.getLeftChild()); System.out.print(tree.getData()+"--"); traversalTree(tree.getRightChild()); } /*** * 删除 * @param num */ public static void deleteAll(int num){ delete(num, bioRoot); } public static void delete(int num,BiObject bio){ if(bio!=null){ if(num<bio.getData()){ delete(num, bio.getLeftChild()); }else if(num>bio.getData()){ delete(num, bio.getRightChild()); }else{ System.out.println("bio : = null --"+bio.getData()); bio = null; } } } public static void main(String[] args) { int nums[] = {5, 9, 2, 1, 4, 7, 6, 8}; create(nums); System.out.println("\n第1次遍历 :"); traversalTree(bioRoot); insert(3); System.out.println("\n第2次遍历 (增加3) :"); traversalTree(bioRoot); System.out.println("\n第3次遍历 :"); traversalTree(search(bioRoot,2)); System.out.println("\n第4次遍历 :"); deleteAll(1); traversalTree(bioRoot); } } /**节点对象 **/ class BiObject{ private int data; private BiObject leftChild; private BiObject rightChild; public int getData() { return data; } public void setData(int data) { this.data = data; } public BiObject getLeftChild() { return leftChild; } public void setLeftChild(BiObject leftChild) { this.leftChild = leftChild; } public BiObject getRightChild() { return rightChild; } public void setRightChild(BiObject rightChild) { this.rightChild = rightChild; } }
false
920
39
1,103
45
1,106
39
1,103
45
1,378
74
false
false
false
false
false
true
45894_3
package Heap; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; //题目描述:给定k个已经排好序的数组,找到最小的range,使得每个数组都至少有一个元素包含在这个区间之内,例如[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]],返回 // [20,24],第一个数组中的24,第二个数组中的20,第三个数组中22在这个区间里 //解法描述:类似于merge k sorted array的思路,不同的是,queue的大小必须是k,才能保证每个数组都至少有一个元素在区间之内,区间就是queue里面元素的最大和最小值,不断 // 更新这个区间 public class SmallestRange { public int[] smallestRange(List<List<Integer>> nums) { PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(a -> nums.get(a[0]) .get(a[1]))); // max表示queue里的最大元素 int start = 0, end = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < nums.size(); ++i) { queue.add(new int[] { i, 0 }); max = Math.max(max, nums.get(i) .get(0)); } while (queue.size() == nums.size()) { int[] array = queue.poll(); int row = array[0]; int col = array[1]; // 遇到更小的区间,就更新 if (end - start > max - nums.get(row) .get(col)) { start = nums.get(row) .get(col); end = max; } // max始终表示queue里面的最大元素 if (col + 1 < nums.get(row) .size()) { queue.add(new int[] { row, col + 1 }); max = Math.max(max, nums.get(row) .get(col + 1)); } } return new int[] { start, end }; } }
LeeNJU/NewCode
src/Heap/SmallestRange.java
541
// 更新这个区间
line_comment
zh-cn
package Heap; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; //题目描述:给定k个已经排好序的数组,找到最小的range,使得每个数组都至少有一个元素包含在这个区间之内,例如[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]],返回 // [20,24],第一个数组中的24,第二个数组中的20,第三个数组中22在这个区间里 //解法描述:类似于merge k sorted array的思路,不同的是,queue的大小必须是k,才能保证每个数组都至少有一个元素在区间之内,区间就是queue里面元素的最大和最小值,不断 // 更新 <SUF> public class SmallestRange { public int[] smallestRange(List<List<Integer>> nums) { PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(a -> nums.get(a[0]) .get(a[1]))); // max表示queue里的最大元素 int start = 0, end = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < nums.size(); ++i) { queue.add(new int[] { i, 0 }); max = Math.max(max, nums.get(i) .get(0)); } while (queue.size() == nums.size()) { int[] array = queue.poll(); int row = array[0]; int col = array[1]; // 遇到更小的区间,就更新 if (end - start > max - nums.get(row) .get(col)) { start = nums.get(row) .get(col); end = max; } // max始终表示queue里面的最大元素 if (col + 1 < nums.get(row) .size()) { queue.add(new int[] { row, col + 1 }); max = Math.max(max, nums.get(row) .get(col + 1)); } } return new int[] { start, end }; } }
false
467
5
541
6
541
5
541
6
684
8
false
false
false
false
false
true
22251_2
package util; /** * Created by Hiki on 2016/10/16. */ public enum RoomType { /** * 单人房 */ Single, /** * 双人房 */ Couple, /** * 标准房 */ Standard, /** * 套房 */ Suite, /** * 总统套房 */ PresidentialSuite, /** * 商务套房 */ BusinessSuite, /** * 大床房 */ Queen, /** * 家庭房 */ Family, /** * 情侣房 */ Lover, /** * 不限 */ All, }
Leftovers4/Leftovers
HotelOS/Common/src/main/java/util/RoomType.java
174
/** * 双人房 */
block_comment
zh-cn
package util; /** * Created by Hiki on 2016/10/16. */ public enum RoomType { /** * 单人房 */ Single, /** * 双人房 <SUF>*/ Couple, /** * 标准房 */ Standard, /** * 套房 */ Suite, /** * 总统套房 */ PresidentialSuite, /** * 商务套房 */ BusinessSuite, /** * 大床房 */ Queen, /** * 家庭房 */ Family, /** * 情侣房 */ Lover, /** * 不限 */ All, }
false
169
10
174
9
194
10
174
9
242
11
false
false
false
false
false
true
48830_1
package com.example.dl.hymvp.bean; import java.io.Serializable; import java.util.List; /** * Incremental change is better than ambitious failure. * * @author : <a href="http://mysticcoder.coding.me/myBlog">MysticCoder</a> * @date : 2017/12/4 * @desc : */ public class Survey { private List<SurveylistBean> surveylist; public List<SurveylistBean> getSurveylist() { return surveylist; } public void setSurveylist(List<SurveylistBean> surveylist) { this.surveylist = surveylist; } @Override public String toString() { return "SurveyModel{" + "surveylist=" + surveylist + '}'; } public static class SurveylistBean implements Serializable { /** * author : 北京市垂杨柳医院 * remark : 为不断改善医院住院服务质量,我院正在进行住院病人的满意度调查。非常感谢您抽出宝贵时间参加本次调查,提供您的看法与意见,能倾听您的意见,我们感到十分荣幸。谢谢! * id : 93 * title : 住院病人满意度调查 */ private String author; private String remark; private int id; @Override public String toString() { return "SurveylistBean{" + "author='" + author + '\'' + ", remark='" + remark + '\'' + ", id=" + id + ", title='" + title + '\'' + '}'; } private String title; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } }
LegendaryMystic/HYMVP
app/src/main/java/com/example/dl/hymvp/bean/Survey.java
526
/** * author : 北京市垂杨柳医院 * remark : 为不断改善医院住院服务质量,我院正在进行住院病人的满意度调查。非常感谢您抽出宝贵时间参加本次调查,提供您的看法与意见,能倾听您的意见,我们感到十分荣幸。谢谢! * id : 93 * title : 住院病人满意度调查 */
block_comment
zh-cn
package com.example.dl.hymvp.bean; import java.io.Serializable; import java.util.List; /** * Incremental change is better than ambitious failure. * * @author : <a href="http://mysticcoder.coding.me/myBlog">MysticCoder</a> * @date : 2017/12/4 * @desc : */ public class Survey { private List<SurveylistBean> surveylist; public List<SurveylistBean> getSurveylist() { return surveylist; } public void setSurveylist(List<SurveylistBean> surveylist) { this.surveylist = surveylist; } @Override public String toString() { return "SurveyModel{" + "surveylist=" + surveylist + '}'; } public static class SurveylistBean implements Serializable { /** * aut <SUF>*/ private String author; private String remark; private int id; @Override public String toString() { return "SurveylistBean{" + "author='" + author + '\'' + ", remark='" + remark + '\'' + ", id=" + id + ", title='" + title + '\'' + '}'; } private String title; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } }
false
461
83
526
116
540
89
526
116
704
186
false
false
false
false
false
true
8843_21
package leetcode.editor.cn;//假设你是一个专业的狗仔,参加了一个 n 人派对,其中每个人被从 0 到 n - 1 标号。在这个派对人群当中可能存在一位 “名人”。所谓 “名人” 的定义是 //:其他所有 n - 1 个人都认识他/她,而他/她并不认识其他任何人。 // // 现在你想要确认这个 “名人” 是谁,或者确定这里没有 “名人”。而你唯一能做的就是问诸如 “A 你好呀,请问你认不认识 B呀?” 的问题,以确定 A 是否 //认识 B。你需要在(渐近意义上)尽可能少的问题内来确定这位 “名人” 是谁(或者确定这里没有 “名人”)。 // // 在本题中,你可以使用辅助函数 bool knows(a, b) 获取到 A 是否认识 B。请你来实现一个函数 int findCelebrity(n)。 // // // 派对最多只会有一个 “名人” 参加。若 “名人” 存在,请返回他/她的编号;若 “名人” 不存在,请返回 -1。 // // // // 示例 1: // // // // //输入: graph = [ // [1,1,0], // [0,1,0], // [1,1,1] //] //输出: 1 //解释: 有编号分别为 0、1 和 2 的三个人。graph[i][j] = 1 代表编号为 i 的人认识编号为 j 的人,而 graph[i][j] = 0 // 则代表编号为 i 的人不认识编号为 j 的人。“名人” 是编号 1 的人,因为 0 和 2 均认识他/她,但 1 不认识任何人。 // // // 示例 2: // // // // //输入: graph = [ // [1,0,1], // [1,1,0], // [0,1,1] //] //输出: -1 //解释: 没有 “名人” // // // // // 提示: // // // n == graph.length // n == graph[i].length // 2 <= n <= 100 // graph[i][j] 是 0 或 1. // graph[i][i] == 1 // // // // // 进阶:如果允许调用 API knows 的最大次数为 3 * n ,你可以设计一个不超过最大调用次数的解决方案吗? // // // // Related Topics 贪心 图 双指针 交互 👍 175 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ class Relation { public boolean knows(int a, int b) { return a == b; } } class findCelebritySolution extends Relation { public int findCelebrity(int n) { int cand = 0; for (int other = 1; other < n; other++) { if (knows(cand, other) || !knows(other, cand)) { cand = other; } } for (int other = 0; other < n; other++) { if (cand == other) continue; if (knows(cand, other) || !knows(other, cand)) return -1; } return cand; } } //leetcode submit region end(Prohibit modification and deletion)
LehiChiang/FightFor2022
algorithm/leetcode/editor/cn/[277]搜寻名人.java
946
// 提示:
line_comment
zh-cn
package leetcode.editor.cn;//假设你是一个专业的狗仔,参加了一个 n 人派对,其中每个人被从 0 到 n - 1 标号。在这个派对人群当中可能存在一位 “名人”。所谓 “名人” 的定义是 //:其他所有 n - 1 个人都认识他/她,而他/她并不认识其他任何人。 // // 现在你想要确认这个 “名人” 是谁,或者确定这里没有 “名人”。而你唯一能做的就是问诸如 “A 你好呀,请问你认不认识 B呀?” 的问题,以确定 A 是否 //认识 B。你需要在(渐近意义上)尽可能少的问题内来确定这位 “名人” 是谁(或者确定这里没有 “名人”)。 // // 在本题中,你可以使用辅助函数 bool knows(a, b) 获取到 A 是否认识 B。请你来实现一个函数 int findCelebrity(n)。 // // // 派对最多只会有一个 “名人” 参加。若 “名人” 存在,请返回他/她的编号;若 “名人” 不存在,请返回 -1。 // // // // 示例 1: // // // // //输入: graph = [ // [1,1,0], // [0,1,0], // [1,1,1] //] //输出: 1 //解释: 有编号分别为 0、1 和 2 的三个人。graph[i][j] = 1 代表编号为 i 的人认识编号为 j 的人,而 graph[i][j] = 0 // 则代表编号为 i 的人不认识编号为 j 的人。“名人” 是编号 1 的人,因为 0 和 2 均认识他/她,但 1 不认识任何人。 // // // 示例 2: // // // // //输入: graph = [ // [1,0,1], // [1,1,0], // [0,1,1] //] //输出: -1 //解释: 没有 “名人” // // // // // 提示 <SUF> // // // n == graph.length // n == graph[i].length // 2 <= n <= 100 // graph[i][j] 是 0 或 1. // graph[i][i] == 1 // // // // // 进阶:如果允许调用 API knows 的最大次数为 3 * n ,你可以设计一个不超过最大调用次数的解决方案吗? // // // // Related Topics 贪心 图 双指针 交互 👍 175 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ class Relation { public boolean knows(int a, int b) { return a == b; } } class findCelebritySolution extends Relation { public int findCelebrity(int n) { int cand = 0; for (int other = 1; other < n; other++) { if (knows(cand, other) || !knows(other, cand)) { cand = other; } } for (int other = 0; other < n; other++) { if (cand == other) continue; if (knows(cand, other) || !knows(other, cand)) return -1; } return cand; } } //leetcode submit region end(Prohibit modification and deletion)
false
794
5
946
5
862
4
946
5
1,180
6
false
false
false
false
false
true
54582_2
package permutationSequence; // 这道题借助了divide 那道题的思路,想到了他的所有的情况的总数是n! 也就是 n *(n-1) !而后面也就是 n-1个数的排列的总数。 // 因为是按照从小到大的顺序来进行排,所以可以从头往后进行排,前面排好了,从里面将这个remove 掉,整个还是排好序的,由这个想到了用arraylist 里面的先将所有的元素都按照顺序add 进来,然后每次从中间删掉一个,然后再在这里取元素往后面进行排 // 现在的问题是这个里面该取哪个元素,比如213 这个肯定是1**已经排过了,所以他肯定能得到1 *(n-1)!的数,在这个index 的后面。这个就类似于整除。 // 要注意的是因为这个k是从1开始的,整除会有问题,所以要先减去1 再除以 (n-1) ! // 因为又要每次求(n-1)!这个比较耗时间,所以用dp 的方法先将这些都存进去。然后每次都去取。 // 本来整除之后是在这个基础上少1的,倒是arraylist 又是从0开始的,所以这个就不需要+1,直接用得到的数据从里面get 出来就可以了。 // 然后得出来了之后这个就不能取了,就要从这里面进行remove // 然后加到最重要返回的stringbuffer 里面。 // 再后面就是将前面这么多数减去,这样就不管这一位,去找后面一位。 // 最后有个要注意的是,因为开始的时候0! 可以赋值为1,最后可以找到,这一位,不然最终要提前一位出来,append 剩下的一位,防止除以0 // 方法类似http://yucoding.blogspot.com/2013/04/leetcode-question-68-permutation.html // 他有一点做的比较好的是不是减,直接用% 值得学习。 import java.util.ArrayList; public class DP { public static String getPermutation(int n, int k) { int[] dp = new int[10]; int total = 1; for (int i = 1; i <= 9; i++) { total *= i; dp[i] = total; } // 这边赋值为1 dp[0] = 1; ArrayList<Integer> numbers = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { numbers.add(i); } StringBuffer sb = new StringBuffer(); for (int i = n; i >= 1; i--) { int index = (k - 1) / dp[i - 1]; sb.append(numbers.get(index)); numbers.remove(index); k = k - dp[i - 1] * (index); } // sb.append(numbers.get(0)); return sb.toString(); } public static void main(String[] args) { int n = 5; int k = 10; System.out.println(getPermutation(n, k)); } }
LeikaiMa/LGCHASER
LeetCode_VII/src/permutationSequence/DP.java
803
// 现在的问题是这个里面该取哪个元素,比如213 这个肯定是1**已经排过了,所以他肯定能得到1 *(n-1)!的数,在这个index 的后面。这个就类似于整除。
line_comment
zh-cn
package permutationSequence; // 这道题借助了divide 那道题的思路,想到了他的所有的情况的总数是n! 也就是 n *(n-1) !而后面也就是 n-1个数的排列的总数。 // 因为是按照从小到大的顺序来进行排,所以可以从头往后进行排,前面排好了,从里面将这个remove 掉,整个还是排好序的,由这个想到了用arraylist 里面的先将所有的元素都按照顺序add 进来,然后每次从中间删掉一个,然后再在这里取元素往后面进行排 // 现在 <SUF> // 要注意的是因为这个k是从1开始的,整除会有问题,所以要先减去1 再除以 (n-1) ! // 因为又要每次求(n-1)!这个比较耗时间,所以用dp 的方法先将这些都存进去。然后每次都去取。 // 本来整除之后是在这个基础上少1的,倒是arraylist 又是从0开始的,所以这个就不需要+1,直接用得到的数据从里面get 出来就可以了。 // 然后得出来了之后这个就不能取了,就要从这里面进行remove // 然后加到最重要返回的stringbuffer 里面。 // 再后面就是将前面这么多数减去,这样就不管这一位,去找后面一位。 // 最后有个要注意的是,因为开始的时候0! 可以赋值为1,最后可以找到,这一位,不然最终要提前一位出来,append 剩下的一位,防止除以0 // 方法类似http://yucoding.blogspot.com/2013/04/leetcode-question-68-permutation.html // 他有一点做的比较好的是不是减,直接用% 值得学习。 import java.util.ArrayList; public class DP { public static String getPermutation(int n, int k) { int[] dp = new int[10]; int total = 1; for (int i = 1; i <= 9; i++) { total *= i; dp[i] = total; } // 这边赋值为1 dp[0] = 1; ArrayList<Integer> numbers = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { numbers.add(i); } StringBuffer sb = new StringBuffer(); for (int i = n; i >= 1; i--) { int index = (k - 1) / dp[i - 1]; sb.append(numbers.get(index)); numbers.remove(index); k = k - dp[i - 1] * (index); } // sb.append(numbers.get(0)); return sb.toString(); } public static void main(String[] args) { int n = 5; int k = 10; System.out.println(getPermutation(n, k)); } }
false
693
51
803
60
731
50
803
60
1,077
86
false
false
false
false
false
true
62244_3
/* * 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 com.nageoffer.shortlink.admin.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.nageoffer.shortlink.admin.common.convention.result.Result; import com.nageoffer.shortlink.admin.common.convention.result.Results; import com.nageoffer.shortlink.admin.remote.ShortLinkActualRemoteService; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkBatchCreateReqDTO; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkCreateReqDTO; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkPageReqDTO; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkUpdateReqDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkBaseInfoRespDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkBatchCreateRespDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkCreateRespDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkPageRespDTO; import com.nageoffer.shortlink.admin.toolkit.EasyExcelWebUtil; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 短链接后管控制层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @RestController @RequiredArgsConstructor public class ShortLinkController { private final ShortLinkActualRemoteService shortLinkActualRemoteService; /** * 创建短链接 */ @PostMapping("/api/short-link/admin/v1/create") public Result<ShortLinkCreateRespDTO> createShortLink(@RequestBody ShortLinkCreateReqDTO requestParam) { return shortLinkActualRemoteService.createShortLink(requestParam); } /** * 批量创建短链接 */ @SneakyThrows @PostMapping("/api/short-link/admin/v1/create/batch") public void batchCreateShortLink(@RequestBody ShortLinkBatchCreateReqDTO requestParam, HttpServletResponse response) { Result<ShortLinkBatchCreateRespDTO> shortLinkBatchCreateRespDTOResult = shortLinkActualRemoteService.batchCreateShortLink(requestParam); if (shortLinkBatchCreateRespDTOResult.isSuccess()) { List<ShortLinkBaseInfoRespDTO> baseLinkInfos = shortLinkBatchCreateRespDTOResult.getData().getBaseLinkInfos(); EasyExcelWebUtil.write(response, "批量创建短链接-SaaS短链接系统", ShortLinkBaseInfoRespDTO.class, baseLinkInfos); } } /** * 修改短链接 */ @PostMapping("/api/short-link/admin/v1/update") public Result<Void> updateShortLink(@RequestBody ShortLinkUpdateReqDTO requestParam) { shortLinkActualRemoteService.updateShortLink(requestParam); return Results.success(); } /** * 分页查询短链接 */ @GetMapping("/api/short-link/admin/v1/page") public Result<Page<ShortLinkPageRespDTO>> pageShortLink(ShortLinkPageReqDTO requestParam) { return shortLinkActualRemoteService.pageShortLink(requestParam.getGid(), requestParam.getOrderTag(), requestParam.getCurrent(), requestParam.getSize()); } }
LeoLi23/shortlink
admin/src/main/java/com/nageoffer/shortlink/admin/controller/ShortLinkController.java
1,064
/** * 批量创建短链接 */
block_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 com.nageoffer.shortlink.admin.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.nageoffer.shortlink.admin.common.convention.result.Result; import com.nageoffer.shortlink.admin.common.convention.result.Results; import com.nageoffer.shortlink.admin.remote.ShortLinkActualRemoteService; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkBatchCreateReqDTO; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkCreateReqDTO; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkPageReqDTO; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkUpdateReqDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkBaseInfoRespDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkBatchCreateRespDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkCreateRespDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkPageRespDTO; import com.nageoffer.shortlink.admin.toolkit.EasyExcelWebUtil; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 短链接后管控制层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @RestController @RequiredArgsConstructor public class ShortLinkController { private final ShortLinkActualRemoteService shortLinkActualRemoteService; /** * 创建短链接 */ @PostMapping("/api/short-link/admin/v1/create") public Result<ShortLinkCreateRespDTO> createShortLink(@RequestBody ShortLinkCreateReqDTO requestParam) { return shortLinkActualRemoteService.createShortLink(requestParam); } /** * 批量创 <SUF>*/ @SneakyThrows @PostMapping("/api/short-link/admin/v1/create/batch") public void batchCreateShortLink(@RequestBody ShortLinkBatchCreateReqDTO requestParam, HttpServletResponse response) { Result<ShortLinkBatchCreateRespDTO> shortLinkBatchCreateRespDTOResult = shortLinkActualRemoteService.batchCreateShortLink(requestParam); if (shortLinkBatchCreateRespDTOResult.isSuccess()) { List<ShortLinkBaseInfoRespDTO> baseLinkInfos = shortLinkBatchCreateRespDTOResult.getData().getBaseLinkInfos(); EasyExcelWebUtil.write(response, "批量创建短链接-SaaS短链接系统", ShortLinkBaseInfoRespDTO.class, baseLinkInfos); } } /** * 修改短链接 */ @PostMapping("/api/short-link/admin/v1/update") public Result<Void> updateShortLink(@RequestBody ShortLinkUpdateReqDTO requestParam) { shortLinkActualRemoteService.updateShortLink(requestParam); return Results.success(); } /** * 分页查询短链接 */ @GetMapping("/api/short-link/admin/v1/page") public Result<Page<ShortLinkPageRespDTO>> pageShortLink(ShortLinkPageReqDTO requestParam) { return shortLinkActualRemoteService.pageShortLink(requestParam.getGid(), requestParam.getOrderTag(), requestParam.getCurrent(), requestParam.getSize()); } }
false
881
12
1,064
10
1,074
11
1,064
10
1,320
21
false
false
false
false
false
true
46030_0
package com.example.demo.leetcode; import java.util.Arrays; import java.util.PriorityQueue; /** * 天堂硅谷专场 * */ public class TTGG { public static void main(String[] args) { } public int lastMaterial(int[] material) { PriorityQueue<Integer> queue = new PriorityQueue<>((a,b)->b-a); for(int n : material){ queue.add(n); } while (queue.size()>=2){ int p = queue.poll(); int q = queue.poll(); if(p==q){ continue; } queue.add(Math.abs(q-p)); } return queue.size()==0?0:queue.poll(); } public int longestESR(int[] sales) { int ans = 0; int n = sales.length; if(n==1){ return sales[0]>8?1:0; } int sum = 0; int right =0; for (int i = 0; i <n; i++) { while ((i == right) || right<n&& sum>0){ sum += (sales[right]>8?1:-1); right++; } if(right-i!=1){ ans = Math.max(ans, right-i-1); } sum -= (sales[i]>8?1:-1); } sum = 0; right =0; for(int i = 0; i<=n/2;i++){ int t = sales[i]; sales[i] = sales[n-i-1]; sales[n-i-1] = t; } for (int i = 0; i <n; i++) { while ((i == right) || (right<n&& sum>0)){ sum += (sales[right]>8?1:-1); right++; } if(right-i!=1){ ans = Math.max(ans, right-i-1); } sum -= (sales[i]>8?1:-1); } return ans; } }
Leocn/algorithm
leetcode/TTGG.java
505
/** * 天堂硅谷专场 * */
block_comment
zh-cn
package com.example.demo.leetcode; import java.util.Arrays; import java.util.PriorityQueue; /** * 天堂硅 <SUF>*/ public class TTGG { public static void main(String[] args) { } public int lastMaterial(int[] material) { PriorityQueue<Integer> queue = new PriorityQueue<>((a,b)->b-a); for(int n : material){ queue.add(n); } while (queue.size()>=2){ int p = queue.poll(); int q = queue.poll(); if(p==q){ continue; } queue.add(Math.abs(q-p)); } return queue.size()==0?0:queue.poll(); } public int longestESR(int[] sales) { int ans = 0; int n = sales.length; if(n==1){ return sales[0]>8?1:0; } int sum = 0; int right =0; for (int i = 0; i <n; i++) { while ((i == right) || right<n&& sum>0){ sum += (sales[right]>8?1:-1); right++; } if(right-i!=1){ ans = Math.max(ans, right-i-1); } sum -= (sales[i]>8?1:-1); } sum = 0; right =0; for(int i = 0; i<=n/2;i++){ int t = sales[i]; sales[i] = sales[n-i-1]; sales[n-i-1] = t; } for (int i = 0; i <n; i++) { while ((i == right) || (right<n&& sum>0)){ sum += (sales[right]>8?1:-1); right++; } if(right-i!=1){ ans = Math.max(ans, right-i-1); } sum -= (sales[i]>8?1:-1); } return ans; } }
false
436
10
505
16
548
12
505
16
586
15
false
false
false
false
false
true
41820_6
package com.llqqww.thinkjdbc; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; import javax.sql.DataSource; public class D { private static DbConfig dbConfig; private static DataSource dataSource; private static String version="V1.4.5_16"; private static String TablePrefix=""; private static String pk="id"; private static boolean isPkAutoInc=true; private static boolean isAutoClose=true; private static boolean checkField=true; private static final ThreadLocal<Connection> threadConn = new ThreadLocal<Connection>(){ //ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法,返回此方法值 @Override protected Connection initialValue() { return null; } }; static{ File cfgFile=new File("thinkjdbc.properties"); if(cfgFile.exists()) { try { Properties cfg = new Properties(); cfg.load(new FileInputStream(cfgFile)); String DbUrl = cfg.getProperty("jdbcUrl"); String DbUser = cfg.getProperty("dataSource.user"); String DbPassword = cfg.getProperty("dataSource.password"); String DriverName = cfg.getProperty("dataSource.driverClassName"); setDbConfig(DbUrl, DbUser, DbPassword,DriverName); //System.out.println("File Config"); } catch (IOException |ClassNotFoundException e) { e.printStackTrace(); } }else { cfgFile=null; } } public static M M() throws Exception { return new M(); } public static M M(String table) throws Exception { return new M(table); } public static M M(Object bean) throws Exception { return new M(bean); } public static M M(Class<?> beanClass) throws Exception { return new M(beanClass); } public static Connection getConnection() throws Exception { Connection conn=threadConn.get(); // System.out.println("Thread:"+Thread.currentThread().getName()+",conn==null:"+(conn==null)); if(null!=conn) { return conn; }else if(null!=dataSource) { conn = dataSource.getConnection(); }else { if(null!=dbConfig) { conn = DriverManager.getConnection(dbConfig.getDbUrl(), dbConfig.getDbUser(), dbConfig.getDbPassword()); }else { throw new Exception("DbConfig/DataSource haven't set , D.setDbConfig()/D.setDataSource() should be called first !"); } } threadConn.set(conn); return conn; } /** * 获取事务连接 * @return Connection 返回事务连接 * @throws Exception 获取失败或设置为事务失败时关闭连接并抛异常 */ public static Connection getTransConnection() throws Exception{ Connection conn=null; try { conn= getConnection(); conn.setAutoCommit(false); } catch (Exception e) { closeConn(conn); throw e; } return conn; } /** * 事务提交 * 中途异常关闭conn连接 * @param conn 事务连接 * @throws Exception if has error */ public static void commit(Connection conn) throws Exception{ Exception ex = null; try { conn.commit(); } catch (Exception e) { ex=e; }finally { autoCloseTransConn(conn); if(null!=ex) { throw ex; } } } /** * 事务回滚,中途异常关闭conn连接 * @param conn 事务连接 * @throws Exception if has error */ public static void rollback(Connection conn) throws Exception{ Exception ex = null; try { conn.rollback(); } catch (Exception e) { ex=e; }finally { autoCloseTransConn(conn); if(null!=ex) { throw ex; } } } /** * 关闭连接 */ public static void closeConn(){ Connection conn=threadConn.get(); try { if(conn!=null && !conn.isClosed()) { conn.close(); threadConn.remove(); } } catch (Exception e) { e.printStackTrace(); } } /** * 关闭连接,有事务不关闭 * @param conn 连接 * @throws Exception if has error */ protected static void closeConn(Connection conn) throws Exception{ if(conn!=null && !conn.isClosed()) { conn.close(); threadConn.remove(); } } /** * 关闭连接,有事务不关闭 * @param conn 连接 * @throws Exception if has error */ protected static void autoCloseConn(Connection conn) throws Exception{ if(D.isAutoClose() && null!=conn && conn.getAutoCommit()) { D.closeConn(conn); } } /** * 关闭事务连接 * @param conn 连接 * @throws Exception if has error */ protected static void autoCloseTransConn(Connection conn) throws Exception{ if(D.isAutoClose()) { D.closeConn(conn); } } public static void setDbConfig(String DbUrl,String DbUser,String DbPassword) throws ClassNotFoundException{ setDbConfig(new DbConfig(DbUrl,DbUser,DbPassword)); } public static void setDbConfig(String DbUrl,String DbUser,String DbPassword,String DriverName) throws ClassNotFoundException{ setDbConfig(new DbConfig(DbUrl,DbUser,DbPassword,DriverName)); } public static void setDbConfig(DbConfig dbConfig) throws ClassNotFoundException{ D.dbConfig = dbConfig; Class.forName(dbConfig.getDriverName()); } public static DbConfig getDbConfig() { return dbConfig; } public static void setDataSource(DataSource dataSource) { D.dataSource=dataSource; } public static DataSource getDataSource() { return dataSource; } public static String getTablePrefix() { return TablePrefix; } public static void setTablePrefix(String tablePrefix) { TablePrefix = tablePrefix; } public static boolean isAutoClose() { return isAutoClose; } public static void setAutoClose(boolean isAutoClose) { D.isAutoClose = isAutoClose; } public static boolean isCheckField() { return checkField; } public static void setCheckField(boolean checkField) { D.checkField = checkField; } public static String getPk() { return pk; } public static void setPk(String pk) { D.pk = pk; } public static boolean isPkAutoInc() { return isPkAutoInc; } public static void setPkAutoInc(boolean isPkAutoInc) { D.isPkAutoInc = isPkAutoInc; } public static String getVersion(){ return version; } public static void about() { String about="ThinkJDBC "+version+" By Leytton 2018/04/14-. Apache 2.0 Licence"; System.out.println(about); } }
Leytton/ThinkJD
src/com/llqqww/thinkjdbc/D.java
1,855
/** * 关闭连接 */
block_comment
zh-cn
package com.llqqww.thinkjdbc; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; import javax.sql.DataSource; public class D { private static DbConfig dbConfig; private static DataSource dataSource; private static String version="V1.4.5_16"; private static String TablePrefix=""; private static String pk="id"; private static boolean isPkAutoInc=true; private static boolean isAutoClose=true; private static boolean checkField=true; private static final ThreadLocal<Connection> threadConn = new ThreadLocal<Connection>(){ //ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法,返回此方法值 @Override protected Connection initialValue() { return null; } }; static{ File cfgFile=new File("thinkjdbc.properties"); if(cfgFile.exists()) { try { Properties cfg = new Properties(); cfg.load(new FileInputStream(cfgFile)); String DbUrl = cfg.getProperty("jdbcUrl"); String DbUser = cfg.getProperty("dataSource.user"); String DbPassword = cfg.getProperty("dataSource.password"); String DriverName = cfg.getProperty("dataSource.driverClassName"); setDbConfig(DbUrl, DbUser, DbPassword,DriverName); //System.out.println("File Config"); } catch (IOException |ClassNotFoundException e) { e.printStackTrace(); } }else { cfgFile=null; } } public static M M() throws Exception { return new M(); } public static M M(String table) throws Exception { return new M(table); } public static M M(Object bean) throws Exception { return new M(bean); } public static M M(Class<?> beanClass) throws Exception { return new M(beanClass); } public static Connection getConnection() throws Exception { Connection conn=threadConn.get(); // System.out.println("Thread:"+Thread.currentThread().getName()+",conn==null:"+(conn==null)); if(null!=conn) { return conn; }else if(null!=dataSource) { conn = dataSource.getConnection(); }else { if(null!=dbConfig) { conn = DriverManager.getConnection(dbConfig.getDbUrl(), dbConfig.getDbUser(), dbConfig.getDbPassword()); }else { throw new Exception("DbConfig/DataSource haven't set , D.setDbConfig()/D.setDataSource() should be called first !"); } } threadConn.set(conn); return conn; } /** * 获取事务连接 * @return Connection 返回事务连接 * @throws Exception 获取失败或设置为事务失败时关闭连接并抛异常 */ public static Connection getTransConnection() throws Exception{ Connection conn=null; try { conn= getConnection(); conn.setAutoCommit(false); } catch (Exception e) { closeConn(conn); throw e; } return conn; } /** * 事务提交 * 中途异常关闭conn连接 * @param conn 事务连接 * @throws Exception if has error */ public static void commit(Connection conn) throws Exception{ Exception ex = null; try { conn.commit(); } catch (Exception e) { ex=e; }finally { autoCloseTransConn(conn); if(null!=ex) { throw ex; } } } /** * 事务回滚,中途异常关闭conn连接 * @param conn 事务连接 * @throws Exception if has error */ public static void rollback(Connection conn) throws Exception{ Exception ex = null; try { conn.rollback(); } catch (Exception e) { ex=e; }finally { autoCloseTransConn(conn); if(null!=ex) { throw ex; } } } /** * 关闭连 <SUF>*/ public static void closeConn(){ Connection conn=threadConn.get(); try { if(conn!=null && !conn.isClosed()) { conn.close(); threadConn.remove(); } } catch (Exception e) { e.printStackTrace(); } } /** * 关闭连接,有事务不关闭 * @param conn 连接 * @throws Exception if has error */ protected static void closeConn(Connection conn) throws Exception{ if(conn!=null && !conn.isClosed()) { conn.close(); threadConn.remove(); } } /** * 关闭连接,有事务不关闭 * @param conn 连接 * @throws Exception if has error */ protected static void autoCloseConn(Connection conn) throws Exception{ if(D.isAutoClose() && null!=conn && conn.getAutoCommit()) { D.closeConn(conn); } } /** * 关闭事务连接 * @param conn 连接 * @throws Exception if has error */ protected static void autoCloseTransConn(Connection conn) throws Exception{ if(D.isAutoClose()) { D.closeConn(conn); } } public static void setDbConfig(String DbUrl,String DbUser,String DbPassword) throws ClassNotFoundException{ setDbConfig(new DbConfig(DbUrl,DbUser,DbPassword)); } public static void setDbConfig(String DbUrl,String DbUser,String DbPassword,String DriverName) throws ClassNotFoundException{ setDbConfig(new DbConfig(DbUrl,DbUser,DbPassword,DriverName)); } public static void setDbConfig(DbConfig dbConfig) throws ClassNotFoundException{ D.dbConfig = dbConfig; Class.forName(dbConfig.getDriverName()); } public static DbConfig getDbConfig() { return dbConfig; } public static void setDataSource(DataSource dataSource) { D.dataSource=dataSource; } public static DataSource getDataSource() { return dataSource; } public static String getTablePrefix() { return TablePrefix; } public static void setTablePrefix(String tablePrefix) { TablePrefix = tablePrefix; } public static boolean isAutoClose() { return isAutoClose; } public static void setAutoClose(boolean isAutoClose) { D.isAutoClose = isAutoClose; } public static boolean isCheckField() { return checkField; } public static void setCheckField(boolean checkField) { D.checkField = checkField; } public static String getPk() { return pk; } public static void setPk(String pk) { D.pk = pk; } public static boolean isPkAutoInc() { return isPkAutoInc; } public static void setPkAutoInc(boolean isPkAutoInc) { D.isPkAutoInc = isPkAutoInc; } public static String getVersion(){ return version; } public static void about() { String about="ThinkJDBC "+version+" By Leytton 2018/04/14-. Apache 2.0 Licence"; System.out.println(about); } }
false
1,554
9
1,849
8
1,906
9
1,849
8
2,294
14
false
false
false
false
false
true
26015_2
/* 一个处理器要处理一堆request,一次只能处理一条,每次执行一个任务最多执行时间q,接着执行等待着的下一个任务。 若前一个任务没执行完则放到队尾,等待下一次执行。 假设只要有任务开始以后cpu是不会空闲的,也就是说cpu开始后如果空闲了就说明没有任务了,另外Robin Round最后返回值是float。 OA 示例: 例子: 【0,1,4】 【5,2,3】 q=3. 输出的是average wait time 2.3333333 第0秒,任务1进队列。我们peek目前队列中有的任务是任务1,我们发现任务1开始时间第0秒,目前也是第0秒,所以任务1等待时间是0。 然后任务1执行3秒,它自身还有2秒钟。 这时候我们查看3秒的时候哪些任务达到了,发现任务2在第1秒到达。于是任务2进队列。 这时候我们查看任务1有没有执行完,发现没有执行完,于是我们poll任务1,再把任务1 add到队列末尾。 这时候队列的顺序是任务2,任务1. 现在我们再次peek队列,于是找到任务2.我们发现任务2在第1秒到达了,目前我们在第3秒。所以等待时间是3-1=2. 我们重复刚刚的步骤,发现任务2执行时间只要2秒,于是我们到第5秒。这时候我们查找第5秒哪些任务到达了。我们发现任务3也到达了。于是任务3进队列。 所以目前队列顺序是任务2,任务1,任务3. 我们又发现任务2已经执行完了,于是我们把任务2 poll出队列,不再把它放进队列里了。 所以现在队列里面剩余的任务是任务1,任务3. 于是我们再peek队列。请注意,这时候的q被重新设置过了,不是3-2=1秒,而是又是3秒。 我们再次peek队列,找到任务1,目前是在第5秒,我们刚刚执行过任务1,他暂停在第3秒,所以任务1又等了2秒。目前秒数是2+2=4秒。 目前任务1还有2秒。我们执行完任务1以后,到达第5+2 = 7把他扔出队列。目前队列里只有任务3了。 然后我们再peek,现在只有任务3了,目前我们在第7秒。任务3进来的时候在第4秒。所以任务3等了7-4 = 3秒。所以等待时间又加3秒。 所以最终等待时间是2+2+3 = 7秒。平均等待时间是7/3 = 2.3333秒。 */ import java.util.LinkedList; import java.util.Queue; class process { int arrTime; int exeTime; process(int arr, int exe) { arrTime = arr; exeTime = exe; } } public class RoundRobinScheduling { public float Solution(int[] Atime, int[] Etime, int q) { // Corner case if (Atime == null || Etime == null || Atime.length != Etime.length) return 0; int length = Atime.length; Queue<process> queue = new LinkedList<process>(); int curTime = 0, waitTime = 0; int index = 0; while (!queue.isEmpty() || index < length) { if (!queue.isEmpty()) { process cur = queue.poll(); waitTime += curTime - cur.arrTime; curTime += Math.min(cur.exeTime, q); for (; index < length && Atime[index] <= curTime; index++) queue.offer(new process(Atime[index], Etime[index])); if (cur.exeTime > q) queue.offer(new process(curTime, cur.exeTime - q)); } else { queue.offer(new process(Atime[index], Etime[index])); curTime = Atime[index++]; } } return (float) waitTime / length; } } /*-------------------另一版本------------------------------------------------------------------------------*/ public classRoundRobinScheduling { public static float Solution(int[] Atime, int[] Etime, int q) { if(Atime == null || Etime ==null ||Atime.length <= 1 ||Etime.length <= 1 ||Atime.length != Etime.length) return 0; int len =Atime.length; // usequeue data structure to store every process Queue<Process> processList =newLinkedList<Process>(); // crtTimeis total time from 0 till now, waitTime is total waiting time int crtTime =Atime[0], waitTime= 0; // addfirst process into the list processList.add(newProcess(Atime[0], Etime[0])); // indexof all original process int index = 1; while(!processList.isEmpty()){ Process crtProcess =processList.poll(); waitTime += crtTime -crtProcess.aTime; crtTime += crtProcess.eTime< q ? crtProcess.eTime : q; for(; index< len && Atime[index] <= crtTime; ++index) processList.add(newProcess(Atime[index], Etime[index])); if(crtProcess.eTime> q) processList.add(newProcess(crtTime, crtProcess.eTime - q)); } return (float)waitTime /len; } } /*==================另一种理解======================================================================================*/ /* 示例输入: request time: [0,1,3,9] duration: [2,1,7,5] q=3 average waiting time : 0.5 request time: [0,2,4,5] duration: [7,4,1,4] q=3 average waiting time : 7 即在剩下的request里选择duration小的,这样就不能用queue做了。 */ private static double roundRobin(int[] arrivetime, int[] executiontime, int q) { // TODO Auto-generated method stub LinkedList<process> que = new LinkedList<process>(); if(arrivetime.length < 1 || executiontime.length < 1) return 0; int currentTime = 0; int waitTime = 0; int nextP = 0; while(true) { if(!que.isEmpty()) { process curP = que.poll(); waitTime += currentTime - arrivetime[nextP]; if(curP.excuteTime <= q) { currentTime += curP.excuteTime; executiontime[nextP] = executiontime[nextP]- curP.excuteTime; } else { currentTime+= q; arrivetime[nextP] = currentTime; executiontime[nextP] = executiontime[nextP]-q; //System.out.println(currentTime +"\t"+arrivetime[nextP]+"\t"+executiontime[nextP]); } que.peek(); int min = 1000000; int count = 0; //找下一个最小 for(int i=0; i < arrivetime.length; i++) { if(arrivetime[i] <= currentTime) { if(min > executiontime[i]&& executiontime[i]>0) { min = executiontime[i]; nextP = i; } if(executiontime[i]<1) { count++; // System.out.println("i:\t"+i+" :"+executiontime[i]+"\tnow count:\t"+count); } } } if(count==arrivetime.length) { break; } }else { que.offer(new process(arrivetime[nextP],executiontime[nextP])); } } return ((double)waitTime/arrivetime.length); }
LiJinglin918/Interview_Amazon
RoundRobin.java
1,951
/*-------------------另一版本------------------------------------------------------------------------------*/
block_comment
zh-cn
/* 一个处理器要处理一堆request,一次只能处理一条,每次执行一个任务最多执行时间q,接着执行等待着的下一个任务。 若前一个任务没执行完则放到队尾,等待下一次执行。 假设只要有任务开始以后cpu是不会空闲的,也就是说cpu开始后如果空闲了就说明没有任务了,另外Robin Round最后返回值是float。 OA 示例: 例子: 【0,1,4】 【5,2,3】 q=3. 输出的是average wait time 2.3333333 第0秒,任务1进队列。我们peek目前队列中有的任务是任务1,我们发现任务1开始时间第0秒,目前也是第0秒,所以任务1等待时间是0。 然后任务1执行3秒,它自身还有2秒钟。 这时候我们查看3秒的时候哪些任务达到了,发现任务2在第1秒到达。于是任务2进队列。 这时候我们查看任务1有没有执行完,发现没有执行完,于是我们poll任务1,再把任务1 add到队列末尾。 这时候队列的顺序是任务2,任务1. 现在我们再次peek队列,于是找到任务2.我们发现任务2在第1秒到达了,目前我们在第3秒。所以等待时间是3-1=2. 我们重复刚刚的步骤,发现任务2执行时间只要2秒,于是我们到第5秒。这时候我们查找第5秒哪些任务到达了。我们发现任务3也到达了。于是任务3进队列。 所以目前队列顺序是任务2,任务1,任务3. 我们又发现任务2已经执行完了,于是我们把任务2 poll出队列,不再把它放进队列里了。 所以现在队列里面剩余的任务是任务1,任务3. 于是我们再peek队列。请注意,这时候的q被重新设置过了,不是3-2=1秒,而是又是3秒。 我们再次peek队列,找到任务1,目前是在第5秒,我们刚刚执行过任务1,他暂停在第3秒,所以任务1又等了2秒。目前秒数是2+2=4秒。 目前任务1还有2秒。我们执行完任务1以后,到达第5+2 = 7把他扔出队列。目前队列里只有任务3了。 然后我们再peek,现在只有任务3了,目前我们在第7秒。任务3进来的时候在第4秒。所以任务3等了7-4 = 3秒。所以等待时间又加3秒。 所以最终等待时间是2+2+3 = 7秒。平均等待时间是7/3 = 2.3333秒。 */ import java.util.LinkedList; import java.util.Queue; class process { int arrTime; int exeTime; process(int arr, int exe) { arrTime = arr; exeTime = exe; } } public class RoundRobinScheduling { public float Solution(int[] Atime, int[] Etime, int q) { // Corner case if (Atime == null || Etime == null || Atime.length != Etime.length) return 0; int length = Atime.length; Queue<process> queue = new LinkedList<process>(); int curTime = 0, waitTime = 0; int index = 0; while (!queue.isEmpty() || index < length) { if (!queue.isEmpty()) { process cur = queue.poll(); waitTime += curTime - cur.arrTime; curTime += Math.min(cur.exeTime, q); for (; index < length && Atime[index] <= curTime; index++) queue.offer(new process(Atime[index], Etime[index])); if (cur.exeTime > q) queue.offer(new process(curTime, cur.exeTime - q)); } else { queue.offer(new process(Atime[index], Etime[index])); curTime = Atime[index++]; } } return (float) waitTime / length; } } /*--- <SUF>*/ public classRoundRobinScheduling { public static float Solution(int[] Atime, int[] Etime, int q) { if(Atime == null || Etime ==null ||Atime.length <= 1 ||Etime.length <= 1 ||Atime.length != Etime.length) return 0; int len =Atime.length; // usequeue data structure to store every process Queue<Process> processList =newLinkedList<Process>(); // crtTimeis total time from 0 till now, waitTime is total waiting time int crtTime =Atime[0], waitTime= 0; // addfirst process into the list processList.add(newProcess(Atime[0], Etime[0])); // indexof all original process int index = 1; while(!processList.isEmpty()){ Process crtProcess =processList.poll(); waitTime += crtTime -crtProcess.aTime; crtTime += crtProcess.eTime< q ? crtProcess.eTime : q; for(; index< len && Atime[index] <= crtTime; ++index) processList.add(newProcess(Atime[index], Etime[index])); if(crtProcess.eTime> q) processList.add(newProcess(crtTime, crtProcess.eTime - q)); } return (float)waitTime /len; } } /*==================另一种理解======================================================================================*/ /* 示例输入: request time: [0,1,3,9] duration: [2,1,7,5] q=3 average waiting time : 0.5 request time: [0,2,4,5] duration: [7,4,1,4] q=3 average waiting time : 7 即在剩下的request里选择duration小的,这样就不能用queue做了。 */ private static double roundRobin(int[] arrivetime, int[] executiontime, int q) { // TODO Auto-generated method stub LinkedList<process> que = new LinkedList<process>(); if(arrivetime.length < 1 || executiontime.length < 1) return 0; int currentTime = 0; int waitTime = 0; int nextP = 0; while(true) { if(!que.isEmpty()) { process curP = que.poll(); waitTime += currentTime - arrivetime[nextP]; if(curP.excuteTime <= q) { currentTime += curP.excuteTime; executiontime[nextP] = executiontime[nextP]- curP.excuteTime; } else { currentTime+= q; arrivetime[nextP] = currentTime; executiontime[nextP] = executiontime[nextP]-q; //System.out.println(currentTime +"\t"+arrivetime[nextP]+"\t"+executiontime[nextP]); } que.peek(); int min = 1000000; int count = 0; //找下一个最小 for(int i=0; i < arrivetime.length; i++) { if(arrivetime[i] <= currentTime) { if(min > executiontime[i]&& executiontime[i]>0) { min = executiontime[i]; nextP = i; } if(executiontime[i]<1) { count++; // System.out.println("i:\t"+i+" :"+executiontime[i]+"\tnow count:\t"+count); } } } if(count==arrivetime.length) { break; } }else { que.offer(new process(arrivetime[nextP],executiontime[nextP])); } } return ((double)waitTime/arrivetime.length); }
false
1,756
8
1,951
8
1,984
11
1,951
8
2,617
16
false
false
false
false
false
true
32507_22
package com.cleartv.text2speech; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.cleartv.text2speech.beans.ErrorMsgBean; import com.cleartv.text2speech.beans.MsgBean; import com.cleartv.text2speech.beans.SpeakerParamsBean; import com.cleartv.text2speech.beans.SpeechListBean; import com.cleartv.text2speech.utils.SPUtil; import com.cleartv.text2speech.utils.Utils; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SynthesizerListener; import java.util.ArrayList; import java.util.LinkedList; /** * Created by Lipengfei on 2017/4/20. */ public class SpeechManager { private static final String TAG = "SpeechManager"; private static SpeechManager manager; public boolean isSpeechInit = false; private Context context; // 语音合成对象 private static com.iflytek.cloud.SpeechSynthesizer mTts; // 提示音间隔时间 public static long intervalTime = 15000; private long lastSpeechTime = 0; private SoundPool mSoundPool; /** * 发音人 */ // public final static String[] COLOUD_VOICERS_ENTRIES = {"小燕", "小宇", "凯瑟琳", "亨利", "玛丽", "小研", "小琪", "小峰", "小梅", "小莉", "小蓉", "小芸", "小坤", "小强 ", "小莹", // "小新", "楠楠", "老孙","Mariane","Allabent","Gabriela","Abha","XiaoYun"}; // public final static String[] COLOUD_VOICERS_VALUE = {"xiaoyan", "xiaoyu", "catherine", "henry", "vimary", "vixy", "xiaoqi", "vixf", "xiaomei", // "xiaolin", "xiaorong", "xiaoqian", "xiaokun", "xiaoqiang", "vixying", "xiaoxin", "nannan", "vils","Mariane","Allabent","Gabriela","Abha","XiaoYun"}; private SpeechListBean speechListBean; private LinkedList<ErrorMsgBean> failedMsg = new LinkedList<>(); private SynthesizerListener synthesizerListener = new SynthesizerListener() { @Override public void onSpeakBegin() { Log.i(TAG, "开始播放"); sendMsg(Action.ACTION_SPEAKING_STARTE,"onSpeakBegin:"+speechListBean.speakingMsg.getText(),speechListBean.speakingMsg.getId()); } @Override public void onSpeakPaused() { Log.i(TAG, "暂停播放"); } @Override public void onSpeakResumed() { Log.i(TAG, "继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // TODO 缓冲的进度 Log.i(TAG, "缓冲 : " + percent); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // TODO 说话的进度 Log.i(TAG, "合成 : " + percent); } @Override public void onCompleted(com.iflytek.cloud.SpeechError error) { if (error == null) { Log.i(TAG, "播放完成"); try { sendMsg(Action.ACTION_SPEAKING_END,"onCompleted:"+speechListBean.speakingMsg.getText(),speechListBean.speakingMsg.getId()); } catch (Exception e) { e.printStackTrace(); Log.i(TAG, error.getPlainDescription(true)); sendMsg(Action.ACTION_SPEAKING_ERROR,e.getMessage(),speechListBean.speakingMsg.getId()); } } else if (error != null) { Log.i(TAG, error.getPlainDescription(true)); if(failedMsg.size()>300) failedMsg.removeFirst(); failedMsg.addLast(new ErrorMsgBean(speechListBean.speakingMsg,System.currentTimeMillis(),error.getErrorCode(),error.getErrorDescription())); sendMsg(Action.ACTION_SPEAKING_ERROR,"error code : "+ error.getErrorCode()+error.getPlainDescription(true),speechListBean.speakingMsg.getId()); } lastSpeechTime = System.currentTimeMillis(); startSpeak(); } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { } }; public static SpeechManager getInstance() { if(manager == null){ manager = new SpeechManager(); } return manager; } public void init(final Context context) { this.context = context; if(speechListBean == null){ speechListBean = new SpeechListBean(); speechListBean.speechList = new LinkedList<>(); } mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM,5); mSoundPool.load(context,R.raw.dingdong,1); // 初始化合成对象 if(mTts == null || !isSpeechInit){ mTts = com.iflytek.cloud.SpeechSynthesizer.createSynthesizer(context, new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { sendMsg(Action.ACTION_SPEAKER_FAILED,"初始化语音合成失败 code:"+code); isSpeechInit = false; }else{ sendMsg(Action.ACTION_SPEAKER_SUCCESS,"初始化语音合成成功 code:"+code); isSpeechInit = true; // 设置音量 mTts.setParameter(SpeechConstant.VOLUME, (String) SPUtil.get(context,SpeechConstant.VOLUME, "100")); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, (String) SPUtil.get(context,SpeechConstant.PITCH, "50")); // 设置语速 mTts.setParameter(SpeechConstant.SPEED, (String) SPUtil.get(context,SpeechConstant.SPEED, "50")); } } }); }else{ sendMsg(Action.ACTION_SPEAKER_SUCCESS,"语音合成已初始化"); } } public SpeakerParamsBean getSpeakerParams(){ return new SpeakerParamsBean(mTts.getParameter(SpeechConstant.VOLUME),mTts.getParameter(SpeechConstant.PITCH),mTts.getParameter(SpeechConstant.SPEED)); } public void setSpeaker(String[] atrs){ // 设置语言 // mTts.setParameter(SpeechConstant.LANGUAGE, ""); // // 设置方言 // mTts.setParameter(SpeechConstant.ACCENT, ""); // // 设置发音人 // mTts.setParameter(SpeechConstant.VOICE_NAME, requestBean.getSpeaker()); // 设置音量 SPUtil.putAndApply(context,SpeechConstant.VOLUME, atrs[0]); mTts.setParameter(SpeechConstant.VOLUME, atrs[0]); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, atrs[1]); SPUtil.putAndApply(context,SpeechConstant.PITCH, atrs[1]); // 设置语速 mTts.setParameter(SpeechConstant.SPEED, atrs[2]); SPUtil.putAndApply(context,SpeechConstant.SPEED, atrs[2]); } public void speakSingleMsg(String msg,String id,int index){ if(index>speechListBean.speechList.size()) index = speechListBean.speechList.size(); speechListBean.speechList.add(index , new MsgBean(id,msg)); if(!mTts.isSpeaking()) startSpeak(); } public boolean addMsgByJson(String jsonMsg) { ArrayList<MsgBean> beans = Utils.getBeanListFromJson(jsonMsg,MsgBean.class); if(beans == null || beans.size()<1){ sendMsg(Action.ACTION_SPEAKING_ERROR,"Probably JsonError:\n"+jsonMsg); return false; } for(MsgBean msg : beans){ if(msg!=null && !TextUtils.isEmpty(msg.getText())){ speechListBean.speechList.addLast(msg); } } if(!mTts.isSpeaking()) startSpeak(); return true; } private void startSpeak() { if(speechListBean.speechList.isEmpty()){ // 转换完毕 speechListBean.speakingMsg = null; }else { if(intervalTime > 0 && System.currentTimeMillis() - lastSpeechTime > intervalTime){ // TODO mSoundPool.play(1,1, 1, 0, 0, 1); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } } speechListBean.speakingMsg = speechListBean.speechList.removeFirst(); int code = mTts.startSpeaking(speechListBean.speakingMsg.getText(), synthesizerListener); if (code != ErrorCode.SUCCESS) { if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) { sendMsg(Action.ACTION_SPEAKING_ERROR, "没有安装语音,错误码: " + code); } else { sendMsg(Action.ACTION_SPEAKING_ERROR, "语音合成失败,错误码: " + code); } } } } public void stopSpeaking() { mTts.stopSpeaking(); } public void pauseSpeaking() { mTts.pauseSpeaking(); } public void resumeSpeaking() { mTts.resumeSpeaking(); } public void clearSpeaking() { speechListBean.speechList.clear(); } public void clearFailedList() { failedMsg.clear(); } // 发送广播 private void sendMsg(String action,String msg){ Intent intent = new Intent(); intent.setAction(action); intent.putExtra("msg",msg); context.sendBroadcast(intent); } private void sendMsg(String action,String msg,String id){ Intent intent = new Intent(); intent.setAction(action); intent.putExtra("msg",msg); intent.putExtra("id",id); context.sendBroadcast(intent); } public String getMsgListInfo(){ return Utils.getJsonFromBean(speechListBean); } public SpeechListBean getSpeechListBean(){ return speechListBean; } public LinkedList<ErrorMsgBean> getFailedMsg(){ return failedMsg; } public String getFailedListInfo(){ return Utils.getJsonFromBean(failedMsg); } }
LiPengfei0106/textTospeech_xunfei
src/main/java/com/cleartv/text2speech/SpeechManager.java
2,673
// 设置语速
line_comment
zh-cn
package com.cleartv.text2speech; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.cleartv.text2speech.beans.ErrorMsgBean; import com.cleartv.text2speech.beans.MsgBean; import com.cleartv.text2speech.beans.SpeakerParamsBean; import com.cleartv.text2speech.beans.SpeechListBean; import com.cleartv.text2speech.utils.SPUtil; import com.cleartv.text2speech.utils.Utils; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SynthesizerListener; import java.util.ArrayList; import java.util.LinkedList; /** * Created by Lipengfei on 2017/4/20. */ public class SpeechManager { private static final String TAG = "SpeechManager"; private static SpeechManager manager; public boolean isSpeechInit = false; private Context context; // 语音合成对象 private static com.iflytek.cloud.SpeechSynthesizer mTts; // 提示音间隔时间 public static long intervalTime = 15000; private long lastSpeechTime = 0; private SoundPool mSoundPool; /** * 发音人 */ // public final static String[] COLOUD_VOICERS_ENTRIES = {"小燕", "小宇", "凯瑟琳", "亨利", "玛丽", "小研", "小琪", "小峰", "小梅", "小莉", "小蓉", "小芸", "小坤", "小强 ", "小莹", // "小新", "楠楠", "老孙","Mariane","Allabent","Gabriela","Abha","XiaoYun"}; // public final static String[] COLOUD_VOICERS_VALUE = {"xiaoyan", "xiaoyu", "catherine", "henry", "vimary", "vixy", "xiaoqi", "vixf", "xiaomei", // "xiaolin", "xiaorong", "xiaoqian", "xiaokun", "xiaoqiang", "vixying", "xiaoxin", "nannan", "vils","Mariane","Allabent","Gabriela","Abha","XiaoYun"}; private SpeechListBean speechListBean; private LinkedList<ErrorMsgBean> failedMsg = new LinkedList<>(); private SynthesizerListener synthesizerListener = new SynthesizerListener() { @Override public void onSpeakBegin() { Log.i(TAG, "开始播放"); sendMsg(Action.ACTION_SPEAKING_STARTE,"onSpeakBegin:"+speechListBean.speakingMsg.getText(),speechListBean.speakingMsg.getId()); } @Override public void onSpeakPaused() { Log.i(TAG, "暂停播放"); } @Override public void onSpeakResumed() { Log.i(TAG, "继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // TODO 缓冲的进度 Log.i(TAG, "缓冲 : " + percent); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // TODO 说话的进度 Log.i(TAG, "合成 : " + percent); } @Override public void onCompleted(com.iflytek.cloud.SpeechError error) { if (error == null) { Log.i(TAG, "播放完成"); try { sendMsg(Action.ACTION_SPEAKING_END,"onCompleted:"+speechListBean.speakingMsg.getText(),speechListBean.speakingMsg.getId()); } catch (Exception e) { e.printStackTrace(); Log.i(TAG, error.getPlainDescription(true)); sendMsg(Action.ACTION_SPEAKING_ERROR,e.getMessage(),speechListBean.speakingMsg.getId()); } } else if (error != null) { Log.i(TAG, error.getPlainDescription(true)); if(failedMsg.size()>300) failedMsg.removeFirst(); failedMsg.addLast(new ErrorMsgBean(speechListBean.speakingMsg,System.currentTimeMillis(),error.getErrorCode(),error.getErrorDescription())); sendMsg(Action.ACTION_SPEAKING_ERROR,"error code : "+ error.getErrorCode()+error.getPlainDescription(true),speechListBean.speakingMsg.getId()); } lastSpeechTime = System.currentTimeMillis(); startSpeak(); } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { } }; public static SpeechManager getInstance() { if(manager == null){ manager = new SpeechManager(); } return manager; } public void init(final Context context) { this.context = context; if(speechListBean == null){ speechListBean = new SpeechListBean(); speechListBean.speechList = new LinkedList<>(); } mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM,5); mSoundPool.load(context,R.raw.dingdong,1); // 初始化合成对象 if(mTts == null || !isSpeechInit){ mTts = com.iflytek.cloud.SpeechSynthesizer.createSynthesizer(context, new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { sendMsg(Action.ACTION_SPEAKER_FAILED,"初始化语音合成失败 code:"+code); isSpeechInit = false; }else{ sendMsg(Action.ACTION_SPEAKER_SUCCESS,"初始化语音合成成功 code:"+code); isSpeechInit = true; // 设置音量 mTts.setParameter(SpeechConstant.VOLUME, (String) SPUtil.get(context,SpeechConstant.VOLUME, "100")); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, (String) SPUtil.get(context,SpeechConstant.PITCH, "50")); // 设置语速 mTts.setParameter(SpeechConstant.SPEED, (String) SPUtil.get(context,SpeechConstant.SPEED, "50")); } } }); }else{ sendMsg(Action.ACTION_SPEAKER_SUCCESS,"语音合成已初始化"); } } public SpeakerParamsBean getSpeakerParams(){ return new SpeakerParamsBean(mTts.getParameter(SpeechConstant.VOLUME),mTts.getParameter(SpeechConstant.PITCH),mTts.getParameter(SpeechConstant.SPEED)); } public void setSpeaker(String[] atrs){ // 设置语言 // mTts.setParameter(SpeechConstant.LANGUAGE, ""); // // 设置方言 // mTts.setParameter(SpeechConstant.ACCENT, ""); // // 设置发音人 // mTts.setParameter(SpeechConstant.VOICE_NAME, requestBean.getSpeaker()); // 设置音量 SPUtil.putAndApply(context,SpeechConstant.VOLUME, atrs[0]); mTts.setParameter(SpeechConstant.VOLUME, atrs[0]); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, atrs[1]); SPUtil.putAndApply(context,SpeechConstant.PITCH, atrs[1]); // 设置 <SUF> mTts.setParameter(SpeechConstant.SPEED, atrs[2]); SPUtil.putAndApply(context,SpeechConstant.SPEED, atrs[2]); } public void speakSingleMsg(String msg,String id,int index){ if(index>speechListBean.speechList.size()) index = speechListBean.speechList.size(); speechListBean.speechList.add(index , new MsgBean(id,msg)); if(!mTts.isSpeaking()) startSpeak(); } public boolean addMsgByJson(String jsonMsg) { ArrayList<MsgBean> beans = Utils.getBeanListFromJson(jsonMsg,MsgBean.class); if(beans == null || beans.size()<1){ sendMsg(Action.ACTION_SPEAKING_ERROR,"Probably JsonError:\n"+jsonMsg); return false; } for(MsgBean msg : beans){ if(msg!=null && !TextUtils.isEmpty(msg.getText())){ speechListBean.speechList.addLast(msg); } } if(!mTts.isSpeaking()) startSpeak(); return true; } private void startSpeak() { if(speechListBean.speechList.isEmpty()){ // 转换完毕 speechListBean.speakingMsg = null; }else { if(intervalTime > 0 && System.currentTimeMillis() - lastSpeechTime > intervalTime){ // TODO mSoundPool.play(1,1, 1, 0, 0, 1); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } } speechListBean.speakingMsg = speechListBean.speechList.removeFirst(); int code = mTts.startSpeaking(speechListBean.speakingMsg.getText(), synthesizerListener); if (code != ErrorCode.SUCCESS) { if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) { sendMsg(Action.ACTION_SPEAKING_ERROR, "没有安装语音,错误码: " + code); } else { sendMsg(Action.ACTION_SPEAKING_ERROR, "语音合成失败,错误码: " + code); } } } } public void stopSpeaking() { mTts.stopSpeaking(); } public void pauseSpeaking() { mTts.pauseSpeaking(); } public void resumeSpeaking() { mTts.resumeSpeaking(); } public void clearSpeaking() { speechListBean.speechList.clear(); } public void clearFailedList() { failedMsg.clear(); } // 发送广播 private void sendMsg(String action,String msg){ Intent intent = new Intent(); intent.setAction(action); intent.putExtra("msg",msg); context.sendBroadcast(intent); } private void sendMsg(String action,String msg,String id){ Intent intent = new Intent(); intent.setAction(action); intent.putExtra("msg",msg); intent.putExtra("id",id); context.sendBroadcast(intent); } public String getMsgListInfo(){ return Utils.getJsonFromBean(speechListBean); } public SpeechListBean getSpeechListBean(){ return speechListBean; } public LinkedList<ErrorMsgBean> getFailedMsg(){ return failedMsg; } public String getFailedListInfo(){ return Utils.getJsonFromBean(failedMsg); } }
false
2,314
5
2,648
5
2,698
5
2,648
5
3,266
7
false
false
false
false
false
true
38621_3
package com.imooc.netty.ch11; import io.netty.channel.ChannelFuture; import io.netty.channel.socket.nio.NioSocketChannel; import java.util.ArrayList; import java.util.List; public class ObserverTest { /** * 被观察者 */ public interface Observerable { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObserver(); } /** * 观察者 */ public interface Observer { void notify(String message); } public static class Girl implements Observerable { private String message; List<Observer> observerList; public Girl() { observerList = new ArrayList<>(); } @Override public void registerObserver(Observer o) { observerList.add(o); } @Override public void removeObserver(Observer o) { observerList.remove(o); } @Override public void notifyObserver() { for (Observer observer : observerList) { observer.notify(message); } } public void hasBoyFriend() { message = "女神有男朋友了"; notifyObserver(); } public void getMarried() { message = "女神结婚了,你们都死心吧!"; notifyObserver(); } public void getSingled() { message = "女神单身了,你们有机会了!"; notifyObserver(); } } /** * 男孩 */ public static class Boy implements Observer { public void notify(String message) { System.out.println("男孩收到消息:" + message); } } /** * 男人 */ public static class Man implements Observer { public void notify(String message) { System.out.println("男人收到消息:" + message); } } /** * 老男人 */ public static class OldMan implements Observer { public void notify(String message) { System.out.println("老男人收到消息:" + message); } } public static void main(String[] args) { Girl girl = new Girl(); Boy boy = new Boy(); Man man = new Man(); OldMan oldMan = new OldMan(); // 通知男孩、男人、老男人,女神有男朋友了 girl.registerObserver(boy); girl.registerObserver(man); girl.registerObserver(oldMan); girl.hasBoyFriend(); System.out.println("===================="); // 通知男孩,男人,女神结婚了 girl.removeObserver(oldMan); girl.getMarried(); System.out.println("===================="); girl.registerObserver(oldMan); girl.getSingled(); } public void write(NioSocketChannel channel, Object object) { ChannelFuture channelFuture = channel.writeAndFlush(object); channelFuture.addListener(future -> { if (future.isSuccess()) { } else { } }); channelFuture.addListener(future -> { if (future.isSuccess()) { } else { } }); channelFuture.addListener(future -> { if (future.isSuccess()) { } else { } }); } }
LiWenGu/learn-netty
netty-depth-analysis-code/src/main/java/com/imooc/netty/ch11/ObserverTest.java
768
/** * 男人 */
block_comment
zh-cn
package com.imooc.netty.ch11; import io.netty.channel.ChannelFuture; import io.netty.channel.socket.nio.NioSocketChannel; import java.util.ArrayList; import java.util.List; public class ObserverTest { /** * 被观察者 */ public interface Observerable { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObserver(); } /** * 观察者 */ public interface Observer { void notify(String message); } public static class Girl implements Observerable { private String message; List<Observer> observerList; public Girl() { observerList = new ArrayList<>(); } @Override public void registerObserver(Observer o) { observerList.add(o); } @Override public void removeObserver(Observer o) { observerList.remove(o); } @Override public void notifyObserver() { for (Observer observer : observerList) { observer.notify(message); } } public void hasBoyFriend() { message = "女神有男朋友了"; notifyObserver(); } public void getMarried() { message = "女神结婚了,你们都死心吧!"; notifyObserver(); } public void getSingled() { message = "女神单身了,你们有机会了!"; notifyObserver(); } } /** * 男孩 */ public static class Boy implements Observer { public void notify(String message) { System.out.println("男孩收到消息:" + message); } } /** * 男人 <SUF>*/ public static class Man implements Observer { public void notify(String message) { System.out.println("男人收到消息:" + message); } } /** * 老男人 */ public static class OldMan implements Observer { public void notify(String message) { System.out.println("老男人收到消息:" + message); } } public static void main(String[] args) { Girl girl = new Girl(); Boy boy = new Boy(); Man man = new Man(); OldMan oldMan = new OldMan(); // 通知男孩、男人、老男人,女神有男朋友了 girl.registerObserver(boy); girl.registerObserver(man); girl.registerObserver(oldMan); girl.hasBoyFriend(); System.out.println("===================="); // 通知男孩,男人,女神结婚了 girl.removeObserver(oldMan); girl.getMarried(); System.out.println("===================="); girl.registerObserver(oldMan); girl.getSingled(); } public void write(NioSocketChannel channel, Object object) { ChannelFuture channelFuture = channel.writeAndFlush(object); channelFuture.addListener(future -> { if (future.isSuccess()) { } else { } }); channelFuture.addListener(future -> { if (future.isSuccess()) { } else { } }); channelFuture.addListener(future -> { if (future.isSuccess()) { } else { } }); } }
false
659
8
768
8
805
8
768
8
948
10
false
false
false
false
false
true
56803_3
package com.inititute.main.DesignPattern.状态模式; /** * 演示例子 * Created by LiRan on 2016-02-22. */ public class StatePattern_example { public static void main(String[] args) { Work work = new Work(); work.hour = 9; work.writeProgram(); work.hour = 11; work.writeProgram(); work.hour = 12; work.writeProgram(); work.hour = 15; work.writeProgram(); work.isFinish=true; work.hour = 19; work.writeProgram(); work.hour = 21; work.writeProgram(); work.hour = 22; work.writeProgram(); work.hour = 23; work.writeProgram(); } } class Work { public int hour; public boolean isFinish; private WorkState current; public Work() { current = new MorinigState(); } public WorkState getState() { return current; } public void setState(WorkState current) { this.current = current; } public void writeProgram() { current.writeProgram(this); } } /** * 抽象工作状态类 */ abstract class WorkState { abstract public void writeProgram(Work w); } /** * 上午工作状态 */ class MorinigState extends WorkState { @Override public void writeProgram(Work w) { if (w.hour < 12) { System.out.println("当前时间是:" + w.hour + " 精神百倍"); } else { w.setState(new noonState()); w.writeProgram(); } } } /** * 中午工作状态 */ class noonState extends WorkState { @Override public void writeProgram(Work w) { if (w.hour < 13) { System.out.println("当前时间是:" + w.hour + " 吃午饭 困 午休 "); } else { w.setState(new afternoonState()); w.writeProgram(); } } } /** * 下午工作状态 */ class afternoonState extends WorkState { @Override public void writeProgram(Work w) { if (w.hour < 17) { System.out.println("当前时间是:" + w.hour + " 感觉状态还不错 "); } else { w.setState(new eveningState()); w.writeProgram(); } } } /** * 晚上工作状态 */ class eveningState extends WorkState { @Override public void writeProgram(Work w) { if (w.isFinish) { w.setState(new restState()); w.writeProgram(); } else { if (w.hour < 21) { System.out.println("当前时间是:" + w.hour + " 加班啊 "); } else { w.setState(new SleepingState()); w.writeProgram(); } } } } class SleepingState extends WorkState { @Override public void writeProgram(Work w) { System.out.println("当前时间是:" + w.hour + " 不行了 睡着了 "); } } class restState extends WorkState { @Override public void writeProgram(Work w) { System.out.println("当前时间是:" + w.hour + " 下班回家了 "); } }
LiXiaoRan/AndroidStudio_Workspace
javaproject/src/main/java/com/inititute/main/DesignPattern/状态模式/StatePattern_example.java
849
/** * 中午工作状态 */
block_comment
zh-cn
package com.inititute.main.DesignPattern.状态模式; /** * 演示例子 * Created by LiRan on 2016-02-22. */ public class StatePattern_example { public static void main(String[] args) { Work work = new Work(); work.hour = 9; work.writeProgram(); work.hour = 11; work.writeProgram(); work.hour = 12; work.writeProgram(); work.hour = 15; work.writeProgram(); work.isFinish=true; work.hour = 19; work.writeProgram(); work.hour = 21; work.writeProgram(); work.hour = 22; work.writeProgram(); work.hour = 23; work.writeProgram(); } } class Work { public int hour; public boolean isFinish; private WorkState current; public Work() { current = new MorinigState(); } public WorkState getState() { return current; } public void setState(WorkState current) { this.current = current; } public void writeProgram() { current.writeProgram(this); } } /** * 抽象工作状态类 */ abstract class WorkState { abstract public void writeProgram(Work w); } /** * 上午工作状态 */ class MorinigState extends WorkState { @Override public void writeProgram(Work w) { if (w.hour < 12) { System.out.println("当前时间是:" + w.hour + " 精神百倍"); } else { w.setState(new noonState()); w.writeProgram(); } } } /** * 中午工 <SUF>*/ class noonState extends WorkState { @Override public void writeProgram(Work w) { if (w.hour < 13) { System.out.println("当前时间是:" + w.hour + " 吃午饭 困 午休 "); } else { w.setState(new afternoonState()); w.writeProgram(); } } } /** * 下午工作状态 */ class afternoonState extends WorkState { @Override public void writeProgram(Work w) { if (w.hour < 17) { System.out.println("当前时间是:" + w.hour + " 感觉状态还不错 "); } else { w.setState(new eveningState()); w.writeProgram(); } } } /** * 晚上工作状态 */ class eveningState extends WorkState { @Override public void writeProgram(Work w) { if (w.isFinish) { w.setState(new restState()); w.writeProgram(); } else { if (w.hour < 21) { System.out.println("当前时间是:" + w.hour + " 加班啊 "); } else { w.setState(new SleepingState()); w.writeProgram(); } } } } class SleepingState extends WorkState { @Override public void writeProgram(Work w) { System.out.println("当前时间是:" + w.hour + " 不行了 睡着了 "); } } class restState extends WorkState { @Override public void writeProgram(Work w) { System.out.println("当前时间是:" + w.hour + " 下班回家了 "); } }
false
733
8
849
9
886
9
849
9
1,049
14
false
false
false
false
false
true
15520_6
/** * 567. Permutation in String (https://leetcode.com/problems/permutation-in-string/) */ public class PermutationInString { /*********** Solution 1: Sliding Window with Fixed Size ******************/ /** * 类似 438. Find All Anagrams in a String (https://leetcode.com/problems/find-all-anagrams-in-a-string/description/) * 简单版的 * * Time: O(S1 + S2) Space: O(1) */ public boolean checkInclusion(String s1, String s2) { // iterate over s1 to build counter int[] counter = new int[26]; int debt = 0; for (char c : s1.toCharArray()) { if (counter[c - 'a'] == 0) debt++; counter[c - 'a']++; } // iterate over s2, keep sliding window of size = s1.length() & update counter for (int i = 0; i < s2.length(); i++) { // 右侧进来 int in = s2.charAt(i) - 'a'; if (counter[in] == 0) debt++; counter[in]--; if (counter[in] == 0) debt--; if (i >= s1.length()) { // 左侧出去 int out = s2.charAt(i - s1.length()) - 'a'; if (counter[out] == 0) debt++; counter[out]++; if (counter[out] == 0) debt--; } // 比较 s1 和 window 是否全等 // 注意!!!在 if 外面,不然 TC#3 会 fail if (debt == 0) return true; } return false; } public static void main(String[] args) { PermutationInString solution = new PermutationInString(); // TC#1 System.out.println(solution.checkInclusion("ab", "eidbaooo")); //true // TC#2 System.out.println(solution.checkInclusion("ab", "eidboaooo")); //false // TC#3 System.out.println(solution.checkInclusion("a", "ab")); //true } }
LiXieLabs/codingpractice
src/PermutationInString.java
540
// 左侧出去
line_comment
zh-cn
/** * 567. Permutation in String (https://leetcode.com/problems/permutation-in-string/) */ public class PermutationInString { /*********** Solution 1: Sliding Window with Fixed Size ******************/ /** * 类似 438. Find All Anagrams in a String (https://leetcode.com/problems/find-all-anagrams-in-a-string/description/) * 简单版的 * * Time: O(S1 + S2) Space: O(1) */ public boolean checkInclusion(String s1, String s2) { // iterate over s1 to build counter int[] counter = new int[26]; int debt = 0; for (char c : s1.toCharArray()) { if (counter[c - 'a'] == 0) debt++; counter[c - 'a']++; } // iterate over s2, keep sliding window of size = s1.length() & update counter for (int i = 0; i < s2.length(); i++) { // 右侧进来 int in = s2.charAt(i) - 'a'; if (counter[in] == 0) debt++; counter[in]--; if (counter[in] == 0) debt--; if (i >= s1.length()) { // 左侧 <SUF> int out = s2.charAt(i - s1.length()) - 'a'; if (counter[out] == 0) debt++; counter[out]++; if (counter[out] == 0) debt--; } // 比较 s1 和 window 是否全等 // 注意!!!在 if 外面,不然 TC#3 会 fail if (debt == 0) return true; } return false; } public static void main(String[] args) { PermutationInString solution = new PermutationInString(); // TC#1 System.out.println(solution.checkInclusion("ab", "eidbaooo")); //true // TC#2 System.out.println(solution.checkInclusion("ab", "eidboaooo")); //false // TC#3 System.out.println(solution.checkInclusion("a", "ab")); //true } }
false
493
5
540
6
555
4
540
6
637
8
false
false
false
false
false
true
59565_2
import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.Queue; /** * BST * * @author LiYang * @date 2020/1/13 **/ public class BST<E extends Comparable> { private class Node{ //内部类 public E e; public Node left, right; public Node(E e){ this.e = e; left = null; right = null; } } private Node root; private int size; public BST(){ root = null; size = 0; } public int getSize() { return size; } public boolean isEmpty(){ return size == 0; } public void add(E e) { root = add(root, e); } private Node add(Node node, E e) { // 终止条件 if (node == null){ size++; return new Node(e); } // 开始递归 if (e.compareTo(node.e) < 0) node.left = add(node.left, e); else if (e.compareTo(node.e) > 0) node.right = add(node.right, e); return node; } public boolean contains(E e) { return contains(root, e); } private boolean contains(Node node, E e) { if (node == null) return false; if (e.compareTo(node.e) < 0) return contains(node.left, e); else if (e.compareTo(node.e) > 0) return contains(node.right, e); else return true; } /** 前序遍历 **/ public void preOrder(){ preOrder(root); } private void preOrder(Node node) { if (node == null) return; System.out.println(node.e); // 在前面 preOrder(node.left); preOrder(node.right); } /** 中序遍历 **/ public void inOrder() { inOrder(root); } public void preOrderNR(){ Stack<Node> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { Node cur = stack.pop(); System.out.println(cur.e); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); } } private void inOrder(Node node) { if (node == null) return; inOrder(node.left); System.out.println(node.e); // 在中间 三角形 inOrder(node.right); } public void lastOrder() { lastOrder(root); } private void lastOrder(Node node) { if (node == null) return; lastOrder(node.left); lastOrder(node.right); System.out.println(node.e); } public void levelOrder() { Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { Node cur = q.remove(); System.out.println(cur.e); if (cur.left != null) q.add(cur.left); if (cur.right != null) q.add(cur.right); } } public void removeMinimum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); removeMinimum(root); } private Node removeMinimum(Node node) { if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } node.left = removeMinimum(node.left); return node; } public void removeMaximum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); removeMaximum(root); } private Node removeMaximum(Node node) { if (node.right == null) { Node leftNode = node.left; node.left = null; size--; return leftNode; } node.right = removeMaximum(node.right); return node; } public void remove(E e) { root = remove(root, e); } private Node remove(Node node, E e) { if (node == null) return null; if (e.compareTo(node.e) < 0) { node.left = remove(node.left, e); return node; } else if (e.compareTo(node.e) > 0) { node.right = remove(node.right, e); return node; } else { if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } if (node.right == null) { Node leftNode = node.left; node.left = null; size--; return leftNode; } Node successor = minimum(node.right); successor.right = removeMinimum(node.right); successor.left = node.left; size++; node.left = node.right = null; size--; return successor; } } public void minimum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); System.out.println(minimum(root).e); } private Node minimum(Node node) { if (node.left == null) return node; return minimum(node.left); } public void maximum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); System.out.println(maximum(root).e); } private Node maximum(Node node) { if (node.right == null) return node; return minimum(node.right); } @Override public String toString() { StringBuilder res = new StringBuilder(); generateBSTString(root, 0, res); return res.toString(); } private void generateBSTString(Node node, int depth, StringBuilder res) { if (node == null) { res.append(generateDepthString(depth) + "null\n"); return; } res.append(generateDepthString(depth) + node.e + "null\n"); generateBSTString(node.left, depth + 1, res); generateBSTString(node.right, depth + 1, res); } private String generateDepthString(int depth) { StringBuilder res = new StringBuilder(); for (int i = 0; i < depth; i++) { res.append("--"); } return res.toString(); } public static void main(String[] args) { BST<Integer> bst = new BST<Integer>(); bst.add(10); bst.add(3); bst.add(5); bst.add(2); bst.add(12); bst.add(15); bst.add(11); System.out.println(bst.contains(1)); bst.preOrder(); System.out.println(); bst.preOrderNR(); System.out.println("inOrder"); bst.inOrder(); System.out.println(); bst.lastOrder(); System.out.println(); bst.levelOrder(); System.out.println(); bst.removeMinimum(); bst.levelOrder(); System.out.println(); bst.minimum(); } }
LiYangSir/Data-Structures-and-Algorithms
BST/BST.java
1,787
// 终止条件
line_comment
zh-cn
import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.Queue; /** * BST * * @author LiYang * @date 2020/1/13 **/ public class BST<E extends Comparable> { private class Node{ //内部类 public E e; public Node left, right; public Node(E e){ this.e = e; left = null; right = null; } } private Node root; private int size; public BST(){ root = null; size = 0; } public int getSize() { return size; } public boolean isEmpty(){ return size == 0; } public void add(E e) { root = add(root, e); } private Node add(Node node, E e) { // 终止 <SUF> if (node == null){ size++; return new Node(e); } // 开始递归 if (e.compareTo(node.e) < 0) node.left = add(node.left, e); else if (e.compareTo(node.e) > 0) node.right = add(node.right, e); return node; } public boolean contains(E e) { return contains(root, e); } private boolean contains(Node node, E e) { if (node == null) return false; if (e.compareTo(node.e) < 0) return contains(node.left, e); else if (e.compareTo(node.e) > 0) return contains(node.right, e); else return true; } /** 前序遍历 **/ public void preOrder(){ preOrder(root); } private void preOrder(Node node) { if (node == null) return; System.out.println(node.e); // 在前面 preOrder(node.left); preOrder(node.right); } /** 中序遍历 **/ public void inOrder() { inOrder(root); } public void preOrderNR(){ Stack<Node> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { Node cur = stack.pop(); System.out.println(cur.e); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); } } private void inOrder(Node node) { if (node == null) return; inOrder(node.left); System.out.println(node.e); // 在中间 三角形 inOrder(node.right); } public void lastOrder() { lastOrder(root); } private void lastOrder(Node node) { if (node == null) return; lastOrder(node.left); lastOrder(node.right); System.out.println(node.e); } public void levelOrder() { Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { Node cur = q.remove(); System.out.println(cur.e); if (cur.left != null) q.add(cur.left); if (cur.right != null) q.add(cur.right); } } public void removeMinimum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); removeMinimum(root); } private Node removeMinimum(Node node) { if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } node.left = removeMinimum(node.left); return node; } public void removeMaximum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); removeMaximum(root); } private Node removeMaximum(Node node) { if (node.right == null) { Node leftNode = node.left; node.left = null; size--; return leftNode; } node.right = removeMaximum(node.right); return node; } public void remove(E e) { root = remove(root, e); } private Node remove(Node node, E e) { if (node == null) return null; if (e.compareTo(node.e) < 0) { node.left = remove(node.left, e); return node; } else if (e.compareTo(node.e) > 0) { node.right = remove(node.right, e); return node; } else { if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } if (node.right == null) { Node leftNode = node.left; node.left = null; size--; return leftNode; } Node successor = minimum(node.right); successor.right = removeMinimum(node.right); successor.left = node.left; size++; node.left = node.right = null; size--; return successor; } } public void minimum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); System.out.println(minimum(root).e); } private Node minimum(Node node) { if (node.left == null) return node; return minimum(node.left); } public void maximum() { if (size == 0) throw new IllegalArgumentException("BST is empty"); System.out.println(maximum(root).e); } private Node maximum(Node node) { if (node.right == null) return node; return minimum(node.right); } @Override public String toString() { StringBuilder res = new StringBuilder(); generateBSTString(root, 0, res); return res.toString(); } private void generateBSTString(Node node, int depth, StringBuilder res) { if (node == null) { res.append(generateDepthString(depth) + "null\n"); return; } res.append(generateDepthString(depth) + node.e + "null\n"); generateBSTString(node.left, depth + 1, res); generateBSTString(node.right, depth + 1, res); } private String generateDepthString(int depth) { StringBuilder res = new StringBuilder(); for (int i = 0; i < depth; i++) { res.append("--"); } return res.toString(); } public static void main(String[] args) { BST<Integer> bst = new BST<Integer>(); bst.add(10); bst.add(3); bst.add(5); bst.add(2); bst.add(12); bst.add(15); bst.add(11); System.out.println(bst.contains(1)); bst.preOrder(); System.out.println(); bst.preOrderNR(); System.out.println("inOrder"); bst.inOrder(); System.out.println(); bst.lastOrder(); System.out.println(); bst.levelOrder(); System.out.println(); bst.removeMinimum(); bst.levelOrder(); System.out.println(); bst.minimum(); } }
false
1,538
5
1,787
5
1,981
4
1,787
5
2,139
8
false
false
false
false
false
true
28573_13
package 数据结构; class Sort { public int[] sortArray(int[] nums) { if(nums.length <=1)return nums; //qSort(nums,0,nums.length-1); //selectSort(nums); // insertSort(nums); // shellSort(nums); // bucketSort(nums); // countSort(nums); // mergeSort(nums,0,nums.length-1); heapSort(nums); return nums; } /** * 冒泡排序 * 稳定的算法 * O(n2) * 代码组织一下最好情况可以达到O(n) */ void bubbleSort(int[] arr, int n){ for (int i = 0; i < arr.length; i++) { for (int j = 1; j < arr.length-i; j++) { if (arr[j-1]>arr[j]){ int temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } } /** 快速排序 **/ void qSort(int[] arr,int s,int e){ int l = s, r = e; if(l < r){ int temp = arr[l]; while(l < r){ while(l < r && arr[r] >= temp) r--; if(l < r) arr[l] = arr[r]; while(l < r && arr[l] < temp) l++; if(l < r) arr[r] = arr[l]; } arr[l] = temp; qSort(arr,s,l); qSort(arr,l + 1, e); } } /** 选择排序 稳定的算法 O(n2) **/ void selectSort(int[] arr){ int min; for(int i = 0;i<arr.length;i++){ min = i; for(int j = i;j<arr.length;j++){ if(arr[j] < arr[min]){ min = j; } } if(min != i) { int temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } } } /** * * 插入排序:数列前面部分看为有序,依次将后面的无序数列元素插入到前面的有序数列中,初始状态有序数列仅有一个元素,即首元素。在将无序数列元素插入有序数列的过程中,采用了逆序遍历有序数列,相较于顺序遍历会稍显繁琐,但当数列本身已近排序状态效率会更高。 * * 时间复杂度:O(N2)   稳定性:稳定 * @param arr */ public void insertSort(int arr[]){ for(int i = 1; i < arr.length; i++){ int rt = arr[i]; for(int j = i - 1; j >= 0; j--){ if(rt < arr[j]){ arr[j + 1] = arr[j]; arr[j] = rt; }else{ break; } } } } /** * 希尔排序 - 插入排序的改进版。为了减少数据的移动次数,在初始序列较大时取较大的步长,通常取序列长度的一半,此时只有两个元素比较,交换一次;之后步长依次减半直至步长为1,即为插入排序,由于此时序列已接近有序,故插入元素时数据移动的次数会相对较少,效率得到了提高。 * * 时间复杂度:通常认为是O(N3/2) ,未验证  稳定性:不稳定 * @param arr */ void shellSort(int arr[]){ int d = arr.length >> 1; while(d >= 1){ for(int i = d; i < arr.length; i++){ int rt = arr[i]; for(int j = i - d; j >= 0; j -= d){ if(rt < arr[j]){ arr[j + d] = arr[j]; arr[j] = rt; }else break; } } d >>= 1; } } /** * 桶排序 - 实现线性排序,但当元素间值得大小有较大差距时会带来内存空间的较大浪费。首先,找出待排序列中得最大元素max,申请内存大小为max + 1的桶(数组)并初始化为0;然后,遍历排序数列,并依次将每个元素作为下标的桶元素值自增1; * 最后,遍历桶元素,并依次将值非0的元素下标值载入排序数列(桶元素>1表明有值大小相等的元素,此时依次将他们载入排序数列),遍历完成,排序数列便为有序数列。 * * 时间复杂度:O(x*N)   稳定性:稳定 * @param arr */ void bucketSort(int[] arr){ int[] bk = new int[50000 * 2 + 1]; for(int i = 0; i < arr.length; i++){ bk[arr[i] + 50000] += 1; } int ar = 0; for(int i = 0; i < bk.length; i++){ for(int j = bk[i]; j > 0; j--){ arr[ar++] = i - 50000; } } } /** * 基数排序 - 桶排序的改进版,桶的大小固定为10,减少了内存空间的开销。首先,找出待排序列中得最大元素max,并依次按max的低位到高位对所有元素排序; * 桶元素10个元素的大小即为待排序数列元素对应数值为相等元素的个数,即每次遍历待排序数列,桶将其按对应数值位大小分为了10个层级,桶内元素值得和为待排序数列元素个数。 * @param arr */ void countSort(int[] arr){ int[] bk = new int[19]; Integer max = Integer.MIN_VALUE; for(int i = 0; i < arr.length; i++){ if(max < Math.abs(arr[i])) max = arr[i]; } if(max < 0) max = -max; max = max.toString().length(); int [][] bd = new int[19][arr.length]; for(int k = 0; k < max; k++) { for (int i = 0; i < arr.length; i++) { int value = (int)(arr[i] / (Math.pow(10,k)) % 10); bd[value+9][bk[value+9]++] = arr[i]; } int fl = 0; for(int l = 0; l < 19; l++){ if(bk[l] != 0){ for(int s = 0; s < bk[l]; s++){ arr[fl++] = bd[l][s]; } } } bk = new int[19]; fl = 0; } } /** * 归并排序 - 采用了分治和递归的思想,递归&分治-排序整个数列如同排序两个有序数列,依次执行这个过程直至排序末端的两个元素,再依次向上层输送排序好的两个子列进行排序直至整个数列有序(类比二叉树的思想,from down to up)。 * * 时间复杂度:O(NlogN)   稳定性:稳定 * @param arr */ void mergeSortInOrder(int[] arr,int bgn,int mid, int end){ int l = bgn, m = mid +1, e = end; int[] arrs = new int[end - bgn + 1]; int k = 0; while(l <= mid && m <= e){ if(arr[l] < arr[m]){ arrs[k++] = arr[l++]; }else{ arrs[k++] = arr[m++]; } } while(l <= mid){ arrs[k++] = arr[l++]; } while(m <= e){ arrs[k++] = arr[m++]; } for(int i = 0; i < arrs.length; i++){ arr[i + bgn] = arrs[i]; } } void mergeSort(int[] arr, int bgn, int end) { if(bgn >= end){ return; } int mid = (bgn + end) >> 1; mergeSort(arr,bgn,mid); mergeSort(arr,mid + 1, end); mergeSortInOrder(arr,bgn,mid,end); } /** * 堆排序 - 堆排序的思想借助于二叉堆中的最大堆得以实现。首先,将待排序数列抽象为二叉树,并构造出最大堆;然后,依次将最大元素(即根节点元素)与待排序数列的最后一个元素交换(即二叉树最深层最右边的叶子结点元素); * 每次遍历,刷新最后一个元素的位置(自减1),直至其与首元素相交,即完成排序。 * * 时间复杂度:O(NlogN)   稳定性:不稳定 * * @param arr */ void heapSort(int[] nums) { int size = nums.length; for (int i = size/2-1; i >=0; i--) { adjust(nums, size, i); } for (int i = size - 1; i >= 1; i--) { int temp = nums[0]; nums[0] = nums[i]; nums[i] = temp; adjust(nums, i, 0); } } void adjust(int []nums, int len, int index) { int l = 2 * index + 1; int r = 2 * index + 2; int maxIndex = index; if (l<len&&nums[l]>nums[maxIndex])maxIndex = l; if (r<len&&nums[r]>nums[maxIndex])maxIndex = r; if (maxIndex != index) { int temp = nums[maxIndex]; nums[maxIndex] = nums[index]; nums[index] = temp; adjust(nums, len, maxIndex); } } }
LiYueguang6/VirtualNotebook
数据结构/Sort.java
2,593
/** * 基数排序 - 桶排序的改进版,桶的大小固定为10,减少了内存空间的开销。首先,找出待排序列中得最大元素max,并依次按max的低位到高位对所有元素排序; * 桶元素10个元素的大小即为待排序数列元素对应数值为相等元素的个数,即每次遍历待排序数列,桶将其按对应数值位大小分为了10个层级,桶内元素值得和为待排序数列元素个数。 * @param arr */
block_comment
zh-cn
package 数据结构; class Sort { public int[] sortArray(int[] nums) { if(nums.length <=1)return nums; //qSort(nums,0,nums.length-1); //selectSort(nums); // insertSort(nums); // shellSort(nums); // bucketSort(nums); // countSort(nums); // mergeSort(nums,0,nums.length-1); heapSort(nums); return nums; } /** * 冒泡排序 * 稳定的算法 * O(n2) * 代码组织一下最好情况可以达到O(n) */ void bubbleSort(int[] arr, int n){ for (int i = 0; i < arr.length; i++) { for (int j = 1; j < arr.length-i; j++) { if (arr[j-1]>arr[j]){ int temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } } /** 快速排序 **/ void qSort(int[] arr,int s,int e){ int l = s, r = e; if(l < r){ int temp = arr[l]; while(l < r){ while(l < r && arr[r] >= temp) r--; if(l < r) arr[l] = arr[r]; while(l < r && arr[l] < temp) l++; if(l < r) arr[r] = arr[l]; } arr[l] = temp; qSort(arr,s,l); qSort(arr,l + 1, e); } } /** 选择排序 稳定的算法 O(n2) **/ void selectSort(int[] arr){ int min; for(int i = 0;i<arr.length;i++){ min = i; for(int j = i;j<arr.length;j++){ if(arr[j] < arr[min]){ min = j; } } if(min != i) { int temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } } } /** * * 插入排序:数列前面部分看为有序,依次将后面的无序数列元素插入到前面的有序数列中,初始状态有序数列仅有一个元素,即首元素。在将无序数列元素插入有序数列的过程中,采用了逆序遍历有序数列,相较于顺序遍历会稍显繁琐,但当数列本身已近排序状态效率会更高。 * * 时间复杂度:O(N2)   稳定性:稳定 * @param arr */ public void insertSort(int arr[]){ for(int i = 1; i < arr.length; i++){ int rt = arr[i]; for(int j = i - 1; j >= 0; j--){ if(rt < arr[j]){ arr[j + 1] = arr[j]; arr[j] = rt; }else{ break; } } } } /** * 希尔排序 - 插入排序的改进版。为了减少数据的移动次数,在初始序列较大时取较大的步长,通常取序列长度的一半,此时只有两个元素比较,交换一次;之后步长依次减半直至步长为1,即为插入排序,由于此时序列已接近有序,故插入元素时数据移动的次数会相对较少,效率得到了提高。 * * 时间复杂度:通常认为是O(N3/2) ,未验证  稳定性:不稳定 * @param arr */ void shellSort(int arr[]){ int d = arr.length >> 1; while(d >= 1){ for(int i = d; i < arr.length; i++){ int rt = arr[i]; for(int j = i - d; j >= 0; j -= d){ if(rt < arr[j]){ arr[j + d] = arr[j]; arr[j] = rt; }else break; } } d >>= 1; } } /** * 桶排序 - 实现线性排序,但当元素间值得大小有较大差距时会带来内存空间的较大浪费。首先,找出待排序列中得最大元素max,申请内存大小为max + 1的桶(数组)并初始化为0;然后,遍历排序数列,并依次将每个元素作为下标的桶元素值自增1; * 最后,遍历桶元素,并依次将值非0的元素下标值载入排序数列(桶元素>1表明有值大小相等的元素,此时依次将他们载入排序数列),遍历完成,排序数列便为有序数列。 * * 时间复杂度:O(x*N)   稳定性:稳定 * @param arr */ void bucketSort(int[] arr){ int[] bk = new int[50000 * 2 + 1]; for(int i = 0; i < arr.length; i++){ bk[arr[i] + 50000] += 1; } int ar = 0; for(int i = 0; i < bk.length; i++){ for(int j = bk[i]; j > 0; j--){ arr[ar++] = i - 50000; } } } /** * 基数排 <SUF>*/ void countSort(int[] arr){ int[] bk = new int[19]; Integer max = Integer.MIN_VALUE; for(int i = 0; i < arr.length; i++){ if(max < Math.abs(arr[i])) max = arr[i]; } if(max < 0) max = -max; max = max.toString().length(); int [][] bd = new int[19][arr.length]; for(int k = 0; k < max; k++) { for (int i = 0; i < arr.length; i++) { int value = (int)(arr[i] / (Math.pow(10,k)) % 10); bd[value+9][bk[value+9]++] = arr[i]; } int fl = 0; for(int l = 0; l < 19; l++){ if(bk[l] != 0){ for(int s = 0; s < bk[l]; s++){ arr[fl++] = bd[l][s]; } } } bk = new int[19]; fl = 0; } } /** * 归并排序 - 采用了分治和递归的思想,递归&分治-排序整个数列如同排序两个有序数列,依次执行这个过程直至排序末端的两个元素,再依次向上层输送排序好的两个子列进行排序直至整个数列有序(类比二叉树的思想,from down to up)。 * * 时间复杂度:O(NlogN)   稳定性:稳定 * @param arr */ void mergeSortInOrder(int[] arr,int bgn,int mid, int end){ int l = bgn, m = mid +1, e = end; int[] arrs = new int[end - bgn + 1]; int k = 0; while(l <= mid && m <= e){ if(arr[l] < arr[m]){ arrs[k++] = arr[l++]; }else{ arrs[k++] = arr[m++]; } } while(l <= mid){ arrs[k++] = arr[l++]; } while(m <= e){ arrs[k++] = arr[m++]; } for(int i = 0; i < arrs.length; i++){ arr[i + bgn] = arrs[i]; } } void mergeSort(int[] arr, int bgn, int end) { if(bgn >= end){ return; } int mid = (bgn + end) >> 1; mergeSort(arr,bgn,mid); mergeSort(arr,mid + 1, end); mergeSortInOrder(arr,bgn,mid,end); } /** * 堆排序 - 堆排序的思想借助于二叉堆中的最大堆得以实现。首先,将待排序数列抽象为二叉树,并构造出最大堆;然后,依次将最大元素(即根节点元素)与待排序数列的最后一个元素交换(即二叉树最深层最右边的叶子结点元素); * 每次遍历,刷新最后一个元素的位置(自减1),直至其与首元素相交,即完成排序。 * * 时间复杂度:O(NlogN)   稳定性:不稳定 * * @param arr */ void heapSort(int[] nums) { int size = nums.length; for (int i = size/2-1; i >=0; i--) { adjust(nums, size, i); } for (int i = size - 1; i >= 1; i--) { int temp = nums[0]; nums[0] = nums[i]; nums[i] = temp; adjust(nums, i, 0); } } void adjust(int []nums, int len, int index) { int l = 2 * index + 1; int r = 2 * index + 2; int maxIndex = index; if (l<len&&nums[l]>nums[maxIndex])maxIndex = l; if (r<len&&nums[r]>nums[maxIndex])maxIndex = r; if (maxIndex != index) { int temp = nums[maxIndex]; nums[maxIndex] = nums[index]; nums[index] = temp; adjust(nums, len, maxIndex); } } }
false
2,310
130
2,591
139
2,681
128
2,593
140
3,464
227
false
false
false
false
false
true
57250_2
package com.liaoguoyin.蓝桥.算法练习.C1; import java.util.Arrays; import java.util.Scanner; /** * 数组越界的问题用arr.length来严格把控可以很好解决 * Arrays库好用得一匹= =! //译者注: 类似的工具类还有 Collections * 今天这个题有点顶不住,要做的小模块有点多,看来低估题目难度了,明天得加一把劲 * 有时候思路太乱,直接删干净写过的题目也是个办法 //译者注: 重构 */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 获取序列数n int n = scanner.nextInt(); int[] arr = new int[n]; // 获取n个序列 for (int i = 0; i < arr.length; i++) { arr[i] = scanner.nextInt(); } // 获取操作数的个数m int m = scanner.nextInt(); // 获取m行操作数 int[] ll = new int[m]; int[] rr = new int[m]; int[] kk = new int[m]; for (int z = 0; z < m; z++) { ll[z] = scanner.nextInt(); rr[z] = scanner.nextInt(); kk[z] = scanner.nextInt() - 1; } // 操作每一行,截取子数组 for (int i = 0; i < m; i++) { int[] SubArr = split_arr(ll[i], rr[i], arr); System.out.println(SubArr[kk[i]]); } } //译者注: 注意 IDEA 给出的代码修正提示 //译者注: 方法名应当使用小驼峰, 例如 splitArray(尽可能不要使用缩写以提升代码可读性) public static int[] split_arr(int i, int j, int[] arr) { int count = 0; int[] SubArr = new int[j - i + 1]; for (; i <= j; i++) { SubArr[count] = arr[i - 1]; count++; } Arrays.sort(SubArr); int[] new_Arr = new int[SubArr.length]; for (int k = 0; k < SubArr.length; k++) { new_Arr[SubArr.length - k - 1] = SubArr[k]; } return new_Arr; } }
LiaoGuoYin/Lanqiao
蓝桥/src/main/java/com/liaoguoyin/蓝桥/算法练习/C1/Main.java
613
// 获取n个序列
line_comment
zh-cn
package com.liaoguoyin.蓝桥.算法练习.C1; import java.util.Arrays; import java.util.Scanner; /** * 数组越界的问题用arr.length来严格把控可以很好解决 * Arrays库好用得一匹= =! //译者注: 类似的工具类还有 Collections * 今天这个题有点顶不住,要做的小模块有点多,看来低估题目难度了,明天得加一把劲 * 有时候思路太乱,直接删干净写过的题目也是个办法 //译者注: 重构 */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 获取序列数n int n = scanner.nextInt(); int[] arr = new int[n]; // 获取 <SUF> for (int i = 0; i < arr.length; i++) { arr[i] = scanner.nextInt(); } // 获取操作数的个数m int m = scanner.nextInt(); // 获取m行操作数 int[] ll = new int[m]; int[] rr = new int[m]; int[] kk = new int[m]; for (int z = 0; z < m; z++) { ll[z] = scanner.nextInt(); rr[z] = scanner.nextInt(); kk[z] = scanner.nextInt() - 1; } // 操作每一行,截取子数组 for (int i = 0; i < m; i++) { int[] SubArr = split_arr(ll[i], rr[i], arr); System.out.println(SubArr[kk[i]]); } } //译者注: 注意 IDEA 给出的代码修正提示 //译者注: 方法名应当使用小驼峰, 例如 splitArray(尽可能不要使用缩写以提升代码可读性) public static int[] split_arr(int i, int j, int[] arr) { int count = 0; int[] SubArr = new int[j - i + 1]; for (; i <= j; i++) { SubArr[count] = arr[i - 1]; count++; } Arrays.sort(SubArr); int[] new_Arr = new int[SubArr.length]; for (int k = 0; k < SubArr.length; k++) { new_Arr[SubArr.length - k - 1] = SubArr[k]; } return new_Arr; } }
false
539
5
613
5
620
5
613
5
795
8
false
false
false
false
false
true
20502_3
public class TestSuper { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Teacher teacher = new Teacher("zhangsan","th"); teacher.displayName(); teacher.test(); } } class Person{ public int height; private String name; public Person(String n){ name = n; } public void setName(String n){ name = n; } public String getName(){ return name; } public void displayName(){ System.out.println(name); } } class Teacher extends Person{ private String school; //No.1 //开始写代码。需求:定义一个带2个参数的构造器:name和school,并使用它们分别初始化父类的name和这个类中的school属性 public Teacher(String n, String scl){ super(n); //调用父类构造器; school = scl; } //end_code public void displayName(){ System.out.println(getName()+"老师"); } public void test(){ super.height = 100; super.displayName(); System.out.println(super.height); } }
LiaoPan/MyCodeSpace
EnhanceJava/exJava/src/TestSuper.java
316
//开始写代码。需求:定义一个带2个参数的构造器:name和school,并使用它们分别初始化父类的name和这个类中的school属性
line_comment
zh-cn
public class TestSuper { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Teacher teacher = new Teacher("zhangsan","th"); teacher.displayName(); teacher.test(); } } class Person{ public int height; private String name; public Person(String n){ name = n; } public void setName(String n){ name = n; } public String getName(){ return name; } public void displayName(){ System.out.println(name); } } class Teacher extends Person{ private String school; //No.1 //开始 <SUF> public Teacher(String n, String scl){ super(n); //调用父类构造器; school = scl; } //end_code public void displayName(){ System.out.println(getName()+"老师"); } public void test(){ super.height = 100; super.displayName(); System.out.println(super.height); } }
false
250
35
316
35
314
35
316
35
381
59
false
false
false
false
false
true
60457_5
package com.lcw.beauty.demo1; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.util.Log; /** * Create by: chenWei.li * Date: 2018/11/8 * Time: 下午11:02 * Email: [email protected] */ public class BeautyUtil { /** * 调整图片的色相,饱和度,灰度 * * @param srcBitmap * @param rotate * @param saturation * @param scale * @return */ public static Bitmap beautyImage(Bitmap srcBitmap, float rotate, float saturation, float scale) { //调整色相 ColorMatrix rotateMatrix = new ColorMatrix(); rotateMatrix.setRotate(0, rotate); rotateMatrix.setRotate(1, rotate); rotateMatrix.setRotate(2, rotate); //调整色彩饱和度 ColorMatrix saturationMatrix = new ColorMatrix(); saturationMatrix.setSaturation(saturation); //调整灰度 ColorMatrix scaleMatrix = new ColorMatrix(); scaleMatrix.setScale(scale, scale, scale, 1); //叠加效果 ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.postConcat(rotateMatrix); colorMatrix.postConcat(saturationMatrix); colorMatrix.postConcat(scaleMatrix); //创建一个大小相同的空白Bitmap Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888); //载入Canvas,Paint Canvas canvas = new Canvas(dstBitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); //绘图 canvas.drawBitmap(srcBitmap, 0, 0, paint); return dstBitmap; } /** * 通过更改图片像素点的RGBA值,生成底片效果 * * @param scrBitmap * @return */ public static Bitmap beautyImage(Bitmap scrBitmap) { int width = scrBitmap.getWidth(); int height = scrBitmap.getHeight(); int count = width * height; int[] oldPixels = new int[count]; int[] newPixels = new int[count]; scrBitmap.getPixels(oldPixels, 0, width, 0, 0, width, height); for (int i = 0; i < oldPixels.length; i++) { int pixel = oldPixels[i]; int r = Color.red(pixel); int g = Color.green(pixel); int b = Color.blue(pixel); r = 255 - r; g = 255 - g; b = 255 - b; if (r > 255) { r = 255; } if (g > 255) { g = 255; } if (b > 255) { b = 255; } if (r < 0) { r = 0; } if (g < 0) { g = 0; } if (b < 0) { b = 0; } newPixels[i] = Color.rgb(r, g, b); } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(newPixels, 0, width, 0, 0, width, height); return bitmap; } // 黑白 public static final float colormatrix_heibai[] = {0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0, 0, 0, 1.0f, 0}; // 怀旧 public static final float colormatrix_huaijiu[] = {0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0, 0, 0, 1, 0}; // 哥特 public static final float colormatrix_gete[] = {1.9f, -0.3f, -0.2f, 0, -87.0f, -0.2f, 1.7f, -0.1f, 0, -87.0f, -0.1f, -0.6f, 2.0f, 0, -87.0f, 0, 0, 0, 1.0f, 0}; // 淡雅 public static final float colormatrix_danya[] = {0.6f, 0.3f, 0.1f, 0, 73.3f, 0.2f, 0.7f, 0.1f, 0, 73.3f, 0.2f, 0.3f, 0.4f, 0, 73.3f, 0, 0, 0, 1.0f, 0}; // 蓝调 public static final float colormatrix_landiao[] = {2.1f, -1.4f, 0.6f, 0.0f, -71.0f, -0.3f, 2.0f, -0.3f, 0.0f, -71.0f, -1.1f, -0.2f, 2.6f, 0.0f, -71.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 光晕 public static final float colormatrix_guangyun[] = {0.9f, 0, 0, 0, 64.9f, 0, 0.9f, 0, 0, 64.9f, 0, 0, 0.9f, 0, 64.9f, 0, 0, 0, 1.0f, 0}; // 梦幻 public static final float colormatrix_menghuan[] = {0.8f, 0.3f, 0.1f, 0.0f, 46.5f, 0.1f, 0.9f, 0.0f, 0.0f, 46.5f, 0.1f, 0.3f, 0.7f, 0.0f, 46.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 酒红 public static final float colormatrix_jiuhong[] = {1.2f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 胶片 public static final float colormatrix_fanse[] = {-1.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, -1.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, -1.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 湖光掠影 public static final float colormatrix_huguang[] = {0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 褐片 public static final float colormatrix_hepian[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 复古 public static final float colormatrix_fugu[] = {0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 泛黄 public static final float colormatrix_huan_huang[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 传统 public static final float colormatrix_chuan_tong[] = {1.0f, 0.0f, 0.0f, 0, -10f, 0.0f, 1.0f, 0.0f, 0, -10f, 0.0f, 0.0f, 1.0f, 0, -10f, 0, 0, 0, 1, 0}; // 胶片2 public static final float colormatrix_jiao_pian[] = {0.71f, 0.2f, 0.0f, 0.0f, 60.0f, 0.0f, 0.94f, 0.0f, 0.0f, 60.0f, 0.0f, 0.0f, 0.62f, 0.0f, 60.0f, 0, 0, 0, 1.0f, 0}; // 锐色 public static final float colormatrix_ruise[] = {4.8f, -1.0f, -0.1f, 0, -388.4f, -0.5f, 4.4f, -0.1f, 0, -388.4f, -0.5f, -1.0f, 5.2f, 0, -388.4f, 0, 0, 0, 1.0f, 0}; // 清宁 public static final float colormatrix_qingning[] = {0.9f, 0, 0, 0, 0, 0, 1.1f, 0, 0, 0, 0, 0, 0.9f, 0, 0, 0, 0, 0, 1.0f, 0}; // 浪漫 public static final float colormatrix_langman[] = {0.9f, 0, 0, 0, 63.0f, 0, 0.9f, 0, 0, 63.0f, 0, 0, 0.9f, 0, 63.0f, 0, 0, 0, 1.0f, 0}; // 夜色 public static final float colormatrix_yese[] = {1.0f, 0.0f, 0.0f, 0.0f, -66.6f, 0.0f, 1.1f, 0.0f, 0.0f, -66.6f, 0.0f, 0.0f, 1.0f, 0.0f, -66.6f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; }
Lichenwei-Dev/BeautyImageDemo
app/src/main/java/com/lcw/beauty/demo1/BeautyUtil.java
3,279
//叠加效果
line_comment
zh-cn
package com.lcw.beauty.demo1; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.util.Log; /** * Create by: chenWei.li * Date: 2018/11/8 * Time: 下午11:02 * Email: [email protected] */ public class BeautyUtil { /** * 调整图片的色相,饱和度,灰度 * * @param srcBitmap * @param rotate * @param saturation * @param scale * @return */ public static Bitmap beautyImage(Bitmap srcBitmap, float rotate, float saturation, float scale) { //调整色相 ColorMatrix rotateMatrix = new ColorMatrix(); rotateMatrix.setRotate(0, rotate); rotateMatrix.setRotate(1, rotate); rotateMatrix.setRotate(2, rotate); //调整色彩饱和度 ColorMatrix saturationMatrix = new ColorMatrix(); saturationMatrix.setSaturation(saturation); //调整灰度 ColorMatrix scaleMatrix = new ColorMatrix(); scaleMatrix.setScale(scale, scale, scale, 1); //叠加 <SUF> ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.postConcat(rotateMatrix); colorMatrix.postConcat(saturationMatrix); colorMatrix.postConcat(scaleMatrix); //创建一个大小相同的空白Bitmap Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888); //载入Canvas,Paint Canvas canvas = new Canvas(dstBitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); //绘图 canvas.drawBitmap(srcBitmap, 0, 0, paint); return dstBitmap; } /** * 通过更改图片像素点的RGBA值,生成底片效果 * * @param scrBitmap * @return */ public static Bitmap beautyImage(Bitmap scrBitmap) { int width = scrBitmap.getWidth(); int height = scrBitmap.getHeight(); int count = width * height; int[] oldPixels = new int[count]; int[] newPixels = new int[count]; scrBitmap.getPixels(oldPixels, 0, width, 0, 0, width, height); for (int i = 0; i < oldPixels.length; i++) { int pixel = oldPixels[i]; int r = Color.red(pixel); int g = Color.green(pixel); int b = Color.blue(pixel); r = 255 - r; g = 255 - g; b = 255 - b; if (r > 255) { r = 255; } if (g > 255) { g = 255; } if (b > 255) { b = 255; } if (r < 0) { r = 0; } if (g < 0) { g = 0; } if (b < 0) { b = 0; } newPixels[i] = Color.rgb(r, g, b); } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(newPixels, 0, width, 0, 0, width, height); return bitmap; } // 黑白 public static final float colormatrix_heibai[] = {0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0, 0, 0, 1.0f, 0}; // 怀旧 public static final float colormatrix_huaijiu[] = {0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0, 0, 0, 1, 0}; // 哥特 public static final float colormatrix_gete[] = {1.9f, -0.3f, -0.2f, 0, -87.0f, -0.2f, 1.7f, -0.1f, 0, -87.0f, -0.1f, -0.6f, 2.0f, 0, -87.0f, 0, 0, 0, 1.0f, 0}; // 淡雅 public static final float colormatrix_danya[] = {0.6f, 0.3f, 0.1f, 0, 73.3f, 0.2f, 0.7f, 0.1f, 0, 73.3f, 0.2f, 0.3f, 0.4f, 0, 73.3f, 0, 0, 0, 1.0f, 0}; // 蓝调 public static final float colormatrix_landiao[] = {2.1f, -1.4f, 0.6f, 0.0f, -71.0f, -0.3f, 2.0f, -0.3f, 0.0f, -71.0f, -1.1f, -0.2f, 2.6f, 0.0f, -71.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 光晕 public static final float colormatrix_guangyun[] = {0.9f, 0, 0, 0, 64.9f, 0, 0.9f, 0, 0, 64.9f, 0, 0, 0.9f, 0, 64.9f, 0, 0, 0, 1.0f, 0}; // 梦幻 public static final float colormatrix_menghuan[] = {0.8f, 0.3f, 0.1f, 0.0f, 46.5f, 0.1f, 0.9f, 0.0f, 0.0f, 46.5f, 0.1f, 0.3f, 0.7f, 0.0f, 46.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 酒红 public static final float colormatrix_jiuhong[] = {1.2f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 胶片 public static final float colormatrix_fanse[] = {-1.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, -1.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, -1.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 湖光掠影 public static final float colormatrix_huguang[] = {0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 褐片 public static final float colormatrix_hepian[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 复古 public static final float colormatrix_fugu[] = {0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 泛黄 public static final float colormatrix_huan_huang[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 传统 public static final float colormatrix_chuan_tong[] = {1.0f, 0.0f, 0.0f, 0, -10f, 0.0f, 1.0f, 0.0f, 0, -10f, 0.0f, 0.0f, 1.0f, 0, -10f, 0, 0, 0, 1, 0}; // 胶片2 public static final float colormatrix_jiao_pian[] = {0.71f, 0.2f, 0.0f, 0.0f, 60.0f, 0.0f, 0.94f, 0.0f, 0.0f, 60.0f, 0.0f, 0.0f, 0.62f, 0.0f, 60.0f, 0, 0, 0, 1.0f, 0}; // 锐色 public static final float colormatrix_ruise[] = {4.8f, -1.0f, -0.1f, 0, -388.4f, -0.5f, 4.4f, -0.1f, 0, -388.4f, -0.5f, -1.0f, 5.2f, 0, -388.4f, 0, 0, 0, 1.0f, 0}; // 清宁 public static final float colormatrix_qingning[] = {0.9f, 0, 0, 0, 0, 0, 1.1f, 0, 0, 0, 0, 0, 0.9f, 0, 0, 0, 0, 0, 1.0f, 0}; // 浪漫 public static final float colormatrix_langman[] = {0.9f, 0, 0, 0, 63.0f, 0, 0.9f, 0, 0, 63.0f, 0, 0, 0.9f, 0, 63.0f, 0, 0, 0, 1.0f, 0}; // 夜色 public static final float colormatrix_yese[] = {1.0f, 0.0f, 0.0f, 0.0f, -66.6f, 0.0f, 1.1f, 0.0f, 0.0f, -66.6f, 0.0f, 0.0f, 1.0f, 0.0f, -66.6f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; }
false
3,194
3
3,279
5
3,323
4
3,279
5
3,574
7
false
false
false
false
false
true
36403_1
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Strategy; import Adapter.Adapter_Card; import Adapter.Operation; import doudizhu.playWin; import javax.swing.JTextField; /** * * @author 聂娜 * 完成时间:2017/04/18 * 具体策略类:玩家(电脑)0抢地主算法 */ public class Strage0_setLord extends AbstractStrategy_setLord { public int setLordalrorithm(playWin main, int lordTurn) { JTextField time = main.getTime(0); int lord = lordTurn; time.setText("不抢"); //默认为不抢 Operation operation = Adapter_Card.getIntance(); //前面没有玩家抢地主 if (lord == 0) { time.setText("抢地主"); lord = 0; } else //前面有玩家抢地主 if (operation.getScore(main.getPlayerList(0)) > operation.getScore(main.getPlayerList(2))) { double ram = Math.random(); if (ram < 0.5) { // 电脑选地主,选择电脑0 time.setText("抢地主"); lord = 0; } } time.setVisible(true); System.out.println("当前地主:"+lord+"号玩家"); return lord; } }
LieeLa/LordLand
DouDizhu/src/Strategy/Strage0_setLord.java
379
/** * * @author 聂娜 * 完成时间:2017/04/18 * 具体策略类:玩家(电脑)0抢地主算法 */
block_comment
zh-cn
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Strategy; import Adapter.Adapter_Card; import Adapter.Operation; import doudizhu.playWin; import javax.swing.JTextField; /** * * @au <SUF>*/ public class Strage0_setLord extends AbstractStrategy_setLord { public int setLordalrorithm(playWin main, int lordTurn) { JTextField time = main.getTime(0); int lord = lordTurn; time.setText("不抢"); //默认为不抢 Operation operation = Adapter_Card.getIntance(); //前面没有玩家抢地主 if (lord == 0) { time.setText("抢地主"); lord = 0; } else //前面有玩家抢地主 if (operation.getScore(main.getPlayerList(0)) > operation.getScore(main.getPlayerList(2))) { double ram = Math.random(); if (ram < 0.5) { // 电脑选地主,选择电脑0 time.setText("抢地主"); lord = 0; } } time.setVisible(true); System.out.println("当前地主:"+lord+"号玩家"); return lord; } }
false
319
45
379
49
368
44
379
49
456
68
false
false
false
false
false
true
9777_8
package appoint; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.example.life.R; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import org.json.JSONArray; import java.util.LinkedList; import java.util.List; import appoint.adapter.DoctorAdapter; import appoint.entity.Doctor; import appoint.utils.JsonParser; import config.App; import static com.android.volley.VolleyLog.TAG; /** * @author lifan * @date 2018/10/22 10:04 * @email [email protected] * @desc */ public class DoctorTabFragment extends Fragment { private String type; /** * 上拉刷新的控件 */ private PullToRefreshListView mPullRefreshListView; private DoctorAdapter doctorAdapter; /** * 搜索关键字 */ private String searchContent; private List<Doctor> list; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: if (list != null) { doctorAdapter = new DoctorAdapter(list,getActivity()); mPullRefreshListView.setAdapter(doctorAdapter); } break; } } ; }; public void setType(String type) { this.type = type; } public void setSearchContent(String searchContent){ this.searchContent = searchContent; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news1, container, false); list = new LinkedList<>(); init(view); return view; } private void init(View view) { mPullRefreshListView = view.findViewById(R.id.pull_refresh_list); mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { Log.e("TAG", "onPullDownToRefresh"); //这里写下拉刷新的任务 new GetDataTask().execute(); } @Override public void onPullUpToRefresh( PullToRefreshBase<ListView> refreshView) { Log.e("TAG", "onPullUpToRefresh"); //这里写上拉加载更多的任务 new GetDataTask().execute(); } }); mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); initData(); } private class GetDataTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String result) { //mListItems.add(result); //mAdapter.notifyDataSetChanged(); initData(); doctorAdapter.notifyDataSetChanged(); mPullRefreshListView.onRefreshComplete(); } } private void initData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences("base", 0); String token = sharedPreferences.getString("token","1"); String httpurl = App.testHttpUrl+"getDocByDept?hId=1&hDept=内科&hRoom=消化内科"; if(searchContent!=null){ //搜索医生 httpurl = App.testHttpUrl+"searchDoctor?keywords="+searchContent+"&startId="+1; } else if("医生".equals(type)){ //收藏的医生 httpurl = App.testHttpUrl+"getCollectionDoc?token="+token; } RequestQueue mQueue = Volley.newRequestQueue(getActivity()); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(httpurl, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray jsonArray) { Log.v("DoctorsTab","成功"+jsonArray.toString()); list.addAll(JsonParser.jsonToDoctors(jsonArray.toString())); mHandler.sendEmptyMessage(0); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e(TAG, volleyError.getMessage(), volleyError); } }); jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(10000,0,0f)); mQueue.add(jsonArrayRequest); } }
Lifan1998/Gohospital
app/src/main/java/appoint/DoctorTabFragment.java
1,308
//收藏的医生
line_comment
zh-cn
package appoint; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.example.life.R; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import org.json.JSONArray; import java.util.LinkedList; import java.util.List; import appoint.adapter.DoctorAdapter; import appoint.entity.Doctor; import appoint.utils.JsonParser; import config.App; import static com.android.volley.VolleyLog.TAG; /** * @author lifan * @date 2018/10/22 10:04 * @email [email protected] * @desc */ public class DoctorTabFragment extends Fragment { private String type; /** * 上拉刷新的控件 */ private PullToRefreshListView mPullRefreshListView; private DoctorAdapter doctorAdapter; /** * 搜索关键字 */ private String searchContent; private List<Doctor> list; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: if (list != null) { doctorAdapter = new DoctorAdapter(list,getActivity()); mPullRefreshListView.setAdapter(doctorAdapter); } break; } } ; }; public void setType(String type) { this.type = type; } public void setSearchContent(String searchContent){ this.searchContent = searchContent; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news1, container, false); list = new LinkedList<>(); init(view); return view; } private void init(View view) { mPullRefreshListView = view.findViewById(R.id.pull_refresh_list); mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { Log.e("TAG", "onPullDownToRefresh"); //这里写下拉刷新的任务 new GetDataTask().execute(); } @Override public void onPullUpToRefresh( PullToRefreshBase<ListView> refreshView) { Log.e("TAG", "onPullUpToRefresh"); //这里写上拉加载更多的任务 new GetDataTask().execute(); } }); mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); initData(); } private class GetDataTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String result) { //mListItems.add(result); //mAdapter.notifyDataSetChanged(); initData(); doctorAdapter.notifyDataSetChanged(); mPullRefreshListView.onRefreshComplete(); } } private void initData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences("base", 0); String token = sharedPreferences.getString("token","1"); String httpurl = App.testHttpUrl+"getDocByDept?hId=1&hDept=内科&hRoom=消化内科"; if(searchContent!=null){ //搜索医生 httpurl = App.testHttpUrl+"searchDoctor?keywords="+searchContent+"&startId="+1; } else if("医生".equals(type)){ //收藏 <SUF> httpurl = App.testHttpUrl+"getCollectionDoc?token="+token; } RequestQueue mQueue = Volley.newRequestQueue(getActivity()); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(httpurl, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray jsonArray) { Log.v("DoctorsTab","成功"+jsonArray.toString()); list.addAll(JsonParser.jsonToDoctors(jsonArray.toString())); mHandler.sendEmptyMessage(0); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e(TAG, volleyError.getMessage(), volleyError); } }); jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(10000,0,0f)); mQueue.add(jsonArrayRequest); } }
false
1,075
4
1,308
6
1,332
4
1,308
6
1,554
8
false
false
false
false
false
true
56745_8
package view; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.Color; import java.sql.Date; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.text.html.HTMLDocument.Iterator; import dao.InforDAO; import dao.PayDAO; import model.Infor; import model.MyTableModel; import model.Pay; import panel.CheckBox; import javax.swing.JScrollPane; public class PayTableP extends JPanel implements Tb_panel{ private static PayTableP payTableP; private JTable table; private static String number; private MyTableModel mymodel; private CheckBox checkBox; private String[] string = {"姓名","基本工资","奖金","扣除","加班","补贴","保险","总计"}; Date date ; ArrayList<Infor> list_1 = null; PayDAO payDAO = new PayDAO(); /** * Create the panel. */ private PayTableP(String number) { this.number = number; setLayout(null); this.setSize(553,471); checkBox = new CheckBox(); add(checkBox); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 73, 533, 322); add(scrollPane); table = new JTable(); scrollPane.setViewportView(table); table.setSelectionBackground(Color.ORANGE) ; } @Override public void edit() { mymodel.edit(); } @Override public void unedit() { mymodel.unedit(); } @Override public void updata() { String str = checkBox.getYear()+"-"+checkBox.getMonth()+"-21"; date = Date.valueOf(str); InforDAO inforDAO = new InforDAO(); mymodel = new MyTableModel(); for(int i=0;i<string.length;i++){ mymodel.addColumn(string[i]); //System.out.println(string[i]); } list_1 = inforDAO.getTInfor(number); java.util.Iterator<Infor> it_1 = list_1.iterator(); while(it_1.hasNext()){ Infor infor = it_1.next(); Pay pay =null; try { pay = payDAO.getPay(infor.getNumber(), date); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if(pay!=null){ mymodel.addRow(new Object[]{infor.getName(),pay.getBase()+"",pay.getBonus()+"",pay.getDeduct(),pay.getExtra(), pay.getSubsidy(),pay.getOther(),pay.getFact() }); pay = null; } else { mymodel.addRow(new Object[]{infor.getName(),0,0,0,0,0,0,0 }); } //System.out.println(mymodel); } table.setModel(mymodel); } public static PayTableP getInstance(String number){ if(number.equals(PayTableP.number)) return payTableP; else { payTableP = new PayTableP(number); return payTableP; } } @Override public void save() { ArrayList<Integer> ilist = mymodel.getEditedIndex(); java.util.Iterator<Integer> it = ilist.iterator(); while(it.hasNext()){ int i = it.next().intValue(); System.out.println(i); //System.out.println(Integer.parseInt(mymodel.getValueAt(i, 3).toString())); Pay pay = new Pay(); pay.setNumber(list_1.get(i).getNumber()); pay.setBase(Integer.parseInt(mymodel.getValueAt(i, 1).toString())); pay.setBonus(Integer.parseInt(mymodel.getValueAt(i, 2).toString())); pay.setDeduct(Integer.parseInt(mymodel.getValueAt(i, 3).toString())); pay.setExtra(Integer.parseInt(mymodel.getValueAt(i, 4).toString())); pay.setSubsidy(Integer.parseInt(mymodel.getValueAt(i, 5).toString())); pay.setOther(Integer.parseInt(mymodel.getValueAt(i, 6).toString())); pay.setFact(Integer.parseInt(mymodel.getValueAt(i, 7).toString())); pay.setDate(date); Pay pay1 = null; try { pay1 = payDAO.getPay(list_1.get(i).getNumber(), date); //System.out.println(pay1); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if(pay1==null) payDAO.addPay(pay); else payDAO.update(pay); //System.out.println(pay); //删除原记录 //插入新纪录 } mymodel.unedit(); } }
Lifan1998/PersonnelM
src/view/PayTableP.java
1,349
//删除原记录
line_comment
zh-cn
package view; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.Color; import java.sql.Date; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.text.html.HTMLDocument.Iterator; import dao.InforDAO; import dao.PayDAO; import model.Infor; import model.MyTableModel; import model.Pay; import panel.CheckBox; import javax.swing.JScrollPane; public class PayTableP extends JPanel implements Tb_panel{ private static PayTableP payTableP; private JTable table; private static String number; private MyTableModel mymodel; private CheckBox checkBox; private String[] string = {"姓名","基本工资","奖金","扣除","加班","补贴","保险","总计"}; Date date ; ArrayList<Infor> list_1 = null; PayDAO payDAO = new PayDAO(); /** * Create the panel. */ private PayTableP(String number) { this.number = number; setLayout(null); this.setSize(553,471); checkBox = new CheckBox(); add(checkBox); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 73, 533, 322); add(scrollPane); table = new JTable(); scrollPane.setViewportView(table); table.setSelectionBackground(Color.ORANGE) ; } @Override public void edit() { mymodel.edit(); } @Override public void unedit() { mymodel.unedit(); } @Override public void updata() { String str = checkBox.getYear()+"-"+checkBox.getMonth()+"-21"; date = Date.valueOf(str); InforDAO inforDAO = new InforDAO(); mymodel = new MyTableModel(); for(int i=0;i<string.length;i++){ mymodel.addColumn(string[i]); //System.out.println(string[i]); } list_1 = inforDAO.getTInfor(number); java.util.Iterator<Infor> it_1 = list_1.iterator(); while(it_1.hasNext()){ Infor infor = it_1.next(); Pay pay =null; try { pay = payDAO.getPay(infor.getNumber(), date); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if(pay!=null){ mymodel.addRow(new Object[]{infor.getName(),pay.getBase()+"",pay.getBonus()+"",pay.getDeduct(),pay.getExtra(), pay.getSubsidy(),pay.getOther(),pay.getFact() }); pay = null; } else { mymodel.addRow(new Object[]{infor.getName(),0,0,0,0,0,0,0 }); } //System.out.println(mymodel); } table.setModel(mymodel); } public static PayTableP getInstance(String number){ if(number.equals(PayTableP.number)) return payTableP; else { payTableP = new PayTableP(number); return payTableP; } } @Override public void save() { ArrayList<Integer> ilist = mymodel.getEditedIndex(); java.util.Iterator<Integer> it = ilist.iterator(); while(it.hasNext()){ int i = it.next().intValue(); System.out.println(i); //System.out.println(Integer.parseInt(mymodel.getValueAt(i, 3).toString())); Pay pay = new Pay(); pay.setNumber(list_1.get(i).getNumber()); pay.setBase(Integer.parseInt(mymodel.getValueAt(i, 1).toString())); pay.setBonus(Integer.parseInt(mymodel.getValueAt(i, 2).toString())); pay.setDeduct(Integer.parseInt(mymodel.getValueAt(i, 3).toString())); pay.setExtra(Integer.parseInt(mymodel.getValueAt(i, 4).toString())); pay.setSubsidy(Integer.parseInt(mymodel.getValueAt(i, 5).toString())); pay.setOther(Integer.parseInt(mymodel.getValueAt(i, 6).toString())); pay.setFact(Integer.parseInt(mymodel.getValueAt(i, 7).toString())); pay.setDate(date); Pay pay1 = null; try { pay1 = payDAO.getPay(list_1.get(i).getNumber(), date); //System.out.println(pay1); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if(pay1==null) payDAO.addPay(pay); else payDAO.update(pay); //System.out.println(pay); //删除 <SUF> //插入新纪录 } mymodel.unedit(); } }
false
1,060
5
1,330
5
1,321
5
1,330
5
1,704
7
false
false
false
false
false
true
25628_8
package template; /** * @Package: dataStructure_Algorithm.sort * @Author: Chen Long * @Description: 车抽象类 * @Datetime: 2021/11/12 22:13:19 */ public abstract class CarModel { /* * 首先,这个模型要能发动起来,别管是手摇发动,还是电力发动,反正 * 是要能够发动起来,那这个实现要在实现类里了 */ protected abstract void start(); //能发动,还要能停下来,那才是真本事 protected abstract void stop(); //喇叭会出声音,是滴滴叫,还是哔哔叫 protected abstract void alarm(); //引擎会轰隆隆地响,不响那是假的 protected abstract void engineBoom(); //那模型应该会跑吧,别管是人推的,还是电力驱动,总之要会跑 final protected void run() { //先发动汽车 this.start(); //引擎开始轰鸣 this.engineBoom(); //然后就开始跑了,跑的过程中遇到一条狗挡路,就按喇叭 if (isAlarm()) { this.alarm(); } //到达目的地就停车 this.stop(); } //钩子方法,由实现类来重写 protected boolean isAlarm() { return true; } }
LifeIsAlsoGG/java-study
designPattern/src/main/java/template/CarModel.java
362
//然后就开始跑了,跑的过程中遇到一条狗挡路,就按喇叭
line_comment
zh-cn
package template; /** * @Package: dataStructure_Algorithm.sort * @Author: Chen Long * @Description: 车抽象类 * @Datetime: 2021/11/12 22:13:19 */ public abstract class CarModel { /* * 首先,这个模型要能发动起来,别管是手摇发动,还是电力发动,反正 * 是要能够发动起来,那这个实现要在实现类里了 */ protected abstract void start(); //能发动,还要能停下来,那才是真本事 protected abstract void stop(); //喇叭会出声音,是滴滴叫,还是哔哔叫 protected abstract void alarm(); //引擎会轰隆隆地响,不响那是假的 protected abstract void engineBoom(); //那模型应该会跑吧,别管是人推的,还是电力驱动,总之要会跑 final protected void run() { //先发动汽车 this.start(); //引擎开始轰鸣 this.engineBoom(); //然后 <SUF> if (isAlarm()) { this.alarm(); } //到达目的地就停车 this.stop(); } //钩子方法,由实现类来重写 protected boolean isAlarm() { return true; } }
false
304
16
362
27
325
16
362
27
483
40
false
false
false
false
false
true
60047_9
package org.example.design.principle.third; import lombok.extern.log4j.Log4j2; /** * 依赖倒置原则:https://app.yinxiang.com/fx/c2784ddf-be3b-4487-be0d-1681afe3abeb * * 依赖倒置原则在面向对象中十分常见,几乎所有的项目都会遵守,此23种设计模式中更是经常出现。其核心思想是:要面向接口编程,不要面向实现编程。 * 依赖倒置原则是实现开闭原则的重要途径之一,它降低了客户与实现模块之间的耦合。 * * 由于在软件设计中,细节具有多变性,而抽象层则相对稳定,因此以抽象为基础搭建起来的架构要比以细节为基础搭建起来的架构要稳定得多。这里的抽象指的是接口或者抽象类,而细节是指具体的实现类。 * * 依赖倒置原则的目的是通过要面向接口的编程来降低类间的耦合性,所以我们在实际编程中只要遵循以下4点,就能在项目中满足这个规则。 * 1. 每个类尽量提供接口或抽象类,或者两者都具备。 * 2. 变量的声明类型尽量是接口或者是抽象类。 * 3. 任何类都不应该从具体类派生。 * 4. 使用继承时尽量遵循里氏替换原则。 * 5. 高层模块不应该依赖低层模块[即抽象类不能依赖真正的子类实现类,而应该调用抽象] * * Author: GL * Date: 2021-12-08 */ public class Explain { } /** * 反例:具体Jim人类 * * 下面代码看起来比较简单, 但其实是一个非常脆弱的设计. 现在Jim可以吃苹果了, 但是不能只吃苹果而不吃别的水果啊, 这样下去肯定会造成营养失衡. 现在想让Jim吃香蕉了(好像香蕉里含钾元素比较多, 吃点比较有益), 突然发现Jim * 是吃不了香蕉的, 那怎么办呢?看来只有修改代码了啊, 由于上面代码中Jim类依赖于Apple类, 所以导致不得不去改动Jim类里面的代码. 那如果下次Jim * 又要吃别的水果了呢?继续修改代码?这种处理方式显然是不可取的, 频繁修改会带来很大的系统风险, 改着改着可能就发现Jim不会吃水果了. * * 上面的代码之所以会出现上述难堪的问题, 就是因为Jim类依赖于Apple类, 两者是紧耦合的关系, 其导致的结果就是系统的可维护性大大降低. 要增加香蕉类却要去修改Jim类代码, 这是不可忍受的, 你改你的代码为什么要动我的啊, 显然Jim * 不乐意了. 我们常说要设计一个健壮稳定的系统, 而这里只是增加了一个香蕉类, 就要去修改Jim类, 健壮和稳定还从何谈起. * * 而根据依赖倒置原则, 我们可以对上述代码做些修改, 提取抽象的部分. 首先我们提取出两个接口:People和Fruit, 都提供各自必需的抽象方法, 这样以后无论是增加Jim人类, 还是增加Apple、Banana * 等各种水果, 都只需要增加自己的实现类就可以了. 由于遵循依赖倒置原则, 只依赖于抽象, 而不依赖于细节, 所以增加类无需修改其他类. */ @Log4j2 class Jim { public void eat(Apple apple) { log.info(String.format("Counterexample: Jim eat: %s ", apple.getName())); } } //具体苹果类 class Apple { public String getName() { return "apple"; } } /** * 正例:人接口 * * People和Fruit接口都是复杂的业务逻辑, 属于高层模块, 而Apple2属于低层模块. People依赖于抽象的Fruit接口, 这就做到了:高层模块不应该依赖低层模块, 两者都应该依赖于抽象(抽象类或接口). * People和Fruit接口与各自的实现类没有关系, 增加实现类不会影响接口, 这就做到了:抽象(抽象类或接口)不应该依赖于细节(具体实现类). * Jim、Apple、Banana实现类都要去实现各自的接口所定义的抽象方法, 所以是依赖于接口的. 这就做到了:细节(具体实现类)应该依赖抽象. */ interface People { void eat(Fruit fruit); //将吃的细节抽象, 并且面向抽象类参数 } //水果接口 interface Fruit { String getName(); //将获取水果名的细节抽象 } //具体Jim人类 @Log4j2 class Jim2 implements People { public void eat(Fruit fruit) { log.info(String.format("Positive example: Jim eat: %s ", fruit.getName())); } } //具体苹果类 class Apple2 implements Fruit { public String getName() { return "apple"; } } //具体香蕉类 class Banana implements Fruit { public String getName() { return "banana"; } }
LightGao-Hub/23-design-pattern
src/main/java/org/example/design/principle/third/Explain.java
1,432
//具体香蕉类
line_comment
zh-cn
package org.example.design.principle.third; import lombok.extern.log4j.Log4j2; /** * 依赖倒置原则:https://app.yinxiang.com/fx/c2784ddf-be3b-4487-be0d-1681afe3abeb * * 依赖倒置原则在面向对象中十分常见,几乎所有的项目都会遵守,此23种设计模式中更是经常出现。其核心思想是:要面向接口编程,不要面向实现编程。 * 依赖倒置原则是实现开闭原则的重要途径之一,它降低了客户与实现模块之间的耦合。 * * 由于在软件设计中,细节具有多变性,而抽象层则相对稳定,因此以抽象为基础搭建起来的架构要比以细节为基础搭建起来的架构要稳定得多。这里的抽象指的是接口或者抽象类,而细节是指具体的实现类。 * * 依赖倒置原则的目的是通过要面向接口的编程来降低类间的耦合性,所以我们在实际编程中只要遵循以下4点,就能在项目中满足这个规则。 * 1. 每个类尽量提供接口或抽象类,或者两者都具备。 * 2. 变量的声明类型尽量是接口或者是抽象类。 * 3. 任何类都不应该从具体类派生。 * 4. 使用继承时尽量遵循里氏替换原则。 * 5. 高层模块不应该依赖低层模块[即抽象类不能依赖真正的子类实现类,而应该调用抽象] * * Author: GL * Date: 2021-12-08 */ public class Explain { } /** * 反例:具体Jim人类 * * 下面代码看起来比较简单, 但其实是一个非常脆弱的设计. 现在Jim可以吃苹果了, 但是不能只吃苹果而不吃别的水果啊, 这样下去肯定会造成营养失衡. 现在想让Jim吃香蕉了(好像香蕉里含钾元素比较多, 吃点比较有益), 突然发现Jim * 是吃不了香蕉的, 那怎么办呢?看来只有修改代码了啊, 由于上面代码中Jim类依赖于Apple类, 所以导致不得不去改动Jim类里面的代码. 那如果下次Jim * 又要吃别的水果了呢?继续修改代码?这种处理方式显然是不可取的, 频繁修改会带来很大的系统风险, 改着改着可能就发现Jim不会吃水果了. * * 上面的代码之所以会出现上述难堪的问题, 就是因为Jim类依赖于Apple类, 两者是紧耦合的关系, 其导致的结果就是系统的可维护性大大降低. 要增加香蕉类却要去修改Jim类代码, 这是不可忍受的, 你改你的代码为什么要动我的啊, 显然Jim * 不乐意了. 我们常说要设计一个健壮稳定的系统, 而这里只是增加了一个香蕉类, 就要去修改Jim类, 健壮和稳定还从何谈起. * * 而根据依赖倒置原则, 我们可以对上述代码做些修改, 提取抽象的部分. 首先我们提取出两个接口:People和Fruit, 都提供各自必需的抽象方法, 这样以后无论是增加Jim人类, 还是增加Apple、Banana * 等各种水果, 都只需要增加自己的实现类就可以了. 由于遵循依赖倒置原则, 只依赖于抽象, 而不依赖于细节, 所以增加类无需修改其他类. */ @Log4j2 class Jim { public void eat(Apple apple) { log.info(String.format("Counterexample: Jim eat: %s ", apple.getName())); } } //具体苹果类 class Apple { public String getName() { return "apple"; } } /** * 正例:人接口 * * People和Fruit接口都是复杂的业务逻辑, 属于高层模块, 而Apple2属于低层模块. People依赖于抽象的Fruit接口, 这就做到了:高层模块不应该依赖低层模块, 两者都应该依赖于抽象(抽象类或接口). * People和Fruit接口与各自的实现类没有关系, 增加实现类不会影响接口, 这就做到了:抽象(抽象类或接口)不应该依赖于细节(具体实现类). * Jim、Apple、Banana实现类都要去实现各自的接口所定义的抽象方法, 所以是依赖于接口的. 这就做到了:细节(具体实现类)应该依赖抽象. */ interface People { void eat(Fruit fruit); //将吃的细节抽象, 并且面向抽象类参数 } //水果接口 interface Fruit { String getName(); //将获取水果名的细节抽象 } //具体Jim人类 @Log4j2 class Jim2 implements People { public void eat(Fruit fruit) { log.info(String.format("Positive example: Jim eat: %s ", fruit.getName())); } } //具体苹果类 class Apple2 implements Fruit { public String getName() { return "apple"; } } //具体 <SUF> class Banana implements Fruit { public String getName() { return "banana"; } }
false
1,173
4
1,432
7
1,176
4
1,432
7
2,171
10
false
false
false
false
false
true
28502_1
package net.lawaxi.esuperbotany.item.block; import net.lawaxi.esuperbotany.block.BlockManaStorage; import net.minecraft.block.Block; import net.minecraft.client.resources.I18n; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import vazkii.botania.api.item.IManaDissolvable; import vazkii.botania.api.mana.IManaPool; import vazkii.botania.common.core.helper.ItemNBTHelper; import vazkii.botania.common.network.PacketBotaniaEffect; import vazkii.botania.common.network.PacketHandler; import javax.annotation.Nullable; import java.util.List; public class ItemManaStorage extends ItemBlock implements IManaDissolvable { private static final String itemnbt = "mana"; public ItemManaStorage(Block block) { super(block); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { tooltip.add(I18n.format("tile.esuperbotany:manastorage.lore")+getMana(stack)); } //执行方法参见 TilePool.class //噢我的天哪 这代码抄的与黑莲花有什么区别 @Override public void onDissolveTick(IManaPool iManaPool, ItemStack itemStack, EntityItem entityItem) { if (!iManaPool.isFull() && !entityItem.world.isRemote) { PacketHandler.sendToNearby(entityItem.world, entityItem.getPosition(), new PacketBotaniaEffect(PacketBotaniaEffect.EffectType.BLACK_LOTUS_DISSOLVE, entityItem.getPosition().getX(), entityItem.getPosition().getY() + 0.5, entityItem.getPosition().getZ())); iManaPool.recieveMana(getMana(itemStack)); itemStack.shrink(1); } } public void setMana(ItemStack stack,int mana){ ItemNBTHelper.setInt(stack,itemnbt,mana); } public int getMana(ItemStack stack){ return Math.abs(ItemNBTHelper.getInt(stack,itemnbt, BlockManaStorage.default_mana)); } }
Lilium-Studio/EsuperBotany
src/main/java/net/lawaxi/esuperbotany/item/block/ItemManaStorage.java
605
//噢我的天哪 这代码抄的与黑莲花有什么区别
line_comment
zh-cn
package net.lawaxi.esuperbotany.item.block; import net.lawaxi.esuperbotany.block.BlockManaStorage; import net.minecraft.block.Block; import net.minecraft.client.resources.I18n; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import vazkii.botania.api.item.IManaDissolvable; import vazkii.botania.api.mana.IManaPool; import vazkii.botania.common.core.helper.ItemNBTHelper; import vazkii.botania.common.network.PacketBotaniaEffect; import vazkii.botania.common.network.PacketHandler; import javax.annotation.Nullable; import java.util.List; public class ItemManaStorage extends ItemBlock implements IManaDissolvable { private static final String itemnbt = "mana"; public ItemManaStorage(Block block) { super(block); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) { tooltip.add(I18n.format("tile.esuperbotany:manastorage.lore")+getMana(stack)); } //执行方法参见 TilePool.class //噢我 <SUF> @Override public void onDissolveTick(IManaPool iManaPool, ItemStack itemStack, EntityItem entityItem) { if (!iManaPool.isFull() && !entityItem.world.isRemote) { PacketHandler.sendToNearby(entityItem.world, entityItem.getPosition(), new PacketBotaniaEffect(PacketBotaniaEffect.EffectType.BLACK_LOTUS_DISSOLVE, entityItem.getPosition().getX(), entityItem.getPosition().getY() + 0.5, entityItem.getPosition().getZ())); iManaPool.recieveMana(getMana(itemStack)); itemStack.shrink(1); } } public void setMana(ItemStack stack,int mana){ ItemNBTHelper.setInt(stack,itemnbt,mana); } public int getMana(ItemStack stack){ return Math.abs(ItemNBTHelper.getInt(stack,itemnbt, BlockManaStorage.default_mana)); } }
false
473
15
605
21
581
14
605
21
707
35
false
false
false
false
false
true
17345_3
package rdc.constant; /** * Created by Lin Yaotian on 2018/4/14. */ public class Constant { /** * 正则表达式:验证手机号 */ public static final String REGEX_PHONE_NUMBER = "0?(13|14|15|18)[0-9]{9}"; /** * 正则表达式:验证邮箱 */ public static final String REGEX_EMAIL = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"; /** * 密码位数 */ public static final Integer PASSWORD_NUM = 6; /** * 默认的标签顺序 */ public static final String DEFAULT_TAGS_ORDER = "首页,热门,比赛,公益,运动,交友,讲座,其他"; }
LinYaoTian/Activity
app/src/main/java/rdc/constant/Constant.java
228
/** * 密码位数 */
block_comment
zh-cn
package rdc.constant; /** * Created by Lin Yaotian on 2018/4/14. */ public class Constant { /** * 正则表达式:验证手机号 */ public static final String REGEX_PHONE_NUMBER = "0?(13|14|15|18)[0-9]{9}"; /** * 正则表达式:验证邮箱 */ public static final String REGEX_EMAIL = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"; /** * 密码位 <SUF>*/ public static final Integer PASSWORD_NUM = 6; /** * 默认的标签顺序 */ public static final String DEFAULT_TAGS_ORDER = "首页,热门,比赛,公益,运动,交友,讲座,其他"; }
false
205
11
228
9
230
10
228
9
299
12
false
false
false
false
false
true
19319_3
package com.lingber.service; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** * @author 作者 Lingber [email protected]: * @version 创建时间:2018年7月9日 下午2:00:57 * 类说明 : */ public class MyServerHandler extends ChannelInboundHandlerAdapter { private boolean first = true; private FileOutputStream fos; private BufferedOutputStream bufferedOutputStream; /* * channelAction * * channel 通道 * action 活跃的 * * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据 * */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { first = true; System.out.println(ctx.channel().localAddress().toString() + " channelActive"); } /* * channelInactive * * channel 通道 * Inactive 不活跃的 * * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据 * */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println(ctx.channel().localAddress().toString() + " channelInactive"); // 关闭流 bufferedOutputStream.flush(); bufferedOutputStream.close(); first = false; } /* * channelRead * * channel 通道 * Read 读 * */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 第一次接收信息只创建文件 // if (first) { System.out.println("创建文件"); // first = false; File file = new File("F:\\test" + new SimpleDateFormat("yyyymmddhhmmss").format(new Date()) + ".jpg"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { fos = new FileOutputStream(file); bufferedOutputStream = new BufferedOutputStream(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } // return; // } // 开始处理文件信息 ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); System.out.println("本次接收内容长度:" + msg.toString().length()); try { bufferedOutputStream.write(bytes, 0, bytes.length); buf.release(); } catch (IOException e) { e.printStackTrace(); } } /* * channelReadComplete * * channel 通道 * Read 读取 * Complete 完成 * * 在通道读取完成后会在这个方法里通知,对应可以做刷新操作 * ctx.flush() * */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } /* * exceptionCaught * * exception 异常 * Caught 抓住 * * 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接 * */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); System.out.println("异常信息:\r\n" + cause.getMessage()); } }
Lingber/Hotel_Netty
src/main/java/com/lingber/service/MyServerHandler.java
879
// 关闭流
line_comment
zh-cn
package com.lingber.service; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** * @author 作者 Lingber [email protected]: * @version 创建时间:2018年7月9日 下午2:00:57 * 类说明 : */ public class MyServerHandler extends ChannelInboundHandlerAdapter { private boolean first = true; private FileOutputStream fos; private BufferedOutputStream bufferedOutputStream; /* * channelAction * * channel 通道 * action 活跃的 * * 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据 * */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { first = true; System.out.println(ctx.channel().localAddress().toString() + " channelActive"); } /* * channelInactive * * channel 通道 * Inactive 不活跃的 * * 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据 * */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println(ctx.channel().localAddress().toString() + " channelInactive"); // 关闭 <SUF> bufferedOutputStream.flush(); bufferedOutputStream.close(); first = false; } /* * channelRead * * channel 通道 * Read 读 * */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 第一次接收信息只创建文件 // if (first) { System.out.println("创建文件"); // first = false; File file = new File("F:\\test" + new SimpleDateFormat("yyyymmddhhmmss").format(new Date()) + ".jpg"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { fos = new FileOutputStream(file); bufferedOutputStream = new BufferedOutputStream(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } // return; // } // 开始处理文件信息 ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); System.out.println("本次接收内容长度:" + msg.toString().length()); try { bufferedOutputStream.write(bytes, 0, bytes.length); buf.release(); } catch (IOException e) { e.printStackTrace(); } } /* * channelReadComplete * * channel 通道 * Read 读取 * Complete 完成 * * 在通道读取完成后会在这个方法里通知,对应可以做刷新操作 * ctx.flush() * */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } /* * exceptionCaught * * exception 异常 * Caught 抓住 * * 抓住异常,当发生异常的时候,可以做一些相应的处理,比如打印日志、关闭链接 * */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); System.out.println("异常信息:\r\n" + cause.getMessage()); } }
false
805
4
879
4
931
3
879
4
1,184
7
false
false
false
false
false
true
40928_13
package CodeOf871; import java.util.PriorityQueue; /** * @author linsvert * leetcode 每日一题 【871.最低加油次数】 * @url https://leetcode.cn/problems/minimum-number-of-refueling-stops/ * @tag */ public class CodeOf871 { /** * 动态规划 * @param target target * @param startFuel startFuel * @param stations stations * @return int */ public int minRefuelStops(int target, int startFuel, int[][] stations) { //dp[i] => 加油i次能到达最远的距离 //dp[i + 1] = Max{dp[i + 1], dp[i] + loc} //dp[0] = startFuel long[] dp = new long[stations.length + 1]; dp[0] = startFuel; //所能到达的最远距离 for (int i = 0; i < stations.length; i++) { for (int j = i;j >=0; j --) { //求 到达 加油站 i 加油 j + 1 次所能达到的最远距离 //当前能到距离一定大于加油站的位置 //求 dp[j + 1] => 防止 dp[j + 1] 因 stations[j][1] 重复计算 所以要 从大往小 if (dp[j] >= stations[i][0]) { dp[j + 1] = Math.max(dp[j + 1], dp[j] + stations[i][1]); } } } //寻找第 i 次加油能到达 >= target for (int i = 0;i <= stations.length;i++) { if (dp[i] >= target) { return i; } } return -1; } /** * 优先队列 * @param target target * @param startFuel startFuel * @param stations stations * @return int */ public int solution(int target, int startFuel, int[][] stations) { //优先队列 油量优先 PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> b - a); int n = stations.length; int r = 0; int loc = 0; //加队列下标记 int idx = 0; while (loc < target) { //没油的时候判断 if (startFuel == 0) { if (!q.isEmpty()) { //加一次油 r ++; startFuel = q.poll(); } else { return -1; } } loc += startFuel; startFuel = 0; //添加队列 油站位置小于当前位置距离近 while (idx < n && stations[idx][0] <= loc) { q.add(stations[idx][1]); idx++; } } return r; } public static void main(String[] args) { CodeOf871 c = new CodeOf871(); int target = 100; int startFuel = 50; int[][] stations = {{25,25}, {50,50}}; System.out.println(c.minRefuelStops(target, startFuel, stations)); } }
LinsVert/leetcode_everyday
CodeOf871/CodeOf871.java
801
//没油的时候判断
line_comment
zh-cn
package CodeOf871; import java.util.PriorityQueue; /** * @author linsvert * leetcode 每日一题 【871.最低加油次数】 * @url https://leetcode.cn/problems/minimum-number-of-refueling-stops/ * @tag */ public class CodeOf871 { /** * 动态规划 * @param target target * @param startFuel startFuel * @param stations stations * @return int */ public int minRefuelStops(int target, int startFuel, int[][] stations) { //dp[i] => 加油i次能到达最远的距离 //dp[i + 1] = Max{dp[i + 1], dp[i] + loc} //dp[0] = startFuel long[] dp = new long[stations.length + 1]; dp[0] = startFuel; //所能到达的最远距离 for (int i = 0; i < stations.length; i++) { for (int j = i;j >=0; j --) { //求 到达 加油站 i 加油 j + 1 次所能达到的最远距离 //当前能到距离一定大于加油站的位置 //求 dp[j + 1] => 防止 dp[j + 1] 因 stations[j][1] 重复计算 所以要 从大往小 if (dp[j] >= stations[i][0]) { dp[j + 1] = Math.max(dp[j + 1], dp[j] + stations[i][1]); } } } //寻找第 i 次加油能到达 >= target for (int i = 0;i <= stations.length;i++) { if (dp[i] >= target) { return i; } } return -1; } /** * 优先队列 * @param target target * @param startFuel startFuel * @param stations stations * @return int */ public int solution(int target, int startFuel, int[][] stations) { //优先队列 油量优先 PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> b - a); int n = stations.length; int r = 0; int loc = 0; //加队列下标记 int idx = 0; while (loc < target) { //没油 <SUF> if (startFuel == 0) { if (!q.isEmpty()) { //加一次油 r ++; startFuel = q.poll(); } else { return -1; } } loc += startFuel; startFuel = 0; //添加队列 油站位置小于当前位置距离近 while (idx < n && stations[idx][0] <= loc) { q.add(stations[idx][1]); idx++; } } return r; } public static void main(String[] args) { CodeOf871 c = new CodeOf871(); int target = 100; int startFuel = 50; int[][] stations = {{25,25}, {50,50}}; System.out.println(c.minRefuelStops(target, startFuel, stations)); } }
false
750
5
801
6
826
5
801
6
1,016
10
false
false
false
false
false
true
29053_0
class Philosopher implements Runnable { private String name; private Chopsticks leftChopstick; private Chopsticks rightChopstick; public Philosopher(String name, Chopsticks leftChopstick, Chopsticks rightChopstick) { this.name = name; this.leftChopstick = leftChopstick; this.rightChopstick = rightChopstick; } public void run() { while (true) { think(); eat(); System.out.println(name + "吃完了"); leftChopstick.putDown(); rightChopstick.putDown(); } } private void think() { try { System.out.println(name + "开始思考"); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } private void eat() { try { leftChopstick.pickUp(); synchronized (leftChopstick) { rightChopstick.pickUp(); synchronized (rightChopstick) { System.out.println(name + "开始吃饭"); Thread.sleep(2000); } } } catch (InterruptedException e) { e.printStackTrace(); } } } /* 先来看一下Philosopher类,这个类实现了Runnable接口,每个哲学家都是一个线程,有一个名字、左右两只筷子。然后定义了run()、think()、eat()三个方法。 run()方法里面是一个死循环,不停地思考、吃饭、放下筷子,相当于模拟了一个哲学家的生活。在每次思考和吃饭之前,调用了think()和eat()方法。 think()方法表示哲学家开始思考,执行时间为2秒钟。 eat()方法表示哲学家开始吃饭,先拿起左边的筷子,如果左边没有筷子可用,则等待。然后再尝试取右边的筷子,如果右边没有可用的,则必须先将左边的放回去,等待其他哲学家将筷子放下。最后,如果成功获取了右边的筷子,则开始吃饭,执行时间为2秒钟。 再来看一下Chopsticks类,这个类表示一只筷子,有一个状态变量isUsed(是否被使用),同时定义了pickUp()和putDown()两个方法。 pickUp()方法表示将筷子拿起来,如果当前这只筷子已经被使用,则等待(调用wait()方法),直到其他线程通过调用putDown()方法将其放下。 putDown()方法表示将筷子放下,并且将isUsed变回false,并且通知其他等待的线程。 最后是Test类,主要函数是main(),首先定义了五个筷子和五个哲学家,每个哲学家拿到的左右筷子不同,然后开启五个线程,每个线程对应一个哲学家。 执行步骤如下: 创建五个哲学家和五个筷子对象。 创建五个线程分别对应五个哲学家。 启动五个线程,每个线程都会进入Philosopher的run()函数里面,开始思考和吃饭。 在eat()方法中,如果当前线程无法获得左边或右边的筷子,则会一直等待,直到其他线程释放筷子且自己成功获取到筷子。如果一个哲学家持有左边的筷子但无法获取右边的筷子,则会一直占用左边的筷子并且无法释放,导致其他哲学家也无法获取这只筷子,从而引起死锁。 如果一个哲学家成功获取到左右两只筷子,则开始进食,执行时间为2秒钟。 在吃完饭之后,哲学家会将筷子放下,并通知其他线程有筷子可用。然后再次进行思考和吃饭的循环。*/
Linsastar/JMU-Java
2023.4.27/PhilosopherDining/Philosopher.java
952
/* 先来看一下Philosopher类,这个类实现了Runnable接口,每个哲学家都是一个线程,有一个名字、左右两只筷子。然后定义了run()、think()、eat()三个方法。 run()方法里面是一个死循环,不停地思考、吃饭、放下筷子,相当于模拟了一个哲学家的生活。在每次思考和吃饭之前,调用了think()和eat()方法。 think()方法表示哲学家开始思考,执行时间为2秒钟。 eat()方法表示哲学家开始吃饭,先拿起左边的筷子,如果左边没有筷子可用,则等待。然后再尝试取右边的筷子,如果右边没有可用的,则必须先将左边的放回去,等待其他哲学家将筷子放下。最后,如果成功获取了右边的筷子,则开始吃饭,执行时间为2秒钟。 再来看一下Chopsticks类,这个类表示一只筷子,有一个状态变量isUsed(是否被使用),同时定义了pickUp()和putDown()两个方法。 pickUp()方法表示将筷子拿起来,如果当前这只筷子已经被使用,则等待(调用wait()方法),直到其他线程通过调用putDown()方法将其放下。 putDown()方法表示将筷子放下,并且将isUsed变回false,并且通知其他等待的线程。 最后是Test类,主要函数是main(),首先定义了五个筷子和五个哲学家,每个哲学家拿到的左右筷子不同,然后开启五个线程,每个线程对应一个哲学家。 执行步骤如下: 创建五个哲学家和五个筷子对象。 创建五个线程分别对应五个哲学家。 启动五个线程,每个线程都会进入Philosopher的run()函数里面,开始思考和吃饭。 在eat()方法中,如果当前线程无法获得左边或右边的筷子,则会一直等待,直到其他线程释放筷子且自己成功获取到筷子。如果一个哲学家持有左边的筷子但无法获取右边的筷子,则会一直占用左边的筷子并且无法释放,导致其他哲学家也无法获取这只筷子,从而引起死锁。 如果一个哲学家成功获取到左右两只筷子,则开始进食,执行时间为2秒钟。 在吃完饭之后,哲学家会将筷子放下,并通知其他线程有筷子可用。然后再次进行思考和吃饭的循环。*/
block_comment
zh-cn
class Philosopher implements Runnable { private String name; private Chopsticks leftChopstick; private Chopsticks rightChopstick; public Philosopher(String name, Chopsticks leftChopstick, Chopsticks rightChopstick) { this.name = name; this.leftChopstick = leftChopstick; this.rightChopstick = rightChopstick; } public void run() { while (true) { think(); eat(); System.out.println(name + "吃完了"); leftChopstick.putDown(); rightChopstick.putDown(); } } private void think() { try { System.out.println(name + "开始思考"); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } private void eat() { try { leftChopstick.pickUp(); synchronized (leftChopstick) { rightChopstick.pickUp(); synchronized (rightChopstick) { System.out.println(name + "开始吃饭"); Thread.sleep(2000); } } } catch (InterruptedException e) { e.printStackTrace(); } } } /* 先来看 <SUF>*/
false
757
499
952
654
838
513
952
654
1,363
992
true
true
true
true
true
false
63590_16
package com.liqi.nohttputils.nohttp; import android.app.Dialog; import android.content.Context; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.text.TextUtils; import android.widget.Toast; import com.liqi.nohttputils.R; import com.liqi.nohttputils.interfa.OnDialogGetListener; import com.liqi.nohttputils.interfa.OnIsRequestListener; import com.liqi.nohttputils.nohttp.rx_threadpool.interfa.OnRxMessageGetListener; import com.liqi.nohttputils.nohttp.rx_threadpool.model.BaseRxRequestModel; import com.liqi.nohttputils.nohttp.rx_threadpool.model.RxRequestModel; import com.liqi.nohttputils.nohttp.rx_threadpool.thread.RxThreadDispatch; import com.liqi.nohttputils.nohttp.rx_threadpool.utils.RxThreadPoolUtisl; import com.yanzhenjie.nohttp.Logger; import com.yanzhenjie.nohttp.error.NetworkError; import com.yanzhenjie.nohttp.error.NotFoundCacheError; import com.yanzhenjie.nohttp.error.TimeoutError; import com.yanzhenjie.nohttp.error.URLError; import com.yanzhenjie.nohttp.error.UnKnownHostError; import java.net.ConnectException; import java.net.ProtocolException; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * 把数据源中的数据转换成rxJava线程的中转站对象 * Created by LiQi on 2017/3/20. */ public class RxThreadInterchange implements RxThreadDispatch.OnRunDataDisListener { //Rx线程池并发数量处理值 private static final int RUNSIZE = RxUtilsConfig.ConfigBuilder.getConfigBuilder().getRxUtilsConfig().getRunRequestSize(); private static RxThreadInterchange mRxThreadInterchange; private final String REQUEST_REVOCATION = "撤销请求"; //当队列信息长度达到此长度的时候清空掉 private final int SIZE = RUNSIZE; private RxThreadDispatch mRxThreadDispatch; private OnRxMessageGetListener mOnRxMessageDisListener; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { RxRequestModel baseRxRequestModel = (RxRequestModel) msg.obj; runRequest(baseRxRequestModel); } }; private RxThreadInterchange() { } static RxThreadInterchange getRxThreadInterchange() { return mRxThreadInterchange = null == mRxThreadInterchange ? new RxThreadInterchange() : mRxThreadInterchange; } /** * 转换运行 * * @param onRxMessageGetListener 数据源对内暴露接口 * @param <T> */ <T extends BaseRxRequestModel> void start(@NonNull OnRxMessageGetListener<T> onRxMessageGetListener) { if (null == mOnRxMessageDisListener) { selectOkState(onRxMessageGetListener); } else { if (mOnRxMessageDisListener != onRxMessageGetListener) { selectOkState(onRxMessageGetListener); } } if (null == mRxThreadDispatch || !mRxThreadDispatch.isAlive()) { runToNo(); //开启中转线程 mRxThreadDispatch = new RxThreadDispatch(RUNSIZE, mOnRxMessageDisListener.getList()); mRxThreadDispatch.setOnRunDataDisListener(this); mRxThreadDispatch.setDaemon(true); mRxThreadDispatch.start(); } else { mRxThreadDispatch.setRunSize(false); synchronized (this) { start(); } } } /** * 唤醒中转线程起来做事了 */ private void start() { if (mRxThreadDispatch.isAlive() && !mRxThreadDispatch.isRunState()) { RxThreadPoolUtisl.threadNotify(RxThreadInterchange.this); //Logger.e("唤醒中转线程>>>>"); } } /** * 判断当前是已经获取数据源对象 * * @param onRxMessageDisListener */ private void selectOkState(@NonNull OnRxMessageGetListener onRxMessageDisListener) { mOnRxMessageDisListener = onRxMessageDisListener; runToNo(); } /** * 把当前中转线程打死 */ private void runToNo() { if (null != mRxThreadDispatch) { mRxThreadDispatch.setRunTag(false); mRxThreadDispatch = null; } } /** * 中转线程创建rxJava线程 * * @param baseRxRequestModel 要处理的对象 * @param <T> */ private <T> void runRequest(final RxRequestModel<T> baseRxRequestModel) { if (null != baseRxRequestModel) { Dialog dialog = getDialog(baseRxRequestModel); if (null != dialog && !dialog.isShowing()) { try { dialog.show(); } catch (Exception e) { Logger.e("Dialog-显示异常:由于Dialog依赖的Context不是栈顶。"); } } Observable.create(baseRxRequestModel) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<T>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Dialog dialog = getDialog(baseRxRequestModel); if (null != dialog && dialog.isShowing()) { try { dialog.dismiss(); } catch (Exception e1) { Logger.e("Dialog-关闭异常:由于Dialog已经关闭或者依赖的Context不存在"); } } // 提示异常信息。 if (e instanceof NetworkError) {// 网络不好 show(dialog, R.string.error_please_check_network); } else if (e instanceof TimeoutError) {// 请求超时 show(dialog, R.string.error_timeout); } else if (e instanceof UnKnownHostError) {// 找不到服务器 show(dialog, R.string.error_not_found_server); } else if (e instanceof URLError) {// URL是错的 show(dialog, R.string.error_url_error); } else if (e instanceof NotFoundCacheError) { // 这个异常只会在仅仅查找缓存时没有找到缓存时返回 show(dialog, R.string.error_not_found_cache); } else if (e instanceof ProtocolException) { show(dialog, R.string.error_system_unsupport_method); } else if (e instanceof ConnectException) {//没有连接到服务器 show(dialog, R.string.error_no_service); } else { if (e.getMessage().contains(REQUEST_REVOCATION)) { Logger.e(e.getMessage()); } else { Logger.e("NoHttpUtils捕获异常:" + e.toString()); StackTraceElement[] stackTrace = e.getStackTrace(); if (null != stackTrace) { for (StackTraceElement traceElement : stackTrace) { Logger.e("NoHttpUtils捕获异常:" + traceElement.toString()); } } String anUnknownErrorHint = baseRxRequestModel.getAnUnknownErrorHint(); if (TextUtils.isEmpty(anUnknownErrorHint)) { show(dialog, R.string.error_unknow); } else { show(dialog, anUnknownErrorHint); } } } OnIsRequestListener<T> onIsRequestListener = baseRxRequestModel.getOnIsRequestListener(); if (null != onIsRequestListener) { onIsRequestListener.onError(e); } baseRxRequestModel.clearAll(); messageListDalete(); } @Override public void onNext(T t) { Dialog dialog = getDialog(baseRxRequestModel); if (null != dialog && dialog.isShowing()) { try { dialog.dismiss(); } catch (Exception e) { Logger.e("Dialog-关闭异常:由于Dialog已经关闭或者依赖的Context不存在"); } } OnIsRequestListener<T> onIsRequestListener = baseRxRequestModel.getOnIsRequestListener(); if (null != onIsRequestListener) { onIsRequestListener.onNext(t); } baseRxRequestModel.clearAll(); messageListDalete(); } }); } } /** * 当数据源里面的数据长度达到一个指定的值的时候,干掉指定值长度的数据。然后继续浪(运行) */ private void messageListDalete() { synchronized (this) { int size = mOnRxMessageDisListener.size(); if (size >= SIZE) { for (int i = 0; i < size; i++) { int index = i % size; BaseRxRequestModel baseRxRequestModel = mOnRxMessageDisListener.get(index); if (null != baseRxRequestModel && baseRxRequestModel.isRunDispose()) { mOnRxMessageDisListener.delete(index); } } } mRxThreadDispatch.addRunSize(); start(); } } @Override public void getRunData(BaseRxRequestModel runData) { Message message = mHandler.obtainMessage(); message.obj = runData; mHandler.sendMessage(message); } @Override public void waitThread() { RxThreadPoolUtisl.threadWait(this); } /** * 土司提示 * * @param stringId 提示内容资源ID */ private void show(Dialog dialog, int stringId) { if (null != dialog) { Context context = dialog.getContext(); Toast.makeText(context, context.getResources().getString(stringId), Toast.LENGTH_SHORT).show(); } } /** * 土司提示 * * @param hint 提示内容 */ private void show(Dialog dialog, String hint) { if (null != dialog) { Context context = dialog.getContext(); Toast.makeText(context, hint, Toast.LENGTH_SHORT).show(); } } /** * 从RxRequestModel对象中获取dialog * * @param baseRxRequestModel RxRequestModel对象 * @return */ private Dialog getDialog(RxRequestModel baseRxRequestModel) { OnDialogGetListener onDialogGetListener = baseRxRequestModel.getOnDialogGetListener(); return null == onDialogGetListener ? null : onDialogGetListener.getDialog(); } }
LiqiNew/NoHttpRxUtils
nohttputils-r1/src/main/java/com/liqi/nohttputils/nohttp/RxThreadInterchange.java
2,493
//没有连接到服务器
line_comment
zh-cn
package com.liqi.nohttputils.nohttp; import android.app.Dialog; import android.content.Context; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.text.TextUtils; import android.widget.Toast; import com.liqi.nohttputils.R; import com.liqi.nohttputils.interfa.OnDialogGetListener; import com.liqi.nohttputils.interfa.OnIsRequestListener; import com.liqi.nohttputils.nohttp.rx_threadpool.interfa.OnRxMessageGetListener; import com.liqi.nohttputils.nohttp.rx_threadpool.model.BaseRxRequestModel; import com.liqi.nohttputils.nohttp.rx_threadpool.model.RxRequestModel; import com.liqi.nohttputils.nohttp.rx_threadpool.thread.RxThreadDispatch; import com.liqi.nohttputils.nohttp.rx_threadpool.utils.RxThreadPoolUtisl; import com.yanzhenjie.nohttp.Logger; import com.yanzhenjie.nohttp.error.NetworkError; import com.yanzhenjie.nohttp.error.NotFoundCacheError; import com.yanzhenjie.nohttp.error.TimeoutError; import com.yanzhenjie.nohttp.error.URLError; import com.yanzhenjie.nohttp.error.UnKnownHostError; import java.net.ConnectException; import java.net.ProtocolException; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * 把数据源中的数据转换成rxJava线程的中转站对象 * Created by LiQi on 2017/3/20. */ public class RxThreadInterchange implements RxThreadDispatch.OnRunDataDisListener { //Rx线程池并发数量处理值 private static final int RUNSIZE = RxUtilsConfig.ConfigBuilder.getConfigBuilder().getRxUtilsConfig().getRunRequestSize(); private static RxThreadInterchange mRxThreadInterchange; private final String REQUEST_REVOCATION = "撤销请求"; //当队列信息长度达到此长度的时候清空掉 private final int SIZE = RUNSIZE; private RxThreadDispatch mRxThreadDispatch; private OnRxMessageGetListener mOnRxMessageDisListener; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { RxRequestModel baseRxRequestModel = (RxRequestModel) msg.obj; runRequest(baseRxRequestModel); } }; private RxThreadInterchange() { } static RxThreadInterchange getRxThreadInterchange() { return mRxThreadInterchange = null == mRxThreadInterchange ? new RxThreadInterchange() : mRxThreadInterchange; } /** * 转换运行 * * @param onRxMessageGetListener 数据源对内暴露接口 * @param <T> */ <T extends BaseRxRequestModel> void start(@NonNull OnRxMessageGetListener<T> onRxMessageGetListener) { if (null == mOnRxMessageDisListener) { selectOkState(onRxMessageGetListener); } else { if (mOnRxMessageDisListener != onRxMessageGetListener) { selectOkState(onRxMessageGetListener); } } if (null == mRxThreadDispatch || !mRxThreadDispatch.isAlive()) { runToNo(); //开启中转线程 mRxThreadDispatch = new RxThreadDispatch(RUNSIZE, mOnRxMessageDisListener.getList()); mRxThreadDispatch.setOnRunDataDisListener(this); mRxThreadDispatch.setDaemon(true); mRxThreadDispatch.start(); } else { mRxThreadDispatch.setRunSize(false); synchronized (this) { start(); } } } /** * 唤醒中转线程起来做事了 */ private void start() { if (mRxThreadDispatch.isAlive() && !mRxThreadDispatch.isRunState()) { RxThreadPoolUtisl.threadNotify(RxThreadInterchange.this); //Logger.e("唤醒中转线程>>>>"); } } /** * 判断当前是已经获取数据源对象 * * @param onRxMessageDisListener */ private void selectOkState(@NonNull OnRxMessageGetListener onRxMessageDisListener) { mOnRxMessageDisListener = onRxMessageDisListener; runToNo(); } /** * 把当前中转线程打死 */ private void runToNo() { if (null != mRxThreadDispatch) { mRxThreadDispatch.setRunTag(false); mRxThreadDispatch = null; } } /** * 中转线程创建rxJava线程 * * @param baseRxRequestModel 要处理的对象 * @param <T> */ private <T> void runRequest(final RxRequestModel<T> baseRxRequestModel) { if (null != baseRxRequestModel) { Dialog dialog = getDialog(baseRxRequestModel); if (null != dialog && !dialog.isShowing()) { try { dialog.show(); } catch (Exception e) { Logger.e("Dialog-显示异常:由于Dialog依赖的Context不是栈顶。"); } } Observable.create(baseRxRequestModel) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<T>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Dialog dialog = getDialog(baseRxRequestModel); if (null != dialog && dialog.isShowing()) { try { dialog.dismiss(); } catch (Exception e1) { Logger.e("Dialog-关闭异常:由于Dialog已经关闭或者依赖的Context不存在"); } } // 提示异常信息。 if (e instanceof NetworkError) {// 网络不好 show(dialog, R.string.error_please_check_network); } else if (e instanceof TimeoutError) {// 请求超时 show(dialog, R.string.error_timeout); } else if (e instanceof UnKnownHostError) {// 找不到服务器 show(dialog, R.string.error_not_found_server); } else if (e instanceof URLError) {// URL是错的 show(dialog, R.string.error_url_error); } else if (e instanceof NotFoundCacheError) { // 这个异常只会在仅仅查找缓存时没有找到缓存时返回 show(dialog, R.string.error_not_found_cache); } else if (e instanceof ProtocolException) { show(dialog, R.string.error_system_unsupport_method); } else if (e instanceof ConnectException) {//没有 <SUF> show(dialog, R.string.error_no_service); } else { if (e.getMessage().contains(REQUEST_REVOCATION)) { Logger.e(e.getMessage()); } else { Logger.e("NoHttpUtils捕获异常:" + e.toString()); StackTraceElement[] stackTrace = e.getStackTrace(); if (null != stackTrace) { for (StackTraceElement traceElement : stackTrace) { Logger.e("NoHttpUtils捕获异常:" + traceElement.toString()); } } String anUnknownErrorHint = baseRxRequestModel.getAnUnknownErrorHint(); if (TextUtils.isEmpty(anUnknownErrorHint)) { show(dialog, R.string.error_unknow); } else { show(dialog, anUnknownErrorHint); } } } OnIsRequestListener<T> onIsRequestListener = baseRxRequestModel.getOnIsRequestListener(); if (null != onIsRequestListener) { onIsRequestListener.onError(e); } baseRxRequestModel.clearAll(); messageListDalete(); } @Override public void onNext(T t) { Dialog dialog = getDialog(baseRxRequestModel); if (null != dialog && dialog.isShowing()) { try { dialog.dismiss(); } catch (Exception e) { Logger.e("Dialog-关闭异常:由于Dialog已经关闭或者依赖的Context不存在"); } } OnIsRequestListener<T> onIsRequestListener = baseRxRequestModel.getOnIsRequestListener(); if (null != onIsRequestListener) { onIsRequestListener.onNext(t); } baseRxRequestModel.clearAll(); messageListDalete(); } }); } } /** * 当数据源里面的数据长度达到一个指定的值的时候,干掉指定值长度的数据。然后继续浪(运行) */ private void messageListDalete() { synchronized (this) { int size = mOnRxMessageDisListener.size(); if (size >= SIZE) { for (int i = 0; i < size; i++) { int index = i % size; BaseRxRequestModel baseRxRequestModel = mOnRxMessageDisListener.get(index); if (null != baseRxRequestModel && baseRxRequestModel.isRunDispose()) { mOnRxMessageDisListener.delete(index); } } } mRxThreadDispatch.addRunSize(); start(); } } @Override public void getRunData(BaseRxRequestModel runData) { Message message = mHandler.obtainMessage(); message.obj = runData; mHandler.sendMessage(message); } @Override public void waitThread() { RxThreadPoolUtisl.threadWait(this); } /** * 土司提示 * * @param stringId 提示内容资源ID */ private void show(Dialog dialog, int stringId) { if (null != dialog) { Context context = dialog.getContext(); Toast.makeText(context, context.getResources().getString(stringId), Toast.LENGTH_SHORT).show(); } } /** * 土司提示 * * @param hint 提示内容 */ private void show(Dialog dialog, String hint) { if (null != dialog) { Context context = dialog.getContext(); Toast.makeText(context, hint, Toast.LENGTH_SHORT).show(); } } /** * 从RxRequestModel对象中获取dialog * * @param baseRxRequestModel RxRequestModel对象 * @return */ private Dialog getDialog(RxRequestModel baseRxRequestModel) { OnDialogGetListener onDialogGetListener = baseRxRequestModel.getOnDialogGetListener(); return null == onDialogGetListener ? null : onDialogGetListener.getDialog(); } }
false
2,257
5
2,493
5
2,697
5
2,493
5
3,259
9
false
false
false
false
false
true
60469_10
package com.tencent.liteav.beautykit.constant; public class BeautyConstants { public static final int TAB_TYPE_BEAUTY = 10001; // 美颜 public static final int TAB_TYPE_FILTER = 10002; // 滤镜 public static final int TAB_TYPE_MOTION = 10003; // 动效 public static final int TAB_TYPE_BEAUTY_FACE = 10004; // 美妆 public static final int TAB_TYPE_GESTURE = 10005; // 手势 public static final int TAB_TYPE_CUTOUT_BACKGROUND = 10006; // 抠背 public static final int TAB_TYPE_GREEN = 10007; // 绿幕 public static final int ITEM_TYPE_BEAUTY_SMOOTH = 20101; // 光滑 public static final int ITEM_TYPE_BEAUTY_NATURAL = 20102; // 自然 public static final int ITEM_TYPE_BEAUTY_PITU = 20103; // 天天P图 public static final int ITEM_TYPE_BEAUTY_WHITE = 20104; // 美白 public static final int ITEM_TYPE_BEAUTY_RUDDY = 20105; // 红润 public static final int ITEM_TYPE_BEAUTY_BIG_EYE = 20106; // 大眼 public static final int ITEM_TYPE_BEAUTY_FACES_LIM = 20107; // 瘦脸 public static final int ITEM_TYPE_BEAUTY_FACEV = 20108; // V脸 public static final int ITEM_TYPE_BEAUTY_CHIN = 20109; // 下巴 public static final int ITEM_TYPE_BEAUTY_FACE_SHORT = 20110; // 短脸 public static final int ITEM_TYPE_BEAUTY_NOSES_LIM = 20111; // 瘦鼻 public static final int ITEM_TYPE_BEAUTY_EYE_BRIGHT = 20112; // 亮眼 public static final int ITEM_TYPE_BEAUTY_TOOTH_WHITE = 20113; // 白牙 public static final int ITEM_TYPE_BEAUTY_WRINKLE_REMOVE = 20114; // 祛皱 public static final int ITEM_TYPE_BEAUTY_POUCH_REMOVE = 20115; // 祛眼袋 public static final int ITEM_TYPE_BEAUTY_SMILE_LINES = 20116; // 袪法令纹 public static final int ITEM_TYPE_BEAUTY_FOREHEAD = 20117; // 发际线 public static final int ITEM_TYPE_BEAUTY_EYE_DISTANCE = 20118; // 眼距 public static final int ITEM_TYPE_BEAUTY_EYE_ANGLE = 20119; // 眼角 public static final int ITEM_TYPE_BEAUTY_MOUTH_SHAPE = 20120; // 嘴型 public static final int ITEM_TYPE_BEAUTY_NOSEWING = 20121; // 鼻翼 public static final int ITEM_TYPE_BEAUTY_NOSE_POSITION = 20122; // 鼻子位置 public static final int ITEM_TYPE_BEAUTY_MOUSE_WIDTH = 20123; // 嘴唇厚度 public static final int ITEM_TYPE_BEAUTY_FACE_SHAPE = 20124; // 脸型 public static final int ITEM_TYPE_FILTER_FACE_SHAPE = 20201; // 无特效 public static final int ITEM_TYPE_FILTER_BAIXI = 20202; // 白皙 public static final int ITEM_TYPE_FILTER_STANDARD = 20203; // 标准 public static final int ITEM_TYPE_FILTER_ZIRAN = 20204; // 自然 public static final int ITEM_TYPE_FILTER_CHEERY = 20205; // 樱红 public static final int ITEM_TYPE_FILTER_CLOUD = 20206; // 云裳 public static final int ITEM_TYPE_FILTER_PURE = 20207; // 纯真 public static final int ITEM_TYPE_FILTER_ORCHID = 20208; // 白兰 public static final int ITEM_TYPE_FILTER_VITALITY = 20209; // 元气 public static final int ITEM_TYPE_FILTER_SUPER = 20210; // 超脱 public static final int ITEM_TYPE_FILTER_FRAGRANCE = 20211; // 香氛 public static final int ITEM_TYPE_FILTER_WHITE = 20212; // 美白 public static final int ITEM_TYPE_FILTER_ROMANTIC = 20213; // 浪漫 public static final int ITEM_TYPE_FILTER_FRESH = 20214; // 清新 public static final int ITEM_TYPE_FILTER_BEAUTIFUL = 20215; // 唯美 public static final int ITEM_TYPE_FILTER_PINK = 20216; // 粉嫩 public static final int ITEM_TYPE_FILTER_REMINISCENCE = 20217; // 怀旧 public static final int ITEM_TYPE_FILTER_BLUES = 20218; // 蓝调 public static final int ITEM_TYPE_FILTER_COOL = 20219; // 清凉 public static final int ITEM_TYPE_FILTER_JAPANESE = 20220; // 日系 public static final int ITEM_TYPE_MOTION_NONE = 20301; // 动效,无特效 public static final int ITEM_TYPE_MOTION_MATERIAL = 20302; // 动效,素材 public static final int ITEM_TYPE_BEAUTY_FACE_NONE = 20401; // 美妆,无特效 public static final int ITEM_TYPE_BEAUTY_FACE_MATERIAL = 20402; // 美妆,素材 public static final int ITEM_TYPE_GESTURE_NONE = 20501; // 手势,无特效 public static final int ITEM_TYPE_GESTURE_MATERIAL = 20502; // 手势,素材 public static final int ITEM_TYPE_CUTOUT_BACKGROUND_NONE = 20601; // 抠背,无特效 public static final int ITEM_TYPE_CUTOUT_BACKGROUND_MATERIAL = 20602; // 抠背,AI public static final int ITEM_TYPE_GREEN_NONE = 20701; // 绿幕,无特效 public static final int ITEM_TYPE_GREEN_GOOD_LUCK = 20702; // 绿幕,good luck public static final String BEAUTY_BG_GRAY = "#CC000000";// 灰色背景 }
LiteAVSDK/UGSV_Android
Demo/beautykit/src/main/java/com/tencent/liteav/beautykit/constant/BeautyConstants.java
1,868
// 美妆,素材
line_comment
zh-cn
package com.tencent.liteav.beautykit.constant; public class BeautyConstants { public static final int TAB_TYPE_BEAUTY = 10001; // 美颜 public static final int TAB_TYPE_FILTER = 10002; // 滤镜 public static final int TAB_TYPE_MOTION = 10003; // 动效 public static final int TAB_TYPE_BEAUTY_FACE = 10004; // 美妆 public static final int TAB_TYPE_GESTURE = 10005; // 手势 public static final int TAB_TYPE_CUTOUT_BACKGROUND = 10006; // 抠背 public static final int TAB_TYPE_GREEN = 10007; // 绿幕 public static final int ITEM_TYPE_BEAUTY_SMOOTH = 20101; // 光滑 public static final int ITEM_TYPE_BEAUTY_NATURAL = 20102; // 自然 public static final int ITEM_TYPE_BEAUTY_PITU = 20103; // 天天P图 public static final int ITEM_TYPE_BEAUTY_WHITE = 20104; // 美白 public static final int ITEM_TYPE_BEAUTY_RUDDY = 20105; // 红润 public static final int ITEM_TYPE_BEAUTY_BIG_EYE = 20106; // 大眼 public static final int ITEM_TYPE_BEAUTY_FACES_LIM = 20107; // 瘦脸 public static final int ITEM_TYPE_BEAUTY_FACEV = 20108; // V脸 public static final int ITEM_TYPE_BEAUTY_CHIN = 20109; // 下巴 public static final int ITEM_TYPE_BEAUTY_FACE_SHORT = 20110; // 短脸 public static final int ITEM_TYPE_BEAUTY_NOSES_LIM = 20111; // 瘦鼻 public static final int ITEM_TYPE_BEAUTY_EYE_BRIGHT = 20112; // 亮眼 public static final int ITEM_TYPE_BEAUTY_TOOTH_WHITE = 20113; // 白牙 public static final int ITEM_TYPE_BEAUTY_WRINKLE_REMOVE = 20114; // 祛皱 public static final int ITEM_TYPE_BEAUTY_POUCH_REMOVE = 20115; // 祛眼袋 public static final int ITEM_TYPE_BEAUTY_SMILE_LINES = 20116; // 袪法令纹 public static final int ITEM_TYPE_BEAUTY_FOREHEAD = 20117; // 发际线 public static final int ITEM_TYPE_BEAUTY_EYE_DISTANCE = 20118; // 眼距 public static final int ITEM_TYPE_BEAUTY_EYE_ANGLE = 20119; // 眼角 public static final int ITEM_TYPE_BEAUTY_MOUTH_SHAPE = 20120; // 嘴型 public static final int ITEM_TYPE_BEAUTY_NOSEWING = 20121; // 鼻翼 public static final int ITEM_TYPE_BEAUTY_NOSE_POSITION = 20122; // 鼻子位置 public static final int ITEM_TYPE_BEAUTY_MOUSE_WIDTH = 20123; // 嘴唇厚度 public static final int ITEM_TYPE_BEAUTY_FACE_SHAPE = 20124; // 脸型 public static final int ITEM_TYPE_FILTER_FACE_SHAPE = 20201; // 无特效 public static final int ITEM_TYPE_FILTER_BAIXI = 20202; // 白皙 public static final int ITEM_TYPE_FILTER_STANDARD = 20203; // 标准 public static final int ITEM_TYPE_FILTER_ZIRAN = 20204; // 自然 public static final int ITEM_TYPE_FILTER_CHEERY = 20205; // 樱红 public static final int ITEM_TYPE_FILTER_CLOUD = 20206; // 云裳 public static final int ITEM_TYPE_FILTER_PURE = 20207; // 纯真 public static final int ITEM_TYPE_FILTER_ORCHID = 20208; // 白兰 public static final int ITEM_TYPE_FILTER_VITALITY = 20209; // 元气 public static final int ITEM_TYPE_FILTER_SUPER = 20210; // 超脱 public static final int ITEM_TYPE_FILTER_FRAGRANCE = 20211; // 香氛 public static final int ITEM_TYPE_FILTER_WHITE = 20212; // 美白 public static final int ITEM_TYPE_FILTER_ROMANTIC = 20213; // 浪漫 public static final int ITEM_TYPE_FILTER_FRESH = 20214; // 清新 public static final int ITEM_TYPE_FILTER_BEAUTIFUL = 20215; // 唯美 public static final int ITEM_TYPE_FILTER_PINK = 20216; // 粉嫩 public static final int ITEM_TYPE_FILTER_REMINISCENCE = 20217; // 怀旧 public static final int ITEM_TYPE_FILTER_BLUES = 20218; // 蓝调 public static final int ITEM_TYPE_FILTER_COOL = 20219; // 清凉 public static final int ITEM_TYPE_FILTER_JAPANESE = 20220; // 日系 public static final int ITEM_TYPE_MOTION_NONE = 20301; // 动效,无特效 public static final int ITEM_TYPE_MOTION_MATERIAL = 20302; // 动效,素材 public static final int ITEM_TYPE_BEAUTY_FACE_NONE = 20401; // 美妆,无特效 public static final int ITEM_TYPE_BEAUTY_FACE_MATERIAL = 20402; // 美妆 <SUF> public static final int ITEM_TYPE_GESTURE_NONE = 20501; // 手势,无特效 public static final int ITEM_TYPE_GESTURE_MATERIAL = 20502; // 手势,素材 public static final int ITEM_TYPE_CUTOUT_BACKGROUND_NONE = 20601; // 抠背,无特效 public static final int ITEM_TYPE_CUTOUT_BACKGROUND_MATERIAL = 20602; // 抠背,AI public static final int ITEM_TYPE_GREEN_NONE = 20701; // 绿幕,无特效 public static final int ITEM_TYPE_GREEN_GOOD_LUCK = 20702; // 绿幕,good luck public static final String BEAUTY_BG_GRAY = "#CC000000";// 灰色背景 }
false
1,728
7
1,868
8
1,732
5
1,868
8
2,317
11
false
false
false
false
false
true
18608_2
package com.liuguilin.kotlintools.bean; import java.util.List; /** * FileName: JokeBean * Founder: LiuGuiLin * Profile: */ public class JokeBean { /** * reason : success * result : [{"content":"\u200d\u200d\u200d\u200d记者:\u201c许仙先生,你和妻子这么多年保持爱情新鲜的秘诀是什么?\u201d 许仙:\u201c每天我下班回家,她都迎上来给我一个蛇吻。\u201d\u200d\u200d\u200d\u200d","hashId":"671124C4196663E8122C4FDC4B60CAC5","unixtime":1437575665},{"content":"\u200d\u200d\u200d\u200d今天逗比了,一客户给我打招呼,很热情的样子。 手里拿着一袋瓜子,朝我方向走过来,然后倒出点瓜子在手心。 有瓜子的那只手伸向我说:\u201c把那资料给我看看!\u201d 我居然说:\u201c不吃。\u201d 我真想多了。\u200d\u200d\u200d\u200d","hashId":"D67AE38C3441749BB005511702342A5B","unixtime":1437576211},{"content":"有一同事住我家隔壁。昨天十万火急给我来电话,说:\u201c兄弟我家断网了,现在急需用网想去你家上半个小时解决了先。很急!\u201d我:\u201c都这么久兄弟了,还需要打我电话问么,我老婆在家。你急,直接去上就是了。随便上。\u201d他TM竟然说:上你老婆?那怎么好意思呢!","hashId":"3098c221e68d492ced214c82664efc7c","unixtime":1437576232},{"content":"同事辞职,昨晚请他去喝酒!酒至半酣,他一把拉住我\u201c哥,只有你对我好,我得报答你\u201d\u201c嗯?\u201d\u201c公司第三厂房女厕所知道吧?\u201d\u201c嗯\u201d\u201c女厕所后面有一排树,靠近第四厂房正数第三颗往那一蹲,嗯,有wifi、三格!\u201d","hashId":"5afdd13ba93ca2c05cc661e5153e5125","unixtime":1437576232},{"content":"老婆回家对老公大怒:你是不是和我秘书有一腿?老公:是啊!我不是经过你同意了吗?老婆:你放屁,我什么时候同意过的?老公:我问你秘书小美能不能干,你说能干。","hashId":"dbd44c22b5a127ec21ac987e16525553","unixtime":1437576232},{"content":"女上司责骂我的工作状态,我一直低头不语。这样的反应可能激怒了她,她一改平静的语气,咆哮道:\u201c你为什么不说话,你不服吗!\u201d我解释说:\u201c不是,我女朋友不让我跟漂亮女人说话!","hashId":"0da7ff4bea8f046f2abc4850d1351eee","unixtime":1437576232},{"content":"闺蜜应聘上了一公司老板秘书,一上班老板娘就训话:\u201c做女秘书要懂规矩,不要像前任那样!!\u201d\u201c老板娘,前任秘书怎么了?\u201d\u201c我就是前任!\u201d。。。","hashId":"a92f8e3402d117c36fadf35a960a4c01","unixtime":1437576232},{"content":"女朋友拿着手机对我说:\u201c我觉得这拖把不错,我们买一个吧?\u201d\u201c不错什么!\u201d我站起来指着她说:\u201c啥时候我用的东西轮到你做决定了!\u201d","hashId":"6a01d519ff36b2a09458a9d93047102f","unixtime":1437576232},{"content":"小朋友,你要知道:在对不起前面加个阿姨,这样的道歉基本上是没用的。","hashId":"f1afcece74351768b338cb2320166c2d","unixtime":1437576232},{"content":"果然和人聊天不能太敷衍。。。刚刚室友讲到女朋友爱说梦话,我随口接了一句我知道,现在气氛变得十分微妙。","hashId":"cde62d88a9f689d536716f34e3dcd088","unixtime":1437576232}] * error_code : 0 */ private String reason; private int error_code; private List<ResultBean> result; public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public List<ResultBean> getResult() { return result; } public void setResult(List<ResultBean> result) { this.result = result; } public static class ResultBean { /** * content : ‍‍‍‍记者:“许仙先生,你和妻子这么多年保持爱情新鲜的秘诀是什么?” 许仙:“每天我下班回家,她都迎上来给我一个蛇吻。”‍‍‍‍ * hashId : 671124C4196663E8122C4FDC4B60CAC5 * unixtime : 1437575665 */ private String content; private String hashId; private int unixtime; 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; } } }
LiuGuiLinAndroid/Kotlin
Sample/KotlinTools/app/src/main/java/com/liuguilin/kotlintools/bean/JokeBean.java
2,022
/** * content : ‍‍‍‍记者:“许仙先生,你和妻子这么多年保持爱情新鲜的秘诀是什么?” 许仙:“每天我下班回家,她都迎上来给我一个蛇吻。”‍‍‍‍ * hashId : 671124C4196663E8122C4FDC4B60CAC5 * unixtime : 1437575665 */
block_comment
zh-cn
package com.liuguilin.kotlintools.bean; import java.util.List; /** * FileName: JokeBean * Founder: LiuGuiLin * Profile: */ public class JokeBean { /** * reason : success * result : [{"content":"\u200d\u200d\u200d\u200d记者:\u201c许仙先生,你和妻子这么多年保持爱情新鲜的秘诀是什么?\u201d 许仙:\u201c每天我下班回家,她都迎上来给我一个蛇吻。\u201d\u200d\u200d\u200d\u200d","hashId":"671124C4196663E8122C4FDC4B60CAC5","unixtime":1437575665},{"content":"\u200d\u200d\u200d\u200d今天逗比了,一客户给我打招呼,很热情的样子。 手里拿着一袋瓜子,朝我方向走过来,然后倒出点瓜子在手心。 有瓜子的那只手伸向我说:\u201c把那资料给我看看!\u201d 我居然说:\u201c不吃。\u201d 我真想多了。\u200d\u200d\u200d\u200d","hashId":"D67AE38C3441749BB005511702342A5B","unixtime":1437576211},{"content":"有一同事住我家隔壁。昨天十万火急给我来电话,说:\u201c兄弟我家断网了,现在急需用网想去你家上半个小时解决了先。很急!\u201d我:\u201c都这么久兄弟了,还需要打我电话问么,我老婆在家。你急,直接去上就是了。随便上。\u201d他TM竟然说:上你老婆?那怎么好意思呢!","hashId":"3098c221e68d492ced214c82664efc7c","unixtime":1437576232},{"content":"同事辞职,昨晚请他去喝酒!酒至半酣,他一把拉住我\u201c哥,只有你对我好,我得报答你\u201d\u201c嗯?\u201d\u201c公司第三厂房女厕所知道吧?\u201d\u201c嗯\u201d\u201c女厕所后面有一排树,靠近第四厂房正数第三颗往那一蹲,嗯,有wifi、三格!\u201d","hashId":"5afdd13ba93ca2c05cc661e5153e5125","unixtime":1437576232},{"content":"老婆回家对老公大怒:你是不是和我秘书有一腿?老公:是啊!我不是经过你同意了吗?老婆:你放屁,我什么时候同意过的?老公:我问你秘书小美能不能干,你说能干。","hashId":"dbd44c22b5a127ec21ac987e16525553","unixtime":1437576232},{"content":"女上司责骂我的工作状态,我一直低头不语。这样的反应可能激怒了她,她一改平静的语气,咆哮道:\u201c你为什么不说话,你不服吗!\u201d我解释说:\u201c不是,我女朋友不让我跟漂亮女人说话!","hashId":"0da7ff4bea8f046f2abc4850d1351eee","unixtime":1437576232},{"content":"闺蜜应聘上了一公司老板秘书,一上班老板娘就训话:\u201c做女秘书要懂规矩,不要像前任那样!!\u201d\u201c老板娘,前任秘书怎么了?\u201d\u201c我就是前任!\u201d。。。","hashId":"a92f8e3402d117c36fadf35a960a4c01","unixtime":1437576232},{"content":"女朋友拿着手机对我说:\u201c我觉得这拖把不错,我们买一个吧?\u201d\u201c不错什么!\u201d我站起来指着她说:\u201c啥时候我用的东西轮到你做决定了!\u201d","hashId":"6a01d519ff36b2a09458a9d93047102f","unixtime":1437576232},{"content":"小朋友,你要知道:在对不起前面加个阿姨,这样的道歉基本上是没用的。","hashId":"f1afcece74351768b338cb2320166c2d","unixtime":1437576232},{"content":"果然和人聊天不能太敷衍。。。刚刚室友讲到女朋友爱说梦话,我随口接了一句我知道,现在气氛变得十分微妙。","hashId":"cde62d88a9f689d536716f34e3dcd088","unixtime":1437576232}] * error_code : 0 */ private String reason; private int error_code; private List<ResultBean> result; public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public List<ResultBean> getResult() { return result; } public void setResult(List<ResultBean> result) { this.result = result; } public static class ResultBean { /** * con <SUF>*/ private String content; private String hashId; private int unixtime; 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; } } }
false
1,702
112
2,022
128
1,809
106
2,022
128
2,468
161
false
false
false
false
false
true
52873_0
package com.foodforcat.pinnedheaderlistviewexample; import com.foodforcat.R; import com.foodforcat.pinnedheaderlistview.PinnedHeaderListView; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends Activity { private boolean isScroll = true; private MyAdapter adapter; private ListView left_listView; private String[] leftStr = new String[] { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", "星期1", "星期2", "星期3", "星期4", "星期5", "星期6", "星期7", "星期8", "星期9", "星期0", "星期01", "星期02" }; private boolean[] flagArray = { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; private String[][] rightStr = new String[][] { { "星期一 早餐", "星期一 午餐", "星期一 晚餐" }, { "星期二 早餐", "星期二 午餐", "星期二 晚餐" }, { "星期三 早餐", "星期三 午餐", "星期三 晚餐" }, { "星期四 早餐", "星期四 午餐", "星期四 晚餐" }, { "星期五 早餐", "星期五 午餐", "星期五 晚餐" }, { "星期六 早餐", "星期六 午餐", "星期六 晚餐" }, { "星期日 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期1 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期2 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期3 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期4 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期5 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期6 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期7 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期8 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期9 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期0 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期01 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期02 早餐", "星期日 午餐", "星期日 晚餐" } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final PinnedHeaderListView right_listview = (PinnedHeaderListView) findViewById(R.id.pinnedListView); final TestSectionedAdapter sectionedAdapter = new TestSectionedAdapter(this, leftStr, rightStr); right_listview.setAdapter(sectionedAdapter); left_listView = (ListView) findViewById(R.id.left_listview); adapter = new MyAdapter(); left_listView.setAdapter(adapter); left_listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) { isScroll = false; for (int i = 0; i < leftStr.length; i++) { if (i == position) { flagArray[i] = true; } else { flagArray[i] = false; } } adapter.notifyDataSetChanged(); int rightSection = 0; for (int i = 0; i < position; i++) { rightSection += sectionedAdapter.getCountForSection(i) + 1; } right_listview.setSelection(rightSection); } }); right_listview.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView arg0, int scrollState) { switch (scrollState) { // 当不滚动时 case OnScrollListener.SCROLL_STATE_IDLE: // 判断滚动到底部 if (right_listview.getLastVisiblePosition() == (right_listview.getCount() - 1)) { left_listView.setSelection(ListView.FOCUS_DOWN); } // 判断滚动到顶部 if (right_listview.getFirstVisiblePosition() == 0) { } break; } } int y = 0; int x = 0; int z = 0; @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (isScroll) { for (int i = 0; i < rightStr.length; i++) { if (i == sectionedAdapter.getSectionForPosition(right_listview.getFirstVisiblePosition())) { flagArray[i] = true; x = i; } else { flagArray[i] = false; } } if (x != y) { adapter.notifyDataSetChanged(); y = x; if (y == left_listView.getLastVisiblePosition()) { z = z + 3; left_listView.setSelection(z); } if (x == left_listView.getFirstVisiblePosition()) { z = z - 1; left_listView.setSelection(z); } if (firstVisibleItem + visibleItemCount == totalItemCount - 1) { left_listView.setSelection(ListView.FOCUS_DOWN); } } } else { isScroll = true; } } }); } public class MyAdapter extends BaseAdapter { @Override public int getCount() { return leftStr.length; } @Override public Object getItem(int arg0) { return leftStr[arg0]; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { Holder holder = null; if (arg1 == null) { holder = new Holder(); arg1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.left_list_item, null); holder.left_list_item = (TextView) arg1.findViewById(R.id.left_list_item); arg1.setTag(holder); } else { holder = (Holder) arg1.getTag(); } holder.updataView(arg0); return arg1; } private class Holder { private TextView left_list_item; public void updataView(final int position) { left_list_item.setText(leftStr[position]); if (flagArray[position]) { left_list_item.setBackgroundColor(Color.rgb(255, 255, 255)); } else { left_list_item.setBackgroundColor(Color.TRANSPARENT); } } } } }
LiuSecret/LinkedListView
example/src/com/foodforcat/pinnedheaderlistviewexample/MainActivity.java
2,165
// 当不滚动时
line_comment
zh-cn
package com.foodforcat.pinnedheaderlistviewexample; import com.foodforcat.R; import com.foodforcat.pinnedheaderlistview.PinnedHeaderListView; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends Activity { private boolean isScroll = true; private MyAdapter adapter; private ListView left_listView; private String[] leftStr = new String[] { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", "星期1", "星期2", "星期3", "星期4", "星期5", "星期6", "星期7", "星期8", "星期9", "星期0", "星期01", "星期02" }; private boolean[] flagArray = { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; private String[][] rightStr = new String[][] { { "星期一 早餐", "星期一 午餐", "星期一 晚餐" }, { "星期二 早餐", "星期二 午餐", "星期二 晚餐" }, { "星期三 早餐", "星期三 午餐", "星期三 晚餐" }, { "星期四 早餐", "星期四 午餐", "星期四 晚餐" }, { "星期五 早餐", "星期五 午餐", "星期五 晚餐" }, { "星期六 早餐", "星期六 午餐", "星期六 晚餐" }, { "星期日 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期1 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期2 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期3 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期4 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期5 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期6 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期7 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期8 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期9 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期0 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期01 早餐", "星期日 午餐", "星期日 晚餐" }, { "星期02 早餐", "星期日 午餐", "星期日 晚餐" } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final PinnedHeaderListView right_listview = (PinnedHeaderListView) findViewById(R.id.pinnedListView); final TestSectionedAdapter sectionedAdapter = new TestSectionedAdapter(this, leftStr, rightStr); right_listview.setAdapter(sectionedAdapter); left_listView = (ListView) findViewById(R.id.left_listview); adapter = new MyAdapter(); left_listView.setAdapter(adapter); left_listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) { isScroll = false; for (int i = 0; i < leftStr.length; i++) { if (i == position) { flagArray[i] = true; } else { flagArray[i] = false; } } adapter.notifyDataSetChanged(); int rightSection = 0; for (int i = 0; i < position; i++) { rightSection += sectionedAdapter.getCountForSection(i) + 1; } right_listview.setSelection(rightSection); } }); right_listview.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView arg0, int scrollState) { switch (scrollState) { // 当不 <SUF> case OnScrollListener.SCROLL_STATE_IDLE: // 判断滚动到底部 if (right_listview.getLastVisiblePosition() == (right_listview.getCount() - 1)) { left_listView.setSelection(ListView.FOCUS_DOWN); } // 判断滚动到顶部 if (right_listview.getFirstVisiblePosition() == 0) { } break; } } int y = 0; int x = 0; int z = 0; @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (isScroll) { for (int i = 0; i < rightStr.length; i++) { if (i == sectionedAdapter.getSectionForPosition(right_listview.getFirstVisiblePosition())) { flagArray[i] = true; x = i; } else { flagArray[i] = false; } } if (x != y) { adapter.notifyDataSetChanged(); y = x; if (y == left_listView.getLastVisiblePosition()) { z = z + 3; left_listView.setSelection(z); } if (x == left_listView.getFirstVisiblePosition()) { z = z - 1; left_listView.setSelection(z); } if (firstVisibleItem + visibleItemCount == totalItemCount - 1) { left_listView.setSelection(ListView.FOCUS_DOWN); } } } else { isScroll = true; } } }); } public class MyAdapter extends BaseAdapter { @Override public int getCount() { return leftStr.length; } @Override public Object getItem(int arg0) { return leftStr[arg0]; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { Holder holder = null; if (arg1 == null) { holder = new Holder(); arg1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.left_list_item, null); holder.left_list_item = (TextView) arg1.findViewById(R.id.left_list_item); arg1.setTag(holder); } else { holder = (Holder) arg1.getTag(); } holder.updataView(arg0); return arg1; } private class Holder { private TextView left_list_item; public void updataView(final int position) { left_list_item.setText(leftStr[position]); if (flagArray[position]) { left_list_item.setBackgroundColor(Color.rgb(255, 255, 255)); } else { left_list_item.setBackgroundColor(Color.TRANSPARENT); } } } } }
false
1,736
5
2,165
6
1,857
5
2,165
6
2,715
9
false
false
false
false
false
true
19598_0
package DP; import java.util.Arrays; import java.util.Comparator; /** * @Author 年年 * @Date 2021/12/15 11:47 * @Description LeetCode-354:俄罗斯套娃信封问题 * https://leetcode-cn.com/problems/russian-doll-envelopes/ * 给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。 * 当另一个信封的宽度和高度都比这个信封大(注意不能相等)的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。 * 请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。 * 注意:不允许旋转信封。 */ public class MaxEnvelopes { /** * 方法一:dp * 理解:对于这种两个维度都要比较大小的问题,我们可以考虑一个维度升序,一个维度降序,比如 * 在第一个属性上升序,第二个维度降序,后续我们从前至后遍历的时候,可以只比较第二个维度的大 * 因为对于<i,j>两个位置的元素 nums[i][0]<=nums[j][0],一定成立。此时只要nums[i][1] * >=nums[j][1],则可以说第j个元素大于第i个元素,因为此时我们在第二个位置使用降序,所以不会 * 出现{<6,7><6,8><6,9>}之类的序列,只会有{<6,9><6,8><6,7>},这样不会判定<6,8>比<6,7>大, * 符合题目要求的大于的定义 * <p> * int[] dp[i] 表示以第i个信封收尾时最多叠加几次 * 递推公式: * dp[i] = Math.max{dp[i],dp[j = 0...i]+1} | (envelopes[i]>envelopes[j]) * * @param envelopes * @return */ public int maxEnvelopes(int[][] envelopes) { Arrays.sort(envelopes, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if (o1[0] == o2[0]) return o2[1] - o1[1]; else return o1[0] - o2[0]; } }); int[] dp = new int[envelopes.length]; int max = 0; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < i; j++) { if (envelopes[i][1] > envelopes[j][1]) { dp[i] = Math.max(dp[i], dp[j] + 1); max = Math.max(max, dp[i]); } } } return max + 1; } /* * 方法二:优化,dp+二分查找 * */ }
LiuTongyuan/LeetCode
src/DP/MaxEnvelopes.java
803
/** * @Author 年年 * @Date 2021/12/15 11:47 * @Description LeetCode-354:俄罗斯套娃信封问题 * https://leetcode-cn.com/problems/russian-doll-envelopes/ * 给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。 * 当另一个信封的宽度和高度都比这个信封大(注意不能相等)的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。 * 请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。 * 注意:不允许旋转信封。 */
block_comment
zh-cn
package DP; import java.util.Arrays; import java.util.Comparator; /** * @Au <SUF>*/ public class MaxEnvelopes { /** * 方法一:dp * 理解:对于这种两个维度都要比较大小的问题,我们可以考虑一个维度升序,一个维度降序,比如 * 在第一个属性上升序,第二个维度降序,后续我们从前至后遍历的时候,可以只比较第二个维度的大 * 因为对于<i,j>两个位置的元素 nums[i][0]<=nums[j][0],一定成立。此时只要nums[i][1] * >=nums[j][1],则可以说第j个元素大于第i个元素,因为此时我们在第二个位置使用降序,所以不会 * 出现{<6,7><6,8><6,9>}之类的序列,只会有{<6,9><6,8><6,7>},这样不会判定<6,8>比<6,7>大, * 符合题目要求的大于的定义 * <p> * int[] dp[i] 表示以第i个信封收尾时最多叠加几次 * 递推公式: * dp[i] = Math.max{dp[i],dp[j = 0...i]+1} | (envelopes[i]>envelopes[j]) * * @param envelopes * @return */ public int maxEnvelopes(int[][] envelopes) { Arrays.sort(envelopes, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if (o1[0] == o2[0]) return o2[1] - o1[1]; else return o1[0] - o2[0]; } }); int[] dp = new int[envelopes.length]; int max = 0; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < i; j++) { if (envelopes[i][1] > envelopes[j][1]) { dp[i] = Math.max(dp[i], dp[j] + 1); max = Math.max(max, dp[i]); } } } return max + 1; } /* * 方法二:优化,dp+二分查找 * */ }
false
704
178
803
219
766
184
803
219
1,080
322
true
true
true
true
true
false
18150_2
package com.lag.lanlord.constant; import com.lag.lanlord.LandlordBaseUtil; import com.lag.lanlord.card.define.EnumCardTypePoker; public interface Consts { int ROLE_PEASANT = 1; // 农民 int ROLE_LANDLORD = 2; // 地主 int TYPE_HIGH = 1; // 单牌 int TYPE_PAIR = 2; // 一对 int TYPE_THREE = 3; // 三张 int TYPE_STRAIGHT = 4; // 顺子 例34567 int TYPE_SERIAL_PAIR = 5; // 连对 例778899 int TYPE_THREE_WITH_ONE = 6; // 三带1 例3335 int TYPE_THREE_WITH_TWO = 7; // 三带2 例88866 int TYPE_SERIAL_THREE = 8; // 三张的顺子 例777888 int TYPE_AIRPLANE = 9; // 飞机 多个连续的三带1或连续的三带2 例777888999456 int TYPE_FOUR_WITH_TWO = 10; // 四带二或四带两对 int TYPE_BOMB = 11; // 炸弹 int TYPE_ROCKET = 12; // 火箭(王炸) // 部分牌值 int KING_MIN = EnumCardTypePoker.KING.getFirst();// 小王 int KING_MAX = EnumCardTypePoker.KING.getLast();// 大王 int SIGNBOARD = EnumCardTypePoker.SIGNBOARD.getFirst();// 广告牌 int KING_TYPE = LandlordBaseUtil.getCardType(KING_MIN); // 大小王的type int KING_VALUE_MIN = LandlordBaseUtil.getCardValue(KING_MIN);// 小王解析后的value int KING_VALUE_MAX = LandlordBaseUtil.getCardValue(KING_MAX);// 大王解析后的value }
Liuguozhu/landlord
src/com/lanlord/constant/Consts.java
498
// 三带1 例3335
line_comment
zh-cn
package com.lag.lanlord.constant; import com.lag.lanlord.LandlordBaseUtil; import com.lag.lanlord.card.define.EnumCardTypePoker; public interface Consts { int ROLE_PEASANT = 1; // 农民 int ROLE_LANDLORD = 2; // 地主 int TYPE_HIGH = 1; // 单牌 int TYPE_PAIR = 2; // 一对 int TYPE_THREE = 3; // 三张 int TYPE_STRAIGHT = 4; // 顺子 例34567 int TYPE_SERIAL_PAIR = 5; // 连对 例778899 int TYPE_THREE_WITH_ONE = 6; // 三带 <SUF> int TYPE_THREE_WITH_TWO = 7; // 三带2 例88866 int TYPE_SERIAL_THREE = 8; // 三张的顺子 例777888 int TYPE_AIRPLANE = 9; // 飞机 多个连续的三带1或连续的三带2 例777888999456 int TYPE_FOUR_WITH_TWO = 10; // 四带二或四带两对 int TYPE_BOMB = 11; // 炸弹 int TYPE_ROCKET = 12; // 火箭(王炸) // 部分牌值 int KING_MIN = EnumCardTypePoker.KING.getFirst();// 小王 int KING_MAX = EnumCardTypePoker.KING.getLast();// 大王 int SIGNBOARD = EnumCardTypePoker.SIGNBOARD.getFirst();// 广告牌 int KING_TYPE = LandlordBaseUtil.getCardType(KING_MIN); // 大小王的type int KING_VALUE_MIN = LandlordBaseUtil.getCardValue(KING_MIN);// 小王解析后的value int KING_VALUE_MAX = LandlordBaseUtil.getCardValue(KING_MAX);// 大王解析后的value }
false
470
11
498
11
459
9
498
11
630
13
false
false
false
false
false
true
22432_0
package Model; /** * 模块说明: 学生 * */ public class Student { private int id; private String sno;// 学号 private String name; private String sex; private String department;// 院系 private String homeTown;// 籍贯 private String mark;// 学分 private String email; private String tel;// 联系方式 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSno() { return sno; } public void setSno(String sno) { this.sno = sno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getHomeTown() { return homeTown; } public void setHomeTown(String homeTown) { this.homeTown = homeTown; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } }
Liujiang240556/StudentGradeMangerSystem
src/Model/Student.java
450
/** * 模块说明: 学生 * */
block_comment
zh-cn
package Model; /** * 模块说 <SUF>*/ public class Student { private int id; private String sno;// 学号 private String name; private String sex; private String department;// 院系 private String homeTown;// 籍贯 private String mark;// 学分 private String email; private String tel;// 联系方式 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSno() { return sno; } public void setSno(String sno) { this.sno = sno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getHomeTown() { return homeTown; } public void setHomeTown(String homeTown) { this.homeTown = homeTown; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } }
false
336
14
450
13
435
13
450
13
523
19
false
false
false
false
false
true
18872_7
//计划:当玩家输入/tgame join 时加入游戏 //输入/tgame quit时退出游戏 //有两个队,1v1 //杀一个人得一分 //注意,改插件版本为1.11.2,如果有其他要求请在下面删除CommandManager import com.locydragon.gamelib.api.CustomGame; import com.locydragon.gamelib.api.GameLibrary; import com.locydragon.gamelib.api.entity.PlayingPlayer; import com.locydragon.gamelib.api.event.baby.bukkitevents.GamePlayerDamageEntityEvent; import com.locydragon.gamelib.api.event.baby.bukkitevents.GamePlayerDeathEvent; import com.locydragon.gamelib.api.event.type.EventType; import com.locydragon.gamelib.api.util.CommandManager; import com.locydragon.gamelib.api.util.ScoreManager; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * @author LocyDragon * This is only a example!You can use this code anyway! */ public class TestGame extends JavaPlugin { CustomGame game = null; //游戏 ScoreManager manager = null; //积分器 @Override public void onEnable() { game = GameLibrary.getLibrary().setMaxPlayerInOneTeam(1) //设置每队最多的人数 .teamNumber(2) //设置队数量 .build() //生成Game实例对象 .addEvent(EventType.PLAYING_PLAYER_DEATH, gameEvent -> { GamePlayerDeathEvent event = (GamePlayerDeathEvent)gameEvent; //这里可以强转 PlayingPlayer player = PlayingPlayer.search(event.getProp().getEntity().getKiller()); //获取PlayingPlayer实例对象 if (player.getGame() == null || player.getTeam() == -1) { //检查一下杀人者是否在游戏当中 return; } manager.addOneScore(player.getTeam()); //加一分 game.broadcastMsg(ChatColor.RED+player.getPlayerName()+"杀死了"+event.getProp().getEntity().getName()); //广播杀敌信息 game.broadcastMsg(ChatColor.RED+"目前组"+event.getPlayer().getTeam()+"分数: "+manager.getScore(player.getTeam())); //广播分数 }) .addEvent(EventType.ON_GAME_JOIN, gameEvent -> { ((Player)gameEvent.getPlayer()).sendMessage("你进入了游戏."); //凡是以"ON"开头的事件都得转成Player,其他转成PlayingPlayer即可 }) .addEvent(EventType.ON_GAME_QUIT, gameEvent -> { ((Player)gameEvent.getPlayer()).sendMessage("你退出了游戏."); //凡是以"ON"开头的事件都得转成Player,其他转成PlayingPlayer即可 }) .startGame(); //开始游戏 manager = new ScoreManager(game); //实例化积分器对象 new CommandManager("tgame") //这是为了方便快速注册指令 .bindJoinCmd("join", this.game) //快速加入游戏指令,不过不推荐这么做 .bindQuitCmd("quit", this.game); //快速设置退出游戏指令 //注意: CommandManager仅在1.11.2以下版本奏效,若高于这个版本会报错。 //结果方案:自行注册指令 } }
LocyDragon/GameLib
TestGame.java
876
//设置每队最多的人数
line_comment
zh-cn
//计划:当玩家输入/tgame join 时加入游戏 //输入/tgame quit时退出游戏 //有两个队,1v1 //杀一个人得一分 //注意,改插件版本为1.11.2,如果有其他要求请在下面删除CommandManager import com.locydragon.gamelib.api.CustomGame; import com.locydragon.gamelib.api.GameLibrary; import com.locydragon.gamelib.api.entity.PlayingPlayer; import com.locydragon.gamelib.api.event.baby.bukkitevents.GamePlayerDamageEntityEvent; import com.locydragon.gamelib.api.event.baby.bukkitevents.GamePlayerDeathEvent; import com.locydragon.gamelib.api.event.type.EventType; import com.locydragon.gamelib.api.util.CommandManager; import com.locydragon.gamelib.api.util.ScoreManager; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * @author LocyDragon * This is only a example!You can use this code anyway! */ public class TestGame extends JavaPlugin { CustomGame game = null; //游戏 ScoreManager manager = null; //积分器 @Override public void onEnable() { game = GameLibrary.getLibrary().setMaxPlayerInOneTeam(1) //设置 <SUF> .teamNumber(2) //设置队数量 .build() //生成Game实例对象 .addEvent(EventType.PLAYING_PLAYER_DEATH, gameEvent -> { GamePlayerDeathEvent event = (GamePlayerDeathEvent)gameEvent; //这里可以强转 PlayingPlayer player = PlayingPlayer.search(event.getProp().getEntity().getKiller()); //获取PlayingPlayer实例对象 if (player.getGame() == null || player.getTeam() == -1) { //检查一下杀人者是否在游戏当中 return; } manager.addOneScore(player.getTeam()); //加一分 game.broadcastMsg(ChatColor.RED+player.getPlayerName()+"杀死了"+event.getProp().getEntity().getName()); //广播杀敌信息 game.broadcastMsg(ChatColor.RED+"目前组"+event.getPlayer().getTeam()+"分数: "+manager.getScore(player.getTeam())); //广播分数 }) .addEvent(EventType.ON_GAME_JOIN, gameEvent -> { ((Player)gameEvent.getPlayer()).sendMessage("你进入了游戏."); //凡是以"ON"开头的事件都得转成Player,其他转成PlayingPlayer即可 }) .addEvent(EventType.ON_GAME_QUIT, gameEvent -> { ((Player)gameEvent.getPlayer()).sendMessage("你退出了游戏."); //凡是以"ON"开头的事件都得转成Player,其他转成PlayingPlayer即可 }) .startGame(); //开始游戏 manager = new ScoreManager(game); //实例化积分器对象 new CommandManager("tgame") //这是为了方便快速注册指令 .bindJoinCmd("join", this.game) //快速加入游戏指令,不过不推荐这么做 .bindQuitCmd("quit", this.game); //快速设置退出游戏指令 //注意: CommandManager仅在1.11.2以下版本奏效,若高于这个版本会报错。 //结果方案:自行注册指令 } }
false
739
7
876
8
843
7
876
8
1,273
12
false
false
false
false
false
true
15431_7
import java.util.ArrayList; import java.util.Scanner; import shuhelper.web.*; public class TestWebAPI { private static Scanner in = new Scanner(System.in); public static void main(String[] args) throws Exception { testCJWebAPI(); testXKWebAPI(); } private static boolean login(WebAPI web) throws Exception { // 获取验证码图片 String validatePath = web.getCaptcha(); System.out.println("验证码图片存储在: " + validatePath); // 登录参数 System.out.print("学号: "); String username = in.next();; System.out.print("密码: "); String password = in.next();; System.out.print("验证码: "); String validate = in.next(); // 尝试登录 String res = web.login(username, password, validate); System.out.println("登录结果: " + res); // 返回登录状态 return web.isLogin(); } public static void testCJWebAPI() throws Exception { // 实例化 CJWebAPI CJWebAPI CJ = new CJWebAPI(); // 登录 if (!login(CJ)) return; // 获取2016年冬季学期(20162)课程安排 ArrayList<String[]> schedule = CJ.getScheduleArrayList("20162"); output(schedule, "课程安排 - 2016冬"); // 获取2016年秋季学期(20161)学期成绩 ArrayList<String[]> scoreTerm = CJ.getScoreTermArrayList("20161"); output(scoreTerm, "学期成绩 - 2016秋"); // 获取成绩大表 ArrayList<String[]> scoreSummary = CJ.getScoreSummaryArrayList(); output(scoreSummary, "成绩大表"); } public static void testXKWebAPI() throws Exception { // 实例化 XKWebAPI XKWebAPI XK = new XKWebAPI(); // 查看学期 String[] termInfo = XK.getTermInfo(); for (int i = 0; i < termInfo.length; i++) { System.out.printf("[%d] %s\n", i, termInfo[i]); } // 选择 System.out.print("请选择学期编号: "); int termNo = in.nextInt(); XK.setTerm(termNo); // 登录 if (!login(XK)) return; // 已选课程 ArrayList<String[]> courseTable = XK.getCourseTableArrayList(); output(courseTable, "已选课程"); // 选课排名 ArrayList<String[]> enrollRank = XK.getEnrollRankArrayList(); output(enrollRank, "选课排名"); // 查询所有"0830"课程 ArrayList<String[]> queryCourse = XK.getAllCourseArray("0830"); output(queryCourse, "0830课程"); // 查询选课系统状态 System.out.println("选课状态: " + XK.getEnrollStatus()); // 选课 System.out.println("选课结果: " + XK.enrollCourse("08305013", "1001")); // 退课 System.out.println("退课结果: " + XK.returnCourse("08305013", "1001")); } private static void output(ArrayList<String[]> arrayList, String title) { System.out.println("================================"); System.out.println(title); System.out.println("================================"); for (String[] row : arrayList) { for (String col : row) System.out.print(col + "\t"); System.out.println(); } System.out.printf("-------- Total %d row(s) --------\n", arrayList.size()); } }
Lodour/SHU-Helper
jar/TestWebAPI.java
992
// 获取成绩大表
line_comment
zh-cn
import java.util.ArrayList; import java.util.Scanner; import shuhelper.web.*; public class TestWebAPI { private static Scanner in = new Scanner(System.in); public static void main(String[] args) throws Exception { testCJWebAPI(); testXKWebAPI(); } private static boolean login(WebAPI web) throws Exception { // 获取验证码图片 String validatePath = web.getCaptcha(); System.out.println("验证码图片存储在: " + validatePath); // 登录参数 System.out.print("学号: "); String username = in.next();; System.out.print("密码: "); String password = in.next();; System.out.print("验证码: "); String validate = in.next(); // 尝试登录 String res = web.login(username, password, validate); System.out.println("登录结果: " + res); // 返回登录状态 return web.isLogin(); } public static void testCJWebAPI() throws Exception { // 实例化 CJWebAPI CJWebAPI CJ = new CJWebAPI(); // 登录 if (!login(CJ)) return; // 获取2016年冬季学期(20162)课程安排 ArrayList<String[]> schedule = CJ.getScheduleArrayList("20162"); output(schedule, "课程安排 - 2016冬"); // 获取2016年秋季学期(20161)学期成绩 ArrayList<String[]> scoreTerm = CJ.getScoreTermArrayList("20161"); output(scoreTerm, "学期成绩 - 2016秋"); // 获取 <SUF> ArrayList<String[]> scoreSummary = CJ.getScoreSummaryArrayList(); output(scoreSummary, "成绩大表"); } public static void testXKWebAPI() throws Exception { // 实例化 XKWebAPI XKWebAPI XK = new XKWebAPI(); // 查看学期 String[] termInfo = XK.getTermInfo(); for (int i = 0; i < termInfo.length; i++) { System.out.printf("[%d] %s\n", i, termInfo[i]); } // 选择 System.out.print("请选择学期编号: "); int termNo = in.nextInt(); XK.setTerm(termNo); // 登录 if (!login(XK)) return; // 已选课程 ArrayList<String[]> courseTable = XK.getCourseTableArrayList(); output(courseTable, "已选课程"); // 选课排名 ArrayList<String[]> enrollRank = XK.getEnrollRankArrayList(); output(enrollRank, "选课排名"); // 查询所有"0830"课程 ArrayList<String[]> queryCourse = XK.getAllCourseArray("0830"); output(queryCourse, "0830课程"); // 查询选课系统状态 System.out.println("选课状态: " + XK.getEnrollStatus()); // 选课 System.out.println("选课结果: " + XK.enrollCourse("08305013", "1001")); // 退课 System.out.println("退课结果: " + XK.returnCourse("08305013", "1001")); } private static void output(ArrayList<String[]> arrayList, String title) { System.out.println("================================"); System.out.println(title); System.out.println("================================"); for (String[] row : arrayList) { for (String col : row) System.out.print(col + "\t"); System.out.println(); } System.out.printf("-------- Total %d row(s) --------\n", arrayList.size()); } }
false
853
5
992
7
969
5
992
7
1,298
10
false
false
false
false
false
true
55584_3
package com.house.shiro; import com.house.dao.SysUserRoleDao; import com.house.service.RedisService; import com.house.utils.JwtTokenUtil; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** 自定义域 CustomRealm * * Realm即领域,相当于datasource数据源,securityManager进行安全认证需要通过Realm获取用户身份信息及用户权限数据, * 比如:如果用户身份数据在数据库那么realm就需要从数据库获取用户身份信息 */ public class CustomRealm extends AuthorizingRealm { @Autowired private RedisService redisService; @Autowired private SysUserRoleDao sysUserRoleDao; /** * 此方法必须有,不然我们自定义的 CustomUsernamePasswordToken 不生效 * @param token * @return */ @Override public boolean supports(AuthenticationToken token) { return token instanceof CustomUsernamePasswordToken; } /** * 用户授权,设置用户所拥有的 角色/权限 * @param principals * @return * @throws AuthenticationException */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String accessToken = (String) principals.getPrimaryPrincipal(); // 授权器 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); JwtTokenUtil instance = JwtTokenUtil.getInstance(); String userId = instance.getUserId(accessToken); // 判断 redis 中是否缓存有权限信息 //if (redisService.hasKey(Constant.IDENTIFY_CACHE_KEY + userId)){ // redisService.get(Constant.IDENTIFY_CACHE_KEY + userId); //} // 通过用户id获取该用户所拥有的角色名称 List<String> roleNames = sysUserRoleDao.getRoleNameByUserId(userId); if (roleNames != null && !roleNames.isEmpty()){ authorizationInfo.addRoles(roleNames); } // 通过用户id获取该用户所拥有的权限授权 如:sys:user:add List<String> permissionPerms = sysUserRoleDao.getPermissionPermsByUserId(userId); if (permissionPerms != null && !permissionPerms.isEmpty()){ authorizationInfo.addStringPermissions(permissionPerms); } return authorizationInfo; } /** * 用户认证,以前是验证用户名/密码。现在我们验证 token,吧我们的 token 交还给 认证器 * @param token * @return */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 把我们的 token 交还给 认证器 CustomUsernamePasswordToken customUsernamePasswordToken = (CustomUsernamePasswordToken) token; SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(customUsernamePasswordToken.getPrincipal(), customUsernamePasswordToken.getCredentials(), CustomRealm.class.getName()); return info; } }
Logistic98/house-price-monitor
admin/src/main/java/com/house/shiro/CustomRealm.java
767
// 授权器
line_comment
zh-cn
package com.house.shiro; import com.house.dao.SysUserRoleDao; import com.house.service.RedisService; import com.house.utils.JwtTokenUtil; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** 自定义域 CustomRealm * * Realm即领域,相当于datasource数据源,securityManager进行安全认证需要通过Realm获取用户身份信息及用户权限数据, * 比如:如果用户身份数据在数据库那么realm就需要从数据库获取用户身份信息 */ public class CustomRealm extends AuthorizingRealm { @Autowired private RedisService redisService; @Autowired private SysUserRoleDao sysUserRoleDao; /** * 此方法必须有,不然我们自定义的 CustomUsernamePasswordToken 不生效 * @param token * @return */ @Override public boolean supports(AuthenticationToken token) { return token instanceof CustomUsernamePasswordToken; } /** * 用户授权,设置用户所拥有的 角色/权限 * @param principals * @return * @throws AuthenticationException */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String accessToken = (String) principals.getPrimaryPrincipal(); // 授权 <SUF> SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); JwtTokenUtil instance = JwtTokenUtil.getInstance(); String userId = instance.getUserId(accessToken); // 判断 redis 中是否缓存有权限信息 //if (redisService.hasKey(Constant.IDENTIFY_CACHE_KEY + userId)){ // redisService.get(Constant.IDENTIFY_CACHE_KEY + userId); //} // 通过用户id获取该用户所拥有的角色名称 List<String> roleNames = sysUserRoleDao.getRoleNameByUserId(userId); if (roleNames != null && !roleNames.isEmpty()){ authorizationInfo.addRoles(roleNames); } // 通过用户id获取该用户所拥有的权限授权 如:sys:user:add List<String> permissionPerms = sysUserRoleDao.getPermissionPermsByUserId(userId); if (permissionPerms != null && !permissionPerms.isEmpty()){ authorizationInfo.addStringPermissions(permissionPerms); } return authorizationInfo; } /** * 用户认证,以前是验证用户名/密码。现在我们验证 token,吧我们的 token 交还给 认证器 * @param token * @return */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 把我们的 token 交还给 认证器 CustomUsernamePasswordToken customUsernamePasswordToken = (CustomUsernamePasswordToken) token; SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(customUsernamePasswordToken.getPrincipal(), customUsernamePasswordToken.getCredentials(), CustomRealm.class.getName()); return info; } }
false
681
4
767
4
793
4
767
4
1,039
9
false
false
false
false
false
true
19731_29
package coursework.gui; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.KeyEvent; import java.io.*; import java.nio.charset.StandardCharsets; /** * @author Lolipop * @version 1.0.1 * @lastUpdate 2019/11/6 */ public class NoteBook { private JTextArea textArea; private File file = null; private JFrame frame = new JFrame("NoteBook"); private Clipboard clipboard = frame.getToolkit().getSystemClipboard(); private NoteBook() { // Frame frame.setSize(600, 400); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // TextArea textArea = new JTextArea(); textArea.setFont(new Font("黑体", Font.PLAIN, 20)); // ScrollPane JScrollPane pane = new JScrollPane(textArea); frame.add(pane); // Menu // Menu: init menu body JMenuBar menu = new JMenuBar(); frame.setJMenuBar(menu); // Menu: create menus JMenu fileMenu = new JMenu("File(F)"); JMenu editMenu = new JMenu("Edit(E)"); fileMenu.setMnemonic(KeyEvent.VK_F); editMenu.setMnemonic(KeyEvent.VK_E); // Menu: create menu items JMenuItem newItem = new JMenuItem("New(N)", KeyEvent.VK_N); JMenuItem openItem = new JMenuItem("Open(O)", KeyEvent.VK_O); JMenuItem saveItem = new JMenuItem("Save(S)", KeyEvent.VK_S); JMenuItem exitItem = new JMenuItem("Exit(X)", KeyEvent.VK_X); JMenuItem cutItem = new JMenuItem("Cut(T)", KeyEvent.VK_T); JMenuItem copyItem = new JMenuItem("Copy(C)", KeyEvent.VK_C); JMenuItem pasteItem = new JMenuItem("Paste(P)", KeyEvent.VK_P); // fileMenu: set events // 新建NoteBook窗口 newItem.addActionListener(e -> new NoteBook()); // 打开文件 openItem.addActionListener(e -> { JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showOpenDialog(openItem) == JFileChooser.APPROVE_OPTION) { File aimFile = fileChooser.getSelectedFile(); // 打开新窗口并读取文件 NoteBook newNoteBook = new NoteBook(); readFile(aimFile, newNoteBook.textArea); } }); // 保存文件 saveItem.addActionListener(e -> { // 文件存在时(已经保存过) if (file != null) { saveFile(file.getPath()); } // 文件不存在时(初次保存) else { JFileChooser fileChooser = new JFileChooser(); // 后缀名过滤 String extension = ".txt"; fileChooser.setFileFilter(new FileNameExtensionFilter("文本文件(*.txt)", extension)); if (fileChooser.showSaveDialog(saveItem) == JFileChooser.APPROVE_OPTION) { File newFile = fileChooser.getSelectedFile(); // 获取用户输入的文件名 String fName = fileChooser.getName(newFile); // 若文件名不包含".txt"后缀则在最后加上".txt" if (!fName.contains(extension)) { newFile = new File(fileChooser.getCurrentDirectory(), fName+".txt"); } // 保存文件 saveFile(newFile.getPath()); // 修改全局变量file file = newFile; // 修改窗口title frame.setTitle(file.getName()+" - NoteBook"); } } }); // 退出NoteBook exitItem.addActionListener(e -> { int choice = JOptionPane.showConfirmDialog(null, "Confirm exit NoteBook?", "Exit", JOptionPane.YES_NO_OPTION); if (choice == 0) { frame.dispose(); } }); // editMenu: set events // 剪切 cutItem.addActionListener(e -> { // 将选中的文本内容传递给剪切板 StringSelection cutText = new StringSelection(textArea.getSelectedText()); clipboard.setContents(cutText, null); // 删除选中文本 int start = textArea.getSelectionStart(); int end = textArea.getSelectionEnd(); textArea.replaceRange("", start, end); }); // 复制 copyItem.addActionListener(e -> { StringSelection copyText = new StringSelection(textArea.getSelectedText()); clipboard.setContents(copyText, null); }); // 粘贴 pasteItem.addActionListener(e -> { // 从剪切板获取内容保存到contents中 Transferable contents = clipboard.getContents(null); // 设置DataFlavor映射剪切板String型数据 DataFlavor flavor = DataFlavor.stringFlavor; // 若存在String型数据,则将数据粘贴到光标选中处 if (contents.isDataFlavorSupported(flavor)) { try { // 将contents数据转化成String格式保存到text中 String text = (String)contents.getTransferData(flavor); // 替换选中内容 int start = textArea.getSelectionStart(); int end = textArea.getSelectionEnd(); textArea.replaceRange(text, start, end); } catch (UnsupportedFlavorException | IOException ex) { ex.printStackTrace(); } } }); // Menu: add items to menus fileMenu.add(newItem); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(exitItem); editMenu.add(cutItem); editMenu.add(copyItem); editMenu.add(pasteItem); // Menu: add menus to menu body & set visible menu.add(fileMenu); menu.add(editMenu); menu.setVisible(true); // 设置界面可见 frame.setVisible(true); } /** * 读取文件并在新的窗口显示出来 * @param file 选择欲打开的文件 * @param textArea 新建窗口的textArea */ private void readFile (File file, JTextArea textArea) { // init StringBuilder StringBuilder sBuilder = new StringBuilder(); try { // init BufferedReader & str // 指定GB2312编码以显示文件的中文字符 BufferedReader bReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GB2312")); String str; // BufferedReader所读取数据不为空行时,把str存储的行内容传递给StringBuilder while ((str = bReader.readLine()) != null) { sBuilder.append(str).append('\n'); } // 将StringBuilder存储的数据显示在textArea上 textArea.setText(sBuilder.toString()); } catch (IOException e) { e.printStackTrace(); } } /** * 将输入的内容保存为文本文件 * @param path 文件存储的路径 */ private void saveFile (String path) { FileOutputStream os; try { // init FileOutputStream os = new FileOutputStream(path); // 将textArea域的内容转化为UTF_8编码格式的文本字符对象,并写入对应路径下的文件中 os.write(textArea.getText().getBytes(StandardCharsets.UTF_8)); os.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main (String[] args) { new NoteBook(); } }
LolipopJ/uestc-coursework-repo
java-Coursework/gui/NoteBook.java
1,717
// 替换选中内容
line_comment
zh-cn
package coursework.gui; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.KeyEvent; import java.io.*; import java.nio.charset.StandardCharsets; /** * @author Lolipop * @version 1.0.1 * @lastUpdate 2019/11/6 */ public class NoteBook { private JTextArea textArea; private File file = null; private JFrame frame = new JFrame("NoteBook"); private Clipboard clipboard = frame.getToolkit().getSystemClipboard(); private NoteBook() { // Frame frame.setSize(600, 400); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // TextArea textArea = new JTextArea(); textArea.setFont(new Font("黑体", Font.PLAIN, 20)); // ScrollPane JScrollPane pane = new JScrollPane(textArea); frame.add(pane); // Menu // Menu: init menu body JMenuBar menu = new JMenuBar(); frame.setJMenuBar(menu); // Menu: create menus JMenu fileMenu = new JMenu("File(F)"); JMenu editMenu = new JMenu("Edit(E)"); fileMenu.setMnemonic(KeyEvent.VK_F); editMenu.setMnemonic(KeyEvent.VK_E); // Menu: create menu items JMenuItem newItem = new JMenuItem("New(N)", KeyEvent.VK_N); JMenuItem openItem = new JMenuItem("Open(O)", KeyEvent.VK_O); JMenuItem saveItem = new JMenuItem("Save(S)", KeyEvent.VK_S); JMenuItem exitItem = new JMenuItem("Exit(X)", KeyEvent.VK_X); JMenuItem cutItem = new JMenuItem("Cut(T)", KeyEvent.VK_T); JMenuItem copyItem = new JMenuItem("Copy(C)", KeyEvent.VK_C); JMenuItem pasteItem = new JMenuItem("Paste(P)", KeyEvent.VK_P); // fileMenu: set events // 新建NoteBook窗口 newItem.addActionListener(e -> new NoteBook()); // 打开文件 openItem.addActionListener(e -> { JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showOpenDialog(openItem) == JFileChooser.APPROVE_OPTION) { File aimFile = fileChooser.getSelectedFile(); // 打开新窗口并读取文件 NoteBook newNoteBook = new NoteBook(); readFile(aimFile, newNoteBook.textArea); } }); // 保存文件 saveItem.addActionListener(e -> { // 文件存在时(已经保存过) if (file != null) { saveFile(file.getPath()); } // 文件不存在时(初次保存) else { JFileChooser fileChooser = new JFileChooser(); // 后缀名过滤 String extension = ".txt"; fileChooser.setFileFilter(new FileNameExtensionFilter("文本文件(*.txt)", extension)); if (fileChooser.showSaveDialog(saveItem) == JFileChooser.APPROVE_OPTION) { File newFile = fileChooser.getSelectedFile(); // 获取用户输入的文件名 String fName = fileChooser.getName(newFile); // 若文件名不包含".txt"后缀则在最后加上".txt" if (!fName.contains(extension)) { newFile = new File(fileChooser.getCurrentDirectory(), fName+".txt"); } // 保存文件 saveFile(newFile.getPath()); // 修改全局变量file file = newFile; // 修改窗口title frame.setTitle(file.getName()+" - NoteBook"); } } }); // 退出NoteBook exitItem.addActionListener(e -> { int choice = JOptionPane.showConfirmDialog(null, "Confirm exit NoteBook?", "Exit", JOptionPane.YES_NO_OPTION); if (choice == 0) { frame.dispose(); } }); // editMenu: set events // 剪切 cutItem.addActionListener(e -> { // 将选中的文本内容传递给剪切板 StringSelection cutText = new StringSelection(textArea.getSelectedText()); clipboard.setContents(cutText, null); // 删除选中文本 int start = textArea.getSelectionStart(); int end = textArea.getSelectionEnd(); textArea.replaceRange("", start, end); }); // 复制 copyItem.addActionListener(e -> { StringSelection copyText = new StringSelection(textArea.getSelectedText()); clipboard.setContents(copyText, null); }); // 粘贴 pasteItem.addActionListener(e -> { // 从剪切板获取内容保存到contents中 Transferable contents = clipboard.getContents(null); // 设置DataFlavor映射剪切板String型数据 DataFlavor flavor = DataFlavor.stringFlavor; // 若存在String型数据,则将数据粘贴到光标选中处 if (contents.isDataFlavorSupported(flavor)) { try { // 将contents数据转化成String格式保存到text中 String text = (String)contents.getTransferData(flavor); // 替换 <SUF> int start = textArea.getSelectionStart(); int end = textArea.getSelectionEnd(); textArea.replaceRange(text, start, end); } catch (UnsupportedFlavorException | IOException ex) { ex.printStackTrace(); } } }); // Menu: add items to menus fileMenu.add(newItem); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(exitItem); editMenu.add(cutItem); editMenu.add(copyItem); editMenu.add(pasteItem); // Menu: add menus to menu body & set visible menu.add(fileMenu); menu.add(editMenu); menu.setVisible(true); // 设置界面可见 frame.setVisible(true); } /** * 读取文件并在新的窗口显示出来 * @param file 选择欲打开的文件 * @param textArea 新建窗口的textArea */ private void readFile (File file, JTextArea textArea) { // init StringBuilder StringBuilder sBuilder = new StringBuilder(); try { // init BufferedReader & str // 指定GB2312编码以显示文件的中文字符 BufferedReader bReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GB2312")); String str; // BufferedReader所读取数据不为空行时,把str存储的行内容传递给StringBuilder while ((str = bReader.readLine()) != null) { sBuilder.append(str).append('\n'); } // 将StringBuilder存储的数据显示在textArea上 textArea.setText(sBuilder.toString()); } catch (IOException e) { e.printStackTrace(); } } /** * 将输入的内容保存为文本文件 * @param path 文件存储的路径 */ private void saveFile (String path) { FileOutputStream os; try { // init FileOutputStream os = new FileOutputStream(path); // 将textArea域的内容转化为UTF_8编码格式的文本字符对象,并写入对应路径下的文件中 os.write(textArea.getText().getBytes(StandardCharsets.UTF_8)); os.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main (String[] args) { new NoteBook(); } }
false
1,579
7
1,717
7
1,825
5
1,717
7
2,321
10
false
false
false
false
false
true
61368_2
package com.smallfatcat.thread.thread3; /** * @author zsz * @Description * @date 2022/9/2 */ public class Culprit { public synchronized void say(Police p){ //加锁方法 System.out.println("罪犯:你放了我,我就放了人质"); p.fun(); //调用警察方法 } public synchronized void fun(){ //加锁方法 System.out.println("我放了人质,警察也放了我"); } }
LongTimeNC/Thread
src/main/java/com/smallfatcat/thread/thread3/Culprit.java
137
//调用警察方法
line_comment
zh-cn
package com.smallfatcat.thread.thread3; /** * @author zsz * @Description * @date 2022/9/2 */ public class Culprit { public synchronized void say(Police p){ //加锁方法 System.out.println("罪犯:你放了我,我就放了人质"); p.fun(); //调用 <SUF> } public synchronized void fun(){ //加锁方法 System.out.println("我放了人质,警察也放了我"); } }
false
119
5
137
5
132
4
137
5
168
11
false
false
false
false
false
true
62363_7
package cn.lyl.entity; import java.util.HashSet; import java.util.Set; public class KeShi { private Integer KSBH;//课室编号 private String KSMC;//课室名称 private Integer KSHS;//课室行数 private Integer KSLS;//课室列数 private Integer KSGDS;//课室过道数 private Integer KSZS;//课室最适人数 private String KSGDL;//课室过道所在列,中间用##分开 private String KSKZ1;//扩展字段1 private Integer KSKZ2;//扩展字段2 private Integer KSKZ3;//扩展字段3 private Integer KSKZ4;//扩展字段4 private String KSKZ5;//扩展字段5 //在课室里面表示所属楼栋,一个课室只能属于一个楼栋 private LouDong loudong;// //在课室里面表示所拥有的课室,一个课室可以拥有多个座位 private Set<ZuoWei> setzuowei = new HashSet<ZuoWei>(); public Integer getKSBH() { return KSBH; } public void setKSBH(Integer kSBH) { KSBH = kSBH; } public String getKSMC() { return KSMC; } public void setKSMC(String kSMC) { KSMC = kSMC; } public Integer getKSHS() { return KSHS; } public void setKSHS(Integer kSHS) { KSHS = kSHS; } public Integer getKSLS() { return KSLS; } public void setKSLS(Integer kSLS) { KSLS = kSLS; } public Integer getKSGDS() { return KSGDS; } public void setKSGDS(Integer kSGDS) { KSGDS = kSGDS; } public Integer getKSZS() { return KSZS; } public void setKSZS(Integer kSZS) { KSZS = kSZS; } public String getKSGDL() { return KSGDL; } public void setKSGDL(String kSGDL) { KSGDL = kSGDL; } public String getKSKZ1() { return KSKZ1; } public void setKSKZ1(String kSKZ1) { KSKZ1 = kSKZ1; } public Integer getKSKZ2() { return KSKZ2; } public void setKSKZ2(Integer kSKZ2) { KSKZ2 = kSKZ2; } public Integer getKSKZ3() { return KSKZ3; } public void setKSKZ3(Integer kSKZ3) { KSKZ3 = kSKZ3; } public Integer getKSKZ4() { return KSKZ4; } public void setKSKZ4(Integer kSKZ4) { KSKZ4 = kSKZ4; } public String getKSKZ5() { return KSKZ5; } public void setKSKZ5(String kSKZ5) { KSKZ5 = kSKZ5; } public LouDong getLoudong() { return loudong; } public void setLoudong(LouDong loudong) { this.loudong = loudong; } public Set<ZuoWei> getSetzuowei() { return setzuowei; } public void setSetzuowei(Set<ZuoWei> setzuowei) { this.setzuowei = setzuowei; } }
LongYil/SeatArrangement
src/main/java/cn/lyl/entity/KeShi.java
986
//扩展字段1
line_comment
zh-cn
package cn.lyl.entity; import java.util.HashSet; import java.util.Set; public class KeShi { private Integer KSBH;//课室编号 private String KSMC;//课室名称 private Integer KSHS;//课室行数 private Integer KSLS;//课室列数 private Integer KSGDS;//课室过道数 private Integer KSZS;//课室最适人数 private String KSGDL;//课室过道所在列,中间用##分开 private String KSKZ1;//扩展 <SUF> private Integer KSKZ2;//扩展字段2 private Integer KSKZ3;//扩展字段3 private Integer KSKZ4;//扩展字段4 private String KSKZ5;//扩展字段5 //在课室里面表示所属楼栋,一个课室只能属于一个楼栋 private LouDong loudong;// //在课室里面表示所拥有的课室,一个课室可以拥有多个座位 private Set<ZuoWei> setzuowei = new HashSet<ZuoWei>(); public Integer getKSBH() { return KSBH; } public void setKSBH(Integer kSBH) { KSBH = kSBH; } public String getKSMC() { return KSMC; } public void setKSMC(String kSMC) { KSMC = kSMC; } public Integer getKSHS() { return KSHS; } public void setKSHS(Integer kSHS) { KSHS = kSHS; } public Integer getKSLS() { return KSLS; } public void setKSLS(Integer kSLS) { KSLS = kSLS; } public Integer getKSGDS() { return KSGDS; } public void setKSGDS(Integer kSGDS) { KSGDS = kSGDS; } public Integer getKSZS() { return KSZS; } public void setKSZS(Integer kSZS) { KSZS = kSZS; } public String getKSGDL() { return KSGDL; } public void setKSGDL(String kSGDL) { KSGDL = kSGDL; } public String getKSKZ1() { return KSKZ1; } public void setKSKZ1(String kSKZ1) { KSKZ1 = kSKZ1; } public Integer getKSKZ2() { return KSKZ2; } public void setKSKZ2(Integer kSKZ2) { KSKZ2 = kSKZ2; } public Integer getKSKZ3() { return KSKZ3; } public void setKSKZ3(Integer kSKZ3) { KSKZ3 = kSKZ3; } public Integer getKSKZ4() { return KSKZ4; } public void setKSKZ4(Integer kSKZ4) { KSKZ4 = kSKZ4; } public String getKSKZ5() { return KSKZ5; } public void setKSKZ5(String kSKZ5) { KSKZ5 = kSKZ5; } public LouDong getLoudong() { return loudong; } public void setLoudong(LouDong loudong) { this.loudong = loudong; } public Set<ZuoWei> getSetzuowei() { return setzuowei; } public void setSetzuowei(Set<ZuoWei> setzuowei) { this.setzuowei = setzuowei; } }
false
822
4
986
4
934
4
986
4
1,134
8
false
false
false
false
false
true
21900_2
package model; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Iterator; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.spi.DirStateFactory.Result; import utilitiy.MyBase64; public class Mail { String subject = ""; String from = ""; Vector<String> to_list = new Vector<String>(); String content = ""; public Mail(String subject, String from, Vector<String> to_list, String content) { super(); this.subject = subject; this.from = from; this.to_list = to_list; this.content = content; } public Mail(Vector<String> lines) { super(); initByLines(lines); } private void initByLines(Vector<String> lines) { //决定当前行是否解码 boolean decodeWithBase64 = false; //排除前一行的干扰 boolean isPreLine = false; //是否已经收集完内容 不要html boolean hasContent = false; for (int i = 0; i < lines.size(); i++) { String buf = lines.get(i); isPreLine = false; if (buf.startsWith("Return-Path:")) { String regex = "<(.*)>"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(buf); boolean cont = true; while (m.find()) { // System.out.println(m.group(1)); if (cont) { to_list = new Vector<>(); to_list.addElement(m.group(1)); cont = false; } } }else if (buf.startsWith("Subject:")) { boolean isUTF8 = false; String regex = "=\\?(?i)UTF-8\\?B\\?(.*)\\?="; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(buf); while (m.find()) { isUTF8 = true; subject = MyBase64.getFromBASE64(m.group(1)); } if(!isUTF8) subject = buf.substring(8); }else if (buf.startsWith("From:")) { from = buf.substring(5); }else if (buf.endsWith("base64")) { if(!hasContent){ decodeWithBase64 = true; isPreLine = true; } hasContent = true; }else if (buf.startsWith("--")) { decodeWithBase64 = false; } if (decodeWithBase64 && !isPreLine) { content += MyBase64.getFromBASE64(buf); } } } public String getDataString() { String to = ""; for (int i = 0; i < to_list.size(); i++) { to += to_list.get(i) + ";"; } String result = "From:" + from + "\r\n" + "To:" + to + "\r\n" + "Subject:" + subject + "\r\n" + content + "\r\n"; return result; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public Vector<String> getTo_list() { return to_list; } public void setTo_list(Vector<String> to_list) { this.to_list = to_list; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { String to = ""; for (int i = 0; i < to_list.size(); i++) { to+= to_list.get(i)+";"; } return "主题:"+subject+"\r\n"+ "来自:"+from+"\r\n"+ "回复:"+to+"\r\n"+ "正文:"+content; } }
LoranWong/SimpleEmailClient
src/model/Mail.java
1,112
//是否已经收集完内容 不要html
line_comment
zh-cn
package model; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Iterator; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.spi.DirStateFactory.Result; import utilitiy.MyBase64; public class Mail { String subject = ""; String from = ""; Vector<String> to_list = new Vector<String>(); String content = ""; public Mail(String subject, String from, Vector<String> to_list, String content) { super(); this.subject = subject; this.from = from; this.to_list = to_list; this.content = content; } public Mail(Vector<String> lines) { super(); initByLines(lines); } private void initByLines(Vector<String> lines) { //决定当前行是否解码 boolean decodeWithBase64 = false; //排除前一行的干扰 boolean isPreLine = false; //是否 <SUF> boolean hasContent = false; for (int i = 0; i < lines.size(); i++) { String buf = lines.get(i); isPreLine = false; if (buf.startsWith("Return-Path:")) { String regex = "<(.*)>"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(buf); boolean cont = true; while (m.find()) { // System.out.println(m.group(1)); if (cont) { to_list = new Vector<>(); to_list.addElement(m.group(1)); cont = false; } } }else if (buf.startsWith("Subject:")) { boolean isUTF8 = false; String regex = "=\\?(?i)UTF-8\\?B\\?(.*)\\?="; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(buf); while (m.find()) { isUTF8 = true; subject = MyBase64.getFromBASE64(m.group(1)); } if(!isUTF8) subject = buf.substring(8); }else if (buf.startsWith("From:")) { from = buf.substring(5); }else if (buf.endsWith("base64")) { if(!hasContent){ decodeWithBase64 = true; isPreLine = true; } hasContent = true; }else if (buf.startsWith("--")) { decodeWithBase64 = false; } if (decodeWithBase64 && !isPreLine) { content += MyBase64.getFromBASE64(buf); } } } public String getDataString() { String to = ""; for (int i = 0; i < to_list.size(); i++) { to += to_list.get(i) + ";"; } String result = "From:" + from + "\r\n" + "To:" + to + "\r\n" + "Subject:" + subject + "\r\n" + content + "\r\n"; return result; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public Vector<String> getTo_list() { return to_list; } public void setTo_list(Vector<String> to_list) { this.to_list = to_list; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { String to = ""; for (int i = 0; i < to_list.size(); i++) { to+= to_list.get(i)+";"; } return "主题:"+subject+"\r\n"+ "来自:"+from+"\r\n"+ "回复:"+to+"\r\n"+ "正文:"+content; } }
false
885
10
1,112
10
1,102
9
1,112
10
1,358
14
false
false
false
false
false
true
42531_0
package file; import javabase.lorenwang.tools.file.JtlwFileOptionUtil; /** * 功能作用:清除指定目录空文件夹目录 * 初始注释时间: 2022/2/7 10:34 * 创建人:王亮(Loren) * 思路: * 方法: * 注意: * 修改人: * 修改时间: * 备注: * * @author 王亮(Loren) */ public class ClearEmptyFileDir { public static void main(String[] args) { JtlwFileOptionUtil.getInstance().clearEmptyFileDir("/Volumes/DataStorege/私人/备份文件/手机备份", (filePath, status) -> System.out.println("清除文件夹:" + filePath + ",清除状态:" + status)); } }
Loren-Wang/LorenWangCustomTools
JavaPcToolsFromLorenWang/src/file/ClearEmptyFileDir.java
206
/** * 功能作用:清除指定目录空文件夹目录 * 初始注释时间: 2022/2/7 10:34 * 创建人:王亮(Loren) * 思路: * 方法: * 注意: * 修改人: * 修改时间: * 备注: * * @author 王亮(Loren) */
block_comment
zh-cn
package file; import javabase.lorenwang.tools.file.JtlwFileOptionUtil; /** * 功能作 <SUF>*/ public class ClearEmptyFileDir { public static void main(String[] args) { JtlwFileOptionUtil.getInstance().clearEmptyFileDir("/Volumes/DataStorege/私人/备份文件/手机备份", (filePath, status) -> System.out.println("清除文件夹:" + filePath + ",清除状态:" + status)); } }
false
176
84
206
95
191
85
206
95
262
123
false
false
false
false
false
true
5064_11
package com.book.manager.util.consts; /** * 常量 */ public final class Constants { /** 用户可解数量不足 */ public static final int USER_SIZE_NOT_ENOUGH = -101; /** 图书库存数量不足 */ public static final int BOOK_SIZE_NOT_ENOUGH = -102; /** 用户已借过该图书 */ public static final int BOOK_BORROWED = -201; /** 是 */ public static final int YES = 0; /** 否 */ public static final int NO = 1; /** 一切正常 */ public static final int OK = 1; /** 是 */ public static final String YES_STR = "是"; /** 否 */ public static final String NO_STR = "否"; /** 日期格式 */ public static final String DATE_FORMAT = "yyyy-MM-dd"; /** 学生 */ public static final int STUDENT = 0; /** 教师 */ public static final int TEACHER = 1; /** 其他 */ public static final int OTHER = 2; /** 管理员 */ public static final int ADMIN = 3; /** 身份 */ public static final String STU_STR = "学生"; public static final String TEA_STR = "教师"; public static final String OTHER_STR = "社会人士"; public static final String ADMIN_STR = "管理员"; }
LovebuildJ/book-manager
src/main/java/com/book/manager/util/consts/Constants.java
348
/** 教师 */
block_comment
zh-cn
package com.book.manager.util.consts; /** * 常量 */ public final class Constants { /** 用户可解数量不足 */ public static final int USER_SIZE_NOT_ENOUGH = -101; /** 图书库存数量不足 */ public static final int BOOK_SIZE_NOT_ENOUGH = -102; /** 用户已借过该图书 */ public static final int BOOK_BORROWED = -201; /** 是 */ public static final int YES = 0; /** 否 */ public static final int NO = 1; /** 一切正常 */ public static final int OK = 1; /** 是 */ public static final String YES_STR = "是"; /** 否 */ public static final String NO_STR = "否"; /** 日期格式 */ public static final String DATE_FORMAT = "yyyy-MM-dd"; /** 学生 */ public static final int STUDENT = 0; /** 教师 <SUF>*/ public static final int TEACHER = 1; /** 其他 */ public static final int OTHER = 2; /** 管理员 */ public static final int ADMIN = 3; /** 身份 */ public static final String STU_STR = "学生"; public static final String TEA_STR = "教师"; public static final String OTHER_STR = "社会人士"; public static final String ADMIN_STR = "管理员"; }
false
315
5
348
5
354
4
348
5
419
7
false
false
false
false
false
true
43786_1
package com.chenxin.util.consts; /** * @Description 词义分析常量类 * @Date 2020/9/18 16:03 * @Author by 尘心 */ public class LexerConstants { /** * <p> * 词性缩略说明 * n 普通名词 f 方位名词 s 处所名词 t 时间名词 nr 人名 ns 地名 nt 机构团体名 nw 作品名 nz 其他专名 v 普通动词 vd 动副词 vn 名动词 a 形容词 ad 副形词 an 名形词 d 副词 m 数量词 q 量词 r 代词 p 介词 c 连词 u 助词 xc 其他虚词 * </p> */ public static final String N = "n"; public static final String NT = "nt"; public static final String A = "a"; public static final String AD = "ad"; public static final String V = "v"; public static final String VD = "vd"; public static final String VN = "vn"; }
LovebuildJ/language-ai
src/main/java/com/chenxin/util/consts/LexerConstants.java
296
/** * <p> * 词性缩略说明 * n 普通名词 f 方位名词 s 处所名词 t 时间名词 nr 人名 ns 地名 nt 机构团体名 nw 作品名 nz 其他专名 v 普通动词 vd 动副词 vn 名动词 a 形容词 ad 副形词 an 名形词 d 副词 m 数量词 q 量词 r 代词 p 介词 c 连词 u 助词 xc 其他虚词 * </p> */
block_comment
zh-cn
package com.chenxin.util.consts; /** * @Description 词义分析常量类 * @Date 2020/9/18 16:03 * @Author by 尘心 */ public class LexerConstants { /** * <p> <SUF>*/ public static final String N = "n"; public static final String NT = "nt"; public static final String A = "a"; public static final String AD = "ad"; public static final String V = "v"; public static final String VD = "vd"; public static final String VN = "vn"; }
false
271
143
296
157
301
161
296
157
389
232
false
false
false
false
false
true
61683_4
package Model; public class SchoolInformation { String schoolid; String name; String sex; String birthday; String people; String zzmm;//政治面貌 String IdCard;//身份证 String xjzt;//学籍状态 String xy;//学院 String grade;//年级 String major;//专业 String clas;//班级 String majorid;//专业代码 String examid;//考生号 public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getSchoolid() { return schoolid; } public void setSchoolid(String schoolid) { this.schoolid = schoolid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getPeople() { return people; } public void setPeople(String people) { this.people = people; } public String getZzmm() { return zzmm; } public void setZzmm(String zzmm) { this.zzmm = zzmm; } public String getIdCard() { return IdCard; } public void setIdCard(String idCard) { IdCard = idCard; } public String getXjzt() { return xjzt; } public void setXjzt(String xjzt) { this.xjzt = xjzt; } public String getXy() { return xy; } public void setXy(String xy) { this.xy = xy; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getClas() { return clas; } public void setClas(String clas) { this.clas = clas; } public String getMajorid() { return majorid; } public void setMajorid(String majorid) { this.majorid = majorid; } public String getExamid() { return examid; } public void setExamid(String examid) { this.examid = examid; } }
LovelyWhite/AttendanceSystem
后端/src/Model/SchoolInformation.java
591
//考生号
line_comment
zh-cn
package Model; public class SchoolInformation { String schoolid; String name; String sex; String birthday; String people; String zzmm;//政治面貌 String IdCard;//身份证 String xjzt;//学籍状态 String xy;//学院 String grade;//年级 String major;//专业 String clas;//班级 String majorid;//专业代码 String examid;//考生 <SUF> public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getSchoolid() { return schoolid; } public void setSchoolid(String schoolid) { this.schoolid = schoolid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getPeople() { return people; } public void setPeople(String people) { this.people = people; } public String getZzmm() { return zzmm; } public void setZzmm(String zzmm) { this.zzmm = zzmm; } public String getIdCard() { return IdCard; } public void setIdCard(String idCard) { IdCard = idCard; } public String getXjzt() { return xjzt; } public void setXjzt(String xjzt) { this.xjzt = xjzt; } public String getXy() { return xy; } public void setXy(String xy) { this.xy = xy; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getClas() { return clas; } public void setClas(String clas) { this.clas = clas; } public String getMajorid() { return majorid; } public void setMajorid(String majorid) { this.majorid = majorid; } public String getExamid() { return examid; } public void setExamid(String examid) { this.examid = examid; } }
false
558
3
591
4
674
3
591
4
785
6
false
false
false
false
false
true
17518_8
package com.zh.pojo; public class Question { /**问题编号*/ private Integer questionId; /**问题名称*/ private String quesName; /**选项A*/ private String optionA; /**选项B*/ private String optionB; /**选项C*/ private String optionC; /**选项D*/ private String optionD; /**标准答案*/ private String answer; /**学生答案*/ private String userAnswer; /**对应课程*/ private Integer courseId; /**题型*/ private Integer typeId; /**难度(0:容易,1:中等,2:难)*/ private int difficulty; /**备注*/ private String remark; private String answerDetail; private String gradeId; private String testPointId; private Course course; private Type type; //记录错误的次数 private Integer wrongCount; //记录该题目被选上的次数 private Integer selectedCount; public Integer getWrongCount() { return wrongCount; } public void setWrongCount(Integer wrongCount) { this.wrongCount = wrongCount; } public Integer getSelectedCount() { return selectedCount; } public void setSelectedCount(Integer selectedCount) { this.selectedCount = selectedCount; } public String getTestPointId() { return testPointId; } public void setTestPointId(String testPointId) { this.testPointId = testPointId; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Integer getCourseId() { return courseId; } public void setCourseId(Integer courseId) { this.courseId = courseId; } public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } public String getQuesName() { return quesName; } public Integer getQuestionId() { return questionId; } public void setQuestionId(Integer questionId) { this.questionId = questionId; } public void setQuesName(String quesName) { this.quesName = quesName; } public String getOptionA() { return optionA; } public void setOptionA(String optionA) { this.optionA = optionA; } public String getOptionB() { return optionB; } public void setOptionB(String optionB) { this.optionB = optionB; } public String getOptionC() { return optionC; } public void setOptionC(String optionC) { this.optionC = optionC; } public String getOptionD() { return optionD; } public void setOptionD(String optionD) { this.optionD = optionD; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getUserAnswer() { return userAnswer; } public void setUserAnswer(String userAnswer) { this.userAnswer = userAnswer; } public int getDifficulty() { return difficulty; } public void setDifficulty(int difficulty) { this.difficulty = difficulty; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getAnswerDetail() { return answerDetail; } public void setAnswerDetail(String answerDetail) { this.answerDetail = answerDetail; } public String getGradeId() { return gradeId; } public void setGradeId(String gradeId) { this.gradeId = gradeId; } public Question() { } public Question(int questionId, String quesName, String optionA, String optionB, String optionC, String optionD, String answer, String userAnswer, Integer courseId, Integer typeId, int difficulty, String remark, String answerDetail, String gradeId) { super(); this.questionId = questionId; this.quesName = quesName; this.optionA = optionA; this.optionB = optionB; this.optionC = optionC; this.optionD = optionD; this.answer = answer; this.userAnswer = userAnswer; this.courseId = courseId; this.typeId = typeId; this.difficulty = difficulty; this.remark = remark; this.answerDetail = answerDetail; this.gradeId = gradeId; } @Override public String toString() { return "Question [questionId=" + questionId + ", quesName=" + quesName + ", optionA=" + optionA + ", optionB=" + optionB + ", optionC=" + optionC + ", optionD=" + optionD + ", answer=" + answer + ", userAnswer=" + userAnswer + ", courseId=" + courseId + ", typeId=" + typeId + ", difficulty=" + difficulty + ", remark=" + remark + ", answerDetail=" + answerDetail + ", gradeId=" + gradeId + "]"; } }
Lovelylys/examOnline
src/main/java/com/zh/pojo/Question.java
1,420
/**对应课程*/
block_comment
zh-cn
package com.zh.pojo; public class Question { /**问题编号*/ private Integer questionId; /**问题名称*/ private String quesName; /**选项A*/ private String optionA; /**选项B*/ private String optionB; /**选项C*/ private String optionC; /**选项D*/ private String optionD; /**标准答案*/ private String answer; /**学生答案*/ private String userAnswer; /**对应课 <SUF>*/ private Integer courseId; /**题型*/ private Integer typeId; /**难度(0:容易,1:中等,2:难)*/ private int difficulty; /**备注*/ private String remark; private String answerDetail; private String gradeId; private String testPointId; private Course course; private Type type; //记录错误的次数 private Integer wrongCount; //记录该题目被选上的次数 private Integer selectedCount; public Integer getWrongCount() { return wrongCount; } public void setWrongCount(Integer wrongCount) { this.wrongCount = wrongCount; } public Integer getSelectedCount() { return selectedCount; } public void setSelectedCount(Integer selectedCount) { this.selectedCount = selectedCount; } public String getTestPointId() { return testPointId; } public void setTestPointId(String testPointId) { this.testPointId = testPointId; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Integer getCourseId() { return courseId; } public void setCourseId(Integer courseId) { this.courseId = courseId; } public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } public String getQuesName() { return quesName; } public Integer getQuestionId() { return questionId; } public void setQuestionId(Integer questionId) { this.questionId = questionId; } public void setQuesName(String quesName) { this.quesName = quesName; } public String getOptionA() { return optionA; } public void setOptionA(String optionA) { this.optionA = optionA; } public String getOptionB() { return optionB; } public void setOptionB(String optionB) { this.optionB = optionB; } public String getOptionC() { return optionC; } public void setOptionC(String optionC) { this.optionC = optionC; } public String getOptionD() { return optionD; } public void setOptionD(String optionD) { this.optionD = optionD; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getUserAnswer() { return userAnswer; } public void setUserAnswer(String userAnswer) { this.userAnswer = userAnswer; } public int getDifficulty() { return difficulty; } public void setDifficulty(int difficulty) { this.difficulty = difficulty; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getAnswerDetail() { return answerDetail; } public void setAnswerDetail(String answerDetail) { this.answerDetail = answerDetail; } public String getGradeId() { return gradeId; } public void setGradeId(String gradeId) { this.gradeId = gradeId; } public Question() { } public Question(int questionId, String quesName, String optionA, String optionB, String optionC, String optionD, String answer, String userAnswer, Integer courseId, Integer typeId, int difficulty, String remark, String answerDetail, String gradeId) { super(); this.questionId = questionId; this.quesName = quesName; this.optionA = optionA; this.optionB = optionB; this.optionC = optionC; this.optionD = optionD; this.answer = answer; this.userAnswer = userAnswer; this.courseId = courseId; this.typeId = typeId; this.difficulty = difficulty; this.remark = remark; this.answerDetail = answerDetail; this.gradeId = gradeId; } @Override public String toString() { return "Question [questionId=" + questionId + ", quesName=" + quesName + ", optionA=" + optionA + ", optionB=" + optionB + ", optionC=" + optionC + ", optionD=" + optionD + ", answer=" + answer + ", userAnswer=" + userAnswer + ", courseId=" + courseId + ", typeId=" + typeId + ", difficulty=" + difficulty + ", remark=" + remark + ", answerDetail=" + answerDetail + ", gradeId=" + gradeId + "]"; } }
false
1,111
4
1,420
4
1,391
4
1,420
4
1,595
8
false
false
false
false
false
true
29991_2
package xyz.lovemma.zhihudaily.bean; import xyz.lovemma.zhihudaily.utils.DateUtils; /** * Created by OO on 2017/2/24. */ public class StoryContentComment implements BaseItem{ /** * author : 少先大队委员长 * content : “中国三四线城市现在拥有苹果手机的人数量不在少数”作者这句话的前提是一二线城市现在拥有苹果手机的人非常多。你可能是听多了国内各大厂商对自家手机的宣传所以才会产生苹果越来越差,国产机完全秒杀的错觉。另外就硬件来讲安卓在屏幕,像素,cpu,ram等方面上多年来一直是强过苹果的,但是体验上却很少能有与苹果比肩的,系统的流畅度不是单纯的硬件堆砌能实现的。至于安卓超越ios这个就太夸张了,只能说各有优劣,适合自己的才是最好的,另外安卓与ios多年来也是互相借鉴,谈不上抄袭,毕竟用户需求摆在那里,大家共同进步更好,再考虑到国内对谷歌的阉割所以就国内的体验来讲我觉得安卓还是远远落后于ios的,至于各家的UI也是双刃剑的,符合了国人的使用习惯但是广告太多之类的小问题也是不少。“独创性,改革意义”这种事不是短短几年内就会多次出现的就像汽车发明这么多年了不还是依然四个轱辘么,也没见它上天也没见它下海,要有耐心。以上是我的个人意见 * avatar : http://pic1.zhimg.com/01c635a7439ff86ff7138f93d5a281dc_im.jpg * time : 1487478427 * reply_to : {"content":"说白了,就是没有原则的的\u201c助手\u201d软件抢了黑心厂商苹果爸爸的钱。\n可能坏处是让正版游戏的收入减少,没有资金进行研发。好处也是有的,竞争性抑制。\u201c玩游戏要钱可以,别太过分啊!要不我换地方了\u201d。不让苹果和游戏厂商心太黑。另外,担心游戏行业无法发展维持的人想太多了,游戏行业的利润总比你想象的多。\n还有一点,作者说:\u201c苹果在三四线城市的占有量还是非常大的\u201d,正好说明了苹果在一二线城市占有率不高。真正懂手机现在不怎么喜欢苹果。\n个人认为,乔帮主之后的苹果,就是个垃鸡。硬件创新每年就那个几年,\u201c独创性\u201d和\u201c改革意义\u201d更是几乎没有。系统研发慢慢的开始成为了\u201c抄安卓\u201d。就靠着乔老爷子开创的\u201c软硬件完美结合\u201d混日子。\n随着安卓硬件的快速发展,几乎快追上苹果,系统更是早就超越苹果,这点是我个人意见。软件的生态优势,强于安卓。\n苹果就是个碌碌无为的混日子公司。早就不是那个智能机的开创者了。当然了,暂时还是死不了。百足之虫,死而不僵。","status":0,"id":28150411,"author":"张文辉"} * id : 28160966 * likes : 6 */ private String author; private String content; private String avatar; private int time; private ReplyToBean reply_to; private int id; private int likes; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getTime() { return DateUtils.timestamp2Date(time); } public void setTime(int time) { this.time = time; } public ReplyToBean getReply_to() { return reply_to; } public void setReply_to(ReplyToBean reply_to) { this.reply_to = reply_to; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getLikes() { return likes; } public void setLikes(int likes) { this.likes = likes; } public static class ReplyToBean { /** * content : 说白了,就是没有原则的的“助手”软件抢了黑心厂商苹果爸爸的钱。 可能坏处是让正版游戏的收入减少,没有资金进行研发。好处也是有的,竞争性抑制。“玩游戏要钱可以,别太过分啊!要不我换地方了”。不让苹果和游戏厂商心太黑。另外,担心游戏行业无法发展维持的人想太多了,游戏行业的利润总比你想象的多。 还有一点,作者说:“苹果在三四线城市的占有量还是非常大的”,正好说明了苹果在一二线城市占有率不高。真正懂手机现在不怎么喜欢苹果。 个人认为,乔帮主之后的苹果,就是个垃鸡。硬件创新每年就那个几年,“独创性”和“改革意义”更是几乎没有。系统研发慢慢的开始成为了“抄安卓”。就靠着乔老爷子开创的“软硬件完美结合”混日子。 随着安卓硬件的快速发展,几乎快追上苹果,系统更是早就超越苹果,这点是我个人意见。软件的生态优势,强于安卓。 苹果就是个碌碌无为的混日子公司。早就不是那个智能机的开创者了。当然了,暂时还是死不了。百足之虫,死而不僵。 * status : 0 * id : 28150411 * author : 张文辉 */ private String content; private int status; private int id; private String author; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } } }
Lovemma/ZhihuDaily
app/src/main/java/xyz/lovemma/zhihudaily/bean/StoryContentComment.java
1,927
/** * content : 说白了,就是没有原则的的“助手”软件抢了黑心厂商苹果爸爸的钱。 可能坏处是让正版游戏的收入减少,没有资金进行研发。好处也是有的,竞争性抑制。“玩游戏要钱可以,别太过分啊!要不我换地方了”。不让苹果和游戏厂商心太黑。另外,担心游戏行业无法发展维持的人想太多了,游戏行业的利润总比你想象的多。 还有一点,作者说:“苹果在三四线城市的占有量还是非常大的”,正好说明了苹果在一二线城市占有率不高。真正懂手机现在不怎么喜欢苹果。 个人认为,乔帮主之后的苹果,就是个垃鸡。硬件创新每年就那个几年,“独创性”和“改革意义”更是几乎没有。系统研发慢慢的开始成为了“抄安卓”。就靠着乔老爷子开创的“软硬件完美结合”混日子。 随着安卓硬件的快速发展,几乎快追上苹果,系统更是早就超越苹果,这点是我个人意见。软件的生态优势,强于安卓。 苹果就是个碌碌无为的混日子公司。早就不是那个智能机的开创者了。当然了,暂时还是死不了。百足之虫,死而不僵。 * status : 0 * id : 28150411 * author : 张文辉 */
block_comment
zh-cn
package xyz.lovemma.zhihudaily.bean; import xyz.lovemma.zhihudaily.utils.DateUtils; /** * Created by OO on 2017/2/24. */ public class StoryContentComment implements BaseItem{ /** * author : 少先大队委员长 * content : “中国三四线城市现在拥有苹果手机的人数量不在少数”作者这句话的前提是一二线城市现在拥有苹果手机的人非常多。你可能是听多了国内各大厂商对自家手机的宣传所以才会产生苹果越来越差,国产机完全秒杀的错觉。另外就硬件来讲安卓在屏幕,像素,cpu,ram等方面上多年来一直是强过苹果的,但是体验上却很少能有与苹果比肩的,系统的流畅度不是单纯的硬件堆砌能实现的。至于安卓超越ios这个就太夸张了,只能说各有优劣,适合自己的才是最好的,另外安卓与ios多年来也是互相借鉴,谈不上抄袭,毕竟用户需求摆在那里,大家共同进步更好,再考虑到国内对谷歌的阉割所以就国内的体验来讲我觉得安卓还是远远落后于ios的,至于各家的UI也是双刃剑的,符合了国人的使用习惯但是广告太多之类的小问题也是不少。“独创性,改革意义”这种事不是短短几年内就会多次出现的就像汽车发明这么多年了不还是依然四个轱辘么,也没见它上天也没见它下海,要有耐心。以上是我的个人意见 * avatar : http://pic1.zhimg.com/01c635a7439ff86ff7138f93d5a281dc_im.jpg * time : 1487478427 * reply_to : {"content":"说白了,就是没有原则的的\u201c助手\u201d软件抢了黑心厂商苹果爸爸的钱。\n可能坏处是让正版游戏的收入减少,没有资金进行研发。好处也是有的,竞争性抑制。\u201c玩游戏要钱可以,别太过分啊!要不我换地方了\u201d。不让苹果和游戏厂商心太黑。另外,担心游戏行业无法发展维持的人想太多了,游戏行业的利润总比你想象的多。\n还有一点,作者说:\u201c苹果在三四线城市的占有量还是非常大的\u201d,正好说明了苹果在一二线城市占有率不高。真正懂手机现在不怎么喜欢苹果。\n个人认为,乔帮主之后的苹果,就是个垃鸡。硬件创新每年就那个几年,\u201c独创性\u201d和\u201c改革意义\u201d更是几乎没有。系统研发慢慢的开始成为了\u201c抄安卓\u201d。就靠着乔老爷子开创的\u201c软硬件完美结合\u201d混日子。\n随着安卓硬件的快速发展,几乎快追上苹果,系统更是早就超越苹果,这点是我个人意见。软件的生态优势,强于安卓。\n苹果就是个碌碌无为的混日子公司。早就不是那个智能机的开创者了。当然了,暂时还是死不了。百足之虫,死而不僵。","status":0,"id":28150411,"author":"张文辉"} * id : 28160966 * likes : 6 */ private String author; private String content; private String avatar; private int time; private ReplyToBean reply_to; private int id; private int likes; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getTime() { return DateUtils.timestamp2Date(time); } public void setTime(int time) { this.time = time; } public ReplyToBean getReply_to() { return reply_to; } public void setReply_to(ReplyToBean reply_to) { this.reply_to = reply_to; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getLikes() { return likes; } public void setLikes(int likes) { this.likes = likes; } public static class ReplyToBean { /** * con <SUF>*/ private String content; private int status; private int id; private String author; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } } }
false
1,468
313
1,925
434
1,635
314
1,927
435
2,696
647
true
true
true
true
true
false
47329_0
package top.easyblog.config; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.annotation.Aspect; import top.easyblog.util.SensitiveWordUtils; /** * 敏感词过滤器:对标注@SensitiveFilter的类或方法进行敏感词过滤 * 1. 涉政文字:涉及政人物、政治事件、宗教、反动分裂,以及恐怖主义等违规文本 * 2. 色情文字:识别淫秽、污秽、色诱、文爱等涉黄内容,支持重度色情、轻度色情分级 * 3. 辱骂文本:识别各类场景中含有污辱、谩骂、诋毁等辱骂内容 * 4. 违禁文本:识别赌博、刀枪、毒品、造假、贩假等违规内容 * 5. 广告导流:识别利用微信号、手机号、QQ、二维码等开展违法垃圾广告内容 * 6. 垃圾内容:识别水贴、刷屏、无意义等垃圾内容,实现智能反垃圾 * * @author :huangxin * @modified : * @since :2020/11/10 13:39 */ @Slf4j @Aspect public class SensitiveWordAspect { private SensitiveWordUtils sensitiveWordUtils = SensitiveWordUtils.getInstance(); }
LoverITer/easyblog
src/main/java/top/easyblog/config/SensitiveWordAspect.java
391
/** * 敏感词过滤器:对标注@SensitiveFilter的类或方法进行敏感词过滤 * 1. 涉政文字:涉及政人物、政治事件、宗教、反动分裂,以及恐怖主义等违规文本 * 2. 色情文字:识别淫秽、污秽、色诱、文爱等涉黄内容,支持重度色情、轻度色情分级 * 3. 辱骂文本:识别各类场景中含有污辱、谩骂、诋毁等辱骂内容 * 4. 违禁文本:识别赌博、刀枪、毒品、造假、贩假等违规内容 * 5. 广告导流:识别利用微信号、手机号、QQ、二维码等开展违法垃圾广告内容 * 6. 垃圾内容:识别水贴、刷屏、无意义等垃圾内容,实现智能反垃圾 * * @author :huangxin * @modified : * @since :2020/11/10 13:39 */
block_comment
zh-cn
package top.easyblog.config; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.annotation.Aspect; import top.easyblog.util.SensitiveWordUtils; /** * 敏感词 <SUF>*/ @Slf4j @Aspect public class SensitiveWordAspect { private SensitiveWordUtils sensitiveWordUtils = SensitiveWordUtils.getInstance(); }
false
296
230
391
303
316
234
391
303
547
438
true
true
true
true
true
false
31937_1
package work; /** * 练习 */ public class Person1 { public String name; public int age; public int sex; /** * 学习 */ public void study() { System.out.println("studying"); } /** * 输出年龄 */ public void showAge() { System.out.println(age); } /** * 年龄加2 * @return */ public int addAge(int i) { age +=i; return age; } }
LucasGini/LearningRecord
Java/work/Person1.java
128
/** * 学习 */
block_comment
zh-cn
package work; /** * 练习 */ public class Person1 { public String name; public int age; public int sex; /** * 学习 <SUF>*/ public void study() { System.out.println("studying"); } /** * 输出年龄 */ public void showAge() { System.out.println(age); } /** * 年龄加2 * @return */ public int addAge(int i) { age +=i; return age; } }
false
118
9
128
7
144
8
128
7
165
12
false
false
false
false
false
true
23749_0
package com.wen.seckill.rabbitmq; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; //原谅我把。。这个类是我copy的。不是手写的。太多交换机模式了,蛋疼,只学了默认的 @Configuration public class MQConfig { public static final String MIAOSHA_QUEUE = "hello"; public static final String QUEUE = "queue"; public static final String TOPIC_QUEUE1 = "topic.queue1"; public static final String TOPIC_QUEUE2 = "topic.queue2"; public static final String HEADER_QUEUE = "header.queue"; public static final String TOPIC_EXCHANGE = "topicExchage"; public static final String FANOUT_EXCHANGE = "fanoutExchage"; public static final String HEADERS_EXCHANGE = "headersExchage"; /** * Direct模式 交换机 Exchange * */ @Bean public Queue queue() { return new Queue(QUEUE, true); } /** * Topic模式 交换机Exchange * */ @Bean public Queue topicQueue1() { return new Queue(TOPIC_QUEUE1, true); } @Bean public Queue topicQueue2() { return new Queue(TOPIC_QUEUE2, true); } @Bean public TopicExchange topicExchage(){ return new TopicExchange(TOPIC_EXCHANGE); } @Bean public Binding topicBinding1() { return BindingBuilder.bind(topicQueue1()).to(topicExchage()).with("topic.key1"); } @Bean public Binding topicBinding2() { return BindingBuilder.bind(topicQueue2()).to(topicExchage()).with("topic.#"); } /** * Fanout模式(广播模式) 交换机Exchange * */ @Bean public FanoutExchange fanoutExchage(){ return new FanoutExchange(FANOUT_EXCHANGE); } @Bean public Binding FanoutBinding1() { return BindingBuilder.bind(topicQueue1()).to(fanoutExchage()); } @Bean public Binding FanoutBinding2() { return BindingBuilder.bind(topicQueue2()).to(fanoutExchage()); } /** * Header模式 交换机Exchange * */ @Bean public HeadersExchange headersExchage(){ return new HeadersExchange(HEADERS_EXCHANGE); } @Bean public Queue headerQueue1() { return new Queue(HEADER_QUEUE, true); } @Bean public Binding headerBinding() { Map<String, Object> map = new HashMap<String, Object>(); map.put("header1", "value1"); map.put("header2", "value2"); return BindingBuilder.bind(headerQueue1()).to(headersExchage()).whereAll(map).match(); } }
LuckyToMeet-Dian-N/myseckill
src/main/java/com/wen/seckill/rabbitmq/MQConfig.java
765
//原谅我把。。这个类是我copy的。不是手写的。太多交换机模式了,蛋疼,只学了默认的
line_comment
zh-cn
package com.wen.seckill.rabbitmq; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; //原谅 <SUF> @Configuration public class MQConfig { public static final String MIAOSHA_QUEUE = "hello"; public static final String QUEUE = "queue"; public static final String TOPIC_QUEUE1 = "topic.queue1"; public static final String TOPIC_QUEUE2 = "topic.queue2"; public static final String HEADER_QUEUE = "header.queue"; public static final String TOPIC_EXCHANGE = "topicExchage"; public static final String FANOUT_EXCHANGE = "fanoutExchage"; public static final String HEADERS_EXCHANGE = "headersExchage"; /** * Direct模式 交换机 Exchange * */ @Bean public Queue queue() { return new Queue(QUEUE, true); } /** * Topic模式 交换机Exchange * */ @Bean public Queue topicQueue1() { return new Queue(TOPIC_QUEUE1, true); } @Bean public Queue topicQueue2() { return new Queue(TOPIC_QUEUE2, true); } @Bean public TopicExchange topicExchage(){ return new TopicExchange(TOPIC_EXCHANGE); } @Bean public Binding topicBinding1() { return BindingBuilder.bind(topicQueue1()).to(topicExchage()).with("topic.key1"); } @Bean public Binding topicBinding2() { return BindingBuilder.bind(topicQueue2()).to(topicExchage()).with("topic.#"); } /** * Fanout模式(广播模式) 交换机Exchange * */ @Bean public FanoutExchange fanoutExchage(){ return new FanoutExchange(FANOUT_EXCHANGE); } @Bean public Binding FanoutBinding1() { return BindingBuilder.bind(topicQueue1()).to(fanoutExchage()); } @Bean public Binding FanoutBinding2() { return BindingBuilder.bind(topicQueue2()).to(fanoutExchage()); } /** * Header模式 交换机Exchange * */ @Bean public HeadersExchange headersExchage(){ return new HeadersExchange(HEADERS_EXCHANGE); } @Bean public Queue headerQueue1() { return new Queue(HEADER_QUEUE, true); } @Bean public Binding headerBinding() { Map<String, Object> map = new HashMap<String, Object>(); map.put("header1", "value1"); map.put("header2", "value2"); return BindingBuilder.bind(headerQueue1()).to(headersExchage()).whereAll(map).match(); } }
false
607
28
765
37
733
28
765
37
875
47
false
false
false
false
false
true
22557_1
import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Yard extends Frame { PaintThread paintThread = new PaintThread(); private boolean gameOver = false; public static final int ROWS = 30; public static final int COLS = 30; public static final int BLOCK_SIZE = 15; private Font fontGameOver = new Font("宋体", Font.BOLD, 50); private int score = 0; Snake s = new Snake(this); Egg e = new Egg(); Image offScreenImage = null; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public void launch() { this.setLocation(200, 200); this.setSize(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE); //使退出键有效果 this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); this.setVisible(true); this.addKeyListener(new KeyMonitor()); new Thread(paintThread).start(); } public static void main(String[] args) { new Yard().launch(); } public void stop() { gameOver = true; } public void paint(Graphics g) { Color c = g.getColor(); g.setColor(Color.GRAY); g.fillRect(0, 0, COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE); g.setColor(Color.DARK_GRAY); //画出横线 for(int i=1; i<ROWS; i++) { g.drawLine(0, BLOCK_SIZE * i, COLS * BLOCK_SIZE, BLOCK_SIZE * i); } for(int i=1; i<COLS; i++) { g.drawLine(BLOCK_SIZE * i, 0, BLOCK_SIZE * i, BLOCK_SIZE * ROWS); } g.setColor(Color.YELLOW); g.drawString("score:" + score, 10, 60); if(gameOver) { g.setFont(fontGameOver); g.drawString("游戏结束", 120, 180); paintThread.pause(); } g.setColor(c); s.eat(e); e.draw(g); s.draw(g); } public void update(Graphics g) { if(offScreenImage == null) { offScreenImage = this.createImage(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE ); } Graphics gOff = offScreenImage.getGraphics(); paint(gOff); g.drawImage(offScreenImage, 0, 0, null); } private class PaintThread implements Runnable { private boolean pause = false; private boolean running = true; public void run() { while(running) { if(pause) continue; else repaint(); try { Thread.sleep(200); //回调paint()方法 } catch (InterruptedException e) { e.printStackTrace(); } } } public void pause() { this.pause = true; } public void reStart() { this.pause = false; s = new Snake(Yard.this); gameOver = false; } public void gameOver() { running = false; } } private class KeyMonitor extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(key == KeyEvent.VK_F2) { paintThread.reStart(); } s.keyPressed(e); } } }
LuckyZXL2016/Snake
src/Yard.java
1,056
//画出横线
line_comment
zh-cn
import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Yard extends Frame { PaintThread paintThread = new PaintThread(); private boolean gameOver = false; public static final int ROWS = 30; public static final int COLS = 30; public static final int BLOCK_SIZE = 15; private Font fontGameOver = new Font("宋体", Font.BOLD, 50); private int score = 0; Snake s = new Snake(this); Egg e = new Egg(); Image offScreenImage = null; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public void launch() { this.setLocation(200, 200); this.setSize(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE); //使退出键有效果 this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); this.setVisible(true); this.addKeyListener(new KeyMonitor()); new Thread(paintThread).start(); } public static void main(String[] args) { new Yard().launch(); } public void stop() { gameOver = true; } public void paint(Graphics g) { Color c = g.getColor(); g.setColor(Color.GRAY); g.fillRect(0, 0, COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE); g.setColor(Color.DARK_GRAY); //画出 <SUF> for(int i=1; i<ROWS; i++) { g.drawLine(0, BLOCK_SIZE * i, COLS * BLOCK_SIZE, BLOCK_SIZE * i); } for(int i=1; i<COLS; i++) { g.drawLine(BLOCK_SIZE * i, 0, BLOCK_SIZE * i, BLOCK_SIZE * ROWS); } g.setColor(Color.YELLOW); g.drawString("score:" + score, 10, 60); if(gameOver) { g.setFont(fontGameOver); g.drawString("游戏结束", 120, 180); paintThread.pause(); } g.setColor(c); s.eat(e); e.draw(g); s.draw(g); } public void update(Graphics g) { if(offScreenImage == null) { offScreenImage = this.createImage(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE ); } Graphics gOff = offScreenImage.getGraphics(); paint(gOff); g.drawImage(offScreenImage, 0, 0, null); } private class PaintThread implements Runnable { private boolean pause = false; private boolean running = true; public void run() { while(running) { if(pause) continue; else repaint(); try { Thread.sleep(200); //回调paint()方法 } catch (InterruptedException e) { e.printStackTrace(); } } } public void pause() { this.pause = true; } public void reStart() { this.pause = false; s = new Snake(Yard.this); gameOver = false; } public void gameOver() { running = false; } } private class KeyMonitor extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(key == KeyEvent.VK_F2) { paintThread.reStart(); } s.keyPressed(e); } } }
false
840
6
1,046
7
1,052
6
1,046
7
1,286
8
false
false
false
false
false
true
24913_10
public class SkillFactory { public static Skill createSkill(int type, Character target1, Character target2, Creature target3) { /* target1 target2 target3 三个目标来供修改 若不需要则传入null */ switch (type) { //下方开始是唤魔 /* 鲜血榨汁机 唤魔 械宗 (25/0/3/0) 每个中回合结束时对自己的人物造成三点伤害,并获得50点能量 */ case 0: return new ChangeCurrentHP(new ChangePower(new BasicSkill(0, target1), 50), -3); /* 奇怪的祭坛 唤魔 神宗 (75/0/3/0) 在己方回合每牺牲一个友方随从,便获得50点能量(最多牺牲五个) */ case 1: return new ChangePower(new BasicSkill(0, target1), 50); /* 邪能收集台 唤魔 法宗 (25/0/5/0)每个中回合结束时,获得25点能量 */ case 2: return new ChangePower(new BasicSkill(0, target1), 25); /* 淘气的小鬼 唤魔 械宗 (25/2/1/2) 战吼:指定一个友方所从,对其造成两点伤害 */ case 3: return new ChangeHP(new BasicSkill(0, target1), -2); /* 嗜血者 唤魔 神宗 (200/5/5/2-3) 战吼:对所有角色造成一点伤害,每有一个角色死亡则获得攻击力加一血加一 */ case 4: return new ChangeHP(new ChangeATK(new BasicSkill(0, target1), 1), 1); /* 被诅咒的封印 唤魔 神宗(500/0/25/0)在回合结束时若己方人物血量正好等于五点,则杀死友方人物,将其替代为造物者 */ //case 5: return new ; /* 地狱之门 唤魔 法宗 (300/0/0/0)战吼:以自己为中心3x3的范围内,对所有角色造成三点伤害 */ case 6: return new CreateCreature(new BasicSkill(0, target1), target3); /* 替死冤魂 唤魔 法宗 (300/4/10/2-3)战吼:选择一个友方yw,若该yw在敌方回合死亡,则使替死幽魂死亡,友方yw复原原来血量的一半(四舍五入) */ case 7: return new ChangeHP(new BasicSkill(0, target1), ((yw) target1).get("HP") / 2); /* 吞噬者的巢穴 唤魔 法宗(350/0/0/0) 战吼:在友方军团3x3的范围内,选择一个战场上的格子,将吞噬者的巢穴放在上面(用不可视), 若有地方军团走到上面,则会召唤系统人物吞噬者,20血,自带5点攻击,且军团里有两只(25/3/2/2)的yw,每个中回合放一只(25/3/2/2)的yw, 并选择攻击最近的人物 */ case 8: return new CreateCreature(new BasicSkill(0, target1), target3); /* 梦魇巨怪 唤魔 神宗(175/7/12/2-3)每个中回合结束时,对自己造成4点伤害 */ case 9: return new ChangeHP(new BasicSkill(0, target1), -4); /* 凋谢的恶魔之花 唤魔 械宗(125/5/5/2-3)亡语:使所有友方角色恢复六点血 */ case 10: return new ChangeHP(new BasicSkill(0, target1), 6); /* 被折磨的弃教者 唤魔 械宗(100/2/10/2-3)该随从每受到一次伤害,就随机对一个非友方角色造成两点伤害 */ case 11: return new ChangeHP(new BasicSkill(0, target1), -2); //下方开始是潜行 /* 被诅咒的封印 潜行 神宗(500/0/25/0)在回合开始时,己方军团格子上有两只需消耗500能量以上的一模一样的yw(能量/攻击/血/攻击距离), */ //case 12: return new ; /* 禁忌的瞳术 潜行 神宗 (200/0/25/0)将你的第二技能换为消耗25点的一段瞳术,以自己为起点选择一排或是一列在这个中回合中可视所有这些格子上的内容。 若在己方回合杀死两个己方随从,则升级为消耗25点的二段瞳术,可视所有以自己为中心3x3范围内所有格子。若在己方回合再杀死两个己方随从,则升级为消耗 25点的三段瞳术,可视所有格子 */ //case 13: return new ; /* 傀儡·爱 潜行 械宗(125/3/10/2-5)战吼:若傀儡恨在场上,则使一个有方角色恢复5点血 */ case 14: return new ChangeHP(new BasicSkill(0, target1), 5); /* 傀儡·恨 潜行 械宗(125/10/3/2-3)己方中回合结束时。若傀儡·爱在场上,则对其两边的yw分别造成三点伤害 */ case 15: return new ChangeHP(new BasicSkill(0, target1), -3); /* 傀儡·情 潜行 械宗(225/?/?/1-5)若傀儡·爱在场上,获得5攻击力,10血;若傀儡恨在场上则获得10攻,5血;若都没有,则获得6攻6血 */ //case 16: return new ; /* 迷雾释放者 潜行 法宗 (175/0/0/0)战吼:在以己为中心3x3的范围内,放置在战场上,成为一个角色,拥有十点血(不能移动),战场重新布回新的战争 迷雾,且迷雾只使所走过的最后三个格子可视。 */ case 17: return new CreateCreature(new BasicSkill(0, target1), target3); /* 暗影织布机 潜行 神宗 (175/0/0/0)战吼:在以己为中心3x3的范围内,放置成为一个角色,拥有十点血(不能移动),每个中回合结束时获得150点能量 */ case 18: return new CreateCreature(new BasicSkill(0, target1), target3); /* 尖锐的匕首 潜行 械宗(250/0/9/0)己方角色本中回合获得五点攻击,攻击距离为2-4 */ case 19: return new ChangeATK(new ChangeRange(new BasicSkill(0, target1), 2), 5); /* 小型青玉石 潜行 神宗 (25/0/4/0) 每个中回合开始时,获得50点能量 */ case 20: return new ChangePower(new BasicSkill(0, target1), 50); /* 飞刀陷阱 潜行 法宗(300/0/0/0)战吼:放置一个脚踏板拥有十五点血(不能移动),在同一排或同一列放置一个飞刀发射器拥有十五点血(不能移动), 若有人踩在脚踏板上,则发射器射中当在他路径上的第一个军团,整个军团的所有角色扣五滴血 */ case 21: return new CreateCreature(new BasicSkill(0, null), target3); /* 闪避术(停滞五回合) 潜行 法宗 (150/0/0/0)战吼: 在下个己方回合开始前,免疫三次对方的攻击(每攻击到一个yw或己方人物算一次) 被诅咒的封印 唤魔 神宗(500/0/25/0)在回合结束时若己方人物血量正好等于五点,则杀死友方人物,将其替代为造物者 */ //case 22: return new; /* 残影制造术(停滞五回合) 潜行 法宗 (150/0/0/0)战吼:在现在的格子上制造残影,若残影被视可视到,仍会显示释放时的所有信息, 在对方第一次攻击完时,则会消失 */ //case 23:; //下方开始是undefined /* FailTrial1 (25/0/3/0)每个中回合结束时,获得25点能量 */ case 24: return new ChangePower(new BasicSkill(0,target1),25); /* FailTrial2 (50/0/3/0)每个中回合开始时,获得50点能量 */ case 25: return new ChangePower(new BasicSkill(0,target1),50); /* FailTrial8 (100/2/3/2)每个中回合结束时,人物恢复3点血 */ case 26: return new ChangeHP(new BasicSkill(0,target1),3); /* 1.FailTrial9 (100/5/6/2-3)每个中回合结束时,人物扣2点血 */ case 27: return new ChangeHP(new BasicSkill(0,target1),-2); /* FailTrial10 (500/0/0/0)消灭一个yw */ case 28: return new BasicSkill(0,target1); /* 种族别名:Undefined 种族技能:人物攻击(耗费能量25):人物获得2点攻击和2-3点攻击距离 */ case 29: return new ChangeATK(new ChangeRange(new BasicSkill(25,target1),2),2); /* 种族别名:Undefined 第二技能:人物回血(耗费能量25):回两点血 */ case 30: return new ChangeHP(new BasicSkill(25,target1),2); } return null; } }
Luke-lujunxian/YW-s-legend-sever
YWLegend/src/SkillFactory.java
2,940
/* 替死冤魂 唤魔 法宗 (300/4/10/2-3)战吼:选择一个友方yw,若该yw在敌方回合死亡,则使替死幽魂死亡,友方yw复原原来血量的一半(四舍五入) */
block_comment
zh-cn
public class SkillFactory { public static Skill createSkill(int type, Character target1, Character target2, Creature target3) { /* target1 target2 target3 三个目标来供修改 若不需要则传入null */ switch (type) { //下方开始是唤魔 /* 鲜血榨汁机 唤魔 械宗 (25/0/3/0) 每个中回合结束时对自己的人物造成三点伤害,并获得50点能量 */ case 0: return new ChangeCurrentHP(new ChangePower(new BasicSkill(0, target1), 50), -3); /* 奇怪的祭坛 唤魔 神宗 (75/0/3/0) 在己方回合每牺牲一个友方随从,便获得50点能量(最多牺牲五个) */ case 1: return new ChangePower(new BasicSkill(0, target1), 50); /* 邪能收集台 唤魔 法宗 (25/0/5/0)每个中回合结束时,获得25点能量 */ case 2: return new ChangePower(new BasicSkill(0, target1), 25); /* 淘气的小鬼 唤魔 械宗 (25/2/1/2) 战吼:指定一个友方所从,对其造成两点伤害 */ case 3: return new ChangeHP(new BasicSkill(0, target1), -2); /* 嗜血者 唤魔 神宗 (200/5/5/2-3) 战吼:对所有角色造成一点伤害,每有一个角色死亡则获得攻击力加一血加一 */ case 4: return new ChangeHP(new ChangeATK(new BasicSkill(0, target1), 1), 1); /* 被诅咒的封印 唤魔 神宗(500/0/25/0)在回合结束时若己方人物血量正好等于五点,则杀死友方人物,将其替代为造物者 */ //case 5: return new ; /* 地狱之门 唤魔 法宗 (300/0/0/0)战吼:以自己为中心3x3的范围内,对所有角色造成三点伤害 */ case 6: return new CreateCreature(new BasicSkill(0, target1), target3); /* 替死冤 <SUF>*/ case 7: return new ChangeHP(new BasicSkill(0, target1), ((yw) target1).get("HP") / 2); /* 吞噬者的巢穴 唤魔 法宗(350/0/0/0) 战吼:在友方军团3x3的范围内,选择一个战场上的格子,将吞噬者的巢穴放在上面(用不可视), 若有地方军团走到上面,则会召唤系统人物吞噬者,20血,自带5点攻击,且军团里有两只(25/3/2/2)的yw,每个中回合放一只(25/3/2/2)的yw, 并选择攻击最近的人物 */ case 8: return new CreateCreature(new BasicSkill(0, target1), target3); /* 梦魇巨怪 唤魔 神宗(175/7/12/2-3)每个中回合结束时,对自己造成4点伤害 */ case 9: return new ChangeHP(new BasicSkill(0, target1), -4); /* 凋谢的恶魔之花 唤魔 械宗(125/5/5/2-3)亡语:使所有友方角色恢复六点血 */ case 10: return new ChangeHP(new BasicSkill(0, target1), 6); /* 被折磨的弃教者 唤魔 械宗(100/2/10/2-3)该随从每受到一次伤害,就随机对一个非友方角色造成两点伤害 */ case 11: return new ChangeHP(new BasicSkill(0, target1), -2); //下方开始是潜行 /* 被诅咒的封印 潜行 神宗(500/0/25/0)在回合开始时,己方军团格子上有两只需消耗500能量以上的一模一样的yw(能量/攻击/血/攻击距离), */ //case 12: return new ; /* 禁忌的瞳术 潜行 神宗 (200/0/25/0)将你的第二技能换为消耗25点的一段瞳术,以自己为起点选择一排或是一列在这个中回合中可视所有这些格子上的内容。 若在己方回合杀死两个己方随从,则升级为消耗25点的二段瞳术,可视所有以自己为中心3x3范围内所有格子。若在己方回合再杀死两个己方随从,则升级为消耗 25点的三段瞳术,可视所有格子 */ //case 13: return new ; /* 傀儡·爱 潜行 械宗(125/3/10/2-5)战吼:若傀儡恨在场上,则使一个有方角色恢复5点血 */ case 14: return new ChangeHP(new BasicSkill(0, target1), 5); /* 傀儡·恨 潜行 械宗(125/10/3/2-3)己方中回合结束时。若傀儡·爱在场上,则对其两边的yw分别造成三点伤害 */ case 15: return new ChangeHP(new BasicSkill(0, target1), -3); /* 傀儡·情 潜行 械宗(225/?/?/1-5)若傀儡·爱在场上,获得5攻击力,10血;若傀儡恨在场上则获得10攻,5血;若都没有,则获得6攻6血 */ //case 16: return new ; /* 迷雾释放者 潜行 法宗 (175/0/0/0)战吼:在以己为中心3x3的范围内,放置在战场上,成为一个角色,拥有十点血(不能移动),战场重新布回新的战争 迷雾,且迷雾只使所走过的最后三个格子可视。 */ case 17: return new CreateCreature(new BasicSkill(0, target1), target3); /* 暗影织布机 潜行 神宗 (175/0/0/0)战吼:在以己为中心3x3的范围内,放置成为一个角色,拥有十点血(不能移动),每个中回合结束时获得150点能量 */ case 18: return new CreateCreature(new BasicSkill(0, target1), target3); /* 尖锐的匕首 潜行 械宗(250/0/9/0)己方角色本中回合获得五点攻击,攻击距离为2-4 */ case 19: return new ChangeATK(new ChangeRange(new BasicSkill(0, target1), 2), 5); /* 小型青玉石 潜行 神宗 (25/0/4/0) 每个中回合开始时,获得50点能量 */ case 20: return new ChangePower(new BasicSkill(0, target1), 50); /* 飞刀陷阱 潜行 法宗(300/0/0/0)战吼:放置一个脚踏板拥有十五点血(不能移动),在同一排或同一列放置一个飞刀发射器拥有十五点血(不能移动), 若有人踩在脚踏板上,则发射器射中当在他路径上的第一个军团,整个军团的所有角色扣五滴血 */ case 21: return new CreateCreature(new BasicSkill(0, null), target3); /* 闪避术(停滞五回合) 潜行 法宗 (150/0/0/0)战吼: 在下个己方回合开始前,免疫三次对方的攻击(每攻击到一个yw或己方人物算一次) 被诅咒的封印 唤魔 神宗(500/0/25/0)在回合结束时若己方人物血量正好等于五点,则杀死友方人物,将其替代为造物者 */ //case 22: return new; /* 残影制造术(停滞五回合) 潜行 法宗 (150/0/0/0)战吼:在现在的格子上制造残影,若残影被视可视到,仍会显示释放时的所有信息, 在对方第一次攻击完时,则会消失 */ //case 23:; //下方开始是undefined /* FailTrial1 (25/0/3/0)每个中回合结束时,获得25点能量 */ case 24: return new ChangePower(new BasicSkill(0,target1),25); /* FailTrial2 (50/0/3/0)每个中回合开始时,获得50点能量 */ case 25: return new ChangePower(new BasicSkill(0,target1),50); /* FailTrial8 (100/2/3/2)每个中回合结束时,人物恢复3点血 */ case 26: return new ChangeHP(new BasicSkill(0,target1),3); /* 1.FailTrial9 (100/5/6/2-3)每个中回合结束时,人物扣2点血 */ case 27: return new ChangeHP(new BasicSkill(0,target1),-2); /* FailTrial10 (500/0/0/0)消灭一个yw */ case 28: return new BasicSkill(0,target1); /* 种族别名:Undefined 种族技能:人物攻击(耗费能量25):人物获得2点攻击和2-3点攻击距离 */ case 29: return new ChangeATK(new ChangeRange(new BasicSkill(25,target1),2),2); /* 种族别名:Undefined 第二技能:人物回血(耗费能量25):回两点血 */ case 30: return new ChangeHP(new BasicSkill(25,target1),2); } return null; } }
false
2,545
71
2,940
88
2,612
72
2,940
88
3,824
113
false
false
false
false
false
true
53859_36
package com.hao.udv; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; import com.hao.gamefivechess.R; /** * Created by ZhangHao on 2017/6/27. * 五子棋 View */ public class FiveChessView extends View implements View.OnTouchListener { //画笔 private Paint paint; //棋子数组 private int[][] chessArray; //当前下棋顺序(默认白棋先下) private boolean isWhite = true; //游戏是否结束 private boolean isGameOver = false; //bitmap private Bitmap whiteChess; private Bitmap blackChess; //Rect private Rect rect; //棋盘宽高 private float len; //棋盘格数 private int GRID_NUMBER = 15; //每格之间的距离 private float preWidth; //边距 private float offset; //回调 private GameCallBack callBack; //当前黑白棋胜利次数 private int whiteChessCount, blackChessCount; //是否是玩家的回合 private boolean isUserBout = true; //玩家执子颜色 private int userChess = WHITE_CHESS; //玩家/AI胜利次数 private int userScore = 0, aiScore = 0; /** * 一些常量 */ //白棋 public static final int WHITE_CHESS = 1; //黑棋 public static final int BLACK_CHESS = 2; //无棋 public static final int NO_CHESS = 0; //白棋赢 public static final int WHITE_WIN = 101; //黑棋赢 public static final int BLACK_WIN = 102; //平局 public static final int NO_WIN = 103; public FiveChessView(Context context) { this(context, null); } public FiveChessView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FiveChessView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //初始化Paint paint = new Paint(); //设置抗锯齿 paint.setAntiAlias(true); paint.setColor(Color.BLACK); //初始化chessArray chessArray = new int[GRID_NUMBER][GRID_NUMBER]; //初始化棋子图片bitmap whiteChess = BitmapFactory.decodeResource(context.getResources(), R.drawable.white_chess); blackChess = BitmapFactory.decodeResource(context.getResources(), R.drawable.black_chess); //初始化胜利局数 whiteChessCount = 0; blackChessCount = 0; //初始化Rect rect = new Rect(); //设置点击监听 setOnTouchListener(this); //重置棋盘状态 for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { chessArray[i][j] = 0; } } } /** * 重新测量宽高,确保宽高一样 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //获取高宽值 int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); //获取宽高中较小的值 int len = width > height ? height : width; //重新设置宽高 setMeasuredDimension(len, len); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //棋盘为一个GRID_NUMBER*GRID_NUMBER的正方形,所有棋盘宽高必须一样 len = getWidth() > getHeight() ? getHeight() : getWidth(); preWidth = len / GRID_NUMBER; //边距 offset = preWidth / 2; //棋盘线条 for (int i = 0; i < GRID_NUMBER; i++) { float start = i * preWidth + offset; //横线 canvas.drawLine(offset, start, len - offset, start, paint); //竖线 canvas.drawLine(start, offset, start, len - offset, paint); } //绘制棋子 for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { //rect中点坐标 float rectX = offset + i * preWidth; float rectY = offset + j * preWidth; //设置rect位置 rect.set((int) (rectX - offset), (int) (rectY - offset), (int) (rectX + offset), (int) (rectY + offset)); //遍历chessArray switch (chessArray[i][j]) { case WHITE_CHESS: //绘制白棋 canvas.drawBitmap(whiteChess, null, rect, paint); break; case BLACK_CHESS: //绘制黑棋 canvas.drawBitmap(blackChess, null, rect, paint); break; } } } } /** * 判断是否结束 */ private void checkGameOver() { //获取落子的颜色(如果当前是白棋,则落子是黑棋) int chess = isWhite ? BLACK_CHESS : WHITE_CHESS; //棋盘是否填满 boolean isFull = true; //遍历chessArray for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { //判断棋盘是否填满 if (chessArray[i][j] != BLACK_CHESS && chessArray[i][j] != WHITE_CHESS) { isFull = false; } //只需要判断落子是否五连即可 if (chessArray[i][j] == chess) { //判断五子相连 if (isFiveSame(i, j)) { //五子相连游戏结束 isGameOver = true; if (callBack != null) { //判断黑白棋胜利 if (chess == WHITE_CHESS) { whiteChessCount++; } else { blackChessCount++; } //判断玩家/AI 胜利 if (userChess == chess) { userScore++; } else { aiScore++; } callBack.GameOver(chess == WHITE_CHESS ? WHITE_WIN : BLACK_WIN); } return; } } } } //如果棋盘填满,平局结束 if (isFull) { isGameOver = true; if (callBack != null) { callBack.GameOver(NO_WIN); } } } /** * 重置游戏 */ public void resetGame() { isGameOver = false; //重置棋盘状态 for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { chessArray[i][j] = 0; } } //更新UI postInvalidate(); } /** * 判断是否存在五子相连 * * @return */ private boolean isFiveSame(int x, int y) { //判断横向 if (x + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x + 1][y] && chessArray[x][y] == chessArray[x + 2][y] && chessArray[x][y] == chessArray[x + 3][y] && chessArray[x][y] == chessArray[x + 4][y]) { return true; } } //判断纵向 if (y + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x][y + 1] && chessArray[x][y] == chessArray[x][y + 2] && chessArray[x][y] == chessArray[x][y + 3] && chessArray[x][y] == chessArray[x][y + 4]) { return true; } } //判断斜向(左上到右下) if (y + 4 < GRID_NUMBER && x + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x + 1][y + 1] && chessArray[x][y] == chessArray[x + 2][y + 2] && chessArray[x][y] == chessArray[x + 3][y + 3] && chessArray[x][y] == chessArray[x + 4][y + 4]) { return true; } } //判断斜向(左下到右上) if (y - 4 > 0 && x + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x + 1][y - 1] && chessArray[x][y] == chessArray[x + 2][y - 2] && chessArray[x][y] == chessArray[x + 3][y - 3] && chessArray[x][y] == chessArray[x + 4][y - 4]) { return true; } } return false; } //电脑判断游戏结束 public void checkAiGameOver() { isWhite = userChess == WHITE_CHESS; checkGameOver(); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (!isGameOver && isUserBout) { //获取按下时的位置 float downX = event.getX(); float downY = event.getY(); //点击的位置在棋盘上 if (downX >= offset / 2 && downX <= len - offset / 2 && downY >= offset / 2 && downY <= len - offset / 2) { //获取棋子对应的位置 int x = (int) (downX / preWidth); int y = (int) (downY / preWidth); //判断当前位置是否已经有子 if (chessArray[x][y] != WHITE_CHESS && chessArray[x][y] != BLACK_CHESS) { //给数组赋值 chessArray[x][y] = userChess; //修改当前落子颜色 isWhite = userChess == WHITE_CHESS; //修改当前为电脑执子 isUserBout = false; //更新棋盘 postInvalidate(); //判断是否结束 checkGameOver(); //回调当前执子 if (callBack != null) { callBack.ChangeGamer(isWhite); } } } } else if (isGameOver) { Toast.makeText(getContext(), "游戏已经结束,请重新开始!", Toast.LENGTH_SHORT).show(); } break; } return false; } public void setCallBack(GameCallBack callBack) { this.callBack = callBack; } public int getWhiteChessCount() { return whiteChessCount; } public int getBlackChessCount() { return blackChessCount; } public int[][] getChessArray() { return chessArray; } public void setUserBout(boolean userBout) { isUserBout = userBout; } public void setUserChess(int userChess) { this.userChess = userChess; } public int getUserScore() { return userScore; } public int getAiScore() { return aiScore; } }
LuoChen-Hao/GameFiveChess
app/src/main/java/com/hao/udv/FiveChessView.java
2,949
/** * 判断是否结束 */
block_comment
zh-cn
package com.hao.udv; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; import com.hao.gamefivechess.R; /** * Created by ZhangHao on 2017/6/27. * 五子棋 View */ public class FiveChessView extends View implements View.OnTouchListener { //画笔 private Paint paint; //棋子数组 private int[][] chessArray; //当前下棋顺序(默认白棋先下) private boolean isWhite = true; //游戏是否结束 private boolean isGameOver = false; //bitmap private Bitmap whiteChess; private Bitmap blackChess; //Rect private Rect rect; //棋盘宽高 private float len; //棋盘格数 private int GRID_NUMBER = 15; //每格之间的距离 private float preWidth; //边距 private float offset; //回调 private GameCallBack callBack; //当前黑白棋胜利次数 private int whiteChessCount, blackChessCount; //是否是玩家的回合 private boolean isUserBout = true; //玩家执子颜色 private int userChess = WHITE_CHESS; //玩家/AI胜利次数 private int userScore = 0, aiScore = 0; /** * 一些常量 */ //白棋 public static final int WHITE_CHESS = 1; //黑棋 public static final int BLACK_CHESS = 2; //无棋 public static final int NO_CHESS = 0; //白棋赢 public static final int WHITE_WIN = 101; //黑棋赢 public static final int BLACK_WIN = 102; //平局 public static final int NO_WIN = 103; public FiveChessView(Context context) { this(context, null); } public FiveChessView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FiveChessView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //初始化Paint paint = new Paint(); //设置抗锯齿 paint.setAntiAlias(true); paint.setColor(Color.BLACK); //初始化chessArray chessArray = new int[GRID_NUMBER][GRID_NUMBER]; //初始化棋子图片bitmap whiteChess = BitmapFactory.decodeResource(context.getResources(), R.drawable.white_chess); blackChess = BitmapFactory.decodeResource(context.getResources(), R.drawable.black_chess); //初始化胜利局数 whiteChessCount = 0; blackChessCount = 0; //初始化Rect rect = new Rect(); //设置点击监听 setOnTouchListener(this); //重置棋盘状态 for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { chessArray[i][j] = 0; } } } /** * 重新测量宽高,确保宽高一样 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //获取高宽值 int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); //获取宽高中较小的值 int len = width > height ? height : width; //重新设置宽高 setMeasuredDimension(len, len); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //棋盘为一个GRID_NUMBER*GRID_NUMBER的正方形,所有棋盘宽高必须一样 len = getWidth() > getHeight() ? getHeight() : getWidth(); preWidth = len / GRID_NUMBER; //边距 offset = preWidth / 2; //棋盘线条 for (int i = 0; i < GRID_NUMBER; i++) { float start = i * preWidth + offset; //横线 canvas.drawLine(offset, start, len - offset, start, paint); //竖线 canvas.drawLine(start, offset, start, len - offset, paint); } //绘制棋子 for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { //rect中点坐标 float rectX = offset + i * preWidth; float rectY = offset + j * preWidth; //设置rect位置 rect.set((int) (rectX - offset), (int) (rectY - offset), (int) (rectX + offset), (int) (rectY + offset)); //遍历chessArray switch (chessArray[i][j]) { case WHITE_CHESS: //绘制白棋 canvas.drawBitmap(whiteChess, null, rect, paint); break; case BLACK_CHESS: //绘制黑棋 canvas.drawBitmap(blackChess, null, rect, paint); break; } } } } /** * 判断是 <SUF>*/ private void checkGameOver() { //获取落子的颜色(如果当前是白棋,则落子是黑棋) int chess = isWhite ? BLACK_CHESS : WHITE_CHESS; //棋盘是否填满 boolean isFull = true; //遍历chessArray for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { //判断棋盘是否填满 if (chessArray[i][j] != BLACK_CHESS && chessArray[i][j] != WHITE_CHESS) { isFull = false; } //只需要判断落子是否五连即可 if (chessArray[i][j] == chess) { //判断五子相连 if (isFiveSame(i, j)) { //五子相连游戏结束 isGameOver = true; if (callBack != null) { //判断黑白棋胜利 if (chess == WHITE_CHESS) { whiteChessCount++; } else { blackChessCount++; } //判断玩家/AI 胜利 if (userChess == chess) { userScore++; } else { aiScore++; } callBack.GameOver(chess == WHITE_CHESS ? WHITE_WIN : BLACK_WIN); } return; } } } } //如果棋盘填满,平局结束 if (isFull) { isGameOver = true; if (callBack != null) { callBack.GameOver(NO_WIN); } } } /** * 重置游戏 */ public void resetGame() { isGameOver = false; //重置棋盘状态 for (int i = 0; i < GRID_NUMBER; i++) { for (int j = 0; j < GRID_NUMBER; j++) { chessArray[i][j] = 0; } } //更新UI postInvalidate(); } /** * 判断是否存在五子相连 * * @return */ private boolean isFiveSame(int x, int y) { //判断横向 if (x + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x + 1][y] && chessArray[x][y] == chessArray[x + 2][y] && chessArray[x][y] == chessArray[x + 3][y] && chessArray[x][y] == chessArray[x + 4][y]) { return true; } } //判断纵向 if (y + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x][y + 1] && chessArray[x][y] == chessArray[x][y + 2] && chessArray[x][y] == chessArray[x][y + 3] && chessArray[x][y] == chessArray[x][y + 4]) { return true; } } //判断斜向(左上到右下) if (y + 4 < GRID_NUMBER && x + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x + 1][y + 1] && chessArray[x][y] == chessArray[x + 2][y + 2] && chessArray[x][y] == chessArray[x + 3][y + 3] && chessArray[x][y] == chessArray[x + 4][y + 4]) { return true; } } //判断斜向(左下到右上) if (y - 4 > 0 && x + 4 < GRID_NUMBER) { if (chessArray[x][y] == chessArray[x + 1][y - 1] && chessArray[x][y] == chessArray[x + 2][y - 2] && chessArray[x][y] == chessArray[x + 3][y - 3] && chessArray[x][y] == chessArray[x + 4][y - 4]) { return true; } } return false; } //电脑判断游戏结束 public void checkAiGameOver() { isWhite = userChess == WHITE_CHESS; checkGameOver(); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (!isGameOver && isUserBout) { //获取按下时的位置 float downX = event.getX(); float downY = event.getY(); //点击的位置在棋盘上 if (downX >= offset / 2 && downX <= len - offset / 2 && downY >= offset / 2 && downY <= len - offset / 2) { //获取棋子对应的位置 int x = (int) (downX / preWidth); int y = (int) (downY / preWidth); //判断当前位置是否已经有子 if (chessArray[x][y] != WHITE_CHESS && chessArray[x][y] != BLACK_CHESS) { //给数组赋值 chessArray[x][y] = userChess; //修改当前落子颜色 isWhite = userChess == WHITE_CHESS; //修改当前为电脑执子 isUserBout = false; //更新棋盘 postInvalidate(); //判断是否结束 checkGameOver(); //回调当前执子 if (callBack != null) { callBack.ChangeGamer(isWhite); } } } } else if (isGameOver) { Toast.makeText(getContext(), "游戏已经结束,请重新开始!", Toast.LENGTH_SHORT).show(); } break; } return false; } public void setCallBack(GameCallBack callBack) { this.callBack = callBack; } public int getWhiteChessCount() { return whiteChessCount; } public int getBlackChessCount() { return blackChessCount; } public int[][] getChessArray() { return chessArray; } public void setUserBout(boolean userBout) { isUserBout = userBout; } public void setUserChess(int userChess) { this.userChess = userChess; } public int getUserScore() { return userScore; } public int getAiScore() { return aiScore; } }
false
2,646
10
2,950
8
3,003
10
2,949
8
3,771
16
false
false
false
false
false
true
45532_8
package com.dong.dongweather.gson; import com.google.gson.annotations.SerializedName; /** * Created by Administrator on 2017/4/18. */ public class Now { //天气状况 @SerializedName("cond") public WeatherRegime weatherRegime; public class WeatherRegime { public String code; public String txt; } //体感温度 public String fl; //相对湿度 public String hum; //降水量 @SerializedName("pcpn") public String mypcpn; //气压 public String pres; //温度 public String tmp; //能见度 public String vis; public Wind wind; public class Wind { //风向(360)度 public String deg; //风向,八个大方向(西北风) public String dir; //风力等级 public String sc; //风速 public String spd; } // // "now": { //实况天气 // "cond": { //天气状况 // "code": "104", //天气状况代码 // "txt": "阴" //天气状况描述 // }, // "fl": "11", //体感温度 // "hum": "31", //相对湿度(%) // "pcpn": "0", //降水量(mm) // "pres": "1025", //气压 // "tmp": "13", //温度 // "vis": "10", //能见度(km) // "wind": { //风力风向 // "deg": "40", //风向(360度) // "dir": "东北风", //风向 // "sc": "4-5", //风力 // "spd": "24" //风速(kmph) // } // }, }
LuoPeiQin/DongWeather
app/src/main/java/com/dong/dongweather/gson/Now.java
493
//风力等级
line_comment
zh-cn
package com.dong.dongweather.gson; import com.google.gson.annotations.SerializedName; /** * Created by Administrator on 2017/4/18. */ public class Now { //天气状况 @SerializedName("cond") public WeatherRegime weatherRegime; public class WeatherRegime { public String code; public String txt; } //体感温度 public String fl; //相对湿度 public String hum; //降水量 @SerializedName("pcpn") public String mypcpn; //气压 public String pres; //温度 public String tmp; //能见度 public String vis; public Wind wind; public class Wind { //风向(360)度 public String deg; //风向,八个大方向(西北风) public String dir; //风力 <SUF> public String sc; //风速 public String spd; } // // "now": { //实况天气 // "cond": { //天气状况 // "code": "104", //天气状况代码 // "txt": "阴" //天气状况描述 // }, // "fl": "11", //体感温度 // "hum": "31", //相对湿度(%) // "pcpn": "0", //降水量(mm) // "pres": "1025", //气压 // "tmp": "13", //温度 // "vis": "10", //能见度(km) // "wind": { //风力风向 // "deg": "40", //风向(360度) // "dir": "东北风", //风向 // "sc": "4-5", //风力 // "spd": "24" //风速(kmph) // } // }, }
false
448
4
493
5
491
4
493
5
630
9
false
false
false
false
false
true
26193_11
package cn.mailu.LushX.constant; public enum VideoTypeEnum { YK_TV_HOT(1), // 优酷-电视剧 YK_MOVIE_HOT(2), // 优酷-电影 YK_ZY_HOT(3), // 优酷-综艺 YK_DM_HOT(4),//优酷-动漫 YK_TV_NEW(5), // 优酷-电视剧 YK_MOVIE_NEW(6), // 优酷-电影 YK_ZY_NEW(7), // 优酷-综艺 YK_DM_NEW(8),//优酷-动漫 IQY_TV(11), // 爱奇艺-电视剧 IQY_MOVIE(12), // 爱奇艺-电影 IQY_ZY(13), // 爱奇艺-综艺 IQY_DM(14), // 爱奇艺-动漫 CL_SEARCH(20),//尘落-搜索 CL_TV_HOT(21),//~~-电视-最热 CL_MOVIES_HOT(22),//~~-电影-最热 CL_ZY_HOT(23),//~~-综艺-最热 CL_DM_HOT(24),//~~-动漫-最热 CL_TV_NEW(25),//~~-电视-最新 CL_MOVIES_NEW(26),//~~-电影-最新 CL_ZY_NEW(27),//~~-综艺-最新 CL_DM_NEW(28);//~~-动漫-最新 private int code; VideoTypeEnum(int code){ this.code = code; } public int getCode() { return code; } }
LushX/LushX-BE
src/main/java/cn/mailu/LushX/constant/VideoTypeEnum.java
442
// 爱奇艺-动漫
line_comment
zh-cn
package cn.mailu.LushX.constant; public enum VideoTypeEnum { YK_TV_HOT(1), // 优酷-电视剧 YK_MOVIE_HOT(2), // 优酷-电影 YK_ZY_HOT(3), // 优酷-综艺 YK_DM_HOT(4),//优酷-动漫 YK_TV_NEW(5), // 优酷-电视剧 YK_MOVIE_NEW(6), // 优酷-电影 YK_ZY_NEW(7), // 优酷-综艺 YK_DM_NEW(8),//优酷-动漫 IQY_TV(11), // 爱奇艺-电视剧 IQY_MOVIE(12), // 爱奇艺-电影 IQY_ZY(13), // 爱奇艺-综艺 IQY_DM(14), // 爱奇 <SUF> CL_SEARCH(20),//尘落-搜索 CL_TV_HOT(21),//~~-电视-最热 CL_MOVIES_HOT(22),//~~-电影-最热 CL_ZY_HOT(23),//~~-综艺-最热 CL_DM_HOT(24),//~~-动漫-最热 CL_TV_NEW(25),//~~-电视-最新 CL_MOVIES_NEW(26),//~~-电影-最新 CL_ZY_NEW(27),//~~-综艺-最新 CL_DM_NEW(28);//~~-动漫-最新 private int code; VideoTypeEnum(int code){ this.code = code; } public int getCode() { return code; } }
false
378
8
442
9
406
6
442
9
587
14
false
false
false
false
false
true
44332_12
package hw9; public class Hw9_2 { public static void main(String[] args) { Account account = new Account(); // 建立帳戶物件 Mom mom = new Mom(account); // 建立媽媽執行緒 Son son = new Son(account); // 建立熊大執行緒 mom.start(); son.start(); } } class Account{ private int balance = 0; //存款餘額 public Account() { } //媽媽進行存款 synchronized public void deposit(int money) { //餘額超過3000元,就會停止匯款給熊大 while (balance > 3000) { System.out.println("媽媽看到餘額在3000以上,暫停匯款"); try { System.out.println("熊大被老媽告知帳戶已經有錢!"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } balance += money; System.out.println("媽媽存了:" + money + ";帳戶共有:" + balance); notify(); //喚醒爭奪執行緒 } //熊大進行提款 synchronized void withdraw(int money) { //帳戶餘額低於熊大要提款的金額,熊大就會暫停提款 while (balance == 0) { System.out.println("熊大看到帳戶沒錢,暫停提款"); try { System.out.println("媽媽被熊大要求匯款!"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } balance -= money; System.out.println("熊大領了:" + money + ";帳戶共有" + balance); if (balance < 2000) { System.out.println("熊大看到餘額低於2000,要求匯款"); notify(); } } } // 媽媽執行存款 class Mom extends Thread { Account account; public Mom(Account account) { this.account = account; } public void run() { for (int i = 1; i <= 10; i++) { account.deposit(2000); // 每次存款2000元 } } } // 熊大執行緒,執行提款操作 class Son extends Thread { Account account; public Son(Account account) { this.account = account; } public void run() { for (int i = 1; i <= 10; i++) { account.withdraw(1000); // 每次提款一千元 } } }
Luuuirene/CIA101-Homework
src/hw9/Hw9_2.java
769
// 每次提款一千元
line_comment
zh-cn
package hw9; public class Hw9_2 { public static void main(String[] args) { Account account = new Account(); // 建立帳戶物件 Mom mom = new Mom(account); // 建立媽媽執行緒 Son son = new Son(account); // 建立熊大執行緒 mom.start(); son.start(); } } class Account{ private int balance = 0; //存款餘額 public Account() { } //媽媽進行存款 synchronized public void deposit(int money) { //餘額超過3000元,就會停止匯款給熊大 while (balance > 3000) { System.out.println("媽媽看到餘額在3000以上,暫停匯款"); try { System.out.println("熊大被老媽告知帳戶已經有錢!"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } balance += money; System.out.println("媽媽存了:" + money + ";帳戶共有:" + balance); notify(); //喚醒爭奪執行緒 } //熊大進行提款 synchronized void withdraw(int money) { //帳戶餘額低於熊大要提款的金額,熊大就會暫停提款 while (balance == 0) { System.out.println("熊大看到帳戶沒錢,暫停提款"); try { System.out.println("媽媽被熊大要求匯款!"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } balance -= money; System.out.println("熊大領了:" + money + ";帳戶共有" + balance); if (balance < 2000) { System.out.println("熊大看到餘額低於2000,要求匯款"); notify(); } } } // 媽媽執行存款 class Mom extends Thread { Account account; public Mom(Account account) { this.account = account; } public void run() { for (int i = 1; i <= 10; i++) { account.deposit(2000); // 每次存款2000元 } } } // 熊大執行緒,執行提款操作 class Son extends Thread { Account account; public Son(Account account) { this.account = account; } public void run() { for (int i = 1; i <= 10; i++) { account.withdraw(1000); // 每次 <SUF> } } }
false
618
8
769
8
696
7
769
8
1,023
11
false
false
false
false
false
true
8700_12
package com.lwk.familycontact.project.main.view; import android.content.Intent; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.View; import com.ashokvarma.bottomnavigation.BadgeItem; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.ashokvarma.bottomnavigation.BottomNavigationItem; import com.lib.base.widget.CommonActionBar; import com.lwk.familycontact.R; import com.lwk.familycontact.base.FCBaseActivity; import com.lwk.familycontact.project.common.version.CheckVersionUtils; import com.lwk.familycontact.project.common.version.VersionBean; import com.lwk.familycontact.project.contact.view.AddFriendActivity; import com.lwk.familycontact.project.contact.view.ContactFragment; import com.lwk.familycontact.project.conversation.view.ConversationFragment; import com.lwk.familycontact.project.dial.view.DialFragment; import com.lwk.familycontact.project.main.presenter.MainPresenter; import com.lwk.familycontact.project.profile.UserProfileActivity; import com.lwk.familycontact.project.setting.view.SettingActivity; import com.lwk.familycontact.utils.event.ComNotifyConfig; import com.lwk.familycontact.utils.event.ComNotifyEventBean; import com.lwk.familycontact.utils.event.EventBusHelper; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; /** * MainActivity * 管理三个主片段 */ public class MainActivity extends FCBaseActivity implements MainView , BottomNavigationBar.OnTabSelectedListener , MainMenuPop.onMenuClickListener { private MainPresenter mPresenter; private CommonActionBar mActionBar; private BottomNavigationBar mNavigationBar; private BadgeItem mBadge01; private BadgeItem mBadge02; private Fragment mCurFragment; private ConversationFragment mFragment01; private ContactFragment mFragment02; private DialFragment mFragment03; private MainMenuPop mMenuPop; @Override protected int setContentViewId() { mPresenter = new MainPresenter(this, mMainHandler); EventBusHelper.getInstance().regist(this); return R.layout.activity_main; } @Override protected void initUI() { mActionBar = findView(R.id.cab_main); mActionBar.setRightImgResource(R.drawable.ic_cab_plus_menu); mActionBar.setRightLayoutClickListener(this); mNavigationBar = findView(R.id.bnb_main); mBadge01 = createBadgeItem(); mBadge02 = createBadgeItem(); //这里真他妈扯淡! //源码中将firstSelectedPosition设置为0 //在navigationbar调用initialise()后就将firstSelectedPosition赋值给内部变量mSelectedPosition,但是不触发监听 //此时手动调用selectTab(0, true)时,监听里触发的不是onTabSelected(),而是他妈的onTabReselected()!!!! //所以想要在一开始默认选中第一个tab并且能触发监听里的onTabSelected(),就必须先将firstSelectedPosition设置为小于0的数 mNavigationBar.setFirstSelectedPosition(-1); mNavigationBar .addItem(createBottomNavigationItem(R.drawable.ic_tab_conversation, R.string.label_main_tab01).setBadgeItem(mBadge01)) .addItem(createBottomNavigationItem(R.drawable.ic_tab_contact, R.string.label_main_tab02).setBadgeItem(mBadge02)) .addItem(createBottomNavigationItem(R.drawable.ic_tab_dial, R.string.label_main_tab03)) .initialise(); mNavigationBar.setTabSelectedListener(this); //默认选中第一个tab mNavigationBar.selectTab(0, true); } //创建navigationbar的tab private BottomNavigationItem createBottomNavigationItem(@NonNull int imgResId, @NonNull int titleResId) { BottomNavigationItem navigationItem = new BottomNavigationItem(imgResId, titleResId); navigationItem.setActiveColorResource(R.color.bnbActiveColor); navigationItem.setInActiveColorResource(R.color.bnbInActiveColor); return navigationItem; } //创建tab的角标 private BadgeItem createBadgeItem() { BadgeItem badgeItem = new BadgeItem(); badgeItem.setHideOnSelect(false); badgeItem.setBorderColor(Color.WHITE); badgeItem.setBorderWidth(1); badgeItem.setGravity(Gravity.RIGHT | Gravity.TOP); badgeItem.setTextColor(Color.WHITE); badgeItem.setBackgroundColor(Color.RED); return badgeItem; } @Override protected void initData() { super.initData(); //刷新各Tab的角标 mPresenter.refreshLeftTabBadge(); mPresenter.refreshMiddleTabBadge(); } @Override protected void onStart() { super.onStart(); //检查版本更新 mPresenter.checkVersion(); } @Override protected void onClick(int id, View v) { switch (id) { case R.id.fl_common_actionbar_right: if (mMenuPop != null) { mMenuPop.dismiss(); mMenuPop = null; } mMenuPop = new MainMenuPop(this, this); mMenuPop.showAsDropDown(mActionBar.getRightLayout(), 0, 0); break; } } @Override public void onTabSelected(int position) { switch (position) { case 0: if (mFragment01 == null) mFragment01 = ConversationFragment.newInstance(); checkFragment(mFragment01); mActionBar.setTitleText(R.string.tv_main_actionbar_tab01); break; case 1: if (mFragment02 == null) mFragment02 = ContactFragment.newInstance(); checkFragment(mFragment02); mActionBar.setTitleText(R.string.tv_main_actionbar_tab02); break; case 2: if (mFragment03 == null) mFragment03 = DialFragment.newInstance(); checkFragment(mFragment03); mActionBar.setTitleText(R.string.tv_main_actionbar_tab03); break; } } @Override public void onTabUnselected(int position) { } @Override public void onTabReselected(int position) { switch (position) { case 1: mFragment02.scrollToTop(); break; case 2: mFragment01.scrollToTop(); break; } } //切换片段的方法 private void checkFragment(Fragment fragment) { //第一次加载片段 if (mCurFragment == null) { getSupportFragmentManager().beginTransaction().replace(R.id.ll_main_container, fragment).commit(); mCurFragment = fragment; return; } //相同的tab不做操作 if (mCurFragment == fragment) { return; } else { if (fragment.isAdded()) getSupportFragmentManager().beginTransaction() .hide(mCurFragment).show(fragment).commit(); else getSupportFragmentManager().beginTransaction() .hide(mCurFragment).add(R.id.ll_main_container, fragment).commit(); mCurFragment = fragment; } } @Override public void onBackPressed() { moveTaskToBack(true); } @Override public void onClickProfile() { startActivity(new Intent(MainActivity.this, UserProfileActivity.class)); } @Override public void onClickAddUser() { startActivity(new Intent(MainActivity.this, AddFriendActivity.class)); } @Override public void onClickSetting() { startActivity(new Intent(MainActivity.this, SettingActivity.class)); } @Override protected void onDestroy() { EventBusHelper.getInstance().unregist(this); super.onDestroy(); } @Override public void onShowFirstBadgeNum(int num) { if (mBadge01 != null) { mBadge01.show(); mBadge01.setText(String.valueOf(num)); } } @Override public void onHideFirstBadgeNum() { if (mBadge01 != null) mBadge01.hide(); } @Override public void onShowMiddleBadgeNum(int num) { if (mBadge02 != null) { mBadge02.setText(String.valueOf(num)); mBadge02.show(); } } @Override public void onHideMiddleBadgeNum() { if (mBadge02 != null) mBadge02.hide(); } @Override public void showVersionDialog(VersionBean versionBean) { CheckVersionUtils.getInstance().showVersionDialog(this, versionBean); } @Subscribe(threadMode = ThreadMode.MAIN) public void onNotifyEventReceived(ComNotifyEventBean eventBean) { switch (eventBean.getFlag()) { case ComNotifyConfig.REFRESH_USER_INVITE: mPresenter.refreshMiddleTabBadge(); break; case ComNotifyConfig.REFRESH_UNREAD_MSG: mPresenter.refreshLeftTabBadge(); break; } } }
LwkCoder/FamilyChat
app/src/main/java/com/lwk/familycontact/project/main/view/MainActivity.java
2,274
//第一次加载片段
line_comment
zh-cn
package com.lwk.familycontact.project.main.view; import android.content.Intent; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.View; import com.ashokvarma.bottomnavigation.BadgeItem; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.ashokvarma.bottomnavigation.BottomNavigationItem; import com.lib.base.widget.CommonActionBar; import com.lwk.familycontact.R; import com.lwk.familycontact.base.FCBaseActivity; import com.lwk.familycontact.project.common.version.CheckVersionUtils; import com.lwk.familycontact.project.common.version.VersionBean; import com.lwk.familycontact.project.contact.view.AddFriendActivity; import com.lwk.familycontact.project.contact.view.ContactFragment; import com.lwk.familycontact.project.conversation.view.ConversationFragment; import com.lwk.familycontact.project.dial.view.DialFragment; import com.lwk.familycontact.project.main.presenter.MainPresenter; import com.lwk.familycontact.project.profile.UserProfileActivity; import com.lwk.familycontact.project.setting.view.SettingActivity; import com.lwk.familycontact.utils.event.ComNotifyConfig; import com.lwk.familycontact.utils.event.ComNotifyEventBean; import com.lwk.familycontact.utils.event.EventBusHelper; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; /** * MainActivity * 管理三个主片段 */ public class MainActivity extends FCBaseActivity implements MainView , BottomNavigationBar.OnTabSelectedListener , MainMenuPop.onMenuClickListener { private MainPresenter mPresenter; private CommonActionBar mActionBar; private BottomNavigationBar mNavigationBar; private BadgeItem mBadge01; private BadgeItem mBadge02; private Fragment mCurFragment; private ConversationFragment mFragment01; private ContactFragment mFragment02; private DialFragment mFragment03; private MainMenuPop mMenuPop; @Override protected int setContentViewId() { mPresenter = new MainPresenter(this, mMainHandler); EventBusHelper.getInstance().regist(this); return R.layout.activity_main; } @Override protected void initUI() { mActionBar = findView(R.id.cab_main); mActionBar.setRightImgResource(R.drawable.ic_cab_plus_menu); mActionBar.setRightLayoutClickListener(this); mNavigationBar = findView(R.id.bnb_main); mBadge01 = createBadgeItem(); mBadge02 = createBadgeItem(); //这里真他妈扯淡! //源码中将firstSelectedPosition设置为0 //在navigationbar调用initialise()后就将firstSelectedPosition赋值给内部变量mSelectedPosition,但是不触发监听 //此时手动调用selectTab(0, true)时,监听里触发的不是onTabSelected(),而是他妈的onTabReselected()!!!! //所以想要在一开始默认选中第一个tab并且能触发监听里的onTabSelected(),就必须先将firstSelectedPosition设置为小于0的数 mNavigationBar.setFirstSelectedPosition(-1); mNavigationBar .addItem(createBottomNavigationItem(R.drawable.ic_tab_conversation, R.string.label_main_tab01).setBadgeItem(mBadge01)) .addItem(createBottomNavigationItem(R.drawable.ic_tab_contact, R.string.label_main_tab02).setBadgeItem(mBadge02)) .addItem(createBottomNavigationItem(R.drawable.ic_tab_dial, R.string.label_main_tab03)) .initialise(); mNavigationBar.setTabSelectedListener(this); //默认选中第一个tab mNavigationBar.selectTab(0, true); } //创建navigationbar的tab private BottomNavigationItem createBottomNavigationItem(@NonNull int imgResId, @NonNull int titleResId) { BottomNavigationItem navigationItem = new BottomNavigationItem(imgResId, titleResId); navigationItem.setActiveColorResource(R.color.bnbActiveColor); navigationItem.setInActiveColorResource(R.color.bnbInActiveColor); return navigationItem; } //创建tab的角标 private BadgeItem createBadgeItem() { BadgeItem badgeItem = new BadgeItem(); badgeItem.setHideOnSelect(false); badgeItem.setBorderColor(Color.WHITE); badgeItem.setBorderWidth(1); badgeItem.setGravity(Gravity.RIGHT | Gravity.TOP); badgeItem.setTextColor(Color.WHITE); badgeItem.setBackgroundColor(Color.RED); return badgeItem; } @Override protected void initData() { super.initData(); //刷新各Tab的角标 mPresenter.refreshLeftTabBadge(); mPresenter.refreshMiddleTabBadge(); } @Override protected void onStart() { super.onStart(); //检查版本更新 mPresenter.checkVersion(); } @Override protected void onClick(int id, View v) { switch (id) { case R.id.fl_common_actionbar_right: if (mMenuPop != null) { mMenuPop.dismiss(); mMenuPop = null; } mMenuPop = new MainMenuPop(this, this); mMenuPop.showAsDropDown(mActionBar.getRightLayout(), 0, 0); break; } } @Override public void onTabSelected(int position) { switch (position) { case 0: if (mFragment01 == null) mFragment01 = ConversationFragment.newInstance(); checkFragment(mFragment01); mActionBar.setTitleText(R.string.tv_main_actionbar_tab01); break; case 1: if (mFragment02 == null) mFragment02 = ContactFragment.newInstance(); checkFragment(mFragment02); mActionBar.setTitleText(R.string.tv_main_actionbar_tab02); break; case 2: if (mFragment03 == null) mFragment03 = DialFragment.newInstance(); checkFragment(mFragment03); mActionBar.setTitleText(R.string.tv_main_actionbar_tab03); break; } } @Override public void onTabUnselected(int position) { } @Override public void onTabReselected(int position) { switch (position) { case 1: mFragment02.scrollToTop(); break; case 2: mFragment01.scrollToTop(); break; } } //切换片段的方法 private void checkFragment(Fragment fragment) { //第一 <SUF> if (mCurFragment == null) { getSupportFragmentManager().beginTransaction().replace(R.id.ll_main_container, fragment).commit(); mCurFragment = fragment; return; } //相同的tab不做操作 if (mCurFragment == fragment) { return; } else { if (fragment.isAdded()) getSupportFragmentManager().beginTransaction() .hide(mCurFragment).show(fragment).commit(); else getSupportFragmentManager().beginTransaction() .hide(mCurFragment).add(R.id.ll_main_container, fragment).commit(); mCurFragment = fragment; } } @Override public void onBackPressed() { moveTaskToBack(true); } @Override public void onClickProfile() { startActivity(new Intent(MainActivity.this, UserProfileActivity.class)); } @Override public void onClickAddUser() { startActivity(new Intent(MainActivity.this, AddFriendActivity.class)); } @Override public void onClickSetting() { startActivity(new Intent(MainActivity.this, SettingActivity.class)); } @Override protected void onDestroy() { EventBusHelper.getInstance().unregist(this); super.onDestroy(); } @Override public void onShowFirstBadgeNum(int num) { if (mBadge01 != null) { mBadge01.show(); mBadge01.setText(String.valueOf(num)); } } @Override public void onHideFirstBadgeNum() { if (mBadge01 != null) mBadge01.hide(); } @Override public void onShowMiddleBadgeNum(int num) { if (mBadge02 != null) { mBadge02.setText(String.valueOf(num)); mBadge02.show(); } } @Override public void onHideMiddleBadgeNum() { if (mBadge02 != null) mBadge02.hide(); } @Override public void showVersionDialog(VersionBean versionBean) { CheckVersionUtils.getInstance().showVersionDialog(this, versionBean); } @Subscribe(threadMode = ThreadMode.MAIN) public void onNotifyEventReceived(ComNotifyEventBean eventBean) { switch (eventBean.getFlag()) { case ComNotifyConfig.REFRESH_USER_INVITE: mPresenter.refreshMiddleTabBadge(); break; case ComNotifyConfig.REFRESH_UNREAD_MSG: mPresenter.refreshLeftTabBadge(); break; } } }
false
1,935
5
2,248
7
2,428
5
2,248
7
2,789
9
false
false
false
false
false
true
11105_7
package com.lyd.wx.task; import com.lyd.wx.pojo.*; import com.lyd.wx.uitls.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.text.ParseException; /** * 描述: * * @author liyadong * @create 2022-08-22-16:21-周一 */ @Component public class Send { @Autowired RestTemplate restTemplate; @Autowired MyWx wx; /** * 发送天气数据 * @param token * @param w * @throws ParseException */ public void send1(String token, Weather w, String userid) throws ParseException { String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; String c1="#fdcbf1"; SendJson sendJson = new SendJson(); sendJson.setTouser(userid); sendJson.setTemplate_id(wx.getTempateid1()); sendJson.setTopcolor(c1); //数据 SendData sendData = new SendData(); //城市和日期 sendData.setCity(new Item(w.getCity(),"#f093fb")); sendData.setDate(new Item(w.getDate(),"#f093fb")); sendData.setWeek(new Item(w.getWeek(),"#f093fb")); //关于空气 sendData.setAir(new Item(w.getAir(),"#0acffe")); sendData.setAir_level(new Item(w.getAir_level(),"#0acffe")); sendData.setAir_pm25(new Item(w.getAir_pm25(),"#0acffe")); sendData.setHumidity(new Item(w.getHumidity(),"#0acffe")); sendData.setAir_tips(new Item(w.getAir_tips(),"#0acffe")); sendData.setPressure(new Item(w.getPressure(),"#0acffe")); sendData.setVisibility(new Item(w.getVisibility(),"#0acffe")); //关于温度天气 sendData.setTem1(new Item(w.getTem1(),"#f43b47")); sendData.setTem2(new Item(w.getTem2(),"#f43b47")); sendData.setWea(new Item(w.getWea(),"#f43b47")); //关于风 sendData.setWin_meter(new Item(w.getWin_meter(),"#88d3ce")); sendData.setWin_speed(new Item(w.getWin_speed(),"#88d3ce")); sendData.setWin(new Item(w.getWin(),"#88d3ce")); //附加数据 sendData.setTxt1(new Item("亲爱的乖乖宝贝,早上好! (๑•̀ㅂ•́)و✧记得按时吃早饭午饭晚饭。今天也要开心哦ヽ(✿゚▽゚)ノ","#ff7eb3")); sendData.setTxt2(new Item("下面由我来给你播报一下今天的天气状况╰(*°▽°*)╯","#f09819")); //发送请求 sendJson.setData(sendData); String s = restTemplate.postForObject(url, sendJson, String.class); System.out.println(s); } /** * 发送纪念日数据 * @param token */ public void send2(String token,String userid) throws ParseException { String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; String c1="#fdcbf1"; SendJson sendJson = new SendJson(); sendJson.setTouser(userid); sendJson.setTemplate_id(wx.getTempateid2()); sendJson.setTopcolor(c1); SendData sd = new SendData(); //距离认识多少天 sd.setDay1(new Item(DateUtils.dayForLastDay(wx.getDay1()),"#fee140")); //距离在一起多少天 sd.setDay2(new Item(DateUtils.dayForLastDay(wx.getDay2()),"#fee140")); //距离我生日多少天 sd.setDay3(new Item(DateUtils.dayToBirthday(wx.getDay3()),"#fee140")); //距离宝贝生日多少天 sd.setDay4(new Item(DateUtils.dayToBirthday(wx.getDay4()),"#fee140")); //距离我出生多少天 sd.setDay5(new Item(DateUtils.dayForLastDay(wx.getDay3()),"#fee140")); //距离宝贝出生多少天 sd.setDay6(new Item(DateUtils.dayForLastDay(wx.getDay4()),"#fee140")); //附加文本数据 sd.setTxt1(new Item("宝贝,今天也很爱你哦(*/ω\*)","#cd9cf2")); sd.setTxt2(new Item("还有很长的日子,要一直陪你走下去 *′∀`)′∀`)*′∀`)*′∀`)","#cd9cf2")); sendJson.setData(sd); String s = restTemplate.postForObject(url, sendJson, String.class); System.out.println(s); } /** * 事件提醒 * 可以设置三句话,不同颜色,t文本,c颜色 */ public void send3(String token,String userid,String t1,String c1,String t2,String c2,String t3,String c3){ String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; String c="#fdcbf1"; SendJson sendJson = new SendJson(); sendJson.setTouser(userid); sendJson.setTemplate_id(wx.getTempateid3()); sendJson.setTopcolor(c); SendData sd = new SendData(); sd.setTxt1(new Item(t1,c1)); sd.setTxt2(new Item(t2,c2)); sd.setTxt3(new Item(t3,c3)); sendJson.setData(sd); String s = restTemplate.postForObject(url, sendJson, String.class); System.out.println(s); } }
Lyd889911/wx
src/main/java/com/lyd/wx/task/Send.java
1,602
//附加数据
line_comment
zh-cn
package com.lyd.wx.task; import com.lyd.wx.pojo.*; import com.lyd.wx.uitls.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.text.ParseException; /** * 描述: * * @author liyadong * @create 2022-08-22-16:21-周一 */ @Component public class Send { @Autowired RestTemplate restTemplate; @Autowired MyWx wx; /** * 发送天气数据 * @param token * @param w * @throws ParseException */ public void send1(String token, Weather w, String userid) throws ParseException { String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; String c1="#fdcbf1"; SendJson sendJson = new SendJson(); sendJson.setTouser(userid); sendJson.setTemplate_id(wx.getTempateid1()); sendJson.setTopcolor(c1); //数据 SendData sendData = new SendData(); //城市和日期 sendData.setCity(new Item(w.getCity(),"#f093fb")); sendData.setDate(new Item(w.getDate(),"#f093fb")); sendData.setWeek(new Item(w.getWeek(),"#f093fb")); //关于空气 sendData.setAir(new Item(w.getAir(),"#0acffe")); sendData.setAir_level(new Item(w.getAir_level(),"#0acffe")); sendData.setAir_pm25(new Item(w.getAir_pm25(),"#0acffe")); sendData.setHumidity(new Item(w.getHumidity(),"#0acffe")); sendData.setAir_tips(new Item(w.getAir_tips(),"#0acffe")); sendData.setPressure(new Item(w.getPressure(),"#0acffe")); sendData.setVisibility(new Item(w.getVisibility(),"#0acffe")); //关于温度天气 sendData.setTem1(new Item(w.getTem1(),"#f43b47")); sendData.setTem2(new Item(w.getTem2(),"#f43b47")); sendData.setWea(new Item(w.getWea(),"#f43b47")); //关于风 sendData.setWin_meter(new Item(w.getWin_meter(),"#88d3ce")); sendData.setWin_speed(new Item(w.getWin_speed(),"#88d3ce")); sendData.setWin(new Item(w.getWin(),"#88d3ce")); //附加 <SUF> sendData.setTxt1(new Item("亲爱的乖乖宝贝,早上好! (๑•̀ㅂ•́)و✧记得按时吃早饭午饭晚饭。今天也要开心哦ヽ(✿゚▽゚)ノ","#ff7eb3")); sendData.setTxt2(new Item("下面由我来给你播报一下今天的天气状况╰(*°▽°*)╯","#f09819")); //发送请求 sendJson.setData(sendData); String s = restTemplate.postForObject(url, sendJson, String.class); System.out.println(s); } /** * 发送纪念日数据 * @param token */ public void send2(String token,String userid) throws ParseException { String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; String c1="#fdcbf1"; SendJson sendJson = new SendJson(); sendJson.setTouser(userid); sendJson.setTemplate_id(wx.getTempateid2()); sendJson.setTopcolor(c1); SendData sd = new SendData(); //距离认识多少天 sd.setDay1(new Item(DateUtils.dayForLastDay(wx.getDay1()),"#fee140")); //距离在一起多少天 sd.setDay2(new Item(DateUtils.dayForLastDay(wx.getDay2()),"#fee140")); //距离我生日多少天 sd.setDay3(new Item(DateUtils.dayToBirthday(wx.getDay3()),"#fee140")); //距离宝贝生日多少天 sd.setDay4(new Item(DateUtils.dayToBirthday(wx.getDay4()),"#fee140")); //距离我出生多少天 sd.setDay5(new Item(DateUtils.dayForLastDay(wx.getDay3()),"#fee140")); //距离宝贝出生多少天 sd.setDay6(new Item(DateUtils.dayForLastDay(wx.getDay4()),"#fee140")); //附加文本数据 sd.setTxt1(new Item("宝贝,今天也很爱你哦(*/ω\*)","#cd9cf2")); sd.setTxt2(new Item("还有很长的日子,要一直陪你走下去 *′∀`)′∀`)*′∀`)*′∀`)","#cd9cf2")); sendJson.setData(sd); String s = restTemplate.postForObject(url, sendJson, String.class); System.out.println(s); } /** * 事件提醒 * 可以设置三句话,不同颜色,t文本,c颜色 */ public void send3(String token,String userid,String t1,String c1,String t2,String c2,String t3,String c3){ String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; String c="#fdcbf1"; SendJson sendJson = new SendJson(); sendJson.setTouser(userid); sendJson.setTemplate_id(wx.getTempateid3()); sendJson.setTopcolor(c); SendData sd = new SendData(); sd.setTxt1(new Item(t1,c1)); sd.setTxt2(new Item(t2,c2)); sd.setTxt3(new Item(t3,c3)); sendJson.setData(sd); String s = restTemplate.postForObject(url, sendJson, String.class); System.out.println(s); } }
false
1,264
3
1,602
4
1,571
3
1,602
4
1,940
7
false
false
false
false
false
true
47829_0
public boolean offer(E e){ if(e==NULL) throw new NullPointerException; modCount++; int i=size; if(i>queue.length) grow(i+1); //自动扩容 size=i+1; if(i==0) queue[0]=e; else shiftUp(i,e); return true; } //从k指定的位置开始,将x逐层与当前点的parent进行比较并交换,直到满足x >= queue[parent]为止 private void shiftUp(int k,E x){ while(k>0){ int parent=(k-1)>>>1; //parent=(nodeNo-1)/2 Object e=queue[parent]; if(comparator.compare(x,(E) e)>=0) break; queue[k]=e; k=parent; } queue[k]=x; } public E poll(){ if(size==0) return null; int s=--size; modCount++; E result=(E)queue[0]; E x=(E)queue[s]; queue[s]=null; if(s!=0) shiftDown(0,x); return result; } private void shiftDown(int k,E x){ int half=size>>>1; while(k<half){ int child=(k<<1)+1; //leftNo=parentNo*2+1 Object c=queue[child]; int right=child+1; if(right<size && comparator.compare((E)c,(E) queue[right])>0) c=queue[child=right]; if(comparator.compare(x,(E) c)<=0) break; queue[k]=c; k=child; } queue[k]=x; } public E peek(){ if(size==0) return null; return queue[0]; }
Lyon-NEU/Java_Learn_old
collections/PriorityQueue.java
501
//自动扩容
line_comment
zh-cn
public boolean offer(E e){ if(e==NULL) throw new NullPointerException; modCount++; int i=size; if(i>queue.length) grow(i+1); //自动 <SUF> size=i+1; if(i==0) queue[0]=e; else shiftUp(i,e); return true; } //从k指定的位置开始,将x逐层与当前点的parent进行比较并交换,直到满足x >= queue[parent]为止 private void shiftUp(int k,E x){ while(k>0){ int parent=(k-1)>>>1; //parent=(nodeNo-1)/2 Object e=queue[parent]; if(comparator.compare(x,(E) e)>=0) break; queue[k]=e; k=parent; } queue[k]=x; } public E poll(){ if(size==0) return null; int s=--size; modCount++; E result=(E)queue[0]; E x=(E)queue[s]; queue[s]=null; if(s!=0) shiftDown(0,x); return result; } private void shiftDown(int k,E x){ int half=size>>>1; while(k<half){ int child=(k<<1)+1; //leftNo=parentNo*2+1 Object c=queue[child]; int right=child+1; if(right<size && comparator.compare((E)c,(E) queue[right])>0) c=queue[child=right]; if(comparator.compare(x,(E) c)<=0) break; queue[k]=c; k=child; } queue[k]=x; } public E peek(){ if(size==0) return null; return queue[0]; }
false
380
4
501
5
496
5
501
5
557
8
false
false
false
false
false
true
20750_19
package util; public final class MessageType { public MessageType() { // TODO Auto-generated constructor stub } //Message-Type public static final String operFeedback = "OPER_FEEDBACK"; //管理员:管理用户 public static final String outputAllStudent = "OUTPUT_ALL_STUDENT"; public static final String outputAllTeacher = "OUTPUT_ALL_TEACHER"; public static final String outputAllRetailer = "OUTPUT_ALL_RETAILER"; public static final String outputAllDoctor = "OUTPUT_ALL_DOCTOR"; public static final String addStudent = "ADD_STUDENT"; public static final String deleteStudent = "DELETE_STUDENT"; public static final String updateStudent = "UPDATE_STUDENT"; public static final String queryStudent = "QUERY_STUDENT"; public static final String queryStudentByMajor = "QUERY_STUDENT_BY_MAJOR"; public static final String addTeacher = "ADD_TEACHER"; public static final String deleteTeacher = "DELETE_TEACHER"; public static final String updateTeacher = "UPDATE_TEACHER"; public static final String queryTeacher = "QUERY_TEACHER"; public static final String addRetailer = "ADD_RETAILER"; public static final String deleteRetailer = "DELETE_RETAILER"; public static final String updateRetailer = "UPDATE_RETAILER"; public static final String queryRetailer = "QUERY_RETAILER"; public static final String addDoctor = "ADD_DOCTOR"; public static final String deleteDoctor = "DELETE_DOCTOR"; public static final String updateDoctor = "UPDATE_DOCTOR"; public static final String queryDoctor = "QUERY_DOCTOR"; //用户操作 public static final String userLogin = "USER_LOGIN"; public static final String register = "REGISTER"; //图书馆 public static final String outputallbooks = "OUTPUT_ALL_BOOKS";//返回所有书目 public static final String outputallbooksbystudy="OUTPUT_ALL_BOOKS_BYSTUDY";//学业书籍推荐 public static final String outputallbooksbyhappy="OUTPUT_ALL_BOOKS_BYHAPPY";//休闲书籍推荐 public static final String outputbyindistinctsearch="OUTPUT_BY_INDISTINCTSEARCH";//模糊查询 public static final String outputbybookidsearch="OUTPUT_BY_BOOKIDSEARCH";//通过书ID查询 public static final String outputbybooknamesearch="OUTPUT_BY_BOOKNAMESEARCH";//通过书名查询 public static final String outputbybookauthorsearch="OUTPUT_BY_BOOKAUTHORSEARCH";//通过书的作者查询 public static final String outputbysearchbyrecordstudentidisreturn="OUTPUT_BY_SEARCHBYRECORDSTUDENTIDISRETURN";//返回我的已还 public static final String outputbysearchbyrecordstudentidnotreturn="OUTPUT_BY_SEARCHBYRECORDSTUDENTIDNOTRETURN";//返回我的待还 public static final String outputbysearchbyrecordid="OUTPUTBYSEARCHBYRECORDID"; public static final String insertbook="INSERT_BOOK";//插入书 public static final String deletelibbook="DELETE_LIBBOOK";//删除书 public static final String updatebook="UPDATE_BOOK";//更新书的信息 public static final String returnbook="RETURN_BOOK";//还书 public static final String lendbook="LEND_BOOK";//借书 //商店 public static final String shopQuery = "SHOP_QUERY";//查询商品 public static final String shopInit = "SHOP_INIT";//查询所有 public static final String Buy = "BUY";//购买 public static final String PurchaseRecordQuery = "PURCHASERECORD_QUERY";//查询购买记录 public static final String SellingRecordQuery = "SELLINGRECORD_QUERY";//查询售出记录 public static final String Score = "SCORE"; public static final String shop_queryStudent = "SHOP_QUERYSTUDENT"; public static final String shop_queryRetailer = "SHOP_QUERYRETAILER"; public static final String add_product = "ADD_PRODUCT"; //课程 public static final String course_query = "COURSE_QUERY";//返回所有查询学期的课(学生 public static final String course_query_admin = "COURSE_QUERY_ADMIN";//返回所有查询学期的课(管理员(所有课 public static final String course_init = "COURSE_INIT"; //返回所有本学期的课 public static final String course_choose = "COURSE_CHOOSE";//学生选课,grade表插入记录 public static final String course_my_table = "COURSE_MYTABLE";//返回该学生该学期的课 public static final String course_giveup = "COURSE_GIVEUP";//退课 public static final String course_query_grade = "COURSE_QUERY_GRADE";//查成绩 public static final String course_teacher_table = "COURSE_TEACHER_TABLE";//老师课程表 public static final String course_studentList_query = "COURSE_STUDENTLIST_QUERY";//查询该门课程有哪些学生选择 public static final String course_grade_add = "COURSE_GRADE_ADD";//登成绩 public static final String course_query_course = "COURSE_QUERY_COURSE";//查一门课 public static final String course_exam_add = "COURSE_EXAM_ADD";//发布考试 public static final String course_add = "COURSE_ADD";//管理员加课 //银行 public static final String record_Query = "RECORD_QUERY";//查询交易明细 public static final String phone_Pay = "PHONE_PAY";//支付手机流量包 public static final String wifi_Pay = "WIFI_PAY";//支付校园网套餐 public static final String tuition_Pay = "TUITION_PAY";//支付学费 public static final String card_Invest = "CARD_INVEST";//对一卡通进行充值 public static final String account_Query = "ACCOUNT_QUERY";//查询具体账单金额 //场馆 public static final String place_query_all = "PLACE_QUERY_ALL";//查询场馆列表的公共入口 public static final String place_ap_insert = "PLACE_AP_INSERT";//新增场馆预约 public static final String place_ap_query = "PLACE_AP_QUERY";//场馆预约记录查询(按照场馆 public static final String stu_ap_query = "STU_AP_QUERY";//场馆预约记录查询(按照学生 public static final String place_ap_delete = "PLACE_AP_DELETE";//场馆预约记录取消 public static final String place_query_by_name = "PLACE_QUERY_BY_NAME";//查询特定场馆 //医院 public static final String doc_query_all = "DOC_QUERY_ALL";//返回所有医生(医生表 public static final String doc_query_doc = "DOC_QUERY_DOC";//返回指定医生(医生表 public static final String stu_advice_query_stu = "STU_ADVICE_QUERY_STU";//返回指定学生的咨询记录(咨询记录表 public static final String stu_advice_query_doc = "STU_ADVICE_QUERY_DOC";//返回指定医生的咨询记录(咨询记录表 public static final String stu_res_query = "STU_RES_QUERY";//返回指定学生的挂号记录(挂号记录表 public static final String stu_advice_insert = "STU_ADVICE_INSERT";//增加一条记录(咨询记录表 public static final String stu_res_insert = "STU_RES_INSERT";//增加一条记录(挂号记录表 public static final String stu_advice_query_relevant = "STU_ADVICE_QUERY_RELEVANT";//查询相关问题 public static final String doc_rank = "DOC_RANK";//更新医生的声誉(医生表 public static final String doc_schedule_query = "DOC_SCHEDULE_QUERY";//返回一个医生的出诊安排(医生安排表 public static final String doc_advice_ans = "DOC_ADVICE_ANS";//医生的回复-修改记录(咨询记录表 public static final String doc_schedule_add = "DOC_SCHEDULE_ADD";//添加一个医生的出诊安排(医生安排表 public static final String doc_schedule_del = "DOC_SCHEDULE_DEL";//删除一个医生的出诊安排(医生安排表 }
M-Ethereal/VCampus
src/util/MessageType.java
2,015
//查询购买记录
line_comment
zh-cn
package util; public final class MessageType { public MessageType() { // TODO Auto-generated constructor stub } //Message-Type public static final String operFeedback = "OPER_FEEDBACK"; //管理员:管理用户 public static final String outputAllStudent = "OUTPUT_ALL_STUDENT"; public static final String outputAllTeacher = "OUTPUT_ALL_TEACHER"; public static final String outputAllRetailer = "OUTPUT_ALL_RETAILER"; public static final String outputAllDoctor = "OUTPUT_ALL_DOCTOR"; public static final String addStudent = "ADD_STUDENT"; public static final String deleteStudent = "DELETE_STUDENT"; public static final String updateStudent = "UPDATE_STUDENT"; public static final String queryStudent = "QUERY_STUDENT"; public static final String queryStudentByMajor = "QUERY_STUDENT_BY_MAJOR"; public static final String addTeacher = "ADD_TEACHER"; public static final String deleteTeacher = "DELETE_TEACHER"; public static final String updateTeacher = "UPDATE_TEACHER"; public static final String queryTeacher = "QUERY_TEACHER"; public static final String addRetailer = "ADD_RETAILER"; public static final String deleteRetailer = "DELETE_RETAILER"; public static final String updateRetailer = "UPDATE_RETAILER"; public static final String queryRetailer = "QUERY_RETAILER"; public static final String addDoctor = "ADD_DOCTOR"; public static final String deleteDoctor = "DELETE_DOCTOR"; public static final String updateDoctor = "UPDATE_DOCTOR"; public static final String queryDoctor = "QUERY_DOCTOR"; //用户操作 public static final String userLogin = "USER_LOGIN"; public static final String register = "REGISTER"; //图书馆 public static final String outputallbooks = "OUTPUT_ALL_BOOKS";//返回所有书目 public static final String outputallbooksbystudy="OUTPUT_ALL_BOOKS_BYSTUDY";//学业书籍推荐 public static final String outputallbooksbyhappy="OUTPUT_ALL_BOOKS_BYHAPPY";//休闲书籍推荐 public static final String outputbyindistinctsearch="OUTPUT_BY_INDISTINCTSEARCH";//模糊查询 public static final String outputbybookidsearch="OUTPUT_BY_BOOKIDSEARCH";//通过书ID查询 public static final String outputbybooknamesearch="OUTPUT_BY_BOOKNAMESEARCH";//通过书名查询 public static final String outputbybookauthorsearch="OUTPUT_BY_BOOKAUTHORSEARCH";//通过书的作者查询 public static final String outputbysearchbyrecordstudentidisreturn="OUTPUT_BY_SEARCHBYRECORDSTUDENTIDISRETURN";//返回我的已还 public static final String outputbysearchbyrecordstudentidnotreturn="OUTPUT_BY_SEARCHBYRECORDSTUDENTIDNOTRETURN";//返回我的待还 public static final String outputbysearchbyrecordid="OUTPUTBYSEARCHBYRECORDID"; public static final String insertbook="INSERT_BOOK";//插入书 public static final String deletelibbook="DELETE_LIBBOOK";//删除书 public static final String updatebook="UPDATE_BOOK";//更新书的信息 public static final String returnbook="RETURN_BOOK";//还书 public static final String lendbook="LEND_BOOK";//借书 //商店 public static final String shopQuery = "SHOP_QUERY";//查询商品 public static final String shopInit = "SHOP_INIT";//查询所有 public static final String Buy = "BUY";//购买 public static final String PurchaseRecordQuery = "PURCHASERECORD_QUERY";//查询 <SUF> public static final String SellingRecordQuery = "SELLINGRECORD_QUERY";//查询售出记录 public static final String Score = "SCORE"; public static final String shop_queryStudent = "SHOP_QUERYSTUDENT"; public static final String shop_queryRetailer = "SHOP_QUERYRETAILER"; public static final String add_product = "ADD_PRODUCT"; //课程 public static final String course_query = "COURSE_QUERY";//返回所有查询学期的课(学生 public static final String course_query_admin = "COURSE_QUERY_ADMIN";//返回所有查询学期的课(管理员(所有课 public static final String course_init = "COURSE_INIT"; //返回所有本学期的课 public static final String course_choose = "COURSE_CHOOSE";//学生选课,grade表插入记录 public static final String course_my_table = "COURSE_MYTABLE";//返回该学生该学期的课 public static final String course_giveup = "COURSE_GIVEUP";//退课 public static final String course_query_grade = "COURSE_QUERY_GRADE";//查成绩 public static final String course_teacher_table = "COURSE_TEACHER_TABLE";//老师课程表 public static final String course_studentList_query = "COURSE_STUDENTLIST_QUERY";//查询该门课程有哪些学生选择 public static final String course_grade_add = "COURSE_GRADE_ADD";//登成绩 public static final String course_query_course = "COURSE_QUERY_COURSE";//查一门课 public static final String course_exam_add = "COURSE_EXAM_ADD";//发布考试 public static final String course_add = "COURSE_ADD";//管理员加课 //银行 public static final String record_Query = "RECORD_QUERY";//查询交易明细 public static final String phone_Pay = "PHONE_PAY";//支付手机流量包 public static final String wifi_Pay = "WIFI_PAY";//支付校园网套餐 public static final String tuition_Pay = "TUITION_PAY";//支付学费 public static final String card_Invest = "CARD_INVEST";//对一卡通进行充值 public static final String account_Query = "ACCOUNT_QUERY";//查询具体账单金额 //场馆 public static final String place_query_all = "PLACE_QUERY_ALL";//查询场馆列表的公共入口 public static final String place_ap_insert = "PLACE_AP_INSERT";//新增场馆预约 public static final String place_ap_query = "PLACE_AP_QUERY";//场馆预约记录查询(按照场馆 public static final String stu_ap_query = "STU_AP_QUERY";//场馆预约记录查询(按照学生 public static final String place_ap_delete = "PLACE_AP_DELETE";//场馆预约记录取消 public static final String place_query_by_name = "PLACE_QUERY_BY_NAME";//查询特定场馆 //医院 public static final String doc_query_all = "DOC_QUERY_ALL";//返回所有医生(医生表 public static final String doc_query_doc = "DOC_QUERY_DOC";//返回指定医生(医生表 public static final String stu_advice_query_stu = "STU_ADVICE_QUERY_STU";//返回指定学生的咨询记录(咨询记录表 public static final String stu_advice_query_doc = "STU_ADVICE_QUERY_DOC";//返回指定医生的咨询记录(咨询记录表 public static final String stu_res_query = "STU_RES_QUERY";//返回指定学生的挂号记录(挂号记录表 public static final String stu_advice_insert = "STU_ADVICE_INSERT";//增加一条记录(咨询记录表 public static final String stu_res_insert = "STU_RES_INSERT";//增加一条记录(挂号记录表 public static final String stu_advice_query_relevant = "STU_ADVICE_QUERY_RELEVANT";//查询相关问题 public static final String doc_rank = "DOC_RANK";//更新医生的声誉(医生表 public static final String doc_schedule_query = "DOC_SCHEDULE_QUERY";//返回一个医生的出诊安排(医生安排表 public static final String doc_advice_ans = "DOC_ADVICE_ANS";//医生的回复-修改记录(咨询记录表 public static final String doc_schedule_add = "DOC_SCHEDULE_ADD";//添加一个医生的出诊安排(医生安排表 public static final String doc_schedule_del = "DOC_SCHEDULE_DEL";//删除一个医生的出诊安排(医生安排表 }
false
1,686
4
2,015
5
1,866
4
2,015
5
2,688
13
false
false
false
false
false
true
45657_6
package main ; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class TestForFunction { //创建一个窗口,在窗口中添加一个按钮,按钮点击时,在JLabel输出helloword public static void main(String[] args) { //1.创建一个窗口(JFrame) JFrame frame=new JFrame("监听器例子"); frame.setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//x 掉窗口推出java程序 //2.设置窗口的位置和大小 frame.setLocation(500, 500); frame.setSize(300, 250); //3.创建一个JLable和按钮 final JLabel label=new JLabel("未点击"); JButton btn=new JButton("点我!"); //5.将按钮添加到窗口中 frame.add(label); frame.add(btn); //6.创建一个监听器 ActionListener listener = new ActionListener() { //事件处理器 public void actionPerformed(ActionEvent e) { label.setText("HelloWord"); System.out.println("HelloWord"); } }; /** * 事件源:按钮 * 事件:按钮被点击 * 监听器:Listener * 将监听器注册到按钮(事件源)上,监听器将会一直监听(监视)按钮的状态变化,一旦按钮被 * 点击(事件发生),将会通知监听器,监听器将会调用特定的方法处理"按钮被点击" * 事件 */ //7.注册监听器(让监听器监听指定的按钮) btn.addActionListener(listener); //8.设置窗口为显示(状态) frame.setVisible(true); } }
MANNIX-CHEN/Tetris
src/main/TestForFunction.java
434
//6.创建一个监听器
line_comment
zh-cn
package main ; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class TestForFunction { //创建一个窗口,在窗口中添加一个按钮,按钮点击时,在JLabel输出helloword public static void main(String[] args) { //1.创建一个窗口(JFrame) JFrame frame=new JFrame("监听器例子"); frame.setLayout(new FlowLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//x 掉窗口推出java程序 //2.设置窗口的位置和大小 frame.setLocation(500, 500); frame.setSize(300, 250); //3.创建一个JLable和按钮 final JLabel label=new JLabel("未点击"); JButton btn=new JButton("点我!"); //5.将按钮添加到窗口中 frame.add(label); frame.add(btn); //6. <SUF> ActionListener listener = new ActionListener() { //事件处理器 public void actionPerformed(ActionEvent e) { label.setText("HelloWord"); System.out.println("HelloWord"); } }; /** * 事件源:按钮 * 事件:按钮被点击 * 监听器:Listener * 将监听器注册到按钮(事件源)上,监听器将会一直监听(监视)按钮的状态变化,一旦按钮被 * 点击(事件发生),将会通知监听器,监听器将会调用特定的方法处理"按钮被点击" * 事件 */ //7.注册监听器(让监听器监听指定的按钮) btn.addActionListener(listener); //8.设置窗口为显示(状态) frame.setVisible(true); } }
false
389
7
434
6
448
6
434
6
672
14
false
false
false
false
false
true
43772_3
package com.hlsp.video.model; import com.hlsp.video.bean.AuthorInfoResponse; import com.hlsp.video.bean.AuthorVideoResponse; import com.hlsp.video.bean.LoginResult; import com.hlsp.video.bean.data.ChannelListData; import com.hlsp.video.bean.data.VideoListData; import com.hlsp.video.bean.data.VideoUrlData; import com.hlsp.video.model.main.MainInfo; import java.util.List; import java.util.Map; import cn.share.jack.cyghttp.BaseResponse; import io.reactivex.Observable; import okhttp3.RequestBody; import retrofit2.http.Body; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; /** * Created by jack on 2017/6/13 */ public interface CygApi { @FormUrlEncoded @POST("MainServlet") Observable<BaseResponse<List<MainInfo>>> getArticle(@FieldMap Map<String, String> params); /** * 获取频道列表 */ @POST("v1/search/channelOf360") Observable<BaseResponse<ChannelListData>> getChannel(@Body RequestBody body); /** * 获取频道的视频列表 */ @POST("v1/search/videoListOf360") Observable<BaseResponse<VideoListData>> getVideoList(@Body RequestBody body); /** * 解密视频 */ @POST("v1/search/videoUrlOf360") Observable<BaseResponse<VideoUrlData>> getVideoUrl(@Body RequestBody body); /** * 获取作者信息 */ @POST("v1/search/getLocalAuthor") Observable<BaseResponse<AuthorInfoResponse>> getAuthorInfo(@Body RequestBody body); /** * 获取作者作品 */ @POST("v1/search/getLocalVideo") Observable<BaseResponse<AuthorVideoResponse>> getAuthorVideo(@Body RequestBody body); /** * 邮箱登录 */ @POST("v2/login/") Observable<BaseResponse<LoginResult>> login(@Body RequestBody body); /** * 版本更新 */ @GET("check/") Observable<BaseResponse<LoginResult>> updateVersion(@Query("type") String type); }
MIkeeJY/honglou
app/src/main/java/com/hlsp/video/model/CygApi.java
578
/** * 解密视频 */
block_comment
zh-cn
package com.hlsp.video.model; import com.hlsp.video.bean.AuthorInfoResponse; import com.hlsp.video.bean.AuthorVideoResponse; import com.hlsp.video.bean.LoginResult; import com.hlsp.video.bean.data.ChannelListData; import com.hlsp.video.bean.data.VideoListData; import com.hlsp.video.bean.data.VideoUrlData; import com.hlsp.video.model.main.MainInfo; import java.util.List; import java.util.Map; import cn.share.jack.cyghttp.BaseResponse; import io.reactivex.Observable; import okhttp3.RequestBody; import retrofit2.http.Body; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; /** * Created by jack on 2017/6/13 */ public interface CygApi { @FormUrlEncoded @POST("MainServlet") Observable<BaseResponse<List<MainInfo>>> getArticle(@FieldMap Map<String, String> params); /** * 获取频道列表 */ @POST("v1/search/channelOf360") Observable<BaseResponse<ChannelListData>> getChannel(@Body RequestBody body); /** * 获取频道的视频列表 */ @POST("v1/search/videoListOf360") Observable<BaseResponse<VideoListData>> getVideoList(@Body RequestBody body); /** * 解密视 <SUF>*/ @POST("v1/search/videoUrlOf360") Observable<BaseResponse<VideoUrlData>> getVideoUrl(@Body RequestBody body); /** * 获取作者信息 */ @POST("v1/search/getLocalAuthor") Observable<BaseResponse<AuthorInfoResponse>> getAuthorInfo(@Body RequestBody body); /** * 获取作者作品 */ @POST("v1/search/getLocalVideo") Observable<BaseResponse<AuthorVideoResponse>> getAuthorVideo(@Body RequestBody body); /** * 邮箱登录 */ @POST("v2/login/") Observable<BaseResponse<LoginResult>> login(@Body RequestBody body); /** * 版本更新 */ @GET("check/") Observable<BaseResponse<LoginResult>> updateVersion(@Query("type") String type); }
false
481
9
578
9
588
10
578
9
676
14
false
false
false
false
false
true
63448_1
package com.itheima.contrast; public class Demo1Oop { /* 需求: 遍历打印数组, 要求结果为[11, 22, 33, 44, 55] 面向对象思想: 指挥 [对象] 来实现需求 */ public static void main(String[] args) { int[] arr = {11,22,33,44,55}; // 1. 创建数组服务员对象 数组服务员 二狗 = new 数组服务员(); // 2. 指挥二狗对象, 调用内部的printArray方法遍历打印数组 二狗.遍历打印数组(arr); } }
MN-ctx/JAVASE
day221128/mOop/src/com/itheima/contrast/Demo1Oop.java
173
// 1. 创建数组服务员对象
line_comment
zh-cn
package com.itheima.contrast; public class Demo1Oop { /* 需求: 遍历打印数组, 要求结果为[11, 22, 33, 44, 55] 面向对象思想: 指挥 [对象] 来实现需求 */ public static void main(String[] args) { int[] arr = {11,22,33,44,55}; // 1. <SUF> 数组服务员 二狗 = new 数组服务员(); // 2. 指挥二狗对象, 调用内部的printArray方法遍历打印数组 二狗.遍历打印数组(arr); } }
false
174
9
172
10
166
10
172
10
236
15
false
false
false
false
false
true
10492_0
package com.mobin.thread; /** * Created by Mobin on 2016/1/27. * 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序。 */ public class MainAndSubCyclical { public static void main(String[] args) { final Common common = new Common(); new Thread( new Runnable() { public void run() { for (int i = 1; i <= 50; i++) { common.sub(i); } } } ).start(); for (int i = 1; i <= 50; i++) { common.main(i); } } } class Common{ private boolean sub = true; public synchronized void sub(int i){ while (!sub) { //用while而不用if可以避免虚假唤醒 try { this.wait(); //等待,主main运行完 } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("sub " + j + " loop of " + i); } sub = false; this.notify(); } public synchronized void main(int i){ while(sub) { try { this.wait(); //等待让sub运行完 } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("main " + j + " loop of " + i); } sub = true; this.notify(); } }
MOBIN-F/Thread
src/com/mobin/thread/MainAndSubCyclical.java
431
/** * Created by Mobin on 2016/1/27. * 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序。 */
block_comment
zh-cn
package com.mobin.thread; /** * Cre <SUF>*/ public class MainAndSubCyclical { public static void main(String[] args) { final Common common = new Common(); new Thread( new Runnable() { public void run() { for (int i = 1; i <= 50; i++) { common.sub(i); } } } ).start(); for (int i = 1; i <= 50; i++) { common.main(i); } } } class Common{ private boolean sub = true; public synchronized void sub(int i){ while (!sub) { //用while而不用if可以避免虚假唤醒 try { this.wait(); //等待,主main运行完 } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("sub " + j + " loop of " + i); } sub = false; this.notify(); } public synchronized void main(int i){ while(sub) { try { this.wait(); //等待让sub运行完 } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("main " + j + " loop of " + i); } sub = true; this.notify(); } }
false
393
69
431
78
466
71
431
78
560
120
false
false
false
false
false
true
18153_22
package com.mobin.convert; import com.github.stuxuhai.jpinyin.PinyinFormat; import com.github.stuxuhai.jpinyin.PinyinHelper; import com.mobin.util.TST; import org.apache.commons.collections.map.HashedMap; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by hadoop on 3/9/16. */ public class ConvertMapper extends Mapper<LongWritable, Text, NullWritable, Text> { private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private SimpleDateFormat f = new SimpleDateFormat("yy年MM月dd日"); private InputStream inputStream; private Properties properties; private TST<String> tst; private Text valueText; protected void setup(Mapper<LongWritable, Text, NullWritable, Text>.Context context) throws IOException, InterruptedException { tst=new TST<String>(); valueText=new Text(); inputStream=getClass().getResourceAsStream("/interest.properties"); properties=new Properties(); properties.load(inputStream); Set<String> stringPropertyNames = properties.stringPropertyNames(); for (String intresting : stringPropertyNames) { tst.put(intresting, properties.getProperty(intresting)); } } protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] _info = null; String[] info = value.toString().split("\t"); double _touristSpots = touristSpots(info[4].replaceAll("[\\[\\]]", "").split(",")); double _shop = shopping(info[15]); try { _info = change(info[5]); } catch (ParseException e) { e.printStackTrace(); } double _hotel = hotel(info[14]); // info[5] = hoteled(info[5]); String hotellevel = hoteled(info[14]); String trafficlevel = trafficLevel(info[8]); double _traffic = traffic(info[8]); double _sight = info[4].substring(1, info[4].length() - 1).split(",").length * 0.3; double total = (_hotel + _traffic + _sight + _touristSpots + _shop) / Integer.valueOf(info[7]); String _total = String.format("%.19f", total); StringBuffer sb = new StringBuffer(); String values = sb //将Jpingyin的jar包放到各节点的Hadoop包目录下,否则会出现couldnotfoundclass错误 .append(info[0]).append("\t") //出发点(拼音) .append(PinyinHelper.convertToPinyinString(info[1].replaceAll("[\\[\\]]", ""),"", PinyinFormat.WITHOUT_TONE)).append("\t") //目的地(拼音) .append(PinyinHelper.convertToPinyinString(info[2].replaceAll("[\\[\\]]", ""),"", PinyinFormat.WITHOUT_TONE)).append("\t") //标题 .append(info[3].replaceAll("[\\[\\]]", "")).append("\t") //目的地 .append(info[4].replaceAll("[\\[\\]]", "")).append("\t") //出发时间 .append(String.valueOf(_info[0])).append("\t") //结束时间 //.append(String.valueOf(_info[1])).append("\t") //出游天数 .append(info[6]).append("\t") //价格 .append(info[7]).append("\t") //交通方式 .append(info[8]).append("\t") //是否往返 .append(info[9]).append("\t") //是否直达 .append(info[10]).append("\t") //跟团游 .append(info[11]).append("\t") //图片 .append(info[12]).append("\t") //代理 .append(info[13]).append("\t") //酒店 .append(info[14]).append("\t") //数据来源 .append("去哪儿网").append("\t") //酒店等级 .append(hotellevel).append("\t") //出发点 .append((info[1].replaceAll("[\\[\\]]", ""))).append("\t") //目的地 .append((info[2].replaceAll("[\\[\\]]", ""))).append("\t") //性价比 .append(_total).append("\t") //交通工具 .append(trafficlevel).append("\t") .toString(); context.write(NullWritable.get(), new Text(values)); } public String[] change(String info) throws ParseException { String ST = ""; String ET = ""; String[] s = new String[2]; if (info.contains("天天")) { ST = sdf.format(new Date()); ET = sdf.format(f.parse("17年01月01日")); } else if (info.contains("多团期")) { String[] _info = info.substring(0, info.lastIndexOf("多团期")).split("\\..."); ST = ST(_info[0]); ET = ET(_info[1]); } else if (info.contains("-")) { String[] _info = info.split("-"); ST = ST(_info[0]); ET = ET(_info[1]); } s[0] = ST; s[1] = ET; return s; } public String ST(String st) throws ParseException { return sdf.format(f.parse("16年" + st)); } public String ET(String et) throws ParseException { return sdf.format(f.parse("16年" + et)); } ////估算酒店星性价比 public double hotel(String hotel) { double _hotel = 0.21; if (hotel.contains("经济型")) { _hotel = _hotel * 2; } else if (hotel.contains("舒适型")) { _hotel = _hotel * 3; } else if (hotel.contains("高档型")) { _hotel = _hotel * 4; } else if (hotel.contains("豪华型")) { _hotel = _hotel * 5; }else{ _hotel = _hotel * 1; } return _hotel; } //计算旅游天数的性价比 public double tData(String data){ double _data = 0.12; String d = data.split("[\u4e00-\u9fa5]+")[0]; return _data * (Integer.valueOf(d)); } //判断酒店星级数 public String hoteled(String hotel) { String level = null; if (hotel.contains("经济型")) { level = "2"; } else if (hotel.contains("舒适型")) { level = "3"; } else if (hotel.contains("高档型")) { level = "4"; } else if (hotel.contains("豪华型")) { level = "5"; } else level = "1"; return level; } public String trafficLevel(String traffic) { if (traffic.contains("航班") || traffic.contains("飞机")) return "5"; else if (traffic.contains("高铁")) return "4"; else if (traffic.contains("火车")) return "3"; else if (traffic.contains("大巴")) return "2"; else return "1"; } public double traffic(String traffic) { double _traffic = 0.21; if (traffic.contains("航班") || traffic.contains("飞机")) { _traffic = _traffic * 5; } else if (traffic.contains("高铁")) { _traffic = _traffic * 4; } else if (traffic.contains("火车")) { _traffic = _traffic * 3; } else if (traffic.contains("大巴")) { _traffic = _traffic * 2; } return _traffic; } //著名景点个数 public double touristSpots(String[] traffic) { double _traffic = 0.38; int count = 0; for(String s : traffic) { String p = PinyinHelper.convertToPinyinString(s,"",PinyinFormat.WITHOUT_TONE); if(!"".equals(p) && p != null){ String i = tst.get(p); if(i != null) count ++; } } return count * _traffic; } public double shopping(String shop){ double _shop = 0.07; if(shop.contains("购物")) return _shop; else return 0; } }
MOBIN-F/TravelPriceComparison
src/main/java/com/mobin/convert/ConvertMapper.java
2,169
//判断酒店星级数
line_comment
zh-cn
package com.mobin.convert; import com.github.stuxuhai.jpinyin.PinyinFormat; import com.github.stuxuhai.jpinyin.PinyinHelper; import com.mobin.util.TST; import org.apache.commons.collections.map.HashedMap; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by hadoop on 3/9/16. */ public class ConvertMapper extends Mapper<LongWritable, Text, NullWritable, Text> { private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private SimpleDateFormat f = new SimpleDateFormat("yy年MM月dd日"); private InputStream inputStream; private Properties properties; private TST<String> tst; private Text valueText; protected void setup(Mapper<LongWritable, Text, NullWritable, Text>.Context context) throws IOException, InterruptedException { tst=new TST<String>(); valueText=new Text(); inputStream=getClass().getResourceAsStream("/interest.properties"); properties=new Properties(); properties.load(inputStream); Set<String> stringPropertyNames = properties.stringPropertyNames(); for (String intresting : stringPropertyNames) { tst.put(intresting, properties.getProperty(intresting)); } } protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] _info = null; String[] info = value.toString().split("\t"); double _touristSpots = touristSpots(info[4].replaceAll("[\\[\\]]", "").split(",")); double _shop = shopping(info[15]); try { _info = change(info[5]); } catch (ParseException e) { e.printStackTrace(); } double _hotel = hotel(info[14]); // info[5] = hoteled(info[5]); String hotellevel = hoteled(info[14]); String trafficlevel = trafficLevel(info[8]); double _traffic = traffic(info[8]); double _sight = info[4].substring(1, info[4].length() - 1).split(",").length * 0.3; double total = (_hotel + _traffic + _sight + _touristSpots + _shop) / Integer.valueOf(info[7]); String _total = String.format("%.19f", total); StringBuffer sb = new StringBuffer(); String values = sb //将Jpingyin的jar包放到各节点的Hadoop包目录下,否则会出现couldnotfoundclass错误 .append(info[0]).append("\t") //出发点(拼音) .append(PinyinHelper.convertToPinyinString(info[1].replaceAll("[\\[\\]]", ""),"", PinyinFormat.WITHOUT_TONE)).append("\t") //目的地(拼音) .append(PinyinHelper.convertToPinyinString(info[2].replaceAll("[\\[\\]]", ""),"", PinyinFormat.WITHOUT_TONE)).append("\t") //标题 .append(info[3].replaceAll("[\\[\\]]", "")).append("\t") //目的地 .append(info[4].replaceAll("[\\[\\]]", "")).append("\t") //出发时间 .append(String.valueOf(_info[0])).append("\t") //结束时间 //.append(String.valueOf(_info[1])).append("\t") //出游天数 .append(info[6]).append("\t") //价格 .append(info[7]).append("\t") //交通方式 .append(info[8]).append("\t") //是否往返 .append(info[9]).append("\t") //是否直达 .append(info[10]).append("\t") //跟团游 .append(info[11]).append("\t") //图片 .append(info[12]).append("\t") //代理 .append(info[13]).append("\t") //酒店 .append(info[14]).append("\t") //数据来源 .append("去哪儿网").append("\t") //酒店等级 .append(hotellevel).append("\t") //出发点 .append((info[1].replaceAll("[\\[\\]]", ""))).append("\t") //目的地 .append((info[2].replaceAll("[\\[\\]]", ""))).append("\t") //性价比 .append(_total).append("\t") //交通工具 .append(trafficlevel).append("\t") .toString(); context.write(NullWritable.get(), new Text(values)); } public String[] change(String info) throws ParseException { String ST = ""; String ET = ""; String[] s = new String[2]; if (info.contains("天天")) { ST = sdf.format(new Date()); ET = sdf.format(f.parse("17年01月01日")); } else if (info.contains("多团期")) { String[] _info = info.substring(0, info.lastIndexOf("多团期")).split("\\..."); ST = ST(_info[0]); ET = ET(_info[1]); } else if (info.contains("-")) { String[] _info = info.split("-"); ST = ST(_info[0]); ET = ET(_info[1]); } s[0] = ST; s[1] = ET; return s; } public String ST(String st) throws ParseException { return sdf.format(f.parse("16年" + st)); } public String ET(String et) throws ParseException { return sdf.format(f.parse("16年" + et)); } ////估算酒店星性价比 public double hotel(String hotel) { double _hotel = 0.21; if (hotel.contains("经济型")) { _hotel = _hotel * 2; } else if (hotel.contains("舒适型")) { _hotel = _hotel * 3; } else if (hotel.contains("高档型")) { _hotel = _hotel * 4; } else if (hotel.contains("豪华型")) { _hotel = _hotel * 5; }else{ _hotel = _hotel * 1; } return _hotel; } //计算旅游天数的性价比 public double tData(String data){ double _data = 0.12; String d = data.split("[\u4e00-\u9fa5]+")[0]; return _data * (Integer.valueOf(d)); } //判断 <SUF> public String hoteled(String hotel) { String level = null; if (hotel.contains("经济型")) { level = "2"; } else if (hotel.contains("舒适型")) { level = "3"; } else if (hotel.contains("高档型")) { level = "4"; } else if (hotel.contains("豪华型")) { level = "5"; } else level = "1"; return level; } public String trafficLevel(String traffic) { if (traffic.contains("航班") || traffic.contains("飞机")) return "5"; else if (traffic.contains("高铁")) return "4"; else if (traffic.contains("火车")) return "3"; else if (traffic.contains("大巴")) return "2"; else return "1"; } public double traffic(String traffic) { double _traffic = 0.21; if (traffic.contains("航班") || traffic.contains("飞机")) { _traffic = _traffic * 5; } else if (traffic.contains("高铁")) { _traffic = _traffic * 4; } else if (traffic.contains("火车")) { _traffic = _traffic * 3; } else if (traffic.contains("大巴")) { _traffic = _traffic * 2; } return _traffic; } //著名景点个数 public double touristSpots(String[] traffic) { double _traffic = 0.38; int count = 0; for(String s : traffic) { String p = PinyinHelper.convertToPinyinString(s,"",PinyinFormat.WITHOUT_TONE); if(!"".equals(p) && p != null){ String i = tst.get(p); if(i != null) count ++; } } return count * _traffic; } public double shopping(String shop){ double _shop = 0.07; if(shop.contains("购物")) return _shop; else return 0; } }
false
1,935
5
2,169
8
2,262
6
2,169
8
2,661
12
false
false
false
false
false
true