file_id
stringlengths
5
9
content
stringlengths
24
16.1k
repo
stringlengths
8
84
path
stringlengths
7
167
token_length
int64
18
3.48k
original_comment
stringlengths
5
2.57k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
11
16.1k
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
14
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
1.74k
file-tokens-bigcode/starcoder2-7b
int64
18
3.48k
comment-tokens-bigcode/starcoder2-7b
int64
2
2.11k
file-tokens-google/codegemma-7b
int64
14
3.57k
comment-tokens-google/codegemma-7b
int64
2
1.75k
file-tokens-ibm-granite/granite-8b-code-base
int64
18
3.48k
comment-tokens-ibm-granite/granite-8b-code-base
int64
2
2.11k
file-tokens-meta-llama/CodeLlama-7b-hf
int64
31
3.93k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
2.71k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
29315_0
package util; import com.sun.rowset.CachedRowSetImpl; import java.io.IOException; import java.sql.*; import java.util.Properties; public class JDBCUtils { private static Properties prop = null; public JDBCUtils() { } /** * 静态代码块,加载数据库配置文件 */ static { prop = new Properties(); try { prop.load(JDBCUtils.class.getClassLoader().getResourceAsStream("JdbcConfig.properties")); // prop.load(new FileInputStream("/resources/JdbcConfig.properties")); } catch (IOException e) { e.printStackTrace(); } } /** * 获取连接 * * @return mysql数据库连接 * @throws Exception */ private static Connection getConn() throws Exception { Class.forName(prop.getProperty("driver")); Connection conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("name"), prop.getProperty("password")); return conn; } /** * 执行sql语句 * @param sql * @param args 动态sql可变参数 * @return 结果集 * @throws Exception */ public static CachedRowSetImpl execSQL(String sql, Object... args) throws Exception { //获取Connection对象 Connection conn = JDBCUtils.getConn(); //建立PreparedStatement对象 PreparedStatement pstm = conn.prepareStatement(sql); //为pstm对象设置SQL参数值 for (int i = 0; i < args.length; i++) { pstm.setObject(i + 1, args[i]); } //执行sql语句 pstm.execute(); //返回结果集,如果执行的SQL语句不返会结果集,则返回null ResultSet resultSet = pstm.getResultSet(); // 如果一定要传递ResultSet,应该使用RowSet,RowSet可以不依赖于Connection和Statement。Java传递的是引用, // 所以如果传递ResultSet,你会不知道Statement和Connection何时关闭,不知道ResultSet何时有效。 CachedRowSetImpl rowSet = new CachedRowSetImpl(); if (resultSet != null) { rowSet.populate(resultSet); close(resultSet, pstm, conn); }else { rowSet = null; } return rowSet; } private static void close(ResultSet rs, Statement stat, Connection conn) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (stat != null) { stat.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
YuRacle/HealthArchivesManagementSystem
src/main/java/util/JDBCUtils.java
630
/** * 静态代码块,加载数据库配置文件 */
block_comment
zh-cn
package util; import com.sun.rowset.CachedRowSetImpl; import java.io.IOException; import java.sql.*; import java.util.Properties; public class JDBCUtils { private static Properties prop = null; public JDBCUtils() { } /** * 静态代 <SUF>*/ static { prop = new Properties(); try { prop.load(JDBCUtils.class.getClassLoader().getResourceAsStream("JdbcConfig.properties")); // prop.load(new FileInputStream("/resources/JdbcConfig.properties")); } catch (IOException e) { e.printStackTrace(); } } /** * 获取连接 * * @return mysql数据库连接 * @throws Exception */ private static Connection getConn() throws Exception { Class.forName(prop.getProperty("driver")); Connection conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("name"), prop.getProperty("password")); return conn; } /** * 执行sql语句 * @param sql * @param args 动态sql可变参数 * @return 结果集 * @throws Exception */ public static CachedRowSetImpl execSQL(String sql, Object... args) throws Exception { //获取Connection对象 Connection conn = JDBCUtils.getConn(); //建立PreparedStatement对象 PreparedStatement pstm = conn.prepareStatement(sql); //为pstm对象设置SQL参数值 for (int i = 0; i < args.length; i++) { pstm.setObject(i + 1, args[i]); } //执行sql语句 pstm.execute(); //返回结果集,如果执行的SQL语句不返会结果集,则返回null ResultSet resultSet = pstm.getResultSet(); // 如果一定要传递ResultSet,应该使用RowSet,RowSet可以不依赖于Connection和Statement。Java传递的是引用, // 所以如果传递ResultSet,你会不知道Statement和Connection何时关闭,不知道ResultSet何时有效。 CachedRowSetImpl rowSet = new CachedRowSetImpl(); if (resultSet != null) { rowSet.populate(resultSet); close(resultSet, pstm, conn); }else { rowSet = null; } return rowSet; } private static void close(ResultSet rs, Statement stat, Connection conn) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (stat != null) { stat.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
false
593
17
630
13
697
15
630
13
853
27
false
false
false
false
false
true
57628_0
public class ProtoTypeCitation { public static void main(String[] args) throws CloneNotSupportedException { citation obj1 = new citation("张三", "同学:在2016学年第一学期中表现优秀,被评为三好学生。", "韶关学院"); obj1.display(); citation obj2 = (citation) obj1.clone(); obj2.setName("李四"); obj2.display(); obj1.display(); } } //奖状类 class citation implements Cloneable { String name; String info; String college; citation(String name, String info, String college) { this.name = name; this.info = info; this.college = college; System.out.println("奖状创建成功!"); } void setName(String name) { this.name = name; } String getName() { return (this.name); } void display() { System.out.println(name + info + college); } public Object clone() throws CloneNotSupportedException { System.out.println("奖状拷贝成功!"); return (citation) super.clone(); } }
YuTao0310/programmer
java/javaExample/ProtoTypeCitation.java
284
//奖状类
line_comment
zh-cn
public class ProtoTypeCitation { public static void main(String[] args) throws CloneNotSupportedException { citation obj1 = new citation("张三", "同学:在2016学年第一学期中表现优秀,被评为三好学生。", "韶关学院"); obj1.display(); citation obj2 = (citation) obj1.clone(); obj2.setName("李四"); obj2.display(); obj1.display(); } } //奖状 <SUF> class citation implements Cloneable { String name; String info; String college; citation(String name, String info, String college) { this.name = name; this.info = info; this.college = college; System.out.println("奖状创建成功!"); } void setName(String name) { this.name = name; } String getName() { return (this.name); } void display() { System.out.println(name + info + college); } public Object clone() throws CloneNotSupportedException { System.out.println("奖状拷贝成功!"); return (citation) super.clone(); } }
false
239
4
284
4
294
4
284
4
350
6
false
false
false
false
false
true
38110_1
package main; public class Rect extends Shape { double chang; double kuan; //构造方法 Rect(double chang, double kuan) { this.chang = chang; this.kuan = kuan; } //计算矩形周长 @Override public void zhouchang() { System.out.println("矩形的周长为:" + (2 * chang + 2 * kuan)); } //计算矩形面积 @Override public void area() { System.out.println("矩形的面积为:" + (chang * kuan)); } //判断矩形长宽哪个长 public void cha() { if (chang > kuan) System.out.println("长比宽大"); if (chang < kuan) System.out.println("宽比长大"); } }
YuZhangWang/Java-Demo
12第1题/src/main/Rect.java
207
//计算矩形周长
line_comment
zh-cn
package main; public class Rect extends Shape { double chang; double kuan; //构造方法 Rect(double chang, double kuan) { this.chang = chang; this.kuan = kuan; } //计算 <SUF> @Override public void zhouchang() { System.out.println("矩形的周长为:" + (2 * chang + 2 * kuan)); } //计算矩形面积 @Override public void area() { System.out.println("矩形的面积为:" + (chang * kuan)); } //判断矩形长宽哪个长 public void cha() { if (chang > kuan) System.out.println("长比宽大"); if (chang < kuan) System.out.println("宽比长大"); } }
false
187
6
207
6
209
6
207
6
260
9
false
false
false
false
false
true
62411_10
public class MultiplyStrings { public static void main(String[] args) { String sample01a = "123"; String sample01b = "456"; String sample02a = "9"; String sample02b = "9"; String sample03a = "9"; String sample03b = "99"; String result = multiply(sample01a, sample01b); System.out.println("Result is " + result); } public static String multiply(String num1, String num2) { // base case if (num1 == null || num2 == null || num1.equals("0") || num2.equals("0")) { return "0"; } if (num1.equals("1")) { return num2; } if (num2.equals("1")) { return num1; } // 直式乘法 int mSize = num1.length(); int nSize = num2.length(); int[] resultIntArray = new int[mSize + nSize]; for (int j = nSize - 1; j >= 0; j--) { for (int i = mSize - 1; i >= 0; i--) { // Doing multiply int multiplyResult = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); // 加上,上一次算出來的左邊那個數字 multiplyResult += resultIntArray[i + j + 1]; // 處理這次計算的結果 resultIntArray[i + j + 1] = multiplyResult % 10; // 右邊數字 // carry,用 += 是因為這個欄位是上一個 operation 的 i + j + 1 留下來的數字。 // 上一個右邊數字(現在的 Operation 變成左邊數字) += 這次的左邊數字 resultIntArray[i + j] += multiplyResult / 10; // 左邊數字 } } // 轉換成 String StringBuilder stringBuilder = new StringBuilder(); for (int number : resultIntArray) { // 去除首字母是 0 的情形 if (stringBuilder.length() == 0 && number == 0) { continue; } System.out.println("number is " + number); stringBuilder.append(number); } return stringBuilder.toString(); } }
YuanLiou/JavaLeetCode
src/MultiplyStrings.java
582
// 去除首字母是 0 的情形
line_comment
zh-cn
public class MultiplyStrings { public static void main(String[] args) { String sample01a = "123"; String sample01b = "456"; String sample02a = "9"; String sample02b = "9"; String sample03a = "9"; String sample03b = "99"; String result = multiply(sample01a, sample01b); System.out.println("Result is " + result); } public static String multiply(String num1, String num2) { // base case if (num1 == null || num2 == null || num1.equals("0") || num2.equals("0")) { return "0"; } if (num1.equals("1")) { return num2; } if (num2.equals("1")) { return num1; } // 直式乘法 int mSize = num1.length(); int nSize = num2.length(); int[] resultIntArray = new int[mSize + nSize]; for (int j = nSize - 1; j >= 0; j--) { for (int i = mSize - 1; i >= 0; i--) { // Doing multiply int multiplyResult = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); // 加上,上一次算出來的左邊那個數字 multiplyResult += resultIntArray[i + j + 1]; // 處理這次計算的結果 resultIntArray[i + j + 1] = multiplyResult % 10; // 右邊數字 // carry,用 += 是因為這個欄位是上一個 operation 的 i + j + 1 留下來的數字。 // 上一個右邊數字(現在的 Operation 變成左邊數字) += 這次的左邊數字 resultIntArray[i + j] += multiplyResult / 10; // 左邊數字 } } // 轉換成 String StringBuilder stringBuilder = new StringBuilder(); for (int number : resultIntArray) { // 去除 <SUF> if (stringBuilder.length() == 0 && number == 0) { continue; } System.out.println("number is " + number); stringBuilder.append(number); } return stringBuilder.toString(); } }
false
544
12
582
13
590
10
582
13
714
14
false
false
false
false
false
true
64065_5
import java.util.List; /** * Created by Administrator on 2017/11/07. */ /*装载序列,它的每个元素对应装载阶段的一个选择。比如有装载ps, ps[k]表示在第K装载阶段应选择的块号 */ public class PackingSequence { int[] avail; //各种剩余箱子的数目 List<Plan> plan; //一个放置列表 SpaceStack spaceStack; //剩余空间堆栈 double volume; //被装载箱子的总体积 int depth; //深度 public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } public int[] getAvail() { return avail; } public void setAvail(int[] avail) { this.avail = avail; } public SpaceStack getSpaceStack() { return spaceStack; } public void setSpaceStack(SpaceStack spaceStack) { this.spaceStack = spaceStack; } public List<Plan> getPlan() { return plan; } public void setPlan(List<Plan> plan) { this.plan = plan; } }
YuanYunGuoYan/packing
src/PackingSequence.java
291
//被装载箱子的总体积
line_comment
zh-cn
import java.util.List; /** * Created by Administrator on 2017/11/07. */ /*装载序列,它的每个元素对应装载阶段的一个选择。比如有装载ps, ps[k]表示在第K装载阶段应选择的块号 */ public class PackingSequence { int[] avail; //各种剩余箱子的数目 List<Plan> plan; //一个放置列表 SpaceStack spaceStack; //剩余空间堆栈 double volume; //被装 <SUF> int depth; //深度 public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } public int[] getAvail() { return avail; } public void setAvail(int[] avail) { this.avail = avail; } public SpaceStack getSpaceStack() { return spaceStack; } public void setSpaceStack(SpaceStack spaceStack) { this.spaceStack = spaceStack; } public List<Plan> getPlan() { return plan; } public void setPlan(List<Plan> plan) { this.plan = plan; } }
false
265
7
291
10
309
8
291
10
383
16
false
false
false
false
false
true
57833_2
package RMI; import RMI.MeetingInterface; import RMI.MeetingInterfaceImpl; import java.rmi.Naming; import java.rmi.registry.LocateRegistry; /** * RMI 服务器 * * @author Hu Yuxi * @date 2018-12-18 * */ public class RMIServer { /** * 启动 RMI 注册服务并进行对象注册 */ public static void main(String[] args) { try { // 启动RMI注册服务,指定端口为1099 (1099为默认端口) // 也可以通过命令 $java_home/bin/rmiregistry 1099启动 // 这里用这种方式避免了再打开一个DOS窗口 // 而且用命令rmi registry启动注册服务还必须事先用RMIC生成一个stub类为它所用 LocateRegistry.createRegistry(1099); // 创建远程对象的一个或多个实例,下面是MeetingInterfaceImpl对象 // 可以用不同名字注册不同的实例 MeetingInterface meetingInterface = new MeetingInterfaceImpl(); // 把hello注册到RMI注册服务器上,命名为Hello Naming.rebind("Meeting", meetingInterface); // 如果要把hello实例注册到另一台启动了RMI注册服务的机器上 // Naming.rebind("//192.168.1.105:1099/Hello",hello); System.out.println("RMI Meeting Server is ready."); } catch (Exception e) { System.out.println("RMI Meeting Server failed: " + e); } } }
YuhsiHu/SSD8-Network-and-distributed-computing
RMI/RMI/RMIServer.java
384
// 启动RMI注册服务,指定端口为1099 (1099为默认端口)
line_comment
zh-cn
package RMI; import RMI.MeetingInterface; import RMI.MeetingInterfaceImpl; import java.rmi.Naming; import java.rmi.registry.LocateRegistry; /** * RMI 服务器 * * @author Hu Yuxi * @date 2018-12-18 * */ public class RMIServer { /** * 启动 RMI 注册服务并进行对象注册 */ public static void main(String[] args) { try { // 启动 <SUF> // 也可以通过命令 $java_home/bin/rmiregistry 1099启动 // 这里用这种方式避免了再打开一个DOS窗口 // 而且用命令rmi registry启动注册服务还必须事先用RMIC生成一个stub类为它所用 LocateRegistry.createRegistry(1099); // 创建远程对象的一个或多个实例,下面是MeetingInterfaceImpl对象 // 可以用不同名字注册不同的实例 MeetingInterface meetingInterface = new MeetingInterfaceImpl(); // 把hello注册到RMI注册服务器上,命名为Hello Naming.rebind("Meeting", meetingInterface); // 如果要把hello实例注册到另一台启动了RMI注册服务的机器上 // Naming.rebind("//192.168.1.105:1099/Hello",hello); System.out.println("RMI Meeting Server is ready."); } catch (Exception e) { System.out.println("RMI Meeting Server failed: " + e); } } }
false
366
28
384
25
391
23
384
25
547
40
false
false
false
false
false
true
35584_17
package com.wzy.api.model.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 帖子 * * @TableName post */ @TableName(value = "post") @Data public class Post implements Serializable { /** * id */ @TableId(type = IdType.AUTO) private Long id; /** * 年龄 */ private Integer age; /** * 性别(0-男, 1-女) */ private Integer gender; /** * 学历 */ private String education; /** * 地点 */ private String place; /** * 职业 */ private String job; /** * 联系方式 */ private String contact; /** * 感情经历 */ private String loveExp; /** * 内容(个人介绍) */ private String content; /** * 照片地址 */ private String photo; /** * 状态(0-待审核, 1-通过, 2-拒绝) */ private Integer reviewStatus; /** * 审核信息 */ private String reviewMessage; /** * 浏览数 */ private Integer viewNum; /** * 点赞数 */ private Integer thumbNum; /** * 创建用户 id */ private Long userId; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; /** * 是否删除 */ @TableLogic private Integer isDelete; @TableField(exist = false) private static final long serialVersionUID = 1L; }
YukeSeko/YukeSeko-Interface
api/src/main/java/com/wzy/api/model/entity/Post.java
411
/** * 更新时间 */
block_comment
zh-cn
package com.wzy.api.model.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 帖子 * * @TableName post */ @TableName(value = "post") @Data public class Post implements Serializable { /** * id */ @TableId(type = IdType.AUTO) private Long id; /** * 年龄 */ private Integer age; /** * 性别(0-男, 1-女) */ private Integer gender; /** * 学历 */ private String education; /** * 地点 */ private String place; /** * 职业 */ private String job; /** * 联系方式 */ private String contact; /** * 感情经历 */ private String loveExp; /** * 内容(个人介绍) */ private String content; /** * 照片地址 */ private String photo; /** * 状态(0-待审核, 1-通过, 2-拒绝) */ private Integer reviewStatus; /** * 审核信息 */ private String reviewMessage; /** * 浏览数 */ private Integer viewNum; /** * 点赞数 */ private Integer thumbNum; /** * 创建用户 id */ private Long userId; /** * 创建时间 */ private Date createTime; /** * 更新时 <SUF>*/ private Date updateTime; /** * 是否删除 */ @TableLogic private Integer isDelete; @TableField(exist = false) private static final long serialVersionUID = 1L; }
false
399
8
411
7
463
9
411
7
581
12
false
false
false
false
false
true
20168_1
package com.effective.android.base.util; import androidx.annotation.NonNull; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * 动态时间格式化 * Created by scwang on 2017/6/17. */ public class TimeFormatUtils extends SimpleDateFormat { private static Locale locale = Locale.CHINA; private static String weeks[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}; private static String moments[] = {"中午", "凌晨", "早上", "下午", "晚上"}; private String mFormat = "%s"; public TimeFormatUtils() { this("%s", "yyyy年", "M月d日", "HH:mm"); } public TimeFormatUtils(String format) { this(); this.mFormat = format; } public TimeFormatUtils(String yearFormat, String dateFormat, String timeFormat) { super(String.format(locale, "%s %s %s", yearFormat, dateFormat, timeFormat), locale); } public TimeFormatUtils(String format, String yearFormat, String dateFormat, String timeFormat) { this(yearFormat, dateFormat, timeFormat); this.mFormat = format; } @Override public StringBuffer format(@NonNull Date date, @NonNull StringBuffer toAppendTo, @NonNull FieldPosition pos) { toAppendTo = super.format(date, toAppendTo, pos); Calendar otherCalendar = calendar; Calendar todayCalendar = Calendar.getInstance(); int hour = otherCalendar.get(Calendar.HOUR_OF_DAY); String[] times = toAppendTo.toString().split(" "); String moment = hour == 12 ? moments[0] : moments[hour / 6 + 1]; String timeFormat = moment + " " + times[2]; String dateFormat = times[1] + " " + timeFormat; String yearFormat = times[0] + dateFormat; toAppendTo.delete(0, toAppendTo.length()); boolean yearTemp = todayCalendar.get(Calendar.YEAR) == otherCalendar.get(Calendar.YEAR); if (yearTemp) { int todayMonth = todayCalendar.get(Calendar.MONTH); int otherMonth = otherCalendar.get(Calendar.MONTH); if (todayMonth == otherMonth) {//表示是同一个月 int temp = todayCalendar.get(Calendar.DATE) - otherCalendar.get(Calendar.DATE); switch (temp) { case 0: toAppendTo.append(timeFormat); break; case 1: toAppendTo.append("昨天 "); toAppendTo.append(timeFormat); break; case 2: toAppendTo.append("前天 "); toAppendTo.append(timeFormat); break; case 3: case 4: case 5: case 6: int dayOfMonth = otherCalendar.get(Calendar.WEEK_OF_MONTH); int todayOfMonth = todayCalendar.get(Calendar.WEEK_OF_MONTH); if (dayOfMonth == todayOfMonth) {//表示是同一周 int dayOfWeek = otherCalendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek != 1) {//判断当前是不是星期日 如想显示为:周日 12:09 可去掉此判断 toAppendTo.append(weeks[otherCalendar.get(Calendar.DAY_OF_WEEK) - 1]); toAppendTo.append(' '); toAppendTo.append(timeFormat); } else { toAppendTo.append(dateFormat); } } else { toAppendTo.append(dateFormat); } break; default: toAppendTo.append(dateFormat); break; } } else { toAppendTo.append(dateFormat); } } else { toAppendTo.append(yearFormat); } int length = toAppendTo.length(); toAppendTo.append(String.format(locale, mFormat, toAppendTo.toString())); toAppendTo.delete(0, length); return toAppendTo; } }
YummyLau/AndroidModularArchiteture
libBase/src/main/java/com/effective/android/base/util/TimeFormatUtils.java
989
//表示是同一个月
line_comment
zh-cn
package com.effective.android.base.util; import androidx.annotation.NonNull; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * 动态时间格式化 * Created by scwang on 2017/6/17. */ public class TimeFormatUtils extends SimpleDateFormat { private static Locale locale = Locale.CHINA; private static String weeks[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}; private static String moments[] = {"中午", "凌晨", "早上", "下午", "晚上"}; private String mFormat = "%s"; public TimeFormatUtils() { this("%s", "yyyy年", "M月d日", "HH:mm"); } public TimeFormatUtils(String format) { this(); this.mFormat = format; } public TimeFormatUtils(String yearFormat, String dateFormat, String timeFormat) { super(String.format(locale, "%s %s %s", yearFormat, dateFormat, timeFormat), locale); } public TimeFormatUtils(String format, String yearFormat, String dateFormat, String timeFormat) { this(yearFormat, dateFormat, timeFormat); this.mFormat = format; } @Override public StringBuffer format(@NonNull Date date, @NonNull StringBuffer toAppendTo, @NonNull FieldPosition pos) { toAppendTo = super.format(date, toAppendTo, pos); Calendar otherCalendar = calendar; Calendar todayCalendar = Calendar.getInstance(); int hour = otherCalendar.get(Calendar.HOUR_OF_DAY); String[] times = toAppendTo.toString().split(" "); String moment = hour == 12 ? moments[0] : moments[hour / 6 + 1]; String timeFormat = moment + " " + times[2]; String dateFormat = times[1] + " " + timeFormat; String yearFormat = times[0] + dateFormat; toAppendTo.delete(0, toAppendTo.length()); boolean yearTemp = todayCalendar.get(Calendar.YEAR) == otherCalendar.get(Calendar.YEAR); if (yearTemp) { int todayMonth = todayCalendar.get(Calendar.MONTH); int otherMonth = otherCalendar.get(Calendar.MONTH); if (todayMonth == otherMonth) {//表示 <SUF> int temp = todayCalendar.get(Calendar.DATE) - otherCalendar.get(Calendar.DATE); switch (temp) { case 0: toAppendTo.append(timeFormat); break; case 1: toAppendTo.append("昨天 "); toAppendTo.append(timeFormat); break; case 2: toAppendTo.append("前天 "); toAppendTo.append(timeFormat); break; case 3: case 4: case 5: case 6: int dayOfMonth = otherCalendar.get(Calendar.WEEK_OF_MONTH); int todayOfMonth = todayCalendar.get(Calendar.WEEK_OF_MONTH); if (dayOfMonth == todayOfMonth) {//表示是同一周 int dayOfWeek = otherCalendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek != 1) {//判断当前是不是星期日 如想显示为:周日 12:09 可去掉此判断 toAppendTo.append(weeks[otherCalendar.get(Calendar.DAY_OF_WEEK) - 1]); toAppendTo.append(' '); toAppendTo.append(timeFormat); } else { toAppendTo.append(dateFormat); } } else { toAppendTo.append(dateFormat); } break; default: toAppendTo.append(dateFormat); break; } } else { toAppendTo.append(dateFormat); } } else { toAppendTo.append(yearFormat); } int length = toAppendTo.length(); toAppendTo.append(String.format(locale, mFormat, toAppendTo.toString())); toAppendTo.delete(0, length); return toAppendTo; } }
false
851
5
989
6
1,037
5
989
6
1,186
8
false
false
false
false
false
true
37097_1
import java.util.List; public abstract class ladderChoice { /** * 传入所有的梯子和当前需要决策的一只猴子,返回决策后猴子应该上的梯子对象,如果猴子不应该上梯子,则返回null * * @param monkey 需要做上哪个梯子决策的猴子 * @param ladderList 所有可供选择的梯子 * @return 做出的决策的梯子,如果猴子不上梯子,就返回null */ public abstract Ladder getLadder(Monkey monkey, List<Ladder> ladderList); /** * 用于产生随机的猴子过河策略 * * @return 一种随机的过河策略对象,策略是已经实现的策略之一 */ static ladderChoice getChoice() { double choice = Math.random() * 3; // if (choice > 0 && choice <= 1) // return new firstStrategy(); // else if (choice > 1 && choice <= 2) // return new secondStrategy(); // else return new thirdStrategy(); } }
YunFeng0817/Software-Lab6
src/ladderChoice.java
277
/** * 用于产生随机的猴子过河策略 * * @return 一种随机的过河策略对象,策略是已经实现的策略之一 */
block_comment
zh-cn
import java.util.List; public abstract class ladderChoice { /** * 传入所有的梯子和当前需要决策的一只猴子,返回决策后猴子应该上的梯子对象,如果猴子不应该上梯子,则返回null * * @param monkey 需要做上哪个梯子决策的猴子 * @param ladderList 所有可供选择的梯子 * @return 做出的决策的梯子,如果猴子不上梯子,就返回null */ public abstract Ladder getLadder(Monkey monkey, List<Ladder> ladderList); /** * 用于产 <SUF>*/ static ladderChoice getChoice() { double choice = Math.random() * 3; // if (choice > 0 && choice <= 1) // return new firstStrategy(); // else if (choice > 1 && choice <= 2) // return new secondStrategy(); // else return new thirdStrategy(); } }
false
245
38
277
39
253
39
277
39
391
78
false
false
false
false
false
true
22408_0
/**注意:本软件从3.2之后推出少月版,自此小米人少月版由本人负责 * @author 七少月 * @author Mandarava(原程序开发) * 2016-2018 *本次为2017年8月8日更新的3.5.0版本 **/ public class ApkIDE { public String 培训动态="新增渗透风控、armvmp实现、https开发与抓包、虚拟机加固脱壳、ollvm等最新课程!" public String 软件名称="APK改之理(少月版)"; public String 软件类型="免费软件"; public String 软件别名="APK IDE(少月版)"; public String 程序开发="七少月"; public String 原版小米人开发(3.1版之前)="mandarava"; public String 联系邮箱="[email protected]"; public String 官方技术交流QQ群1="泗县软件技术交流协会,309357280"; public String 官方技术交流QQ群2="移动安全预前班,530097946"; public String 官方技术交流QQ群3="移动安全预前班2,460047982"; public String i春秋官方网站="https://www.ichunqiu.com/"; public String 友情网站1="逆向未来技术社区(http://www.pd521.com/)"; public String 友情网站2="看雪安全论坛(http://bbs.pediy.com/)"; public String 友情网站3="吾爱破解论坛(http://www.52pojie.cn/)"; public String 版权信息="版权所有(C)2016-2018, 七少月与Mandarava共同保留部分权利."; public String 软件简介="一个可视化的、易用的、快捷的、一体化的APK修改工具."; public String 一个提示="按住Ctrl键,右键单击左侧目录或搜索结果中的文件会弹出系统右键菜单"; public String 更多信息="请联系作者QQ:397216633,欢迎支持"; public String 感谢信息="感谢小米人,吾爱论坛,看雪安全论坛,逆向未来论坛,当然还有一直为逆向努力的大家"; }
YunLambert/TravelFrog_Tool
ApkIDE/Appres/Start.java
637
/**注意:本软件从3.2之后推出少月版,自此小米人少月版由本人负责 * @author 七少月 * @author Mandarava(原程序开发) * 2016-2018 *本次为2017年8月8日更新的3.5.0版本 **/
block_comment
zh-cn
/**注意: <SUF>*/ public class ApkIDE { public String 培训动态="新增渗透风控、armvmp实现、https开发与抓包、虚拟机加固脱壳、ollvm等最新课程!" public String 软件名称="APK改之理(少月版)"; public String 软件类型="免费软件"; public String 软件别名="APK IDE(少月版)"; public String 程序开发="七少月"; public String 原版小米人开发(3.1版之前)="mandarava"; public String 联系邮箱="[email protected]"; public String 官方技术交流QQ群1="泗县软件技术交流协会,309357280"; public String 官方技术交流QQ群2="移动安全预前班,530097946"; public String 官方技术交流QQ群3="移动安全预前班2,460047982"; public String i春秋官方网站="https://www.ichunqiu.com/"; public String 友情网站1="逆向未来技术社区(http://www.pd521.com/)"; public String 友情网站2="看雪安全论坛(http://bbs.pediy.com/)"; public String 友情网站3="吾爱破解论坛(http://www.52pojie.cn/)"; public String 版权信息="版权所有(C)2016-2018, 七少月与Mandarava共同保留部分权利."; public String 软件简介="一个可视化的、易用的、快捷的、一体化的APK修改工具."; public String 一个提示="按住Ctrl键,右键单击左侧目录或搜索结果中的文件会弹出系统右键菜单"; public String 更多信息="请联系作者QQ:397216633,欢迎支持"; public String 感谢信息="感谢小米人,吾爱论坛,看雪安全论坛,逆向未来论坛,当然还有一直为逆向努力的大家"; }
false
552
79
637
86
553
79
637
86
864
101
false
false
false
false
false
true
13040_1
package cn.iocoder.yudao.module.pay.api.order.dto; import cn.iocoder.yudao.module.pay.enums.order.PayOrderStatusEnum; import lombok.Data; /** * 支付单信息 Response DTO * * @author 芋道源码 */ @Data public class PayOrderRespDTO { /** * 订单编号,数据库自增 */ private Long id; /** * 渠道编码 * * 枚举 PayChannelEnum */ private String channelCode; // ========== 商户相关字段 ========== /** * 商户订单编号 * 例如说,内部系统 A 的订单号。需要保证每个 PayMerchantDO 唯一 */ private String merchantOrderId; // ========== 订单相关字段 ========== /** * 支付金额,单位:分 */ private Integer price; /** * 支付状态 * * 枚举 {@link PayOrderStatusEnum} */ private Integer status; // ========== 渠道相关字段 ========== }
YunaiV/ruoyi-vue-pro
yudao-module-pay/yudao-module-pay-api/src/main/java/cn/iocoder/yudao/module/pay/api/order/dto/PayOrderRespDTO.java
244
/** * 订单编号,数据库自增 */
block_comment
zh-cn
package cn.iocoder.yudao.module.pay.api.order.dto; import cn.iocoder.yudao.module.pay.enums.order.PayOrderStatusEnum; import lombok.Data; /** * 支付单信息 Response DTO * * @author 芋道源码 */ @Data public class PayOrderRespDTO { /** * 订单编 <SUF>*/ private Long id; /** * 渠道编码 * * 枚举 PayChannelEnum */ private String channelCode; // ========== 商户相关字段 ========== /** * 商户订单编号 * 例如说,内部系统 A 的订单号。需要保证每个 PayMerchantDO 唯一 */ private String merchantOrderId; // ========== 订单相关字段 ========== /** * 支付金额,单位:分 */ private Integer price; /** * 支付状态 * * 枚举 {@link PayOrderStatusEnum} */ private Integer status; // ========== 渠道相关字段 ========== }
false
231
13
244
12
257
13
244
12
355
22
false
false
false
false
false
true
38097_3
package yuzunyannn.elementalsorcery.block; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.BlockBush; import net.minecraft.block.IGrowable; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import yuzunyannn.elementalsorcery.advancement.ESCriteriaTriggers; import yuzunyannn.elementalsorcery.api.ESObjects; import yuzunyannn.elementalsorcery.config.Config; import yuzunyannn.elementalsorcery.render.effect.Effect; import yuzunyannn.elementalsorcery.render.effect.batch.EffectElement; import yuzunyannn.elementalsorcery.tile.TileCrystalFlower; import yuzunyannn.elementalsorcery.tile.TileLifeDirt; import yuzunyannn.elementalsorcery.util.helper.RandomHelper; public class BlockLifeFlower extends Block { @Config private float PROBABILITY_OF_CONSUME_MAIGC_PER_GROW = 0.02f; public static final AxisAlignedBB AABB = new AxisAlignedBB(0.09999999403953552D, 0.0D, 0.09999999403953552D, 0.8999999761581421D, 0.800000011920929D, 0.8999999761581421D); public BlockLifeFlower() { super(Material.PLANTS); this.setTranslationKey("lifeFlower"); this.setSoundType(SoundType.PLANT); this.setTickRandomly(true); this.setLightLevel(1); } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return AABB; } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.CUTOUT; } @Override public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) { return BlockFaceShape.UNDEFINED; } @Nullable public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return NULL_AABB; } @Override public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { if (!pos.down().equals(fromPos)) return; if (world.getBlockState(fromPos).getBlock() != ESObjects.BLOCKS.MAGIC_POT) { this.dropBlockAsItem(world, pos, state, 0); world.setBlockToAir(pos); } } @Override public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { if (!this.isIntact(worldIn, pos)) return; if (placer instanceof EntityPlayerMP) ESCriteriaTriggers.ES_TRING.trigger((EntityPlayerMP) placer, "build:garden"); } @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { return worldIn.getBlockState(pos.down()).getBlock() == ESObjects.BLOCKS.MAGIC_POT; } public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isFullCube(IBlockState state) { return false; } private boolean hasPower(World worldIn, BlockPos pos) { IBlockState state = worldIn.getBlockState(pos.down()); if (state.getBlock() != ESObjects.BLOCKS.MAGIC_POT) return false; return ((BlockMagicPot) state.getBlock()).hasPower(worldIn, state, pos.down()); } private boolean isIntact(World worldIn, BlockPos pos) { IBlockState state = worldIn.getBlockState(pos.down()); if (state.getBlock() != ESObjects.BLOCKS.MAGIC_POT) return false; return ((BlockMagicPot) state.getBlock()).isIntact(worldIn, pos.down()); } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) { if (!this.hasPower(worldIn, pos)) return; Vec3d v3d = new Vec3d(pos).add(0.5, 0.5, 0.5); v3d = v3d.add(Math.random() - 0.5, Math.random() - 0.25, Math.random() - 0.5); EffectElement effect = new EffectElement(worldIn, v3d.x, v3d.y, v3d.z); effect.setColor(RandomHelper.rand.nextInt()); Effect.addEffect(effect); } @Override public void updateTick(World world, BlockPos flowerPos, IBlockState state, Random rand) { if (!this.hasPower(world, flowerPos)) return; growAll(world, flowerPos); if (world.isRemote) return; BlockPos potPos = flowerPos.down(); IBlockState potState = world.getBlockState(potPos); int magic = potState.getValue(BlockMagicPot.MAGIC); if (magic <= 0) return; if (rand.nextDouble() < PROBABILITY_OF_CONSUME_MAIGC_PER_GROW) world.setBlockState(potPos, potState.withProperty(BlockMagicPot.MAGIC, magic - 1)); } public void tryGrowAll(World world, BlockPos flowerPos) { if (!this.hasPower(world, flowerPos)) return; growAll(world, flowerPos); } /** 成长所有内容一次 */ public void growAll(World world, BlockPos flowerPos) { BlockPos center = flowerPos.down(2); for (int x = -4; x <= 4; x++) { for (int z = -4; z <= 4; z++) { BlockPos pos = center.add(x, 0, z); if (world.getBlockState(pos).getBlock() != ESObjects.BLOCKS.LIFE_DIRT) continue; grow(world, pos); } } } protected void grow(World world, BlockPos pos) { if (world.rand.nextInt(2) == 0) return; // 检查上方是否有已经的植物 if (world.isAirBlock(pos.up())) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileLifeDirt) newGrow(world, pos, (TileLifeDirt) tile); return; } // 上方已有方块,检测是否可以成长 pos = pos.up(); IBlockState state = world.getBlockState(pos); Block block = state.getBlock(); if (block instanceof IGrowable == false) { if (world.isRemote) return; if (block == Blocks.REEDS || block == Blocks.CACTUS) growUp(world, pos, 2); return; } // 长大 IGrowable growable = ((IGrowable) block); if (growable.canGrow(world, pos, state, world.isRemote)) { if (world.isRemote) return; if (block == ESObjects.BLOCKS.CRYSTAL_FLOWER) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileCrystalFlower) { // 这里可以做一些操作=-=-=-=-=-=-=-=-= } } growable.grow(world, world.rand, pos, state); } } public static void growUp(World world, BlockPos pos, int max) { if (world.isAirBlock(pos)) return; IBlockState state = world.getBlockState(pos); for (int i = 0; i < max; i++) { pos = pos.up(); if (world.isAirBlock(pos)) { world.setBlockState(pos, state); return; } if (world.getBlockState(pos).getBlock() != state.getBlock()) return; } } private void newGrow(World world, BlockPos pos, TileLifeDirt tile) { if (world.isRemote) return; // 生成新的 ItemStack plant = tile.getPlant(); // 没有植物索性移除tileentity if (plant.isEmpty()) { world.removeTileEntity(pos); return; } Item item = plant.getItem(); Block block = Block.getBlockFromItem(item); if (item instanceof IPlantable) { IBlockState state = ((IPlantable) item).getPlant(world, pos); world.setBlockState(pos.up(), state); } else if (block instanceof IGrowable || block == Blocks.CACTUS) { world.setBlockState(pos.up(), block.getDefaultState()); } else if (item == Items.REEDS) { world.setBlockState(pos.up(), Blocks.REEDS.getDefaultState()); } else if (block instanceof BlockBush) { world.setBlockState(pos.up(), block.getStateFromMeta(plant.getMetadata())); } else { world.setBlockState(pos.up(), ESObjects.BLOCKS.CRYSTAL_FLOWER.getDefaultState()); TileEntity t = world.getTileEntity(pos.up()); if (t instanceof TileCrystalFlower) ((TileCrystalFlower) t).setCrystal(tile.getPlant()); } } }
Yuzunyannn/ElementalSorcery
src/main/java/yuzunyannn/elementalsorcery/block/BlockLifeFlower.java
2,750
// 长大
line_comment
zh-cn
package yuzunyannn.elementalsorcery.block; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.BlockBush; import net.minecraft.block.IGrowable; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import yuzunyannn.elementalsorcery.advancement.ESCriteriaTriggers; import yuzunyannn.elementalsorcery.api.ESObjects; import yuzunyannn.elementalsorcery.config.Config; import yuzunyannn.elementalsorcery.render.effect.Effect; import yuzunyannn.elementalsorcery.render.effect.batch.EffectElement; import yuzunyannn.elementalsorcery.tile.TileCrystalFlower; import yuzunyannn.elementalsorcery.tile.TileLifeDirt; import yuzunyannn.elementalsorcery.util.helper.RandomHelper; public class BlockLifeFlower extends Block { @Config private float PROBABILITY_OF_CONSUME_MAIGC_PER_GROW = 0.02f; public static final AxisAlignedBB AABB = new AxisAlignedBB(0.09999999403953552D, 0.0D, 0.09999999403953552D, 0.8999999761581421D, 0.800000011920929D, 0.8999999761581421D); public BlockLifeFlower() { super(Material.PLANTS); this.setTranslationKey("lifeFlower"); this.setSoundType(SoundType.PLANT); this.setTickRandomly(true); this.setLightLevel(1); } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return AABB; } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.CUTOUT; } @Override public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) { return BlockFaceShape.UNDEFINED; } @Nullable public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return NULL_AABB; } @Override public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { if (!pos.down().equals(fromPos)) return; if (world.getBlockState(fromPos).getBlock() != ESObjects.BLOCKS.MAGIC_POT) { this.dropBlockAsItem(world, pos, state, 0); world.setBlockToAir(pos); } } @Override public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { if (!this.isIntact(worldIn, pos)) return; if (placer instanceof EntityPlayerMP) ESCriteriaTriggers.ES_TRING.trigger((EntityPlayerMP) placer, "build:garden"); } @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { return worldIn.getBlockState(pos.down()).getBlock() == ESObjects.BLOCKS.MAGIC_POT; } public boolean isOpaqueCube(IBlockState state) { return false; } public boolean isFullCube(IBlockState state) { return false; } private boolean hasPower(World worldIn, BlockPos pos) { IBlockState state = worldIn.getBlockState(pos.down()); if (state.getBlock() != ESObjects.BLOCKS.MAGIC_POT) return false; return ((BlockMagicPot) state.getBlock()).hasPower(worldIn, state, pos.down()); } private boolean isIntact(World worldIn, BlockPos pos) { IBlockState state = worldIn.getBlockState(pos.down()); if (state.getBlock() != ESObjects.BLOCKS.MAGIC_POT) return false; return ((BlockMagicPot) state.getBlock()).isIntact(worldIn, pos.down()); } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) { if (!this.hasPower(worldIn, pos)) return; Vec3d v3d = new Vec3d(pos).add(0.5, 0.5, 0.5); v3d = v3d.add(Math.random() - 0.5, Math.random() - 0.25, Math.random() - 0.5); EffectElement effect = new EffectElement(worldIn, v3d.x, v3d.y, v3d.z); effect.setColor(RandomHelper.rand.nextInt()); Effect.addEffect(effect); } @Override public void updateTick(World world, BlockPos flowerPos, IBlockState state, Random rand) { if (!this.hasPower(world, flowerPos)) return; growAll(world, flowerPos); if (world.isRemote) return; BlockPos potPos = flowerPos.down(); IBlockState potState = world.getBlockState(potPos); int magic = potState.getValue(BlockMagicPot.MAGIC); if (magic <= 0) return; if (rand.nextDouble() < PROBABILITY_OF_CONSUME_MAIGC_PER_GROW) world.setBlockState(potPos, potState.withProperty(BlockMagicPot.MAGIC, magic - 1)); } public void tryGrowAll(World world, BlockPos flowerPos) { if (!this.hasPower(world, flowerPos)) return; growAll(world, flowerPos); } /** 成长所有内容一次 */ public void growAll(World world, BlockPos flowerPos) { BlockPos center = flowerPos.down(2); for (int x = -4; x <= 4; x++) { for (int z = -4; z <= 4; z++) { BlockPos pos = center.add(x, 0, z); if (world.getBlockState(pos).getBlock() != ESObjects.BLOCKS.LIFE_DIRT) continue; grow(world, pos); } } } protected void grow(World world, BlockPos pos) { if (world.rand.nextInt(2) == 0) return; // 检查上方是否有已经的植物 if (world.isAirBlock(pos.up())) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileLifeDirt) newGrow(world, pos, (TileLifeDirt) tile); return; } // 上方已有方块,检测是否可以成长 pos = pos.up(); IBlockState state = world.getBlockState(pos); Block block = state.getBlock(); if (block instanceof IGrowable == false) { if (world.isRemote) return; if (block == Blocks.REEDS || block == Blocks.CACTUS) growUp(world, pos, 2); return; } // 长大 <SUF> IGrowable growable = ((IGrowable) block); if (growable.canGrow(world, pos, state, world.isRemote)) { if (world.isRemote) return; if (block == ESObjects.BLOCKS.CRYSTAL_FLOWER) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileCrystalFlower) { // 这里可以做一些操作=-=-=-=-=-=-=-=-= } } growable.grow(world, world.rand, pos, state); } } public static void growUp(World world, BlockPos pos, int max) { if (world.isAirBlock(pos)) return; IBlockState state = world.getBlockState(pos); for (int i = 0; i < max; i++) { pos = pos.up(); if (world.isAirBlock(pos)) { world.setBlockState(pos, state); return; } if (world.getBlockState(pos).getBlock() != state.getBlock()) return; } } private void newGrow(World world, BlockPos pos, TileLifeDirt tile) { if (world.isRemote) return; // 生成新的 ItemStack plant = tile.getPlant(); // 没有植物索性移除tileentity if (plant.isEmpty()) { world.removeTileEntity(pos); return; } Item item = plant.getItem(); Block block = Block.getBlockFromItem(item); if (item instanceof IPlantable) { IBlockState state = ((IPlantable) item).getPlant(world, pos); world.setBlockState(pos.up(), state); } else if (block instanceof IGrowable || block == Blocks.CACTUS) { world.setBlockState(pos.up(), block.getDefaultState()); } else if (item == Items.REEDS) { world.setBlockState(pos.up(), Blocks.REEDS.getDefaultState()); } else if (block instanceof BlockBush) { world.setBlockState(pos.up(), block.getStateFromMeta(plant.getMetadata())); } else { world.setBlockState(pos.up(), ESObjects.BLOCKS.CRYSTAL_FLOWER.getDefaultState()); TileEntity t = world.getTileEntity(pos.up()); if (t instanceof TileCrystalFlower) ((TileCrystalFlower) t).setCrystal(tile.getPlant()); } } }
false
2,228
6
2,718
5
2,658
4
2,718
5
3,180
5
false
false
false
false
false
true
23287_3
package com.duixiang; public class Phone { /** * 类如何定义 * public class 类的名称{} * * 手机类抽象的概念 * 1.成员属性 * 2.成员方法 */ String brand;//手机品牌 double price;//手机价格 /** * 拨打电话 */ public void call(){ System.out.println("使用"+brand+"拨打电话"); } public void sendMsg(){ System.out.println("发送短信"); } }
Yxj00/Mytest1
Phone.java
127
/** * 拨打电话 */
block_comment
zh-cn
package com.duixiang; public class Phone { /** * 类如何定义 * public class 类的名称{} * * 手机类抽象的概念 * 1.成员属性 * 2.成员方法 */ String brand;//手机品牌 double price;//手机价格 /** * 拨打电 <SUF>*/ public void call(){ System.out.println("使用"+brand+"拨打电话"); } public void sendMsg(){ System.out.println("发送短信"); } }
false
117
10
127
10
133
10
127
10
180
14
false
false
false
false
false
true
59211_5
package perception; import org.neuroph.core.Connection; import org.neuroph.core.Layer; import org.neuroph.core.NeuralNetwork; import org.neuroph.core.Neuron; import org.neuroph.core.transfer.TransferFunction; import org.neuroph.nnet.comp.neuron.BiasNeuron; import org.neuroph.nnet.comp.neuron.InputNeuron; import org.neuroph.util.*; /** * @Author: 李钰萍 * @Description: * @Date: Created in 2018/3/18 12:09 */ public class MyAndPerceptionNolearn extends NeuralNetwork { public MyAndPerceptionNolearn(int inputNeuronsCount){ createNetwork(inputNeuronsCount); } private void createNetwork(int inputNeuronsCount){ //设置网络类型为感知机 this.setNetworkType(NeuralNetworkType.PERCEPTRON); //建立输入神经元,表示输入的刺激 NeuronProperties inputNeuronProperties = new NeuronProperties(); inputNeuronProperties.setProperty("neuronType",InputNeuron.class); //由输入神经元构成的输入层 Layer inputLayer = LayerFactory.createLayer(inputNeuronsCount,inputNeuronProperties); this.addLayer(inputLayer); //在输入层增加BiasNeuron,表示神经元偏执 inputLayer.addNeuron(new BiasNeuron()); //建立输出神经元,设置传输函数为step()函数 NeuronProperties outputNeuronPerperties = new NeuronProperties(); outputNeuronPerperties.setProperty("transferFunction", TransferFunctionType.STEP); //由输出神经元构成的输出层 Layer outputLayer = LayerFactory.createLayer(1,outputNeuronPerperties); this.addLayer(outputLayer); //将输入层和输出层进行全连接 ConnectionFactory.fullConnect(inputLayer,outputLayer); NeuralNetworkFactory.setDefaultIO(this); //设置输入神经元和感知机之间的连接权重 Neuron n = outputLayer.getNeuronAt(0); n.getInputConnections()[0].getWeight().setValue(1); n.getInputConnections()[1].getWeight().setValue(1); n.getInputConnections()[2].getWeight().setValue(-1.5); } }
ZBIGBEAR/neuroph
src/perception/MyAndPerceptionNolearn.java
547
//建立输出神经元,设置传输函数为step()函数
line_comment
zh-cn
package perception; import org.neuroph.core.Connection; import org.neuroph.core.Layer; import org.neuroph.core.NeuralNetwork; import org.neuroph.core.Neuron; import org.neuroph.core.transfer.TransferFunction; import org.neuroph.nnet.comp.neuron.BiasNeuron; import org.neuroph.nnet.comp.neuron.InputNeuron; import org.neuroph.util.*; /** * @Author: 李钰萍 * @Description: * @Date: Created in 2018/3/18 12:09 */ public class MyAndPerceptionNolearn extends NeuralNetwork { public MyAndPerceptionNolearn(int inputNeuronsCount){ createNetwork(inputNeuronsCount); } private void createNetwork(int inputNeuronsCount){ //设置网络类型为感知机 this.setNetworkType(NeuralNetworkType.PERCEPTRON); //建立输入神经元,表示输入的刺激 NeuronProperties inputNeuronProperties = new NeuronProperties(); inputNeuronProperties.setProperty("neuronType",InputNeuron.class); //由输入神经元构成的输入层 Layer inputLayer = LayerFactory.createLayer(inputNeuronsCount,inputNeuronProperties); this.addLayer(inputLayer); //在输入层增加BiasNeuron,表示神经元偏执 inputLayer.addNeuron(new BiasNeuron()); //建立 <SUF> NeuronProperties outputNeuronPerperties = new NeuronProperties(); outputNeuronPerperties.setProperty("transferFunction", TransferFunctionType.STEP); //由输出神经元构成的输出层 Layer outputLayer = LayerFactory.createLayer(1,outputNeuronPerperties); this.addLayer(outputLayer); //将输入层和输出层进行全连接 ConnectionFactory.fullConnect(inputLayer,outputLayer); NeuralNetworkFactory.setDefaultIO(this); //设置输入神经元和感知机之间的连接权重 Neuron n = outputLayer.getNeuronAt(0); n.getInputConnections()[0].getWeight().setValue(1); n.getInputConnections()[1].getWeight().setValue(1); n.getInputConnections()[2].getWeight().setValue(-1.5); } }
false
491
13
547
14
539
13
547
14
714
20
false
false
false
false
false
true
40055_17
package com.alex.crawl.main; import com.alex.crawl.page.HttpCrawl; import com.alex.crawl.util.CrawlThread; import com.alex.crawl.util.MysqlConnecter; import com.huaban.analysis.jieba.JiebaSegmenter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author zjx * @Title: ${file_name} * @Package ${package_name} * @Description: ${todo} * @date 2018/6/410:41 */ public class MyCrawl { private ArrayList<String> urlList = new ArrayList<>(); private HttpCrawl httpCrawl = new HttpCrawl(); private int index=0; private MysqlConnecter connector = new MysqlConnecter(); public static void main(String[] args){ String[]urls = { "https://blog.csdn.net/qq_14950717/article/details/78747129", "https://blog.csdn.net/xiamizy/article/details/38225993", "https://blog.csdn.net/bluishglc/article/details/80423323", "https://blog.csdn.net/trigl/article/details/50968079", "https://blog.csdn.net/pamchen/article/details/61196099", "https://blog.csdn.net/yeyingss/article/details/73087625", "https://blog.csdn.net/column/details/evermysql.html", "https://blog.csdn.net/column/details/linuxresearch.html", "https://blog.csdn.net/21cnbao/article/details/56275456", "https://www.cnblogs.com/moonlightL/p/7891803.html" }; for(int i=7;i<8;i++) { MyCrawl crawl = new MyCrawl(); crawl.urlList.add(urls[i]); CrawlThread crawlThread = new CrawlThread(crawl); Thread thread = new Thread(crawlThread); thread.start(); } } public void urlReader(){ if(index<urlList.size()) { String url = urlList.get(index); index++; //查询该url是否在blogs中存在 int c = connector.isExist("blogs","url",url); if(c>0){ System.out.println("blogs exists "+url); return; } System.out.println("index:"+index); String html = httpCrawl.getHtml(url); Document doc = Jsoup.parse(html); Elements newsList = doc.select("a"); Elements readCount = doc.select(".float-right"); Elements titleElement = doc.select(".title-article"); Elements tagsElements = doc.select(".tags-box").select("a"); String count=""; String title=""; String tags = ""; int hasReadCount=0; for(Element ele: readCount){ if(ele.text().contains("阅读数")){ count = ele.text().split(":")[1]; hasReadCount++; } } if(titleElement!=null && titleElement.size()>0){ title = titleElement.get(0).text(); hasReadCount++; } Elements article = doc.select("article"); String content = ""; if(article!=null && article.size()>0) { content = article.get(0).html(); hasReadCount++; } if(tagsElements!=null && tagsElements.size()>0){ for(Element ta : tagsElements){ tags +=ta.text()+";"; } tags = tags.substring(0,tags.length()-1); } content = getChinese(content); content = title+"#"+content; if(hasReadCount==3) { String sqlInsert = "insert into blogs(title,content,viewCount,url,tags) values('" + title + "','" + content + "',"+count+",'"+url+"','"+tags+"');"; String sqlSelect = "select * from blogs t where t.url='"+url+"'"; //System.out.println(sqlInsert); try { ArrayList<Map<String,String>> ret = connector.select(sqlSelect,"blogs"); if(ret!=null && ret.size()>0){ System.out.println(url+" 已经存在!"); }else { connector.insert(sqlInsert); System.out.println(url+" 保存成功!"); } }catch(Exception e){ System.out.println("插入失败:"+sqlInsert); } } for (Element element : newsList) { String nextUrl = element.attr("href"); String title1 = element.text(); if(nextUrl.contains("csdn") && !nextUrl.contains("month")) { int a = connector.isExist("urls","url",nextUrl); int b = connector.isExist("blogs","url",nextUrl); if(a==0 && b==0) { String sqlInsert = "insert into urls(url) values('" + nextUrl + "')"; connector.insert(sqlInsert); System.out.println("save to urls "+nextUrl); }else if(a>0){ System.out.println("urls exists "+nextUrl); }else if(b>0){ System.out.println("blogs exists "+nextUrl); } //urlList.add(nextUrl); } } }else{ index=0; getURLs(); System.out.println("没有可用网址"); } } public void getURLs(){ /* for(int i=0;i<urlList.size();i++){ int c = connector.isExist("url",urlList.get(i)); if(c>0){ continue; }else{ String sqlInsert = "insert into urls(url) values('"+urlList.get(i)+"')"; connector.insert(sqlInsert); } }*/ String sqlDelete = "delete from urls where url in ("; String urls = ""; for(int i=0;i<urlList.size();i++){ urls+="'"+urlList.get(i)+"',"; } sqlDelete+= urls.substring(0,urls.length()-1)+")"; int c = connector.delete(sqlDelete); System.out.println(sqlDelete+","+c); urlList.clear(); String sqlSelect = "select distinct id,url,flag from urls limit 100"; ArrayList<Map<String,String>> ret = connector.select(sqlSelect,"urls"); for(int i=0;i<ret.size();i++){ System.out.println(ret.get(i).get("url")+" add to urlList"); if(!urlList.contains(ret.get(i).get("url"))) { urlList.add(ret.get(i).get("url")); } } } public void getKeyWord(String content){ JiebaSegmenter segmenter = new JiebaSegmenter(); System.out.println(segmenter.sentenceProcess(content)); //jieba.analyse.extract_tags(content, topK=topK, withWeight=withWeight); } /*1、至少匹配一个汉字的写法。 2、这两个unicode值正好是Unicode表中的汉字的头和尾。 3、"[]"代表里边的值出现一个就可以,后边的“+”代表至少出现1次,合起来即至少匹配一个汉字。 */ public static String getChinese(String paramValue) { String regex = "([\u4e00-\u9fa5]+)"; String str = ""; Matcher matcher = Pattern.compile(regex).matcher(paramValue); while (matcher.find()) { str+= matcher.group(0); } //去掉单引号 str = str.replaceAll("'","#"); return str; } /* public void xx(String ){ for (int i = 0; i < max_iter; ++i) { Map<String, Float> m = new HashMap<String, Float>(); float max_diff = 0; for (Map.Entry<String, Set<String>> entry : words.entrySet()) { String key = entry.getKey(); Set<String> value = entry.getValue(); m.put(key, 1 - d); for (String other : value) { int size = words.get(other).size(); if (key.equals(other) || size == 0) continue; m.put(key, m.get(key) + d / size * (score.get(other) == null ? 0 : score.get(other))); } max_diff = Math.max(max_diff, Math.abs(m.get(key) - (score.get(key) == null ? 0 : score.get(key)))); } score = m; if (max_diff <= min_diff) break; } 排序后的投票 }*/ /* public static String TFIDF (String title,String content, int topK){ FilterRecognition filterRecognition = new FilterRecognition(); filterRecognition.insertStopWords(stopWords); filterRecognition.insertStopWord("事儿", "有没有", "前有", "后有", "更多"); filterRecognition.insertStopNatures("d", "p", "m", "r", "w", "a", "j", "l","null","num"); List<Term> terms = NlpAnalysis.parse(content).recognition(filterRecognition).getTerms(); //词的总数 int totalWords= terms.size(); Map<String, Integer> wordsCount = new HashMap<String, Integer>(); //根据词的长度加权 int maxWordLen = 0; for(Term term:terms){ Integer count = wordsCount.get(term.getName()); count = count == null ? 0 : count; wordsCount.put(term.getName(), count+1); if(maxWordLen<term.getName().length()){ maxWordLen = term.getName().length(); } } //计算tf Map<String, Double> tf = new HashMap<String, Double>(); for(String word:wordsCount.keySet()){ tf.put(word, (double)wordsCount.get(word)/(totalWords+1)); } //保留词的长度 Set<Integer> perWordLen = new HashSet<Integer>(); //计算每个词的词长权重 Map<String, Double> lenWeight = new HashMap<String, Double>(); for( String key:tf.keySet()){ lenWeight.put(key, (double)key.length()/maxWordLen); perWordLen.add(key.length()); } //标题中出现的关键词 List<Term> titleTerms = NlpAnalysis.parse(title).recognition(filterRecognition).getTerms(); Map<String, String> titleWords = new HashMap<String, String>(); for(Term term:titleTerms){ titleWords.put(term.getName(), term.getNatureStr()); } //计算idf Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int len:perWordLen){ int sum = 0; for(String w:wordsCount.keySet()){ if(w.length()==len){ sum += wordsCount.get(w); } } map.put(len, sum); } Map<String, Double> idf = new HashMap<String, Double>(); for(String w:wordsCount.keySet()){ Integer integer = wordsCount.get(w); int len = w.length(); Integer totalSim = map.get(len); idf.put(w, Math.log(((double)totalSim/integer)+1)); } //计算每个词的在文章中的权重 Map<String, Double> wordWeight = new HashMap<String, Double>(); for(Term term:terms){ String word = term.getName(); String nature = term.getNatureStr(); if(word.length()<2){ continue; } if(wordWeight.get(word)!=null){ continue; } Double aDouble = tf.get(word); Double aDouble1 = idf.get(word); double weight = 1.0; if(titleWords.keySet().contains(word)){ weight += 3.0; } weight += (double)word.length()/maxWordLen; switch (nature){ case "en": weight += 3.0; case "nr": weight += 6.0; case "nrf": weight += 6.0; case "nw" : weight += 3.0; case "nt": weight += 6.0; case "nz": weight += 3.0; case "kw": weight += 3.0; case "ns": weight += 3.0; default: weight += 1.0; } wordWeight.put(word,aDouble*aDouble1*weight); } Map<String, Double> stringDoubleMap = MapUtil.sortByValue(wordWeight); List<String> topKSet = new ArrayList<String>(); int i = 0; for(String word:stringDoubleMap.keySet()){ if(i >= topK){ break; } topKSet.add(word+" `` +stringDoubleMap.get(word)); i++; } return StringUtils.join(topKSet, "\t"); }*/ }
ZBIGBEAR/spider
src/com/alex/crawl/main/MyCrawl.java
3,278
//去掉单引号
line_comment
zh-cn
package com.alex.crawl.main; import com.alex.crawl.page.HttpCrawl; import com.alex.crawl.util.CrawlThread; import com.alex.crawl.util.MysqlConnecter; import com.huaban.analysis.jieba.JiebaSegmenter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author zjx * @Title: ${file_name} * @Package ${package_name} * @Description: ${todo} * @date 2018/6/410:41 */ public class MyCrawl { private ArrayList<String> urlList = new ArrayList<>(); private HttpCrawl httpCrawl = new HttpCrawl(); private int index=0; private MysqlConnecter connector = new MysqlConnecter(); public static void main(String[] args){ String[]urls = { "https://blog.csdn.net/qq_14950717/article/details/78747129", "https://blog.csdn.net/xiamizy/article/details/38225993", "https://blog.csdn.net/bluishglc/article/details/80423323", "https://blog.csdn.net/trigl/article/details/50968079", "https://blog.csdn.net/pamchen/article/details/61196099", "https://blog.csdn.net/yeyingss/article/details/73087625", "https://blog.csdn.net/column/details/evermysql.html", "https://blog.csdn.net/column/details/linuxresearch.html", "https://blog.csdn.net/21cnbao/article/details/56275456", "https://www.cnblogs.com/moonlightL/p/7891803.html" }; for(int i=7;i<8;i++) { MyCrawl crawl = new MyCrawl(); crawl.urlList.add(urls[i]); CrawlThread crawlThread = new CrawlThread(crawl); Thread thread = new Thread(crawlThread); thread.start(); } } public void urlReader(){ if(index<urlList.size()) { String url = urlList.get(index); index++; //查询该url是否在blogs中存在 int c = connector.isExist("blogs","url",url); if(c>0){ System.out.println("blogs exists "+url); return; } System.out.println("index:"+index); String html = httpCrawl.getHtml(url); Document doc = Jsoup.parse(html); Elements newsList = doc.select("a"); Elements readCount = doc.select(".float-right"); Elements titleElement = doc.select(".title-article"); Elements tagsElements = doc.select(".tags-box").select("a"); String count=""; String title=""; String tags = ""; int hasReadCount=0; for(Element ele: readCount){ if(ele.text().contains("阅读数")){ count = ele.text().split(":")[1]; hasReadCount++; } } if(titleElement!=null && titleElement.size()>0){ title = titleElement.get(0).text(); hasReadCount++; } Elements article = doc.select("article"); String content = ""; if(article!=null && article.size()>0) { content = article.get(0).html(); hasReadCount++; } if(tagsElements!=null && tagsElements.size()>0){ for(Element ta : tagsElements){ tags +=ta.text()+";"; } tags = tags.substring(0,tags.length()-1); } content = getChinese(content); content = title+"#"+content; if(hasReadCount==3) { String sqlInsert = "insert into blogs(title,content,viewCount,url,tags) values('" + title + "','" + content + "',"+count+",'"+url+"','"+tags+"');"; String sqlSelect = "select * from blogs t where t.url='"+url+"'"; //System.out.println(sqlInsert); try { ArrayList<Map<String,String>> ret = connector.select(sqlSelect,"blogs"); if(ret!=null && ret.size()>0){ System.out.println(url+" 已经存在!"); }else { connector.insert(sqlInsert); System.out.println(url+" 保存成功!"); } }catch(Exception e){ System.out.println("插入失败:"+sqlInsert); } } for (Element element : newsList) { String nextUrl = element.attr("href"); String title1 = element.text(); if(nextUrl.contains("csdn") && !nextUrl.contains("month")) { int a = connector.isExist("urls","url",nextUrl); int b = connector.isExist("blogs","url",nextUrl); if(a==0 && b==0) { String sqlInsert = "insert into urls(url) values('" + nextUrl + "')"; connector.insert(sqlInsert); System.out.println("save to urls "+nextUrl); }else if(a>0){ System.out.println("urls exists "+nextUrl); }else if(b>0){ System.out.println("blogs exists "+nextUrl); } //urlList.add(nextUrl); } } }else{ index=0; getURLs(); System.out.println("没有可用网址"); } } public void getURLs(){ /* for(int i=0;i<urlList.size();i++){ int c = connector.isExist("url",urlList.get(i)); if(c>0){ continue; }else{ String sqlInsert = "insert into urls(url) values('"+urlList.get(i)+"')"; connector.insert(sqlInsert); } }*/ String sqlDelete = "delete from urls where url in ("; String urls = ""; for(int i=0;i<urlList.size();i++){ urls+="'"+urlList.get(i)+"',"; } sqlDelete+= urls.substring(0,urls.length()-1)+")"; int c = connector.delete(sqlDelete); System.out.println(sqlDelete+","+c); urlList.clear(); String sqlSelect = "select distinct id,url,flag from urls limit 100"; ArrayList<Map<String,String>> ret = connector.select(sqlSelect,"urls"); for(int i=0;i<ret.size();i++){ System.out.println(ret.get(i).get("url")+" add to urlList"); if(!urlList.contains(ret.get(i).get("url"))) { urlList.add(ret.get(i).get("url")); } } } public void getKeyWord(String content){ JiebaSegmenter segmenter = new JiebaSegmenter(); System.out.println(segmenter.sentenceProcess(content)); //jieba.analyse.extract_tags(content, topK=topK, withWeight=withWeight); } /*1、至少匹配一个汉字的写法。 2、这两个unicode值正好是Unicode表中的汉字的头和尾。 3、"[]"代表里边的值出现一个就可以,后边的“+”代表至少出现1次,合起来即至少匹配一个汉字。 */ public static String getChinese(String paramValue) { String regex = "([\u4e00-\u9fa5]+)"; String str = ""; Matcher matcher = Pattern.compile(regex).matcher(paramValue); while (matcher.find()) { str+= matcher.group(0); } //去掉 <SUF> str = str.replaceAll("'","#"); return str; } /* public void xx(String ){ for (int i = 0; i < max_iter; ++i) { Map<String, Float> m = new HashMap<String, Float>(); float max_diff = 0; for (Map.Entry<String, Set<String>> entry : words.entrySet()) { String key = entry.getKey(); Set<String> value = entry.getValue(); m.put(key, 1 - d); for (String other : value) { int size = words.get(other).size(); if (key.equals(other) || size == 0) continue; m.put(key, m.get(key) + d / size * (score.get(other) == null ? 0 : score.get(other))); } max_diff = Math.max(max_diff, Math.abs(m.get(key) - (score.get(key) == null ? 0 : score.get(key)))); } score = m; if (max_diff <= min_diff) break; } 排序后的投票 }*/ /* public static String TFIDF (String title,String content, int topK){ FilterRecognition filterRecognition = new FilterRecognition(); filterRecognition.insertStopWords(stopWords); filterRecognition.insertStopWord("事儿", "有没有", "前有", "后有", "更多"); filterRecognition.insertStopNatures("d", "p", "m", "r", "w", "a", "j", "l","null","num"); List<Term> terms = NlpAnalysis.parse(content).recognition(filterRecognition).getTerms(); //词的总数 int totalWords= terms.size(); Map<String, Integer> wordsCount = new HashMap<String, Integer>(); //根据词的长度加权 int maxWordLen = 0; for(Term term:terms){ Integer count = wordsCount.get(term.getName()); count = count == null ? 0 : count; wordsCount.put(term.getName(), count+1); if(maxWordLen<term.getName().length()){ maxWordLen = term.getName().length(); } } //计算tf Map<String, Double> tf = new HashMap<String, Double>(); for(String word:wordsCount.keySet()){ tf.put(word, (double)wordsCount.get(word)/(totalWords+1)); } //保留词的长度 Set<Integer> perWordLen = new HashSet<Integer>(); //计算每个词的词长权重 Map<String, Double> lenWeight = new HashMap<String, Double>(); for( String key:tf.keySet()){ lenWeight.put(key, (double)key.length()/maxWordLen); perWordLen.add(key.length()); } //标题中出现的关键词 List<Term> titleTerms = NlpAnalysis.parse(title).recognition(filterRecognition).getTerms(); Map<String, String> titleWords = new HashMap<String, String>(); for(Term term:titleTerms){ titleWords.put(term.getName(), term.getNatureStr()); } //计算idf Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int len:perWordLen){ int sum = 0; for(String w:wordsCount.keySet()){ if(w.length()==len){ sum += wordsCount.get(w); } } map.put(len, sum); } Map<String, Double> idf = new HashMap<String, Double>(); for(String w:wordsCount.keySet()){ Integer integer = wordsCount.get(w); int len = w.length(); Integer totalSim = map.get(len); idf.put(w, Math.log(((double)totalSim/integer)+1)); } //计算每个词的在文章中的权重 Map<String, Double> wordWeight = new HashMap<String, Double>(); for(Term term:terms){ String word = term.getName(); String nature = term.getNatureStr(); if(word.length()<2){ continue; } if(wordWeight.get(word)!=null){ continue; } Double aDouble = tf.get(word); Double aDouble1 = idf.get(word); double weight = 1.0; if(titleWords.keySet().contains(word)){ weight += 3.0; } weight += (double)word.length()/maxWordLen; switch (nature){ case "en": weight += 3.0; case "nr": weight += 6.0; case "nrf": weight += 6.0; case "nw" : weight += 3.0; case "nt": weight += 6.0; case "nz": weight += 3.0; case "kw": weight += 3.0; case "ns": weight += 3.0; default: weight += 1.0; } wordWeight.put(word,aDouble*aDouble1*weight); } Map<String, Double> stringDoubleMap = MapUtil.sortByValue(wordWeight); List<String> topKSet = new ArrayList<String>(); int i = 0; for(String word:stringDoubleMap.keySet()){ if(i >= topK){ break; } topKSet.add(word+" `` +stringDoubleMap.get(word)); i++; } return StringUtils.join(topKSet, "\t"); }*/ }
false
2,859
5
3,278
6
3,514
5
3,278
6
3,886
8
false
false
false
false
false
true
25340_8
package com.zcshou.utils; public class MapUtils { // public final static String COORDINATE_TYPE_GCJ02 = "gcj02"; // public final static String COORDINATE_TYPE_BD09LL = "bd09ll"; // public final static String COORDINATE_TYPE_BD09MC = "bd09"; // public static float[] EARTH_WEIGHT = {0.1f, 0.2f, 0.4f, 0.6f, 0.8f}; // 推算计算权重_地球 // public static float[] MOON_WEIGHT = {0.0167f,0.033f,0.067f,0.1f,0.133f}; // public static float[] MARS_WEIGHT = {0.034f,0.068f,0.152f,0.228f,0.304f}; //坐标转换相关 public final static double pi = 3.14159265358979324; public final static double a = 6378245.0; public final static double ee = 0.00669342162296594323; public final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0; public static double[] bd2wgs(double lon, double lat) { double[] bd2Gcj = bd09togcj02(lon, lat); return gcj02towgs84(bd2Gcj[0], bd2Gcj[1]); } /** * WGS84 转换为 BD-09 * @param lng 经度 * @param lat 纬度 * @return double[] 转换后的经度,纬度 数组 * */ public static double[] wgs2bd09(double lng, double lat){ //第一次转换 double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLon(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * pi; double magic = Math.sin(radlat); magic = 1 - ee * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); double mglat = lat + dlat; double mglng = lng + dlng; //第二次转换 double z = Math.sqrt(mglng * mglng + mglat * mglat) + 0.00002 * Math.sin(mglat * x_pi); double theta = Math.atan2(mglat, mglng) + 0.000003 * Math.cos(mglng * x_pi); double bd_lng = z * Math.cos(theta) + 0.0065; double bd_lat = z * Math.sin(theta) + 0.006; return new double[] { bd_lng, bd_lat }; } public static double[] bd09togcj02(double bd_lon, double bd_lat) { double x = bd_lon - 0.0065; double y = bd_lat - 0.006; double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi); double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi); double gg_lng = z * Math.cos(theta); double gg_lat = z * Math.sin(theta); return new double[] { gg_lng, gg_lat }; } public static double[] gcj02towgs84(double lng, double lat) { double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLon(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * pi; double magic = Math.sin(radlat); magic = 1 - ee * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); double mglat = lat + dlat; double mglng = lng + dlng; return new double[] { lng * 2 - mglng, lat * 2 - mglat }; } private static double transformLat(double lat, double lon) { double ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon + 0.2 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi / 30.0)) * 2.0 / 3.0; return ret; } private static double transformLon(double lat, double lon) { double ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0; return ret; } // private static boolean out_of_china(double lng, double lat) { // return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271)); // } }
ZCShou/GoGoGo
app/src/main/java/com/zcshou/utils/MapUtils.java
1,801
//第一次转换
line_comment
zh-cn
package com.zcshou.utils; public class MapUtils { // public final static String COORDINATE_TYPE_GCJ02 = "gcj02"; // public final static String COORDINATE_TYPE_BD09LL = "bd09ll"; // public final static String COORDINATE_TYPE_BD09MC = "bd09"; // public static float[] EARTH_WEIGHT = {0.1f, 0.2f, 0.4f, 0.6f, 0.8f}; // 推算计算权重_地球 // public static float[] MOON_WEIGHT = {0.0167f,0.033f,0.067f,0.1f,0.133f}; // public static float[] MARS_WEIGHT = {0.034f,0.068f,0.152f,0.228f,0.304f}; //坐标转换相关 public final static double pi = 3.14159265358979324; public final static double a = 6378245.0; public final static double ee = 0.00669342162296594323; public final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0; public static double[] bd2wgs(double lon, double lat) { double[] bd2Gcj = bd09togcj02(lon, lat); return gcj02towgs84(bd2Gcj[0], bd2Gcj[1]); } /** * WGS84 转换为 BD-09 * @param lng 经度 * @param lat 纬度 * @return double[] 转换后的经度,纬度 数组 * */ public static double[] wgs2bd09(double lng, double lat){ //第一 <SUF> double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLon(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * pi; double magic = Math.sin(radlat); magic = 1 - ee * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); double mglat = lat + dlat; double mglng = lng + dlng; //第二次转换 double z = Math.sqrt(mglng * mglng + mglat * mglat) + 0.00002 * Math.sin(mglat * x_pi); double theta = Math.atan2(mglat, mglng) + 0.000003 * Math.cos(mglng * x_pi); double bd_lng = z * Math.cos(theta) + 0.0065; double bd_lat = z * Math.sin(theta) + 0.006; return new double[] { bd_lng, bd_lat }; } public static double[] bd09togcj02(double bd_lon, double bd_lat) { double x = bd_lon - 0.0065; double y = bd_lat - 0.006; double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi); double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi); double gg_lng = z * Math.cos(theta); double gg_lat = z * Math.sin(theta); return new double[] { gg_lng, gg_lat }; } public static double[] gcj02towgs84(double lng, double lat) { double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLon(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * pi; double magic = Math.sin(radlat); magic = 1 - ee * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); double mglat = lat + dlat; double mglng = lng + dlng; return new double[] { lng * 2 - mglng, lat * 2 - mglat }; } private static double transformLat(double lat, double lon) { double ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon + 0.2 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi / 30.0)) * 2.0 / 3.0; return ret; } private static double transformLon(double lat, double lon) { double ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0; return ret; } // private static boolean out_of_china(double lng, double lat) { // return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271)); // } }
false
1,689
4
1,792
5
1,846
4
1,792
5
1,972
7
false
false
false
false
false
true
39267_50
//艾特作图2.0.java //作者尹志平 //感叹号大概是接口暂时坏掉,等站长修复就好了 import java.util.*; import java.lang.*; import java.text.*; public static final Map tumap = new HashMap(); static {//看起来高端一点 //收录接口也很辛苦的好吗 List 爬了=Arrays.asList(new String[]{"http://ovooa.com/API/pa/api.php?QQ=","https://yysk.yitzu.cn.qingf.top/api/xb/api/pa.php?qq="}); String 爬=爬了.get(new Random().nextInt(爬了.size())); List 想了=Arrays.asList(new String[]{"http://ovooa.com/API/face_thsee/?QQ=","http://yysk.yitzu.cn.qingf.top/api/xb/api/xiang_2.php?qq="}); String 想=想了.get(new Random().nextInt(想了.size()));//两个接口不一样哦 tumap.put("看这个","https://api.xingzhige.com/API/Lookatthis/?qq="); tumap.put("抱","https://api.xingzhige.com/API/baororo/?qq="); tumap.put("咬","https://api.xingzhige.com/API/bite/?qq="); tumap.put("吞","https://bg.suol.cc/API/chi/?uin="); tumap.put("拍","https://api.xingzhige.com/API/paigua/?qq="); tumap.put("抓","https://api.xingzhige.com/API/grab/?qq="); tumap.put("顶","https://api.xingzhige.com/API/dingqiu/?qq="); tumap.put("一起笑","https://api.xingzhige.com/API/LaughTogether/?qq="); tumap.put("搂","https://api.xingzhige.com/API/FortuneCat/?qq="); tumap.put("摇","https://api.xingzhige.com/API/DanceChickenLeg/?qq="); tumap.put("捣","https://api.xingzhige.com/API/pound/?qq="); tumap.put("撕","http://ovooa.com/API/si/?QQ="); tumap.put("加框","http://ovooa.com/API/head/?QQ="); tumap.put("赞","http://ovooa.com/API/zan/api.php?QQ="); tumap.put("丢","http://ovooa.com/API/diu/api.php?QQ="); tumap.put("爬",爬); tumap.put("遗照","http://lkaa.top/API/yi/?QQ="); tumap.put("牵","http://api.tangdouz.com/wz/qian.php?q="+MyUin+"&qq="); tumap.put("需要","http://yysk.yitzu.cn.qingf.top/api/xb/api/need.php?qq="); tumap.put("鄙视","http://xiaobai.klizi.cn/API/ce/bishi.php?qq="); tumap.put("比心","http://xiaobai.klizi.cn/API/ce/xin.php?qq="); tumap.put("跟我处对象","http://api.klizi.cn/API/ce/xie.php?qq="); tumap.put("圈钱跑路","http://xiaobai.klizi.cn/API/ce/pao.php?qq="); tumap.put("膜拜","http://ovooa.com/API/face_worship/?QQ="); tumap.put("摸","http://ovooa.com/API/face_petpet/?QQ="); tumap.put("想",想); tumap.put("吃掉","http://ovooa.com/API/face_bite/?QQ="); tumap.put("抱着哭","https://yysk.yitzu.cn.qingf.top/api/xb/api/ku.php?qq="); tumap.put("精神支柱","https://yysk.yitzu.cn.qingf.top/api/xb/api/jingshenzhizhu.php?qq="); tumap.put("看完干活","http://xiaobapi.top/api/xb/api/back_to_work.php?qq="); tumap.put("舔","https://yysk.yitzu.cn.qingf.top/api/xb/api/tian.php?qq="); tumap.put("遮脸","https://yysk.yitzu.cn.qingf.top/api/xb/api/cover_face.php?qq="); tumap.put("疑问","https://yysk.yitzu.cn.qingf.top/api/xb/api/wenhao.php?qq="); tumap.put("上电视","https://yysk.yitzu.cn.qingf.top/api/xb/api/kandianshi.php?qq="); tumap.put("这像画吗","https://yysk.yitzu.cn.qingf.top/api/xb/api/hua.php?qq="); tumap.put("推","http://yysk.yitzu.cn.qingf.top/api/xb/api/roll.php?qq="); tumap.put("垃圾","https://api.klizi.cn/API/gif/garbage.php?qq="); tumap.put("为什么艾特我","https://yysk.yitzu.cn.qingf.top/api/xb/api/whyatme.php?qq="); tumap.put("墙纸","https://yysk.yitzu.cn.qingf.top/api/xb/api/wallpaper.php?qq="); tumap.put("黑化","http://yysk.yitzu.cn.qingf.top/api/xb/api/h.php?qq="); tumap.put("快逃","http://xiaobai.klizi.cn/API/gif/escape.php?qq="); } //类似的使用接口的一言之类都可以使用这种写法 Set keys=tumap.keySet(); public String kk(String a,Set list){//如果以key开始则返回key值 String result=""; for(String b:list){ if(a.startsWith(b)){ result=b; break;} } return result; } public static boolean iss(String str){//判断是否数字 for (int i = str.length();--i>=0;){ if (!Character.isDigit(str.charAt(i))){ return false; } } return true; } AddItem("开启/关闭限制","开关",PluginID); public void 开关(String qun,String qqq,int type) { if("1".equals(getString(qun,"脚本"))||"1".equals(getString(qqq,"脚本"))) { putString(qun, "脚本", null);putString(qqq,"脚本",null); Toast("限制已开启,本聊天仅自己可用"); } else{ putString(qun,"脚本","1");putString(qqq,"脚本","1"); Toast("限制已关闭,本聊天他人也可使用"); } } public void onMsg(Object msg) { String text=msg.MessageContent; String qq=msg.UserUin; String qun=msg.GroupUin; public void sendpic(p){ if(msg.IsGroup){sendPic(qun,"",p);} else{sendPic("",msg.msg.frienduin,p);}} public void fc(String s,String q){//匹配key值,获取相应接口 new Thread(new Runnable(){//新线程防止延迟过长 public void run() {sendpic(tumap.get(s)+q); }}).start(); } if(msg.IsSend||"1".equals(getString(qun,"脚本"))||"1".equals(getString(GetFriendUin(),"脚本"))){//限制 if(!"".equals(kk(text,keys))){ String s=kk(text,keys);//指令key值 String uin=text.replace(s,"");//非key值部分 if(uin.equals("我")){ try{//使用快捷方式 fc(s,qq);}catch(e){return;} } if(iss(uin)){ try{//输入了qq号 fc(s,uin);}catch(e){return;} } if(msg.IsGroup) {//群聊且艾特 if(msg.mAtList.size()>=1){ try{String q=msg.mAtList.get(0); fc(s,q);}catch(e){return;} }} if(!msg.IsGroup){ try{//私聊 String q=MyUin; if(iss(uin))return; if(uin.equals("我")){q=qq;} if(uin.equals("你")){if(qq.equals(MyUin))q=msg.msg.frienduin;else q=MyUin; } fc(s,q);}catch(e){return;} }}//如果不是萌新说我还不知道有msg.msg.frienduin这个东西 if(text.equals("功能")){ sendMsg(qun,GetFriendUin(),"功能列表:\n⭐"+keys.toString().replace(",","+@ ⭐").replaceAll("[\\[\\]]","")+"+@\n\n快捷方式\n+我 例:摸我 \n+qq 例:摸10001\n"+"\n👆私聊把@换成你或我👆");}}} Toast("发送 功能 查看功能\n三杠可控制是否他人可用");
ZGQ-inc/ZGQs_QRbot
BSH/at_pic_2.0.java
2,469
//匹配key值,获取相应接口
line_comment
zh-cn
//艾特作图2.0.java //作者尹志平 //感叹号大概是接口暂时坏掉,等站长修复就好了 import java.util.*; import java.lang.*; import java.text.*; public static final Map tumap = new HashMap(); static {//看起来高端一点 //收录接口也很辛苦的好吗 List 爬了=Arrays.asList(new String[]{"http://ovooa.com/API/pa/api.php?QQ=","https://yysk.yitzu.cn.qingf.top/api/xb/api/pa.php?qq="}); String 爬=爬了.get(new Random().nextInt(爬了.size())); List 想了=Arrays.asList(new String[]{"http://ovooa.com/API/face_thsee/?QQ=","http://yysk.yitzu.cn.qingf.top/api/xb/api/xiang_2.php?qq="}); String 想=想了.get(new Random().nextInt(想了.size()));//两个接口不一样哦 tumap.put("看这个","https://api.xingzhige.com/API/Lookatthis/?qq="); tumap.put("抱","https://api.xingzhige.com/API/baororo/?qq="); tumap.put("咬","https://api.xingzhige.com/API/bite/?qq="); tumap.put("吞","https://bg.suol.cc/API/chi/?uin="); tumap.put("拍","https://api.xingzhige.com/API/paigua/?qq="); tumap.put("抓","https://api.xingzhige.com/API/grab/?qq="); tumap.put("顶","https://api.xingzhige.com/API/dingqiu/?qq="); tumap.put("一起笑","https://api.xingzhige.com/API/LaughTogether/?qq="); tumap.put("搂","https://api.xingzhige.com/API/FortuneCat/?qq="); tumap.put("摇","https://api.xingzhige.com/API/DanceChickenLeg/?qq="); tumap.put("捣","https://api.xingzhige.com/API/pound/?qq="); tumap.put("撕","http://ovooa.com/API/si/?QQ="); tumap.put("加框","http://ovooa.com/API/head/?QQ="); tumap.put("赞","http://ovooa.com/API/zan/api.php?QQ="); tumap.put("丢","http://ovooa.com/API/diu/api.php?QQ="); tumap.put("爬",爬); tumap.put("遗照","http://lkaa.top/API/yi/?QQ="); tumap.put("牵","http://api.tangdouz.com/wz/qian.php?q="+MyUin+"&qq="); tumap.put("需要","http://yysk.yitzu.cn.qingf.top/api/xb/api/need.php?qq="); tumap.put("鄙视","http://xiaobai.klizi.cn/API/ce/bishi.php?qq="); tumap.put("比心","http://xiaobai.klizi.cn/API/ce/xin.php?qq="); tumap.put("跟我处对象","http://api.klizi.cn/API/ce/xie.php?qq="); tumap.put("圈钱跑路","http://xiaobai.klizi.cn/API/ce/pao.php?qq="); tumap.put("膜拜","http://ovooa.com/API/face_worship/?QQ="); tumap.put("摸","http://ovooa.com/API/face_petpet/?QQ="); tumap.put("想",想); tumap.put("吃掉","http://ovooa.com/API/face_bite/?QQ="); tumap.put("抱着哭","https://yysk.yitzu.cn.qingf.top/api/xb/api/ku.php?qq="); tumap.put("精神支柱","https://yysk.yitzu.cn.qingf.top/api/xb/api/jingshenzhizhu.php?qq="); tumap.put("看完干活","http://xiaobapi.top/api/xb/api/back_to_work.php?qq="); tumap.put("舔","https://yysk.yitzu.cn.qingf.top/api/xb/api/tian.php?qq="); tumap.put("遮脸","https://yysk.yitzu.cn.qingf.top/api/xb/api/cover_face.php?qq="); tumap.put("疑问","https://yysk.yitzu.cn.qingf.top/api/xb/api/wenhao.php?qq="); tumap.put("上电视","https://yysk.yitzu.cn.qingf.top/api/xb/api/kandianshi.php?qq="); tumap.put("这像画吗","https://yysk.yitzu.cn.qingf.top/api/xb/api/hua.php?qq="); tumap.put("推","http://yysk.yitzu.cn.qingf.top/api/xb/api/roll.php?qq="); tumap.put("垃圾","https://api.klizi.cn/API/gif/garbage.php?qq="); tumap.put("为什么艾特我","https://yysk.yitzu.cn.qingf.top/api/xb/api/whyatme.php?qq="); tumap.put("墙纸","https://yysk.yitzu.cn.qingf.top/api/xb/api/wallpaper.php?qq="); tumap.put("黑化","http://yysk.yitzu.cn.qingf.top/api/xb/api/h.php?qq="); tumap.put("快逃","http://xiaobai.klizi.cn/API/gif/escape.php?qq="); } //类似的使用接口的一言之类都可以使用这种写法 Set keys=tumap.keySet(); public String kk(String a,Set list){//如果以key开始则返回key值 String result=""; for(String b:list){ if(a.startsWith(b)){ result=b; break;} } return result; } public static boolean iss(String str){//判断是否数字 for (int i = str.length();--i>=0;){ if (!Character.isDigit(str.charAt(i))){ return false; } } return true; } AddItem("开启/关闭限制","开关",PluginID); public void 开关(String qun,String qqq,int type) { if("1".equals(getString(qun,"脚本"))||"1".equals(getString(qqq,"脚本"))) { putString(qun, "脚本", null);putString(qqq,"脚本",null); Toast("限制已开启,本聊天仅自己可用"); } else{ putString(qun,"脚本","1");putString(qqq,"脚本","1"); Toast("限制已关闭,本聊天他人也可使用"); } } public void onMsg(Object msg) { String text=msg.MessageContent; String qq=msg.UserUin; String qun=msg.GroupUin; public void sendpic(p){ if(msg.IsGroup){sendPic(qun,"",p);} else{sendPic("",msg.msg.frienduin,p);}} public void fc(String s,String q){//匹配 <SUF> new Thread(new Runnable(){//新线程防止延迟过长 public void run() {sendpic(tumap.get(s)+q); }}).start(); } if(msg.IsSend||"1".equals(getString(qun,"脚本"))||"1".equals(getString(GetFriendUin(),"脚本"))){//限制 if(!"".equals(kk(text,keys))){ String s=kk(text,keys);//指令key值 String uin=text.replace(s,"");//非key值部分 if(uin.equals("我")){ try{//使用快捷方式 fc(s,qq);}catch(e){return;} } if(iss(uin)){ try{//输入了qq号 fc(s,uin);}catch(e){return;} } if(msg.IsGroup) {//群聊且艾特 if(msg.mAtList.size()>=1){ try{String q=msg.mAtList.get(0); fc(s,q);}catch(e){return;} }} if(!msg.IsGroup){ try{//私聊 String q=MyUin; if(iss(uin))return; if(uin.equals("我")){q=qq;} if(uin.equals("你")){if(qq.equals(MyUin))q=msg.msg.frienduin;else q=MyUin; } fc(s,q);}catch(e){return;} }}//如果不是萌新说我还不知道有msg.msg.frienduin这个东西 if(text.equals("功能")){ sendMsg(qun,GetFriendUin(),"功能列表:\n⭐"+keys.toString().replace(",","+@ ⭐").replaceAll("[\\[\\]]","")+"+@\n\n快捷方式\n+我 例:摸我 \n+qq 例:摸10001\n"+"\n👆私聊把@换成你或我👆");}}} Toast("发送 功能 查看功能\n三杠可控制是否他人可用");
false
1,923
8
2,469
8
2,252
8
2,469
8
2,860
14
false
false
false
false
false
true
41110_0
/** * 严肃声明: * 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究! * 可正常分享和学习源码,不得用于违法犯罪活动,违者必究! * Copyright (c) 2021 十三 all rights reserved. * 版权所有,侵权必究! */ package com.my.column.service.impl; import com.my.column.common.Constants; import com.my.column.common.ServiceResultEnum; import com.my.column.dao.ColumnEntityMapper; import com.my.column.dao.UserEntityMapper; import com.my.column.entity.ColumnEntity; import com.my.column.entity.UserEntity; import com.my.column.service.UserService; import com.my.column.util.MD5Util; import com.my.column.util.SystemUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpSession; @Service public class UserServiceImpl implements UserService { @Autowired private UserEntityMapper userEntityMapper; @Autowired private ColumnEntityMapper columnEntityMapper; @Override @Transactional public String register(String loginName, String password) { if (userEntityMapper.selectByLoginName(loginName) != null) { return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult(); } //注册用户 UserEntity registerUser = new UserEntity(); registerUser.setLoginName(loginName); //默认头像 registerUser.setHeadImgUrl("/images/default-user-img.png"); //默认介绍 registerUser.setIntroduce("随心写作,自由表达"); //行业 registerUser.setProfession("未知"); //居住地 registerUser.setAddress("未知"); String passwordMD5 = MD5Util.MD5Encode(password, "UTF-8"); registerUser.setPasswordMd5(passwordMD5); //新增用户数据及用户的专栏数据 if (userEntityMapper.insertSelective(registerUser) > 0) { //专栏数据 ColumnEntity columnEntity = new ColumnEntity(); columnEntity.setUserId(registerUser.getUserId()); //专栏名称 columnEntity.setColumnName(loginName + "的专栏"); //默认专栏封面 columnEntity.setColumnCover("/images/default-column-img.jpg"); //默认专栏介绍 columnEntity.setColumnIntroduce("这是" + loginName + "的专栏,赶快来阅读吧"); if (columnEntityMapper.insertSelective(columnEntity) > 0) { return ServiceResultEnum.SUCCESS.getResult(); } } return ServiceResultEnum.DB_ERROR.getResult(); } @Override public String login(String loginName, String passwordMD5, HttpSession httpSession) { UserEntity user = userEntityMapper.selectByLoginNameAndPasswd(loginName, passwordMD5); if (user != null && httpSession != null) { httpSession.setAttribute(Constants.USER_SESSION_KEY, user); return ServiceResultEnum.SUCCESS.getResult(); } return ServiceResultEnum.LOGIN_ERROR.getResult(); } @Override public UserEntity updateUserInfo(UserEntity userEntity, HttpSession httpSession) { UserEntity userTemp = (UserEntity) httpSession.getAttribute(Constants.USER_SESSION_KEY); UserEntity userFromDB = userEntityMapper.selectByPrimaryKey(userTemp.getUserId()); if (userFromDB != null) { userFromDB.setProfession(SystemUtil.cleanString(userEntity.getProfession())); userFromDB.setAddress(SystemUtil.cleanString(userEntity.getAddress())); userFromDB.setIntroduce(SystemUtil.cleanString(userEntity.getIntroduce())); userFromDB.setHeadImgUrl(SystemUtil.cleanString(userEntity.getHeadImgUrl())); if (userEntityMapper.updateByPrimaryKeySelective(userFromDB) > 0) { httpSession.setAttribute(Constants.USER_SESSION_KEY, userFromDB); return userFromDB; } } return null; } @Override public UserEntity getUserById(Long userId) { return userEntityMapper.selectByPrimaryKey(userId); } }
ZHENFENG13/My-Column
src/main/java/com/my/column/service/impl/UserServiceImpl.java
1,034
/** * 严肃声明: * 开源版本请务必保留此注释头信息,若删除我方将保留所有法律责任追究! * 可正常分享和学习源码,不得用于违法犯罪活动,违者必究! * Copyright (c) 2021 十三 all rights reserved. * 版权所有,侵权必究! */
block_comment
zh-cn
/** * 严肃声 <SUF>*/ package com.my.column.service.impl; import com.my.column.common.Constants; import com.my.column.common.ServiceResultEnum; import com.my.column.dao.ColumnEntityMapper; import com.my.column.dao.UserEntityMapper; import com.my.column.entity.ColumnEntity; import com.my.column.entity.UserEntity; import com.my.column.service.UserService; import com.my.column.util.MD5Util; import com.my.column.util.SystemUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpSession; @Service public class UserServiceImpl implements UserService { @Autowired private UserEntityMapper userEntityMapper; @Autowired private ColumnEntityMapper columnEntityMapper; @Override @Transactional public String register(String loginName, String password) { if (userEntityMapper.selectByLoginName(loginName) != null) { return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult(); } //注册用户 UserEntity registerUser = new UserEntity(); registerUser.setLoginName(loginName); //默认头像 registerUser.setHeadImgUrl("/images/default-user-img.png"); //默认介绍 registerUser.setIntroduce("随心写作,自由表达"); //行业 registerUser.setProfession("未知"); //居住地 registerUser.setAddress("未知"); String passwordMD5 = MD5Util.MD5Encode(password, "UTF-8"); registerUser.setPasswordMd5(passwordMD5); //新增用户数据及用户的专栏数据 if (userEntityMapper.insertSelective(registerUser) > 0) { //专栏数据 ColumnEntity columnEntity = new ColumnEntity(); columnEntity.setUserId(registerUser.getUserId()); //专栏名称 columnEntity.setColumnName(loginName + "的专栏"); //默认专栏封面 columnEntity.setColumnCover("/images/default-column-img.jpg"); //默认专栏介绍 columnEntity.setColumnIntroduce("这是" + loginName + "的专栏,赶快来阅读吧"); if (columnEntityMapper.insertSelective(columnEntity) > 0) { return ServiceResultEnum.SUCCESS.getResult(); } } return ServiceResultEnum.DB_ERROR.getResult(); } @Override public String login(String loginName, String passwordMD5, HttpSession httpSession) { UserEntity user = userEntityMapper.selectByLoginNameAndPasswd(loginName, passwordMD5); if (user != null && httpSession != null) { httpSession.setAttribute(Constants.USER_SESSION_KEY, user); return ServiceResultEnum.SUCCESS.getResult(); } return ServiceResultEnum.LOGIN_ERROR.getResult(); } @Override public UserEntity updateUserInfo(UserEntity userEntity, HttpSession httpSession) { UserEntity userTemp = (UserEntity) httpSession.getAttribute(Constants.USER_SESSION_KEY); UserEntity userFromDB = userEntityMapper.selectByPrimaryKey(userTemp.getUserId()); if (userFromDB != null) { userFromDB.setProfession(SystemUtil.cleanString(userEntity.getProfession())); userFromDB.setAddress(SystemUtil.cleanString(userEntity.getAddress())); userFromDB.setIntroduce(SystemUtil.cleanString(userEntity.getIntroduce())); userFromDB.setHeadImgUrl(SystemUtil.cleanString(userEntity.getHeadImgUrl())); if (userEntityMapper.updateByPrimaryKeySelective(userFromDB) > 0) { httpSession.setAttribute(Constants.USER_SESSION_KEY, userFromDB); return userFromDB; } } return null; } @Override public UserEntity getUserById(Long userId) { return userEntityMapper.selectByPrimaryKey(userId); } }
false
835
79
1,034
97
1,036
84
1,034
97
1,263
145
false
false
false
false
false
true
16441_2
package com.ssm.promotion.core.util; public class AntiXssUtil { /** * 滤除content中的危险 HTML 代码, 主要是脚本代码, 滚动字幕代码以及脚本事件处理代码 * * @param content 需要滤除的字符串 * @return 过滤的结果 */ public static String replaceHtmlCode(String content) { if (null == content) { return null; } if (0 == content.length()) { return ""; } // 需要滤除的脚本事件关键字 String[] eventKeywords = {"onmouseover", "onmouseout", "onmousedown", "onmouseup", "onmousemove", "onclick", "ondblclick", "onkeypress", "onkeydown", "onkeyup", "ondragstart", "onerrorupdate", "onhelp", "onreadystatechange", "onrowenter", "onrowexit", "onselectstart", "onload", "onunload", "onbeforeunload", "onblur", "onerror", "onfocus", "onresize", "onscroll", "oncontextmenu", "alert", "href", "window", "script"}; content = replace(content, "<script", "<script", false); content = replace(content, "</script", "</script", false); content = replace(content, "<marquee", "<marquee", false); content = replace(content, "</marquee", "</marquee", false); content = replace(content, "'", "_", false);// 将单引号替换成下划线 content = replace(content, "\"", "_", false);// 将双引号替换成下划线 // 滤除脚本事件代码 for (int i = 0; i < eventKeywords.length; i++) { if (content.toLowerCase().contains(eventKeywords[i].toLowerCase())) { content = replace(content, eventKeywords[i], "_" + eventKeywords[i], false); // 添加一个"_", 使事件代码无效 } } return content; } /** * 将字符串 source 中的 oldStr 替换为 newStr, 并以大小写敏感方式进行查找 * * @param source 需要替换的源字符串 * @param oldStr 需要被替换的老字符串 * @param newStr 替换为的新字符串 */ private static String replace(String source, String oldStr, String newStr) { return replace(source, oldStr, newStr, true); } /** * 将字符串 source 中的 oldStr 替换为 newStr, matchCase 为是否设置大小写敏感查找 * * @param source 需要替换的源字符串 * @param oldStr 需要被替换的老字符串 * @param newStr 替换为的新字符串 * @param matchCase 是否需要按照大小写敏感方式查找 */ private static String replace(String source, String oldStr, String newStr, boolean matchCase) { if (source == null) { return null; } if (source.toLowerCase().indexOf(oldStr.toLowerCase()) == -1) { return source; } int findStartPos = 0; int a = 0; while (a > -1) { int b = 0; String str1, str2, str3, str4, strA, strB; str1 = source; str2 = str1.toLowerCase(); str3 = oldStr; str4 = str3.toLowerCase(); if (matchCase) { strA = str1; strB = str3; } else { strA = str2; strB = str4; } a = strA.indexOf(strB, findStartPos); if (a > -1) { b = oldStr.length(); findStartPos = a + b; StringBuffer bbuf = new StringBuffer(source); source = bbuf.replace(a, a + b, newStr) + ""; findStartPos = findStartPos + newStr.length() - b; } } return source; } }
ZHENFENG13/perfect-ssm
src/main/java/com/ssm/promotion/core/util/AntiXssUtil.java
931
// 将单引号替换成下划线
line_comment
zh-cn
package com.ssm.promotion.core.util; public class AntiXssUtil { /** * 滤除content中的危险 HTML 代码, 主要是脚本代码, 滚动字幕代码以及脚本事件处理代码 * * @param content 需要滤除的字符串 * @return 过滤的结果 */ public static String replaceHtmlCode(String content) { if (null == content) { return null; } if (0 == content.length()) { return ""; } // 需要滤除的脚本事件关键字 String[] eventKeywords = {"onmouseover", "onmouseout", "onmousedown", "onmouseup", "onmousemove", "onclick", "ondblclick", "onkeypress", "onkeydown", "onkeyup", "ondragstart", "onerrorupdate", "onhelp", "onreadystatechange", "onrowenter", "onrowexit", "onselectstart", "onload", "onunload", "onbeforeunload", "onblur", "onerror", "onfocus", "onresize", "onscroll", "oncontextmenu", "alert", "href", "window", "script"}; content = replace(content, "<script", "<script", false); content = replace(content, "</script", "</script", false); content = replace(content, "<marquee", "<marquee", false); content = replace(content, "</marquee", "</marquee", false); content = replace(content, "'", "_", false);// 将单 <SUF> content = replace(content, "\"", "_", false);// 将双引号替换成下划线 // 滤除脚本事件代码 for (int i = 0; i < eventKeywords.length; i++) { if (content.toLowerCase().contains(eventKeywords[i].toLowerCase())) { content = replace(content, eventKeywords[i], "_" + eventKeywords[i], false); // 添加一个"_", 使事件代码无效 } } return content; } /** * 将字符串 source 中的 oldStr 替换为 newStr, 并以大小写敏感方式进行查找 * * @param source 需要替换的源字符串 * @param oldStr 需要被替换的老字符串 * @param newStr 替换为的新字符串 */ private static String replace(String source, String oldStr, String newStr) { return replace(source, oldStr, newStr, true); } /** * 将字符串 source 中的 oldStr 替换为 newStr, matchCase 为是否设置大小写敏感查找 * * @param source 需要替换的源字符串 * @param oldStr 需要被替换的老字符串 * @param newStr 替换为的新字符串 * @param matchCase 是否需要按照大小写敏感方式查找 */ private static String replace(String source, String oldStr, String newStr, boolean matchCase) { if (source == null) { return null; } if (source.toLowerCase().indexOf(oldStr.toLowerCase()) == -1) { return source; } int findStartPos = 0; int a = 0; while (a > -1) { int b = 0; String str1, str2, str3, str4, strA, strB; str1 = source; str2 = str1.toLowerCase(); str3 = oldStr; str4 = str3.toLowerCase(); if (matchCase) { strA = str1; strB = str3; } else { strA = str2; strB = str4; } a = strA.indexOf(strB, findStartPos); if (a > -1) { b = oldStr.length(); findStartPos = a + b; StringBuffer bbuf = new StringBuffer(source); source = bbuf.replace(a, a + b, newStr) + ""; findStartPos = findStartPos + newStr.length() - b; } } return source; } }
false
925
11
931
10
991
10
931
10
1,225
16
false
false
false
false
false
true
65899_3
package com.core.entity; import java.io.Serializable; import java.util.List; public class Book implements Serializable { private String id;// 主键id private String isbn;// ISBN码 private String path;// 图片 private String title;// 标题 private String subtitle;// 副标题 private String originalTitle; private String marketPrice;// 市场价 private String intro;// 简介 private String binding;// 装订方式 private String pages;// 页数 private String author;// 作者 private String publisher;// 出版社 private String catalog;// 目录 private int supply;// 库存 private String status;// 状态 private int hot;// 热度值 private String indate;// 入库日期 List<Store> stores; public String getId() { return id; } public List<Store> getStores() { return stores; } public void setStores(List<Store> stores) { this.stores = stores; } public void setId(String id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public String getOriginalTitle() { return originalTitle; } public void setOriginalTitle(String originalTitle) { this.originalTitle = originalTitle; } public String getMarketPrice() { return marketPrice; } public void setMarketPrice(String marketPrice) { this.marketPrice = marketPrice; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public String getBinding() { return binding; } public void setBinding(String binding) { this.binding = binding; } public String getPages() { return pages; } public void setPages(String page) { this.pages = page; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public int getSupply() { return supply; } public void setSupply(int supply) { this.supply = supply; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getHot() { return hot; } public void setHot(int hot) { this.hot = hot; } public String getIndate() { return indate; } public void setIndate(String indate) { this.indate = indate; } @Override public String toString() { return "Book{" + "id='" + id + '\'' + ", isbn='" + isbn + '\'' + ", path='" + path + '\'' + ", title='" + title + '\'' + ", subtitle='" + subtitle + '\'' + ", originalTitle='" + originalTitle + '\'' + ", marketPrice='" + marketPrice + '\'' + ", intro='" + intro + '\'' + ", binding='" + binding + '\'' + ", pages='" + pages + '\'' + ", author='" + author + '\'' + ", publisher='" + publisher + '\'' + ", catalog='" + catalog + '\'' + ", supply=" + supply + ", status='" + status + '\'' + ", hot=" + hot + ", indate='" + indate + '\'' + ", stores=" + stores + '}'; } }
ZHENFENG13/ssm-demo
ssm-demo/src/com/core/entity/Book.java
960
// 标题
line_comment
zh-cn
package com.core.entity; import java.io.Serializable; import java.util.List; public class Book implements Serializable { private String id;// 主键id private String isbn;// ISBN码 private String path;// 图片 private String title;// 标题 <SUF> private String subtitle;// 副标题 private String originalTitle; private String marketPrice;// 市场价 private String intro;// 简介 private String binding;// 装订方式 private String pages;// 页数 private String author;// 作者 private String publisher;// 出版社 private String catalog;// 目录 private int supply;// 库存 private String status;// 状态 private int hot;// 热度值 private String indate;// 入库日期 List<Store> stores; public String getId() { return id; } public List<Store> getStores() { return stores; } public void setStores(List<Store> stores) { this.stores = stores; } public void setId(String id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public String getOriginalTitle() { return originalTitle; } public void setOriginalTitle(String originalTitle) { this.originalTitle = originalTitle; } public String getMarketPrice() { return marketPrice; } public void setMarketPrice(String marketPrice) { this.marketPrice = marketPrice; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public String getBinding() { return binding; } public void setBinding(String binding) { this.binding = binding; } public String getPages() { return pages; } public void setPages(String page) { this.pages = page; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public int getSupply() { return supply; } public void setSupply(int supply) { this.supply = supply; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getHot() { return hot; } public void setHot(int hot) { this.hot = hot; } public String getIndate() { return indate; } public void setIndate(String indate) { this.indate = indate; } @Override public String toString() { return "Book{" + "id='" + id + '\'' + ", isbn='" + isbn + '\'' + ", path='" + path + '\'' + ", title='" + title + '\'' + ", subtitle='" + subtitle + '\'' + ", originalTitle='" + originalTitle + '\'' + ", marketPrice='" + marketPrice + '\'' + ", intro='" + intro + '\'' + ", binding='" + binding + '\'' + ", pages='" + pages + '\'' + ", author='" + author + '\'' + ", publisher='" + publisher + '\'' + ", catalog='" + catalog + '\'' + ", supply=" + supply + ", status='" + status + '\'' + ", hot=" + hot + ", indate='" + indate + '\'' + ", stores=" + stores + '}'; } }
false
930
5
958
4
1,081
3
958
4
1,257
5
false
false
false
false
false
true
31030_0
import java.util.*; //将技巧抽象为一个方法,单独拿出来 interface Skill{ public: void skill(); }; //詹姆斯的技巧 class JamesSkill implements SKill{ public void JamesSkill::skill() { system.out.println("詹姆斯的技巧:战斧式扣篮"); } }; //科比的技巧 class KobeSkill implements SKill{ public void JamesSkill::skill() { system.out.println("科比的技巧: 后仰跳投"); } }; //艾弗森的技巧 class AISkill implements SKill{ public void JamesSkill::skill() { system.out.println("艾弗森的技巧: 变相"); } }; class NBAPlayer { : //姓名 private string name; private Skill skill; public NBAPlayer(string name,Skill skill){ this.name=name; this.skill=skill; } public void setSkill(Skill skill){ this.skill=skill; } public Skill getSkill(){ return skill; } public string getName(){ return name; } public void action(){ skill.skill(); } }; public class Main{ public static void main(String args[]) { //不同的技巧 Skill jamesSkill=new JamesSkill(); Skill kobeSkill=new KobeSkill(); Skill aiSkill=new AISkill(); //不同的球员 NBAPlayer james=new NBAPlayer("James",jamesSkill); NBAPlayer kobe=new NBAPlayer("kobe",kobeSkill); NBAPlayer ai=new NBAPlayer("AI",aiSkill); //会有不同的表现 james.action(); kobe.action(); ai.action(); } }
ZHONGHuanGit/DesignPattern
1开闭原则/NBAPlayer.java
499
//将技巧抽象为一个方法,单独拿出来
line_comment
zh-cn
import java.util.*; //将技 <SUF> interface Skill{ public: void skill(); }; //詹姆斯的技巧 class JamesSkill implements SKill{ public void JamesSkill::skill() { system.out.println("詹姆斯的技巧:战斧式扣篮"); } }; //科比的技巧 class KobeSkill implements SKill{ public void JamesSkill::skill() { system.out.println("科比的技巧: 后仰跳投"); } }; //艾弗森的技巧 class AISkill implements SKill{ public void JamesSkill::skill() { system.out.println("艾弗森的技巧: 变相"); } }; class NBAPlayer { : //姓名 private string name; private Skill skill; public NBAPlayer(string name,Skill skill){ this.name=name; this.skill=skill; } public void setSkill(Skill skill){ this.skill=skill; } public Skill getSkill(){ return skill; } public string getName(){ return name; } public void action(){ skill.skill(); } }; public class Main{ public static void main(String args[]) { //不同的技巧 Skill jamesSkill=new JamesSkill(); Skill kobeSkill=new KobeSkill(); Skill aiSkill=new AISkill(); //不同的球员 NBAPlayer james=new NBAPlayer("James",jamesSkill); NBAPlayer kobe=new NBAPlayer("kobe",kobeSkill); NBAPlayer ai=new NBAPlayer("AI",aiSkill); //会有不同的表现 james.action(); kobe.action(); ai.action(); } }
false
360
10
499
15
451
11
499
15
600
25
false
false
false
false
false
true
38899_3
package cdss.kb.core.patient; import cdss.kb.core.Core; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; import java.util.ArrayList; import java.util.Date; @Data public class PatientInfo extends Core { // 病人ID private String patientId; // 姓名 private String name; // 性别: 男,女 private String sex; // 出生日期: yyyy-MM-dd @JSONField(format = "yyyy-MM-dd") private Date dateOfBirth; // 血型: [0]-RH血型:阴性,阳性,未知; [1]-ABO血型:A,B,AB,O,未知, 例如['阴性','A']" private ArrayList<String> bloodType; // 电话 private String phone; // 地址 private String address; // 婚姻状态: 已婚,未婚,离婚 private String maritalStatus; // 职业 private String occupation; public PatientInfo(){ bloodType = new ArrayList<>(); } }
ZJU-BME-VICO/openEHR-COVID-19
Drools-Rules/DataModel/patient/PatientInfo.java
279
// 血型: [0]-RH血型:阴性,阳性,未知; [1]-ABO血型:A,B,AB,O,未知, 例如['阴性','A']"
line_comment
zh-cn
package cdss.kb.core.patient; import cdss.kb.core.Core; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; import java.util.ArrayList; import java.util.Date; @Data public class PatientInfo extends Core { // 病人ID private String patientId; // 姓名 private String name; // 性别: 男,女 private String sex; // 出生日期: yyyy-MM-dd @JSONField(format = "yyyy-MM-dd") private Date dateOfBirth; // 血型 <SUF> private ArrayList<String> bloodType; // 电话 private String phone; // 地址 private String address; // 婚姻状态: 已婚,未婚,离婚 private String maritalStatus; // 职业 private String occupation; public PatientInfo(){ bloodType = new ArrayList<>(); } }
false
241
46
279
54
270
45
279
54
339
63
false
false
false
false
false
true
65779_0
package com.zjut.oa.tool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.JSONObject; public class UploadTool { private static final Log log = LogFactory.getLog(UploadTool.class); //编辑器图片 public static final String SAVE_DIR_NAME = "attached"; public static final String[] ALLOW_FILE_SUFFIX = new String[] { "gif", "jpg", "jpeg", "png", "bmp" }; public static final long ALLOW_MAX_FILE_SIZE = 1000000; // 1M //图像 public static final String[] IMAGE_ALLOW_FILE_SUFFIX = new String[] { "gif", "jpg", "jpeg", "png", "bmp", }; public static final long IMAGE_ALLOW_MAX_FILE_SIZE = 10000000; // 10M public static final String FILE_SAVE_DIR_NAME = "file"; public static final String[] FILE_ALLOW_FILE_SUFFIX = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "doc", "ppt", "xls", "pdf", "chm", "7z", "zip", "rar" }; public static final long FILE_ALLOW_MAX_FILE_SIZE = 10000000; // 10M // 产品 public static final String PRODUCT_SAVE_DIR_NAME = "product"; // 团队 public static final String TEAM_SAVE_DIR_NAME = "team"; @SuppressWarnings("unchecked") public static String getErrorJson(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); log.info("Error Json: " + obj.toJSONString()); return obj.toJSONString(); } }
ZJUT/Jh-oa
src/com/zjut/oa/tool/UploadTool.java
464
//编辑器图片
line_comment
zh-cn
package com.zjut.oa.tool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.JSONObject; public class UploadTool { private static final Log log = LogFactory.getLog(UploadTool.class); //编辑 <SUF> public static final String SAVE_DIR_NAME = "attached"; public static final String[] ALLOW_FILE_SUFFIX = new String[] { "gif", "jpg", "jpeg", "png", "bmp" }; public static final long ALLOW_MAX_FILE_SIZE = 1000000; // 1M //图像 public static final String[] IMAGE_ALLOW_FILE_SUFFIX = new String[] { "gif", "jpg", "jpeg", "png", "bmp", }; public static final long IMAGE_ALLOW_MAX_FILE_SIZE = 10000000; // 10M public static final String FILE_SAVE_DIR_NAME = "file"; public static final String[] FILE_ALLOW_FILE_SUFFIX = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "doc", "ppt", "xls", "pdf", "chm", "7z", "zip", "rar" }; public static final long FILE_ALLOW_MAX_FILE_SIZE = 10000000; // 10M // 产品 public static final String PRODUCT_SAVE_DIR_NAME = "product"; // 团队 public static final String TEAM_SAVE_DIR_NAME = "team"; @SuppressWarnings("unchecked") public static String getErrorJson(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); log.info("Error Json: " + obj.toJSONString()); return obj.toJSONString(); } }
false
374
4
464
4
454
4
464
4
540
8
false
false
false
false
false
true
23251_3
public class Dog { // Java对象和类 // 对象:object 某个类的实例; 类:class 一类对象的行为和状态。 // 面向对象:抽象、封装、继承、多态 // 定义类的属性,成员变量 /* * Java中的基本数据类型:8种 * 1、整数型: byte、short、int、long * 2、浮点型: float(0.0f)、double(0.0d) * 3、字符:char 一个单一的 16 位 Unicode 字符 * 4、布尔型:boolean 只有两个值:true 和 false;默认是false * * 注: * 常用的是int: int数据类型是32位、有符号的以二进制补码表示的整数。默认值是0;整数型默认值都是0。long是0L * */ String breed; int size; String colour; int age; // 定义方法,类的行为; void eat() { } void run() { } void sleep() { } void name() { } }
ZJchenchang/HelloWorld
Dog.java
266
// 定义类的属性,成员变量
line_comment
zh-cn
public class Dog { // Java对象和类 // 对象:object 某个类的实例; 类:class 一类对象的行为和状态。 // 面向对象:抽象、封装、继承、多态 // 定义 <SUF> /* * Java中的基本数据类型:8种 * 1、整数型: byte、short、int、long * 2、浮点型: float(0.0f)、double(0.0d) * 3、字符:char 一个单一的 16 位 Unicode 字符 * 4、布尔型:boolean 只有两个值:true 和 false;默认是false * * 注: * 常用的是int: int数据类型是32位、有符号的以二进制补码表示的整数。默认值是0;整数型默认值都是0。long是0L * */ String breed; int size; String colour; int age; // 定义方法,类的行为; void eat() { } void run() { } void sleep() { } void name() { } }
false
275
10
266
8
276
7
266
8
364
13
false
false
false
false
false
true
9145_2
package leetcode; public class leet738 { //贪就完了 /* public int monotoneIncreasingDigits(int N) { char[] chars = (N + "").toCharArray(); StringBuilder sb=new StringBuilder(); int pre=-1; boolean flag=false; for (int i = 0; i < chars.length; i++) { if(flag==true){ sb.append(9); continue; } if(chars[i]>=pre){ sb.append(chars[i]); pre=chars[i]; }else { char c=sb.charAt(sb.length()-1); while (sb.length()>0&&sb.charAt(sb.length()-1)==c){ sb.deleteCharAt(sb.length()-1); i--; } sb.append((char)(chars[i]-1)); flag=true;i--; } } return Integer.valueOf(sb.toString()); }*/ //别人的貌似简单多了 哈哈哈 思想是一样的 public int monotoneIncreasingDigits(int N) { char[] arr = (N + "").toCharArray(); int max = -1, idx = -1; for (int i = 0; i < arr.length - 1; i++) { if (max < arr[i]) { max = arr[i]; idx = i; } if (arr[i] > arr[i + 1]) { arr[idx] -= 1; for(int j = idx + 1;j < arr.length;j++) { arr[j] = '9'; } break; } } return Integer.parseInt(new String(arr)); } //好家伙 //简单说一下理解 //就像叠罗汉一样 在保证递增的情况下在9次之内一定可以达到最大 // 1111 // 111 // 11 // 1 /* public int monotoneIncreasingDigits(int N) { int ones = 111111111; int res = 0; for(int i=0;i<9;i++){ while(res+ones>N){ ones/=10; } res += ones; if(ones==0) break; } return res; } */ }
ZLBer/DaliyOfProgramme
src/main/java/leetcode/leet738.java
559
//别人的貌似简单多了 哈哈哈 思想是一样的
line_comment
zh-cn
package leetcode; public class leet738 { //贪就完了 /* public int monotoneIncreasingDigits(int N) { char[] chars = (N + "").toCharArray(); StringBuilder sb=new StringBuilder(); int pre=-1; boolean flag=false; for (int i = 0; i < chars.length; i++) { if(flag==true){ sb.append(9); continue; } if(chars[i]>=pre){ sb.append(chars[i]); pre=chars[i]; }else { char c=sb.charAt(sb.length()-1); while (sb.length()>0&&sb.charAt(sb.length()-1)==c){ sb.deleteCharAt(sb.length()-1); i--; } sb.append((char)(chars[i]-1)); flag=true;i--; } } return Integer.valueOf(sb.toString()); }*/ //别人 <SUF> public int monotoneIncreasingDigits(int N) { char[] arr = (N + "").toCharArray(); int max = -1, idx = -1; for (int i = 0; i < arr.length - 1; i++) { if (max < arr[i]) { max = arr[i]; idx = i; } if (arr[i] > arr[i + 1]) { arr[idx] -= 1; for(int j = idx + 1;j < arr.length;j++) { arr[j] = '9'; } break; } } return Integer.parseInt(new String(arr)); } //好家伙 //简单说一下理解 //就像叠罗汉一样 在保证递增的情况下在9次之内一定可以达到最大 // 1111 // 111 // 11 // 1 /* public int monotoneIncreasingDigits(int N) { int ones = 111111111; int res = 0; for(int i=0;i<9;i++){ while(res+ones>N){ ones/=10; } res += ones; if(ones==0) break; } return res; } */ }
false
497
14
559
19
594
12
559
19
694
35
false
false
false
false
false
true
49760_2
package servlet.student; import po.CollegeEntity; import po.StudentEntity; import po.XieyiEntity; import util.HibernateUtil; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.List; /** * Created by libin on 2017/5/16. */ public class Student_SecondSanfangxieyi extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); int studentid; if (request.getSession().getAttribute("userid") != null) { studentid = Integer.parseInt(session.getAttribute("userid").toString()); } else { studentid = Integer.parseInt(request.getParameter("studentid")); } //判断是否已经申请过 String hql = "where studentid=" + studentid; List<XieyiEntity> students = HibernateUtil.query("XieyiEntity", hql); if (students.size() == 0) { XieyiEntity student = new XieyiEntity(); //查找学生所属学院 StudentEntity student2 = (StudentEntity) HibernateUtil.get(StudentEntity.class, studentid); String collegename = student2.getStudentcollege(); String hql1 = "where collegename=" + "'" + collegename + "'"; List<CollegeEntity> colleges = HibernateUtil.query("CollegeEntity", hql1); String collegeid = ""; for (CollegeEntity college : colleges) { collegeid = college.getCollegeid() + ""; } //判断学院id位数 if (Integer.parseInt(collegeid) / 10 == 0) { collegeid = "0" + collegeid; } String others = request.getParameter("others"); student.setStudentid(studentid); student.setState(0); student.setOthers(others); student.setCollegename(collegename); student.setComnature("党政机关、科研事业单位、学校、商贸公司、厂矿企业、部队、其它(划√)"); HibernateUtil.add(student); //再次查找并拼接三方协议编号 List<XieyiEntity> xieyis = HibernateUtil.query("XieyiEntity", "where studentid=" + studentid); for (XieyiEntity xieyi : xieyis) { String xieyiid = xieyi.getXieyiid() + " "; String xieyinumber1 = xieyiid.substring(0, 4); String xieyinumber2 = xieyiid.substring(4, 8); xieyi.setXieyinum(xieyinumber1 + collegeid + xieyinumber2); HibernateUtil.update(xieyi); } request.setAttribute("message", "申请成功"); if (request.getSession().getAttribute("userid") != null) { request.getRequestDispatcher("/WEUI/operate_success.jsp").forward(request, response); } else { request.getRequestDispatcher("student_secondSanfangxieyi.jsp").forward(request, response); } } else { if (request.getSession().getAttribute("userid") != null) { request.getRequestDispatcher("/WEUI/sanfang.jsp").forward(request, response); } else { request.setAttribute("message", "已提交过申请请耐心等待"); request.getRequestDispatcher("student_secondSanfangxieyi.jsp").forward(request, response); } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
ZLBer/sdauweixin
src/servlet/student/Student_SecondSanfangxieyi.java
944
//查找学生所属学院
line_comment
zh-cn
package servlet.student; import po.CollegeEntity; import po.StudentEntity; import po.XieyiEntity; import util.HibernateUtil; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.List; /** * Created by libin on 2017/5/16. */ public class Student_SecondSanfangxieyi extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); int studentid; if (request.getSession().getAttribute("userid") != null) { studentid = Integer.parseInt(session.getAttribute("userid").toString()); } else { studentid = Integer.parseInt(request.getParameter("studentid")); } //判断是否已经申请过 String hql = "where studentid=" + studentid; List<XieyiEntity> students = HibernateUtil.query("XieyiEntity", hql); if (students.size() == 0) { XieyiEntity student = new XieyiEntity(); //查找 <SUF> StudentEntity student2 = (StudentEntity) HibernateUtil.get(StudentEntity.class, studentid); String collegename = student2.getStudentcollege(); String hql1 = "where collegename=" + "'" + collegename + "'"; List<CollegeEntity> colleges = HibernateUtil.query("CollegeEntity", hql1); String collegeid = ""; for (CollegeEntity college : colleges) { collegeid = college.getCollegeid() + ""; } //判断学院id位数 if (Integer.parseInt(collegeid) / 10 == 0) { collegeid = "0" + collegeid; } String others = request.getParameter("others"); student.setStudentid(studentid); student.setState(0); student.setOthers(others); student.setCollegename(collegename); student.setComnature("党政机关、科研事业单位、学校、商贸公司、厂矿企业、部队、其它(划√)"); HibernateUtil.add(student); //再次查找并拼接三方协议编号 List<XieyiEntity> xieyis = HibernateUtil.query("XieyiEntity", "where studentid=" + studentid); for (XieyiEntity xieyi : xieyis) { String xieyiid = xieyi.getXieyiid() + " "; String xieyinumber1 = xieyiid.substring(0, 4); String xieyinumber2 = xieyiid.substring(4, 8); xieyi.setXieyinum(xieyinumber1 + collegeid + xieyinumber2); HibernateUtil.update(xieyi); } request.setAttribute("message", "申请成功"); if (request.getSession().getAttribute("userid") != null) { request.getRequestDispatcher("/WEUI/operate_success.jsp").forward(request, response); } else { request.getRequestDispatcher("student_secondSanfangxieyi.jsp").forward(request, response); } } else { if (request.getSession().getAttribute("userid") != null) { request.getRequestDispatcher("/WEUI/sanfang.jsp").forward(request, response); } else { request.setAttribute("message", "已提交过申请请耐心等待"); request.getRequestDispatcher("student_secondSanfangxieyi.jsp").forward(request, response); } } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
false
797
5
944
7
956
5
944
7
1,107
11
false
false
false
false
false
true
43055_2
package db; import org.apache.commons.dbcp2.BasicDataSourceFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /* * DBCP连接池在构建时需要引入 * commons-collections * commons-dbcp2 * commons-logging * commons-pool2 * mysql-connector * 共五个jar包,缺一不可*/ /** * 本模块构建了一个DBCP连接池 * DBCP连接池配置位于config/dbcpconfig.properties中 * 连接数据库qzqmall user:root password:admin useSSL:false charset:utf8 */ public class DBCPUtils { private static DataSource ds;//定义一个连接池对象 static{ try { Properties pro = new Properties(); pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("config/dbcpconfig.properties")); ds = BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象 } catch (Exception e) { throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!"); } } /** * 构造从连接池取出连接的方法 * @return Connection * @throws SQLException */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 关闭rs & stmt & conn * @param rs ResultSet * @param stmt Statement * @param conn Connection */ public static void closeAll(ResultSet rs, Statement stmt, Connection conn){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close();//关闭 } catch (SQLException e) { e.printStackTrace(); } } } /** * 测试类 * @param args */ public static void main(String[] args) { try { System.out.println("对DBCP池进行测试"); Connection con = DBCPUtils.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM user"); System.out.println(rs.next()); closeAll(rs,stmt,con); } catch (SQLException e) { e.printStackTrace(); } } }
ZQ-Qi/QMYmall
src/db/DBCPUtils.java
585
//定义一个连接池对象
line_comment
zh-cn
package db; import org.apache.commons.dbcp2.BasicDataSourceFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /* * DBCP连接池在构建时需要引入 * commons-collections * commons-dbcp2 * commons-logging * commons-pool2 * mysql-connector * 共五个jar包,缺一不可*/ /** * 本模块构建了一个DBCP连接池 * DBCP连接池配置位于config/dbcpconfig.properties中 * 连接数据库qzqmall user:root password:admin useSSL:false charset:utf8 */ public class DBCPUtils { private static DataSource ds;//定义 <SUF> static{ try { Properties pro = new Properties(); pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("config/dbcpconfig.properties")); ds = BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象 } catch (Exception e) { throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!"); } } /** * 构造从连接池取出连接的方法 * @return Connection * @throws SQLException */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 关闭rs & stmt & conn * @param rs ResultSet * @param stmt Statement * @param conn Connection */ public static void closeAll(ResultSet rs, Statement stmt, Connection conn){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close();//关闭 } catch (SQLException e) { e.printStackTrace(); } } } /** * 测试类 * @param args */ public static void main(String[] args) { try { System.out.println("对DBCP池进行测试"); Connection con = DBCPUtils.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM user"); System.out.println(rs.next()); closeAll(rs,stmt,con); } catch (SQLException e) { e.printStackTrace(); } } }
false
529
6
585
6
634
6
585
6
750
10
false
false
false
false
false
true
30628_1
package com.gz.fz.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class HttpUtils { public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } // public static void main(String []args) { // String data = HttpUtils.sendGet("http://127.0.0.1:5000/search?q=法律&bid=5"); // System.out.println("data:" + data); // } }
ZQPlantSoftware/ebook-reader-services
src/main/java/com/gz/fz/utils/HttpUtils.java
400
// 设置通用的请求属性
line_comment
zh-cn
package com.gz.fz.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class HttpUtils { public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置 <SUF> connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } // public static void main(String []args) { // String data = HttpUtils.sendGet("http://127.0.0.1:5000/search?q=法律&bid=5"); // System.out.println("data:" + data); // } }
false
350
6
400
6
425
6
400
6
488
11
false
false
false
false
false
true
64668_2
1、采用ViewHolder优化ListView (1)在自定义的Adapter中自定义内部类ViewHolder,并将布局的控价作为成员变量。 (2)核心代码: 判断是否缓存,若没有缓存,则通过ConvertView.setTag(holder)方法进行缓存,否则通过Tag找到缓存布局。 2、设置分隔线:通过divider和dividerHight两个属性实现。 代码如下: android:divider="@android:color/draker_gray" android:dividerHight="10dp" /****若divider设为null,则表示分割线为透明的。********/ 3、隐藏滚动条:android:scrollBar="none" 4、取消Item点击效果:android:listSelector="@android:color/transparent" 或 android:listSelector="#00000000" 5、设置ListView需要显示第几项:listView.setSelection(N); 6、实现平滑移动: mListView.smoothScrollBy(distance,duration); mListView.smoothScrollByOffset(offset); mListView.smoothScrollToPosition(index); 7、动态修改ListView: mData.add("New"); mAdapter.notifyDataSetChanged(); 8、处理空的ListView: listView.setEmptyView(findViewById(R.id.empty_view)); //表示当listView为空数据时,显示一张默认的图片,用力提示用户,有数据时,则不会显示。 9、ListView 的滑动监听: (1)onTouchListener: onTouch回调方法: ACTION_DOMN,ACTION_UP,ACTION_MOVE 三个事件。 (2)onScrollListener:onScrollStateChanged()和onScroll()两个回调方法。 onScrollStateChanged()参数有三种形式: --> onScrollListener.SCROLL_STATE_IDLE:滚动停止时 --> onScrollListener.SCROLL_STATE_TOUCH_SCROLL:正在滚动时 --> onScrollListener.SCROLL_STATE_FLING:用手指用力滑动时,在离开时由于惯性继续滑动的状态。 10、onScroll方法: (1)参数如下: firstVisibleItem:当前能看到的第一个Item的ID visibleItemCount:当前能看见的Item总数 totalItemCount:整个ListView的Item总数 (2)即使显示一小半的Item也包括在内了。 (3)判断滚动是否到最后一行,就可以使用如下的代码了: if(firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0){ //滚动到最后一行了 } (4)判断滚动方向: if(firstVisibleItem > lastVisibleItem){ //上滑 } else if(firstVisibleItem < lastVisibleItem){ //下滑 } lastVisibleItem = firstVisibleItem; 11、ScrollTo 与 ScrollBy: SCrollTo(int x,int y) //表示移动到一个具体的坐标点 SCrollBy(int dx,int dy) //表示移动的增量为 dx,dy 注意:移动的只是View的content,所以应该View所在的ViewGroup中来使用ScrollBy()方法,移动它的子View,代码如下: ((view).getParent).scrollBy(offsetX,offsetY); 12、SCroller 实现平滑滚动原理: (1)原理: 将滑动距离分成多分,每份采用瞬间移动,利用人眼视觉暂留特性。 (2)大致步骤: a. 创建Scroll对象。 b. 重写computeScroll()方法,实现模拟滑动(记得调用invalidate()方法实现重绘方法,不断调用computeScroll()方法)。 c. 开启模拟过程。 13、具有弹性的ListView: (1)重写overScrollBy()方法。 (2)将maxOverScrollY改为设置的值 -mMaxOverDistance private void initeView() { DisPlayMetrics metrics = mContext.getResource().getDisplayMetrics(); float density = metrics.density; mMaxOverDistance = (int)(density * mMaxOverDistance); } 14、向下滚动时,标题栏和悬浮按钮消失效果实现: (1)添加一个HeadView,避免第一个Item被ToolBar遮挡。 (2)定义一个变量用来获取系统认为的最低滑动距离。 (3)监听滑动事件了。 15、聊天界面: getItemViewType(int position) //返回第position个Item是何种类型 getViewTypeCount() //返回不同布局的总数 16、侧边滑动效果:DrawerLayout 和 SlidingPanelLayout 布局背后的实现类:ViewDragHelper (1)初始化ViewDragHelper,viewDragHelper.create(this,callBack); (2)重写事件拦截方法,onInterceptTouchEvent,onTouchEvent。 (3)处理computeScroll()方法。 (4)处理回调callBack。
ZSCDumin/AndroidDevelopmentSummary
Android性能优化总结/ListView性能优化.java
1,132
//滚动到最后一行了
line_comment
zh-cn
1、采用ViewHolder优化ListView (1)在自定义的Adapter中自定义内部类ViewHolder,并将布局的控价作为成员变量。 (2)核心代码: 判断是否缓存,若没有缓存,则通过ConvertView.setTag(holder)方法进行缓存,否则通过Tag找到缓存布局。 2、设置分隔线:通过divider和dividerHight两个属性实现。 代码如下: android:divider="@android:color/draker_gray" android:dividerHight="10dp" /****若divider设为null,则表示分割线为透明的。********/ 3、隐藏滚动条:android:scrollBar="none" 4、取消Item点击效果:android:listSelector="@android:color/transparent" 或 android:listSelector="#00000000" 5、设置ListView需要显示第几项:listView.setSelection(N); 6、实现平滑移动: mListView.smoothScrollBy(distance,duration); mListView.smoothScrollByOffset(offset); mListView.smoothScrollToPosition(index); 7、动态修改ListView: mData.add("New"); mAdapter.notifyDataSetChanged(); 8、处理空的ListView: listView.setEmptyView(findViewById(R.id.empty_view)); //表示当listView为空数据时,显示一张默认的图片,用力提示用户,有数据时,则不会显示。 9、ListView 的滑动监听: (1)onTouchListener: onTouch回调方法: ACTION_DOMN,ACTION_UP,ACTION_MOVE 三个事件。 (2)onScrollListener:onScrollStateChanged()和onScroll()两个回调方法。 onScrollStateChanged()参数有三种形式: --> onScrollListener.SCROLL_STATE_IDLE:滚动停止时 --> onScrollListener.SCROLL_STATE_TOUCH_SCROLL:正在滚动时 --> onScrollListener.SCROLL_STATE_FLING:用手指用力滑动时,在离开时由于惯性继续滑动的状态。 10、onScroll方法: (1)参数如下: firstVisibleItem:当前能看到的第一个Item的ID visibleItemCount:当前能看见的Item总数 totalItemCount:整个ListView的Item总数 (2)即使显示一小半的Item也包括在内了。 (3)判断滚动是否到最后一行,就可以使用如下的代码了: if(firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0){ //滚动 <SUF> } (4)判断滚动方向: if(firstVisibleItem > lastVisibleItem){ //上滑 } else if(firstVisibleItem < lastVisibleItem){ //下滑 } lastVisibleItem = firstVisibleItem; 11、ScrollTo 与 ScrollBy: SCrollTo(int x,int y) //表示移动到一个具体的坐标点 SCrollBy(int dx,int dy) //表示移动的增量为 dx,dy 注意:移动的只是View的content,所以应该View所在的ViewGroup中来使用ScrollBy()方法,移动它的子View,代码如下: ((view).getParent).scrollBy(offsetX,offsetY); 12、SCroller 实现平滑滚动原理: (1)原理: 将滑动距离分成多分,每份采用瞬间移动,利用人眼视觉暂留特性。 (2)大致步骤: a. 创建Scroll对象。 b. 重写computeScroll()方法,实现模拟滑动(记得调用invalidate()方法实现重绘方法,不断调用computeScroll()方法)。 c. 开启模拟过程。 13、具有弹性的ListView: (1)重写overScrollBy()方法。 (2)将maxOverScrollY改为设置的值 -mMaxOverDistance private void initeView() { DisPlayMetrics metrics = mContext.getResource().getDisplayMetrics(); float density = metrics.density; mMaxOverDistance = (int)(density * mMaxOverDistance); } 14、向下滚动时,标题栏和悬浮按钮消失效果实现: (1)添加一个HeadView,避免第一个Item被ToolBar遮挡。 (2)定义一个变量用来获取系统认为的最低滑动距离。 (3)监听滑动事件了。 15、聊天界面: getItemViewType(int position) //返回第position个Item是何种类型 getViewTypeCount() //返回不同布局的总数 16、侧边滑动效果:DrawerLayout 和 SlidingPanelLayout 布局背后的实现类:ViewDragHelper (1)初始化ViewDragHelper,viewDragHelper.create(this,callBack); (2)重写事件拦截方法,onInterceptTouchEvent,onTouchEvent。 (3)处理computeScroll()方法。 (4)处理回调callBack。
false
1,035
6
1,132
8
1,112
5
1,132
8
1,596
11
false
false
false
false
false
true
41193_12
package com.zscdumin.zhixinapp.activity; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.pgyersdk.crash.PgyCrashManager; import com.pgyersdk.javabean.AppBean; import com.pgyersdk.update.PgyUpdateManager; import com.pgyersdk.update.UpdateManagerListener; import com.zscdumin.zhixinapp.R; import com.zscdumin.zhixinapp.fragment.MeFragment; import com.zscdumin.zhixinapp.fragment.ParentFragment; import com.zscdumin.zhixinapp.service.AutoUpdateService; import java.io.IOException; import java.io.InputStream; import butterknife.BindView; import butterknife.ButterKnife; import cn.bmob.v3.Bmob; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.ResponseBody; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @BindView(R.id.drawer_layout) DrawerLayout drawer; @BindView(R.id.nav_layout) NavigationView nav_layout; //Fragment private ParentFragment newsListFragment = null; private MeFragment meFragment = null; private FragmentTransaction transaction; private Fragment fragment; private ImageView user_icon_iv = null; private TextView user_name_tv = null; private TextView user_phone_tv = null; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0x11: user_icon_iv.setImageBitmap((Bitmap) msg.obj); break; } } }; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bmob.initialize(this, "e7edc6aee5407505ad8a1b08cddbd4d8"); if (getSupportActionBar() != null) { getSupportActionBar().hide(); } setContentView(R.layout.fragment_main); ButterKnife.bind(this); PgyUpdateManager.register(this); transaction = getSupportFragmentManager().beginTransaction(); //初始是新闻页面 newsListFragment = new ParentFragment(); transaction.add(R.id.fl_content, newsListFragment, "newsListFragment").commit(); nav_layout.setNavigationItemSelectedListener(this); View view = nav_layout.inflateHeaderView(R.layout.nav_header_main); user_name_tv = view.findViewById(R.id.user_name); user_phone_tv = view.findViewById(R.id.user_phone); user_icon_iv = view.findViewById(R.id.user_icon); /** * 获取用户数据 */ Intent intent = getIntent(); Bundle bundle = intent.getExtras(); String login_type = bundle.getString("login_type"); if (login_type.equals("with_face")) { String user_name = bundle.getString("user_name"); String user_icon_url = bundle.getString("user_icon"); String user_phone = bundle.getString("phone_num"); user_name_tv.setText("用户:【" + user_name + "】"); user_phone_tv.setText("手机:【" + user_phone + "】"); setBitmapByUrl(user_icon_url); } else if (login_type.equals("with_account")) { user_name_tv.setText("用户:【杜敏】"); user_phone_tv.setText("手机:【18979429542】"); } Intent service = new Intent(this, AutoUpdateService.class); startService(service); } public void setBitmapByUrl(final String url) { new Thread() { @Override public void run() { //获取okHttp对象get请求, try { OkHttpClient client = new OkHttpClient(); //获取请求对象 Request request = new Request.Builder().url(url).build(); //获取响应体 ResponseBody body = client.newCall(request).execute().body(); //获取流 InputStream in = body.byteStream(); //转化为bitmap Bitmap bitmap = BitmapFactory.decodeStream(in); //使用Hanlder发送消息 Message msg = Message.obtain(); msg.what = 0x11; msg.obj = bitmap; handler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } } }.start(); } @Override public boolean onNavigationItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.nav_news: //新闻菜单 item.setChecked(true); transaction = getSupportFragmentManager().beginTransaction(); fragment = getSupportFragmentManager().findFragmentByTag("newsListFragment"); if (fragment != null) { transaction.show(newsListFragment); } else { transaction.add(R.id.fl_content, newsListFragment, "newsListFragment"); } if (meFragment != null) { transaction.hide(getSupportFragmentManager().findFragmentByTag("meFragment")); } //提交事务 transaction.commit(); //关闭抽屉菜单 drawer.closeDrawers(); break; case R.id.nav_me: item.setChecked(true); transaction = getSupportFragmentManager().beginTransaction(); if (meFragment != null) { transaction.show(meFragment); } else { meFragment = new MeFragment(); transaction.add(R.id.fl_content, meFragment, "meFragment"); } if (newsListFragment != null) { transaction.hide(getSupportFragmentManager().findFragmentByTag("newsListFragment")); } transaction.commit(); //关闭抽屉菜单 drawer.closeDrawers(); break; case R.id.nav_tuling: intent = new Intent(this, TulingActivity.class); startActivity(intent); break; case R.id.nav_weather: intent = new Intent(this, WeatherMainActivity.class); startActivity(intent); break; case R.id.nav_version_update: checkAppUpdate(); break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { new AlertDialog.Builder(this).setTitle("主人,确定要退出吗?") .setIcon(R.drawable.exit) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "向右滑弹出抽屉菜单!", Toast.LENGTH_LONG).show(); } }).show(); } return false; } @Override protected void onDestroy() { super.onDestroy(); PgyCrashManager.unregister(); System.exit(0); } //版本更新代码 private void checkAppUpdate() { PgyUpdateManager.register(MainActivity.this, new UpdateManagerListener() { @Override public void onUpdateAvailable(final String result) { // 将新版本信息封装到AppBean中 final AppBean appBean = getAppBeanFromString(result); new AlertDialog.Builder(MainActivity.this) .setIcon(R.drawable.update_bg) .setTitle("发现新版本,立即更新?") .setMessage(appBean.getReleaseNote()) .setNegativeButton( "确定", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { startDownloadTask( MainActivity.this, appBean.getDownloadURL()); } }).show(); } @Override public void onNoUpdateAvailable() { Toast.makeText(MainActivity.this, "当前应用已经是最新版了!", Toast.LENGTH_SHORT).show(); } }); } }
ZSCDumin/ZhiXinApp
app/src/main/java/com/zscdumin/zhixinapp/activity/MainActivity.java
2,290
//关闭抽屉菜单
line_comment
zh-cn
package com.zscdumin.zhixinapp.activity; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.pgyersdk.crash.PgyCrashManager; import com.pgyersdk.javabean.AppBean; import com.pgyersdk.update.PgyUpdateManager; import com.pgyersdk.update.UpdateManagerListener; import com.zscdumin.zhixinapp.R; import com.zscdumin.zhixinapp.fragment.MeFragment; import com.zscdumin.zhixinapp.fragment.ParentFragment; import com.zscdumin.zhixinapp.service.AutoUpdateService; import java.io.IOException; import java.io.InputStream; import butterknife.BindView; import butterknife.ButterKnife; import cn.bmob.v3.Bmob; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.ResponseBody; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @BindView(R.id.drawer_layout) DrawerLayout drawer; @BindView(R.id.nav_layout) NavigationView nav_layout; //Fragment private ParentFragment newsListFragment = null; private MeFragment meFragment = null; private FragmentTransaction transaction; private Fragment fragment; private ImageView user_icon_iv = null; private TextView user_name_tv = null; private TextView user_phone_tv = null; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0x11: user_icon_iv.setImageBitmap((Bitmap) msg.obj); break; } } }; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bmob.initialize(this, "e7edc6aee5407505ad8a1b08cddbd4d8"); if (getSupportActionBar() != null) { getSupportActionBar().hide(); } setContentView(R.layout.fragment_main); ButterKnife.bind(this); PgyUpdateManager.register(this); transaction = getSupportFragmentManager().beginTransaction(); //初始是新闻页面 newsListFragment = new ParentFragment(); transaction.add(R.id.fl_content, newsListFragment, "newsListFragment").commit(); nav_layout.setNavigationItemSelectedListener(this); View view = nav_layout.inflateHeaderView(R.layout.nav_header_main); user_name_tv = view.findViewById(R.id.user_name); user_phone_tv = view.findViewById(R.id.user_phone); user_icon_iv = view.findViewById(R.id.user_icon); /** * 获取用户数据 */ Intent intent = getIntent(); Bundle bundle = intent.getExtras(); String login_type = bundle.getString("login_type"); if (login_type.equals("with_face")) { String user_name = bundle.getString("user_name"); String user_icon_url = bundle.getString("user_icon"); String user_phone = bundle.getString("phone_num"); user_name_tv.setText("用户:【" + user_name + "】"); user_phone_tv.setText("手机:【" + user_phone + "】"); setBitmapByUrl(user_icon_url); } else if (login_type.equals("with_account")) { user_name_tv.setText("用户:【杜敏】"); user_phone_tv.setText("手机:【18979429542】"); } Intent service = new Intent(this, AutoUpdateService.class); startService(service); } public void setBitmapByUrl(final String url) { new Thread() { @Override public void run() { //获取okHttp对象get请求, try { OkHttpClient client = new OkHttpClient(); //获取请求对象 Request request = new Request.Builder().url(url).build(); //获取响应体 ResponseBody body = client.newCall(request).execute().body(); //获取流 InputStream in = body.byteStream(); //转化为bitmap Bitmap bitmap = BitmapFactory.decodeStream(in); //使用Hanlder发送消息 Message msg = Message.obtain(); msg.what = 0x11; msg.obj = bitmap; handler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } } }.start(); } @Override public boolean onNavigationItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.nav_news: //新闻菜单 item.setChecked(true); transaction = getSupportFragmentManager().beginTransaction(); fragment = getSupportFragmentManager().findFragmentByTag("newsListFragment"); if (fragment != null) { transaction.show(newsListFragment); } else { transaction.add(R.id.fl_content, newsListFragment, "newsListFragment"); } if (meFragment != null) { transaction.hide(getSupportFragmentManager().findFragmentByTag("meFragment")); } //提交事务 transaction.commit(); //关闭抽屉菜单 drawer.closeDrawers(); break; case R.id.nav_me: item.setChecked(true); transaction = getSupportFragmentManager().beginTransaction(); if (meFragment != null) { transaction.show(meFragment); } else { meFragment = new MeFragment(); transaction.add(R.id.fl_content, meFragment, "meFragment"); } if (newsListFragment != null) { transaction.hide(getSupportFragmentManager().findFragmentByTag("newsListFragment")); } transaction.commit(); //关闭 <SUF> drawer.closeDrawers(); break; case R.id.nav_tuling: intent = new Intent(this, TulingActivity.class); startActivity(intent); break; case R.id.nav_weather: intent = new Intent(this, WeatherMainActivity.class); startActivity(intent); break; case R.id.nav_version_update: checkAppUpdate(); break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { new AlertDialog.Builder(this).setTitle("主人,确定要退出吗?") .setIcon(R.drawable.exit) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "向右滑弹出抽屉菜单!", Toast.LENGTH_LONG).show(); } }).show(); } return false; } @Override protected void onDestroy() { super.onDestroy(); PgyCrashManager.unregister(); System.exit(0); } //版本更新代码 private void checkAppUpdate() { PgyUpdateManager.register(MainActivity.this, new UpdateManagerListener() { @Override public void onUpdateAvailable(final String result) { // 将新版本信息封装到AppBean中 final AppBean appBean = getAppBeanFromString(result); new AlertDialog.Builder(MainActivity.this) .setIcon(R.drawable.update_bg) .setTitle("发现新版本,立即更新?") .setMessage(appBean.getReleaseNote()) .setNegativeButton( "确定", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { startDownloadTask( MainActivity.this, appBean.getDownloadURL()); } }).show(); } @Override public void onNoUpdateAvailable() { Toast.makeText(MainActivity.this, "当前应用已经是最新版了!", Toast.LENGTH_SHORT).show(); } }); } }
false
1,760
5
2,290
6
2,224
5
2,290
6
3,057
13
false
false
false
false
false
true
46258_7
/* * 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.zto.fire.common.bean.runtime; import com.sun.management.ThreadMXBean; import java.io.Serializable; import java.lang.management.ManagementFactory; /** * 用于包装运行时线程信息 * @author ChengLong 2019-9-28 19:36:52 */ public class ThreadInfo implements Serializable { private static final long serialVersionUID = 7950498675819426939L; /** * 当前线程的总 CPU 时间(以毫微秒为单位) */ private long cpuTime; /** * 当前线程的总用户cpu时间(以毫微秒为单位) */ private long userTime; /** * 当前守护线程的总数 */ private int deamonCount; /** * 返回自从 Java 虚拟机启动或峰值重置以来峰值活动线程计数 */ private int peakCount; /** * 返回当前线程的总数,包括守护线程和非守护线程 */ private int totalCount; /** * 返回自从 Java 虚拟机启动以来创建和启动的线程总数目 */ private long totalStartedCount; private ThreadInfo() {} public long getCpuTime() { return cpuTime; } public long getUserTime() { return userTime; } public int getDeamonCount() { return deamonCount; } public int getPeakCount() { return peakCount; } public int getTotalCount() { return totalCount; } public long getTotalStartedCount() { return totalStartedCount; } /** * 获取线程相关信息 */ public static ThreadInfo getThreadInfo() { ThreadInfo threadInfo = new ThreadInfo(); ThreadMXBean threadMBean = (ThreadMXBean) ManagementFactory.getThreadMXBean(); threadInfo.cpuTime = threadMBean.getCurrentThreadCpuTime(); threadInfo.userTime = threadMBean.getCurrentThreadUserTime(); threadInfo.deamonCount = threadMBean.getDaemonThreadCount(); threadInfo.peakCount = threadMBean.getPeakThreadCount(); threadInfo.totalCount = threadMBean.getThreadCount(); threadInfo.totalStartedCount = threadMBean.getTotalStartedThreadCount(); return threadInfo; } }
ZTO-Express/fire
fire-common/src/main/java/com/zto/fire/common/bean/runtime/ThreadInfo.java
725
/** * 返回自从 Java 虚拟机启动以来创建和启动的线程总数目 */
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.zto.fire.common.bean.runtime; import com.sun.management.ThreadMXBean; import java.io.Serializable; import java.lang.management.ManagementFactory; /** * 用于包装运行时线程信息 * @author ChengLong 2019-9-28 19:36:52 */ public class ThreadInfo implements Serializable { private static final long serialVersionUID = 7950498675819426939L; /** * 当前线程的总 CPU 时间(以毫微秒为单位) */ private long cpuTime; /** * 当前线程的总用户cpu时间(以毫微秒为单位) */ private long userTime; /** * 当前守护线程的总数 */ private int deamonCount; /** * 返回自从 Java 虚拟机启动或峰值重置以来峰值活动线程计数 */ private int peakCount; /** * 返回当前线程的总数,包括守护线程和非守护线程 */ private int totalCount; /** * 返回自 <SUF>*/ private long totalStartedCount; private ThreadInfo() {} public long getCpuTime() { return cpuTime; } public long getUserTime() { return userTime; } public int getDeamonCount() { return deamonCount; } public int getPeakCount() { return peakCount; } public int getTotalCount() { return totalCount; } public long getTotalStartedCount() { return totalStartedCount; } /** * 获取线程相关信息 */ public static ThreadInfo getThreadInfo() { ThreadInfo threadInfo = new ThreadInfo(); ThreadMXBean threadMBean = (ThreadMXBean) ManagementFactory.getThreadMXBean(); threadInfo.cpuTime = threadMBean.getCurrentThreadCpuTime(); threadInfo.userTime = threadMBean.getCurrentThreadUserTime(); threadInfo.deamonCount = threadMBean.getDaemonThreadCount(); threadInfo.peakCount = threadMBean.getPeakThreadCount(); threadInfo.totalCount = threadMBean.getThreadCount(); threadInfo.totalStartedCount = threadMBean.getTotalStartedThreadCount(); return threadInfo; } }
false
681
24
725
23
763
22
725
23
947
42
false
false
false
false
false
true
27129_7
/* 习题: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. */ /*解析 本题考察的东西就是看你思考的全不全面,而且他还没有说具体的规则,我说一下它判定的规则,分为几种情况 1.空串 2.数字之前有空格如:“ 123” 3.带符号的字符串 如:“+123” 4.在数字中间夹杂字符或者空格 如:“ —12 33” 将要输出 -12 后面舍弃 5.存在溢出问题,这个我在写的时候就很迷茫。下面主要说明这个问题。 因为是int类型的,所以占4个字节,记住 最大的最小的是 -(2^31)-1 ~ 2^31 -1(有一位是符号位,还有一个数字是0) 判断溢出的条件就是,有两种可能,1.结果>最大位/10 2.结果=最大位/10 并且 digit>最大位%10 只有这两种可能,因为一个数位的变化就是增加或者减少10。 代码如下: */ class Solution { public int myAtoi(String str) { int sybol = 1;//符号显示 int index=0;//索引位置 int digit;//记录每一位 int result=0;//记录结果 //1.空串 if(str.length()==0){ return 0; } //2.带有空格进行移除 while(str.charAt(index)==' ') { index++; } //3.正数负数 if(str.charAt(index)=='+'||str.charAt(index)=='-') { if(str.charAt(index)=='-') { sybol=0; } index++; } //4.逐一扫描 for(int i = index;i<str.length();i++) { digit=str.charAt(i)-'0'; //如果是数字 if(digit>=0&&digit<=9){ //判断溢出 if(Integer.MAX_VALUE/10 < result || Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE %10 < digit) return sybol == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; result = result*10+digit; } //如果中途是空格 else if(digit==' '-'0'){ break; } //如果是非数字非空隔,即为字符 else{ break; } } System.out.println(result); //如果是负数 if(sybol==0) { result = -result; } return result; } }
ZTYZZ/leetcode
8. String to Integer (atoi).java
723
//2.带有空格进行移除
line_comment
zh-cn
/* 习题: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. */ /*解析 本题考察的东西就是看你思考的全不全面,而且他还没有说具体的规则,我说一下它判定的规则,分为几种情况 1.空串 2.数字之前有空格如:“ 123” 3.带符号的字符串 如:“+123” 4.在数字中间夹杂字符或者空格 如:“ —12 33” 将要输出 -12 后面舍弃 5.存在溢出问题,这个我在写的时候就很迷茫。下面主要说明这个问题。 因为是int类型的,所以占4个字节,记住 最大的最小的是 -(2^31)-1 ~ 2^31 -1(有一位是符号位,还有一个数字是0) 判断溢出的条件就是,有两种可能,1.结果>最大位/10 2.结果=最大位/10 并且 digit>最大位%10 只有这两种可能,因为一个数位的变化就是增加或者减少10。 代码如下: */ class Solution { public int myAtoi(String str) { int sybol = 1;//符号显示 int index=0;//索引位置 int digit;//记录每一位 int result=0;//记录结果 //1.空串 if(str.length()==0){ return 0; } //2. <SUF> while(str.charAt(index)==' ') { index++; } //3.正数负数 if(str.charAt(index)=='+'||str.charAt(index)=='-') { if(str.charAt(index)=='-') { sybol=0; } index++; } //4.逐一扫描 for(int i = index;i<str.length();i++) { digit=str.charAt(i)-'0'; //如果是数字 if(digit>=0&&digit<=9){ //判断溢出 if(Integer.MAX_VALUE/10 < result || Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE %10 < digit) return sybol == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; result = result*10+digit; } //如果中途是空格 else if(digit==' '-'0'){ break; } //如果是非数字非空隔,即为字符 else{ break; } } System.out.println(result); //如果是负数 if(sybol==0) { result = -result; } return result; } }
false
638
9
722
9
715
7
723
9
947
13
false
false
false
false
false
true
66632_3
package org.zyf.javabasic.workflowpipline.worker.aideal; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Service; import org.zyf.javabasic.workflowpipline.annotations.WorkerInfo; import org.zyf.javabasic.workflowpipline.core.Workflow; import org.zyf.javabasic.workflowpipline.core.WorkflowExecutionContext; import org.zyf.javabasic.workflowpipline.dataprocess.Item; import org.zyf.javabasic.workflowpipline.model.KnowledgeMetadata; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * @program: zyfboot-javabasic * @description: 情绪分生成分析 * @author: zhangyanfeng * @create: 2024-02-15 13:40 **/ @Slf4j @WorkerInfo(name = "moodScoreCreateWorker") @Service public class MoodScoreCreateWorker extends AbstractAIDealWorker implements InitializingBean { @Override protected WorkflowExecutionContext doWork(WorkflowExecutionContext context) { //抽取item List<Item> typedItems = context.getResult().getItems(); if (CollectionUtils.isEmpty(typedItems)) { return context; } //模拟:通过请求算法服务,根据当前标题和文本给出对应的关键词和实体词信息 for (Item item : typedItems) { KnowledgeMetadata data = Item.getData(item.getData(), KnowledgeMetadata.class); if (Objects.isNull(data)) { log.warn("AIWordCreateWorker Item data is null! item={}", item); continue; } String content = data.getContent(); if (StringUtils.isBlank(content)) { continue; } //模拟:根据标题成对应的情绪分 data.setMoodScore(getSentimentScore(content)); item.setData(data); } context.getResult().setItems(typedItems); return context; } private double getSentimentScore(String text) { if (text == null || text.isEmpty()) { return 0.0; // 文本为空时情绪分为0 } final List<String> POSITIVE_WORDS = Arrays.asList( "好", "出色", "快乐", "幸福", "赞", "发现", "可能存在生命" ); final List<String> NEGATIVE_WORDS = Arrays.asList( "坏", "糟糕", "悲伤", "愤怒", "批评", "冲击", "不稳定", "下调", "影响", "衰退", "下降", "担忧" ); double score = 0.0; // 对于文本中的每个正面词,增加分数 for (String word : POSITIVE_WORDS) { if (text.contains(word)) { score += 1.0; } } // 对于文本中的每个负面词,减少分数 for (String word : NEGATIVE_WORDS) { if (text.contains(word)) { score -= 1.0; } } return score; } @Override public void afterPropertiesSet() throws Exception { Workflow.registerWorker(getName(), this); } }
ZYFCodes/zyfboot-javabasic
src/main/java/org/zyf/javabasic/workflowpipline/worker/aideal/MoodScoreCreateWorker.java
831
//模拟:根据标题成对应的情绪分
line_comment
zh-cn
package org.zyf.javabasic.workflowpipline.worker.aideal; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Service; import org.zyf.javabasic.workflowpipline.annotations.WorkerInfo; import org.zyf.javabasic.workflowpipline.core.Workflow; import org.zyf.javabasic.workflowpipline.core.WorkflowExecutionContext; import org.zyf.javabasic.workflowpipline.dataprocess.Item; import org.zyf.javabasic.workflowpipline.model.KnowledgeMetadata; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * @program: zyfboot-javabasic * @description: 情绪分生成分析 * @author: zhangyanfeng * @create: 2024-02-15 13:40 **/ @Slf4j @WorkerInfo(name = "moodScoreCreateWorker") @Service public class MoodScoreCreateWorker extends AbstractAIDealWorker implements InitializingBean { @Override protected WorkflowExecutionContext doWork(WorkflowExecutionContext context) { //抽取item List<Item> typedItems = context.getResult().getItems(); if (CollectionUtils.isEmpty(typedItems)) { return context; } //模拟:通过请求算法服务,根据当前标题和文本给出对应的关键词和实体词信息 for (Item item : typedItems) { KnowledgeMetadata data = Item.getData(item.getData(), KnowledgeMetadata.class); if (Objects.isNull(data)) { log.warn("AIWordCreateWorker Item data is null! item={}", item); continue; } String content = data.getContent(); if (StringUtils.isBlank(content)) { continue; } //模拟 <SUF> data.setMoodScore(getSentimentScore(content)); item.setData(data); } context.getResult().setItems(typedItems); return context; } private double getSentimentScore(String text) { if (text == null || text.isEmpty()) { return 0.0; // 文本为空时情绪分为0 } final List<String> POSITIVE_WORDS = Arrays.asList( "好", "出色", "快乐", "幸福", "赞", "发现", "可能存在生命" ); final List<String> NEGATIVE_WORDS = Arrays.asList( "坏", "糟糕", "悲伤", "愤怒", "批评", "冲击", "不稳定", "下调", "影响", "衰退", "下降", "担忧" ); double score = 0.0; // 对于文本中的每个正面词,增加分数 for (String word : POSITIVE_WORDS) { if (text.contains(word)) { score += 1.0; } } // 对于文本中的每个负面词,减少分数 for (String word : NEGATIVE_WORDS) { if (text.contains(word)) { score -= 1.0; } } return score; } @Override public void afterPropertiesSet() throws Exception { Workflow.registerWorker(getName(), this); } }
false
696
9
830
12
831
9
831
12
1,066
19
false
false
false
false
false
true
13425_1
package org.zz.gmhelper; public class SM2Cipher { /** * ECC密钥 */ private byte[] c1; /** * 真正的密文 */ private byte[] c2; /** * 对(c1+c2)的SM3-HASH值 */ private byte[] c3; /** * SM2标准的密文,即(c1+c2+c3) */ private byte[] cipherText; public byte[] getC1() { return c1; } public void setC1(byte[] c1) { this.c1 = c1; } public byte[] getC2() { return c2; } public void setC2(byte[] c2) { this.c2 = c2; } public byte[] getC3() { return c3; } public void setC3(byte[] c3) { this.c3 = c3; } public byte[] getCipherText() { return cipherText; } public void setCipherText(byte[] cipherText) { this.cipherText = cipherText; } }
ZZMarquis/gmhelper
src/main/java/org/zz/gmhelper/SM2Cipher.java
270
/** * 真正的密文 */
block_comment
zh-cn
package org.zz.gmhelper; public class SM2Cipher { /** * ECC密钥 */ private byte[] c1; /** * 真正的 <SUF>*/ private byte[] c2; /** * 对(c1+c2)的SM3-HASH值 */ private byte[] c3; /** * SM2标准的密文,即(c1+c2+c3) */ private byte[] cipherText; public byte[] getC1() { return c1; } public void setC1(byte[] c1) { this.c1 = c1; } public byte[] getC2() { return c2; } public void setC2(byte[] c2) { this.c2 = c2; } public byte[] getC3() { return c3; } public void setC3(byte[] c3) { this.c3 = c3; } public byte[] getCipherText() { return cipherText; } public void setCipherText(byte[] cipherText) { this.cipherText = cipherText; } }
false
255
13
270
11
306
12
270
11
345
13
false
false
false
false
false
true
16690_3
package com.neu.his.cloud.zuul.controller; import com.neu.his.cloud.zuul.common.CommonResult; import com.neu.his.cloud.zuul.dto.sms.SmsStaffLoginParam; import com.neu.his.cloud.zuul.dto.sms.SmsStaffParam; import com.neu.his.cloud.zuul.model.SmsStaff; import com.neu.his.cloud.zuul.service.sms.SmsStaffService; import com.neu.his.cloud.zuul.service.tms.TestFeignService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.util.HashMap; import java.util.Map; @Controller @Api(tags = "SmsStaffController", description = "用户管理") @RequestMapping("/staff") @CrossOrigin(allowCredentials = "true") public class SmsStaffController { @Autowired private SmsStaffService smsStaffService; @Autowired private TestFeignService testFeignService; @Value("${jwt.tokenHeader}") //自动装载jwt private String tokenHeader; @Value("${jwt.tokenHead}") private String tokenHead; /** * 描述:登录 * <p>author: 赵煜 */ @ApiOperation(value = "登录以后返回token") @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public CommonResult login(@RequestBody SmsStaffLoginParam smsStaffLoginParam, BindingResult result) { String token = smsStaffService.login(smsStaffLoginParam.getUsername(), smsStaffLoginParam.getPassword()); if (token == null) { return CommonResult.validateFailed("用户名或密码错误"); } //如果 token不等于 null Map<String, String> tokenMap = new HashMap<>(); tokenMap.put("token", token); tokenMap.put("tokenHead", tokenHead); return CommonResult.success(tokenMap); //为什么要用HashMap进行返回,难道是为了减少实体类? } @ApiOperation(value = "获取当前登录用户信息") @RequestMapping(value = "/info", method = RequestMethod.GET) @ResponseBody public CommonResult getAdminInfo(Principal principal) { String username = principal.getName(); SmsStaff smsStaff = smsStaffService.selectByUserName(username); Map<String, Object> data = new HashMap<>(); data.put("username", smsStaff.getUsername()); data.put("id", smsStaff.getId()); data.put("name", smsStaff.getName()); data.put("deptId", smsStaff.getDeptId()); data.put("roleId",smsStaff.getRoleId()); return CommonResult.success(data); } /** * 描述:新增一个用户 * <p>author:赵煜 */ @ApiOperation("新增用户(调用注册接口)") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody SmsStaffParam smsStaffParam, BindingResult result){ SmsStaff smsStaff= smsStaffService.register(smsStaffParam); return CommonResult.success(smsStaff); } // // /** // * 描述:登录 // * <p>author: 赵煜 // */ // @ApiOperation(value = "test") // @RequestMapping(value = "/test", method = RequestMethod.GET) // @ResponseBody // @PreAuthorize("hasAuthority('dept:zzz')") // public CommonResult test() { // return CommonResult.success("success"); // } // /** // * 描述:登录 // * <p>author: 赵煜 // */ // @ApiOperation(value = "testHi") // @RequestMapping(value = "/testHi", method = RequestMethod.GET) // @ResponseBody //// @PreAuthorize("hasAuthority('dept:create')") // public CommonResult testHi(@RequestParam("message") String message) { // return CommonResult.success(testFeignService.hiTest(message)); // } }
ZainZhao/HIS
his-cloud/his-cloud-zuul/src/main/java/com/neu/his/cloud/zuul/controller/SmsStaffController.java
1,062
//为什么要用HashMap进行返回,难道是为了减少实体类?
line_comment
zh-cn
package com.neu.his.cloud.zuul.controller; import com.neu.his.cloud.zuul.common.CommonResult; import com.neu.his.cloud.zuul.dto.sms.SmsStaffLoginParam; import com.neu.his.cloud.zuul.dto.sms.SmsStaffParam; import com.neu.his.cloud.zuul.model.SmsStaff; import com.neu.his.cloud.zuul.service.sms.SmsStaffService; import com.neu.his.cloud.zuul.service.tms.TestFeignService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.util.HashMap; import java.util.Map; @Controller @Api(tags = "SmsStaffController", description = "用户管理") @RequestMapping("/staff") @CrossOrigin(allowCredentials = "true") public class SmsStaffController { @Autowired private SmsStaffService smsStaffService; @Autowired private TestFeignService testFeignService; @Value("${jwt.tokenHeader}") //自动装载jwt private String tokenHeader; @Value("${jwt.tokenHead}") private String tokenHead; /** * 描述:登录 * <p>author: 赵煜 */ @ApiOperation(value = "登录以后返回token") @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public CommonResult login(@RequestBody SmsStaffLoginParam smsStaffLoginParam, BindingResult result) { String token = smsStaffService.login(smsStaffLoginParam.getUsername(), smsStaffLoginParam.getPassword()); if (token == null) { return CommonResult.validateFailed("用户名或密码错误"); } //如果 token不等于 null Map<String, String> tokenMap = new HashMap<>(); tokenMap.put("token", token); tokenMap.put("tokenHead", tokenHead); return CommonResult.success(tokenMap); //为什 <SUF> } @ApiOperation(value = "获取当前登录用户信息") @RequestMapping(value = "/info", method = RequestMethod.GET) @ResponseBody public CommonResult getAdminInfo(Principal principal) { String username = principal.getName(); SmsStaff smsStaff = smsStaffService.selectByUserName(username); Map<String, Object> data = new HashMap<>(); data.put("username", smsStaff.getUsername()); data.put("id", smsStaff.getId()); data.put("name", smsStaff.getName()); data.put("deptId", smsStaff.getDeptId()); data.put("roleId",smsStaff.getRoleId()); return CommonResult.success(data); } /** * 描述:新增一个用户 * <p>author:赵煜 */ @ApiOperation("新增用户(调用注册接口)") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody SmsStaffParam smsStaffParam, BindingResult result){ SmsStaff smsStaff= smsStaffService.register(smsStaffParam); return CommonResult.success(smsStaff); } // // /** // * 描述:登录 // * <p>author: 赵煜 // */ // @ApiOperation(value = "test") // @RequestMapping(value = "/test", method = RequestMethod.GET) // @ResponseBody // @PreAuthorize("hasAuthority('dept:zzz')") // public CommonResult test() { // return CommonResult.success("success"); // } // /** // * 描述:登录 // * <p>author: 赵煜 // */ // @ApiOperation(value = "testHi") // @RequestMapping(value = "/testHi", method = RequestMethod.GET) // @ResponseBody //// @PreAuthorize("hasAuthority('dept:create')") // public CommonResult testHi(@RequestParam("message") String message) { // return CommonResult.success(testFeignService.hiTest(message)); // } }
false
890
13
1,061
16
1,053
13
1,062
17
1,309
29
false
false
false
false
false
true
21917_3
package email; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import changecode.Utf8code; public class MailToYou extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private String checkCode=null; private String sendAddress = null; private String sendSubject = null; private String sendContent = null; public MailToYou() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ checkCode=request.getParameter("check"); if(!checkCode.equalsIgnoreCase((String)request.getSession().getAttribute("randomCode"))) { request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else{ sendAddress=Utf8code.changeCode(request.getParameter("useraddress")); sendSubject=Utf8code.changeCode(request.getParameter("sendsubject")); sendContent=Utf8code.changeCode(request.getParameter("sendcontent")); if(sendAddress==null){ request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else if(sendSubject==null){ request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else if(sendContent==null){ request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else{ sendContent="来自:"+sendAddress+"(请管理员回复该邮箱!) 此用户向您咨询:"+sendContent; // 这个类主要是设置邮件 MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.qq.com"); mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); mailInfo.setUserName("[email protected]"); mailInfo.setPassword("15527518572");// 您的邮箱密码 mailInfo.setFromAddress("[email protected]"); mailInfo.setToAddress("[email protected]"); mailInfo.setSubject(sendSubject); mailInfo.setContent(sendContent); // 这个类主要来发送邮件 SimpleMailSender sms = new SimpleMailSender(); //sms.sendTextMail(mailInfo);// 发送文体格式 sms.sendHtmlMail(mailInfo);// 发送html格式 request.getSession().setAttribute("sendsuccess", "success!"); response.sendRedirect("help/help.jsp"); return; } } } catch (Exception e) { // TODO Auto-generated catch block request.getSession().setAttribute("senderror", "error!"); try { response.sendRedirect("help/help.jsp"); return; } catch (IOException e1) { // TODO Auto-generated catch block return; } } } public void doPost(HttpServletRequest request, HttpServletResponse response) { doGet(request, response); } public void init(){ // Put your code here } }
Zaiwen/PMRMP
src/email/MailToYou.java
869
// 您的邮箱密码
line_comment
zh-cn
package email; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import changecode.Utf8code; public class MailToYou extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private String checkCode=null; private String sendAddress = null; private String sendSubject = null; private String sendContent = null; public MailToYou() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ checkCode=request.getParameter("check"); if(!checkCode.equalsIgnoreCase((String)request.getSession().getAttribute("randomCode"))) { request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else{ sendAddress=Utf8code.changeCode(request.getParameter("useraddress")); sendSubject=Utf8code.changeCode(request.getParameter("sendsubject")); sendContent=Utf8code.changeCode(request.getParameter("sendcontent")); if(sendAddress==null){ request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else if(sendSubject==null){ request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else if(sendContent==null){ request.getSession().setAttribute("senderror", "error!"); response.sendRedirect("help/help.jsp"); return; }else{ sendContent="来自:"+sendAddress+"(请管理员回复该邮箱!) 此用户向您咨询:"+sendContent; // 这个类主要是设置邮件 MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.qq.com"); mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); mailInfo.setUserName("[email protected]"); mailInfo.setPassword("15527518572");// 您的 <SUF> mailInfo.setFromAddress("[email protected]"); mailInfo.setToAddress("[email protected]"); mailInfo.setSubject(sendSubject); mailInfo.setContent(sendContent); // 这个类主要来发送邮件 SimpleMailSender sms = new SimpleMailSender(); //sms.sendTextMail(mailInfo);// 发送文体格式 sms.sendHtmlMail(mailInfo);// 发送html格式 request.getSession().setAttribute("sendsuccess", "success!"); response.sendRedirect("help/help.jsp"); return; } } } catch (Exception e) { // TODO Auto-generated catch block request.getSession().setAttribute("senderror", "error!"); try { response.sendRedirect("help/help.jsp"); return; } catch (IOException e1) { // TODO Auto-generated catch block return; } } } public void doPost(HttpServletRequest request, HttpServletResponse response) { doGet(request, response); } public void init(){ // Put your code here } }
false
717
7
866
7
862
6
866
7
1,059
15
false
false
false
false
false
true
39098_1
package com.shcm.utils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SystemConstants { // public static final String IMAGE_UPLOAD_DIR = "D:\\workspace\\IDEA\\nginx-1.18.0\\html\\shcm\\imgs"; //图片上传地址,这里选择采用动态读取配置文件,因为本地的地址和服务器地址不一样 public static String IMAGE_UPLOAD_DIR; public static final String USER_NICK_NAME_PREFIX = "user_"; //todo 這裏應該做成滾動刷新 public static final int DEFAULT_PAGE_SIZE = 999; //todo 這裏應該做成滾動刷新 //主頁博客查詢時的最大數量 public static final int MAX_PAGE_SIZE = 999; @Value("${IMAGE_UPLOAD_DIR}") public void SystemConstants(String IMAGE_UPLOAD_DIR) { this.IMAGE_UPLOAD_DIR = IMAGE_UPLOAD_DIR; } }
ZangYT-im/shcm-platform
src/main/java/com/shcm/utils/SystemConstants.java
254
//图片上传地址,这里选择采用动态读取配置文件,因为本地的地址和服务器地址不一样
line_comment
zh-cn
package com.shcm.utils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SystemConstants { // public static final String IMAGE_UPLOAD_DIR = "D:\\workspace\\IDEA\\nginx-1.18.0\\html\\shcm\\imgs"; //图片 <SUF> public static String IMAGE_UPLOAD_DIR; public static final String USER_NICK_NAME_PREFIX = "user_"; //todo 這裏應該做成滾動刷新 public static final int DEFAULT_PAGE_SIZE = 999; //todo 這裏應該做成滾動刷新 //主頁博客查詢時的最大數量 public static final int MAX_PAGE_SIZE = 999; @Value("${IMAGE_UPLOAD_DIR}") public void SystemConstants(String IMAGE_UPLOAD_DIR) { this.IMAGE_UPLOAD_DIR = IMAGE_UPLOAD_DIR; } }
false
203
22
254
21
244
20
254
21
355
45
false
false
false
false
false
true
15689_1
package com.imooc.demo.demo; public class ResultCode { /** * 成功 */ public static final int SUCCESS = 0; /** * 失败 */ public static final int FAIL = -1; /** * 无权限 */ public static final int NO_AUTH = -2; }
ZbLeaning/MyWheel
ResultCode.java
78
/** * 失败 */
block_comment
zh-cn
package com.imooc.demo.demo; public class ResultCode { /** * 成功 */ public static final int SUCCESS = 0; /** * 失败 <SUF>*/ public static final int FAIL = -1; /** * 无权限 */ public static final int NO_AUTH = -2; }
false
74
9
77
7
86
9
77
7
99
10
false
false
false
false
false
true
57197_3
package cn.zealon.notes.service; import cn.zealon.notes.common.result.Result; import cn.zealon.notes.common.result.ResultUtil; import cn.zealon.notes.repository.CategoryRepository; import cn.zealon.notes.repository.NotesRepository; import cn.zealon.notes.repository.TagRepository; import cn.zealon.notes.security.jwt.JwtAuthService; import cn.zealon.notes.vo.DashboardVO; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; /** * 仪表盘 * @author: zealon * @since: 2021/1/7 */ @Service public class DashboardService { @Autowired private JwtAuthService jwtAuthService; @Autowired private CategoryRepository categoryRepository; @Autowired private NotesRepository notesRepository; @Autowired private TagRepository tagRepository; /** * 获取仪表盘数据 * @return */ public Result getDashboardSummary(){ DashboardVO vo = new DashboardVO(); String userId = jwtAuthService.getLoginUserBean().getUsername(); vo.setCategoryCount(categoryRepository.findCountByUserId(userId)); vo.setNotesCount(notesRepository.findCountByUserId(userId)); vo.setClassicQuotations(this.getClassicQuotations()); vo.setTagCount(tagRepository.findCountByUserId(userId)); this.getWelcome(vo); return ResultUtil.success(vo); } /** * 经典语录 */ private List<String> getClassicQuotations(){ String[] arr = "态度决定一切,仰望星空,脚踏实地,道路艰难,唯勇者行,聪明是一种天赋,而善良是一种选择,最重要的是把要事当做要事,陷入爱河,人人都会变成诗人,青春不是年华,而是心境,生活并不公平,接受它吧,我是一个与众不同的存在,人不是为失败而生,爱所有人,信部分人,不伤害任何人,有信仰,有热情的人生值得一过" .split(","); return Arrays.asList(arr); } /** 欢迎语 */ private String getWelcome(DashboardVO vo){ int hour = DateTime.now().getHourOfDay(); String greet = ""; String welcome = ",深夜了要抓紧休息啦"; if(hour > 5 && hour < 10){ greet = "早安,"; welcome = ",今天也要元气满满哦"; } else if (hour >= 10 && hour < 14){ greet = "中午好,"; welcome = ",祝你开心每一天"; } else if (hour >= 14 && hour < 18){ greet = "下午好,"; welcome = ",晚上要吃顿好的呀"; } else if (hour >= 18 && hour < 22){ greet = "晚上好,"; welcome = ",今天也要早早休息哦"; } vo.setGreet(greet); vo.setWelcome(welcome); return welcome; } }
Zealon159/easy-notes
src/main/java/cn/zealon/notes/service/DashboardService.java
824
/** 欢迎语 */
block_comment
zh-cn
package cn.zealon.notes.service; import cn.zealon.notes.common.result.Result; import cn.zealon.notes.common.result.ResultUtil; import cn.zealon.notes.repository.CategoryRepository; import cn.zealon.notes.repository.NotesRepository; import cn.zealon.notes.repository.TagRepository; import cn.zealon.notes.security.jwt.JwtAuthService; import cn.zealon.notes.vo.DashboardVO; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; /** * 仪表盘 * @author: zealon * @since: 2021/1/7 */ @Service public class DashboardService { @Autowired private JwtAuthService jwtAuthService; @Autowired private CategoryRepository categoryRepository; @Autowired private NotesRepository notesRepository; @Autowired private TagRepository tagRepository; /** * 获取仪表盘数据 * @return */ public Result getDashboardSummary(){ DashboardVO vo = new DashboardVO(); String userId = jwtAuthService.getLoginUserBean().getUsername(); vo.setCategoryCount(categoryRepository.findCountByUserId(userId)); vo.setNotesCount(notesRepository.findCountByUserId(userId)); vo.setClassicQuotations(this.getClassicQuotations()); vo.setTagCount(tagRepository.findCountByUserId(userId)); this.getWelcome(vo); return ResultUtil.success(vo); } /** * 经典语录 */ private List<String> getClassicQuotations(){ String[] arr = "态度决定一切,仰望星空,脚踏实地,道路艰难,唯勇者行,聪明是一种天赋,而善良是一种选择,最重要的是把要事当做要事,陷入爱河,人人都会变成诗人,青春不是年华,而是心境,生活并不公平,接受它吧,我是一个与众不同的存在,人不是为失败而生,爱所有人,信部分人,不伤害任何人,有信仰,有热情的人生值得一过" .split(","); return Arrays.asList(arr); } /** 欢迎语 <SUF>*/ private String getWelcome(DashboardVO vo){ int hour = DateTime.now().getHourOfDay(); String greet = ""; String welcome = ",深夜了要抓紧休息啦"; if(hour > 5 && hour < 10){ greet = "早安,"; welcome = ",今天也要元气满满哦"; } else if (hour >= 10 && hour < 14){ greet = "中午好,"; welcome = ",祝你开心每一天"; } else if (hour >= 14 && hour < 18){ greet = "下午好,"; welcome = ",晚上要吃顿好的呀"; } else if (hour >= 18 && hour < 22){ greet = "晚上好,"; welcome = ",今天也要早早休息哦"; } vo.setGreet(greet); vo.setWelcome(welcome); return welcome; } }
false
658
7
824
7
782
5
824
7
1,050
10
false
false
false
false
false
true
56956_1
10 https://raw.githubusercontent.com/hzc869046779/JAVA-STUDY/master/src/javaStudy/enumStudy/enumStudy.java package javaStudy.enumStudy; public class enumStudy { public static void main(String args[]){ for(Color c:Color.values()){ System.out.println(""+c.ordinal()+"-"+c.name()+"-"+c.toString()); } // 枚举类继承接口 IMessage msg = Color.RED; System.out.println(msg.getMessage()); } } interface IMessage{ public String getMessage(); } enum Color implements IMessage{ //枚举类 RED("红色"), GREEN("绿色"), BLUE("蓝色");//枚举对象第一行 private String title; private Color(String title){ this.title = title; } public String toString(){ return this.title; } public String getMessage(){ return this.title; } }
Zehrex/DD2476-Project
Crawler/data/enumStudy.java
238
// 枚举类继承接口
line_comment
zh-cn
10 https://raw.githubusercontent.com/hzc869046779/JAVA-STUDY/master/src/javaStudy/enumStudy/enumStudy.java package javaStudy.enumStudy; public class enumStudy { public static void main(String args[]){ for(Color c:Color.values()){ System.out.println(""+c.ordinal()+"-"+c.name()+"-"+c.toString()); } // 枚举 <SUF> IMessage msg = Color.RED; System.out.println(msg.getMessage()); } } interface IMessage{ public String getMessage(); } enum Color implements IMessage{ //枚举类 RED("红色"), GREEN("绿色"), BLUE("蓝色");//枚举对象第一行 private String title; private Color(String title){ this.title = title; } public String toString(){ return this.title; } public String getMessage(){ return this.title; } }
false
191
7
238
7
242
6
238
7
314
17
false
false
false
false
false
true
21431_4
package com.zcs.app.monkeyalmanac.utils; public class Constants { /** 星期 */ public static final String[] WEEKS = { "日", "一", "二", "三", "四", "五", "六" }; /** 方向 */ public static final String[] DIRECTIONS = { "北方", "东北方", "东方", "东南方", "南方", "西南方", "西方", "西北方" }; /** 变量名称 */ public static final String[] VAR_NAMES = { "jieguo", "huodong", "pay", "expire", "zhangdan", "every", "free", "i1", "a", "virtual", "ad", "spider", "mima", "pass", "ui" }; /** 工具 */ public static final String[] TOOLS = { "Eclipse写程序", "MSOffice写文档", "记事本写程序", "Windows8", "Linux", "MacOS", "IE", "Android设备", "iOS设备" }; /** 饮料 */ public static final String[] DRINKS = { "水", "茶", "红茶", "绿茶", "咖啡", "奶茶", "可乐", "鲜奶", "豆奶", "果汁", "果味汽水", "苏打水", "运动饮料", "酸奶", "酒" }; }
ZengCS/MonkeyAlmanac
src/com/zcs/app/monkeyalmanac/utils/Constants.java
356
/** 饮料 */
block_comment
zh-cn
package com.zcs.app.monkeyalmanac.utils; public class Constants { /** 星期 */ public static final String[] WEEKS = { "日", "一", "二", "三", "四", "五", "六" }; /** 方向 */ public static final String[] DIRECTIONS = { "北方", "东北方", "东方", "东南方", "南方", "西南方", "西方", "西北方" }; /** 变量名称 */ public static final String[] VAR_NAMES = { "jieguo", "huodong", "pay", "expire", "zhangdan", "every", "free", "i1", "a", "virtual", "ad", "spider", "mima", "pass", "ui" }; /** 工具 */ public static final String[] TOOLS = { "Eclipse写程序", "MSOffice写文档", "记事本写程序", "Windows8", "Linux", "MacOS", "IE", "Android设备", "iOS设备" }; /** 饮料 <SUF>*/ public static final String[] DRINKS = { "水", "茶", "红茶", "绿茶", "咖啡", "奶茶", "可乐", "鲜奶", "豆奶", "果汁", "果味汽水", "苏打水", "运动饮料", "酸奶", "酒" }; }
false
300
6
356
6
310
4
356
6
404
7
false
false
false
false
false
true
38705_0
package pattern.strategy; import pattern.strategy.travel.TravelType; /**策略模式 * 策略模式 〈测试〉 * 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。 * @author gw.Zeng * @create 2018/6/20 * @since 1.0.0 */ public class TravelTrafficTest { public static void main(String[] args) { TravelTraffic travel = new TravelTraffic("262201199812042344","机票xxxxxx"); //出行,选择飞机、火车、客车、滴滴快车、滴滴顺风车 //这个值是在出行的时候才决定用哪个值 TravelState res = travel.travel(TravelType.TRAIN_TRAVEL); System.out.println(res); } }
ZengGwei/DesignPattern
strategy/TravelTrafficTest.java
238
/**策略模式 * 策略模式 〈测试〉 * 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。 * @author gw.Zeng * @create 2018/6/20 * @since 1.0.0 */
block_comment
zh-cn
package pattern.strategy; import pattern.strategy.travel.TravelType; /**策略模 <SUF>*/ public class TravelTrafficTest { public static void main(String[] args) { TravelTraffic travel = new TravelTraffic("262201199812042344","机票xxxxxx"); //出行,选择飞机、火车、客车、滴滴快车、滴滴顺风车 //这个值是在出行的时候才决定用哪个值 TravelState res = travel.travel(TravelType.TRAIN_TRAVEL); System.out.println(res); } }
false
200
83
238
88
217
79
238
88
342
137
false
false
false
false
false
true
61323_9
package com.lab.silent.algorithm.solution; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class 字节一面 { /** * 技能点skill[] 表示每个同学的技能点数,偶数同学,两个同学组一队, * 1.每队的技能点数之和相等 * 2.每队的技能点数乘积之和为多少,如果条件2不满足,则返回-1 * @param nums * @param * @return */ public static int allMatch(int[] nums){ //申明匹配列 LinkedList<Integer> path = new LinkedList<>(); //申明最终返回结果 List<List<Integer>> res = new ArrayList<>(); //记录选择过程中是否选择 boolean[] used = new boolean[nums.length]; //初始团队技能点 int tmpSum = nums[0]+nums[1]; //回溯获取组合结果 backTrack(nums,used,path,res,tmpSum); if(res.size()==0){ return -1; } if(res.size() != nums.length/2){ return -1; } return res.stream().map(t->{ System.out.println(JSONObject.toJSONString(t)); return t.get(0)*t.get(1);}).reduce(Integer::sum).get(); } public static void backTrack(int[] nums,boolean[] used,LinkedList<Integer> path,List<List<Integer>> res,int tmpSum){ //记录满足条件的解 if(path.size() == 2 && path.get(0)+path.get(1) == tmpSum){ res.add(new ArrayList<>(path)); return; } //遍历所有的组合方式 for (int i = 0; i < nums.length; i++) { //剪枝: 如果组合中包含重复数据则跳过 if(used[i]){continue;} //记录不重复的数字路径 path.add(nums[i]); used[i] = true; //重新累计下一次技能点之和 if(res.size()>0){ tmpSum = res.get(0).get(0) + res.get(0).get(1); } //进入下一次递归 backTrack(nums,used,path,res,tmpSum); //回溯上次的选择 path.removeLast(); used[i] = false; } } public static void main(String[] args) { int[] skill = {3,2,5,1,3,4}; int tmp = allMatch(skill); System.out.println(tmp); } }
ZengLiQAQ/silentTestLab
src/main/java/com/lab/silent/algorithm/solution/字节一面.java
652
//记录不重复的数字路径
line_comment
zh-cn
package com.lab.silent.algorithm.solution; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class 字节一面 { /** * 技能点skill[] 表示每个同学的技能点数,偶数同学,两个同学组一队, * 1.每队的技能点数之和相等 * 2.每队的技能点数乘积之和为多少,如果条件2不满足,则返回-1 * @param nums * @param * @return */ public static int allMatch(int[] nums){ //申明匹配列 LinkedList<Integer> path = new LinkedList<>(); //申明最终返回结果 List<List<Integer>> res = new ArrayList<>(); //记录选择过程中是否选择 boolean[] used = new boolean[nums.length]; //初始团队技能点 int tmpSum = nums[0]+nums[1]; //回溯获取组合结果 backTrack(nums,used,path,res,tmpSum); if(res.size()==0){ return -1; } if(res.size() != nums.length/2){ return -1; } return res.stream().map(t->{ System.out.println(JSONObject.toJSONString(t)); return t.get(0)*t.get(1);}).reduce(Integer::sum).get(); } public static void backTrack(int[] nums,boolean[] used,LinkedList<Integer> path,List<List<Integer>> res,int tmpSum){ //记录满足条件的解 if(path.size() == 2 && path.get(0)+path.get(1) == tmpSum){ res.add(new ArrayList<>(path)); return; } //遍历所有的组合方式 for (int i = 0; i < nums.length; i++) { //剪枝: 如果组合中包含重复数据则跳过 if(used[i]){continue;} //记录 <SUF> path.add(nums[i]); used[i] = true; //重新累计下一次技能点之和 if(res.size()>0){ tmpSum = res.get(0).get(0) + res.get(0).get(1); } //进入下一次递归 backTrack(nums,used,path,res,tmpSum); //回溯上次的选择 path.removeLast(); used[i] = false; } } public static void main(String[] args) { int[] skill = {3,2,5,1,3,4}; int tmp = allMatch(skill); System.out.println(tmp); } }
false
575
7
652
7
679
7
652
7
840
13
false
false
false
false
false
true
36151_1
package bill.zts.com.bill.utils; import android.Manifest; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.text.TextUtils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import bill.zts.com.bill.R; /** * Created by Administrator on 2016/8/1. */ public class ConstantUtils { public static String[] StudentTag = {"早餐","午餐","晚餐","饮料","零食","日常用品","电影票","学习用品","车费","杂七杂八"}; public static String[] OfficeWorkTag = {"早餐","车费","午餐","下午茶","买菜","晚餐","日常用品","应酬","水电费","杂七杂八"}; public static String[] DailyTag = {"柴","米","油","盐","酱","醋","茶","厨房用品","浴室用品","水电费","车费","买菜","杂七杂八"}; public static String[] LeisureTag = {"电影票","车票","酒店住宿","机票","景点门票","小吃","纪念品","服务费","杂七杂八"}; public static String Token = "fb9af6b34774f96ac9ac30d840c00209"; /** * 获取版本号 * * @return 当前应用的版本号 */ public static String getVersion(Context context) { try { PackageManager manager = context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); return info.versionName; } catch (Exception e) { e.printStackTrace(); return context.getString(R.string.can_not_find_version_name); } } }
ZengTianShengZ/Bill
app/src/main/java/bill/zts/com/bill/utils/ConstantUtils.java
499
/** * 获取版本号 * * @return 当前应用的版本号 */
block_comment
zh-cn
package bill.zts.com.bill.utils; import android.Manifest; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.text.TextUtils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import bill.zts.com.bill.R; /** * Created by Administrator on 2016/8/1. */ public class ConstantUtils { public static String[] StudentTag = {"早餐","午餐","晚餐","饮料","零食","日常用品","电影票","学习用品","车费","杂七杂八"}; public static String[] OfficeWorkTag = {"早餐","车费","午餐","下午茶","买菜","晚餐","日常用品","应酬","水电费","杂七杂八"}; public static String[] DailyTag = {"柴","米","油","盐","酱","醋","茶","厨房用品","浴室用品","水电费","车费","买菜","杂七杂八"}; public static String[] LeisureTag = {"电影票","车票","酒店住宿","机票","景点门票","小吃","纪念品","服务费","杂七杂八"}; public static String Token = "fb9af6b34774f96ac9ac30d840c00209"; /** * 获取版 <SUF>*/ public static String getVersion(Context context) { try { PackageManager manager = context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); return info.versionName; } catch (Exception e) { e.printStackTrace(); return context.getString(R.string.can_not_find_version_name); } } }
false
380
22
499
19
464
23
499
19
640
30
false
false
false
false
false
true
14271_10
package com.zzh.gdut.gduthelper.bean; import java.util.List; /** * 个人信息类 * Created by ZengZeHong on 2016/9/26. */ public class PersonInfo { //学号 private String numberTag; private String number; //民族 private String nationTag; private String nation; //宿舍号 private String dormitoryTag; private String dormitory; //政治面貌 private String polityTag; private String polity; //入学日期 private String dateToSchoolTag; private String dateToSchool; //出生日期 private String dateToBirthTag; private String dateToBirth; //电话号码 private String phoneNumberTag; private String phoneNumber; //电子邮箱 private String emailTag; private String email; //家庭住址 private String addressTag; private String address; //专业方向 private String majorTag; private String major; //毕业中学 private String graduateTag; private String gradurate; //邮政编码 private String postCode; //家庭邮编 private String familyCode; //家庭电话 private String familyPhoneNumber; //父亲名 private String father; //父亲单位 private String fatherWork; //父亲单位邮编 private String fatherWorkCode; //父亲手机 private String fatherPhoneNumber; //母亲 private String mother; //母亲单位 private String motherWork; //母亲单位邮编 private String motherWorkCode; //母亲手机 private String mothePhoneNumber; //联系电话 private String contractPhoneNumber; //籍贯 private String nativePlace; //健康状况 private String heathy; //入党时间 private String timeToPolity; //火车终点站 private String stationEnd; //政治面貌 private List<String> policyList; //家庭所在地 private String familyLocation; public String getPostCode() { return postCode; } public String getFamilyLocation() { return familyLocation; } public void setFamilyLocation(String familyLocation) { this.familyLocation = familyLocation; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getFamilyCode() { return familyCode; } public void setFamilyCode(String familyCode) { this.familyCode = familyCode; } public String getFamilyPhoneNumber() { return familyPhoneNumber; } public void setFamilyPhoneNumber(String familyPhoneNumber) { this.familyPhoneNumber = familyPhoneNumber; } public String getFather() { return father; } public void setFather(String father) { this.father = father; } public String getFatherWork() { return fatherWork; } public void setFatherWork(String fatherWork) { this.fatherWork = fatherWork; } public String getFatherWorkCode() { return fatherWorkCode; } public void setFatherWorkCode(String fatherWorkCode) { this.fatherWorkCode = fatherWorkCode; } public String getFatherPhoneNumber() { return fatherPhoneNumber; } public void setFatherPhoneNumber(String fatherPhoneNumber) { this.fatherPhoneNumber = fatherPhoneNumber; } public String getMother() { return mother; } public void setMother(String mother) { this.mother = mother; } public String getMotherWork() { return motherWork; } public void setMotherWork(String motherWork) { this.motherWork = motherWork; } public String getMotherWorkCode() { return motherWorkCode; } public void setMotherWorkCode(String motherWorkCode) { this.motherWorkCode = motherWorkCode; } public String getMothePhoneNumber() { return mothePhoneNumber; } public void setMothePhoneNumber(String mothePhoneNumber) { this.mothePhoneNumber = mothePhoneNumber; } public String getContractPhoneNumber() { return contractPhoneNumber; } public void setContractPhoneNumber(String contractPhoneNumber) { this.contractPhoneNumber = contractPhoneNumber; } public String getNativePlace() { return nativePlace; } public void setNativePlace(String nativePlace) { this.nativePlace = nativePlace; } public String getHeathy() { return heathy; } public void setHeathy(String heathy) { this.heathy = heathy; } public String getTimeToPolity() { return timeToPolity; } public void setTimeToPolity(String timeToPolity) { this.timeToPolity = timeToPolity; } public String getStationEnd() { return stationEnd; } public void setStationEnd(String stationEnd) { this.stationEnd = stationEnd; } public String getNumberTag() { return numberTag; } public void setNumberTag(String numberTag) { this.numberTag = numberTag; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getNationTag() { return nationTag; } public void setNationTag(String nationTag) { this.nationTag = nationTag; } public String getNation() { return nation; } public void setNation(String nation) { this.nation = nation; } public String getDormitoryTag() { return dormitoryTag; } public void setDormitoryTag(String dormitoryTag) { this.dormitoryTag = dormitoryTag; } public String getDormitory() { return dormitory; } public void setDormitory(String dormitory) { this.dormitory = dormitory; } public String getPolityTag() { return polityTag; } public void setPolityTag(String polityTag) { this.polityTag = polityTag; } public String getPolity() { return polity; } public void setPolity(String polity) { this.polity = polity; } public String getDateToSchoolTag() { return dateToSchoolTag; } public void setDateToSchoolTag(String dateToSchoolTag) { this.dateToSchoolTag = dateToSchoolTag; } public String getDateToSchool() { return dateToSchool; } public void setDateToSchool(String dateToSchool) { this.dateToSchool = dateToSchool; } public String getDateToBirthTag() { return dateToBirthTag; } public void setDateToBirthTag(String dateToBirthTag) { this.dateToBirthTag = dateToBirthTag; } public String getDateToBirth() { return dateToBirth; } public void setDateToBirth(String dateToBirth) { this.dateToBirth = dateToBirth; } public String getPhoneNumberTag() { return phoneNumberTag; } public void setPhoneNumberTag(String phoneNumberTag) { this.phoneNumberTag = phoneNumberTag; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmailTag() { return emailTag; } public void setEmailTag(String emailTag) { this.emailTag = emailTag; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddressTag() { return addressTag; } public void setAddressTag(String addressTag) { this.addressTag = addressTag; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMajorTag() { return majorTag; } public void setMajorTag(String majorTag) { this.majorTag = majorTag; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getGraduateTag() { return graduateTag; } public void setGraduateTag(String graduateTag) { this.graduateTag = graduateTag; } public String getGradurate() { return gradurate; } public void setGradurate(String gradurate) { this.gradurate = gradurate; } public List<String> getPolicyList() { return policyList; } public void setPolicyList(List<String> policyList) { this.policyList = policyList; } }
ZengZeHong/GDUTHelper
app/src/main/java/com/zzh/gdut/gduthelper/bean/PersonInfo.java
2,101
//邮政编码
line_comment
zh-cn
package com.zzh.gdut.gduthelper.bean; import java.util.List; /** * 个人信息类 * Created by ZengZeHong on 2016/9/26. */ public class PersonInfo { //学号 private String numberTag; private String number; //民族 private String nationTag; private String nation; //宿舍号 private String dormitoryTag; private String dormitory; //政治面貌 private String polityTag; private String polity; //入学日期 private String dateToSchoolTag; private String dateToSchool; //出生日期 private String dateToBirthTag; private String dateToBirth; //电话号码 private String phoneNumberTag; private String phoneNumber; //电子邮箱 private String emailTag; private String email; //家庭住址 private String addressTag; private String address; //专业方向 private String majorTag; private String major; //毕业中学 private String graduateTag; private String gradurate; //邮政 <SUF> private String postCode; //家庭邮编 private String familyCode; //家庭电话 private String familyPhoneNumber; //父亲名 private String father; //父亲单位 private String fatherWork; //父亲单位邮编 private String fatherWorkCode; //父亲手机 private String fatherPhoneNumber; //母亲 private String mother; //母亲单位 private String motherWork; //母亲单位邮编 private String motherWorkCode; //母亲手机 private String mothePhoneNumber; //联系电话 private String contractPhoneNumber; //籍贯 private String nativePlace; //健康状况 private String heathy; //入党时间 private String timeToPolity; //火车终点站 private String stationEnd; //政治面貌 private List<String> policyList; //家庭所在地 private String familyLocation; public String getPostCode() { return postCode; } public String getFamilyLocation() { return familyLocation; } public void setFamilyLocation(String familyLocation) { this.familyLocation = familyLocation; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getFamilyCode() { return familyCode; } public void setFamilyCode(String familyCode) { this.familyCode = familyCode; } public String getFamilyPhoneNumber() { return familyPhoneNumber; } public void setFamilyPhoneNumber(String familyPhoneNumber) { this.familyPhoneNumber = familyPhoneNumber; } public String getFather() { return father; } public void setFather(String father) { this.father = father; } public String getFatherWork() { return fatherWork; } public void setFatherWork(String fatherWork) { this.fatherWork = fatherWork; } public String getFatherWorkCode() { return fatherWorkCode; } public void setFatherWorkCode(String fatherWorkCode) { this.fatherWorkCode = fatherWorkCode; } public String getFatherPhoneNumber() { return fatherPhoneNumber; } public void setFatherPhoneNumber(String fatherPhoneNumber) { this.fatherPhoneNumber = fatherPhoneNumber; } public String getMother() { return mother; } public void setMother(String mother) { this.mother = mother; } public String getMotherWork() { return motherWork; } public void setMotherWork(String motherWork) { this.motherWork = motherWork; } public String getMotherWorkCode() { return motherWorkCode; } public void setMotherWorkCode(String motherWorkCode) { this.motherWorkCode = motherWorkCode; } public String getMothePhoneNumber() { return mothePhoneNumber; } public void setMothePhoneNumber(String mothePhoneNumber) { this.mothePhoneNumber = mothePhoneNumber; } public String getContractPhoneNumber() { return contractPhoneNumber; } public void setContractPhoneNumber(String contractPhoneNumber) { this.contractPhoneNumber = contractPhoneNumber; } public String getNativePlace() { return nativePlace; } public void setNativePlace(String nativePlace) { this.nativePlace = nativePlace; } public String getHeathy() { return heathy; } public void setHeathy(String heathy) { this.heathy = heathy; } public String getTimeToPolity() { return timeToPolity; } public void setTimeToPolity(String timeToPolity) { this.timeToPolity = timeToPolity; } public String getStationEnd() { return stationEnd; } public void setStationEnd(String stationEnd) { this.stationEnd = stationEnd; } public String getNumberTag() { return numberTag; } public void setNumberTag(String numberTag) { this.numberTag = numberTag; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getNationTag() { return nationTag; } public void setNationTag(String nationTag) { this.nationTag = nationTag; } public String getNation() { return nation; } public void setNation(String nation) { this.nation = nation; } public String getDormitoryTag() { return dormitoryTag; } public void setDormitoryTag(String dormitoryTag) { this.dormitoryTag = dormitoryTag; } public String getDormitory() { return dormitory; } public void setDormitory(String dormitory) { this.dormitory = dormitory; } public String getPolityTag() { return polityTag; } public void setPolityTag(String polityTag) { this.polityTag = polityTag; } public String getPolity() { return polity; } public void setPolity(String polity) { this.polity = polity; } public String getDateToSchoolTag() { return dateToSchoolTag; } public void setDateToSchoolTag(String dateToSchoolTag) { this.dateToSchoolTag = dateToSchoolTag; } public String getDateToSchool() { return dateToSchool; } public void setDateToSchool(String dateToSchool) { this.dateToSchool = dateToSchool; } public String getDateToBirthTag() { return dateToBirthTag; } public void setDateToBirthTag(String dateToBirthTag) { this.dateToBirthTag = dateToBirthTag; } public String getDateToBirth() { return dateToBirth; } public void setDateToBirth(String dateToBirth) { this.dateToBirth = dateToBirth; } public String getPhoneNumberTag() { return phoneNumberTag; } public void setPhoneNumberTag(String phoneNumberTag) { this.phoneNumberTag = phoneNumberTag; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmailTag() { return emailTag; } public void setEmailTag(String emailTag) { this.emailTag = emailTag; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddressTag() { return addressTag; } public void setAddressTag(String addressTag) { this.addressTag = addressTag; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMajorTag() { return majorTag; } public void setMajorTag(String majorTag) { this.majorTag = majorTag; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getGraduateTag() { return graduateTag; } public void setGraduateTag(String graduateTag) { this.graduateTag = graduateTag; } public String getGradurate() { return gradurate; } public void setGradurate(String gradurate) { this.gradurate = gradurate; } public List<String> getPolicyList() { return policyList; } public void setPolicyList(List<String> policyList) { this.policyList = policyList; } }
false
1,919
3
2,101
4
2,267
4
2,101
4
2,631
7
false
false
false
false
false
true
1645_5
package com.myblog.lucene; import org.apache.lucene.search.suggest.InputIterator; import org.apache.lucene.util.BytesRef; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Created with IntelliJ IDEA. * User: Zephery * Time: 2017/7/26 11:50 * Description: */ public class ProductIterator implements InputIterator { private Iterator<Product> productIterator; private Product currentProduct; ProductIterator(Iterator<Product> productIterator) { this.productIterator = productIterator; } @Override public boolean hasContexts() { return true; } /** * 是否有设置payload信息 */ @Override public boolean hasPayloads() { return true; } public Comparator<BytesRef> getComparator() { return null; } @Override public BytesRef next() { if (productIterator.hasNext()) { currentProduct = productIterator.next(); try { //返回当前Project的name值,把product类的name属性值作为key return new BytesRef(currentProduct.getName().getBytes("UTF8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Couldn't convert to UTF-8", e); } } else { return null; } } /** * 将Product对象序列化存入payload * [这里仅仅是个示例,其实这种做法不可取,一般不会把整个对象存入payload,这样索引体积会很大,浪费硬盘空间] */ @Override public BytesRef payload() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(currentProduct); out.close(); return new BytesRef(bos.toByteArray()); } catch (IOException e) { throw new RuntimeException("Well that's unfortunate."); } } /** * 把产品的销售区域存入context,context里可以是任意的自定义数据,一般用于数据过滤 * Set集合里的每一个元素都会被创建一个TermQuery,你只是提供一个Set集合,至于new TermQuery * Lucene底层API去做了,但你必须要了解底层干了些什么 */ @Override public Set<BytesRef> contexts() { try { Set<BytesRef> regions = new HashSet<BytesRef>(); for (String region : currentProduct.getRegions()) { regions.add(new BytesRef(region.getBytes("UTF8"))); } return regions; } catch (UnsupportedEncodingException e) { throw new RuntimeException("Couldn't convert to UTF-8"); } } /** * 返回权重值,这个值会影响排序 * 这里以产品的销售量作为权重值,weight值即最终返回的热词列表里每个热词的权重值 * 怎么设计返回这个权重值,发挥你们的想象力吧 */ public long weight() { return currentProduct.getNumberSold(); } }
Zephery/newblog
src/main/java/com/myblog/lucene/ProductIterator.java
750
/** * 返回权重值,这个值会影响排序 * 这里以产品的销售量作为权重值,weight值即最终返回的热词列表里每个热词的权重值 * 怎么设计返回这个权重值,发挥你们的想象力吧 */
block_comment
zh-cn
package com.myblog.lucene; import org.apache.lucene.search.suggest.InputIterator; import org.apache.lucene.util.BytesRef; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Created with IntelliJ IDEA. * User: Zephery * Time: 2017/7/26 11:50 * Description: */ public class ProductIterator implements InputIterator { private Iterator<Product> productIterator; private Product currentProduct; ProductIterator(Iterator<Product> productIterator) { this.productIterator = productIterator; } @Override public boolean hasContexts() { return true; } /** * 是否有设置payload信息 */ @Override public boolean hasPayloads() { return true; } public Comparator<BytesRef> getComparator() { return null; } @Override public BytesRef next() { if (productIterator.hasNext()) { currentProduct = productIterator.next(); try { //返回当前Project的name值,把product类的name属性值作为key return new BytesRef(currentProduct.getName().getBytes("UTF8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Couldn't convert to UTF-8", e); } } else { return null; } } /** * 将Product对象序列化存入payload * [这里仅仅是个示例,其实这种做法不可取,一般不会把整个对象存入payload,这样索引体积会很大,浪费硬盘空间] */ @Override public BytesRef payload() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(currentProduct); out.close(); return new BytesRef(bos.toByteArray()); } catch (IOException e) { throw new RuntimeException("Well that's unfortunate."); } } /** * 把产品的销售区域存入context,context里可以是任意的自定义数据,一般用于数据过滤 * Set集合里的每一个元素都会被创建一个TermQuery,你只是提供一个Set集合,至于new TermQuery * Lucene底层API去做了,但你必须要了解底层干了些什么 */ @Override public Set<BytesRef> contexts() { try { Set<BytesRef> regions = new HashSet<BytesRef>(); for (String region : currentProduct.getRegions()) { regions.add(new BytesRef(region.getBytes("UTF8"))); } return regions; } catch (UnsupportedEncodingException e) { throw new RuntimeException("Couldn't convert to UTF-8"); } } /** * 返回权 <SUF>*/ public long weight() { return currentProduct.getNumberSold(); } }
false
675
61
750
68
803
64
750
68
1,051
123
false
false
false
false
false
true
58367_5
package com._0myun.minecraft.pixelmonknockout.dao.data; import com._0myun.minecraft.pixelmonknockout.DB; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import lombok.*; import java.sql.SQLException; import java.util.UUID; /** * 玩家数据库 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString @Builder @DatabaseTable(tableName = "PlayerGameData", daoClass = PlayerGameData.class) public class PlayerGameData { @DatabaseField(columnName = "id", dataType = DataType.INTEGER, generatedId = true) int id; /** * 玩家UUID */ @DatabaseField(columnName = "uuid", dataType = DataType.UUID, uniqueCombo = true) UUID uuid; /** * 地图名字 */ @DatabaseField(columnName = "game", dataType = DataType.STRING, uniqueCombo = true) String game; /** * 参加总数 */ @DatabaseField(columnName = "total", dataType = DataType.INTEGER, defaultValue = "0") int total; /** * 冠军 */ @DatabaseField(columnName = "win", dataType = DataType.INTEGER, defaultValue = "0") int first; /** * 亚军 */ @DatabaseField(columnName = "second", dataType = DataType.INTEGER, defaultValue = "0") int second; /** * 季军 */ @DatabaseField(columnName = "third", dataType = DataType.INTEGER, defaultValue = "0") int third; public Games getGames() throws SQLException { return DB.games.queryForGame(getGame()); } }
Zerek-Cheng/Zerek-Develop-Projects-For-Work
PixelmonKnockOut/src/main/java/com/_0myun/minecraft/pixelmonknockout/dao/data/PlayerGameData.java
425
/** * 亚军 */
block_comment
zh-cn
package com._0myun.minecraft.pixelmonknockout.dao.data; import com._0myun.minecraft.pixelmonknockout.DB; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import lombok.*; import java.sql.SQLException; import java.util.UUID; /** * 玩家数据库 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString @Builder @DatabaseTable(tableName = "PlayerGameData", daoClass = PlayerGameData.class) public class PlayerGameData { @DatabaseField(columnName = "id", dataType = DataType.INTEGER, generatedId = true) int id; /** * 玩家UUID */ @DatabaseField(columnName = "uuid", dataType = DataType.UUID, uniqueCombo = true) UUID uuid; /** * 地图名字 */ @DatabaseField(columnName = "game", dataType = DataType.STRING, uniqueCombo = true) String game; /** * 参加总数 */ @DatabaseField(columnName = "total", dataType = DataType.INTEGER, defaultValue = "0") int total; /** * 冠军 */ @DatabaseField(columnName = "win", dataType = DataType.INTEGER, defaultValue = "0") int first; /** * 亚军 <SUF>*/ @DatabaseField(columnName = "second", dataType = DataType.INTEGER, defaultValue = "0") int second; /** * 季军 */ @DatabaseField(columnName = "third", dataType = DataType.INTEGER, defaultValue = "0") int third; public Games getGames() throws SQLException { return DB.games.queryForGame(getGame()); } }
false
372
8
425
8
441
9
425
8
539
12
false
false
false
false
false
true
34689_3
/* * 版权所有(C)Niconico Craft 保留所有权利 * 您不得在未经作者许可的情况下,擅自发布本软件的任何部分或全部内容 * 否则将会追究二次发布者的法律责任 */ package cn.phpmc.manager; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; /** * * @author jiang */ public class AES { public static String Decrypt(String sSrc, String sKey) throws Exception { try { //判断Key是否正确 if (sKey == null) { System.out.print("Key为null"); return null; } //判断Key是否为16位 if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] encrypted1 = hex2byte(sSrc); try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } catch (BadPaddingException | IllegalBlockSizeException e) { System.out.println(e.toString()); return null; } } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException ex) { System.out.println(ex.toString()); return null; } } public static String Encrypt(String sSrc, String sKey) throws Exception { if (sKey == null) { System.out.print("Key为null"); return null; } if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes()); return byte2hex(encrypted).toLowerCase(); } public static byte[] hex2byte(String strhex) { if (strhex == null) { return null; } int l = strhex.length(); if (l % 2 == 1) { return null; } byte[] b = new byte[l / 2]; for (int i = 0; i != l / 2; i++) { b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16); } return b; } public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) { hs = hs + "0" + stmp; } else { hs = hs + stmp; } } return hs.toUpperCase(); } }
ZeroDream-CN/PHPMC7-Daemon
src/cn/phpmc/manager/AES.java
838
//判断Key是否为16位
line_comment
zh-cn
/* * 版权所有(C)Niconico Craft 保留所有权利 * 您不得在未经作者许可的情况下,擅自发布本软件的任何部分或全部内容 * 否则将会追究二次发布者的法律责任 */ package cn.phpmc.manager; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; /** * * @author jiang */ public class AES { public static String Decrypt(String sSrc, String sKey) throws Exception { try { //判断Key是否正确 if (sKey == null) { System.out.print("Key为null"); return null; } //判断 <SUF> if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] encrypted1 = hex2byte(sSrc); try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } catch (BadPaddingException | IllegalBlockSizeException e) { System.out.println(e.toString()); return null; } } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException ex) { System.out.println(ex.toString()); return null; } } public static String Encrypt(String sSrc, String sKey) throws Exception { if (sKey == null) { System.out.print("Key为null"); return null; } if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes()); return byte2hex(encrypted).toLowerCase(); } public static byte[] hex2byte(String strhex) { if (strhex == null) { return null; } int l = strhex.length(); if (l % 2 == 1) { return null; } byte[] b = new byte[l / 2]; for (int i = 0; i != l / 2; i++) { b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16); } return b; } public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) { hs = hs + "0" + stmp; } else { hs = hs + stmp; } } return hs.toUpperCase(); } }
false
737
8
838
8
902
8
838
8
1,051
10
false
false
false
false
false
true
31376_2
package entity; import java.util.List; /** * 表实体 * @author Administrator * */ public class Table { private String name;//表名称 private String name2;//处理后的表名称 private String comment;//介绍 private String key;// 主键列 private String key2;// 主键列(驼峰) private String key2Upper;// 主键列(驼峰) private String keyType;//主键类型 public String getKey2Upper() { return key2Upper; } public void setKey2Upper(String key2Upper) { this.key2Upper = key2Upper; } public String getKey2() { return key2; } public void setKey2(String key2) { this.key2 = key2; } public String getKeyType() { return keyType; } public void setKeyType(String keyType) { this.keyType = keyType; } public String getKey() { return key; } public String getName2() { return name2; } public void setName2(String name2) { this.name2 = name2; } public void setKey(String key) { this.key = key; } private List<Column> columns;//列集合 public List<Column> getColumns() { return columns; } public void setColumns(List<Column> columns) { this.columns = columns; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
ZeroOrInfinity/codeutil
src/main/java/entity/Table.java
456
//处理后的表名称
line_comment
zh-cn
package entity; import java.util.List; /** * 表实体 * @author Administrator * */ public class Table { private String name;//表名称 private String name2;//处理 <SUF> private String comment;//介绍 private String key;// 主键列 private String key2;// 主键列(驼峰) private String key2Upper;// 主键列(驼峰) private String keyType;//主键类型 public String getKey2Upper() { return key2Upper; } public void setKey2Upper(String key2Upper) { this.key2Upper = key2Upper; } public String getKey2() { return key2; } public void setKey2(String key2) { this.key2 = key2; } public String getKeyType() { return keyType; } public void setKeyType(String keyType) { this.keyType = keyType; } public String getKey() { return key; } public String getName2() { return name2; } public void setName2(String name2) { this.name2 = name2; } public void setKey(String key) { this.key = key; } private List<Column> columns;//列集合 public List<Column> getColumns() { return columns; } public void setColumns(List<Column> columns) { this.columns = columns; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
false
354
5
456
5
455
5
456
5
529
8
false
false
false
false
false
true
18851_4
package domain; /** * 玩家信息和行为 * * 作者:豆芽 Dora * 版权:Dora */ public class Player { //姓名 private String name; //steamId private String steamId; //x坐标 private double xPos; //y坐标 private double yPos; //行为 private String action; //健康 private double health; //伤害 private Double damage; //是否存活 public boolean isDead() { return action.contains("died"); } //具体方位 public String getDetailPosition() { if (xPos > 100 && yPos > 100) { return ""; } return ""; } //整理行为 public String getDetailAction(){ return ""; } }
ZeroWM/LogAnalysisAndDBDataImportSystem
src/main/java/domain/Player.java
194
//是否存活
line_comment
zh-cn
package domain; /** * 玩家信息和行为 * * 作者:豆芽 Dora * 版权:Dora */ public class Player { //姓名 private String name; //steamId private String steamId; //x坐标 private double xPos; //y坐标 private double yPos; //行为 private String action; //健康 private double health; //伤害 private Double damage; //是否 <SUF> public boolean isDead() { return action.contains("died"); } //具体方位 public String getDetailPosition() { if (xPos > 100 && yPos > 100) { return ""; } return ""; } //整理行为 public String getDetailAction(){ return ""; } }
false
184
3
194
4
204
4
194
4
256
5
false
false
false
false
false
true
65564_3
package com.mall.xiaomi.mq; import com.mall.xiaomi.service.OrderService; import com.mall.xiaomi.service.SeckillProductService; import com.mall.xiaomi.util.RedisKey; import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; /** * @Auther: wdd * @Date: 2020-04-24 9:30 * @Description: */ @Component public class SeckillOrderQueue { @Autowired private OrderService orderService; @Autowired private SeckillProductService seckillProductService; @Autowired StringRedisTemplate stringRedisTemplate; @RabbitListener(queues = "seckill_order") public void insertOrder(Map map, Channel channel, Message message){ // 查看id,保证幂等性 String correlationId = message.getMessageProperties().getCorrelationId(); if (!stringRedisTemplate.hasKey(RedisKey.SECKILL_RABBITMQ_ID + correlationId)) { // redis中存在,表明此条消息已消费,请勿重复消费 return; } String seckillId = (String) map.get("seckillId"); String userId = (String) map.get("userId"); // 存入redis,因为只需要判断是否存在,因此value为多少无所谓 stringRedisTemplate.opsForValue().set(RedisKey.SECKILL_RABBITMQ_ID + correlationId, "1"); Long seckillEndTime = seckillProductService.getEndTime(seckillId); stringRedisTemplate.expire(RedisKey.SECKILL_RABBITMQ_ID + correlationId, seckillEndTime - new Date().getTime(), TimeUnit.SECONDS); // 设置过期时间 try { orderService.addSeckillOrder(seckillId, userId); } catch (Exception e) { e.printStackTrace(); try { stringRedisTemplate.delete(RedisKey.SECKILL_RABBITMQ_ID + correlationId); // 将该消息放入队列尾部,尝试再次消费 channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true); } catch (IOException ioException) { ioException.printStackTrace(); } } } }
ZeroWdd/Xiaomi
src/main/java/com/mall/xiaomi/mq/SeckillOrderQueue.java
630
// 存入redis,因为只需要判断是否存在,因此value为多少无所谓
line_comment
zh-cn
package com.mall.xiaomi.mq; import com.mall.xiaomi.service.OrderService; import com.mall.xiaomi.service.SeckillProductService; import com.mall.xiaomi.util.RedisKey; import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; /** * @Auther: wdd * @Date: 2020-04-24 9:30 * @Description: */ @Component public class SeckillOrderQueue { @Autowired private OrderService orderService; @Autowired private SeckillProductService seckillProductService; @Autowired StringRedisTemplate stringRedisTemplate; @RabbitListener(queues = "seckill_order") public void insertOrder(Map map, Channel channel, Message message){ // 查看id,保证幂等性 String correlationId = message.getMessageProperties().getCorrelationId(); if (!stringRedisTemplate.hasKey(RedisKey.SECKILL_RABBITMQ_ID + correlationId)) { // redis中存在,表明此条消息已消费,请勿重复消费 return; } String seckillId = (String) map.get("seckillId"); String userId = (String) map.get("userId"); // 存入 <SUF> stringRedisTemplate.opsForValue().set(RedisKey.SECKILL_RABBITMQ_ID + correlationId, "1"); Long seckillEndTime = seckillProductService.getEndTime(seckillId); stringRedisTemplate.expire(RedisKey.SECKILL_RABBITMQ_ID + correlationId, seckillEndTime - new Date().getTime(), TimeUnit.SECONDS); // 设置过期时间 try { orderService.addSeckillOrder(seckillId, userId); } catch (Exception e) { e.printStackTrace(); try { stringRedisTemplate.delete(RedisKey.SECKILL_RABBITMQ_ID + correlationId); // 将该消息放入队列尾部,尝试再次消费 channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true); } catch (IOException ioException) { ioException.printStackTrace(); } } } }
false
529
16
630
21
621
16
630
21
760
30
false
false
false
false
false
true
38349_0
public class Run { public static void main(String[] args) { //创建必要对象 MainSystem mainSystem = new MainSystem(); System.out.println("系统启动中..."); //日志输出 mainSystem.start(); } }
Zerodotgit/StudentsInfoManageSystem
src/Run.java
55
//创建必要对象
line_comment
zh-cn
public class Run { public static void main(String[] args) { //创建 <SUF> MainSystem mainSystem = new MainSystem(); System.out.println("系统启动中..."); //日志输出 mainSystem.start(); } }
false
53
4
55
4
61
4
55
4
72
7
false
false
false
false
false
true
49382_1
//超级丑数 是一个正整数,并满足其所有质因数都出现在质数数组 primes 中。 // // 给你一个整数 n 和一个整数数组 primes ,返回第 n 个 超级丑数 。 // // 题目数据保证第 n 个 超级丑数 在 32-bit 带符号整数范围内。 // // // // 示例 1: // // //输入:n = 12, primes = [2,7,13,19] //输出:32 //解释:给定长度为 4 的质数数组 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26, //28,32] 。 // // 示例 2: // // //输入:n = 1, primes = [2,3,5] //输出:1 //解释:1 不含质因数,因此它的所有质因数都在质数数组 primes = [2,3,5] 中。 // // // // // // // 提示: // // // 1 <= n <= 106 // 1 <= primes.length <= 100 // 2 <= primes[i] <= 1000 // 题目数据 保证 primes[i] 是一个质数 // primes 中的所有值都 互不相同 ,且按 递增顺序 排列 // // // // // Related Topics 数组 哈希表 数学 动态规划 堆(优先队列) // 👍 233 👎 0 import java.util.HashSet; import java.util.PriorityQueue; import java.util.Set; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int nthSuperUglyNumber(int n, int[] primes) { Set<Long> seen = new HashSet<>(); PriorityQueue<Long> heap = new PriorityQueue<>(); seen.add(1L); heap.offer(1L); int ugly = 0; for (int i = 0; i < n; i++) { long cur = heap.poll(); ugly = (int) cur; for (int prime : primes) { long next = ugly * prime; if (seen.add(next)) { heap.offer(next); } } } return ugly; } /*public int nthSuperUglyNumber(int n, int[] primes) { Set<Long> seen = new HashSet<>(); PriorityQueue<Long> heap = new PriorityQueue<>(); seen.add(1L); heap.offer(1L); int ugly = 0; for (int i = 0; i < n; i++) { long cur = heap.poll(); ugly = (long) cur; for (int prime : primes) { long next = cur * prime; if (seen.add(next)) { heap.offer(next); } } } return ugly; }*/ } //leetcode submit region end(Prohibit modification and deletion)
Zeroisstart4/myLeetCode
leetcode/editor/cn/[313]超级丑数.java
798
// 给你一个整数 n 和一个整数数组 primes ,返回第 n 个 超级丑数 。
line_comment
zh-cn
//超级丑数 是一个正整数,并满足其所有质因数都出现在质数数组 primes 中。 // // 给你 <SUF> // // 题目数据保证第 n 个 超级丑数 在 32-bit 带符号整数范围内。 // // // // 示例 1: // // //输入:n = 12, primes = [2,7,13,19] //输出:32 //解释:给定长度为 4 的质数数组 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26, //28,32] 。 // // 示例 2: // // //输入:n = 1, primes = [2,3,5] //输出:1 //解释:1 不含质因数,因此它的所有质因数都在质数数组 primes = [2,3,5] 中。 // // // // // // // 提示: // // // 1 <= n <= 106 // 1 <= primes.length <= 100 // 2 <= primes[i] <= 1000 // 题目数据 保证 primes[i] 是一个质数 // primes 中的所有值都 互不相同 ,且按 递增顺序 排列 // // // // // Related Topics 数组 哈希表 数学 动态规划 堆(优先队列) // 👍 233 👎 0 import java.util.HashSet; import java.util.PriorityQueue; import java.util.Set; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int nthSuperUglyNumber(int n, int[] primes) { Set<Long> seen = new HashSet<>(); PriorityQueue<Long> heap = new PriorityQueue<>(); seen.add(1L); heap.offer(1L); int ugly = 0; for (int i = 0; i < n; i++) { long cur = heap.poll(); ugly = (int) cur; for (int prime : primes) { long next = ugly * prime; if (seen.add(next)) { heap.offer(next); } } } return ugly; } /*public int nthSuperUglyNumber(int n, int[] primes) { Set<Long> seen = new HashSet<>(); PriorityQueue<Long> heap = new PriorityQueue<>(); seen.add(1L); heap.offer(1L); int ugly = 0; for (int i = 0; i < n; i++) { long cur = heap.poll(); ugly = (long) cur; for (int prime : primes) { long next = cur * prime; if (seen.add(next)) { heap.offer(next); } } } return ugly; }*/ } //leetcode submit region end(Prohibit modification and deletion)
false
706
28
798
26
789
22
798
26
1,021
43
false
false
false
false
false
true
27082_4
/* 841. 钥匙和房间 https://leetcode-cn.com/problems/keys-and-rooms/ 有 N 个房间,开始时你位于 0 号房间。 每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。 在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。 最初,除 0 号房间外的其余所有房间都被锁住。 你可以自由地在房间之间来回走动。 如果能进入每个房间返回 true,否则返回 false。 执行用时:3 ms, 在所有 Java 提交中击败了39.43%的用户 内存消耗:39.7 MB, 在所有 Java 提交中击败了65.12%的用户 */ class Solution { public boolean canVisitAllRooms(List<List<Integer>> rooms) { int n = rooms.size(); Set<Integer> set = new HashSet<>(); set.add(0); Queue<Integer> queue = new LinkedList<>(); queue.offer(0); while (!queue.isEmpty()) { List<Integer> keys = rooms.get(queue.poll()); int visit = 0; for (Integer i : keys) { if (set.contains(i)) visit++; else { set.add(i); queue.offer(i); } } } return set.size() == n; } } class Solution2 { boolean[] vis; int num; public boolean canVisitAllRooms(List<List<Integer>> rooms) { int n = rooms.size(); num = 0; vis = new boolean[n]; dfs(rooms, 0); return num == n; } public void dfs(List<List<Integer>> rooms, int x) { vis[x] = true; num++; for (int it : rooms.get(x)) { if (!vis[it]) { dfs(rooms, it); } } } } // 作者:LeetCode-Solution // 链接:https://leetcode-cn.com/problems/keys-and-rooms/solution/yao-chi-he-fang-jian-by-leetcode-solution/ // 来源:力扣(LeetCode) // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Zesunlight/Online-Judge
LeetCode/841_钥匙和房间.java
651
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
line_comment
zh-cn
/* 841. 钥匙和房间 https://leetcode-cn.com/problems/keys-and-rooms/ 有 N 个房间,开始时你位于 0 号房间。 每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。 在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。 最初,除 0 号房间外的其余所有房间都被锁住。 你可以自由地在房间之间来回走动。 如果能进入每个房间返回 true,否则返回 false。 执行用时:3 ms, 在所有 Java 提交中击败了39.43%的用户 内存消耗:39.7 MB, 在所有 Java 提交中击败了65.12%的用户 */ class Solution { public boolean canVisitAllRooms(List<List<Integer>> rooms) { int n = rooms.size(); Set<Integer> set = new HashSet<>(); set.add(0); Queue<Integer> queue = new LinkedList<>(); queue.offer(0); while (!queue.isEmpty()) { List<Integer> keys = rooms.get(queue.poll()); int visit = 0; for (Integer i : keys) { if (set.contains(i)) visit++; else { set.add(i); queue.offer(i); } } } return set.size() == n; } } class Solution2 { boolean[] vis; int num; public boolean canVisitAllRooms(List<List<Integer>> rooms) { int n = rooms.size(); num = 0; vis = new boolean[n]; dfs(rooms, 0); return num == n; } public void dfs(List<List<Integer>> rooms, int x) { vis[x] = true; num++; for (int it : rooms.get(x)) { if (!vis[it]) { dfs(rooms, it); } } } } // 作者:LeetCode-Solution // 链接:https://leetcode-cn.com/problems/keys-and-rooms/solution/yao-chi-he-fang-jian-by-leetcode-solution/ // 来源:力扣(LeetCode) // 著作 <SUF>
false
571
21
651
30
646
23
651
30
835
46
false
false
false
false
false
true
25545_21
package com.example.demo.leetcode.ii; import java.util.ArrayDeque; import java.util.Arrays; import java.util.List; /** * Description: 2866. 美丽塔 II * 给你一个长度为 n 下标从 0 开始的整数数组 maxHeights 。 * * 你的任务是在坐标轴上建 n 座塔。第 i 座塔的下标为 i ,高度为 heights[i] 。 * 如果以下条件满足,我们称这些塔是 美丽 的: * 1 <= heights[i] <= maxHeights[i] * heights 是一个 山脉 数组。 * * 如果存在下标 i 满足以下条件,那么我们称数组 heights 是一个 山脉 数组: * 对于所有 0 < j <= i ,都有 heights[j - 1] <= heights[j] * 对于所有 i <= k < n - 1 ,都有 heights[k + 1] <= heights[k] * * 请你返回满足 美丽塔 要求的方案中,高度和的最大值 。 * * @author Zeti * @date 2023/12/21 10:08 */ public class MaximumSumOfHeights { public static void main(String[] args) { List<Integer> m1 = Arrays.asList(5,3,4,1,1); System.err.println(maximumSumOfHeights(m1)); // res=13; 和最大的美丽塔方案为 heights = [5,3,3,1,1] List<Integer> m2 = Arrays.asList(6,5,3,9,2,7); System.err.println(maximumSumOfHeights(m2)); // res=22; 和最大的美丽塔方案为 heights = [3,3,3,9,2,2] List<Integer> m3 = Arrays.asList(3,2,5,5,2,3); System.err.println(maximumSumOfHeights(m3)); // res=18; 和最大的美丽塔方案为 heights = [2,2,5,5,2,2] List<Integer> m4 = Arrays.asList(1000000000,1000000000,1000000000); System.err.println(maximumSumOfHeights(m4)); // res=3000000000; 和最大的美丽塔方案为 heights = [1000000000,1000000000,1000000000] } /** * 利用单调栈,存储每个元素作为塔中心时,左右两侧的总和 * * @param maxHeights * @return */ public static long maximumSumOfHeights(List<Integer> maxHeights) { int len = maxHeights.size(); // 单调栈,左右两侧计算总和时,作为一个临时存储下标的介质 ArrayDeque<Integer> deque = new ArrayDeque<>(); // 每个元素作为塔中心时,左侧的总和 long[] left = new long[len]; for (int i = 0; i < len; i++) { Integer num = maxHeights.get(i); // 左侧大于当前元素的值全都出栈,因为需要重新计算 while (!deque.isEmpty() && maxHeights.get(deque.peek()) > num) { deque.pop(); } // 栈内剩余的下标对应的左侧和 + 需要重新计算的和 = 当前元素左侧总和 long sum = deque.isEmpty() ? (long) num * (i + 1) : left[deque.peek()] + (long) num * (i - deque.peek()); left[i] = sum; // 将当前元素下标压入栈,下次循环时使用 deque.push(i); } // 清空栈,计算右侧元素和 deque.clear(); // 同理,每个元素作为塔中心时,右侧的总和 long[] right = new long[len]; for (int i = len-1; i >= 0; i--) { Integer num = maxHeights.get(i); // 左侧大于当前元素的值全都出栈,因为需要重新计算 while (!deque.isEmpty() && maxHeights.get(deque.peek()) > num) { deque.pop(); } // 栈内剩余的下标对应的左侧和 + 需要重新计算的和 = 当前元素左侧总和 long sum = deque.isEmpty() ? (long) num * (len - i) : right[deque.peek()] + (long) num * (deque.peek()-i); right[i] = sum; // 将当前元素下标压入栈,下次循环时使用 deque.push(i); } // 计算结果最大和 long max = 0; for (int i = 0; i < len; i++) { max = Math.max(max, left[i] + right[i] - maxHeights.get(i)); } return max; } /** * 笨方法,遍历所有,超时 * * @param maxHeights * @return */ public static long maximumSumOfHeights2(List<Integer> maxHeights) { int size = maxHeights.size(); long max = 0; // 尝试让下标为i的元素作为塔的中心,遍历找出和最大的美丽塔 for (int i = 0; i < size; i++) { // 当前塔的总和 long sum = maxHeights.get(i); int l = i-1; long ln = maxHeights.get(i); // 塔的左边 while (l >= 0) { long min = Math.min(maxHeights.get(l), ln); sum += min; ln = min; l--; } int r = i+1; long rn = maxHeights.get(i); // 塔的右边 while (r < size) { long min = Math.min(maxHeights.get(r), rn); sum += min; rn = min; r++; } max = Math.max(max, sum); } return max; } }
ZetiG/DesignPractice
src/main/java/com/example/demo/leetcode/ii/MaximumSumOfHeights.java
1,550
// 塔的右边
line_comment
zh-cn
package com.example.demo.leetcode.ii; import java.util.ArrayDeque; import java.util.Arrays; import java.util.List; /** * Description: 2866. 美丽塔 II * 给你一个长度为 n 下标从 0 开始的整数数组 maxHeights 。 * * 你的任务是在坐标轴上建 n 座塔。第 i 座塔的下标为 i ,高度为 heights[i] 。 * 如果以下条件满足,我们称这些塔是 美丽 的: * 1 <= heights[i] <= maxHeights[i] * heights 是一个 山脉 数组。 * * 如果存在下标 i 满足以下条件,那么我们称数组 heights 是一个 山脉 数组: * 对于所有 0 < j <= i ,都有 heights[j - 1] <= heights[j] * 对于所有 i <= k < n - 1 ,都有 heights[k + 1] <= heights[k] * * 请你返回满足 美丽塔 要求的方案中,高度和的最大值 。 * * @author Zeti * @date 2023/12/21 10:08 */ public class MaximumSumOfHeights { public static void main(String[] args) { List<Integer> m1 = Arrays.asList(5,3,4,1,1); System.err.println(maximumSumOfHeights(m1)); // res=13; 和最大的美丽塔方案为 heights = [5,3,3,1,1] List<Integer> m2 = Arrays.asList(6,5,3,9,2,7); System.err.println(maximumSumOfHeights(m2)); // res=22; 和最大的美丽塔方案为 heights = [3,3,3,9,2,2] List<Integer> m3 = Arrays.asList(3,2,5,5,2,3); System.err.println(maximumSumOfHeights(m3)); // res=18; 和最大的美丽塔方案为 heights = [2,2,5,5,2,2] List<Integer> m4 = Arrays.asList(1000000000,1000000000,1000000000); System.err.println(maximumSumOfHeights(m4)); // res=3000000000; 和最大的美丽塔方案为 heights = [1000000000,1000000000,1000000000] } /** * 利用单调栈,存储每个元素作为塔中心时,左右两侧的总和 * * @param maxHeights * @return */ public static long maximumSumOfHeights(List<Integer> maxHeights) { int len = maxHeights.size(); // 单调栈,左右两侧计算总和时,作为一个临时存储下标的介质 ArrayDeque<Integer> deque = new ArrayDeque<>(); // 每个元素作为塔中心时,左侧的总和 long[] left = new long[len]; for (int i = 0; i < len; i++) { Integer num = maxHeights.get(i); // 左侧大于当前元素的值全都出栈,因为需要重新计算 while (!deque.isEmpty() && maxHeights.get(deque.peek()) > num) { deque.pop(); } // 栈内剩余的下标对应的左侧和 + 需要重新计算的和 = 当前元素左侧总和 long sum = deque.isEmpty() ? (long) num * (i + 1) : left[deque.peek()] + (long) num * (i - deque.peek()); left[i] = sum; // 将当前元素下标压入栈,下次循环时使用 deque.push(i); } // 清空栈,计算右侧元素和 deque.clear(); // 同理,每个元素作为塔中心时,右侧的总和 long[] right = new long[len]; for (int i = len-1; i >= 0; i--) { Integer num = maxHeights.get(i); // 左侧大于当前元素的值全都出栈,因为需要重新计算 while (!deque.isEmpty() && maxHeights.get(deque.peek()) > num) { deque.pop(); } // 栈内剩余的下标对应的左侧和 + 需要重新计算的和 = 当前元素左侧总和 long sum = deque.isEmpty() ? (long) num * (len - i) : right[deque.peek()] + (long) num * (deque.peek()-i); right[i] = sum; // 将当前元素下标压入栈,下次循环时使用 deque.push(i); } // 计算结果最大和 long max = 0; for (int i = 0; i < len; i++) { max = Math.max(max, left[i] + right[i] - maxHeights.get(i)); } return max; } /** * 笨方法,遍历所有,超时 * * @param maxHeights * @return */ public static long maximumSumOfHeights2(List<Integer> maxHeights) { int size = maxHeights.size(); long max = 0; // 尝试让下标为i的元素作为塔的中心,遍历找出和最大的美丽塔 for (int i = 0; i < size; i++) { // 当前塔的总和 long sum = maxHeights.get(i); int l = i-1; long ln = maxHeights.get(i); // 塔的左边 while (l >= 0) { long min = Math.min(maxHeights.get(l), ln); sum += min; ln = min; l--; } int r = i+1; long rn = maxHeights.get(i); // 塔的 <SUF> while (r < size) { long min = Math.min(maxHeights.get(r), rn); sum += min; rn = min; r++; } max = Math.max(max, sum); } return max; } }
false
1,423
6
1,550
7
1,526
4
1,550
7
1,984
6
false
false
false
false
false
true
22157_5
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class utils { public static void main(String[] args){ System.out.println("this is utils file"); } //print the time public static void print_time(int[] date){ if (date.length==7) { System.out.printf("%d年 %d月 %02d日 星期%d %02d时 %02d分 %02d秒\n",date[0],date[1],date[2],date[6],date[3],date[4],date[5]); } else{ if (date.length==3) { System.out.printf("剩余时间:%02d时 %02d分 %02d秒\n",date[0],date[1],date[2]); } else{ System.out.printf("您设置的闹钟是:%02d时 %02d分\n",date[0],date[1]); } } } //transer the ms to normal time public static int[] transerform(long millisecond){ int[] countdown_time = new int[3]; countdown_time[0] = (int)((millisecond % (24 * 60 * 60 * 1000))) / (60 * 60 * 1000);//hour countdown_time[1] = (int)((millisecond % (60 * 60 * 1000)) / (60 * 1000));//minutes countdown_time[2] = (int)((millisecond % (60 * 1000)) / 1000);//minutes return countdown_time; } // 将日期时间格式转换为数组 public static int[] toArr(LocalDateTime currentDateTime) { int[] date = new int[7]; // 初始化数组 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); date[0] = currentDateTime.getYear(); date[1] = currentDateTime.getMonthValue(); date[2] = currentDateTime.getDayOfMonth(); date[3] = currentDateTime.getHour(); date[4] = currentDateTime.getMinute(); date[5] = currentDateTime.getSecond(); date[6] = currentDateTime.getDayOfWeek().getValue(); return date; } //贪睡模式修改时间 public static int[] moresleep(int[] date){ if (date[1]+10>=60) { date[1] = (date[1]+10)%60; date[0] = date[0] + 1; if (date[0]>=24) { date[0] = date[0] % 24; } } else{ date[1] = (date[1]+10); } return date; } //int型数值星期数转换为中文字符 public static String weekday(int week){ String chinaNum = "错误"; switch (week) { case 1: chinaNum = "一"; break; case 2: chinaNum = "二"; break; case 3: chinaNum = "三"; break; case 4: chinaNum = "四"; break; case 5: chinaNum = "五"; break; case 6: chinaNum = "六"; break; case 7: chinaNum = "日"; default: break; } return chinaNum; } }
Zh-Qr/Digitial-Clock
utils.java
858
// 将日期时间格式转换为数组
line_comment
zh-cn
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class utils { public static void main(String[] args){ System.out.println("this is utils file"); } //print the time public static void print_time(int[] date){ if (date.length==7) { System.out.printf("%d年 %d月 %02d日 星期%d %02d时 %02d分 %02d秒\n",date[0],date[1],date[2],date[6],date[3],date[4],date[5]); } else{ if (date.length==3) { System.out.printf("剩余时间:%02d时 %02d分 %02d秒\n",date[0],date[1],date[2]); } else{ System.out.printf("您设置的闹钟是:%02d时 %02d分\n",date[0],date[1]); } } } //transer the ms to normal time public static int[] transerform(long millisecond){ int[] countdown_time = new int[3]; countdown_time[0] = (int)((millisecond % (24 * 60 * 60 * 1000))) / (60 * 60 * 1000);//hour countdown_time[1] = (int)((millisecond % (60 * 60 * 1000)) / (60 * 1000));//minutes countdown_time[2] = (int)((millisecond % (60 * 1000)) / 1000);//minutes return countdown_time; } // 将日 <SUF> public static int[] toArr(LocalDateTime currentDateTime) { int[] date = new int[7]; // 初始化数组 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); date[0] = currentDateTime.getYear(); date[1] = currentDateTime.getMonthValue(); date[2] = currentDateTime.getDayOfMonth(); date[3] = currentDateTime.getHour(); date[4] = currentDateTime.getMinute(); date[5] = currentDateTime.getSecond(); date[6] = currentDateTime.getDayOfWeek().getValue(); return date; } //贪睡模式修改时间 public static int[] moresleep(int[] date){ if (date[1]+10>=60) { date[1] = (date[1]+10)%60; date[0] = date[0] + 1; if (date[0]>=24) { date[0] = date[0] % 24; } } else{ date[1] = (date[1]+10); } return date; } //int型数值星期数转换为中文字符 public static String weekday(int week){ String chinaNum = "错误"; switch (week) { case 1: chinaNum = "一"; break; case 2: chinaNum = "二"; break; case 3: chinaNum = "三"; break; case 4: chinaNum = "四"; break; case 5: chinaNum = "五"; break; case 6: chinaNum = "六"; break; case 7: chinaNum = "日"; default: break; } return chinaNum; } }
false
792
10
854
9
909
8
854
9
997
15
false
false
false
false
false
true
37532_2
import java.util.Scanner; public class Ddd { public boolean isleap(int year) { return (year % 4 == 0) && (year % 100 != 0) || year % 400 == 0; } public int daysOfmonth(int year, int month) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: if (isleap(year)) return 29; else return 28; default: System.out.println("程序错误:输入的月份有误!"); return 0; } } private int weekOffirst(int year, int month) { int m = month; int d = 1; if (month <= 2) { /* 对小于2的月份进行修正 */ year--; m = month + 12; } int y = year % 100; int c = year / 100;// 世纪数减1 int w = (y + y / 4 + c / 4 - 2 * c + (13 * (m + 1) / 5) + d - 1) % 7; if (w < 0) /* 修正计算结果是负数的情况 */ w += 7; return w; } public void dataprint(int year, int month) { System.out.println("\t\t" + year + "年" + " " + month + "月"); System.out.println("日\t一\t二\t三\t四\t五\t六"); int week = weekOffirst(year, month); int[][] data = new int[6][7]; int daynum = 1; for (int i = 0; daynum <= daysOfmonth(year, month); i++) { for (int j = 0; j < 7 && daynum <= daysOfmonth(year, month); j++) { if (i == 0 && j < week) { data[i][j] = 0; System.out.print("\t"); } else { data[i][j] = daynum++; System.out.print(data[i][j] + "\t"); } } System.out.println(); } } public static void main(String[] args) { Ddd du = new Ddd(); Scanner scn = new Scanner(System.in); System.out.print("输入年:"); int year = scn.nextInt(); System.out.print("输入月:"); int month = scn.nextInt(); scn.close(); du.dataprint(year, month); } }
ZhaiJinPei/fFEIJI
src/Ddd.java
693
/* 修正计算结果是负数的情况 */
block_comment
zh-cn
import java.util.Scanner; public class Ddd { public boolean isleap(int year) { return (year % 4 == 0) && (year % 100 != 0) || year % 400 == 0; } public int daysOfmonth(int year, int month) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: if (isleap(year)) return 29; else return 28; default: System.out.println("程序错误:输入的月份有误!"); return 0; } } private int weekOffirst(int year, int month) { int m = month; int d = 1; if (month <= 2) { /* 对小于2的月份进行修正 */ year--; m = month + 12; } int y = year % 100; int c = year / 100;// 世纪数减1 int w = (y + y / 4 + c / 4 - 2 * c + (13 * (m + 1) / 5) + d - 1) % 7; if (w < 0) /* 修正计 <SUF>*/ w += 7; return w; } public void dataprint(int year, int month) { System.out.println("\t\t" + year + "年" + " " + month + "月"); System.out.println("日\t一\t二\t三\t四\t五\t六"); int week = weekOffirst(year, month); int[][] data = new int[6][7]; int daynum = 1; for (int i = 0; daynum <= daysOfmonth(year, month); i++) { for (int j = 0; j < 7 && daynum <= daysOfmonth(year, month); j++) { if (i == 0 && j < week) { data[i][j] = 0; System.out.print("\t"); } else { data[i][j] = daynum++; System.out.print(data[i][j] + "\t"); } } System.out.println(); } } public static void main(String[] args) { Ddd du = new Ddd(); Scanner scn = new Scanner(System.in); System.out.print("输入年:"); int year = scn.nextInt(); System.out.print("输入月:"); int month = scn.nextInt(); scn.close(); du.dataprint(year, month); } }
false
639
10
692
11
753
9
692
11
819
19
false
false
false
false
false
true
41416_10
package com.xufree.learning.algorithm.tree; import java.util.*; /** * 字典树 * * @author zhangmingxu ON 09:29 2019-06-17 **/ public class TrieTree { //所有的头节点 private final Map<Character, Node> heads = new HashMap<>(); public void put(String value) { if (value == null) { return; } char[] chars = getChars(value); if (chars.length == 0) { return; } Node head; if (chars.length == 1) {//只有一个字符的话创建完头就可以返回了 buildHead(chars[0], true); return; } else { head = buildHead(chars[0], false); } Node curFather = head; for (int i = 1; i < chars.length; i++) { char childChar = chars[i]; boolean isEnd = i == chars.length - 1; curFather = getChild(curFather, childChar, isEnd); } } /** * 判断value是否存在于树中 * * @param value 待判断的值 * @return value是否存在于树中 */ public boolean contains(String value) { if (value == null) { throw new IllegalArgumentException("value can not be null"); } char[] chars = getChars(value); Node cur = heads.get(chars[0]); if (cur == null) { return false; } for (int i = 1; i < chars.length; i++) { cur = cur.children.get(chars[i]); if (cur == null) { return false; } } return cur.isEnd; } public void match(String text) { if (text == null) { throw new IllegalArgumentException("text can not be null"); } char[] chars = text.toCharArray(); for (int i = 0; i < chars.length; i++) { match(chars, i, chars.length); } } private void match(char[] chars, int begin, int end) { char first = chars[begin]; Node cur = null; for (int i = begin; i < end; i++) { if (i == begin) { cur = heads.get(first); } else { cur = cur.children.get(chars[i]); } if (cur == null) { return; } if (cur.isEnd) { // System.out.println(true); } } } /** * 获取某一个父节点的子节点 * 如果之前不存在就创建一个 * 如果存在并且之前isEnd是false并且新的是true会修改为true * * @param father 父节点 * @param aChar 对应的char * @param isEnd 是否是最后一个节点 * @return 子节点 */ private Node getChild(Node father, char aChar, boolean isEnd) { Node oldChild = father.children.get(aChar); if (oldChild == null) { Node newChild = new Node(aChar, isEnd); father.children.put(aChar, newChild); return newChild; } else { if (!oldChild.isEnd && isEnd) {//如果之前它不是结尾,现在是了需要修改为是结尾 oldChild.isEnd = true; } return oldChild; } } /** * 创建一个头节点 * 如果之前不存在就创建一个 * 如果存在并且之前isEnd是false并且新的是true会修改为true * * @param head 头char * @param isEnd 是否结束 * @return 头节点 */ private Node buildHead(char head, boolean isEnd) { Node oldHead = heads.get(head); if (oldHead == null) { Node newHead = new Node(head, isEnd); heads.put(head, newHead); return newHead; } else { if (!oldHead.isEnd && isEnd) {//如果之前它不是结尾,现在是了需要修改为是结尾 oldHead.isEnd = true; } return oldHead; } } private char[] getChars(String value) { return value.toCharArray(); } //节点 private static class Node { private final char aChar; //对应的值 private boolean isEnd; //是否有字符串在这里结束 private final Map<Character, Node> children = new HashMap<>(); //子树 public Node(char aChar, boolean isEnd) { this.aChar = aChar; this.isEnd = isEnd; } } public static void main(String[] args) { int n = 10000000; String s1 = "张明旭阿克琉斯就到了卡觉得卡拉胶苏里科夫哈哈弗兰克和你分开见多识广分开就撒谎的逻辑卡收费的"; String s2 = "a克赖斯基让他赶快来发手机看了好几份但是看了就赶快来健身房链接看动画kkk给 i 前后克里斯蒂哈来个合适的空间啊帅哥短裤家居服;看了哈空间的风格"; TrieTree tree = new TrieTree(); tree.put("asd"); tree.put("张明旭"); tree.put("asdasd"); tree.put("张明旭1"); tree.put("dsa"); tree.put("kkk"); tree.put("a"); // System.out.println(tree.contains("asdqqq")); // System.out.println(tree.contains("张明旭")); // System.out.println(tree.contains("张明旭1")); // System.out.println(tree.contains("a")); long treeBegin = System.currentTimeMillis(); for (int i = 0; i < n; i++) { tree.match(s1); tree.match(s2); } System.out.println("tree use " + (System.currentTimeMillis() - treeBegin)); Set<String> set = new HashSet<>(); set.add("asd"); set.add("张明旭"); set.add("asdasd"); set.add("张明旭1"); set.add("dsa"); set.add("kkk"); set.add("a"); long setBegin = System.currentTimeMillis(); for (int i = 0; i < n; i++) { for (String s : set) { s1.contains(s); } for (String s : set) { s2.contains(s); } } System.out.println("set use " + (System.currentTimeMillis() - setBegin)); } }
ZhangMingxu/Learning
algorithm/src/main/java/com/xufree/learning/algorithm/tree/TrieTree.java
1,611
//是否有字符串在这里结束
line_comment
zh-cn
package com.xufree.learning.algorithm.tree; import java.util.*; /** * 字典树 * * @author zhangmingxu ON 09:29 2019-06-17 **/ public class TrieTree { //所有的头节点 private final Map<Character, Node> heads = new HashMap<>(); public void put(String value) { if (value == null) { return; } char[] chars = getChars(value); if (chars.length == 0) { return; } Node head; if (chars.length == 1) {//只有一个字符的话创建完头就可以返回了 buildHead(chars[0], true); return; } else { head = buildHead(chars[0], false); } Node curFather = head; for (int i = 1; i < chars.length; i++) { char childChar = chars[i]; boolean isEnd = i == chars.length - 1; curFather = getChild(curFather, childChar, isEnd); } } /** * 判断value是否存在于树中 * * @param value 待判断的值 * @return value是否存在于树中 */ public boolean contains(String value) { if (value == null) { throw new IllegalArgumentException("value can not be null"); } char[] chars = getChars(value); Node cur = heads.get(chars[0]); if (cur == null) { return false; } for (int i = 1; i < chars.length; i++) { cur = cur.children.get(chars[i]); if (cur == null) { return false; } } return cur.isEnd; } public void match(String text) { if (text == null) { throw new IllegalArgumentException("text can not be null"); } char[] chars = text.toCharArray(); for (int i = 0; i < chars.length; i++) { match(chars, i, chars.length); } } private void match(char[] chars, int begin, int end) { char first = chars[begin]; Node cur = null; for (int i = begin; i < end; i++) { if (i == begin) { cur = heads.get(first); } else { cur = cur.children.get(chars[i]); } if (cur == null) { return; } if (cur.isEnd) { // System.out.println(true); } } } /** * 获取某一个父节点的子节点 * 如果之前不存在就创建一个 * 如果存在并且之前isEnd是false并且新的是true会修改为true * * @param father 父节点 * @param aChar 对应的char * @param isEnd 是否是最后一个节点 * @return 子节点 */ private Node getChild(Node father, char aChar, boolean isEnd) { Node oldChild = father.children.get(aChar); if (oldChild == null) { Node newChild = new Node(aChar, isEnd); father.children.put(aChar, newChild); return newChild; } else { if (!oldChild.isEnd && isEnd) {//如果之前它不是结尾,现在是了需要修改为是结尾 oldChild.isEnd = true; } return oldChild; } } /** * 创建一个头节点 * 如果之前不存在就创建一个 * 如果存在并且之前isEnd是false并且新的是true会修改为true * * @param head 头char * @param isEnd 是否结束 * @return 头节点 */ private Node buildHead(char head, boolean isEnd) { Node oldHead = heads.get(head); if (oldHead == null) { Node newHead = new Node(head, isEnd); heads.put(head, newHead); return newHead; } else { if (!oldHead.isEnd && isEnd) {//如果之前它不是结尾,现在是了需要修改为是结尾 oldHead.isEnd = true; } return oldHead; } } private char[] getChars(String value) { return value.toCharArray(); } //节点 private static class Node { private final char aChar; //对应的值 private boolean isEnd; //是否 <SUF> private final Map<Character, Node> children = new HashMap<>(); //子树 public Node(char aChar, boolean isEnd) { this.aChar = aChar; this.isEnd = isEnd; } } public static void main(String[] args) { int n = 10000000; String s1 = "张明旭阿克琉斯就到了卡觉得卡拉胶苏里科夫哈哈弗兰克和你分开见多识广分开就撒谎的逻辑卡收费的"; String s2 = "a克赖斯基让他赶快来发手机看了好几份但是看了就赶快来健身房链接看动画kkk给 i 前后克里斯蒂哈来个合适的空间啊帅哥短裤家居服;看了哈空间的风格"; TrieTree tree = new TrieTree(); tree.put("asd"); tree.put("张明旭"); tree.put("asdasd"); tree.put("张明旭1"); tree.put("dsa"); tree.put("kkk"); tree.put("a"); // System.out.println(tree.contains("asdqqq")); // System.out.println(tree.contains("张明旭")); // System.out.println(tree.contains("张明旭1")); // System.out.println(tree.contains("a")); long treeBegin = System.currentTimeMillis(); for (int i = 0; i < n; i++) { tree.match(s1); tree.match(s2); } System.out.println("tree use " + (System.currentTimeMillis() - treeBegin)); Set<String> set = new HashSet<>(); set.add("asd"); set.add("张明旭"); set.add("asdasd"); set.add("张明旭1"); set.add("dsa"); set.add("kkk"); set.add("a"); long setBegin = System.currentTimeMillis(); for (int i = 0; i < n; i++) { for (String s : set) { s1.contains(s); } for (String s : set) { s2.contains(s); } } System.out.println("set use " + (System.currentTimeMillis() - setBegin)); } }
false
1,457
5
1,611
7
1,706
5
1,611
7
2,037
14
false
false
false
false
false
true
39947_0
import java.util.Scanner; /* 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数? 程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。 */ /** * Created by apple on 2017/8/17. */ public class Bonus { public static void main(String[] args) { long a; System.out.println("Please input the profit"); Scanner n = new Scanner(System.in); a = n.nextLong(); bonus(a); } private static void bonus(long profit) { long m = 0; long n = profit; if(profit>1000000){ profit = n-1000000; n = 1000000; m = (long) (m + profit*0.01); } if(profit>600000){ profit = n-600000; n = 600000; m = (long) (m + profit*0.015); } if(profit>400000){ profit = n-400000; n = 400000; m = (long) (m + profit*0.03); } if(profit>200000){ profit = n-200000; n = 200000; m = (long) (m + profit*0.05); } if(profit>100000){ profit = n-100000; n = 100000; m = (long) (m + profit*0.075); } m = (long) (m + n*0.1); System.out.println("Bonus: "+m); } }
ZhangNing777/Exercise
Exercise012/Bonus.java
663
/* 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数? 程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。 */
block_comment
zh-cn
import java.util.Scanner; /* 题目: <SUF>*/ /** * Created by apple on 2017/8/17. */ public class Bonus { public static void main(String[] args) { long a; System.out.println("Please input the profit"); Scanner n = new Scanner(System.in); a = n.nextLong(); bonus(a); } private static void bonus(long profit) { long m = 0; long n = profit; if(profit>1000000){ profit = n-1000000; n = 1000000; m = (long) (m + profit*0.01); } if(profit>600000){ profit = n-600000; n = 600000; m = (long) (m + profit*0.015); } if(profit>400000){ profit = n-400000; n = 400000; m = (long) (m + profit*0.03); } if(profit>200000){ profit = n-200000; n = 200000; m = (long) (m + profit*0.05); } if(profit>100000){ profit = n-100000; n = 100000; m = (long) (m + profit*0.075); } m = (long) (m + n*0.1); System.out.println("Bonus: "+m); } }
false
588
194
658
243
656
204
658
243
789
298
false
false
false
false
false
true
23380_5
package org.crazyit.auction.domain; import java.util.*; import javax.persistence.*; /** * Description:<br> * 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br> * Copyright (C), 2001-2020, Yeeku.H.Lee<br> * This program is protected by copyright laws.<br> * Program Name:<br> * Date:<br> * @author Yeeku.H.Lee [email protected]<br> * @version 1.0 */ @Entity @Table(name="kind") public class Kind { // 标识属性 @Id @Column(name="kind_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; // 种类名 @Column(name="kind_name") private String kindName; // 种类描述 @Column(name="kind_desc") private String kindDesc; // 该种类下的所有物品 @OneToMany(targetEntity=Item.class , mappedBy="kind") private Set<Item> items = new HashSet<Item>(); // 无参数的构造器 public Kind() { } // 初始化全部基本属性的构造器 public Kind(String kindName , String kindDesc) { this.kindName = kindName; this.kindDesc = kindDesc; } // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // kindName的setter和getter方法 public void setKindName(String kindName) { this.kindName = kindName; } public String getKindName() { return this.kindName; } // kindDesc的setter和getter方法 public void setKindDesc(String kindDesc) { this.kindDesc = kindDesc; } public String getKindDesc() { return this.kindDesc; } // items的setter和getter方法 public void setItems(Set<Item> items) { this.items = items; } public Set<Item> getItems() { return this.items; } }
ZhangXinNan/crazy-android
19/auction_Eclipse/src/org/crazyit/auction/domain/Kind.java
611
// 无参数的构造器
line_comment
zh-cn
package org.crazyit.auction.domain; import java.util.*; import javax.persistence.*; /** * Description:<br> * 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br> * Copyright (C), 2001-2020, Yeeku.H.Lee<br> * This program is protected by copyright laws.<br> * Program Name:<br> * Date:<br> * @author Yeeku.H.Lee [email protected]<br> * @version 1.0 */ @Entity @Table(name="kind") public class Kind { // 标识属性 @Id @Column(name="kind_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; // 种类名 @Column(name="kind_name") private String kindName; // 种类描述 @Column(name="kind_desc") private String kindDesc; // 该种类下的所有物品 @OneToMany(targetEntity=Item.class , mappedBy="kind") private Set<Item> items = new HashSet<Item>(); // 无参 <SUF> public Kind() { } // 初始化全部基本属性的构造器 public Kind(String kindName , String kindDesc) { this.kindName = kindName; this.kindDesc = kindDesc; } // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // kindName的setter和getter方法 public void setKindName(String kindName) { this.kindName = kindName; } public String getKindName() { return this.kindName; } // kindDesc的setter和getter方法 public void setKindDesc(String kindDesc) { this.kindDesc = kindDesc; } public String getKindDesc() { return this.kindDesc; } // items的setter和getter方法 public void setItems(Set<Item> items) { this.items = items; } public Set<Item> getItems() { return this.items; } }
false
471
8
606
8
584
7
606
8
675
10
false
false
false
false
false
true
20674_1
package com.song.judynews.entity; import java.util.List; /** * Created by judy on 2017/6/28. */ public class JokeEntity { /** * code : 200 * msg : isSuccessful * newslist : [{"id":32729,"title":"经验主义","content":"已出版两部小说的作家安妮与喜好文学的麦克争论着。安妮终于忍不住暴躁地说道:\u201c不,麦克,你根本不知道什么是小说。因为你连一本小说也没有写过。\u201d\u201c没这回事,\u201d麦克说道,\u201c这样的论调实在是很差的经验主义。你想想看我不曾生过鸡蛋,但菜肉蛋卷味道如何,我可比母鸡还清楚。\u201d"},{"id":32729,"title":"模仿","content":"一次,好莱坞为电影表演艺术家查理·卓别林举行生日宴会。宴会结束前,卓别林用抒情高音演唱了一首意大利歌剧插曲。 在座的一位朋友惊叹不已:\u201c查理,我们相处多年,也不知道你唱得这么好啊!\u201d 卓别林回答:\u201c我根本不会唱歌。这只不过是在模仿剧中人恩瑞柯·卡如索罢了!\u201d"},{"id":32729,"title":"别致的求婚","content":"日本电影明星柴田恭兵十分爱恋一位姑娘,但不知说什么好.有一天他 终于鼓足勇 气,对姑娘说:"不知您愿不愿意和我一起变成老公公,老婆婆?" 姑娘听后,忍不 住笑了,接着又羞答答地点点头."},{"id":32729,"title":"辛普森吓破了胆","content":"辛普森杀妻案重新审理.律师满头大汗跑来:\"大事不好了......\" \"不要慌,先生,\"辛普森微笑着说,\"他们没有足够的证据,而我们有最好的律师.\" \"不,他们派来一名中国足球裁判做法官!\"律师喊道. 辛普森大惊失色,战战兢兢道:\"可是......可是我们还有陪审团?\" \"这更糟!陪审团成员都是中国的巡边员!\"辛普森拔腿就跑,至今下落不明."},{"id":32729,"title":"还未到吻的时候","content":" 在一次社交会上,法国神父米尼耶(1853\u20141944年)坐在一位长得特别迷人的姑娘旁边 。一位先生问他是否有胆量吻她一下。 \u201c当然不敢!\u201d神父说,\u201c她还没成为圣物。\u201d"},{"id":32729,"title":"约翰·威尔克斯","content":"英国政治家约翰·威尔克斯(1725一1797年)有一次跟一个罗马天主教的教徒为宗教信仰问题争论了起来。天主教徒说:\u201c在马丁路德的宗教改革以前,你的信仰是什么?\u201d 威尔克斯反问说:\u201c你早上洗过脸了吗?\u201d 天主教徒回答说洗过了之后,威尔克斯继续问道:\u201c那么,请你告诉我,你在洗脸之前脸在什么地方?\u201d"},{"id":32729,"title":"戴高乐","content":"法国总统戴高乐(1809一1970年)下班后,喜欢出去散散步。有一天,他与一位朋友散步公园里。当那位朋友看到一对依偎在一起的情侣时,十分感叹他说:\u201c还有什么比一对青年男女更美好的呢!\u201d 戴高乐安祥地答道:\u201c有,老夫老妻。\u201d"},{"id":32729,"title":"黛玉葬花","content":"话说贾宝玉在后花园遇到拿著锄头的林黛玉,宝玉问黛玉说:『你在埋甚么啊!』黛玉呜噎的说:『花、花\u2026\u2026\u2026。』宝玉赞叹的说:『你的心肠真好!』黛玉松了口气心想不小心的破的古董『花瓶』,埋起来应该没人看到吧!"},{"id":32729,"title":"霍普:不入官场","content":"鲍勃.霍普在美国家喻户晓,因为他极善于用诙谐幽默的语言批评时弊, 尤其是政府的错误.新一任总统上台后,决定请他出任要职.他讥笑着说- -"假如我也去当官,谁还来批评当官的呢?""},{"id":32729,"title":"歌德","content":"有一次,德国著名诗人歌德在公园里散步,在一条仅能让一个人通过的小道上,他遇到了一位曾经尖锐地批评过他的作品的批评家,两人越走越近。\u201c我是从来不给蠢货让路的!\u201d批评家傲慢地开口说。\u201c我却正好相反。\u201d歌德说完,笑着退到路边。"}] */ private int code; private String msg; private List<NewslistBean> newslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<NewslistBean> getNewslist() { return newslist; } public void setNewslist(List<NewslistBean> newslist) { this.newslist = newslist; } public static class NewslistBean { /** * id : 32729 * title : 经验主义 * content : 已出版两部小说的作家安妮与喜好文学的麦克争论着。安妮终于忍不住暴躁地说道:“不,麦克,你根本不知道什么是小说。因为你连一本小说也没有写过。”“没这回事,”麦克说道,“这样的论调实在是很差的经验主义。你想想看我不曾生过鸡蛋,但菜肉蛋卷味道如何,我可比母鸡还清楚。” */ private int id; private String title; private String content; 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; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "NewslistBean{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + '}'; } } @Override public String toString() { return "JokeEntity{" + "code=" + code + ", msg='" + msg + '\'' + ", newslist=" + newslist + '}'; } }
ZhangYeSong/JudyNews
app/src/main/java/com/song/judynews/entity/JokeEntity.java
2,184
/** * code : 200 * msg : isSuccessful * newslist : [{"id":32729,"title":"经验主义","content":"已出版两部小说的作家安妮与喜好文学的麦克争论着。安妮终于忍不住暴躁地说道:\u201c不,麦克,你根本不知道什么是小说。因为你连一本小说也没有写过。\u201d\u201c没这回事,\u201d麦克说道,\u201c这样的论调实在是很差的经验主义。你想想看我不曾生过鸡蛋,但菜肉蛋卷味道如何,我可比母鸡还清楚。\u201d"},{"id":32729,"title":"模仿","content":"一次,好莱坞为电影表演艺术家查理·卓别林举行生日宴会。宴会结束前,卓别林用抒情高音演唱了一首意大利歌剧插曲。 在座的一位朋友惊叹不已:\u201c查理,我们相处多年,也不知道你唱得这么好啊!\u201d 卓别林回答:\u201c我根本不会唱歌。这只不过是在模仿剧中人恩瑞柯·卡如索罢了!\u201d"},{"id":32729,"title":"别致的求婚","content":"日本电影明星柴田恭兵十分爱恋一位姑娘,但不知说什么好.有一天他 终于鼓足勇 气,对姑娘说:"不知您愿不愿意和我一起变成老公公,老婆婆?" 姑娘听后,忍不 住笑了,接着又羞答答地点点头."},{"id":32729,"title":"辛普森吓破了胆","content":"辛普森杀妻案重新审理.律师满头大汗跑来:\"大事不好了......\" \"不要慌,先生,\"辛普森微笑着说,\"他们没有足够的证据,而我们有最好的律师.\" \"不,他们派来一名中国足球裁判做法官!\"律师喊道. 辛普森大惊失色,战战兢兢道:\"可是......可是我们还有陪审团?\" \"这更糟!陪审团成员都是中国的巡边员!\"辛普森拔腿就跑,至今下落不明."},{"id":32729,"title":"还未到吻的时候","content":" 在一次社交会上,法国神父米尼耶(1853\u20141944年)坐在一位长得特别迷人的姑娘旁边 。一位先生问他是否有胆量吻她一下。 \u201c当然不敢!\u201d神父说,\u201c她还没成为圣物。\u201d"},{"id":32729,"title":"约翰·威尔克斯","content":"英国政治家约翰·威尔克斯(1725一1797年)有一次跟一个罗马天主教的教徒为宗教信仰问题争论了起来。天主教徒说:\u201c在马丁路德的宗教改革以前,你的信仰是什么?\u201d 威尔克斯反问说:\u201c你早上洗过脸了吗?\u201d 天主教徒回答说洗过了之后,威尔克斯继续问道:\u201c那么,请你告诉我,你在洗脸之前脸在什么地方?\u201d"},{"id":32729,"title":"戴高乐","content":"法国总统戴高乐(1809一1970年)下班后,喜欢出去散散步。有一天,他与一位朋友散步公园里。当那位朋友看到一对依偎在一起的情侣时,十分感叹他说:\u201c还有什么比一对青年男女更美好的呢!\u201d 戴高乐安祥地答道:\u201c有,老夫老妻。\u201d"},{"id":32729,"title":"黛玉葬花","content":"话说贾宝玉在后花园遇到拿著锄头的林黛玉,宝玉问黛玉说:『你在埋甚么啊!』黛玉呜噎的说:『花、花\u2026\u2026\u2026。』宝玉赞叹的说:『你的心肠真好!』黛玉松了口气心想不小心的破的古董『花瓶』,埋起来应该没人看到吧!"},{"id":32729,"title":"霍普:不入官场","content":"鲍勃.霍普在美国家喻户晓,因为他极善于用诙谐幽默的语言批评时弊, 尤其是政府的错误.新一任总统上台后,决定请他出任要职.他讥笑着说- -"假如我也去当官,谁还来批评当官的呢?""},{"id":32729,"title":"歌德","content":"有一次,德国著名诗人歌德在公园里散步,在一条仅能让一个人通过的小道上,他遇到了一位曾经尖锐地批评过他的作品的批评家,两人越走越近。\u201c我是从来不给蠢货让路的!\u201d批评家傲慢地开口说。\u201c我却正好相反。\u201d歌德说完,笑着退到路边。"}] */
block_comment
zh-cn
package com.song.judynews.entity; import java.util.List; /** * Created by judy on 2017/6/28. */ public class JokeEntity { /** * cod <SUF>*/ private int code; private String msg; private List<NewslistBean> newslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<NewslistBean> getNewslist() { return newslist; } public void setNewslist(List<NewslistBean> newslist) { this.newslist = newslist; } public static class NewslistBean { /** * id : 32729 * title : 经验主义 * content : 已出版两部小说的作家安妮与喜好文学的麦克争论着。安妮终于忍不住暴躁地说道:“不,麦克,你根本不知道什么是小说。因为你连一本小说也没有写过。”“没这回事,”麦克说道,“这样的论调实在是很差的经验主义。你想想看我不曾生过鸡蛋,但菜肉蛋卷味道如何,我可比母鸡还清楚。” */ private int id; private String title; private String content; 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; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "NewslistBean{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + '}'; } } @Override public String toString() { return "JokeEntity{" + "code=" + code + ", msg='" + msg + '\'' + ", newslist=" + newslist + '}'; } }
false
1,679
1,194
2,184
1,624
1,798
1,231
2,184
1,624
2,881
2,162
true
true
true
true
true
false
16425_3
package com.zwayen.testencrypt; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import android.app.Activity; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); android.content.pm.Signature[] signatures = packageInfo.signatures; if (signatures != null && signatures.length > 0) { String md5 = DigestUtils.md5(signatures[0].toCharsString()); String md52 = DigestUtils.md5(new String(signatures[0].toByteArray(), "utf-8")); Log.i("MD5", md5); PublicKey publicKey = getPublicKey(signatures[0]); String strPk = publicKey.toString(); } } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); // 1024位长度,目前1024位也会给破解,最好设置2048, KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); // 私钥 PublicKey publicKey = keyPair.getPublic(); // 公钥 String plaintext = "This is the message being signed"; // Compute signature Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(privateKey); // 用私钥签名 instance.update((plaintext).getBytes()); //原文 byte[] signature = instance.sign(); // 用sha1散列算法生成摘要并用私钥进行数字签名返回 (数字签名就是私钥加密原文的摘要) // Compute digest MessageDigest sha1 = MessageDigest.getInstance("SHA1"); byte[] digest = sha1.digest((plaintext).getBytes()); // Encrypt digest Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] cipherText = cipher.doFinal(digest); // Display results System.out.println("Input data: " + plaintext); System.out.println("Digest: " + bytes2String(digest)); System.out.println("Cipher text: " + bytes2String(cipherText)); //奇怪,Cipher text和Signature的输出不一样,难道Cipher text先sha1再RSA私钥加密两步操作和SHA1withRSA一步出来的结果会不一样。 System.out.println("Signature: " + bytes2String(signature)); /*************************用公钥验证数字签名***********************/ instance.initVerify(publicKey); // 用公钥验证 instance.update(plaintext.getBytes()); //原文 if (instance.verify(signature)) { // 验证是否和数字签名一致 Log.i("Verification", "Signature verification success."); } else { Log.i("Verification", "Signature verification fail."); } /*********************私钥加密,公钥解密*************************/ Cipher encrypt = Cipher.getInstance("RSA"); encrypt.init(Cipher.ENCRYPT_MODE, privateKey); byte[] encryptData = encrypt.doFinal(plaintext.getBytes()); //私钥加密字符串 Cipher decrypt = Cipher.getInstance("RSA"); decrypt.init(Cipher.DECRYPT_MODE, publicKey); byte[] decryptData = decrypt.doFinal(encryptData); //公钥解密字符串 String decryptSt = new String(decryptData); Log.i("public key decrypt", decryptSt); /*********************公钥加密,私钥解密*************************/ Cipher encrypt2 = Cipher.getInstance("RSA"); encrypt2.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptData2 = encrypt.doFinal(plaintext.getBytes()); //公钥加密字符串 Cipher decrypt2 = Cipher.getInstance("RSA"); decrypt2.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptData2 = decrypt.doFinal(encryptData2); //公钥解密字符串 String decryptSt2 = new String(decryptData2); Log.i("private key decrypt", decryptSt2); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalBlockSizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SignatureException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public PublicKey getPublicKey(android.content.pm.Signature signature) throws CertificateException { final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bais = new ByteArrayInputStream(signature.toByteArray()); final Certificate cert = certFactory.generateCertificate(bais); return cert.getPublicKey(); } public static String bytes2String(byte[] bytes) { StringBuilder string = new StringBuilder(); for (byte b : bytes) { String hexString = Integer.toHexString(0x00FF & b); string.append(hexString.length() == 1 ? "0" + hexString : hexString); } return string.toString(); } }
Zhangzhiyi/Android
TestEncrypt/src/com/zwayen/testencrypt/MainActivity.java
1,602
// 1024位长度,目前1024位也会给破解,最好设置2048,
line_comment
zh-cn
package com.zwayen.testencrypt; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import android.app.Activity; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); android.content.pm.Signature[] signatures = packageInfo.signatures; if (signatures != null && signatures.length > 0) { String md5 = DigestUtils.md5(signatures[0].toCharsString()); String md52 = DigestUtils.md5(new String(signatures[0].toByteArray(), "utf-8")); Log.i("MD5", md5); PublicKey publicKey = getPublicKey(signatures[0]); String strPk = publicKey.toString(); } } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); // 10 <SUF> KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); // 私钥 PublicKey publicKey = keyPair.getPublic(); // 公钥 String plaintext = "This is the message being signed"; // Compute signature Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(privateKey); // 用私钥签名 instance.update((plaintext).getBytes()); //原文 byte[] signature = instance.sign(); // 用sha1散列算法生成摘要并用私钥进行数字签名返回 (数字签名就是私钥加密原文的摘要) // Compute digest MessageDigest sha1 = MessageDigest.getInstance("SHA1"); byte[] digest = sha1.digest((plaintext).getBytes()); // Encrypt digest Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] cipherText = cipher.doFinal(digest); // Display results System.out.println("Input data: " + plaintext); System.out.println("Digest: " + bytes2String(digest)); System.out.println("Cipher text: " + bytes2String(cipherText)); //奇怪,Cipher text和Signature的输出不一样,难道Cipher text先sha1再RSA私钥加密两步操作和SHA1withRSA一步出来的结果会不一样。 System.out.println("Signature: " + bytes2String(signature)); /*************************用公钥验证数字签名***********************/ instance.initVerify(publicKey); // 用公钥验证 instance.update(plaintext.getBytes()); //原文 if (instance.verify(signature)) { // 验证是否和数字签名一致 Log.i("Verification", "Signature verification success."); } else { Log.i("Verification", "Signature verification fail."); } /*********************私钥加密,公钥解密*************************/ Cipher encrypt = Cipher.getInstance("RSA"); encrypt.init(Cipher.ENCRYPT_MODE, privateKey); byte[] encryptData = encrypt.doFinal(plaintext.getBytes()); //私钥加密字符串 Cipher decrypt = Cipher.getInstance("RSA"); decrypt.init(Cipher.DECRYPT_MODE, publicKey); byte[] decryptData = decrypt.doFinal(encryptData); //公钥解密字符串 String decryptSt = new String(decryptData); Log.i("public key decrypt", decryptSt); /*********************公钥加密,私钥解密*************************/ Cipher encrypt2 = Cipher.getInstance("RSA"); encrypt2.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptData2 = encrypt.doFinal(plaintext.getBytes()); //公钥加密字符串 Cipher decrypt2 = Cipher.getInstance("RSA"); decrypt2.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptData2 = decrypt.doFinal(encryptData2); //公钥解密字符串 String decryptSt2 = new String(decryptData2); Log.i("private key decrypt", decryptSt2); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalBlockSizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SignatureException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public PublicKey getPublicKey(android.content.pm.Signature signature) throws CertificateException { final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bais = new ByteArrayInputStream(signature.toByteArray()); final Certificate cert = certFactory.generateCertificate(bais); return cert.getPublicKey(); } public static String bytes2String(byte[] bytes) { StringBuilder string = new StringBuilder(); for (byte b : bytes) { String hexString = Integer.toHexString(0x00FF & b); string.append(hexString.length() == 1 ? "0" + hexString : hexString); } return string.toString(); } }
false
1,379
26
1,602
29
1,593
26
1,602
29
2,178
34
false
false
false
false
false
true
11300_3
package com.socks.jiandan.ui; import android.graphics.Color; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.android.volley.Response; import com.android.volley.VolleyError; import com.socks.jiandan.R; import com.socks.jiandan.base.BaseActivity; import com.socks.jiandan.base.ConstantString; import com.socks.jiandan.base.JDApplication; import com.socks.jiandan.model.Commentator; import com.socks.jiandan.net.Request4PushComment; import com.socks.jiandan.net.Request4PushFreshComment; import com.socks.jiandan.utils.EditTextShakeHelper; import com.socks.jiandan.utils.SharedPreUtils; import com.socks.jiandan.utils.ShowToast; import com.socks.jiandan.utils.TextUtil; import java.util.HashMap; import butterknife.ButterKnife; import butterknife.InjectView; public class PushCommentActivity extends BaseActivity { @InjectView(R.id.tv_title) TextView tv_title; @InjectView(R.id.et_content) EditText et_content; @InjectView(R.id.toolbar) Toolbar mToolbar; private String thread_id; private String parent_id; private String parent_name; private String author_name; private String author_email; private String message; private EditText et_name; private EditText et_email; private View positiveAction; private MaterialDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_push_comment); initView(); initData(); } @Override public void initView() { ButterKnife.inject(this); mToolbar.setTitleTextColor(Color.WHITE); setSupportActionBar(mToolbar); mToolbar.setTitle("回复"); mToolbar.setNavigationIcon(R.drawable.ic_actionbar_back); } @Override protected void initData() { parent_name = getIntent().getStringExtra("parent_name"); tv_title.setText(TextUtil.isNull(parent_name) ? "回复:" : "回复:" + parent_name); /*新鲜事中 文章id=当前的thread_id=接口参数中的post_id*/ thread_id = getIntent().getStringExtra("thread_id"); parent_id = getIntent().getStringExtra("parent_id"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_push_comment, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_push: message = et_content.getText().toString(); if (TextUtil.isNull(message)) { ShowToast.Short(ConstantString.INPUT_TOO_SHORT); new EditTextShakeHelper(this).shake(et_content); return true; } dialog = new MaterialDialog.Builder(this) .title("作为游客留言") .backgroundColor(getResources().getColor(JDApplication.COLOR_OF_DIALOG)) .contentColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .positiveColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .negativeColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .titleColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .customView(R.layout.dialog_commentotar_info, true) .positiveText("确定") .negativeText(android.R.string.cancel) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(final MaterialDialog dialog) { author_name = et_name.getText().toString(); author_email = et_email.getText().toString(); SharedPreUtils.setString(PushCommentActivity.this, "author_name", author_name); SharedPreUtils.setString(PushCommentActivity.this, "author_email", author_email); //新鲜事评论get if (thread_id.length() == 5) { String url; //回复别人 和首次评论 if (!TextUtil.isNull(parent_id) && !TextUtil.isNull (parent_name)) { url = Request4PushFreshComment.getRequestURL(thread_id, parent_id, parent_name, author_name, author_email, message); } else { url = Request4PushFreshComment.getRequestURLNoParent(thread_id, author_name, author_email, message); } //提交评论 executeRequest(new Request4PushFreshComment(url, new PushCommentListener(), new PushCommentErrorListener())); return; } //多说的评论post HashMap<String, String> requestParams; //回复别人 和首次评论 if (!TextUtil.isNull(parent_id)) { requestParams = Request4PushComment.getRequestParams(thread_id, parent_id, author_name, author_email, message); } else { requestParams = Request4PushComment.getRequestParamsNoParent(thread_id, author_name, author_email, message); } executeRequest(new Request4PushComment(Commentator.URL_PUSH_COMMENT, requestParams, new PushCommentListener(), new PushCommentErrorListener())); } @Override public void onNegative(MaterialDialog dialog) { } }).build(); et_name = (EditText) (dialog.getCustomView().findViewById(R.id .et_name)); et_email = (EditText) (dialog.getCustomView().findViewById(R.id .et_email)); positiveAction = dialog.getActionButton(DialogAction.POSITIVE); et_name.addTextChangedListener(new InputWatcher()); et_email.addTextChangedListener(new InputWatcher()); et_name.setText(SharedPreUtils.getString(PushCommentActivity .this, "author_name")); et_email.setText(SharedPreUtils.getString(PushCommentActivity .this, "author_email")); dialog.show(); return true; } return super.onOptionsItemSelected(item); } class PushCommentListener implements Response.Listener<Boolean> { @Override public void onResponse(Boolean response) { dialog.dismiss(); if (response) { setResult(RESULT_OK); finish(); } else { ShowToast.Short(ConstantString.COMMENT_FAILED); } } } class PushCommentErrorListener implements Response.ErrorListener { @Override public void onErrorResponse(VolleyError error) { ShowToast.Short(ConstantString.COMMENT_FAILED); dialog.dismiss(); } } private class InputWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { positiveAction.setEnabled(TextUtil.isEmail(et_email.getText().toString().trim() ) && !TextUtil.isNull(et_name.getText().toString())); } @Override public void afterTextChanged(Editable s) { } } }
ZhaoKaiQiang/JianDan
app/src/main/java/com/socks/jiandan/ui/PushCommentActivity.java
1,812
//提交评论
line_comment
zh-cn
package com.socks.jiandan.ui; import android.graphics.Color; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.android.volley.Response; import com.android.volley.VolleyError; import com.socks.jiandan.R; import com.socks.jiandan.base.BaseActivity; import com.socks.jiandan.base.ConstantString; import com.socks.jiandan.base.JDApplication; import com.socks.jiandan.model.Commentator; import com.socks.jiandan.net.Request4PushComment; import com.socks.jiandan.net.Request4PushFreshComment; import com.socks.jiandan.utils.EditTextShakeHelper; import com.socks.jiandan.utils.SharedPreUtils; import com.socks.jiandan.utils.ShowToast; import com.socks.jiandan.utils.TextUtil; import java.util.HashMap; import butterknife.ButterKnife; import butterknife.InjectView; public class PushCommentActivity extends BaseActivity { @InjectView(R.id.tv_title) TextView tv_title; @InjectView(R.id.et_content) EditText et_content; @InjectView(R.id.toolbar) Toolbar mToolbar; private String thread_id; private String parent_id; private String parent_name; private String author_name; private String author_email; private String message; private EditText et_name; private EditText et_email; private View positiveAction; private MaterialDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_push_comment); initView(); initData(); } @Override public void initView() { ButterKnife.inject(this); mToolbar.setTitleTextColor(Color.WHITE); setSupportActionBar(mToolbar); mToolbar.setTitle("回复"); mToolbar.setNavigationIcon(R.drawable.ic_actionbar_back); } @Override protected void initData() { parent_name = getIntent().getStringExtra("parent_name"); tv_title.setText(TextUtil.isNull(parent_name) ? "回复:" : "回复:" + parent_name); /*新鲜事中 文章id=当前的thread_id=接口参数中的post_id*/ thread_id = getIntent().getStringExtra("thread_id"); parent_id = getIntent().getStringExtra("parent_id"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_push_comment, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_push: message = et_content.getText().toString(); if (TextUtil.isNull(message)) { ShowToast.Short(ConstantString.INPUT_TOO_SHORT); new EditTextShakeHelper(this).shake(et_content); return true; } dialog = new MaterialDialog.Builder(this) .title("作为游客留言") .backgroundColor(getResources().getColor(JDApplication.COLOR_OF_DIALOG)) .contentColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .positiveColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .negativeColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .titleColor(JDApplication.COLOR_OF_DIALOG_CONTENT) .customView(R.layout.dialog_commentotar_info, true) .positiveText("确定") .negativeText(android.R.string.cancel) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(final MaterialDialog dialog) { author_name = et_name.getText().toString(); author_email = et_email.getText().toString(); SharedPreUtils.setString(PushCommentActivity.this, "author_name", author_name); SharedPreUtils.setString(PushCommentActivity.this, "author_email", author_email); //新鲜事评论get if (thread_id.length() == 5) { String url; //回复别人 和首次评论 if (!TextUtil.isNull(parent_id) && !TextUtil.isNull (parent_name)) { url = Request4PushFreshComment.getRequestURL(thread_id, parent_id, parent_name, author_name, author_email, message); } else { url = Request4PushFreshComment.getRequestURLNoParent(thread_id, author_name, author_email, message); } //提交 <SUF> executeRequest(new Request4PushFreshComment(url, new PushCommentListener(), new PushCommentErrorListener())); return; } //多说的评论post HashMap<String, String> requestParams; //回复别人 和首次评论 if (!TextUtil.isNull(parent_id)) { requestParams = Request4PushComment.getRequestParams(thread_id, parent_id, author_name, author_email, message); } else { requestParams = Request4PushComment.getRequestParamsNoParent(thread_id, author_name, author_email, message); } executeRequest(new Request4PushComment(Commentator.URL_PUSH_COMMENT, requestParams, new PushCommentListener(), new PushCommentErrorListener())); } @Override public void onNegative(MaterialDialog dialog) { } }).build(); et_name = (EditText) (dialog.getCustomView().findViewById(R.id .et_name)); et_email = (EditText) (dialog.getCustomView().findViewById(R.id .et_email)); positiveAction = dialog.getActionButton(DialogAction.POSITIVE); et_name.addTextChangedListener(new InputWatcher()); et_email.addTextChangedListener(new InputWatcher()); et_name.setText(SharedPreUtils.getString(PushCommentActivity .this, "author_name")); et_email.setText(SharedPreUtils.getString(PushCommentActivity .this, "author_email")); dialog.show(); return true; } return super.onOptionsItemSelected(item); } class PushCommentListener implements Response.Listener<Boolean> { @Override public void onResponse(Boolean response) { dialog.dismiss(); if (response) { setResult(RESULT_OK); finish(); } else { ShowToast.Short(ConstantString.COMMENT_FAILED); } } } class PushCommentErrorListener implements Response.ErrorListener { @Override public void onErrorResponse(VolleyError error) { ShowToast.Short(ConstantString.COMMENT_FAILED); dialog.dismiss(); } } private class InputWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { positiveAction.setEnabled(TextUtil.isEmail(et_email.getText().toString().trim() ) && !TextUtil.isNull(et_name.getText().toString())); } @Override public void afterTextChanged(Editable s) { } } }
false
1,453
3
1,812
3
1,911
3
1,812
3
2,263
9
false
false
false
false
false
true
21797_27
package task; import java.io.File; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; public class FileScanTask { //线程池 public final ExecutorService POOL=Executors.newFixedThreadPool(4); //有了线程池后可以直接使用execute提交任务 //定义一个可以记录线程个数的值 //private static volatile int COUNT; private final AtomicInteger COUNT=new AtomicInteger(); private final CountDownLatch LATCH=new CountDownLatch(1); /* * 做接口回调 * */ private FileScanCallback fileScanCallback; public FileScanTask(FileScanCallback fileScanCallback){ this.fileScanCallback=fileScanCallback; } //private static final CyclicBarrier BARRIER=new CyclicBarrier(2); /* * 启动根目录的扫描文件 * */ public void startScan(File root) { //扫描此文件夹下的文件(包含文件夹) //将文件路径传给递归list() //启动线程进行扫描文件 /*synchronized (this) { COUNT++; }*/ COUNT.incrementAndGet(); POOL.execute(new Runnable() { @Override public void run() { list(root); } }); } /* //测试 public static void main(String[] args) throws InterruptedException { FileScanTask task=new FileScanTask();//实例化一个类 task.startScan(new File("D:\\ccc"));//启动扫描文件夹 synchronized (task){ task.wait();//等待task结束 } System.out.println("执行完毕"); } */ /* * 等待所有的扫描任务执行完毕 * */ public void waitFinish() throws InterruptedException { //wait过程我们都清楚,需要等待所有的线程执行结束后 // 才完成,但是如果我们一开始选择错误的文件夹,此时文件夹比较大 // 我们就需要中断现在运行的线程,中段的线程也就是线程池中的线程。 /*try { synchronized (this){ this.wait();//开闭原则 } } catch (InterruptedException e) { e.printStackTrace(); }*/ //等待 try { LATCH.await(); }finally { //捕获到线程我们中断线程池 POOL.shutdown();//调用每个线程的interrupt中断 // POOL.shutdownNow();//调用每个线程stop()关闭。 } /*try { BARRIER.await(); } catch (BrokenBarrierException e) { e.printStackTrace(); }*/ } /* * 在这里使用递归的方法,因为我们获取到子文件,还有会是文件夹的情况,写一个递归的方法 * */ public void list(File dir) { if (!Thread.interrupted()) { try { //将整个文件添加到接口中 fileScanCallback.execute(dir); //System.out.println(dir.getPath()); if (dir.isDirectory()) { //将子文件放入到一个数组中 // children是子文件,子文件夹 File[] children = dir.listFiles(); //如果根文件夹中有数据进入 if (children != null && children.length > 0) { //遍历,使用递归,获取所有的内容 for (File child : children) { //这里我们已经进入到文件内,所以现在我们看的是文件夹就就进行递归,不是的话直接打印 if (child.isDirectory()) { //递归我们每次只要看到里面有子文件夹我们就启动一个线程执行 //这样就不可避免产生大量的线程,所以我们创建一个线程池 /*synchronized (this) { COUNT++; }*/ COUNT.incrementAndGet(); POOL.execute(new Runnable() { @Override public void run() { list(child); } }); } else { fileScanCallback.execute(dir); //System.out.println(child.getPath()); } } } } } finally { if (COUNT.decrementAndGet() == 0) { //通知 LATCH.countDown(); /*try { BARRIER.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); }*/ } } } } }
ZhaoYLong-cxcx/demo
FileScanTask.java
981
//如果根文件夹中有数据进入
line_comment
zh-cn
package task; import java.io.File; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; public class FileScanTask { //线程池 public final ExecutorService POOL=Executors.newFixedThreadPool(4); //有了线程池后可以直接使用execute提交任务 //定义一个可以记录线程个数的值 //private static volatile int COUNT; private final AtomicInteger COUNT=new AtomicInteger(); private final CountDownLatch LATCH=new CountDownLatch(1); /* * 做接口回调 * */ private FileScanCallback fileScanCallback; public FileScanTask(FileScanCallback fileScanCallback){ this.fileScanCallback=fileScanCallback; } //private static final CyclicBarrier BARRIER=new CyclicBarrier(2); /* * 启动根目录的扫描文件 * */ public void startScan(File root) { //扫描此文件夹下的文件(包含文件夹) //将文件路径传给递归list() //启动线程进行扫描文件 /*synchronized (this) { COUNT++; }*/ COUNT.incrementAndGet(); POOL.execute(new Runnable() { @Override public void run() { list(root); } }); } /* //测试 public static void main(String[] args) throws InterruptedException { FileScanTask task=new FileScanTask();//实例化一个类 task.startScan(new File("D:\\ccc"));//启动扫描文件夹 synchronized (task){ task.wait();//等待task结束 } System.out.println("执行完毕"); } */ /* * 等待所有的扫描任务执行完毕 * */ public void waitFinish() throws InterruptedException { //wait过程我们都清楚,需要等待所有的线程执行结束后 // 才完成,但是如果我们一开始选择错误的文件夹,此时文件夹比较大 // 我们就需要中断现在运行的线程,中段的线程也就是线程池中的线程。 /*try { synchronized (this){ this.wait();//开闭原则 } } catch (InterruptedException e) { e.printStackTrace(); }*/ //等待 try { LATCH.await(); }finally { //捕获到线程我们中断线程池 POOL.shutdown();//调用每个线程的interrupt中断 // POOL.shutdownNow();//调用每个线程stop()关闭。 } /*try { BARRIER.await(); } catch (BrokenBarrierException e) { e.printStackTrace(); }*/ } /* * 在这里使用递归的方法,因为我们获取到子文件,还有会是文件夹的情况,写一个递归的方法 * */ public void list(File dir) { if (!Thread.interrupted()) { try { //将整个文件添加到接口中 fileScanCallback.execute(dir); //System.out.println(dir.getPath()); if (dir.isDirectory()) { //将子文件放入到一个数组中 // children是子文件,子文件夹 File[] children = dir.listFiles(); //如果 <SUF> if (children != null && children.length > 0) { //遍历,使用递归,获取所有的内容 for (File child : children) { //这里我们已经进入到文件内,所以现在我们看的是文件夹就就进行递归,不是的话直接打印 if (child.isDirectory()) { //递归我们每次只要看到里面有子文件夹我们就启动一个线程执行 //这样就不可避免产生大量的线程,所以我们创建一个线程池 /*synchronized (this) { COUNT++; }*/ COUNT.incrementAndGet(); POOL.execute(new Runnable() { @Override public void run() { list(child); } }); } else { fileScanCallback.execute(dir); //System.out.println(child.getPath()); } } } } } finally { if (COUNT.decrementAndGet() == 0) { //通知 LATCH.countDown(); /*try { BARRIER.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); }*/ } } } } }
false
936
9
973
9
1,053
8
973
9
1,517
16
false
false
false
false
false
true
58282_11
package tk; import java.awt.event.ActionEvent; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.sql.*; import java.util.*; //主线程监听,此线程收发消息;客户端下线,届时再说? public class Server { public static void main(String[] args){ new Server().listenClient(); } private List<mythread> clients=new ArrayList<>() ; private boolean started=false; private ServerSocket ss=null; public Server() { started=true; } //非常熟悉的监听 public void listenClient(){ int port = 12345; String temp = ""; try { ss= new ServerSocket(port); // server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的 int num=0; while (started) { System.out.printf("服务器端正在监听 %d\n",num++); Socket socket = ss.accept(); // clients1.put(socket.getPort(), socket); System.out.println("客户端"+socket.getPort()+":连接"); mythread c = new mythread(socket); clients.add(c); new Thread(c).start(); } } catch (Exception e) { e.printStackTrace(); }finally { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } //所有读写操作都放线程里了 class mythread implements Runnable{ private Connection conn=null; private Statement stmt=null; private ResultSet rs=null; private HashMap<String, String> mp = new HashMap<>(); private Socket socket = null; private DataInputStream dis = null; private DataOutputStream dos=null; private String temp = null; private String str = null; private String name = null; private String tarName = null; private String sym = null; private boolean bConnected=false; private mythread(Socket socket) { bConnected=true; this.socket = socket; } private void init(){ try { dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } private String read(){ try { str=dis.readUTF(); } catch (IOException e) { e.printStackTrace(); } return str; } private boolean readBool(){ boolean ok=false; try { ok=dis.readBoolean(); } catch (IOException e) { e.printStackTrace(); } return ok ; } private void write(String str){ try { dos.writeUTF(str); dos.flush(); } catch (IOException e) { e.printStackTrace(); } } private void initSql(){ try{ Class.forName("com.mysql.cj.jdbc.Driver"); }catch (ClassNotFoundException cne){ cne.printStackTrace(); } String dbur = "jdbc:mysql://127.0.0.1:3306/world?&useSSL=false&serverTimezone=UTC"; try { conn= DriverManager.getConnection(dbur,"root","1qaz2wsx"); stmt=conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } //需要行动的, private String doSql(String name,String sqlStr,String opt){//name是拆除后的,sqlStr用来指示好了 /*原本name就是真实名字,sqlStr可以当做查询的功能模块,有时当做其他功能选择模块,用于if判断; * opt是由于/to私聊时代的到来而进一步发展的,主要用于更进一步的选择*/ initSql(); String flag="false"; String sql = "SELECT * FROM chat"; int num=0; try { //管家注册 rs= stmt.executeQuery(sql); if(sqlStr.equals("quit")){ sql="update chat set online=0 where name=\'"+name+"\'"; stmt.execute(sql); }else { while (rs.next()) {//全部查一遍,经常操作,用个标志位来 if(sqlStr.equals("who")){ num++; System.out.println(rs.getString("name"));//who,客户端显示的话就 } if(sqlStr.equals("name")){ if(name.equals(rs.getString(sqlStr))){ sql=sql+" where name=\'"+name+"\'"; // System.out.println("inside the sql "+sql); rs=stmt.executeQuery(sql);rs.next(); sqlStr=rs.getString("online"); if(opt.equals("check")){ if(sqlStr.equals("1")){ flag="true"; } } if(opt.equals("login")){ if(sqlStr.equals("0")){ flag="true"; sql="update chat set online=1 where name=\'"+name+"\'"; // System.out.println(sql); stmt.execute(sql); } } break; } } //name } } } catch (SQLException e) { e.printStackTrace(); }finally { closeSql(); } if(sqlStr.equals("who")) { System.out.printf("Total online user: %d\n",num); } return flag; } private void closeSql(){ try { if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(conn!=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } private String checkName(){ String name=null; String ok="false"; name=read(); ok=doSql(name,"name","login"); //mysql设计了 write(ok); return name; } private void close(){ try { dos.close(); dis.close(); socket.close(); } catch (IOException e1) { e1.printStackTrace(); } } private int countSpace(int start,String temp){ int mark=0; for (int i = start; i <temp.length() ; i++) { if(temp.charAt(i)==' '){ mark=i;break; } } return mark; } @Override public void run() { String str=""; boolean ok=false; init(); //如果输错,要一直循环等待输入,且quit指令还没放入login;配合mysql while (!ok){ str=checkName(); ok=readBool(); } write(str); System.out.println("子线程开始工作"); try { //不停读取数据 while (bConnected) { name=read(); temp=read(); sym=read(); tarName=read(); //发给所有客户端先 //命令异常,字符不对;长度不够,客户端离线解决断了 if(sym.equals("1")){ if(temp.substring(0,2).equals("to")){ //用户名不带空格,且必须英文字符,否则 int mark=countSpace(3,temp); tarName=temp.substring(3,mark); // System.out.println(mark+" name "+tarName); if(doSql(tarName,"name","check").equals("false")){ sym="5"; temp=tarName+" is not online."; }else { sym="4";//仅有的人可以显示 temp=temp.substring(mark+1); } }else if(temp.equals("who")){//都是在客户端显示的 doSql(null,"who",""); //mysql数据查询了 sym="4";//假设了下 }else if(temp.equals("quit")){ doSql(name,"quit",""); clients.remove(this); bConnected=false; }else if(temp.substring(0,7).equals("history")){ if(temp.length()>7){ temp=temp.substring(8); System.out.println("1 "+temp); int mark=countSpace(0,temp); System.out.println("mark "+mark); tarName=temp.substring(mark+1); temp=temp.substring(0,mark); sym="7"; }else { sym="6"; } } } spread(); System.out.println(clients.size()+"来自客户端"+socket.getPort()+"的消息:" +temp+" sym is "+sym); } //关闭死亡线程 } catch (Exception e) { e.printStackTrace(); }finally { close(); } } private void spread(){ for (int i = 0; i <clients.size() ; i++) { mythread c = clients.get(i); c.write(name); c.write(temp); c.write(sym); c.write(tarName); } } } }
ZhengtianZhu/Internet-Chat-Rooms-based-on-JAVA
Server.java
2,095
//who,客户端显示的话就
line_comment
zh-cn
package tk; import java.awt.event.ActionEvent; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.sql.*; import java.util.*; //主线程监听,此线程收发消息;客户端下线,届时再说? public class Server { public static void main(String[] args){ new Server().listenClient(); } private List<mythread> clients=new ArrayList<>() ; private boolean started=false; private ServerSocket ss=null; public Server() { started=true; } //非常熟悉的监听 public void listenClient(){ int port = 12345; String temp = ""; try { ss= new ServerSocket(port); // server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的 int num=0; while (started) { System.out.printf("服务器端正在监听 %d\n",num++); Socket socket = ss.accept(); // clients1.put(socket.getPort(), socket); System.out.println("客户端"+socket.getPort()+":连接"); mythread c = new mythread(socket); clients.add(c); new Thread(c).start(); } } catch (Exception e) { e.printStackTrace(); }finally { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } //所有读写操作都放线程里了 class mythread implements Runnable{ private Connection conn=null; private Statement stmt=null; private ResultSet rs=null; private HashMap<String, String> mp = new HashMap<>(); private Socket socket = null; private DataInputStream dis = null; private DataOutputStream dos=null; private String temp = null; private String str = null; private String name = null; private String tarName = null; private String sym = null; private boolean bConnected=false; private mythread(Socket socket) { bConnected=true; this.socket = socket; } private void init(){ try { dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } private String read(){ try { str=dis.readUTF(); } catch (IOException e) { e.printStackTrace(); } return str; } private boolean readBool(){ boolean ok=false; try { ok=dis.readBoolean(); } catch (IOException e) { e.printStackTrace(); } return ok ; } private void write(String str){ try { dos.writeUTF(str); dos.flush(); } catch (IOException e) { e.printStackTrace(); } } private void initSql(){ try{ Class.forName("com.mysql.cj.jdbc.Driver"); }catch (ClassNotFoundException cne){ cne.printStackTrace(); } String dbur = "jdbc:mysql://127.0.0.1:3306/world?&useSSL=false&serverTimezone=UTC"; try { conn= DriverManager.getConnection(dbur,"root","1qaz2wsx"); stmt=conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } //需要行动的, private String doSql(String name,String sqlStr,String opt){//name是拆除后的,sqlStr用来指示好了 /*原本name就是真实名字,sqlStr可以当做查询的功能模块,有时当做其他功能选择模块,用于if判断; * opt是由于/to私聊时代的到来而进一步发展的,主要用于更进一步的选择*/ initSql(); String flag="false"; String sql = "SELECT * FROM chat"; int num=0; try { //管家注册 rs= stmt.executeQuery(sql); if(sqlStr.equals("quit")){ sql="update chat set online=0 where name=\'"+name+"\'"; stmt.execute(sql); }else { while (rs.next()) {//全部查一遍,经常操作,用个标志位来 if(sqlStr.equals("who")){ num++; System.out.println(rs.getString("name"));//wh <SUF> } if(sqlStr.equals("name")){ if(name.equals(rs.getString(sqlStr))){ sql=sql+" where name=\'"+name+"\'"; // System.out.println("inside the sql "+sql); rs=stmt.executeQuery(sql);rs.next(); sqlStr=rs.getString("online"); if(opt.equals("check")){ if(sqlStr.equals("1")){ flag="true"; } } if(opt.equals("login")){ if(sqlStr.equals("0")){ flag="true"; sql="update chat set online=1 where name=\'"+name+"\'"; // System.out.println(sql); stmt.execute(sql); } } break; } } //name } } } catch (SQLException e) { e.printStackTrace(); }finally { closeSql(); } if(sqlStr.equals("who")) { System.out.printf("Total online user: %d\n",num); } return flag; } private void closeSql(){ try { if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(conn!=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } private String checkName(){ String name=null; String ok="false"; name=read(); ok=doSql(name,"name","login"); //mysql设计了 write(ok); return name; } private void close(){ try { dos.close(); dis.close(); socket.close(); } catch (IOException e1) { e1.printStackTrace(); } } private int countSpace(int start,String temp){ int mark=0; for (int i = start; i <temp.length() ; i++) { if(temp.charAt(i)==' '){ mark=i;break; } } return mark; } @Override public void run() { String str=""; boolean ok=false; init(); //如果输错,要一直循环等待输入,且quit指令还没放入login;配合mysql while (!ok){ str=checkName(); ok=readBool(); } write(str); System.out.println("子线程开始工作"); try { //不停读取数据 while (bConnected) { name=read(); temp=read(); sym=read(); tarName=read(); //发给所有客户端先 //命令异常,字符不对;长度不够,客户端离线解决断了 if(sym.equals("1")){ if(temp.substring(0,2).equals("to")){ //用户名不带空格,且必须英文字符,否则 int mark=countSpace(3,temp); tarName=temp.substring(3,mark); // System.out.println(mark+" name "+tarName); if(doSql(tarName,"name","check").equals("false")){ sym="5"; temp=tarName+" is not online."; }else { sym="4";//仅有的人可以显示 temp=temp.substring(mark+1); } }else if(temp.equals("who")){//都是在客户端显示的 doSql(null,"who",""); //mysql数据查询了 sym="4";//假设了下 }else if(temp.equals("quit")){ doSql(name,"quit",""); clients.remove(this); bConnected=false; }else if(temp.substring(0,7).equals("history")){ if(temp.length()>7){ temp=temp.substring(8); System.out.println("1 "+temp); int mark=countSpace(0,temp); System.out.println("mark "+mark); tarName=temp.substring(mark+1); temp=temp.substring(0,mark); sym="7"; }else { sym="6"; } } } spread(); System.out.println(clients.size()+"来自客户端"+socket.getPort()+"的消息:" +temp+" sym is "+sym); } //关闭死亡线程 } catch (Exception e) { e.printStackTrace(); }finally { close(); } } private void spread(){ for (int i = 0; i <clients.size() ; i++) { mythread c = clients.get(i); c.write(name); c.write(temp); c.write(sym); c.write(tarName); } } } }
false
1,840
7
2,095
7
2,314
7
2,095
7
2,722
13
false
false
false
false
false
true
49219_8
import FacadePattern.TotalGuide; import FrontController.FrontController; import BuyTicketsSubsystem.*; import Show.Show; import SouvenirShop.SouvenirShopSubsystem; import AdministratorSubsystem.*; import Restaurant.*; import FacilityPlaySubsystem.*; import java.text.ParseException; import java.util.Scanner; public class Main { public static void main(String[] args) throws ParseException, InterruptedException { // 最后的汇总写在这里 Scanner mainScanner=new Scanner(System.in); boolean isAdmin = login(); boolean needGuide=false; //游客模式 if(!isAdmin){ frontControl(1); showmap(); needGuide=needGuide(); //导游代理模式 if(needGuide) Guide(); else visitorMenu(); } //管理员模式 else{ frontControl(2); Administrate(); } } /** * 是否需要导游 */ public static boolean needGuide(){ System.out.println("本次嘉年华提供向导服务,请问您是否需要导游?\n" + "1、需要导游\n" + "2、不需要导游\n"); Scanner scanner=new Scanner(System.in); return scanner.nextInt()==1; } /** * 导游执行 */ public static void Guide(){ TotalGuide guide=new TotalGuide("阿P"); guide.buyTicket(); guide.play(); guide.watch(); guide.end(); } /** * 前端控制器 */ public static void frontControl(int order) throws InterruptedException { FrontController frontController = new FrontController(); if(order==1) { frontController.dispatchRequest("顾客","顾客"); System.out.println("\n"); } else if(order==2){ frontController.dispatchRequest("管理员","管理员"); System.out.println("\n"); } Thread.sleep(2000); } /** * 登录 */ public static boolean login(){ Scanner scanner=new Scanner(System.in); System.out.println("请选择登陆模式:\n" + "1、游客登录\n" + "2、管理员登录"); int isAdmin=scanner.nextInt(); return isAdmin != 1; } /** * 管理员模块 */ public static void Administrate(){ Administrator Admin=new Administrator(); Admin.show(); } /** * 游客菜单 */ public static boolean visitorMenu() throws ParseException, InterruptedException { boolean hasTicket=false; boolean exit=false; int order; while(!exit){ Thread.sleep(2000); System.out.println( "=======menu=======\n"+ "请选择要前往的地区:\n" + "1.票务中心\n" + "2.游乐场\n" + "3.表演会场\n" + "4.园区餐厅\n" + "5.纪念品商店\n" + "0.离开\n"+ "=======menu======="); Scanner sc=new Scanner(System.in); order=sc.nextInt(); switch (order){ case 0: exit=true; System.out.println("您已离开园区!欢迎下次光临!"); break; case 1: hasTicket=ticket(); break; case 2: if(hasTicket) facilityPlay(); else System.out.println("您还未购票,暂时不能入园!"); break; case 3: if(hasTicket) perform(); else System.out.println("您还未购票,暂时不能入园!"); break; case 4: if(hasTicket) restaurant(); else System.out.println("您还未购票,暂时不能入园!"); break; case 5: if(hasTicket) souvenirShop(); else System.out.println("您还未购票,暂时不能入园!"); break; default: System.out.println("指令错误!"); break; } } return hasTicket; } /** * 餐厅模块 */ public static void restaurant() { RestaurantSubsystem restaurant=new RestaurantSubsystem(); restaurant.show(); System.out.println("欢迎下次光临"); } /** * 票务模块 */ public static boolean ticket() throws ParseException { BuyTickets ticketing=new BuyTickets(); ticketing.show(); return ticketing.hasTicket; } /** * 游乐场模块 */ public static void facilityPlay() { FacilityPlay play=new FacilityPlay(); play.show(); } /** * 纪念品商店模块 */ public static void souvenirShop(){ SouvenirShopSubsystem souvenirShop=new SouvenirShopSubsystem(); souvenirShop.show(); System.out.println("欢迎下次光临!"); } /** * 表演模块 */ public static void perform() throws InterruptedException { Show perform=new Show(); perform.show(); System.out.println("欢迎下次光临!"); } /** * 地图显示 */ public static void showmap(){ System.out.format("\33[%dm%s",96,""); System.out.println(" " + " mm m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m\n" + " M M \n" + " # # \n" + " # # \n" + " # |-| # \n" + " # T D # \n" + " # 0 * * * m e * m * v # \n" + " # # Y 4 4 M # \n" + " # , , 9 , % T * # \n" + " # ; - } ~ ' ^ 0 % # \n" + " # ' ^ J 表演会场 # \n" + " # ( Q ] ' - - -* # \n" + " # __ } , ( ; ) # \n" + " # ^~~^ ^ ^ ^ ( * y ) # \n" + " # 大摆锤 (7' ^ ) # \n" + " # === * + *= === # \n" + " # 摩天轮 # \n" + " # x * * x # \n" + " # E l ] q g | # \n" + " # 6 ,- \\ * j ] S M M j # \n" + " # +~\\,/ /// F g r * 7 g 0 # \n" + " # ]- - ^ * * & = ' DQG_4#G # \n" + " # 过山车 B0D#0#g # \n" + " # +*@*M+\"*- # \n" + " # 餐厅 # \n" + " # # \n" + " # # \n" + " # # \n" + " # # \n" + " # ] l . # \n" + " # n @ & , # \n" + " # mX1 # \n" + " # ~ ~ ~^ ^ # \n" + " # *GATE* 票务中心 # \n" + " # * * # \n" + " ]g * * y' \n" + " ^9 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); System.out.format("\33[%dm%s",0,""); } }
ZhichenRen/DesignPattern
src/main/java/Main.java
2,015
/** * 管理员模块 */
block_comment
zh-cn
import FacadePattern.TotalGuide; import FrontController.FrontController; import BuyTicketsSubsystem.*; import Show.Show; import SouvenirShop.SouvenirShopSubsystem; import AdministratorSubsystem.*; import Restaurant.*; import FacilityPlaySubsystem.*; import java.text.ParseException; import java.util.Scanner; public class Main { public static void main(String[] args) throws ParseException, InterruptedException { // 最后的汇总写在这里 Scanner mainScanner=new Scanner(System.in); boolean isAdmin = login(); boolean needGuide=false; //游客模式 if(!isAdmin){ frontControl(1); showmap(); needGuide=needGuide(); //导游代理模式 if(needGuide) Guide(); else visitorMenu(); } //管理员模式 else{ frontControl(2); Administrate(); } } /** * 是否需要导游 */ public static boolean needGuide(){ System.out.println("本次嘉年华提供向导服务,请问您是否需要导游?\n" + "1、需要导游\n" + "2、不需要导游\n"); Scanner scanner=new Scanner(System.in); return scanner.nextInt()==1; } /** * 导游执行 */ public static void Guide(){ TotalGuide guide=new TotalGuide("阿P"); guide.buyTicket(); guide.play(); guide.watch(); guide.end(); } /** * 前端控制器 */ public static void frontControl(int order) throws InterruptedException { FrontController frontController = new FrontController(); if(order==1) { frontController.dispatchRequest("顾客","顾客"); System.out.println("\n"); } else if(order==2){ frontController.dispatchRequest("管理员","管理员"); System.out.println("\n"); } Thread.sleep(2000); } /** * 登录 */ public static boolean login(){ Scanner scanner=new Scanner(System.in); System.out.println("请选择登陆模式:\n" + "1、游客登录\n" + "2、管理员登录"); int isAdmin=scanner.nextInt(); return isAdmin != 1; } /** * 管理员 <SUF>*/ public static void Administrate(){ Administrator Admin=new Administrator(); Admin.show(); } /** * 游客菜单 */ public static boolean visitorMenu() throws ParseException, InterruptedException { boolean hasTicket=false; boolean exit=false; int order; while(!exit){ Thread.sleep(2000); System.out.println( "=======menu=======\n"+ "请选择要前往的地区:\n" + "1.票务中心\n" + "2.游乐场\n" + "3.表演会场\n" + "4.园区餐厅\n" + "5.纪念品商店\n" + "0.离开\n"+ "=======menu======="); Scanner sc=new Scanner(System.in); order=sc.nextInt(); switch (order){ case 0: exit=true; System.out.println("您已离开园区!欢迎下次光临!"); break; case 1: hasTicket=ticket(); break; case 2: if(hasTicket) facilityPlay(); else System.out.println("您还未购票,暂时不能入园!"); break; case 3: if(hasTicket) perform(); else System.out.println("您还未购票,暂时不能入园!"); break; case 4: if(hasTicket) restaurant(); else System.out.println("您还未购票,暂时不能入园!"); break; case 5: if(hasTicket) souvenirShop(); else System.out.println("您还未购票,暂时不能入园!"); break; default: System.out.println("指令错误!"); break; } } return hasTicket; } /** * 餐厅模块 */ public static void restaurant() { RestaurantSubsystem restaurant=new RestaurantSubsystem(); restaurant.show(); System.out.println("欢迎下次光临"); } /** * 票务模块 */ public static boolean ticket() throws ParseException { BuyTickets ticketing=new BuyTickets(); ticketing.show(); return ticketing.hasTicket; } /** * 游乐场模块 */ public static void facilityPlay() { FacilityPlay play=new FacilityPlay(); play.show(); } /** * 纪念品商店模块 */ public static void souvenirShop(){ SouvenirShopSubsystem souvenirShop=new SouvenirShopSubsystem(); souvenirShop.show(); System.out.println("欢迎下次光临!"); } /** * 表演模块 */ public static void perform() throws InterruptedException { Show perform=new Show(); perform.show(); System.out.println("欢迎下次光临!"); } /** * 地图显示 */ public static void showmap(){ System.out.format("\33[%dm%s",96,""); System.out.println(" " + " mm m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m m\n" + " M M \n" + " # # \n" + " # # \n" + " # |-| # \n" + " # T D # \n" + " # 0 * * * m e * m * v # \n" + " # # Y 4 4 M # \n" + " # , , 9 , % T * # \n" + " # ; - } ~ ' ^ 0 % # \n" + " # ' ^ J 表演会场 # \n" + " # ( Q ] ' - - -* # \n" + " # __ } , ( ; ) # \n" + " # ^~~^ ^ ^ ^ ( * y ) # \n" + " # 大摆锤 (7' ^ ) # \n" + " # === * + *= === # \n" + " # 摩天轮 # \n" + " # x * * x # \n" + " # E l ] q g | # \n" + " # 6 ,- \\ * j ] S M M j # \n" + " # +~\\,/ /// F g r * 7 g 0 # \n" + " # ]- - ^ * * & = ' DQG_4#G # \n" + " # 过山车 B0D#0#g # \n" + " # +*@*M+\"*- # \n" + " # 餐厅 # \n" + " # # \n" + " # # \n" + " # # \n" + " # # \n" + " # ] l . # \n" + " # n @ & , # \n" + " # mX1 # \n" + " # ~ ~ ~^ ^ # \n" + " # *GATE* 票务中心 # \n" + " # * * # \n" + " ]g * * y' \n" + " ^9 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"); System.out.format("\33[%dm%s",0,""); } }
false
1,817
12
2,015
8
2,175
10
2,015
8
2,722
15
false
false
false
false
false
true
52817_8
package cn.edu.neu.alink; import cn.edu.neu.alink.cons.ClassifierConstant; import com.alibaba.alink.operator.batch.BatchOperator; import com.alibaba.alink.operator.batch.source.CsvSourceBatchOp; import com.alibaba.alink.operator.batch.source.TextSourceBatchOp; import com.alibaba.alink.pipeline.LocalPredictor; import com.alibaba.alink.pipeline.Pipeline; import com.alibaba.alink.pipeline.PipelineModel; import com.alibaba.alink.pipeline.classification.LogisticRegression; import com.alibaba.alink.pipeline.classification.NaiveBayesTextClassifier; import com.alibaba.alink.pipeline.dataproc.Imputer; import com.alibaba.alink.pipeline.nlp.DocCountVectorizer; import com.alibaba.alink.pipeline.nlp.Segment; import com.alibaba.alink.pipeline.nlp.StopWordsRemover; import org.apache.flink.types.Row; import java.io.File; import java.util.List; /** * @author 32098 */ public class CommentClassifier { private static PipelineModel pipelineModel; public static void initNaiveBayesModel(){ pipelineModel = PipelineModel.load(ClassifierConstant.WEIBO_LR_MODEL_PATH); if(pipelineModel==null){ System.err.println("载入模型失败..."); System.out.println("开始构建模型..."); BatchOperator<?> sourceBatchOp = getCommentSourceOp(); Pipeline pipeline = new Pipeline( // 缺失值填充:null new Imputer().setSelectedCols("review").setOutputCols("featureText").setStrategy("value").setFillValue("null"), // 分词操作 new Segment().setSelectedCol("featureText"), // 去除停用词 new StopWordsRemover().setSelectedCol("featureText"), /* * TF, Term Frequency: 词频,生成特征向量的类型 * https://www.yuque.com/pinshu/alink_doc/7a529b8564228c01c31f2fa58c43f782 */ new DocCountVectorizer().setFeatureType("TF").setSelectedCol("featureText").setOutputCol("featureVector"), new NaiveBayesTextClassifier().setVectorCol("featureVector").setLabelCol("label").setPredictionCol("pred") ); pipelineModel = pipeline.fit(sourceBatchOp); pipelineModel.save(ClassifierConstant.WEIBO_NB_MODEL_PATH); try { // save 方法是将模型连接到了 sink 组件,还需要等到 BatchOperator.execute(),才会真正写出模型 BatchOperator.execute(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("模型构建成功!"); } public static void initLogisticRegressionModel(){ pipelineModel = PipelineModel.load(ClassifierConstant.WEIBO_LR_MODEL_PATH); if(pipelineModel==null){ System.err.println("载入模型失败..."); System.out.println("开始构建模型..."); BatchOperator<?> sourceBatchOp = getCommentSourceOp(); Pipeline pipeline = new Pipeline( // 缺失值填充:null new Imputer().setSelectedCols("review").setOutputCols("featureText").setStrategy("value").setFillValue("null"), // 分词操作 new Segment().setSelectedCol("featureText"), // 去除停用词 new StopWordsRemover().setSelectedCol("featureText"), /* * TF, Term Frequency: 词频,生成特征向量的类型 * https://www.yuque.com/pinshu/alink_doc/7a529b8564228c01c31f2fa58c43f782 */ new DocCountVectorizer().setFeatureType("TF").setSelectedCol("featureText").setOutputCol("featureVector"), new LogisticRegression().setVectorCol("featureVector").setLabelCol("label").setPredictionCol("pred") ); pipelineModel = pipeline.fit(sourceBatchOp); pipelineModel.save(ClassifierConstant.WEIBO_NB_MODEL_PATH); try { // save 方法是将模型连接到了 sink 组件,还需要等到 BatchOperator.execute(),才会真正写出模型 BatchOperator.execute(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("模型构建成功!"); } private static BatchOperator<?> getCommentSourceOp(){ return new CsvSourceBatchOp() .setFilePath(ClassifierConstant.DATASET_WEIBO_PATH) .setSchemaStr("label int, review string") .setIgnoreFirstLine(true); } public static String getClassification(String text){ if(pipelineModel==null){ System.err.println("As you didn't call initNaiveBayesModel() or initLogisticRegressionModel() before using getClassification(String text),\n" + "we will call initNaiveBayesModel() to set value for our inner attribute (pipelineModel) to get your text's Classification"); initNaiveBayesModel(); } try { // https://blog.csdn.net/Alink1024/article/details/107813310 LocalPredictor localPredictor = pipelineModel.collectLocalPredictor("review string"); // System.out.print(localPredictor.getOutputSchema()); Row row = Row.of(text); return String.valueOf(localPredictor.map(row).getField(3)); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) throws Exception { // Can't, we will use LocalPredictor // initNaiveBayesModel(); // System.out.println("------------------------------"); // TextSourceBatchOp textSourceBatchOp1 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/neg.txt".replace("/", File.separator)) // .setTextCol("review"); // pipelineModel.transform(textSourceBatchOp1).select(new String[]{"label", "pred", "review"}).sampleWithSize(20).print(); // // initLogisticRegressionModel(); // System.out.println("------------------------------"); // TextSourceBatchOp textSourceBatchOp2 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/pos.txt".replace("/", File.separator)) // .setTextCol("review"); // pipelineModel.transform(textSourceBatchOp2).select(new String[]{"label", "pred", "review"}).sampleWithSize(20).print(); // except to be 1(pos) System.out.println(CommentClassifier.getClassification("你真好")); // except to be 1(pos) System.out.println(CommentClassifier.getClassification("哇哦今年的春夏季衣服不错诶")); // except to be 0(neg) System.out.println(CommentClassifier.getClassification("去死吧")); // TextSourceBatchOp textSourceBatchOp1 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/neg.txt".replace("/", File.separator)) // .setTextCol("review"); // TextSourceBatchOp textSourceBatchOp2 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/pos.txt".replace("/", File.separator)) // .setTextCol("review"); // List<Row> negRows = textSourceBatchOp1.getDataSet().collect(); // List<Row> posRows = textSourceBatchOp2.getDataSet().collect(); // int acc = 0; // for (Row negRow : negRows) { // // except to be 0 // String text = getClassification((String) negRow.getField(0)); // System.out.println(text); // if("0".equals(text)){ // acc+=1; // } // } // for (Row posRow : posRows) { // // except to be 1 // String text = getClassification((String) posRow.getField(0)); // System.out.println(text); // if("0".equals(text)){ // acc+=1; // } // } // System.out.println("Acc: "+(double) acc/(negRows.size()+posRows.size())); } }
Zhifa-Liu/EmotionClassDemo
src/main/java/cn/edu/neu/alink/CommentClassifier.java
2,084
// 去除停用词
line_comment
zh-cn
package cn.edu.neu.alink; import cn.edu.neu.alink.cons.ClassifierConstant; import com.alibaba.alink.operator.batch.BatchOperator; import com.alibaba.alink.operator.batch.source.CsvSourceBatchOp; import com.alibaba.alink.operator.batch.source.TextSourceBatchOp; import com.alibaba.alink.pipeline.LocalPredictor; import com.alibaba.alink.pipeline.Pipeline; import com.alibaba.alink.pipeline.PipelineModel; import com.alibaba.alink.pipeline.classification.LogisticRegression; import com.alibaba.alink.pipeline.classification.NaiveBayesTextClassifier; import com.alibaba.alink.pipeline.dataproc.Imputer; import com.alibaba.alink.pipeline.nlp.DocCountVectorizer; import com.alibaba.alink.pipeline.nlp.Segment; import com.alibaba.alink.pipeline.nlp.StopWordsRemover; import org.apache.flink.types.Row; import java.io.File; import java.util.List; /** * @author 32098 */ public class CommentClassifier { private static PipelineModel pipelineModel; public static void initNaiveBayesModel(){ pipelineModel = PipelineModel.load(ClassifierConstant.WEIBO_LR_MODEL_PATH); if(pipelineModel==null){ System.err.println("载入模型失败..."); System.out.println("开始构建模型..."); BatchOperator<?> sourceBatchOp = getCommentSourceOp(); Pipeline pipeline = new Pipeline( // 缺失值填充:null new Imputer().setSelectedCols("review").setOutputCols("featureText").setStrategy("value").setFillValue("null"), // 分词操作 new Segment().setSelectedCol("featureText"), // 去除停用词 new StopWordsRemover().setSelectedCol("featureText"), /* * TF, Term Frequency: 词频,生成特征向量的类型 * https://www.yuque.com/pinshu/alink_doc/7a529b8564228c01c31f2fa58c43f782 */ new DocCountVectorizer().setFeatureType("TF").setSelectedCol("featureText").setOutputCol("featureVector"), new NaiveBayesTextClassifier().setVectorCol("featureVector").setLabelCol("label").setPredictionCol("pred") ); pipelineModel = pipeline.fit(sourceBatchOp); pipelineModel.save(ClassifierConstant.WEIBO_NB_MODEL_PATH); try { // save 方法是将模型连接到了 sink 组件,还需要等到 BatchOperator.execute(),才会真正写出模型 BatchOperator.execute(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("模型构建成功!"); } public static void initLogisticRegressionModel(){ pipelineModel = PipelineModel.load(ClassifierConstant.WEIBO_LR_MODEL_PATH); if(pipelineModel==null){ System.err.println("载入模型失败..."); System.out.println("开始构建模型..."); BatchOperator<?> sourceBatchOp = getCommentSourceOp(); Pipeline pipeline = new Pipeline( // 缺失值填充:null new Imputer().setSelectedCols("review").setOutputCols("featureText").setStrategy("value").setFillValue("null"), // 分词操作 new Segment().setSelectedCol("featureText"), // 去除 <SUF> new StopWordsRemover().setSelectedCol("featureText"), /* * TF, Term Frequency: 词频,生成特征向量的类型 * https://www.yuque.com/pinshu/alink_doc/7a529b8564228c01c31f2fa58c43f782 */ new DocCountVectorizer().setFeatureType("TF").setSelectedCol("featureText").setOutputCol("featureVector"), new LogisticRegression().setVectorCol("featureVector").setLabelCol("label").setPredictionCol("pred") ); pipelineModel = pipeline.fit(sourceBatchOp); pipelineModel.save(ClassifierConstant.WEIBO_NB_MODEL_PATH); try { // save 方法是将模型连接到了 sink 组件,还需要等到 BatchOperator.execute(),才会真正写出模型 BatchOperator.execute(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("模型构建成功!"); } private static BatchOperator<?> getCommentSourceOp(){ return new CsvSourceBatchOp() .setFilePath(ClassifierConstant.DATASET_WEIBO_PATH) .setSchemaStr("label int, review string") .setIgnoreFirstLine(true); } public static String getClassification(String text){ if(pipelineModel==null){ System.err.println("As you didn't call initNaiveBayesModel() or initLogisticRegressionModel() before using getClassification(String text),\n" + "we will call initNaiveBayesModel() to set value for our inner attribute (pipelineModel) to get your text's Classification"); initNaiveBayesModel(); } try { // https://blog.csdn.net/Alink1024/article/details/107813310 LocalPredictor localPredictor = pipelineModel.collectLocalPredictor("review string"); // System.out.print(localPredictor.getOutputSchema()); Row row = Row.of(text); return String.valueOf(localPredictor.map(row).getField(3)); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) throws Exception { // Can't, we will use LocalPredictor // initNaiveBayesModel(); // System.out.println("------------------------------"); // TextSourceBatchOp textSourceBatchOp1 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/neg.txt".replace("/", File.separator)) // .setTextCol("review"); // pipelineModel.transform(textSourceBatchOp1).select(new String[]{"label", "pred", "review"}).sampleWithSize(20).print(); // // initLogisticRegressionModel(); // System.out.println("------------------------------"); // TextSourceBatchOp textSourceBatchOp2 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/pos.txt".replace("/", File.separator)) // .setTextCol("review"); // pipelineModel.transform(textSourceBatchOp2).select(new String[]{"label", "pred", "review"}).sampleWithSize(20).print(); // except to be 1(pos) System.out.println(CommentClassifier.getClassification("你真好")); // except to be 1(pos) System.out.println(CommentClassifier.getClassification("哇哦今年的春夏季衣服不错诶")); // except to be 0(neg) System.out.println(CommentClassifier.getClassification("去死吧")); // TextSourceBatchOp textSourceBatchOp1 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/neg.txt".replace("/", File.separator)) // .setTextCol("review"); // TextSourceBatchOp textSourceBatchOp2 = new TextSourceBatchOp() // .setFilePath(System.getProperty("user.dir")+"/src/main/java/cn/edu/neu/zoom/data/pos.txt".replace("/", File.separator)) // .setTextCol("review"); // List<Row> negRows = textSourceBatchOp1.getDataSet().collect(); // List<Row> posRows = textSourceBatchOp2.getDataSet().collect(); // int acc = 0; // for (Row negRow : negRows) { // // except to be 0 // String text = getClassification((String) negRow.getField(0)); // System.out.println(text); // if("0".equals(text)){ // acc+=1; // } // } // for (Row posRow : posRows) { // // except to be 1 // String text = getClassification((String) posRow.getField(0)); // System.out.println(text); // if("0".equals(text)){ // acc+=1; // } // } // System.out.println("Acc: "+(double) acc/(negRows.size()+posRows.size())); } }
false
1,823
8
2,084
7
2,114
6
2,084
7
2,495
11
false
false
false
false
false
true
63631_5
package zwh.move; import zwh.exception.UnvalidPointException; import zwh.map.MapDirection; import zwh.map.MapSymble; import zwh.map.SokobanMap; import zwh.map.point.Point; import zwh.move.rule.DefaultMapMoveRule; import zwh.move.rule.IMapMoveRule; public class ManMover { /** * 使用默认的DefaultMapMoveRule,如果往该方向移动一格是合法的移动,则返回移动后的SokobanMap,否则返回原来的SokobanMap * @param map * @param direction * @return */ public static SokobanMap moveOneStep(SokobanMap map, int direction){ return ManMover.moveOneStep(map, direction, new DefaultMapMoveRule()); } /** * 传入指定的IMapMoveRule,如果往该方向移动一格是合法的移动,则返回移动后的SokobanMap,否则返回原来的SokobanMap * @param map * @param direction * @return */ public static SokobanMap moveOneStep(SokobanMap map, int direction, IMapMoveRule mapRule) { switch (direction) { case MapDirection.UP: return ManMover.up(map, mapRule); case MapDirection.DOWN: return ManMover.down(map, mapRule); case MapDirection.LEFT: return ManMover.left(map, mapRule); case MapDirection.RIGHT: return ManMover.right(map, mapRule); default: break; } return null; } public static SokobanMap up(SokobanMap map, IMapMoveRule mapRule) { SokobanMap resMap = ManMover.move(map, MapDirection.UP, mapRule); return resMap; } public static SokobanMap up(SokobanMap map) { return ManMover.up(map, new DefaultMapMoveRule()); } public static SokobanMap down(SokobanMap map, IMapMoveRule mapRule){ SokobanMap resMap = ManMover.move(map, MapDirection.DOWN, mapRule); return resMap; } public static SokobanMap down(SokobanMap map){ return ManMover.down(map, new DefaultMapMoveRule()); } public static SokobanMap left(SokobanMap map, IMapMoveRule mapRule){ SokobanMap resMap = ManMover.move(map, MapDirection.LEFT, mapRule); return resMap; } public static SokobanMap left(SokobanMap map){ return ManMover.left(map, new DefaultMapMoveRule()); } public static SokobanMap right(SokobanMap map, IMapMoveRule mapRule){ SokobanMap resMap = ManMover.move(map, MapDirection.RIGHT, mapRule); return resMap; } public static SokobanMap right(SokobanMap map){ return ManMover.right(map, new DefaultMapMoveRule()); } /** * 每次移动一格,修改传入的地图参数,返回新的地图 * * @param map * @param movePoint * @param direction * @param mapRule * @return */ private static SokobanMap move(SokobanMap map, int direction, IMapMoveRule mapRule) { SokobanMap resMap = null; //人的坐标Point Point movePoint = map.manPoint; //目标坐标 Point nextPoint = ManMover.getTargetPoint(movePoint, direction); //目标坐标的下一个点 Point nextNextPoint = ManMover.getTargetPoint(nextPoint, direction); try { //人坐标点的字符 char moveChar = map.getCharByPoint(movePoint); //目标坐标的字符 char goalChar = map.getCharByPoint(nextPoint); //判断需要移动的物体是否为人(只有人能被移动) if (MapSymble.isMan(moveChar)) { //判断人的目的地点是否为墙壁或者另一个人 if (goalChar == MapSymble.WALL_CHAR || MapSymble.isMan(goalChar)) { resMap = map; }else if(goalChar == MapSymble.GROUND_CHAR || goalChar == MapSymble.GOAL_CHAR){//判断人的目的地点是否为地板或目标地点,是则可以移动 //修改人移动前的坐标点的字符 resMap = map.modifyPoint(movePoint, mapRule.getCharOfMoveAfterMove(moveChar)); //修改目标点的字符 resMap = resMap.modifyPoint(nextPoint, mapRule.getCharOfGoalAfterMove(goalChar, moveChar)); //修改路径 resMap = new SokobanMap(resMap.getMapList(), resMap.path + MapDirection.getPath(direction)); }else if(MapSymble.isBox(goalChar)){//判断人的目的地点是否为箱子 char nextNextChar = map.getCharByPoint(nextNextPoint); //判断人的目标地点的下个地点是否为地板和goal,如果是则可以移动,否则不能移动 if(nextNextChar == MapSymble.GROUND_CHAR || nextNextChar == MapSymble.GOAL_CHAR){ resMap = map.modifyPoint(movePoint, mapRule.getCharOfMoveAfterMove(moveChar)); resMap = resMap.modifyPoint(nextPoint, mapRule.getCharOfGoalAfterMove(goalChar, moveChar)); resMap = resMap.modifyPoint(nextNextPoint, mapRule.getCharOfGoalAfterMove(nextNextChar, goalChar)); resMap = new SokobanMap(resMap.getMapList(), resMap.path + MapDirection.getPath(direction).toUpperCase()); }else{ resMap = map; } } }else{ resMap = map; } return resMap; } catch (UnvalidPointException e) { System.out.println("ManMover>move: " + e.getMessage()); // e.printStackTrace(); return map; } } /** * 返回新的地图 * * @param mapList * 地图 * @param movePoint * 需要移动的物体所在坐标 * @param direction * 移动方向 * @return 1.map 2.null:不可移动 */ // private static SokobanMap move(SokobanMap map, Point movePoint, int // direction, IMapMoveRule mapRule) { // SokobanMap resMap; // Point nextPoint = ManMover.getTargetPoint(movePoint, direction); // char moveChar; // char targetChar; // try { // moveChar = map.getCharByPoint(movePoint); // targetChar = map.getCharByPoint(nextPoint); // //如果为下面情况,则表明可以移动 // if(moveChar == MapSymble.GOAL_CHAR // || moveChar == MapSymble.GROUND_CHAR){ // return map; // } // //如果为下面的情况则表明不能移动 // if (targetChar == MapSymble.WALL_CHAR // || targetChar == MapSymble.MAN_CHAR // || targetChar == MapSymble.MAN_ON_GOAL_CHAR // || moveChar == MapSymble.WALL_CHAR // || (moveChar == MapSymble.BOX_CHAR && targetChar == MapSymble.BOX_CHAR) // || (moveChar == MapSymble.BOX_ON_GOAL_CHAR && targetChar == // MapSymble.BOX_CHAR) // || (moveChar == MapSymble.BOX_CHAR && targetChar == // MapSymble.BOX_ON_GOAL_CHAR) // || (moveChar == MapSymble.BOX_ON_GOAL_CHAR && targetChar == // MapSymble.BOX_ON_GOAL_CHAR)) { // return null; // } // resMap = ManMover.move(map, nextPoint, direction, mapRule); // if(resMap != null){ // resMap = resMap.modifyPoint(nextPoint, // mapRule.getCharOfGoalAfterMove(targetChar, moveChar)); // resMap = resMap.modifyPoint(movePoint, // mapRule.getCharOfMoveAfterMove(moveChar)); // return resMap; // } // return null; // } catch (Exception e) { // System.out.println(e.getMessage()); // return null; // } // } /** * 根据当前Point,获取往目标方向前进一格的Point * @param currPoint 当前Point * @param direction 目标方向 * @return 前进一格后的Point */ public static Point getTargetPoint(Point currPoint, int direction) { Point goalPoint; switch (direction) { case MapDirection.UP: goalPoint = new Point(currPoint.x - 1, currPoint.y); break; case MapDirection.DOWN: goalPoint = new Point(currPoint.x + 1, currPoint.y); break; case MapDirection.LEFT: goalPoint = new Point(currPoint.x, currPoint.y - 1); break; case MapDirection.RIGHT: goalPoint = new Point(currPoint.x, currPoint.y + 1); break; default: return new Point(-1, -1); } return goalPoint; } }
ZhongWenhui1995/SokobanSolver
src/zwh/move/ManMover.java
2,353
//目标坐标的下一个点
line_comment
zh-cn
package zwh.move; import zwh.exception.UnvalidPointException; import zwh.map.MapDirection; import zwh.map.MapSymble; import zwh.map.SokobanMap; import zwh.map.point.Point; import zwh.move.rule.DefaultMapMoveRule; import zwh.move.rule.IMapMoveRule; public class ManMover { /** * 使用默认的DefaultMapMoveRule,如果往该方向移动一格是合法的移动,则返回移动后的SokobanMap,否则返回原来的SokobanMap * @param map * @param direction * @return */ public static SokobanMap moveOneStep(SokobanMap map, int direction){ return ManMover.moveOneStep(map, direction, new DefaultMapMoveRule()); } /** * 传入指定的IMapMoveRule,如果往该方向移动一格是合法的移动,则返回移动后的SokobanMap,否则返回原来的SokobanMap * @param map * @param direction * @return */ public static SokobanMap moveOneStep(SokobanMap map, int direction, IMapMoveRule mapRule) { switch (direction) { case MapDirection.UP: return ManMover.up(map, mapRule); case MapDirection.DOWN: return ManMover.down(map, mapRule); case MapDirection.LEFT: return ManMover.left(map, mapRule); case MapDirection.RIGHT: return ManMover.right(map, mapRule); default: break; } return null; } public static SokobanMap up(SokobanMap map, IMapMoveRule mapRule) { SokobanMap resMap = ManMover.move(map, MapDirection.UP, mapRule); return resMap; } public static SokobanMap up(SokobanMap map) { return ManMover.up(map, new DefaultMapMoveRule()); } public static SokobanMap down(SokobanMap map, IMapMoveRule mapRule){ SokobanMap resMap = ManMover.move(map, MapDirection.DOWN, mapRule); return resMap; } public static SokobanMap down(SokobanMap map){ return ManMover.down(map, new DefaultMapMoveRule()); } public static SokobanMap left(SokobanMap map, IMapMoveRule mapRule){ SokobanMap resMap = ManMover.move(map, MapDirection.LEFT, mapRule); return resMap; } public static SokobanMap left(SokobanMap map){ return ManMover.left(map, new DefaultMapMoveRule()); } public static SokobanMap right(SokobanMap map, IMapMoveRule mapRule){ SokobanMap resMap = ManMover.move(map, MapDirection.RIGHT, mapRule); return resMap; } public static SokobanMap right(SokobanMap map){ return ManMover.right(map, new DefaultMapMoveRule()); } /** * 每次移动一格,修改传入的地图参数,返回新的地图 * * @param map * @param movePoint * @param direction * @param mapRule * @return */ private static SokobanMap move(SokobanMap map, int direction, IMapMoveRule mapRule) { SokobanMap resMap = null; //人的坐标Point Point movePoint = map.manPoint; //目标坐标 Point nextPoint = ManMover.getTargetPoint(movePoint, direction); //目标 <SUF> Point nextNextPoint = ManMover.getTargetPoint(nextPoint, direction); try { //人坐标点的字符 char moveChar = map.getCharByPoint(movePoint); //目标坐标的字符 char goalChar = map.getCharByPoint(nextPoint); //判断需要移动的物体是否为人(只有人能被移动) if (MapSymble.isMan(moveChar)) { //判断人的目的地点是否为墙壁或者另一个人 if (goalChar == MapSymble.WALL_CHAR || MapSymble.isMan(goalChar)) { resMap = map; }else if(goalChar == MapSymble.GROUND_CHAR || goalChar == MapSymble.GOAL_CHAR){//判断人的目的地点是否为地板或目标地点,是则可以移动 //修改人移动前的坐标点的字符 resMap = map.modifyPoint(movePoint, mapRule.getCharOfMoveAfterMove(moveChar)); //修改目标点的字符 resMap = resMap.modifyPoint(nextPoint, mapRule.getCharOfGoalAfterMove(goalChar, moveChar)); //修改路径 resMap = new SokobanMap(resMap.getMapList(), resMap.path + MapDirection.getPath(direction)); }else if(MapSymble.isBox(goalChar)){//判断人的目的地点是否为箱子 char nextNextChar = map.getCharByPoint(nextNextPoint); //判断人的目标地点的下个地点是否为地板和goal,如果是则可以移动,否则不能移动 if(nextNextChar == MapSymble.GROUND_CHAR || nextNextChar == MapSymble.GOAL_CHAR){ resMap = map.modifyPoint(movePoint, mapRule.getCharOfMoveAfterMove(moveChar)); resMap = resMap.modifyPoint(nextPoint, mapRule.getCharOfGoalAfterMove(goalChar, moveChar)); resMap = resMap.modifyPoint(nextNextPoint, mapRule.getCharOfGoalAfterMove(nextNextChar, goalChar)); resMap = new SokobanMap(resMap.getMapList(), resMap.path + MapDirection.getPath(direction).toUpperCase()); }else{ resMap = map; } } }else{ resMap = map; } return resMap; } catch (UnvalidPointException e) { System.out.println("ManMover>move: " + e.getMessage()); // e.printStackTrace(); return map; } } /** * 返回新的地图 * * @param mapList * 地图 * @param movePoint * 需要移动的物体所在坐标 * @param direction * 移动方向 * @return 1.map 2.null:不可移动 */ // private static SokobanMap move(SokobanMap map, Point movePoint, int // direction, IMapMoveRule mapRule) { // SokobanMap resMap; // Point nextPoint = ManMover.getTargetPoint(movePoint, direction); // char moveChar; // char targetChar; // try { // moveChar = map.getCharByPoint(movePoint); // targetChar = map.getCharByPoint(nextPoint); // //如果为下面情况,则表明可以移动 // if(moveChar == MapSymble.GOAL_CHAR // || moveChar == MapSymble.GROUND_CHAR){ // return map; // } // //如果为下面的情况则表明不能移动 // if (targetChar == MapSymble.WALL_CHAR // || targetChar == MapSymble.MAN_CHAR // || targetChar == MapSymble.MAN_ON_GOAL_CHAR // || moveChar == MapSymble.WALL_CHAR // || (moveChar == MapSymble.BOX_CHAR && targetChar == MapSymble.BOX_CHAR) // || (moveChar == MapSymble.BOX_ON_GOAL_CHAR && targetChar == // MapSymble.BOX_CHAR) // || (moveChar == MapSymble.BOX_CHAR && targetChar == // MapSymble.BOX_ON_GOAL_CHAR) // || (moveChar == MapSymble.BOX_ON_GOAL_CHAR && targetChar == // MapSymble.BOX_ON_GOAL_CHAR)) { // return null; // } // resMap = ManMover.move(map, nextPoint, direction, mapRule); // if(resMap != null){ // resMap = resMap.modifyPoint(nextPoint, // mapRule.getCharOfGoalAfterMove(targetChar, moveChar)); // resMap = resMap.modifyPoint(movePoint, // mapRule.getCharOfMoveAfterMove(moveChar)); // return resMap; // } // return null; // } catch (Exception e) { // System.out.println(e.getMessage()); // return null; // } // } /** * 根据当前Point,获取往目标方向前进一格的Point * @param currPoint 当前Point * @param direction 目标方向 * @return 前进一格后的Point */ public static Point getTargetPoint(Point currPoint, int direction) { Point goalPoint; switch (direction) { case MapDirection.UP: goalPoint = new Point(currPoint.x - 1, currPoint.y); break; case MapDirection.DOWN: goalPoint = new Point(currPoint.x + 1, currPoint.y); break; case MapDirection.LEFT: goalPoint = new Point(currPoint.x, currPoint.y - 1); break; case MapDirection.RIGHT: goalPoint = new Point(currPoint.x, currPoint.y + 1); break; default: return new Point(-1, -1); } return goalPoint; } }
false
2,058
7
2,353
8
2,388
7
2,353
8
2,764
13
false
false
false
false
false
true
27093_5
package com.zgl.util.secure.util; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.zgl.util.NumberUtil; import com.zgl.util.secure.enums.EnumCipherAlgorithm; import com.zgl.util.secure.enums.EnumKeyAlgorithm; /** * 加解密工具类 * * @author ZGL * */ public class CipherUtil { /** * 加密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param strHexKey 16进制字符串钥匙 * @param byteData 待加密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] encrpty(EnumCipherAlgorithm cipherAlgorithm, String strHexKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { return encrpty(cipherAlgorithm, NumberUtil.strHexToBytes(strHexKey), byteData); } /** * 加密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteKey 二进制钥匙 * @param byteData 待加密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] encrpty(EnumCipherAlgorithm cipherAlgorithm, byte[] byteKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { Security.addProvider(new BouncyCastleProvider()); // 生成秘密密钥或公钥 Key key = null; switch (cipherAlgorithm.getKeyAlgorithm()) { case DES: case DESede: case AES: case IDEA: { key = new SecretKeySpec(byteKey, cipherAlgorithm.getKeyAlgorithm().name()); break; } case RSA: case ElGamal: { try { // 尝试获取公钥 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePublic(x509EncodedKeySpec); break; } catch (Exception e) { try { // 尝试获取私钥 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePrivate(pkcs8EncodedKeySpec); break; } catch (Exception e2) { break; } } } default: break; } return encrpty(cipherAlgorithm, key, byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteData 待解密数据 * @param key 钥匙 * @return * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws Exception */ public static byte[] encrpty(EnumCipherAlgorithm cipherAlgorithm, Key key, byte[] byteData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String algorithm = key.getAlgorithm(); if(cipherAlgorithm != null){ algorithm = cipherAlgorithm.getValue(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param strHexKey 16进制字符串钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, String strHexKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { return decrypt(cipherAlgorithm, NumberUtil.strHexToBytes(strHexKey), byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteKey 二进制钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, byte[] byteKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { Security.addProvider(new BouncyCastleProvider()); // 生成秘密密钥或公钥 Key key = null; switch (cipherAlgorithm.getKeyAlgorithm()) { case DES: case DESede: case AES: case IDEA: { key = new SecretKeySpec(byteKey, cipherAlgorithm.getKeyAlgorithm().name()); break; } case RSA: case ElGamal: { try { // 尝试获取私钥 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePrivate(pkcs8EncodedKeySpec); break; } catch (Exception e) { try { // 尝试获取公钥 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePublic(x509EncodedKeySpec); break; } catch (Exception e2) { break; } } } default: break; } return decrypt(cipherAlgorithm, key, byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param key 钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, Key key, byte[] byteData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String algorithm = key.getAlgorithm(); if(cipherAlgorithm != null){ algorithm = cipherAlgorithm.getValue(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(byteData); } public static void main(String[] args) { try { String dataString = "ZGL"; for (EnumCipherAlgorithm cipherAlgorithm : EnumCipherAlgorithm.values()) { System.out.println(cipherAlgorithm.getValue()); if(EnumKeyAlgorithm.getSymmetric().contains(cipherAlgorithm.getKeyAlgorithm())){ SecretKey secretKey = KeyUtil.generateKey(cipherAlgorithm.getKeyAlgorithm(), null); byte[] e = encrpty(cipherAlgorithm,NumberUtil.bytesToStrHex(secretKey.getEncoded()), dataString.getBytes()); System.out.println("加密后数据: " + NumberUtil.bytesToStrHex(e)); byte[] d = decrypt(cipherAlgorithm, secretKey.getEncoded(), e); System.out.println("解密后数据: " + new String(d)); }else{ KeyPair keyPair = KeyUtil.generateKeyPair(cipherAlgorithm.getKeyAlgorithm(), null); byte[] e = encrpty(cipherAlgorithm, keyPair.getPublic().getEncoded(),dataString.getBytes()); System.out.println("加密后数据: " + NumberUtil.bytesToStrHex(e)); byte[] d = decrypt(cipherAlgorithm, keyPair.getPrivate().getEncoded(), e); System.out.println("解密后数据: " + new String(d)); } System.out.print("\n"); } } catch (Exception e) { e.printStackTrace(); } } }
ZhouGaoliang/secure-util
src/main/java/com/zgl/util/secure/util/CipherUtil.java
2,278
// 尝试获取私钥
line_comment
zh-cn
package com.zgl.util.secure.util; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.zgl.util.NumberUtil; import com.zgl.util.secure.enums.EnumCipherAlgorithm; import com.zgl.util.secure.enums.EnumKeyAlgorithm; /** * 加解密工具类 * * @author ZGL * */ public class CipherUtil { /** * 加密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param strHexKey 16进制字符串钥匙 * @param byteData 待加密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] encrpty(EnumCipherAlgorithm cipherAlgorithm, String strHexKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { return encrpty(cipherAlgorithm, NumberUtil.strHexToBytes(strHexKey), byteData); } /** * 加密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteKey 二进制钥匙 * @param byteData 待加密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] encrpty(EnumCipherAlgorithm cipherAlgorithm, byte[] byteKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { Security.addProvider(new BouncyCastleProvider()); // 生成秘密密钥或公钥 Key key = null; switch (cipherAlgorithm.getKeyAlgorithm()) { case DES: case DESede: case AES: case IDEA: { key = new SecretKeySpec(byteKey, cipherAlgorithm.getKeyAlgorithm().name()); break; } case RSA: case ElGamal: { try { // 尝试获取公钥 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePublic(x509EncodedKeySpec); break; } catch (Exception e) { try { // 尝试 <SUF> PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePrivate(pkcs8EncodedKeySpec); break; } catch (Exception e2) { break; } } } default: break; } return encrpty(cipherAlgorithm, key, byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteData 待解密数据 * @param key 钥匙 * @return * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws Exception */ public static byte[] encrpty(EnumCipherAlgorithm cipherAlgorithm, Key key, byte[] byteData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String algorithm = key.getAlgorithm(); if(cipherAlgorithm != null){ algorithm = cipherAlgorithm.getValue(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param strHexKey 16进制字符串钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, String strHexKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { return decrypt(cipherAlgorithm, NumberUtil.strHexToBytes(strHexKey), byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param byteKey 二进制钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, byte[] byteKey, byte[] byteData) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { Security.addProvider(new BouncyCastleProvider()); // 生成秘密密钥或公钥 Key key = null; switch (cipherAlgorithm.getKeyAlgorithm()) { case DES: case DESede: case AES: case IDEA: { key = new SecretKeySpec(byteKey, cipherAlgorithm.getKeyAlgorithm().name()); break; } case RSA: case ElGamal: { try { // 尝试获取私钥 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePrivate(pkcs8EncodedKeySpec); break; } catch (Exception e) { try { // 尝试获取公钥 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( byteKey); key = KeyFactory.getInstance(cipherAlgorithm.getKeyAlgorithm().name()) .generatePublic(x509EncodedKeySpec); break; } catch (Exception e2) { break; } } } default: break; } return decrypt(cipherAlgorithm, key, byteData); } /** * 解密,非对称加密一般来说是公钥加密,私钥解密 * @param cipherAlgorithm 加密算法 * @param key 钥匙 * @param byteData 待解密数据 * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ public static byte[] decrypt(EnumCipherAlgorithm cipherAlgorithm, Key key, byte[] byteData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { String algorithm = key.getAlgorithm(); if(cipherAlgorithm != null){ algorithm = cipherAlgorithm.getValue(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(byteData); } public static void main(String[] args) { try { String dataString = "ZGL"; for (EnumCipherAlgorithm cipherAlgorithm : EnumCipherAlgorithm.values()) { System.out.println(cipherAlgorithm.getValue()); if(EnumKeyAlgorithm.getSymmetric().contains(cipherAlgorithm.getKeyAlgorithm())){ SecretKey secretKey = KeyUtil.generateKey(cipherAlgorithm.getKeyAlgorithm(), null); byte[] e = encrpty(cipherAlgorithm,NumberUtil.bytesToStrHex(secretKey.getEncoded()), dataString.getBytes()); System.out.println("加密后数据: " + NumberUtil.bytesToStrHex(e)); byte[] d = decrypt(cipherAlgorithm, secretKey.getEncoded(), e); System.out.println("解密后数据: " + new String(d)); }else{ KeyPair keyPair = KeyUtil.generateKeyPair(cipherAlgorithm.getKeyAlgorithm(), null); byte[] e = encrpty(cipherAlgorithm, keyPair.getPublic().getEncoded(),dataString.getBytes()); System.out.println("加密后数据: " + NumberUtil.bytesToStrHex(e)); byte[] d = decrypt(cipherAlgorithm, keyPair.getPrivate().getEncoded(), e); System.out.println("解密后数据: " + new String(d)); } System.out.print("\n"); } } catch (Exception e) { e.printStackTrace(); } } }
false
2,078
7
2,278
6
2,336
6
2,278
6
3,331
14
false
false
false
false
false
true
39797_10
package com.example.steven.fzxyactivity.module.main.View.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.RelativeLayout; import com.example.steven.fzxyactivity.Constant.Constants; import com.example.steven.fzxyactivity.Entity.MessageEntity; import com.example.steven.fzxyactivity.Entity.MyActivityEntity; import com.example.steven.fzxyactivity.R; import com.example.steven.fzxyactivity.common.util.LoadingState; import com.example.steven.fzxyactivity.common.util.NetWorkUtil; import com.example.steven.fzxyactivity.common.util.OkUtils; import com.example.steven.fzxyactivity.common.util.SnackbarUtil; import com.example.steven.fzxyactivity.common.util.SpUtils; import com.example.steven.fzxyactivity.common.util.ToastUtil; import com.example.steven.fzxyactivity.common.util.customview.QQListview; import com.example.steven.fzxyactivity.common.util.customview.XHLoadingView; import com.example.steven.fzxyactivity.materialdesign.utils.DialogAction; import com.example.steven.fzxyactivity.materialdesign.views.MaterialDialog; import com.example.steven.fzxyactivity.module.activitydetail.ActivityDeatailActivity; import com.example.steven.fzxyactivity.module.main.View.Fragment.adapter.MessageAdapter; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import okhttp3.Call; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * to handle interaction events. * Use the {@link MessageFrament#newInstance} factory method to * create an instance of this fragment. */ public class MessageFrament extends android.app.Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; @Bind(R.id.rl_message) RelativeLayout rlMessage; @Bind(R.id.lv_loading) XHLoadingView lvLoading; @Bind(R.id.listview_qq) QQListview listviewQq; private static final String LOADING_STATE="state"; private static final String LOADING="loading"; private static final String LOADING_EMPTY="empty"; private static final String LOADING_NONETWORK="nonet"; private static final String LOADING_ERROR="error"; private String mLoadState; List<MessageEntity> mDatas; MessageAdapter adapter; String content=""; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private LinearLayoutManager mLinearLayoutManager; public MessageFrament() { // Required empty public constructor } public static MessageFrament newInstance(String param1, String param2) { MessageFrament fragment = new MessageFrament(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } mLinearLayoutManager = new LinearLayoutManager(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_message_frament, container, false); ButterKnife.bind(this, view); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); lvLoading.withLoadEmptyText("≥﹏≤ , 啥也木有 !").withEmptyIcon(R.drawable.disk_file_no_data).withBtnEmptyEnnable(false) .withErrorIco(R.drawable.ic_chat_empty).withLoadErrorText("(῀( ˙᷄ỏ˙᷅ )῀)ᵒᵐᵍᵎᵎᵎ,我家程序猿跑路了 !").withBtnErrorText("臭狗屎!!!") .withLoadNoNetworkText("你挡着信号啦o( ̄ヘ ̄o)☞ᗒᗒ 你走").withNoNetIcon(R.drawable.ic_chat_empty).withBtnNoNetText("网弄好了,重试") .withLoadingIcon(R.drawable.loading_animation).withLoadingText("加载中...").withOnRetryListener(new XHLoadingView.OnRetryListener() { @Override public void onRetry() { SnackbarUtil.show(lvLoading,"已经在努力重试了",0); } }).build(); if (!NetWorkUtil.isNetWorkConnected(getActivity())){ lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_ERROR); }else { //加载中 lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_LOADING); String url = Constants.ServerUrl + "ses/searchActivitySes/" + SpUtils.getString(getActivity(), "userId"); //String url = Constants.ServerUrl + "ses/searchActivitySes/sf"; OkUtils.get(url, new StringCallback() { @Override public void onError(Call call, Exception e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_ERROR); } }); } @Override public void onResponse(String response) { try { if (response.equals("null")){ //null 没有活动 getActivity().runOnUiThread(new Runnable() { @Override public void run() { lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_EMPTY); } }); }else { final JSONObject jsonObject = new JSONObject(response); final JSONArray array = jsonObject.getJSONArray("activitysessionmessage"); if (array.getJSONObject(0).getString("code").equals("1")) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { lvLoading.setVisibility(View.GONE); mDatas= new ArrayList<MessageEntity>(); for (int i=0;i<array.length();i++){ try { MessageEntity entity=new MessageEntity(); entity.setMessage(array.getJSONObject(i).getString("message")); entity.setMessageId(array.getJSONObject(i).getString("messageId")); entity.setMessageTime("消息时间:"+array.getJSONObject(i).getString("messageTime")); entity.setUserId(array.getJSONObject(i).getString("userId")); entity.setUserName("用户名:"+array.getJSONObject(i).getString("userName")); mDatas.add(entity); } catch (JSONException e) { e.printStackTrace(); } } adapter=new MessageAdapter(getActivity(),mDatas); listviewQq.setAdapter(adapter); listviewQq.setDelButtonClickListener(new QQListview.DelButtonClickListener() { @Override public void clickHappend(int position) { //网络请求操作删除 try { deleteMsg(array.getJSONObject(position).getString("messageId"),position); } catch (JSONException e) { e.printStackTrace(); } } }); listviewQq.setEditButtonClickListener(new QQListview.EditButtonClickListener() { @Override public void clickEditHappend(final int position) { //编辑操作 new MaterialDialog.Builder(getActivity()) .title("修改消息") .content("修改您的活动消息") .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_WORDS) .positiveText("提交") .onPositive(new MaterialDialog .SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { try { modifyMsg(content,array.getJSONObject(position).getString("messageId")); } catch (JSONException e) { e.printStackTrace(); } } }) .alwaysCallInputCallback() .input(R.string.input, 0, false, new MaterialDialog.InputCallback() { @Override public void onInput(MaterialDialog dialog, CharSequence input) { if (!input.toString().equals ("")) { content = input.toString(); } } }).show(); } }); listviewQq.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //点击操作,跳进消息详情 } }); } }); } } } catch (JSONException e) { e.printStackTrace(); } } }); } } private void modifyMsg(String content,String id) { String url = Constants.ServerUrl + "ses/updateActivitySes"; Map<String, String> map = new HashMap<>(); map.put("MessageId", id); map.put("UserId", SpUtils.getString(getActivity(),"userId")); map.put("UserName", SpUtils.getString(getActivity(),"userName")); map.put("Message", content); OkUtils.post(url, map, new StringCallback() { @Override public void onError(Call call, Exception e) { } @Override public void onResponse(String response) { try { JSONObject jsonObject=new JSONObject(response); ToastUtil.toast(jsonObject.getString("msg")); if (jsonObject.getString("code").equals("1")){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { } }); } } catch (JSONException e) { e.printStackTrace(); } } }); } private void deleteMsg(String messageId, final int position) { String url = Constants.ServerUrl+"ses/deleteActivitySes/"+messageId; OkUtils.get(url, new StringCallback() { @Override public void onError(Call call, Exception e) { } @Override public void onResponse(String response) { try { JSONObject jsonObject=new JSONObject(response); ToastUtil.toast(jsonObject.getString("msg")); if (jsonObject.getString("code").equals("1")){ //界面删除 adapter.delete(position); } } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
ZhouShowfew/FZXYActivity
app/src/main/java/com/example/steven/fzxyactivity/module/main/View/Fragment/MessageFrament.java
2,780
//点击操作,跳进消息详情
line_comment
zh-cn
package com.example.steven.fzxyactivity.module.main.View.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.RelativeLayout; import com.example.steven.fzxyactivity.Constant.Constants; import com.example.steven.fzxyactivity.Entity.MessageEntity; import com.example.steven.fzxyactivity.Entity.MyActivityEntity; import com.example.steven.fzxyactivity.R; import com.example.steven.fzxyactivity.common.util.LoadingState; import com.example.steven.fzxyactivity.common.util.NetWorkUtil; import com.example.steven.fzxyactivity.common.util.OkUtils; import com.example.steven.fzxyactivity.common.util.SnackbarUtil; import com.example.steven.fzxyactivity.common.util.SpUtils; import com.example.steven.fzxyactivity.common.util.ToastUtil; import com.example.steven.fzxyactivity.common.util.customview.QQListview; import com.example.steven.fzxyactivity.common.util.customview.XHLoadingView; import com.example.steven.fzxyactivity.materialdesign.utils.DialogAction; import com.example.steven.fzxyactivity.materialdesign.views.MaterialDialog; import com.example.steven.fzxyactivity.module.activitydetail.ActivityDeatailActivity; import com.example.steven.fzxyactivity.module.main.View.Fragment.adapter.MessageAdapter; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import okhttp3.Call; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * to handle interaction events. * Use the {@link MessageFrament#newInstance} factory method to * create an instance of this fragment. */ public class MessageFrament extends android.app.Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; @Bind(R.id.rl_message) RelativeLayout rlMessage; @Bind(R.id.lv_loading) XHLoadingView lvLoading; @Bind(R.id.listview_qq) QQListview listviewQq; private static final String LOADING_STATE="state"; private static final String LOADING="loading"; private static final String LOADING_EMPTY="empty"; private static final String LOADING_NONETWORK="nonet"; private static final String LOADING_ERROR="error"; private String mLoadState; List<MessageEntity> mDatas; MessageAdapter adapter; String content=""; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private LinearLayoutManager mLinearLayoutManager; public MessageFrament() { // Required empty public constructor } public static MessageFrament newInstance(String param1, String param2) { MessageFrament fragment = new MessageFrament(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } mLinearLayoutManager = new LinearLayoutManager(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_message_frament, container, false); ButterKnife.bind(this, view); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); lvLoading.withLoadEmptyText("≥﹏≤ , 啥也木有 !").withEmptyIcon(R.drawable.disk_file_no_data).withBtnEmptyEnnable(false) .withErrorIco(R.drawable.ic_chat_empty).withLoadErrorText("(῀( ˙᷄ỏ˙᷅ )῀)ᵒᵐᵍᵎᵎᵎ,我家程序猿跑路了 !").withBtnErrorText("臭狗屎!!!") .withLoadNoNetworkText("你挡着信号啦o( ̄ヘ ̄o)☞ᗒᗒ 你走").withNoNetIcon(R.drawable.ic_chat_empty).withBtnNoNetText("网弄好了,重试") .withLoadingIcon(R.drawable.loading_animation).withLoadingText("加载中...").withOnRetryListener(new XHLoadingView.OnRetryListener() { @Override public void onRetry() { SnackbarUtil.show(lvLoading,"已经在努力重试了",0); } }).build(); if (!NetWorkUtil.isNetWorkConnected(getActivity())){ lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_ERROR); }else { //加载中 lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_LOADING); String url = Constants.ServerUrl + "ses/searchActivitySes/" + SpUtils.getString(getActivity(), "userId"); //String url = Constants.ServerUrl + "ses/searchActivitySes/sf"; OkUtils.get(url, new StringCallback() { @Override public void onError(Call call, Exception e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_ERROR); } }); } @Override public void onResponse(String response) { try { if (response.equals("null")){ //null 没有活动 getActivity().runOnUiThread(new Runnable() { @Override public void run() { lvLoading.setVisibility(View.VISIBLE); lvLoading.setState(LoadingState.STATE_EMPTY); } }); }else { final JSONObject jsonObject = new JSONObject(response); final JSONArray array = jsonObject.getJSONArray("activitysessionmessage"); if (array.getJSONObject(0).getString("code").equals("1")) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { lvLoading.setVisibility(View.GONE); mDatas= new ArrayList<MessageEntity>(); for (int i=0;i<array.length();i++){ try { MessageEntity entity=new MessageEntity(); entity.setMessage(array.getJSONObject(i).getString("message")); entity.setMessageId(array.getJSONObject(i).getString("messageId")); entity.setMessageTime("消息时间:"+array.getJSONObject(i).getString("messageTime")); entity.setUserId(array.getJSONObject(i).getString("userId")); entity.setUserName("用户名:"+array.getJSONObject(i).getString("userName")); mDatas.add(entity); } catch (JSONException e) { e.printStackTrace(); } } adapter=new MessageAdapter(getActivity(),mDatas); listviewQq.setAdapter(adapter); listviewQq.setDelButtonClickListener(new QQListview.DelButtonClickListener() { @Override public void clickHappend(int position) { //网络请求操作删除 try { deleteMsg(array.getJSONObject(position).getString("messageId"),position); } catch (JSONException e) { e.printStackTrace(); } } }); listviewQq.setEditButtonClickListener(new QQListview.EditButtonClickListener() { @Override public void clickEditHappend(final int position) { //编辑操作 new MaterialDialog.Builder(getActivity()) .title("修改消息") .content("修改您的活动消息") .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_WORDS) .positiveText("提交") .onPositive(new MaterialDialog .SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { try { modifyMsg(content,array.getJSONObject(position).getString("messageId")); } catch (JSONException e) { e.printStackTrace(); } } }) .alwaysCallInputCallback() .input(R.string.input, 0, false, new MaterialDialog.InputCallback() { @Override public void onInput(MaterialDialog dialog, CharSequence input) { if (!input.toString().equals ("")) { content = input.toString(); } } }).show(); } }); listviewQq.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //点击 <SUF> } }); } }); } } } catch (JSONException e) { e.printStackTrace(); } } }); } } private void modifyMsg(String content,String id) { String url = Constants.ServerUrl + "ses/updateActivitySes"; Map<String, String> map = new HashMap<>(); map.put("MessageId", id); map.put("UserId", SpUtils.getString(getActivity(),"userId")); map.put("UserName", SpUtils.getString(getActivity(),"userName")); map.put("Message", content); OkUtils.post(url, map, new StringCallback() { @Override public void onError(Call call, Exception e) { } @Override public void onResponse(String response) { try { JSONObject jsonObject=new JSONObject(response); ToastUtil.toast(jsonObject.getString("msg")); if (jsonObject.getString("code").equals("1")){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { } }); } } catch (JSONException e) { e.printStackTrace(); } } }); } private void deleteMsg(String messageId, final int position) { String url = Constants.ServerUrl+"ses/deleteActivitySes/"+messageId; OkUtils.get(url, new StringCallback() { @Override public void onError(Call call, Exception e) { } @Override public void onResponse(String response) { try { JSONObject jsonObject=new JSONObject(response); ToastUtil.toast(jsonObject.getString("msg")); if (jsonObject.getString("code").equals("1")){ //界面删除 adapter.delete(position); } } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
false
2,314
8
2,780
8
2,999
8
2,780
8
3,602
16
false
false
false
false
false
true
10758_1
package com.alan.bean; /** * Created by alan on 17/1/11. */ public enum Types { /** * 网站类型 */ Life(1,"新闻"), Tech(2,"科技"), IT(3,"IT"), Spare(4,"娱乐"), Share(5,"社交"), Seeing(6,"看见"), Others(7,"其它"); private int code; private String msg; Types(int code, String msg) { this.code=code; this.msg=msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
Zhouchuanwen/ChromeY
src/main/java/com/alan/bean/Types.java
171
/** * 网站类型 */
block_comment
zh-cn
package com.alan.bean; /** * Created by alan on 17/1/11. */ public enum Types { /** * 网站类 <SUF>*/ Life(1,"新闻"), Tech(2,"科技"), IT(3,"IT"), Spare(4,"娱乐"), Share(5,"社交"), Seeing(6,"看见"), Others(7,"其它"); private int code; private String msg; Types(int code, String msg) { this.code=code; this.msg=msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
false
149
11
171
8
179
9
171
8
218
12
false
false
false
false
false
true
40934_4
import java.util.ArrayList; import java.util.List; /** * * https://www.nowcoder.com/question/next?pid=2811407&qid=46572&tid=6192278 * Created by alan on 16/12/14. * */ public class Jump { //查找公约数的最佳方法 public static List<Integer> gcd(int x){ if(x<=0) return null; List<Integer> list=new ArrayList<>(); for(int i=2;i<=Math.sqrt(x);i++){ if(x%i==0){ list.add(i); if(x/i!=i){ list.add(x/i); } } } return list; } /** * 动态规划思想 * @param n * @param m * @return */ public static int timesTojump(int n,int m){ if (m == n) { return 0; } int steps = m - n + 1;// 算上了起点和终点 int[] dp = new int[steps];// 规划的量:到达 每个位置需要的最小步数 dp[0] = 0; // 起点 for (int i = 1; i < steps; i++) { dp[i] = Integer.MAX_VALUE; // 初始化 表示后续位置都不能到达 } for (int i = 0; i < steps; i++) { // 0对应n石板 ;steps - 1 = m-n对应m石板 if (dp[i] == Integer.MAX_VALUE) { // 该位置不能像前走 dp[i] = 0; continue; } List<Integer> list = gcd(i + n); // i+n才是石板号 for (int j = 0; j < list.size(); j++) { int x = list.get(j); if (i + n + x <= m) { dp[i + x] = Math.min(dp[i + x], dp[i] + 1); } } } if (dp[steps - 1] == 0) { return -1; } else { return dp[steps - 1]; } } public static void main(String[] args){ System.out.println(timesTojump(4,24)); } }
Zhouchuanwen/algorithm4rdEdtion
src/main/java/Jump.java
588
// 规划的量:到达 每个位置需要的最小步数
line_comment
zh-cn
import java.util.ArrayList; import java.util.List; /** * * https://www.nowcoder.com/question/next?pid=2811407&qid=46572&tid=6192278 * Created by alan on 16/12/14. * */ public class Jump { //查找公约数的最佳方法 public static List<Integer> gcd(int x){ if(x<=0) return null; List<Integer> list=new ArrayList<>(); for(int i=2;i<=Math.sqrt(x);i++){ if(x%i==0){ list.add(i); if(x/i!=i){ list.add(x/i); } } } return list; } /** * 动态规划思想 * @param n * @param m * @return */ public static int timesTojump(int n,int m){ if (m == n) { return 0; } int steps = m - n + 1;// 算上了起点和终点 int[] dp = new int[steps];// 规划 <SUF> dp[0] = 0; // 起点 for (int i = 1; i < steps; i++) { dp[i] = Integer.MAX_VALUE; // 初始化 表示后续位置都不能到达 } for (int i = 0; i < steps; i++) { // 0对应n石板 ;steps - 1 = m-n对应m石板 if (dp[i] == Integer.MAX_VALUE) { // 该位置不能像前走 dp[i] = 0; continue; } List<Integer> list = gcd(i + n); // i+n才是石板号 for (int j = 0; j < list.size(); j++) { int x = list.get(j); if (i + n + x <= m) { dp[i + x] = Math.min(dp[i + x], dp[i] + 1); } } } if (dp[steps - 1] == 0) { return -1; } else { return dp[steps - 1]; } } public static void main(String[] args){ System.out.println(timesTojump(4,24)); } }
false
530
18
588
17
620
14
588
17
711
27
false
false
false
false
false
true
56155_4
package entity; /** * 景点信息实体 * @author Administrator * */ public class Tour_mes { private int tid; //地点 private String tname; //景点名字 private int prime_price; //原价 private int group_buying; //团购价 private int vaca_days; //出游天数 private int vaca_per; //已出游人数 private String img_url; //图片地址 private String pecommend; //特别优惠 private String favorable; //景点简介 public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public int getPrime_price() { return prime_price; } public void setPrime_price(int prime_price) { this.prime_price = prime_price; } public int getGroup_buying() { return group_buying; } public void setGroup_buying(int group_buying) { this.group_buying = group_buying; } public int getVaca_days() { return vaca_days; } public void setVaca_days(int vaca_days) { this.vaca_days = vaca_days; } public int getVaca_per() { return vaca_per; } public void setVaca_per(int vaca_per) { this.vaca_per = vaca_per; } public String getImg_url() { return img_url; } public void setImg_url(String img_url) { this.img_url = img_url; } public String getPecommend() { return pecommend; } public void setPecommend(String pecommend) { this.pecommend = pecommend; } public String getFavorable() { return favorable; } public void setFavorable(String favorable) { this.favorable = favorable; } public Tour_mes(int tid, String tname, int prime_price, int group_buying, int vaca_days, int vaca_per, String img_url, String pecommend, String favorable) { super(); this.tid = tid; this.tname = tname; this.prime_price = prime_price; this.group_buying = group_buying; this.vaca_days = vaca_days; this.vaca_per = vaca_per; this.img_url = img_url; this.pecommend = pecommend; this.favorable = favorable; } public Tour_mes(){ } }
Zhouwanxing/Tourism
src/entity/Tour_mes.java
789
//团购价
line_comment
zh-cn
package entity; /** * 景点信息实体 * @author Administrator * */ public class Tour_mes { private int tid; //地点 private String tname; //景点名字 private int prime_price; //原价 private int group_buying; //团购 <SUF> private int vaca_days; //出游天数 private int vaca_per; //已出游人数 private String img_url; //图片地址 private String pecommend; //特别优惠 private String favorable; //景点简介 public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public int getPrime_price() { return prime_price; } public void setPrime_price(int prime_price) { this.prime_price = prime_price; } public int getGroup_buying() { return group_buying; } public void setGroup_buying(int group_buying) { this.group_buying = group_buying; } public int getVaca_days() { return vaca_days; } public void setVaca_days(int vaca_days) { this.vaca_days = vaca_days; } public int getVaca_per() { return vaca_per; } public void setVaca_per(int vaca_per) { this.vaca_per = vaca_per; } public String getImg_url() { return img_url; } public void setImg_url(String img_url) { this.img_url = img_url; } public String getPecommend() { return pecommend; } public void setPecommend(String pecommend) { this.pecommend = pecommend; } public String getFavorable() { return favorable; } public void setFavorable(String favorable) { this.favorable = favorable; } public Tour_mes(int tid, String tname, int prime_price, int group_buying, int vaca_days, int vaca_per, String img_url, String pecommend, String favorable) { super(); this.tid = tid; this.tname = tname; this.prime_price = prime_price; this.group_buying = group_buying; this.vaca_days = vaca_days; this.vaca_per = vaca_per; this.img_url = img_url; this.pecommend = pecommend; this.favorable = favorable; } public Tour_mes(){ } }
false
588
4
787
5
741
5
787
5
854
11
false
false
false
false
false
true
19602_14
package tree; /** * @program: dataStur * @description: 二叉树 * @author: zzs * @create: 2020-07-17 17:04 **/ public class BinaryTreeDemo { /** * 理解 * 有参数 (root递归): (root.leftChild) * 无参数 root.(): root.leftChild.() */ public static void main(String[] args) { HeroNode root = new HeroNode(1, "宋江"); BinaryTree binaryTree = new BinaryTree(root); HeroNode ch2 = new HeroNode(2, "吴用"); HeroNode ch3 = new HeroNode(3, "卢俊义"); HeroNode ch4 = new HeroNode(4, "林冲"); HeroNode ch5 = new HeroNode(5, "鲁智深"); root.leftChild=ch2; root.rightChild=ch3; ch3.rightChild=ch4; ch3.leftChild=ch5; binaryTree.preOrder(); binaryTree.inOrder(); binaryTree.postOrder(); // System.out.println("list():"); // binaryTree.root.list(); // // System.out.println("Binary(in)"); // BinaryTree.list(root); } } /** * 二叉树定义 */ class BinaryTree{ public HeroNode root; public BinaryTree(HeroNode root) { this.root = root; } // public static void list(HeroNode root) { // //中序遍历 // if (root!=null){ // //先找左 // BinaryTree.list(root.leftChild); // //打印中间的节点 // System.out.println(root); // //再找右 // BinaryTree.list(root.rightChild); // } // } /** * 前序遍历:先root在左子树再右子树 */ public void preOrder(){ System.out.println("pre:"); root.preOrder(); } public void inOrder(){ System.out.println("in:"); root.inOrder(); } public void postOrder(){ System.out.println("post:"); root.postOrder(); } } /** * 节点对象定义 */ class HeroNode{ public int no; public String name; public HeroNode leftChild; public HeroNode rightChild; public HeroNode(int no, String name) { this.no = no; this.name = name; } /** * 前序遍历:先root在左子树再右子树 */ public void preOrder(){ System.out.println(this); if (this.leftChild!=null){ this.leftChild.preOrder(); } if (this.rightChild!=null){ this.rightChild.preOrder(); } } public void inOrder(){ if (this.leftChild!=null){ this.leftChild.inOrder(); } System.out.println(this); if (this.rightChild!=null){ this.rightChild.inOrder(); } } public void postOrder(){ if (this.leftChild!=null){ this.leftChild.postOrder(); } if (this.rightChild!=null){ this.rightChild.postOrder(); } System.out.println(this); } @Override public String toString() { return "HeroNode{" + "no=" + no + ", name='" + name + '\'' + '}'; } // public void list() { // //root // System.out.println(this.toString()); // //left // if (this.leftChild!=null){ // this.leftChild.list(); // } // //right // if (this.rightChild!=null){ // this.rightChild.list(); // } // } }
Zhouzhongshang/dataStructure
src/tree/BinaryTreeDemo.java
949
// //再找右
line_comment
zh-cn
package tree; /** * @program: dataStur * @description: 二叉树 * @author: zzs * @create: 2020-07-17 17:04 **/ public class BinaryTreeDemo { /** * 理解 * 有参数 (root递归): (root.leftChild) * 无参数 root.(): root.leftChild.() */ public static void main(String[] args) { HeroNode root = new HeroNode(1, "宋江"); BinaryTree binaryTree = new BinaryTree(root); HeroNode ch2 = new HeroNode(2, "吴用"); HeroNode ch3 = new HeroNode(3, "卢俊义"); HeroNode ch4 = new HeroNode(4, "林冲"); HeroNode ch5 = new HeroNode(5, "鲁智深"); root.leftChild=ch2; root.rightChild=ch3; ch3.rightChild=ch4; ch3.leftChild=ch5; binaryTree.preOrder(); binaryTree.inOrder(); binaryTree.postOrder(); // System.out.println("list():"); // binaryTree.root.list(); // // System.out.println("Binary(in)"); // BinaryTree.list(root); } } /** * 二叉树定义 */ class BinaryTree{ public HeroNode root; public BinaryTree(HeroNode root) { this.root = root; } // public static void list(HeroNode root) { // //中序遍历 // if (root!=null){ // //先找左 // BinaryTree.list(root.leftChild); // //打印中间的节点 // System.out.println(root); // //再找 <SUF> // BinaryTree.list(root.rightChild); // } // } /** * 前序遍历:先root在左子树再右子树 */ public void preOrder(){ System.out.println("pre:"); root.preOrder(); } public void inOrder(){ System.out.println("in:"); root.inOrder(); } public void postOrder(){ System.out.println("post:"); root.postOrder(); } } /** * 节点对象定义 */ class HeroNode{ public int no; public String name; public HeroNode leftChild; public HeroNode rightChild; public HeroNode(int no, String name) { this.no = no; this.name = name; } /** * 前序遍历:先root在左子树再右子树 */ public void preOrder(){ System.out.println(this); if (this.leftChild!=null){ this.leftChild.preOrder(); } if (this.rightChild!=null){ this.rightChild.preOrder(); } } public void inOrder(){ if (this.leftChild!=null){ this.leftChild.inOrder(); } System.out.println(this); if (this.rightChild!=null){ this.rightChild.inOrder(); } } public void postOrder(){ if (this.leftChild!=null){ this.leftChild.postOrder(); } if (this.rightChild!=null){ this.rightChild.postOrder(); } System.out.println(this); } @Override public String toString() { return "HeroNode{" + "no=" + no + ", name='" + name + '\'' + '}'; } // public void list() { // //root // System.out.println(this.toString()); // //left // if (this.leftChild!=null){ // this.leftChild.list(); // } // //right // if (this.rightChild!=null){ // this.rightChild.list(); // } // } }
false
832
6
949
6
1,009
6
949
6
1,121
8
false
false
false
false
false
true
47380_6
package com.zy.blog.view; import com.baomidou.mybatisplus.annotation.TableField; import com.fasterxml.jackson.annotation.JsonFormat; import com.zy.blog.base.ViewBase; import com.zy.blog.utils.annotion.validator.annotion.NotBlank; import com.zy.blog.utils.annotion.validator.annotion.Range; import com.zy.blog.utils.annotion.validator.group.GetOne; import com.zy.blog.utils.annotion.validator.group.Insert; import com.zy.blog.utils.annotion.validator.group.Update; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; @Data public class UserView extends ViewBase { /** * 用户名 */ @NotBlank(groups = {Insert.class, GetOne.class}) @Range(groups = {Insert.class, Update.class}, min = 5, max = 30) private String userName; /** * 密码 */ @NotBlank(groups = {GetOne.class}) private String passWord; /** * 昵称 */ private String nickName; /** * 性别(1:男2:女) */ private String gender; /** * 个人头像 */ private String avatar; /** * 邮箱 */ @NotBlank(groups = {Insert.class}) private String email; /** * 出生年月日 */ @DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd") private Date birthday; /** * 手机 */ private String mobile; /** * QQ号 */ private String qqNumber; /** * 微信号 */ private String weChat; /** * 职业 */ private String occupation; /** * 自我简介最多150字 */ @Range(groups = {Insert.class, Update.class}, max = 200) private String summary; /** * 资料来源 */ private String source; /** * 平台uuid */ private String uuid; /** * 评论状态,0 禁言, 1 正常 */ private Integer commentStatus; /** * 开启邮件通知: 0:关闭, 1:开启 */ private Integer startEmailNotification; /** * 用户标签 0:普通,1:管理员,2:博主 */ private Integer userTag; /** * 用户头像 */ @TableField(exist = false) private String photoUrl; /** * OrderBy排序字段(desc: 降序) */ private String orderByDescColumn; /** * OrderBy排序字段(asc: 升序) */ private String orderByAscColumn; }
Zhrzy/SpringCloudBlog
blog_entity/src/main/java/com/zy/blog/view/UserView.java
674
/** * 出生年月日 */
block_comment
zh-cn
package com.zy.blog.view; import com.baomidou.mybatisplus.annotation.TableField; import com.fasterxml.jackson.annotation.JsonFormat; import com.zy.blog.base.ViewBase; import com.zy.blog.utils.annotion.validator.annotion.NotBlank; import com.zy.blog.utils.annotion.validator.annotion.Range; import com.zy.blog.utils.annotion.validator.group.GetOne; import com.zy.blog.utils.annotion.validator.group.Insert; import com.zy.blog.utils.annotion.validator.group.Update; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; @Data public class UserView extends ViewBase { /** * 用户名 */ @NotBlank(groups = {Insert.class, GetOne.class}) @Range(groups = {Insert.class, Update.class}, min = 5, max = 30) private String userName; /** * 密码 */ @NotBlank(groups = {GetOne.class}) private String passWord; /** * 昵称 */ private String nickName; /** * 性别(1:男2:女) */ private String gender; /** * 个人头像 */ private String avatar; /** * 邮箱 */ @NotBlank(groups = {Insert.class}) private String email; /** * 出生年 <SUF>*/ @DateTimeFormat(pattern = "yyyy-MM-dd") @JsonFormat(pattern = "yyyy-MM-dd") private Date birthday; /** * 手机 */ private String mobile; /** * QQ号 */ private String qqNumber; /** * 微信号 */ private String weChat; /** * 职业 */ private String occupation; /** * 自我简介最多150字 */ @Range(groups = {Insert.class, Update.class}, max = 200) private String summary; /** * 资料来源 */ private String source; /** * 平台uuid */ private String uuid; /** * 评论状态,0 禁言, 1 正常 */ private Integer commentStatus; /** * 开启邮件通知: 0:关闭, 1:开启 */ private Integer startEmailNotification; /** * 用户标签 0:普通,1:管理员,2:博主 */ private Integer userTag; /** * 用户头像 */ @TableField(exist = false) private String photoUrl; /** * OrderBy排序字段(desc: 降序) */ private String orderByDescColumn; /** * OrderBy排序字段(asc: 升序) */ private String orderByAscColumn; }
false
611
12
674
11
731
11
674
11
882
13
false
false
false
false
false
true
34950_0
/** * 项目名:student * 修改历史: * 作者: MZ * 创建时间: 2016年1月6日-上午11:26:11 */ package com.up.student; /** * 模块说明: 定制枚举类型 * */ public enum DAO { AdminDAO, StudentDAO; // private String str; // // private Clazz(String str) { // this.str = str; // } // // public String getStr() { // return this.str; // } }
ZhuangM/student
src/main/java/com/up/student/DAO.java
148
/** * 项目名:student * 修改历史: * 作者: MZ * 创建时间: 2016年1月6日-上午11:26:11 */
block_comment
zh-cn
/** * 项目名 <SUF>*/ package com.up.student; /** * 模块说明: 定制枚举类型 * */ public enum DAO { AdminDAO, StudentDAO; // private String str; // // private Clazz(String str) { // this.str = str; // } // // public String getStr() { // return this.str; // } }
false
125
45
148
47
142
43
148
47
175
60
false
false
false
false
false
true
35227_23
package com.zk.qpm.utils; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.widget.Toast; import java.util.ArrayList; import static android.Manifest.permission; /** * Created by Elvis on 2016/11/23. */ public class PermissionTool { /** * 普通权限--只需要在Manifest.xml中申请就可以 */ private static final String[] normalPermissions = { permission.ACCESS_LOCATION_EXTRA_COMMANDS, permission.ACCESS_NETWORK_STATE, permission.ACCESS_NOTIFICATION_POLICY,//SDK>=11才可以使用 permission.ACCESS_WIFI_STATE, permission.BLUETOOTH, permission.BLUETOOTH_ADMIN, permission.BROADCAST_STICKY, permission.CHANGE_NETWORK_STATE, permission.CHANGE_WIFI_MULTICAST_STATE, permission.CHANGE_WIFI_STATE, permission.DISABLE_KEYGUARD, permission.EXPAND_STATUS_BAR, permission.GET_PACKAGE_SIZE, permission.INSTALL_SHORTCUT,//SDK>=19才可以使用 permission.INTERNET, permission.KILL_BACKGROUND_PROCESSES, permission.MODIFY_AUDIO_SETTINGS, permission.NFC, permission.READ_SYNC_SETTINGS, permission.READ_SYNC_STATS, permission.RECEIVE_BOOT_COMPLETED, permission.REORDER_TASKS, permission.REQUEST_INSTALL_PACKAGES,//SDK>=23才可以使用 permission.SET_ALARM, permission.SET_TIME_ZONE, permission.SET_WALLPAPER, permission.SET_WALLPAPER_HINTS, permission.TRANSMIT_IR,//SDK>=19才可以使用 permission.UNINSTALL_SHORTCUT,//SDK>=19才可以使用 permission.USE_FINGERPRINT,//SDK>=23才可以使用 permission.VIBRATE, permission.WAKE_LOCK, permission.WRITE_SYNC_SETTINGS, }; /** * 危险权限--必要权限--开启应用必须获取的 */ private static final String[] dangerousPermissions = { //存储卡 permission.READ_EXTERNAL_STORAGE,//SDK>=16才可以使用 permission.WRITE_EXTERNAL_STORAGE, //位置 permission.ACCESS_FINE_LOCATION, permission.ACCESS_COARSE_LOCATION, //传感器 permission.BODY_SENSORS,//SDK>=20才可以使用 //日历 permission.READ_CALENDAR, permission.WRITE_CALENDAR, //person_3 permission.CAMERA, //联系人 permission.READ_CONTACTS, permission.WRITE_CONTACTS, permission.GET_ACCOUNTS, //麦克风 permission.RECORD_AUDIO, //手机 permission.READ_PHONE_STATE, permission.CALL_PHONE, permission.READ_CALL_LOG,//SDK>=16才可以使用 permission.WRITE_CALL_LOG,//SDK>=16才可以使用 permission.ADD_VOICEMAIL,//SDK>=14才可以使用 permission.USE_SIP, permission.PROCESS_OUTGOING_CALLS, //短信 permission.SEND_SMS, permission.RECEIVE_SMS, permission.READ_SMS, permission.RECEIVE_WAP_PUSH, permission.RECEIVE_MMS, }; //权限申请标记 public static final int APPLY_PERMISSIONS = 154; /** * 申请权限列表 * * @return */ public static boolean applyPermissions(String[] permissions, Activity activity) { //1.筛选未申请的权限: ArrayList<String> unApplyList = new ArrayList<String>(); for (int i = 0; permissions!=null&&i < permissions.length; i++) { //筛选未拥有&&满足API要求的权限 if (ContextCompat.checkSelfPermission(activity, permissions[i]) != PackageManager.PERMISSION_GRANTED) {//未拥有的权限 if (permissions[i].equals(permission.READ_EXTERNAL_STORAGE) && getSDKVersionNumber() < 16) {//读取文件权限要求16以上 } else if (permissions[i].equals(permission.BODY_SENSORS) && getSDKVersionNumber() < 20) {//获取体征数据要求20以上 } else if (permissions[i].equals(permission.READ_CALL_LOG) && getSDKVersionNumber() < 16) {//读取手机通讯录要求16以上 } else if (permissions[i].equals(permission.WRITE_CALL_LOG) && getSDKVersionNumber() < 16) {//写入手机通讯录要求16以上 } else if (permissions[i].equals(permission.ADD_VOICEMAIL) && getSDKVersionNumber() < 14) {//添加语音信箱要求14以上 } else { unApplyList.add(permissions[i]); } } } //2.如果所有权限都拥有了,返回true,否则申请所有未申请的权限 if (unApplyList.size() == 0) { return true; } else { if (getSDKVersionNumber() < 23) { Toast.makeText(activity, "权限不足,请到设置页面给予应用相应的权限!", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } else { String[] unApplyArray = new String[unApplyList.size()]; for (int i = 0; i < unApplyArray.length; i++) { unApplyArray[i] = unApplyList.get(i); } ActivityCompat.requestPermissions(activity, unApplyArray, APPLY_PERMISSIONS); return false; } } } public static int getSDKVersionNumber() { int sdkVersion; try { sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK); } catch (NumberFormatException e) { sdkVersion = 0; } return sdkVersion; } }
ZhuoKeTeam/QPM
QPM_SDK/src/main/java/com/zk/qpm/utils/PermissionTool.java
1,390
//未拥有的权限
line_comment
zh-cn
package com.zk.qpm.utils; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.widget.Toast; import java.util.ArrayList; import static android.Manifest.permission; /** * Created by Elvis on 2016/11/23. */ public class PermissionTool { /** * 普通权限--只需要在Manifest.xml中申请就可以 */ private static final String[] normalPermissions = { permission.ACCESS_LOCATION_EXTRA_COMMANDS, permission.ACCESS_NETWORK_STATE, permission.ACCESS_NOTIFICATION_POLICY,//SDK>=11才可以使用 permission.ACCESS_WIFI_STATE, permission.BLUETOOTH, permission.BLUETOOTH_ADMIN, permission.BROADCAST_STICKY, permission.CHANGE_NETWORK_STATE, permission.CHANGE_WIFI_MULTICAST_STATE, permission.CHANGE_WIFI_STATE, permission.DISABLE_KEYGUARD, permission.EXPAND_STATUS_BAR, permission.GET_PACKAGE_SIZE, permission.INSTALL_SHORTCUT,//SDK>=19才可以使用 permission.INTERNET, permission.KILL_BACKGROUND_PROCESSES, permission.MODIFY_AUDIO_SETTINGS, permission.NFC, permission.READ_SYNC_SETTINGS, permission.READ_SYNC_STATS, permission.RECEIVE_BOOT_COMPLETED, permission.REORDER_TASKS, permission.REQUEST_INSTALL_PACKAGES,//SDK>=23才可以使用 permission.SET_ALARM, permission.SET_TIME_ZONE, permission.SET_WALLPAPER, permission.SET_WALLPAPER_HINTS, permission.TRANSMIT_IR,//SDK>=19才可以使用 permission.UNINSTALL_SHORTCUT,//SDK>=19才可以使用 permission.USE_FINGERPRINT,//SDK>=23才可以使用 permission.VIBRATE, permission.WAKE_LOCK, permission.WRITE_SYNC_SETTINGS, }; /** * 危险权限--必要权限--开启应用必须获取的 */ private static final String[] dangerousPermissions = { //存储卡 permission.READ_EXTERNAL_STORAGE,//SDK>=16才可以使用 permission.WRITE_EXTERNAL_STORAGE, //位置 permission.ACCESS_FINE_LOCATION, permission.ACCESS_COARSE_LOCATION, //传感器 permission.BODY_SENSORS,//SDK>=20才可以使用 //日历 permission.READ_CALENDAR, permission.WRITE_CALENDAR, //person_3 permission.CAMERA, //联系人 permission.READ_CONTACTS, permission.WRITE_CONTACTS, permission.GET_ACCOUNTS, //麦克风 permission.RECORD_AUDIO, //手机 permission.READ_PHONE_STATE, permission.CALL_PHONE, permission.READ_CALL_LOG,//SDK>=16才可以使用 permission.WRITE_CALL_LOG,//SDK>=16才可以使用 permission.ADD_VOICEMAIL,//SDK>=14才可以使用 permission.USE_SIP, permission.PROCESS_OUTGOING_CALLS, //短信 permission.SEND_SMS, permission.RECEIVE_SMS, permission.READ_SMS, permission.RECEIVE_WAP_PUSH, permission.RECEIVE_MMS, }; //权限申请标记 public static final int APPLY_PERMISSIONS = 154; /** * 申请权限列表 * * @return */ public static boolean applyPermissions(String[] permissions, Activity activity) { //1.筛选未申请的权限: ArrayList<String> unApplyList = new ArrayList<String>(); for (int i = 0; permissions!=null&&i < permissions.length; i++) { //筛选未拥有&&满足API要求的权限 if (ContextCompat.checkSelfPermission(activity, permissions[i]) != PackageManager.PERMISSION_GRANTED) {//未拥 <SUF> if (permissions[i].equals(permission.READ_EXTERNAL_STORAGE) && getSDKVersionNumber() < 16) {//读取文件权限要求16以上 } else if (permissions[i].equals(permission.BODY_SENSORS) && getSDKVersionNumber() < 20) {//获取体征数据要求20以上 } else if (permissions[i].equals(permission.READ_CALL_LOG) && getSDKVersionNumber() < 16) {//读取手机通讯录要求16以上 } else if (permissions[i].equals(permission.WRITE_CALL_LOG) && getSDKVersionNumber() < 16) {//写入手机通讯录要求16以上 } else if (permissions[i].equals(permission.ADD_VOICEMAIL) && getSDKVersionNumber() < 14) {//添加语音信箱要求14以上 } else { unApplyList.add(permissions[i]); } } } //2.如果所有权限都拥有了,返回true,否则申请所有未申请的权限 if (unApplyList.size() == 0) { return true; } else { if (getSDKVersionNumber() < 23) { Toast.makeText(activity, "权限不足,请到设置页面给予应用相应的权限!", Toast.LENGTH_SHORT).show(); activity.finish(); return false; } else { String[] unApplyArray = new String[unApplyList.size()]; for (int i = 0; i < unApplyArray.length; i++) { unApplyArray[i] = unApplyList.get(i); } ActivityCompat.requestPermissions(activity, unApplyArray, APPLY_PERMISSIONS); return false; } } } public static int getSDKVersionNumber() { int sdkVersion; try { sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK); } catch (NumberFormatException e) { sdkVersion = 0; } return sdkVersion; } }
false
1,191
5
1,390
5
1,458
5
1,390
5
1,927
11
false
false
false
false
false
true
42299_12
import enums.VersionEnum; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ui.LinkLabel; import util.DecodeNcx; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.SwingConstants; import javax.swing.filechooser.FileNameExtensionFilter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * UploadSynFrame 破解navicat密码ui * * @author lzy * @date 2021/01/15 14:03 */ public class MainIndexFrame { private static final double NAVICAT11 = 1.1D; /** * 解密工具类 */ private static DecodeNcx decodeNcx; /** * navicat11选项 */ private static final JRadioButton navicat11 = new JRadioButton("navicat11"); /** * navicat12以上选项 */ private static final JRadioButton navicat12more = new JRadioButton("navicat12+", true); /** * 密文正则 */ public static final String PASS_WORD = "^[A-Za-z0-9]+$"; public void UpLoadFile() { JFrame jframe = new JFrame("navicat密码查看工具"); jframe.setLayout(new BorderLayout()); JToolBar jToolBar = new JToolBar(); jframe.setSize(400, 350); JPanel jPanel = new JPanel(); JTextField password = new JTextField("请填入加密密码", 20); JButton showButton = new JButton("查看密码"); JPanel filePanel = new JPanel(); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(navicat11); buttonGroup.add(navicat12more); jPanel.add(navicat11); jPanel.add(navicat12more); jPanel.add(password); jPanel.add(showButton); LinkLabel explain = new LinkLabel("操作说明", "https://blog.csdn.net/kkk123445/article/details/122514124"); explain.setHorizontalAlignment(SwingConstants.LEFT); filePanel.add(explain); JLabel jl = new JLabel("<html>&nbsp;&nbsp;&nbsp;&nbsp;导入ncx文件,请选择:</html>"); jl.setHorizontalAlignment(SwingConstants.LEFT); filePanel.add(jl); JButton developer = new JButton("选择文件"); developer.setHorizontalAlignment(SwingConstants.CENTER); jToolBar.add(developer); filePanel.add(jToolBar); final JSplitPane vSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // 分隔条左侧的高度为 vSplitPane.setDividerLocation(80); vSplitPane.setResizeWeight(0.6); // 分隔条的宽度为 vSplitPane.setDividerSize(10); // 提供UI小部件 vSplitPane.setOneTouchExpandable(false); vSplitPane.setEnabled(false); // 在垂直面板上方添加一个标签组件 vSplitPane.setTopComponent(jPanel); // 在垂直面板下方添加一个标签组件 vSplitPane.setBottomComponent(filePanel); JTextArea textArea = new JTextArea(); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(textArea); scrollPane.setPreferredSize(new Dimension((int) (jframe.getWidth() * 9.6) / 10, (int) (200 * 9.6) / 10)); filePanel.add(scrollPane); jframe.add(vSplitPane); //单个密码查看 showButton.addActionListener(e -> { if (navicat11.isSelected()) { decodeNcx = new DecodeNcx(VersionEnum.native11.name()); } else { decodeNcx = new DecodeNcx(VersionEnum.navicat12more.name()); } if (!Pattern.matches(PASS_WORD, password.getText())) { JOptionPane.showMessageDialog(null, "密码应为字母和数字组合,格式不正确!", "提醒", JOptionPane.WARNING_MESSAGE, null); return; } password.setText(decodeNcx.decode(password.getText().trim())); password.requestFocus(); }); //批量密码查看 developer.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { String result = eventOnImport(new JButton()); textArea.setText(result); } }); jframe.setResizable(false); jframe.setLocationRelativeTo(null); jframe.setVisible(true); } /** * 文件上传功能 * * @param developer 按钮控件名称 */ public static String eventOnImport(JButton developer) { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); /** 过滤文件类型 * */ FileNameExtensionFilter filter = new FileNameExtensionFilter("ncx", "ncx"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(developer); if (returnVal == JFileChooser.APPROVE_OPTION) { /** 得到选择的文件* */ File file = chooser.getSelectedFile(); if (file == null) { return ""; } try { // List<Map <连接名,Map<属性名,值>>> 要导入的连接 List<Map<String, Map<String, String>>> configMap = new ArrayList<>(); //1、创建一个DocumentBuilderFactory的对象 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //2、创建一个DocumentBuilder的对象 //创建DocumentBuilder对象 DocumentBuilder db = dbf.newDocumentBuilder(); //3、通过DocumentBuilder对象的parser方法加载xml文件到当前项目下 Document document = db.parse(file); //获取所有Connections节点的集合 NodeList connectList = document.getElementsByTagName("Connection"); NodeList nodeList = document.getElementsByTagName("Connections"); NamedNodeMap verMap = nodeList.item(0).getAttributes(); double version = Double.parseDouble((verMap.getNamedItem("Ver").getNodeValue())); if (version <= NAVICAT11) { decodeNcx = new DecodeNcx(VersionEnum.native11.name()); } else { decodeNcx = new DecodeNcx(VersionEnum.navicat12more.name()); } //配置map Map<String, Map<String, String>> connectionMap = new HashMap<>(); //遍历每一个Connections节点 for (int i = 0; i < connectList.getLength(); i++) { //通过 item(i)方法 获取一个Connection节点,nodelist的索引值从0开始 Node connect = connectList.item(i); //获取Connection节点的所有属性集合 NamedNodeMap attrs = connect.getAttributes(); //遍历Connection的属性 Map<String, String> map = new HashMap<>(0); for (int j = 0; j < attrs.getLength(); j++) { //通过item(index)方法获取connect节点的某一个属性 Node attr = attrs.item(j); map.put(attr.getNodeName(), attr.getNodeValue()); } connectionMap.put(map.get("ConnectionName") + map.get("ConnType"), map); } configMap.add(connectionMap); return writeConfigFile(configMap); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "导入失败!请导入正确的ncx文件!", "提示", JOptionPane.ERROR_MESSAGE); return ""; } } return ""; } /** * 写入配置文件 * * @param list 读取ncx文件的数据 */ private static String writeConfigFile(List<Map<String, Map<String, String>>> list) { StringBuilder stringBuilder = new StringBuilder(); for (Map<String, Map<String, String>> map : list) { for (Map.Entry<String, Map<String, String>> valueMap : map.entrySet()) { Map<String, String> resultMap = valueMap.getValue(); String password = decodeNcx.decode(resultMap.getOrDefault("Password", "")); stringBuilder.append(resultMap.get("Host")).append("|").append(resultMap.get("Port")).append("|") .append(resultMap.get("UserName")).append("|").append(resultMap.get("ConnType")).append(" = ") .append(password).append("\n"); } } return stringBuilder.toString(); } public static void main(String[] args) { MainIndexFrame u = new MainIndexFrame(); u.UpLoadFile(); } }
Zhuoyuan1/navicat_password_decrypt
src/main/java/MainIndexFrame.java
2,235
//批量密码查看
line_comment
zh-cn
import enums.VersionEnum; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ui.LinkLabel; import util.DecodeNcx; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.SwingConstants; import javax.swing.filechooser.FileNameExtensionFilter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * UploadSynFrame 破解navicat密码ui * * @author lzy * @date 2021/01/15 14:03 */ public class MainIndexFrame { private static final double NAVICAT11 = 1.1D; /** * 解密工具类 */ private static DecodeNcx decodeNcx; /** * navicat11选项 */ private static final JRadioButton navicat11 = new JRadioButton("navicat11"); /** * navicat12以上选项 */ private static final JRadioButton navicat12more = new JRadioButton("navicat12+", true); /** * 密文正则 */ public static final String PASS_WORD = "^[A-Za-z0-9]+$"; public void UpLoadFile() { JFrame jframe = new JFrame("navicat密码查看工具"); jframe.setLayout(new BorderLayout()); JToolBar jToolBar = new JToolBar(); jframe.setSize(400, 350); JPanel jPanel = new JPanel(); JTextField password = new JTextField("请填入加密密码", 20); JButton showButton = new JButton("查看密码"); JPanel filePanel = new JPanel(); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(navicat11); buttonGroup.add(navicat12more); jPanel.add(navicat11); jPanel.add(navicat12more); jPanel.add(password); jPanel.add(showButton); LinkLabel explain = new LinkLabel("操作说明", "https://blog.csdn.net/kkk123445/article/details/122514124"); explain.setHorizontalAlignment(SwingConstants.LEFT); filePanel.add(explain); JLabel jl = new JLabel("<html>&nbsp;&nbsp;&nbsp;&nbsp;导入ncx文件,请选择:</html>"); jl.setHorizontalAlignment(SwingConstants.LEFT); filePanel.add(jl); JButton developer = new JButton("选择文件"); developer.setHorizontalAlignment(SwingConstants.CENTER); jToolBar.add(developer); filePanel.add(jToolBar); final JSplitPane vSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // 分隔条左侧的高度为 vSplitPane.setDividerLocation(80); vSplitPane.setResizeWeight(0.6); // 分隔条的宽度为 vSplitPane.setDividerSize(10); // 提供UI小部件 vSplitPane.setOneTouchExpandable(false); vSplitPane.setEnabled(false); // 在垂直面板上方添加一个标签组件 vSplitPane.setTopComponent(jPanel); // 在垂直面板下方添加一个标签组件 vSplitPane.setBottomComponent(filePanel); JTextArea textArea = new JTextArea(); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(textArea); scrollPane.setPreferredSize(new Dimension((int) (jframe.getWidth() * 9.6) / 10, (int) (200 * 9.6) / 10)); filePanel.add(scrollPane); jframe.add(vSplitPane); //单个密码查看 showButton.addActionListener(e -> { if (navicat11.isSelected()) { decodeNcx = new DecodeNcx(VersionEnum.native11.name()); } else { decodeNcx = new DecodeNcx(VersionEnum.navicat12more.name()); } if (!Pattern.matches(PASS_WORD, password.getText())) { JOptionPane.showMessageDialog(null, "密码应为字母和数字组合,格式不正确!", "提醒", JOptionPane.WARNING_MESSAGE, null); return; } password.setText(decodeNcx.decode(password.getText().trim())); password.requestFocus(); }); //批量 <SUF> developer.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { String result = eventOnImport(new JButton()); textArea.setText(result); } }); jframe.setResizable(false); jframe.setLocationRelativeTo(null); jframe.setVisible(true); } /** * 文件上传功能 * * @param developer 按钮控件名称 */ public static String eventOnImport(JButton developer) { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); /** 过滤文件类型 * */ FileNameExtensionFilter filter = new FileNameExtensionFilter("ncx", "ncx"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(developer); if (returnVal == JFileChooser.APPROVE_OPTION) { /** 得到选择的文件* */ File file = chooser.getSelectedFile(); if (file == null) { return ""; } try { // List<Map <连接名,Map<属性名,值>>> 要导入的连接 List<Map<String, Map<String, String>>> configMap = new ArrayList<>(); //1、创建一个DocumentBuilderFactory的对象 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //2、创建一个DocumentBuilder的对象 //创建DocumentBuilder对象 DocumentBuilder db = dbf.newDocumentBuilder(); //3、通过DocumentBuilder对象的parser方法加载xml文件到当前项目下 Document document = db.parse(file); //获取所有Connections节点的集合 NodeList connectList = document.getElementsByTagName("Connection"); NodeList nodeList = document.getElementsByTagName("Connections"); NamedNodeMap verMap = nodeList.item(0).getAttributes(); double version = Double.parseDouble((verMap.getNamedItem("Ver").getNodeValue())); if (version <= NAVICAT11) { decodeNcx = new DecodeNcx(VersionEnum.native11.name()); } else { decodeNcx = new DecodeNcx(VersionEnum.navicat12more.name()); } //配置map Map<String, Map<String, String>> connectionMap = new HashMap<>(); //遍历每一个Connections节点 for (int i = 0; i < connectList.getLength(); i++) { //通过 item(i)方法 获取一个Connection节点,nodelist的索引值从0开始 Node connect = connectList.item(i); //获取Connection节点的所有属性集合 NamedNodeMap attrs = connect.getAttributes(); //遍历Connection的属性 Map<String, String> map = new HashMap<>(0); for (int j = 0; j < attrs.getLength(); j++) { //通过item(index)方法获取connect节点的某一个属性 Node attr = attrs.item(j); map.put(attr.getNodeName(), attr.getNodeValue()); } connectionMap.put(map.get("ConnectionName") + map.get("ConnType"), map); } configMap.add(connectionMap); return writeConfigFile(configMap); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "导入失败!请导入正确的ncx文件!", "提示", JOptionPane.ERROR_MESSAGE); return ""; } } return ""; } /** * 写入配置文件 * * @param list 读取ncx文件的数据 */ private static String writeConfigFile(List<Map<String, Map<String, String>>> list) { StringBuilder stringBuilder = new StringBuilder(); for (Map<String, Map<String, String>> map : list) { for (Map.Entry<String, Map<String, String>> valueMap : map.entrySet()) { Map<String, String> resultMap = valueMap.getValue(); String password = decodeNcx.decode(resultMap.getOrDefault("Password", "")); stringBuilder.append(resultMap.get("Host")).append("|").append(resultMap.get("Port")).append("|") .append(resultMap.get("UserName")).append("|").append(resultMap.get("ConnType")).append(" = ") .append(password).append("\n"); } } return stringBuilder.toString(); } public static void main(String[] args) { MainIndexFrame u = new MainIndexFrame(); u.UpLoadFile(); } }
false
1,947
4
2,235
4
2,326
4
2,235
4
2,797
9
false
false
false
false
false
true
37470_2
package gpio; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; /** * 【步进电机】 * 电机资料: * <p> * --我接入的是A3A4B3B4端口M2步进电机控制端口 * BCM wiringPi * A3A4B3B4 dir(方向) 24 GPIO_5 * A3A4B3B4 step(步骤) 18 GPIO_1 * A3A4B3B4 Dir(目录) 4 GPIO_7 * A3A4B3B4 mode(模式) 21 GPIO_29 * 22 GPIO_3 * 27 GPIO_2 *----------------------------------- * BCM wiringPi * A3A4B3B4 dir(方向) 13 GPIO_23 * A3A4B3B4 step(步骤) 19 GPIO_24 * A3A4B3B4 Dir(目录) 12 GPIO_26 * A3A4B3B4 mode(模式) 16 GPIO_27 * 17 GPIO_0 * 20 GPIO_28 */ public class StepperMotor { //GPIO控制器接口。此接口描述了通过GPIO进行的所有操作 private GpioController gpioController = GpioFactory.getInstance(); //GPIO控制树莓派的数字针脚 private GpioPinDigitalOutput GPIO_01 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_01, "GPIOController"); private GpioPinDigitalOutput GPIO_07 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_07, "GPIOController"); private GpioPinDigitalOutput GPIO_29 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_29, "GPIOController"); private GpioPinDigitalOutput GPIO_03 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_03, "GPIOController"); private GpioPinDigitalOutput GPIO_02 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_02, "GPIOController"); /* * 控制器:开启 * 设置低电平 */ public void getOpenGPIO() { //GPIO_05.low();//低电平 GPIO_01.low(); GPIO_07.low(); GPIO_29.low(); GPIO_03.low(); GPIO_02.low(); } /* * 控制器:关闭 * 设置高电平 * */ public void getShutDownGPIO() { //GPIO_05.high();//高电平 GPIO_01.high(); GPIO_07.high(); GPIO_29.high(); GPIO_03.high(); GPIO_02.high(); } }
Zhyblx/hellopangbi
src/gpio/StepperMotor.java
734
//GPIO控制树莓派的数字针脚
line_comment
zh-cn
package gpio; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; /** * 【步进电机】 * 电机资料: * <p> * --我接入的是A3A4B3B4端口M2步进电机控制端口 * BCM wiringPi * A3A4B3B4 dir(方向) 24 GPIO_5 * A3A4B3B4 step(步骤) 18 GPIO_1 * A3A4B3B4 Dir(目录) 4 GPIO_7 * A3A4B3B4 mode(模式) 21 GPIO_29 * 22 GPIO_3 * 27 GPIO_2 *----------------------------------- * BCM wiringPi * A3A4B3B4 dir(方向) 13 GPIO_23 * A3A4B3B4 step(步骤) 19 GPIO_24 * A3A4B3B4 Dir(目录) 12 GPIO_26 * A3A4B3B4 mode(模式) 16 GPIO_27 * 17 GPIO_0 * 20 GPIO_28 */ public class StepperMotor { //GPIO控制器接口。此接口描述了通过GPIO进行的所有操作 private GpioController gpioController = GpioFactory.getInstance(); //GP <SUF> private GpioPinDigitalOutput GPIO_01 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_01, "GPIOController"); private GpioPinDigitalOutput GPIO_07 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_07, "GPIOController"); private GpioPinDigitalOutput GPIO_29 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_29, "GPIOController"); private GpioPinDigitalOutput GPIO_03 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_03, "GPIOController"); private GpioPinDigitalOutput GPIO_02 = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_02, "GPIOController"); /* * 控制器:开启 * 设置低电平 */ public void getOpenGPIO() { //GPIO_05.low();//低电平 GPIO_01.low(); GPIO_07.low(); GPIO_29.low(); GPIO_03.low(); GPIO_02.low(); } /* * 控制器:关闭 * 设置高电平 * */ public void getShutDownGPIO() { //GPIO_05.high();//高电平 GPIO_01.high(); GPIO_07.high(); GPIO_29.high(); GPIO_03.high(); GPIO_02.high(); } }
false
683
10
734
11
755
9
734
11
990
24
false
false
false
false
false
true
53001_0
package tools; public class GeoUtil { /** * 地球半径:6378.137KM */ private static double EARTH_RADIUS = 6378.137; /** * 根据经纬度和距离返回一个矩形范围 * @param lng 经度 * @param lat 纬度 * @param distance 距离(单位为米) * @return [lng1,lat1, lng2,lat2] 矩形的左下角(lng1,lat1)和右上角(lng2,lat2) */ public static double[] getRectangle(double lng, double lat, long distance) { float delta = 111000; if (lng != 0 && lat != 0) { double lng1 = lng - distance / Math.abs(Math.cos(Math.toRadians(lat)) * delta); double lng2 = lng + distance / Math.abs(Math.cos(Math.toRadians(lat)) * delta); double lat1 = lat - (distance / delta); double lat2 = lat + (distance / delta); return new double[] {lng1, lat1, lng2, lat2}; } else { double lng1 = lng - distance / delta; double lng2 = lng + distance / delta; double lat1 = lat - (distance / delta); double lat2 = lat + (distance / delta); return new double[] {lng1, lat1, lng2, lat2}; } } /** * 得到两点间的距离 米 * @param lat1 * @param lng1 * @param lat2 * @param lng2 * @return */ public static double getDistanceOfMeter(double lat1, double lng1, double lat2, double lng2) { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10; return s; } private static double rad(double d) { return d * Math.PI / 180.0; } }
Zi-hao-Wei/YFTXWeb
src/tools/GeoUtil.java
610
/** * 地球半径:6378.137KM */
block_comment
zh-cn
package tools; public class GeoUtil { /** * 地球半 <SUF>*/ private static double EARTH_RADIUS = 6378.137; /** * 根据经纬度和距离返回一个矩形范围 * @param lng 经度 * @param lat 纬度 * @param distance 距离(单位为米) * @return [lng1,lat1, lng2,lat2] 矩形的左下角(lng1,lat1)和右上角(lng2,lat2) */ public static double[] getRectangle(double lng, double lat, long distance) { float delta = 111000; if (lng != 0 && lat != 0) { double lng1 = lng - distance / Math.abs(Math.cos(Math.toRadians(lat)) * delta); double lng2 = lng + distance / Math.abs(Math.cos(Math.toRadians(lat)) * delta); double lat1 = lat - (distance / delta); double lat2 = lat + (distance / delta); return new double[] {lng1, lat1, lng2, lat2}; } else { double lng1 = lng - distance / delta; double lng2 = lng + distance / delta; double lat1 = lat - (distance / delta); double lat2 = lat + (distance / delta); return new double[] {lng1, lat1, lng2, lat2}; } } /** * 得到两点间的距离 米 * @param lat1 * @param lng1 * @param lat2 * @param lng2 * @return */ public static double getDistanceOfMeter(double lat1, double lng1, double lat2, double lng2) { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10; return s; } private static double rad(double d) { return d * Math.PI / 180.0; } }
false
577
21
610
20
649
20
610
20
741
27
false
false
false
false
false
true
56081_3
package com.ziyue.furniture; import com.ziyue.furniture.blocks.ChairRegister; import com.ziyue.furniture.blocks.TableRegister; import com.ziyue.furniture.blocks.models.ChairBlock; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder; import net.fabricmc.fabric.api.event.player.UseBlockCallback; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricEntityTypeBuilder; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.SlabBlock; import net.minecraft.block.StairsBlock; import net.minecraft.block.enums.BlockHalf; import net.minecraft.block.enums.SlabType; import net.minecraft.entity.EntityDimensions; import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnGroup; import net.minecraft.entity.vehicle.MinecartEntity; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.Identifier; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3d; import net.minecraft.util.registry.Registry; public class Furniture implements ModInitializer { public static final String MOD_ID = "furniture"; public static final ItemGroup FURNITURE_GROUP = FabricItemGroupBuilder.build(new Identifier(MOD_ID, "itemgroup"), () -> new ItemStack(TableRegister.OAK_TABLE)); @Override public void onInitialize() { /*桌子*/ //橡木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "oak_table"), TableRegister.OAK_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "oak_table"), new BlockItem(TableRegister.OAK_TABLE, new Item.Settings().group(Furniture.FURNITURE_GROUP))); //云杉木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "spruce_table"), TableRegister.SPRUCE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "spruce_table"), new BlockItem(TableRegister.SPRUCE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //白桦木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "birch_table"), TableRegister.BIRCH_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "birch_table"), new BlockItem(TableRegister.BIRCH_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //丛林木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "jungle_table"), TableRegister.JUNGLE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "jungle_table"), new BlockItem(TableRegister.JUNGLE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //金合欢木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "acacia_table"), TableRegister.ACACIA_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "acacia_table"), new BlockItem(TableRegister.ACACIA_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //深色橡木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "dark_oak_table"), TableRegister.DARK_OAK_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "dark_oak_table"), new BlockItem(TableRegister.DARK_OAK_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //绯红菌桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "crimson_table"), TableRegister.CRIMSON_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "crimson_table"), new BlockItem(TableRegister.CRIMSON_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //诡异菌桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "warped_table"), TableRegister.WARPED_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "warped_table"), new BlockItem(TableRegister.WARPED_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //圆石桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "cobblestone_table"), TableRegister.COBBLESTONE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "cobblestone_table"), new BlockItem(TableRegister.COBBLESTONE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //石桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "stone_table"), TableRegister.STONE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "stone_table"), new BlockItem(TableRegister.STONE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //花岗岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "granite_table"), TableRegister.GRANITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "granite_table"), new BlockItem(TableRegister.GRANITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //闪长岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "diorite_table"), TableRegister.DIORITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "diorite_table"), new BlockItem(TableRegister.DIORITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //安山岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "andesite_table"), TableRegister.ANDESITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "andesite_table"), new BlockItem(TableRegister.ANDESITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //石英桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "quartz_table"), TableRegister.QUARTZ_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "quartz_table"), new BlockItem(TableRegister.QUARTZ_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //砂岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "sandstone_table"), TableRegister.SANDSTONE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "sandstone_table"), new BlockItem(TableRegister.SANDSTONE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //下界合金桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "netherite_table"), TableRegister.NETHERITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "netherite_table"), new BlockItem(TableRegister.NETHERITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); /*椅子*/ //橡木椅子 Registry.register(Registry.BLOCK, new Identifier("furniture", "oak_chair"), ChairRegister.OAK_CHAIR); Registry.register(Registry.ITEM, new Identifier("furniture", "oak_chair"), new BlockItem(ChairRegister.OAK_CHAIR, new Item.Settings().group(FURNITURE_GROUP))); registry } }
ZiYueCommentary/ZiYueCommentary
FabricMod/src/main/java/com/ziyue/furniture/Furniture.java
2,001
//白桦木桌子
line_comment
zh-cn
package com.ziyue.furniture; import com.ziyue.furniture.blocks.ChairRegister; import com.ziyue.furniture.blocks.TableRegister; import com.ziyue.furniture.blocks.models.ChairBlock; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder; import net.fabricmc.fabric.api.event.player.UseBlockCallback; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricEntityTypeBuilder; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.SlabBlock; import net.minecraft.block.StairsBlock; import net.minecraft.block.enums.BlockHalf; import net.minecraft.block.enums.SlabType; import net.minecraft.entity.EntityDimensions; import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnGroup; import net.minecraft.entity.vehicle.MinecartEntity; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.Identifier; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3d; import net.minecraft.util.registry.Registry; public class Furniture implements ModInitializer { public static final String MOD_ID = "furniture"; public static final ItemGroup FURNITURE_GROUP = FabricItemGroupBuilder.build(new Identifier(MOD_ID, "itemgroup"), () -> new ItemStack(TableRegister.OAK_TABLE)); @Override public void onInitialize() { /*桌子*/ //橡木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "oak_table"), TableRegister.OAK_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "oak_table"), new BlockItem(TableRegister.OAK_TABLE, new Item.Settings().group(Furniture.FURNITURE_GROUP))); //云杉木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "spruce_table"), TableRegister.SPRUCE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "spruce_table"), new BlockItem(TableRegister.SPRUCE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //白桦 <SUF> Registry.register(Registry.BLOCK, new Identifier("furniture", "birch_table"), TableRegister.BIRCH_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "birch_table"), new BlockItem(TableRegister.BIRCH_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //丛林木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "jungle_table"), TableRegister.JUNGLE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "jungle_table"), new BlockItem(TableRegister.JUNGLE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //金合欢木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "acacia_table"), TableRegister.ACACIA_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "acacia_table"), new BlockItem(TableRegister.ACACIA_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //深色橡木桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "dark_oak_table"), TableRegister.DARK_OAK_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "dark_oak_table"), new BlockItem(TableRegister.DARK_OAK_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //绯红菌桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "crimson_table"), TableRegister.CRIMSON_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "crimson_table"), new BlockItem(TableRegister.CRIMSON_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //诡异菌桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "warped_table"), TableRegister.WARPED_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "warped_table"), new BlockItem(TableRegister.WARPED_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //圆石桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "cobblestone_table"), TableRegister.COBBLESTONE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "cobblestone_table"), new BlockItem(TableRegister.COBBLESTONE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //石桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "stone_table"), TableRegister.STONE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "stone_table"), new BlockItem(TableRegister.STONE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //花岗岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "granite_table"), TableRegister.GRANITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "granite_table"), new BlockItem(TableRegister.GRANITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //闪长岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "diorite_table"), TableRegister.DIORITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "diorite_table"), new BlockItem(TableRegister.DIORITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //安山岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "andesite_table"), TableRegister.ANDESITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "andesite_table"), new BlockItem(TableRegister.ANDESITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //石英桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "quartz_table"), TableRegister.QUARTZ_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "quartz_table"), new BlockItem(TableRegister.QUARTZ_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //砂岩桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "sandstone_table"), TableRegister.SANDSTONE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "sandstone_table"), new BlockItem(TableRegister.SANDSTONE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); //下界合金桌子 Registry.register(Registry.BLOCK, new Identifier("furniture", "netherite_table"), TableRegister.NETHERITE_TABLE); Registry.register(Registry.ITEM, new Identifier("furniture", "netherite_table"), new BlockItem(TableRegister.NETHERITE_TABLE, new Item.Settings().group(FURNITURE_GROUP))); /*椅子*/ //橡木椅子 Registry.register(Registry.BLOCK, new Identifier("furniture", "oak_chair"), ChairRegister.OAK_CHAIR); Registry.register(Registry.ITEM, new Identifier("furniture", "oak_chair"), new BlockItem(ChairRegister.OAK_CHAIR, new Item.Settings().group(FURNITURE_GROUP))); registry } }
false
1,608
5
2,001
8
1,825
5
2,001
8
2,253
10
false
false
false
false
false
true
29127_4
class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) { return 0; } int i = 0; int profit = 0; int valley = prices[0]; // = 0 int peak = prices[0]; // = 0 while (i < prices.length - 1) { // i <= while (i < prices.length - 1 && prices[i] >= prices[i + 1]) i++; valley = prices[i]; while (i < prices.length - 1 && prices[i] <= prices[i + 1]) i++; peak = prices[i]; profit += peak - valley; } return profit; } } // 基本是抄答案了…… Solution 2 // 值得注意的是结束条件 该解包含了分情况讨论的多种条件 // 比如倒数第二个是peak 最后一个小于peak的情况 这时valley前的while会跳出 使valley == peak // 最后使profit += 0
Zichuanyun/go-shuati
chunlin/122.java
259
// 值得注意的是结束条件 该解包含了分情况讨论的多种条件
line_comment
zh-cn
class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) { return 0; } int i = 0; int profit = 0; int valley = prices[0]; // = 0 int peak = prices[0]; // = 0 while (i < prices.length - 1) { // i <= while (i < prices.length - 1 && prices[i] >= prices[i + 1]) i++; valley = prices[i]; while (i < prices.length - 1 && prices[i] <= prices[i + 1]) i++; peak = prices[i]; profit += peak - valley; } return profit; } } // 基本是抄答案了…… Solution 2 // 值得 <SUF> // 比如倒数第二个是peak 最后一个小于peak的情况 这时valley前的while会跳出 使valley == peak // 最后使profit += 0
false
243
19
259
21
258
17
259
21
316
38
false
false
false
false
false
true
60046_12
package WeeklyPractice.Aug24; import java.util.ArrayList; // 来自微软 // 给定两个数组A和B,比如 // A = { 0, 1, 1 } // B = { 1, 2, 3 } // A[0] = 0, B[0] = 1,表示0到1有双向道路 // A[1] = 1, B[1] = 2,表示1到2有双向道路 // A[2] = 1, B[2] = 3,表示1到3有双向道路 // 给定数字N,编号从0~N,所以一共N+1个节点 // 题目输入一定保证所有节点都联通,并且一定没有环 // 默认办公室是0节点,其他1~N节点上,每个节点上都有一个居民 // 每天所有居民都去往0节点上班 // 所有的居民都有一辆5座的车,也都乐意和别人一起坐车 // 车不管负重是多少,只要走过一条路,就耗费1的汽油 // 比如A、B、C的居民,开着自己的车来到D居民的位置,一共耗费3的汽油 // D居民和E居民之间,假设有一条路 // 那么D居民可以接上A、B、C,4个人可以用一辆车,去往E的话,就再耗费1的汽油 // 求所有居民去办公室的路上,最少耗费多少汽油 public class TravelMinFuel { public static int cnt; public static int minFuel(int[] a, int[] b, int n) { cnt = 0; ArrayList<ArrayList<Integer>> list = new ArrayList<>(); for (int i = 0; i <= n; i++) { list.add(new ArrayList<>()); } for (int i = 0; i < a.length; i++) { list.get(a[i]).add(b[i]); list.get(b[i]).add(a[i]); } int[] dfn = new int[n + 1]; int[] size = new int[n + 1]; int[] cost = new int[n + 1]; dfs(dfn, size, cost, list, 0); return cost[0]; } public static void dfs(int[] dfn, int[] size, int[] cost, ArrayList<ArrayList<Integer>> graph, int cur) { dfn[cur] = ++cnt; size[cur] = 1; for (int next : graph.get(cur)) { if (dfn[next] == 0) { dfs(dfn, size, cost, graph, next); cost[cur] += (size[next] + 4) / 5; size[cur] += size[next]; cost[cur] += cost[next]; } } } public static void main(String[] args) { int[] a1 = {0, 1, 1}; int[] b1 = {1, 2, 3}; int n1 = 3; System.out.println(minFuel(a1, b1, n1)); int[] a2 = {1, 1, 1, 9, 9, 9, 9, 7, 8}; int[] b2 = {2, 0, 3, 1, 6, 5, 4, 0, 0}; int n2 = 9; System.out.println(minFuel(a2, b2, n2)); } }
Ziming-Gong/Algorithm
BasicAlgo/src/WeeklyPractice/Aug24/TravelMinFuel.java
885
// 车不管负重是多少,只要走过一条路,就耗费1的汽油
line_comment
zh-cn
package WeeklyPractice.Aug24; import java.util.ArrayList; // 来自微软 // 给定两个数组A和B,比如 // A = { 0, 1, 1 } // B = { 1, 2, 3 } // A[0] = 0, B[0] = 1,表示0到1有双向道路 // A[1] = 1, B[1] = 2,表示1到2有双向道路 // A[2] = 1, B[2] = 3,表示1到3有双向道路 // 给定数字N,编号从0~N,所以一共N+1个节点 // 题目输入一定保证所有节点都联通,并且一定没有环 // 默认办公室是0节点,其他1~N节点上,每个节点上都有一个居民 // 每天所有居民都去往0节点上班 // 所有的居民都有一辆5座的车,也都乐意和别人一起坐车 // 车不 <SUF> // 比如A、B、C的居民,开着自己的车来到D居民的位置,一共耗费3的汽油 // D居民和E居民之间,假设有一条路 // 那么D居民可以接上A、B、C,4个人可以用一辆车,去往E的话,就再耗费1的汽油 // 求所有居民去办公室的路上,最少耗费多少汽油 public class TravelMinFuel { public static int cnt; public static int minFuel(int[] a, int[] b, int n) { cnt = 0; ArrayList<ArrayList<Integer>> list = new ArrayList<>(); for (int i = 0; i <= n; i++) { list.add(new ArrayList<>()); } for (int i = 0; i < a.length; i++) { list.get(a[i]).add(b[i]); list.get(b[i]).add(a[i]); } int[] dfn = new int[n + 1]; int[] size = new int[n + 1]; int[] cost = new int[n + 1]; dfs(dfn, size, cost, list, 0); return cost[0]; } public static void dfs(int[] dfn, int[] size, int[] cost, ArrayList<ArrayList<Integer>> graph, int cur) { dfn[cur] = ++cnt; size[cur] = 1; for (int next : graph.get(cur)) { if (dfn[next] == 0) { dfs(dfn, size, cost, graph, next); cost[cur] += (size[next] + 4) / 5; size[cur] += size[next]; cost[cur] += cost[next]; } } } public static void main(String[] args) { int[] a1 = {0, 1, 1}; int[] b1 = {1, 2, 3}; int n1 = 3; System.out.println(minFuel(a1, b1, n1)); int[] a2 = {1, 1, 1, 9, 9, 9, 9, 7, 8}; int[] b2 = {2, 0, 3, 1, 6, 5, 4, 0, 0}; int n2 = 9; System.out.println(minFuel(a2, b2, n2)); } }
false
780
19
885
26
864
20
885
26
1,066
40
false
false
false
false
false
true
39589_0
package Coding_Interviews; /** * 数组中出现次数超过一半的数字 * 题目描述 * 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 * 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。 * * https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking * * 解题思路 * 1、通过HashMap方式来做,以数字为key,value是重复的次数,最后找出重复次数最多的那个,判断是否大于length/2 * 2、类似于“士兵攻阵地”,我们把数组想象为一群士兵,这些士兵来自不同阵营,士兵们一个一个走出军营去攻打阵地, * 第一个兵占领阵地以后,后面来的兵可能是自己人,也可能不是自己人,是自己人的话,count+1,不是自己人的话,同归于尽, * 最后肯定剩下一个人活到最后,但是这个人并不一定属于人最多的那一个阵营。 * * 比如:'3,3,3,1,2,0',第一个3先上去,第二个3再上去,第三个3再上去,这时候count=3,后面1上去,3-1=2,2上去,2-1=1,1上去,1-1=0, * 这时候留在最后的是0,但是0显然不是人数最多那个阵营的兵,人数最多的那个阵营都被别的阵营消耗掉了。如果出场顺序变为:'3,1,3,3,2,0', * 那最后留下的人就是3,但是3个3并没有> (6/2)。如果3的数量再多一个,那么不论怎么出场,最后剩下的就是3,毕竟人多,与一半的人同归于尽后总会剩下人的, * 这时候显然4个3>(7/2)。 * * Created by ZingBug on 2018/6/25. */ public class MoreThanHalfNum { public int MoreThanHalfNum_Solution(int[] array) { int len=array.length; if(len==0) { return 0; } int n=array[0]; int count=0; for(int val:array) { if(val==n) { count++; } else { count--; } if(count==0) { n=val; count=1; } } //再确定一下 count=0; for(int val:array) { if(n==val) { count++; } } return count*2>len?n:0; } public static void main(String[] args) { MoreThanHalfNum m=new MoreThanHalfNum(); int[] array={1,2,3,2,2,2,5,4,2}; System.out.println(m.MoreThanHalfNum_Solution(array)); } }
ZingBug/AlgorithmProblems
AlgorithmProblems/src/Coding_Interviews/MoreThanHalfNum.java
866
/** * 数组中出现次数超过一半的数字 * 题目描述 * 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 * 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。 * * https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking * * 解题思路 * 1、通过HashMap方式来做,以数字为key,value是重复的次数,最后找出重复次数最多的那个,判断是否大于length/2 * 2、类似于“士兵攻阵地”,我们把数组想象为一群士兵,这些士兵来自不同阵营,士兵们一个一个走出军营去攻打阵地, * 第一个兵占领阵地以后,后面来的兵可能是自己人,也可能不是自己人,是自己人的话,count+1,不是自己人的话,同归于尽, * 最后肯定剩下一个人活到最后,但是这个人并不一定属于人最多的那一个阵营。 * * 比如:'3,3,3,1,2,0',第一个3先上去,第二个3再上去,第三个3再上去,这时候count=3,后面1上去,3-1=2,2上去,2-1=1,1上去,1-1=0, * 这时候留在最后的是0,但是0显然不是人数最多那个阵营的兵,人数最多的那个阵营都被别的阵营消耗掉了。如果出场顺序变为:'3,1,3,3,2,0', * 那最后留下的人就是3,但是3个3并没有> (6/2)。如果3的数量再多一个,那么不论怎么出场,最后剩下的就是3,毕竟人多,与一半的人同归于尽后总会剩下人的, * 这时候显然4个3>(7/2)。 * * Created by ZingBug on 2018/6/25. */
block_comment
zh-cn
package Coding_Interviews; /** * 数组中 <SUF>*/ public class MoreThanHalfNum { public int MoreThanHalfNum_Solution(int[] array) { int len=array.length; if(len==0) { return 0; } int n=array[0]; int count=0; for(int val:array) { if(val==n) { count++; } else { count--; } if(count==0) { n=val; count=1; } } //再确定一下 count=0; for(int val:array) { if(n==val) { count++; } } return count*2>len?n:0; } public static void main(String[] args) { MoreThanHalfNum m=new MoreThanHalfNum(); int[] array={1,2,3,2,2,2,5,4,2}; System.out.println(m.MoreThanHalfNum_Solution(array)); } }
false
737
511
866
619
822
535
866
619
1,140
834
true
true
true
true
true
false
50081_2
package com.tedu.manager; import com.tedu.element.ElementObj; import com.tedu.element.Enemy; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Random; public class EnemyManager { private static EnemyManager em; // 敌人集合 public static List<ElementObj> enemies = new ArrayList<ElementObj>(); //当前得分 private static int score = 0; // 敌人方向枚举 public enum EnemyDir{ LEFT,RIGHT,UP,DOWN } //敌人行为枚举 public enum EnemyAction{ HORIZONTALMOVE,VERTICALMOVE,STOP } private static final String[] NAMES = { "行人", "乐园", "花草", "人才", "左手", "目的", "课文", "优点", "年代", "灰尘", "沙子", "小说", "儿女", "难题", "明星", "本子", "彩色", "水珠", "路灯", "把握", "房屋", "心愿", "左边", "新闻", "早点", "市场", "雨点", "细雨", "书房", "毛巾", "画家", "元旦", "绿豆", "本领", "起点", "青菜", "土豆", "总结", "礼貌", "右边", "老虎", "老鼠", "猴子", "树懒", "斑马", "小狗", "狐狸", "狗熊", "黑熊", "大象", "豹子", "麝牛", "狮子", "熊猫", "疵猪", "羚羊", "驯鹿", "考拉", "犀牛", "给翔", "猩猩", "海牛", "水獭", "海豚", "海象", "刺猬", "袋鼠", "犹徐", "河马", "海豹", "海狮", "编蝠", "白虎", "狸猫", "水牛", "山羊", "绵羊", "牦牛", "猿猴", "松鼠", "野猪", "豪猪", "廉鹿", "花豹", "野狼", "灰狼", "蜂猴", "熊猴", "叶猴", "紫貂", "貂熊", "熊狸", "云豹", "雪豹", "黑鹿", "野马", "惬鹿", "坡鹿", "豚鹿", "野牛", "藏羚", "河狸", "驼鹿", "黄羊", "繁羚", "斑羚", "岩羊", "盘羊", "雪免" }; private static final String[] MODIFIY = {"可爱", "傻傻", "萌萌", "羞差", "笨笨", "呆呆", "美丽", "聪明", "伶俐", "狡猾", "胖乎乎", "粉嫩嫩", "白胖胖", "漂亮", "可爱", "聪明", "懂事", "乖巧", "淘气", "淘气", "顽劣", "调皮", "顽皮", "天真", "可爱", "无邪", "单纯", "纯洁", "无暇", "纯真", "稚气", "温润", "好奇"}; public static final int ENEMY_AI_INTERVAL = 5000; public static final double ENEMY_FIRE_RATE = 0.02; private EnemyManager() { enemies = new ArrayList<ElementObj>(); } public static void RegisterEnemy(ElementObj enemy) { enemies.add(enemy); } public static int GetSize(){ return enemies.size(); } public static int GetScore(){ return score; } public static void AddScore(int a){ score += a; } public static void Clear(){ score = 0; enemies.clear(); } // public static synchronized EnemyManager getEnemyManager() { // if(em == null) {//控制锁定 // em = new EnemyManager(); // } // return em; // } public static String getRandomName() { return MODIFIY[getRandomNumber(0, MODIFIY.length)] + "的" + NAMES[getRandomNumber(0, NAMES.length)]; } public static Color getRandomColor() { return new Color(getRandomNumber(0, 255), getRandomNumber(0, 255), getRandomNumber(0, 255)); } public static int getRandomNumber(int min, int max) { Random random = new Random(); return random.nextInt(max - min) + min; } }
ZishuNing/TankWar-Scnu
src/com/tedu/manager/EnemyManager.java
1,247
// 敌人方向枚举
line_comment
zh-cn
package com.tedu.manager; import com.tedu.element.ElementObj; import com.tedu.element.Enemy; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Random; public class EnemyManager { private static EnemyManager em; // 敌人集合 public static List<ElementObj> enemies = new ArrayList<ElementObj>(); //当前得分 private static int score = 0; // 敌人 <SUF> public enum EnemyDir{ LEFT,RIGHT,UP,DOWN } //敌人行为枚举 public enum EnemyAction{ HORIZONTALMOVE,VERTICALMOVE,STOP } private static final String[] NAMES = { "行人", "乐园", "花草", "人才", "左手", "目的", "课文", "优点", "年代", "灰尘", "沙子", "小说", "儿女", "难题", "明星", "本子", "彩色", "水珠", "路灯", "把握", "房屋", "心愿", "左边", "新闻", "早点", "市场", "雨点", "细雨", "书房", "毛巾", "画家", "元旦", "绿豆", "本领", "起点", "青菜", "土豆", "总结", "礼貌", "右边", "老虎", "老鼠", "猴子", "树懒", "斑马", "小狗", "狐狸", "狗熊", "黑熊", "大象", "豹子", "麝牛", "狮子", "熊猫", "疵猪", "羚羊", "驯鹿", "考拉", "犀牛", "给翔", "猩猩", "海牛", "水獭", "海豚", "海象", "刺猬", "袋鼠", "犹徐", "河马", "海豹", "海狮", "编蝠", "白虎", "狸猫", "水牛", "山羊", "绵羊", "牦牛", "猿猴", "松鼠", "野猪", "豪猪", "廉鹿", "花豹", "野狼", "灰狼", "蜂猴", "熊猴", "叶猴", "紫貂", "貂熊", "熊狸", "云豹", "雪豹", "黑鹿", "野马", "惬鹿", "坡鹿", "豚鹿", "野牛", "藏羚", "河狸", "驼鹿", "黄羊", "繁羚", "斑羚", "岩羊", "盘羊", "雪免" }; private static final String[] MODIFIY = {"可爱", "傻傻", "萌萌", "羞差", "笨笨", "呆呆", "美丽", "聪明", "伶俐", "狡猾", "胖乎乎", "粉嫩嫩", "白胖胖", "漂亮", "可爱", "聪明", "懂事", "乖巧", "淘气", "淘气", "顽劣", "调皮", "顽皮", "天真", "可爱", "无邪", "单纯", "纯洁", "无暇", "纯真", "稚气", "温润", "好奇"}; public static final int ENEMY_AI_INTERVAL = 5000; public static final double ENEMY_FIRE_RATE = 0.02; private EnemyManager() { enemies = new ArrayList<ElementObj>(); } public static void RegisterEnemy(ElementObj enemy) { enemies.add(enemy); } public static int GetSize(){ return enemies.size(); } public static int GetScore(){ return score; } public static void AddScore(int a){ score += a; } public static void Clear(){ score = 0; enemies.clear(); } // public static synchronized EnemyManager getEnemyManager() { // if(em == null) {//控制锁定 // em = new EnemyManager(); // } // return em; // } public static String getRandomName() { return MODIFIY[getRandomNumber(0, MODIFIY.length)] + "的" + NAMES[getRandomNumber(0, NAMES.length)]; } public static Color getRandomColor() { return new Color(getRandomNumber(0, 255), getRandomNumber(0, 255), getRandomNumber(0, 255)); } public static int getRandomNumber(int min, int max) { Random random = new Random(); return random.nextInt(max - min) + min; } }
false
969
7
1,247
8
1,072
6
1,247
8
1,549
14
false
false
false
false
false
true
61406_0
import java.util.HashMap; import java.util.List; import java.util.Map; /** * 554. 砖墙 * 你的面前有一堵矩形的、由 n 行砖块组成的砖墙。这些砖块高度相同(也就是一个单位高)但是宽度不同。每一行砖块的宽度之和应该相等。 * 你现在要画一条 自顶向下 的、穿过 最少 砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。 * 给你一个二维数组 wall ,该数组包含这堵墙的相关信息。其中,wall[i] 是一个代表从左至右每块砖的宽度的数组。你需要找出怎样画才能使这条线 穿过的砖块数量最少 ,并且返回 穿过的砖块数量 。 * <p> * 示例 1: * 输入:wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] * 输出:2 * <p> * 示例 2: * 输入:wall = [[1],[1],[1]] * 输出:3 * <p> * 提示: * n == wall.length * 1 <= n <= 104 * 1 <= wall[i].length <= 104 * 1 <= sum(wall[i].length) <= 2 * 104 * 对于每一行 i ,sum(wall[i]) 应当是相同的 * 1 <= wall[i][j] <= 231 - 1 */ public class Question554_BrickWall { public static void main(String[] args) { } } class Solution554 { public int leastBricks(List<List<Integer>> wall) { HashMap<Integer, Integer> hashMap = new HashMap<>(); for(List<Integer> bricks : wall) { int sum = 0; for(int i = 0; i < bricks.size() - 1; i++) { int brick = bricks.get(i); sum += brick; hashMap.put(sum, hashMap.getOrDefault(sum, 0) + 1); } } int maxNum = 0; for(Map.Entry<Integer, Integer> entry : hashMap.entrySet()) { maxNum = Math.max(maxNum, entry.getValue()); } return wall.size() - maxNum; } }
Zjly/LeetCode
src/main/java/Question554_BrickWall.java
700
/** * 554. 砖墙 * 你的面前有一堵矩形的、由 n 行砖块组成的砖墙。这些砖块高度相同(也就是一个单位高)但是宽度不同。每一行砖块的宽度之和应该相等。 * 你现在要画一条 自顶向下 的、穿过 最少 砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。 * 给你一个二维数组 wall ,该数组包含这堵墙的相关信息。其中,wall[i] 是一个代表从左至右每块砖的宽度的数组。你需要找出怎样画才能使这条线 穿过的砖块数量最少 ,并且返回 穿过的砖块数量 。 * <p> * 示例 1: * 输入:wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] * 输出:2 * <p> * 示例 2: * 输入:wall = [[1],[1],[1]] * 输出:3 * <p> * 提示: * n == wall.length * 1 <= n <= 104 * 1 <= wall[i].length <= 104 * 1 <= sum(wall[i].length) <= 2 * 104 * 对于每一行 i ,sum(wall[i]) 应当是相同的 * 1 <= wall[i][j] <= 231 - 1 */
block_comment
zh-cn
import java.util.HashMap; import java.util.List; import java.util.Map; /** * 554 <SUF>*/ public class Question554_BrickWall { public static void main(String[] args) { } } class Solution554 { public int leastBricks(List<List<Integer>> wall) { HashMap<Integer, Integer> hashMap = new HashMap<>(); for(List<Integer> bricks : wall) { int sum = 0; for(int i = 0; i < bricks.size() - 1; i++) { int brick = bricks.get(i); sum += brick; hashMap.put(sum, hashMap.getOrDefault(sum, 0) + 1); } } int maxNum = 0; for(Map.Entry<Integer, Integer> entry : hashMap.entrySet()) { maxNum = Math.max(maxNum, entry.getValue()); } return wall.size() - maxNum; } }
false
554
365
700
446
613
372
700
446
860
574
true
true
true
true
true
false
44058_1
package zks.leet1.a5; import org.junit.jupiter.api.Test; /* 59. 螺旋矩阵 II 给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 示例 1: 输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]] 示例 2: 输入:n = 1 输出:[[1]] */ public class Q59 { /* 想象一个王八从[0][-1]处出发向右爬,首先它要看前面是路还是墙,也就是说是0还是正数,如果前面是0就前进,并把脚下的0填上数字,如果前方是数字,就右转前进 本问题中,前进步数固定为n*n,就用这个来控制循环终止即可 */ enum Direction { UP, DOWN, LEFT, RIGHT; private Direction turnRight() { switch (this) { case UP: return RIGHT; case RIGHT: return DOWN; case DOWN: return LEFT; } return UP; } //提供当前坐标以及前进方向,返回能否前进 private boolean moveForward(int[][] matrix, int r, int c, Direction direction) { int n = matrix.length; switch (direction) { case DOWN: return r + 1 < n && matrix[r + 1][c] == 0; case UP: return r - 1 > -1 && matrix[r - 1][c] == 0; case LEFT: return c - 1 > -1 && matrix[r][c - 1] == 0; case RIGHT: return c + 1 < n && matrix[r][c + 1] == 0; } return true; } } public int[][] generateMatrix(int n) { int[][] ans = new int[n][n]; int r = 0, c = -1;//起点 Direction direction = Direction.RIGHT;//方向向右 for (int i = 1; i <= n * n; i++) { //先看,若不能前进,则调整方向 if (!direction.moveForward(ans, r, c, direction)) direction = direction.turnRight(); switch (direction) {//前进 case UP: r--; break; case DOWN: r++; break; case LEFT: c--; break; case RIGHT: c++; break; } ans[r][c] = i;//填数 } return ans; } @Test public void T59() { this.generateMatrix(4); } }
ZksCale/LeetCode
Leet1/src/main/java/zks/leet1/a5/Q59.java
665
/* 想象一个王八从[0][-1]处出发向右爬,首先它要看前面是路还是墙,也就是说是0还是正数,如果前面是0就前进,并把脚下的0填上数字,如果前方是数字,就右转前进 本问题中,前进步数固定为n*n,就用这个来控制循环终止即可 */
block_comment
zh-cn
package zks.leet1.a5; import org.junit.jupiter.api.Test; /* 59. 螺旋矩阵 II 给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 示例 1: 输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]] 示例 2: 输入:n = 1 输出:[[1]] */ public class Q59 { /* 想象一 <SUF>*/ enum Direction { UP, DOWN, LEFT, RIGHT; private Direction turnRight() { switch (this) { case UP: return RIGHT; case RIGHT: return DOWN; case DOWN: return LEFT; } return UP; } //提供当前坐标以及前进方向,返回能否前进 private boolean moveForward(int[][] matrix, int r, int c, Direction direction) { int n = matrix.length; switch (direction) { case DOWN: return r + 1 < n && matrix[r + 1][c] == 0; case UP: return r - 1 > -1 && matrix[r - 1][c] == 0; case LEFT: return c - 1 > -1 && matrix[r][c - 1] == 0; case RIGHT: return c + 1 < n && matrix[r][c + 1] == 0; } return true; } } public int[][] generateMatrix(int n) { int[][] ans = new int[n][n]; int r = 0, c = -1;//起点 Direction direction = Direction.RIGHT;//方向向右 for (int i = 1; i <= n * n; i++) { //先看,若不能前进,则调整方向 if (!direction.moveForward(ans, r, c, direction)) direction = direction.turnRight(); switch (direction) {//前进 case UP: r--; break; case DOWN: r++; break; case LEFT: c--; break; case RIGHT: c++; break; } ans[r][c] = i;//填数 } return ans; } @Test public void T59() { this.generateMatrix(4); } }
false
619
88
665
99
689
87
665
99
885
139
false
false
false
false
false
true
25117_5
package com.zoctan.bean; import com.alibaba.fastjson.annotation.JSONField; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 有道翻译响应实体 * http://ai.youdao.com/docs/doc-trans-api.s#p03 * * @author Zoctan * @date 2018/06/29 */ public class YoudaoBean { /** * 错误返回码 一定存在 */ private Integer errorCode; /** * 源语言 查询正确时一定存在 */ private String query; /** * 翻译结果 查询正确时一定存在 */ private List<String> translation; /** * 词义 基本词典,查词时才有 */ private BasicBean basic; /** * 翻译结果发音地址 翻译成功一定存在 */ private String tSpeakUrl; /** * 源语言发音地址 翻译成功一定存在 */ private String speakUrl; @Override public String toString() { try { final String translation = this.getTranslation().stream() .collect(Collectors.joining(" ", "翻译:", "\n")); final String phonetic = Stream.of(this.getBasic().getPhonetic()) .filter(Objects::nonNull) .collect(Collectors.joining(" ", "音标:", "\n")); final String explains = this.getBasic().getExplains().stream() .collect(Collectors.joining("\n", "词义:\n", "")); return translation + phonetic + explains; } catch (final NullPointerException ignored) { return "无法找到该单词哦"; } } public Integer getErrorCode() { return this.errorCode; } public void setErrorCode(final Integer errorCode) { this.errorCode = errorCode; } public String getQuery() { return this.query; } public void setQuery(final String query) { this.query = query; } public List<String> getTranslation() { return this.translation; } public void setTranslation(final List<String> translation) { this.translation = translation; } public BasicBean getBasic() { return this.basic; } public void setBasic(final BasicBean basic) { this.basic = basic; } public String gettSpeakUrl() { return this.tSpeakUrl; } public void settSpeakUrl(final String tSpeakUrl) { this.tSpeakUrl = tSpeakUrl; } public String getSpeakUrl() { return this.speakUrl; } public void setSpeakUrl(final String speakUrl) { this.speakUrl = speakUrl; } public static class BasicBean { /** * 默认音标,默认是英式音标,英文查词成功,一定存在 */ private String phonetic; /** * 美式音标,英文查词成功,一定存在 */ @JSONField(name = "us-phonetic") private String usPhonetic; /** * 英式音标,英文查词成功,一定存在 */ @JSONField(name = "uk-phonetic") private String ukPhonetic; /** * 英式发音,英文查词成功,一定存在 */ @JSONField(name = "uk-speech") private String ukSpeech; /** * 美式发音,英文查词成功,一定存在 */ @JSONField(name = "us-speech") private String usSpeech; /** * 基本释义 */ private List<String> explains; public String getPhonetic() { return this.phonetic; } public void setPhonetic(final String phonetic) { this.phonetic = phonetic; } public List<String> getExplains() { return this.explains; } public void setExplains(final List<String> explains) { this.explains = explains; } public String getUsPhonetic() { return this.usPhonetic; } public void setUsPhonetic(final String usPhonetic) { this.usPhonetic = usPhonetic; } public String getUkPhonetic() { return this.ukPhonetic; } public void setUkPhonetic(final String ukPhonetic) { this.ukPhonetic = ukPhonetic; } public String getUkSpeech() { return this.ukSpeech; } public void setUkSpeech(final String ukSpeech) { this.ukSpeech = ukSpeech; } public String getUsSpeech() { return this.usSpeech; } public void setUsSpeech(final String usSpeech) { this.usSpeech = usSpeech; } } }
Zoctan/Translator
src/main/java/com/zoctan/bean/YoudaoBean.java
1,170
/** * 翻译结果发音地址 翻译成功一定存在 */
block_comment
zh-cn
package com.zoctan.bean; import com.alibaba.fastjson.annotation.JSONField; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 有道翻译响应实体 * http://ai.youdao.com/docs/doc-trans-api.s#p03 * * @author Zoctan * @date 2018/06/29 */ public class YoudaoBean { /** * 错误返回码 一定存在 */ private Integer errorCode; /** * 源语言 查询正确时一定存在 */ private String query; /** * 翻译结果 查询正确时一定存在 */ private List<String> translation; /** * 词义 基本词典,查词时才有 */ private BasicBean basic; /** * 翻译结 <SUF>*/ private String tSpeakUrl; /** * 源语言发音地址 翻译成功一定存在 */ private String speakUrl; @Override public String toString() { try { final String translation = this.getTranslation().stream() .collect(Collectors.joining(" ", "翻译:", "\n")); final String phonetic = Stream.of(this.getBasic().getPhonetic()) .filter(Objects::nonNull) .collect(Collectors.joining(" ", "音标:", "\n")); final String explains = this.getBasic().getExplains().stream() .collect(Collectors.joining("\n", "词义:\n", "")); return translation + phonetic + explains; } catch (final NullPointerException ignored) { return "无法找到该单词哦"; } } public Integer getErrorCode() { return this.errorCode; } public void setErrorCode(final Integer errorCode) { this.errorCode = errorCode; } public String getQuery() { return this.query; } public void setQuery(final String query) { this.query = query; } public List<String> getTranslation() { return this.translation; } public void setTranslation(final List<String> translation) { this.translation = translation; } public BasicBean getBasic() { return this.basic; } public void setBasic(final BasicBean basic) { this.basic = basic; } public String gettSpeakUrl() { return this.tSpeakUrl; } public void settSpeakUrl(final String tSpeakUrl) { this.tSpeakUrl = tSpeakUrl; } public String getSpeakUrl() { return this.speakUrl; } public void setSpeakUrl(final String speakUrl) { this.speakUrl = speakUrl; } public static class BasicBean { /** * 默认音标,默认是英式音标,英文查词成功,一定存在 */ private String phonetic; /** * 美式音标,英文查词成功,一定存在 */ @JSONField(name = "us-phonetic") private String usPhonetic; /** * 英式音标,英文查词成功,一定存在 */ @JSONField(name = "uk-phonetic") private String ukPhonetic; /** * 英式发音,英文查词成功,一定存在 */ @JSONField(name = "uk-speech") private String ukSpeech; /** * 美式发音,英文查词成功,一定存在 */ @JSONField(name = "us-speech") private String usSpeech; /** * 基本释义 */ private List<String> explains; public String getPhonetic() { return this.phonetic; } public void setPhonetic(final String phonetic) { this.phonetic = phonetic; } public List<String> getExplains() { return this.explains; } public void setExplains(final List<String> explains) { this.explains = explains; } public String getUsPhonetic() { return this.usPhonetic; } public void setUsPhonetic(final String usPhonetic) { this.usPhonetic = usPhonetic; } public String getUkPhonetic() { return this.ukPhonetic; } public void setUkPhonetic(final String ukPhonetic) { this.ukPhonetic = ukPhonetic; } public String getUkSpeech() { return this.ukSpeech; } public void setUkSpeech(final String ukSpeech) { this.ukSpeech = ukSpeech; } public String getUsSpeech() { return this.usSpeech; } public void setUsSpeech(final String usSpeech) { this.usSpeech = usSpeech; } } }
false
1,081
20
1,170
18
1,236
18
1,170
18
1,492
33
false
false
false
false
false
true
56666_2
package ZtlApi; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import ZtlApi.ZtlManager; //20210730 修改重复申请权限问题,申请两次没通过就不申请了,防止log刷屏 //20201105 修改getValue(String dir) 接口的返回值,当前GPIO的dir值不相等时,设置它的dir然后再返回value //20201102 修改GPIO口不存在时崩溃的问题 //20200916 去掉了数字openPort。新的app必须使用字符类型的gpio 实现51 71兼容 public class Gpio { private static final String TAG = "GPIO"; private int mPort; private boolean isGpioPortPrepared = false; private File mGpioExport = null; private File mGpioUnExport = null; private File mGpioPort = null; private File mGpioPortDirection = null; private File mGpioPortValue = null; private String gpio_export = "/sys/class/gpio/export"; private String gpio_unexport = "/sys/class/gpio/unexport"; private String gpio_port = "/sys/class/gpio/gpio"; String gpio_name; public static final String rk3288[] = {"", "GPIO0_C2", "GPIO7_B5", "GPIO8_B0", "GPIO7_B4", "GPIO7_C5", "GPIO7_B3", "GPIO8_A2", "GPIO7_A6", "GPIO8_A1", "GPIO7_A5"}; public static final String rk3126c[] = {"", "GPIO1_C7", "GPIO2_A2", "GPIO1_A7", "GPIO2_A0", "GPIO2_A1", "GPIO0_C7", "GPIO2_A6", "GPIO2_A3", "GPIO1_A3", "GPIO3_C5"}; public static final String CQA64[] = {"", "PE7", "PE4", "PE3", "PE2", "PE1"}; //public static final String rk3328[] = {"GPIO3_A0"}; public static final String rk3368[] = {"", "GPIO1_A2", "GPIO1_B6", "GPIO1_A3", "GPIO1_B7", "GPIO1_A4", "GPIO1_C0", "GPIO1_A5", "GPIO1_C1", "GPIO1_A6", "GPIO1_A7"}; public static final String rk3399[] = {"", "GPIO2_B2", "GPIO2_A5", "GPIO2_A3", "GPIO2_A1", "GPIO2_A6", "GPIO2_B0", "GPIO2_A4", "GPIO2_B1", "GPIO2_B4", "GPIO2_A0", "GPIO2_A7", "GPIO2_A2"}; // public static final String rk3399[] = {"GPIO1_D0", "GPIO1_A0", "GPIO1_A2", "GPIO1_C6", "GPIO2_A5", "GPIO2_A3", "GPIO2_A6", "GPIO2_A4", "GPIO2_A2"}; public static final HashMap<String, String[]> GpioNameMap = new HashMap<String, String[]>() {{ put("rk3288", rk3288); put("rk3126", rk3126c); put("A64", CQA64); //put("rk3328",rk3328); put("rk3368", rk3368); put("rk3399", rk3399); }}; public Gpio() { } //直接输入GPIO7_A5 之类 省得每次都按计算器 public boolean open(String strPort) { if (strPort == null || strPort.isEmpty()) return false; gpio_name = strPort; //71 51兼容 int nValue = ZtlManager.GetInstance().gpioStringToInt(strPort); if (nValue == -1) { return false; } this.mPort = nValue; this.mGpioExport = new File(this.gpio_export); this.mGpioUnExport = new File(this.gpio_unexport); this.isGpioPortPrepared = prepare_gpio_port(this.mPort); return isGpioPortPrepared; } //直接输入GPIO7_A5 之类 省得每次都按计算器 public boolean open(int strPort) { gpio_name = strPort+""; //71 51兼容 int nValue = strPort; if (nValue == -1) { return false; } this.mPort = nValue; this.mGpioExport = new File(this.gpio_export); this.mGpioUnExport = new File(this.gpio_unexport); this.isGpioPortPrepared = prepare_gpio_port(this.mPort); return isGpioPortPrepared; } //获取当前GPIO的Direction public String getDirection() { if (isGpioPortPrepared == false) { return "unknown"; } String strDir = null; if (this.mGpioPortDirection == null) { return "unknown"; } if (this.mGpioPortDirection.exists()) { strDir = readGpioNode(this.mGpioPortDirection); } else { return "unknown"; } return strDir; } String lastError = ""; //设置GPIO的Direction public void setDirection(String dir) { if (isGpioPortPrepared == false) { return; } //如果系统占用该IO口,不执行setDirection if (this.mGpioPortDirection == null) return; if (getDirection().equals(dir) == false) { writeGpioNode(this.mGpioPortDirection, dir); } } //获取当前direction的value public int getValue() { if (isGpioPortPrepared == false) { return -1; } int value = -1; if (this.mGpioPortDirection != null) { String string = readGpioNode(this.mGpioPortValue); if (string == null) { return -1; } if (string.equals("0")) value = 0; else if (string.equals("1")) { value = 1; } else { try { value = Integer.valueOf(string); } catch (NumberFormatException m) { return -1; } } } return value; } //获取指定direction的value public int getValue(String direction)//in out { if (isGpioPortPrepared == false) { return -1; } String strCurDirection = null; //该IO口不存在(被系统占用)返回-1 if (this.mGpioPort.exists() == false) { return -1; } //当前direction目录不存在 if (this.mGpioPortDirection.exists() == false) { return -1; } //获取到当前direction是in 还是out strCurDirection = readGpioNode(this.mGpioPortDirection); if (strCurDirection.equals(direction)) { return getValue(); } else { setDirection(direction); return getValue(); } } //设置当前direction的value public void setValue(int value) { if (isGpioPortPrepared == false) { return; } if (getValue() != value) { writeGpioNode(this.mGpioPortValue, Integer.toString(value)); } } //设置指定direction的value //direction = "in" or "out" public void setValue(String direction, int value) { if (isGpioPortPrepared == false) { return; } if (getDirection().equals(direction) == false) { writeGpioNode(this.mGpioPortDirection, direction); } writeGpioNode(this.mGpioPortValue, Integer.toString(value)); } int trynCount = 0;//表示获取权限的次数 private void writeGpioNode(File file, String value) { if (file.exists() == false) return; if (file.exists()) { // System.out.println("write " + flag + " to " + file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(value.getBytes(), 0, value.getBytes().length); fos.flush(); fos.close(); trynCount = 0; } catch (IOException e) { String error = e.toString(); if (error.contains("Permission denied")) { trynCount++; ZtlManager.GetInstance().execRootCmdSilent("chmod 777 " + file.getAbsolutePath()); Log.e(TAG, "正在申请权限"); //判断节点是否有权限,没有权限的话退出 if (trynCount > 2) { Log.e(TAG, "权限申请不通过"); return; } writeGpioNode(file, value); } else { trynCount++; Log.e(TAG, "writeGpioNode " + gpio_name + " 错误"); e.printStackTrace(); if (trynCount > 2) { Log.e(TAG, "权限申请不通过"); return; } } } } } private boolean prepare_gpio_port(int port) { if (this.mGpioExport == null || this.mGpioExport.exists() == false) { return false; } String path = this.gpio_port + port; boolean bbb = ZtlManager.GetInstance().isExist(path); if (bbb == false) writeGpioNode(this.mGpioExport, Integer.toString(port)); String path_direction = path + "/direction"; String path_value = path + "/value"; this.mGpioPort = new File(path); if (this.mGpioPort.exists() == false) { if (gpio_name != null) { Log.e(TAG, "系统没有导出" + gpio_name + " 请看文档或查询定昌技术支持"); } lastError = "系统没有导出这个io口。请看文档或查询定昌技术支持" + mPort; return false; } this.mGpioPortDirection = new File(path_direction); this.mGpioPortValue = new File(path_value); return (this.mGpioPort.exists()) && (this.mGpioPortDirection.exists()) && (this.mGpioPortValue.exists()); } public String getLastError() { String ls = lastError; lastError = ""; return ls; } private boolean gpio_request() { return this.isGpioPortPrepared; } void gpio_free() { if (isGpioPortPrepared == false) return; writeGpioNode(this.mGpioUnExport, Integer.toString(this.mPort)); } private String readGpioNode(File file) { BufferedReader reader = null; String string = null; try { reader = new BufferedReader(new FileReader(file)); string = reader.readLine(); reader.close(); } catch (IOException e) { e.printStackTrace(); } return string; } }
Ztldc/ZtlApi
app/src/main/java/ZtlApi/Gpio.java
2,712
//20201102 修改GPIO口不存在时崩溃的问题
line_comment
zh-cn
package ZtlApi; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import ZtlApi.ZtlManager; //20210730 修改重复申请权限问题,申请两次没通过就不申请了,防止log刷屏 //20201105 修改getValue(String dir) 接口的返回值,当前GPIO的dir值不相等时,设置它的dir然后再返回value //20 <SUF> //20200916 去掉了数字openPort。新的app必须使用字符类型的gpio 实现51 71兼容 public class Gpio { private static final String TAG = "GPIO"; private int mPort; private boolean isGpioPortPrepared = false; private File mGpioExport = null; private File mGpioUnExport = null; private File mGpioPort = null; private File mGpioPortDirection = null; private File mGpioPortValue = null; private String gpio_export = "/sys/class/gpio/export"; private String gpio_unexport = "/sys/class/gpio/unexport"; private String gpio_port = "/sys/class/gpio/gpio"; String gpio_name; public static final String rk3288[] = {"", "GPIO0_C2", "GPIO7_B5", "GPIO8_B0", "GPIO7_B4", "GPIO7_C5", "GPIO7_B3", "GPIO8_A2", "GPIO7_A6", "GPIO8_A1", "GPIO7_A5"}; public static final String rk3126c[] = {"", "GPIO1_C7", "GPIO2_A2", "GPIO1_A7", "GPIO2_A0", "GPIO2_A1", "GPIO0_C7", "GPIO2_A6", "GPIO2_A3", "GPIO1_A3", "GPIO3_C5"}; public static final String CQA64[] = {"", "PE7", "PE4", "PE3", "PE2", "PE1"}; //public static final String rk3328[] = {"GPIO3_A0"}; public static final String rk3368[] = {"", "GPIO1_A2", "GPIO1_B6", "GPIO1_A3", "GPIO1_B7", "GPIO1_A4", "GPIO1_C0", "GPIO1_A5", "GPIO1_C1", "GPIO1_A6", "GPIO1_A7"}; public static final String rk3399[] = {"", "GPIO2_B2", "GPIO2_A5", "GPIO2_A3", "GPIO2_A1", "GPIO2_A6", "GPIO2_B0", "GPIO2_A4", "GPIO2_B1", "GPIO2_B4", "GPIO2_A0", "GPIO2_A7", "GPIO2_A2"}; // public static final String rk3399[] = {"GPIO1_D0", "GPIO1_A0", "GPIO1_A2", "GPIO1_C6", "GPIO2_A5", "GPIO2_A3", "GPIO2_A6", "GPIO2_A4", "GPIO2_A2"}; public static final HashMap<String, String[]> GpioNameMap = new HashMap<String, String[]>() {{ put("rk3288", rk3288); put("rk3126", rk3126c); put("A64", CQA64); //put("rk3328",rk3328); put("rk3368", rk3368); put("rk3399", rk3399); }}; public Gpio() { } //直接输入GPIO7_A5 之类 省得每次都按计算器 public boolean open(String strPort) { if (strPort == null || strPort.isEmpty()) return false; gpio_name = strPort; //71 51兼容 int nValue = ZtlManager.GetInstance().gpioStringToInt(strPort); if (nValue == -1) { return false; } this.mPort = nValue; this.mGpioExport = new File(this.gpio_export); this.mGpioUnExport = new File(this.gpio_unexport); this.isGpioPortPrepared = prepare_gpio_port(this.mPort); return isGpioPortPrepared; } //直接输入GPIO7_A5 之类 省得每次都按计算器 public boolean open(int strPort) { gpio_name = strPort+""; //71 51兼容 int nValue = strPort; if (nValue == -1) { return false; } this.mPort = nValue; this.mGpioExport = new File(this.gpio_export); this.mGpioUnExport = new File(this.gpio_unexport); this.isGpioPortPrepared = prepare_gpio_port(this.mPort); return isGpioPortPrepared; } //获取当前GPIO的Direction public String getDirection() { if (isGpioPortPrepared == false) { return "unknown"; } String strDir = null; if (this.mGpioPortDirection == null) { return "unknown"; } if (this.mGpioPortDirection.exists()) { strDir = readGpioNode(this.mGpioPortDirection); } else { return "unknown"; } return strDir; } String lastError = ""; //设置GPIO的Direction public void setDirection(String dir) { if (isGpioPortPrepared == false) { return; } //如果系统占用该IO口,不执行setDirection if (this.mGpioPortDirection == null) return; if (getDirection().equals(dir) == false) { writeGpioNode(this.mGpioPortDirection, dir); } } //获取当前direction的value public int getValue() { if (isGpioPortPrepared == false) { return -1; } int value = -1; if (this.mGpioPortDirection != null) { String string = readGpioNode(this.mGpioPortValue); if (string == null) { return -1; } if (string.equals("0")) value = 0; else if (string.equals("1")) { value = 1; } else { try { value = Integer.valueOf(string); } catch (NumberFormatException m) { return -1; } } } return value; } //获取指定direction的value public int getValue(String direction)//in out { if (isGpioPortPrepared == false) { return -1; } String strCurDirection = null; //该IO口不存在(被系统占用)返回-1 if (this.mGpioPort.exists() == false) { return -1; } //当前direction目录不存在 if (this.mGpioPortDirection.exists() == false) { return -1; } //获取到当前direction是in 还是out strCurDirection = readGpioNode(this.mGpioPortDirection); if (strCurDirection.equals(direction)) { return getValue(); } else { setDirection(direction); return getValue(); } } //设置当前direction的value public void setValue(int value) { if (isGpioPortPrepared == false) { return; } if (getValue() != value) { writeGpioNode(this.mGpioPortValue, Integer.toString(value)); } } //设置指定direction的value //direction = "in" or "out" public void setValue(String direction, int value) { if (isGpioPortPrepared == false) { return; } if (getDirection().equals(direction) == false) { writeGpioNode(this.mGpioPortDirection, direction); } writeGpioNode(this.mGpioPortValue, Integer.toString(value)); } int trynCount = 0;//表示获取权限的次数 private void writeGpioNode(File file, String value) { if (file.exists() == false) return; if (file.exists()) { // System.out.println("write " + flag + " to " + file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(value.getBytes(), 0, value.getBytes().length); fos.flush(); fos.close(); trynCount = 0; } catch (IOException e) { String error = e.toString(); if (error.contains("Permission denied")) { trynCount++; ZtlManager.GetInstance().execRootCmdSilent("chmod 777 " + file.getAbsolutePath()); Log.e(TAG, "正在申请权限"); //判断节点是否有权限,没有权限的话退出 if (trynCount > 2) { Log.e(TAG, "权限申请不通过"); return; } writeGpioNode(file, value); } else { trynCount++; Log.e(TAG, "writeGpioNode " + gpio_name + " 错误"); e.printStackTrace(); if (trynCount > 2) { Log.e(TAG, "权限申请不通过"); return; } } } } } private boolean prepare_gpio_port(int port) { if (this.mGpioExport == null || this.mGpioExport.exists() == false) { return false; } String path = this.gpio_port + port; boolean bbb = ZtlManager.GetInstance().isExist(path); if (bbb == false) writeGpioNode(this.mGpioExport, Integer.toString(port)); String path_direction = path + "/direction"; String path_value = path + "/value"; this.mGpioPort = new File(path); if (this.mGpioPort.exists() == false) { if (gpio_name != null) { Log.e(TAG, "系统没有导出" + gpio_name + " 请看文档或查询定昌技术支持"); } lastError = "系统没有导出这个io口。请看文档或查询定昌技术支持" + mPort; return false; } this.mGpioPortDirection = new File(path_direction); this.mGpioPortValue = new File(path_value); return (this.mGpioPort.exists()) && (this.mGpioPortDirection.exists()) && (this.mGpioPortValue.exists()); } public String getLastError() { String ls = lastError; lastError = ""; return ls; } private boolean gpio_request() { return this.isGpioPortPrepared; } void gpio_free() { if (isGpioPortPrepared == false) return; writeGpioNode(this.mGpioUnExport, Integer.toString(this.mPort)); } private String readGpioNode(File file) { BufferedReader reader = null; String string = null; try { reader = new BufferedReader(new FileReader(file)); string = reader.readLine(); reader.close(); } catch (IOException e) { e.printStackTrace(); } return string; } }
false
2,519
16
2,712
19
2,900
16
2,712
19
3,445
29
false
false
false
false
false
true
15522_23
import java.io.*; import java.text.SimpleDateFormat; import java.util.*; public class C9 { static String curProjectPath = System.getProperty("user.dir"); // 把 Settings下的java文件都打包成一个文件 输出 html 页面 以及 md文件 // 文件名称为 packages-apps-Settings_java_Analysis.html // 文件名称为 packages-apps-Settings_java_Analysis.md // 把 /packages/apps 和 frameworks/base 下的包含 values-zh-rCN/string.xml 的文件打包成一个文件 // 文件名称为 packages-apps-frameworks-base-values-zh-rCN-_Analysis.txt static File current_juwuba_template_file = new File(System.getProperty("user.dir") + File.separator + "C9_juwuba_template.html"); static String current_juwuba_html_template_content = ""; static String markdownName = "C9_default.html"; static String curDirPath = ""; public static void main(String[] args) { String mFilePath = null; if (args.length >= 1) { mFilePath = args[0]; } else { System.out.println("input argument is empty ! retry input again!"); return; } File curFile; if (mFilePath != null && !mFilePath.isEmpty() && (curFile = new File(mFilePath)).exists()) { System.out.println("input argument success ! "); } else { System.out.println("input argument is invalid ! retry input again!"); return; } markdownName = curFile.getName().substring(0,curFile.getName().lastIndexOf(".")); curDirPath = curFile.getAbsolutePath(); curDirPath = curDirPath.substring(0,curDirPath.lastIndexOf(File.separator)); if (current_juwuba_template_file != null && current_juwuba_template_file.exists()) { current_juwuba_html_template_content = readTemplateStringFromFile(current_juwuba_template_file).toString(); System.out.println("================================ current_juwuba_template_content begin ================================="); // System.out.println(" current_juwuba_template_content = " + current_juwuba_html_template_content); System.out.println("================================ current_juwuba_template_content end ================================="); } else { System.out.println(" current_juwuba_template_content = null "); } String markDownContent = readTemplateStringFromFile(curFile).toString(); String markdownHtml = translateFromMarkdownToHtml(markDownContent); String html_template_str = new String(current_juwuba_html_template_content); // 生成 html 文件的 StringBuilder 先放入 html模板 String outfile_html_name = getOutFileHTMLName(); String htmlTitle = outfile_html_name.replace(".html", ""); // tag 标题 html_template_str = html_template_str.replace("ZukgitHeadTitleHoldPlace_1", outfile_html_name); html_template_str = html_template_str.replace("ZukgitContentTitleHoldPlace_2", htmlTitle + "文件集合"); Date day = new Date(); SimpleDateFormat simpleDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); html_template_str = html_template_str.replace("ZukgitTimeStampHoldPlace_3", simpleDf.format(day)); html_template_str = html_template_str.replace("ZukgitMDContentHoldPlace_4", markdownHtml); writeContentToFile(new File(curDirPath+File.separator+outfile_html_name), html_template_str.toString()); } static String getOutFileHTMLName() { // 输出文件的名称 依据MarkDown文件的名称命名 return markdownName+".html"; } static void writeContentToFile(File file, String strParam) { try { if (file != null && !file.exists()) { file.createNewFile(); } if (file != null && file.exists()) { BufferedWriter curBW = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); curBW.write(strParam); curBW.flush(); curBW.close(); System.out.println("write out File OK ! File = " + file.getAbsolutePath()); } else { System.out.println("write out File Failed ! File = " + file.getAbsolutePath()); } } catch (IOException e) { e.printStackTrace(); } } // 把 MD 格式的 翻译成 html 格式 static StringBuilder readTemplateStringFromFile(File fileItem) { StringBuilder sb = new StringBuilder(); try { BufferedReader curBR = new BufferedReader(new InputStreamReader(new FileInputStream(fileItem), "utf-8")); String lineContent = ""; while (lineContent != null) { lineContent = curBR.readLine(); if (lineContent == null || lineContent.trim().isEmpty()) { continue; } sb.append(lineContent + "\n"); } curBR.close(); } catch (Exception e) { } return sb; } static String translateFromMarkdownToHtml(String markdownCode) { //如果当前的 内容并不在 ``` precode里面的情况 // #空格 <h1> </h1> //##空格 <h2> </h2> // ###空格 <h3> </h3> // ####空格 <h4> </h4> // #####空格 <h5> </h5> // ######空格 <h6> </h6> // #######空格 <h7> </h7> // ########空格 <h8> </h8> // #########空格 <h9> </h9> // 每次遇到 ``` 就把 标志位索引 0 + 1 , 奇数 i%2 ==1 那么就在precode 外面 , 偶数i%2 == 0 就在precode 里面 // 当在 precode 以内 把数据的格式 整理下 //1. pre ``` = "\n<pre><code class=\"\">\n" end``` =</code></pre> // 2. 左右 括号的 切换 // inprecodeStr = inprecodeStr.replace("<", "&lt;"); // inprecodeStr = inprecodeStr.replace(">", "&gt;"); StringBuilder sb = new StringBuilder(); String htmlCode = ""; htmlCode = markdownCode.replace("\n\n\n\n", "\n"); htmlCode = htmlCode.replace("\n\n\n", "\n"); htmlCode = htmlCode.replace("\n\n", "\n"); htmlCode = htmlCode.replace("\n\n", "\n"); String[] mdArr = htmlCode.split("\n"); int codeIndex = 1; for (int i = 0; i < mdArr.length; i++) { String codeHtmlLine = new String(mdArr[i]); if (codeIndex % 2 == 0) { // 偶数 在 preCode 里面 if (mdArr[i].trim().equals("```")) { // 遇到 end``` codeIndex++; codeHtmlLine = "\n</code></pre>\n"; } else { codeHtmlLine = mdArr[i].replace("<", "&lt;"); codeHtmlLine = codeHtmlLine.replace(">", "&gt;"); } } else { // 奇数 在 preCode外面 if (mdArr[i].trim().equals("```")) { // 首次遇到 pre``` codeIndex++; codeHtmlLine = "\n<pre><code class=\"\">\n"; } else { if (mdArr[i].trim().startsWith("######### ")) { // h9 codeHtmlLine = mdArr[i].trim().replace("######### ", "<h9>"); codeHtmlLine = codeHtmlLine + "</h9>"; } else if (mdArr[i].trim().startsWith("######## ")) { // h8 codeHtmlLine = mdArr[i].trim().replace("######## ", "<h8>"); codeHtmlLine = codeHtmlLine + "</h8>"; } else if (mdArr[i].trim().startsWith("####### ")) { // h7 codeHtmlLine = mdArr[i].trim().replace("####### ", "<h7>"); codeHtmlLine = codeHtmlLine + "</h7>"; } else if (mdArr[i].trim().startsWith("###### ")) { // h6 codeHtmlLine = mdArr[i].trim().replace("###### ", "<h6>"); codeHtmlLine = codeHtmlLine + "</h6>"; } else if (mdArr[i].trim().startsWith("##### ")) { // h5 codeHtmlLine = mdArr[i].trim().replace("##### ", "<h5>"); codeHtmlLine = codeHtmlLine + "</h5>"; } else if (mdArr[i].trim().startsWith("#### ")) { // h4 codeHtmlLine = mdArr[i].trim().replace("#### ", "<h4>"); codeHtmlLine = codeHtmlLine + "</h4>"; } else if (mdArr[i].trim().startsWith("### ")) { // h3 codeHtmlLine = mdArr[i].trim().replace("### ", "<h3>"); codeHtmlLine = codeHtmlLine + "</h3>"; } else if (mdArr[i].trim().startsWith("## ")) { // h2 codeHtmlLine = mdArr[i].trim().replace("## ", "<h2>"); codeHtmlLine = codeHtmlLine + "</h2>"; } else if (mdArr[i].trim().startsWith("# ")) { // h1 codeHtmlLine = mdArr[i].trim().replace("# ", "<h1>"); codeHtmlLine = codeHtmlLine + "</h1>"; } } } sb.append(codeHtmlLine + "\n"); System.out.println("第" + i + "行: " + mdArr[i]); } return sb.toString(); } }
ZukGit/WordPress_MD_Git
tool/notepad_zbinfile/zbin/C9.java
2,363
// 2. 左右 括号的 切换
line_comment
zh-cn
import java.io.*; import java.text.SimpleDateFormat; import java.util.*; public class C9 { static String curProjectPath = System.getProperty("user.dir"); // 把 Settings下的java文件都打包成一个文件 输出 html 页面 以及 md文件 // 文件名称为 packages-apps-Settings_java_Analysis.html // 文件名称为 packages-apps-Settings_java_Analysis.md // 把 /packages/apps 和 frameworks/base 下的包含 values-zh-rCN/string.xml 的文件打包成一个文件 // 文件名称为 packages-apps-frameworks-base-values-zh-rCN-_Analysis.txt static File current_juwuba_template_file = new File(System.getProperty("user.dir") + File.separator + "C9_juwuba_template.html"); static String current_juwuba_html_template_content = ""; static String markdownName = "C9_default.html"; static String curDirPath = ""; public static void main(String[] args) { String mFilePath = null; if (args.length >= 1) { mFilePath = args[0]; } else { System.out.println("input argument is empty ! retry input again!"); return; } File curFile; if (mFilePath != null && !mFilePath.isEmpty() && (curFile = new File(mFilePath)).exists()) { System.out.println("input argument success ! "); } else { System.out.println("input argument is invalid ! retry input again!"); return; } markdownName = curFile.getName().substring(0,curFile.getName().lastIndexOf(".")); curDirPath = curFile.getAbsolutePath(); curDirPath = curDirPath.substring(0,curDirPath.lastIndexOf(File.separator)); if (current_juwuba_template_file != null && current_juwuba_template_file.exists()) { current_juwuba_html_template_content = readTemplateStringFromFile(current_juwuba_template_file).toString(); System.out.println("================================ current_juwuba_template_content begin ================================="); // System.out.println(" current_juwuba_template_content = " + current_juwuba_html_template_content); System.out.println("================================ current_juwuba_template_content end ================================="); } else { System.out.println(" current_juwuba_template_content = null "); } String markDownContent = readTemplateStringFromFile(curFile).toString(); String markdownHtml = translateFromMarkdownToHtml(markDownContent); String html_template_str = new String(current_juwuba_html_template_content); // 生成 html 文件的 StringBuilder 先放入 html模板 String outfile_html_name = getOutFileHTMLName(); String htmlTitle = outfile_html_name.replace(".html", ""); // tag 标题 html_template_str = html_template_str.replace("ZukgitHeadTitleHoldPlace_1", outfile_html_name); html_template_str = html_template_str.replace("ZukgitContentTitleHoldPlace_2", htmlTitle + "文件集合"); Date day = new Date(); SimpleDateFormat simpleDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); html_template_str = html_template_str.replace("ZukgitTimeStampHoldPlace_3", simpleDf.format(day)); html_template_str = html_template_str.replace("ZukgitMDContentHoldPlace_4", markdownHtml); writeContentToFile(new File(curDirPath+File.separator+outfile_html_name), html_template_str.toString()); } static String getOutFileHTMLName() { // 输出文件的名称 依据MarkDown文件的名称命名 return markdownName+".html"; } static void writeContentToFile(File file, String strParam) { try { if (file != null && !file.exists()) { file.createNewFile(); } if (file != null && file.exists()) { BufferedWriter curBW = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); curBW.write(strParam); curBW.flush(); curBW.close(); System.out.println("write out File OK ! File = " + file.getAbsolutePath()); } else { System.out.println("write out File Failed ! File = " + file.getAbsolutePath()); } } catch (IOException e) { e.printStackTrace(); } } // 把 MD 格式的 翻译成 html 格式 static StringBuilder readTemplateStringFromFile(File fileItem) { StringBuilder sb = new StringBuilder(); try { BufferedReader curBR = new BufferedReader(new InputStreamReader(new FileInputStream(fileItem), "utf-8")); String lineContent = ""; while (lineContent != null) { lineContent = curBR.readLine(); if (lineContent == null || lineContent.trim().isEmpty()) { continue; } sb.append(lineContent + "\n"); } curBR.close(); } catch (Exception e) { } return sb; } static String translateFromMarkdownToHtml(String markdownCode) { //如果当前的 内容并不在 ``` precode里面的情况 // #空格 <h1> </h1> //##空格 <h2> </h2> // ###空格 <h3> </h3> // ####空格 <h4> </h4> // #####空格 <h5> </h5> // ######空格 <h6> </h6> // #######空格 <h7> </h7> // ########空格 <h8> </h8> // #########空格 <h9> </h9> // 每次遇到 ``` 就把 标志位索引 0 + 1 , 奇数 i%2 ==1 那么就在precode 外面 , 偶数i%2 == 0 就在precode 里面 // 当在 precode 以内 把数据的格式 整理下 //1. pre ``` = "\n<pre><code class=\"\">\n" end``` =</code></pre> // 2. <SUF> // inprecodeStr = inprecodeStr.replace("<", "&lt;"); // inprecodeStr = inprecodeStr.replace(">", "&gt;"); StringBuilder sb = new StringBuilder(); String htmlCode = ""; htmlCode = markdownCode.replace("\n\n\n\n", "\n"); htmlCode = htmlCode.replace("\n\n\n", "\n"); htmlCode = htmlCode.replace("\n\n", "\n"); htmlCode = htmlCode.replace("\n\n", "\n"); String[] mdArr = htmlCode.split("\n"); int codeIndex = 1; for (int i = 0; i < mdArr.length; i++) { String codeHtmlLine = new String(mdArr[i]); if (codeIndex % 2 == 0) { // 偶数 在 preCode 里面 if (mdArr[i].trim().equals("```")) { // 遇到 end``` codeIndex++; codeHtmlLine = "\n</code></pre>\n"; } else { codeHtmlLine = mdArr[i].replace("<", "&lt;"); codeHtmlLine = codeHtmlLine.replace(">", "&gt;"); } } else { // 奇数 在 preCode外面 if (mdArr[i].trim().equals("```")) { // 首次遇到 pre``` codeIndex++; codeHtmlLine = "\n<pre><code class=\"\">\n"; } else { if (mdArr[i].trim().startsWith("######### ")) { // h9 codeHtmlLine = mdArr[i].trim().replace("######### ", "<h9>"); codeHtmlLine = codeHtmlLine + "</h9>"; } else if (mdArr[i].trim().startsWith("######## ")) { // h8 codeHtmlLine = mdArr[i].trim().replace("######## ", "<h8>"); codeHtmlLine = codeHtmlLine + "</h8>"; } else if (mdArr[i].trim().startsWith("####### ")) { // h7 codeHtmlLine = mdArr[i].trim().replace("####### ", "<h7>"); codeHtmlLine = codeHtmlLine + "</h7>"; } else if (mdArr[i].trim().startsWith("###### ")) { // h6 codeHtmlLine = mdArr[i].trim().replace("###### ", "<h6>"); codeHtmlLine = codeHtmlLine + "</h6>"; } else if (mdArr[i].trim().startsWith("##### ")) { // h5 codeHtmlLine = mdArr[i].trim().replace("##### ", "<h5>"); codeHtmlLine = codeHtmlLine + "</h5>"; } else if (mdArr[i].trim().startsWith("#### ")) { // h4 codeHtmlLine = mdArr[i].trim().replace("#### ", "<h4>"); codeHtmlLine = codeHtmlLine + "</h4>"; } else if (mdArr[i].trim().startsWith("### ")) { // h3 codeHtmlLine = mdArr[i].trim().replace("### ", "<h3>"); codeHtmlLine = codeHtmlLine + "</h3>"; } else if (mdArr[i].trim().startsWith("## ")) { // h2 codeHtmlLine = mdArr[i].trim().replace("## ", "<h2>"); codeHtmlLine = codeHtmlLine + "</h2>"; } else if (mdArr[i].trim().startsWith("# ")) { // h1 codeHtmlLine = mdArr[i].trim().replace("# ", "<h1>"); codeHtmlLine = codeHtmlLine + "</h1>"; } } } sb.append(codeHtmlLine + "\n"); System.out.println("第" + i + "行: " + mdArr[i]); } return sb.toString(); } }
false
2,173
15
2,363
13
2,423
12
2,363
13
2,812
16
false
false
false
false
false
true
19868_2
import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class MailTest { public static void main(String[] args) throws MessagingException { Properties prop=new Properties(); prop.put("mail.host","smtp.163.com" ); prop.put("mail.transport.protocol", "smtp"); prop.put("mail.smtp.auth", true); //使用java发送邮件5步骤 //1.创建sesssion Session session=Session.getInstance(prop); //开启session的调试模式,可以查看当前邮件发送状态 session.setDebug(true); //2.通过session获取Transport对象(发送邮件的核心API) Transport ts=session.getTransport(); //3.通过邮件用户名密码链接 ts.connect("[email protected]", "wyzuo19941204"); //4.创建邮件 Message msg=createSimpleMail(session); //5.发送电子邮件 ts.sendMessage(msg, msg.getAllRecipients()); } public static MimeMessage createSimpleMail(Session session) throws AddressException,MessagingException{ //创建邮件对象 MimeMessage mm=new MimeMessage(session); //设置发件人 mm.setFrom(new InternetAddress("[email protected]")); //设置收件人 mm.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); //设置抄送人 // mm.setRecipient(Message.RecipientType.CC, new InternetAddress("用户名@163.com")); mm.setSubject("第一封JAVA邮件!"); mm.setContent("咱们开会把", "text/html;charset=gbk"); return mm; } }
ZuoVJ/ScalaLearning
src/main/java/MailTest.java
486
//开启session的调试模式,可以查看当前邮件发送状态
line_comment
zh-cn
import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class MailTest { public static void main(String[] args) throws MessagingException { Properties prop=new Properties(); prop.put("mail.host","smtp.163.com" ); prop.put("mail.transport.protocol", "smtp"); prop.put("mail.smtp.auth", true); //使用java发送邮件5步骤 //1.创建sesssion Session session=Session.getInstance(prop); //开启 <SUF> session.setDebug(true); //2.通过session获取Transport对象(发送邮件的核心API) Transport ts=session.getTransport(); //3.通过邮件用户名密码链接 ts.connect("[email protected]", "wyzuo19941204"); //4.创建邮件 Message msg=createSimpleMail(session); //5.发送电子邮件 ts.sendMessage(msg, msg.getAllRecipients()); } public static MimeMessage createSimpleMail(Session session) throws AddressException,MessagingException{ //创建邮件对象 MimeMessage mm=new MimeMessage(session); //设置发件人 mm.setFrom(new InternetAddress("[email protected]")); //设置收件人 mm.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); //设置抄送人 // mm.setRecipient(Message.RecipientType.CC, new InternetAddress("用户名@163.com")); mm.setSubject("第一封JAVA邮件!"); mm.setContent("咱们开会把", "text/html;charset=gbk"); return mm; } }
false
418
13
486
13
506
13
486
13
625
26
false
false
false
false
false
true
57908_11
package com.hotent.platform.model.bpm; import com.hotent.core.model.BaseModel; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.EqualsBuilder; /** * 对象功能:流程运行日志 Model对象 * 开发公司:广州宏天软件有限公司 * 开发人员:heyifan * 创建时间:2012-08-06 13:56:42 */ public class BpmRunLog extends BaseModel { /** * 操作类型:启动流程 */ public static final Integer OPERATOR_TYPE_START=0; /** * 操作类型:交办 */ public static final Integer OPERATOR_TYPE_DELEGATE=1; /** * 操作类型:撤销 */ public static final Integer OPERATOR_TYPE_RETRIEVE=2; /** * 操作类型:删除流程实例 */ public static final Integer OPERATOR_TYPE_DELETEINSTANCE=3; /** * 操作类型:删除流程草稿 */ public static final Integer OPERATOR_TYPE_DELETEFORM=23; /** * 操作类型:投票——同意 */ public static final Integer OPERATOR_TYPE_AGREE=4; /** * 操作类型:投票——反对 */ public static final Integer OPERATOR_TYPE_OBJECTION=5; /** * 操作类型:投票——弃权 */ public static final Integer OPERATOR_TYPE_ABSTENTION=6; /** * 操作类型:补签 */ public static final Integer OPERATOR_TYPE_SIGN=7; /** * 操作类型:驳回 */ public static final Integer OPERATOR_TYPE_REJECT=8; /** * 操作类型:驳回到发起人 */ public static final Integer OPERATOR_TYPE_REJECT2SPONSOR=9; /** * 操作类型:删除任务 */ public static final Integer OPERATOR_TYPE_DELETETASK=10; /** * 执行代理任务 */ public static final Integer OPERATOR_TYPE_AGENT=11; /** * 锁定任务 */ public static final Integer OPERATOR_TYPE_LOCK=13; /** * 任务解锁 */ public static final Integer OPERATOR_TYPE_UNLOCK=14; /** * 添加意见。 */ public static final Integer OPERATOR_TYPE_ADDOPINION=15; /** * 任务指派。 */ public static final Integer OPERATOR_TYPE_ASSIGN=16; /** * 修改任务所有人。 */ public static final Integer OPERATOR_TYPE_SETOWNER=17; /** * 操作类型:结束任务 */ public static final Integer OPERATOR_TYPE_ENDTASK=18; /** * 更改执行路径 */ public static final Integer OPERATOR_TYPE_CHANGEPATH=19; /** * 收回任务 */ public static final Integer OPERATOR_TYPE_BACK=20; /** * 操作类型:结束流程实例 */ public static final Integer OPERATOR_TYPE_ENDINSTANCE=21; /** * 保存草稿 */ public static final Integer OPERATOR_TYPE_SAVEFORM=22; /** * 办结转发 */ public static final Integer OPERATOR_TYPE_FINISHDIVERT=23; // 主键 protected Long id; // 用户ID protected Long userid; // 用户名称 protected String username; // 操作时间 protected java.util.Date createtime; // 操作类型 protected Integer operatortype; // 备注 protected String memo; //流程运行ID protected Long runid; //流程标题 protected String processSubject; public void setId(Long id) { this.id = id; } /** * 返回 主键 * @return */ public Long getId() { return this.id; } public void setUserid(Long userid) { this.userid = userid; } /** * 返回 用户ID * @return */ public Long getUserid() { return this.userid; } public void setUsername(String username) { this.username = username; } /** * 返回 用户名称 * @return */ public String getUsername() { return this.username; } public void setCreatetime(java.util.Date createtime) { this.createtime = createtime; } /** * 返回 操作时间 * @return */ public java.util.Date getCreatetime() { return this.createtime; } public void setOperatortype(Integer operatortype) { this.operatortype = operatortype; } /** * 返回 操作类型 * @return */ public Integer getOperatortype() { return this.operatortype; } public void setMemo(String memo) { this.memo = memo; } /** * 返回 备注 * @return */ public String getMemo() { return this.memo; } public Long getRunid() { return runid; } public void setRunid(Long runid) { this.runid = runid; } /** * @see java.lang.Object#equals(Object) */ public boolean equals(Object object) { if (!(object instanceof BpmRunLog)) { return false; } BpmRunLog rhs = (BpmRunLog) object; return new EqualsBuilder() .append(this.id, rhs.id) .append(this.userid, rhs.userid) .append(this.username, rhs.username) .append(this.createtime, rhs.createtime) .append(this.operatortype, rhs.operatortype) .append(this.memo, rhs.memo) .append(this.processSubject, rhs.processSubject) .isEquals(); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return new HashCodeBuilder(-82280557, -700257973) .append(this.id) .append(this.userid) .append(this.username) .append(this.createtime) .append(this.operatortype) .append(this.memo) .append(this.processSubject) .toHashCode(); } /** * @see java.lang.Object#toString() */ public String toString() { return new ToStringBuilder(this) .append("id", this.id) .append("userid", this.userid) .append("username", this.username) .append("createtime", this.createtime) .append("operatortype", this.operatortype) .append("memo", this.memo) .append("processSubject", this.processSubject) .toString(); } public String getProcessSubject() { return processSubject; } public void setProcessSubject(String processSubject) { this.processSubject = processSubject; } }
Zurich1994/Bpmx3_dev
src/com/hotent/platform/model/bpm/BpmRunLog.java
1,914
/** * 操作类型:驳回到发起人 */
block_comment
zh-cn
package com.hotent.platform.model.bpm; import com.hotent.core.model.BaseModel; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.EqualsBuilder; /** * 对象功能:流程运行日志 Model对象 * 开发公司:广州宏天软件有限公司 * 开发人员:heyifan * 创建时间:2012-08-06 13:56:42 */ public class BpmRunLog extends BaseModel { /** * 操作类型:启动流程 */ public static final Integer OPERATOR_TYPE_START=0; /** * 操作类型:交办 */ public static final Integer OPERATOR_TYPE_DELEGATE=1; /** * 操作类型:撤销 */ public static final Integer OPERATOR_TYPE_RETRIEVE=2; /** * 操作类型:删除流程实例 */ public static final Integer OPERATOR_TYPE_DELETEINSTANCE=3; /** * 操作类型:删除流程草稿 */ public static final Integer OPERATOR_TYPE_DELETEFORM=23; /** * 操作类型:投票——同意 */ public static final Integer OPERATOR_TYPE_AGREE=4; /** * 操作类型:投票——反对 */ public static final Integer OPERATOR_TYPE_OBJECTION=5; /** * 操作类型:投票——弃权 */ public static final Integer OPERATOR_TYPE_ABSTENTION=6; /** * 操作类型:补签 */ public static final Integer OPERATOR_TYPE_SIGN=7; /** * 操作类型:驳回 */ public static final Integer OPERATOR_TYPE_REJECT=8; /** * 操作类 <SUF>*/ public static final Integer OPERATOR_TYPE_REJECT2SPONSOR=9; /** * 操作类型:删除任务 */ public static final Integer OPERATOR_TYPE_DELETETASK=10; /** * 执行代理任务 */ public static final Integer OPERATOR_TYPE_AGENT=11; /** * 锁定任务 */ public static final Integer OPERATOR_TYPE_LOCK=13; /** * 任务解锁 */ public static final Integer OPERATOR_TYPE_UNLOCK=14; /** * 添加意见。 */ public static final Integer OPERATOR_TYPE_ADDOPINION=15; /** * 任务指派。 */ public static final Integer OPERATOR_TYPE_ASSIGN=16; /** * 修改任务所有人。 */ public static final Integer OPERATOR_TYPE_SETOWNER=17; /** * 操作类型:结束任务 */ public static final Integer OPERATOR_TYPE_ENDTASK=18; /** * 更改执行路径 */ public static final Integer OPERATOR_TYPE_CHANGEPATH=19; /** * 收回任务 */ public static final Integer OPERATOR_TYPE_BACK=20; /** * 操作类型:结束流程实例 */ public static final Integer OPERATOR_TYPE_ENDINSTANCE=21; /** * 保存草稿 */ public static final Integer OPERATOR_TYPE_SAVEFORM=22; /** * 办结转发 */ public static final Integer OPERATOR_TYPE_FINISHDIVERT=23; // 主键 protected Long id; // 用户ID protected Long userid; // 用户名称 protected String username; // 操作时间 protected java.util.Date createtime; // 操作类型 protected Integer operatortype; // 备注 protected String memo; //流程运行ID protected Long runid; //流程标题 protected String processSubject; public void setId(Long id) { this.id = id; } /** * 返回 主键 * @return */ public Long getId() { return this.id; } public void setUserid(Long userid) { this.userid = userid; } /** * 返回 用户ID * @return */ public Long getUserid() { return this.userid; } public void setUsername(String username) { this.username = username; } /** * 返回 用户名称 * @return */ public String getUsername() { return this.username; } public void setCreatetime(java.util.Date createtime) { this.createtime = createtime; } /** * 返回 操作时间 * @return */ public java.util.Date getCreatetime() { return this.createtime; } public void setOperatortype(Integer operatortype) { this.operatortype = operatortype; } /** * 返回 操作类型 * @return */ public Integer getOperatortype() { return this.operatortype; } public void setMemo(String memo) { this.memo = memo; } /** * 返回 备注 * @return */ public String getMemo() { return this.memo; } public Long getRunid() { return runid; } public void setRunid(Long runid) { this.runid = runid; } /** * @see java.lang.Object#equals(Object) */ public boolean equals(Object object) { if (!(object instanceof BpmRunLog)) { return false; } BpmRunLog rhs = (BpmRunLog) object; return new EqualsBuilder() .append(this.id, rhs.id) .append(this.userid, rhs.userid) .append(this.username, rhs.username) .append(this.createtime, rhs.createtime) .append(this.operatortype, rhs.operatortype) .append(this.memo, rhs.memo) .append(this.processSubject, rhs.processSubject) .isEquals(); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return new HashCodeBuilder(-82280557, -700257973) .append(this.id) .append(this.userid) .append(this.username) .append(this.createtime) .append(this.operatortype) .append(this.memo) .append(this.processSubject) .toHashCode(); } /** * @see java.lang.Object#toString() */ public String toString() { return new ToStringBuilder(this) .append("id", this.id) .append("userid", this.userid) .append("username", this.username) .append("createtime", this.createtime) .append("operatortype", this.operatortype) .append("memo", this.memo) .append("processSubject", this.processSubject) .toString(); } public String getProcessSubject() { return processSubject; } public void setProcessSubject(String processSubject) { this.processSubject = processSubject; } }
false
1,609
14
1,913
16
1,973
14
1,914
16
2,415
21
false
false
false
false
false
true
64506_4
package com.zyfgoup.entity; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author zyfgoup * @since 2020-06-18 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class Department implements Serializable { private static final long serialVersionUID = 1L; /** * 主键uuid */ @TableId(value = "dep_id",type=IdType.ID_WORKER_STR) private String depId; /** * 部门账号作为登录账号 */ private String depNo; /** * 部门名称 */ private String depName; /** * 部门密码 */ private String depPassword; /** * 部门人数 */ private Integer depPersonCount; /** * 部门邮箱 一般账号掌控在一个人手里 通过提醒通知要开会 */ private String depEmail; /** * 角色是用户 */ private String role; }
Zyfgoup/conferenceroom-backend
src/main/java/com/zyfgoup/entity/Department.java
305
/** * 部门密码 */
block_comment
zh-cn
package com.zyfgoup.entity; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author zyfgoup * @since 2020-06-18 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class Department implements Serializable { private static final long serialVersionUID = 1L; /** * 主键uuid */ @TableId(value = "dep_id",type=IdType.ID_WORKER_STR) private String depId; /** * 部门账号作为登录账号 */ private String depNo; /** * 部门名称 */ private String depName; /** * 部门密 <SUF>*/ private String depPassword; /** * 部门人数 */ private Integer depPersonCount; /** * 部门邮箱 一般账号掌控在一个人手里 通过提醒通知要开会 */ private String depEmail; /** * 角色是用户 */ private String role; }
false
274
11
305
8
320
10
305
8
411
12
false
false
false
false
false
true
64250_7
package com.chuxin.law.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.chuxin.law.common.CommonConstant; import com.chuxin.law.common.CommonLogic; import com.chuxin.law.model.CarouseModel; import com.chuxin.law.ui.activity.AudioDetailsActivity; import com.chuxin.law.ui.activity.IntegralActivity; import com.chuxin.law.ui.activity.LawyerIntroductionActivity; import com.chuxin.law.ui.activity.WebViewActivity; import com.chuxin.law.util.GlideImageLoader; import com.chuxin.law.util.UIUtils; import com.chuxin.law.ui.widget.xRecyclerView.XRecyclerView; import com.jusfoun.baselibrary.Util.PhoneUtil; import com.jusfoun.baselibrary.net.Api; import com.youth.banner.Banner; import com.youth.banner.BannerConfig; import com.youth.banner.Transformer; import com.chuxin.law.R; import com.chuxin.law.base.BaseTalkLawFragment; import com.chuxin.law.common.ApiService; import com.chuxin.law.model.ProductListModel; import com.chuxin.law.ui.activity.AtaxCalculatorActivity; import com.chuxin.law.ui.activity.DateCalculatorActivity; import com.chuxin.law.ui.activity.LawyerCalculatorActivity; import com.chuxin.law.ui.activity.LitigationCalculatorActivity; import com.chuxin.law.ui.activity.SearchActivity; import com.chuxin.law.ui.adapter.ProductListAdapter; import com.chuxin.law.ui.widget.BackTitleView; import com.youth.banner.listener.OnBannerListener; import java.util.List; import rx.functions.Action1; import static com.chuxin.law.common.CommonConstant.NET_SUC_CODE; /** * @author zhaoyapeng * @version create time:17/12/2115:49 * @Email [email protected] * @Description ${看法} */ public class StatementFragment extends BaseTalkLawFragment implements View.OnClickListener { protected Banner banner; protected XRecyclerView recyclerView; protected LinearLayout layoutLitigation; protected LinearLayout layoutLawyer; protected LinearLayout layoutAtax; protected LinearLayout layoutDate; protected LinearLayout layoutSearchEdit; protected ImageView imgAudio; protected BackTitleView backTitleView; private ProductListAdapter adapter; private int listDy = 0; private int disY; private List<CarouseModel> carouseList; public static StatementFragment getInstance() { StatementFragment fragment = new StatementFragment(); return fragment; } @Override public int getLayoutResId() { return R.layout.fragment_statement; } @Override public void initDatas() { adapter = new ProductListAdapter(mContext); disY = PhoneUtil.dip2px(mContext, 200); } @Override public void initView(View rootView) { recyclerView = (XRecyclerView) rootView.findViewById(R.id.list); layoutLitigation = (LinearLayout) rootView.findViewById(R.id.layout_litigation); layoutLitigation.setOnClickListener(StatementFragment.this); layoutLawyer = (LinearLayout) rootView.findViewById(R.id.layout_lawyer); layoutLawyer.setOnClickListener(StatementFragment.this); layoutAtax = (LinearLayout) rootView.findViewById(R.id.layout_atax); layoutAtax.setOnClickListener(StatementFragment.this); layoutDate = (LinearLayout) rootView.findViewById(R.id.layout_date); layoutDate.setOnClickListener(StatementFragment.this); View headerView = LayoutInflater.from(mContext).inflate(R.layout.layout_statemen_header, null); recyclerView.addHeaderView(headerView); banner = (Banner) headerView.findViewById(R.id.banner); layoutSearchEdit = (LinearLayout) headerView.findViewById(R.id.layout_search_edit); imgAudio = (ImageView) headerView.findViewById(R.id.img_audio); backTitleView = (BackTitleView) rootView.findViewById(R.id.back_title_view); } @Override public void initAction() { rxManage.on(CommonConstant.EVNET_LIKE, new Action1<Object>() { @Override public void call(Object o) { delMsg(false); } }); recyclerView.setHasFixedSize(true); recyclerView.setPullRefreshEnabled(false); //设置banner样式 banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR); //设置图片加载器 banner.setImageLoader(new GlideImageLoader()); //设置图片集合 //设置banner动画效果 banner.setBannerAnimation(Transformer.Default); //设置标题集合(当banner样式有显示title时) // banner.setBannerTitles(titles); //设置自动轮播,默认为true banner.isAutoPlay(true); //设置轮播时间 banner.setDelayTime(3000); //设置指示器位置(当banner模式中有指示器时) banner.setIndicatorGravity(BannerConfig.CENTER); backTitleView.setFocusable(true); backTitleView.setFocusableInTouchMode(true); backTitleView.requestFocus(); recyclerView.setLayoutManager(new LinearLayoutManager(mContext)); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { listDy += dy; if (listDy < 0) { listDy = 0; } float alpha = listDy / (float) disY; backTitleView.setAlpha(alpha); } }); backTitleView.setTitle("看法"); layoutSearchEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goActivity(null, SearchActivity.class); } }); imgAudio.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (CommonLogic.getInstance().getLawyerProductData()!=null) { Intent intent = new Intent(mContext, AudioDetailsActivity.class); mContext.startActivity(intent); }else { showToast("没有音频"); } } }); banner.setOnBannerListener(new OnBannerListener() { @Override public void OnBannerClick(int position) { if (carouseList != null) { CarouseModel model = carouseList.get(position); if (model != null) { if ("0".equals(model.atype)) { UIUtils.goLawyerDef(mContext, model.url); }else if("1".equals(model.atype)) { Intent intent = new Intent(mContext, WebViewActivity.class); intent.putExtra("url",model.url); intent.putExtra("title","详情"); mContext.startActivity(intent); }else if("2".equals(model.atype)){ Intent intent = new Intent(); intent.putExtra(LawyerIntroductionActivity.ID, model.url); intent.setClass(mContext, LawyerIntroductionActivity.class); mContext.startActivity(intent); }else if("3".equals(model.atype)){ Intent intent = new Intent(); intent.setClass(mContext, IntegralActivity.class); mContext.startActivity(intent); } } } } }); backTitleView.setLeftGone(); } @Override public void onClick(View view) { if (view.getId() == R.id.layout_litigation) { goActivity(null, LitigationCalculatorActivity.class); } else if (view.getId() == R.id.layout_lawyer) { goActivity(null, LawyerCalculatorActivity.class); } else if (view.getId() == R.id.layout_atax) { goActivity(null, AtaxCalculatorActivity.class); } else if (view.getId() == R.id.layout_date) { goActivity(null, DateCalculatorActivity.class); } } @Override protected void refreshData() { delMsg(true); } private void delMsg(boolean isShow) { if (isShow) { showLoadDialog(); } addNetwork(Api.getInstance().getService(ApiService.class).getHomeKanfa() , new Action1<ProductListModel>() { @Override public void call(ProductListModel model) { hideLoadDialog(); if (model != null && model.getCode() == NET_SUC_CODE) { if (model.data != null) { if (model.data.article != null) { adapter.refreshList(model.data.article); } if (model.data.carouse != null) { carouseList = model.data.carouse; banner.setImages(model.data.carouse); banner.start(); // if(model.data.carouse.size()>0) { //// banner.setVisibility(View.VISIBLE); // // }else{ //// banner.setVisibility(View.GONE); // } } else { // banner.setVisibility(View.GONE); } } } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { hideLoadDialog(); } }); } }
ZypTeam/TalkLaw
app/src/main/java/com/chuxin/law/ui/fragment/StatementFragment.java
2,319
//设置自动轮播,默认为true
line_comment
zh-cn
package com.chuxin.law.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.chuxin.law.common.CommonConstant; import com.chuxin.law.common.CommonLogic; import com.chuxin.law.model.CarouseModel; import com.chuxin.law.ui.activity.AudioDetailsActivity; import com.chuxin.law.ui.activity.IntegralActivity; import com.chuxin.law.ui.activity.LawyerIntroductionActivity; import com.chuxin.law.ui.activity.WebViewActivity; import com.chuxin.law.util.GlideImageLoader; import com.chuxin.law.util.UIUtils; import com.chuxin.law.ui.widget.xRecyclerView.XRecyclerView; import com.jusfoun.baselibrary.Util.PhoneUtil; import com.jusfoun.baselibrary.net.Api; import com.youth.banner.Banner; import com.youth.banner.BannerConfig; import com.youth.banner.Transformer; import com.chuxin.law.R; import com.chuxin.law.base.BaseTalkLawFragment; import com.chuxin.law.common.ApiService; import com.chuxin.law.model.ProductListModel; import com.chuxin.law.ui.activity.AtaxCalculatorActivity; import com.chuxin.law.ui.activity.DateCalculatorActivity; import com.chuxin.law.ui.activity.LawyerCalculatorActivity; import com.chuxin.law.ui.activity.LitigationCalculatorActivity; import com.chuxin.law.ui.activity.SearchActivity; import com.chuxin.law.ui.adapter.ProductListAdapter; import com.chuxin.law.ui.widget.BackTitleView; import com.youth.banner.listener.OnBannerListener; import java.util.List; import rx.functions.Action1; import static com.chuxin.law.common.CommonConstant.NET_SUC_CODE; /** * @author zhaoyapeng * @version create time:17/12/2115:49 * @Email [email protected] * @Description ${看法} */ public class StatementFragment extends BaseTalkLawFragment implements View.OnClickListener { protected Banner banner; protected XRecyclerView recyclerView; protected LinearLayout layoutLitigation; protected LinearLayout layoutLawyer; protected LinearLayout layoutAtax; protected LinearLayout layoutDate; protected LinearLayout layoutSearchEdit; protected ImageView imgAudio; protected BackTitleView backTitleView; private ProductListAdapter adapter; private int listDy = 0; private int disY; private List<CarouseModel> carouseList; public static StatementFragment getInstance() { StatementFragment fragment = new StatementFragment(); return fragment; } @Override public int getLayoutResId() { return R.layout.fragment_statement; } @Override public void initDatas() { adapter = new ProductListAdapter(mContext); disY = PhoneUtil.dip2px(mContext, 200); } @Override public void initView(View rootView) { recyclerView = (XRecyclerView) rootView.findViewById(R.id.list); layoutLitigation = (LinearLayout) rootView.findViewById(R.id.layout_litigation); layoutLitigation.setOnClickListener(StatementFragment.this); layoutLawyer = (LinearLayout) rootView.findViewById(R.id.layout_lawyer); layoutLawyer.setOnClickListener(StatementFragment.this); layoutAtax = (LinearLayout) rootView.findViewById(R.id.layout_atax); layoutAtax.setOnClickListener(StatementFragment.this); layoutDate = (LinearLayout) rootView.findViewById(R.id.layout_date); layoutDate.setOnClickListener(StatementFragment.this); View headerView = LayoutInflater.from(mContext).inflate(R.layout.layout_statemen_header, null); recyclerView.addHeaderView(headerView); banner = (Banner) headerView.findViewById(R.id.banner); layoutSearchEdit = (LinearLayout) headerView.findViewById(R.id.layout_search_edit); imgAudio = (ImageView) headerView.findViewById(R.id.img_audio); backTitleView = (BackTitleView) rootView.findViewById(R.id.back_title_view); } @Override public void initAction() { rxManage.on(CommonConstant.EVNET_LIKE, new Action1<Object>() { @Override public void call(Object o) { delMsg(false); } }); recyclerView.setHasFixedSize(true); recyclerView.setPullRefreshEnabled(false); //设置banner样式 banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR); //设置图片加载器 banner.setImageLoader(new GlideImageLoader()); //设置图片集合 //设置banner动画效果 banner.setBannerAnimation(Transformer.Default); //设置标题集合(当banner样式有显示title时) // banner.setBannerTitles(titles); //设置 <SUF> banner.isAutoPlay(true); //设置轮播时间 banner.setDelayTime(3000); //设置指示器位置(当banner模式中有指示器时) banner.setIndicatorGravity(BannerConfig.CENTER); backTitleView.setFocusable(true); backTitleView.setFocusableInTouchMode(true); backTitleView.requestFocus(); recyclerView.setLayoutManager(new LinearLayoutManager(mContext)); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { listDy += dy; if (listDy < 0) { listDy = 0; } float alpha = listDy / (float) disY; backTitleView.setAlpha(alpha); } }); backTitleView.setTitle("看法"); layoutSearchEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goActivity(null, SearchActivity.class); } }); imgAudio.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (CommonLogic.getInstance().getLawyerProductData()!=null) { Intent intent = new Intent(mContext, AudioDetailsActivity.class); mContext.startActivity(intent); }else { showToast("没有音频"); } } }); banner.setOnBannerListener(new OnBannerListener() { @Override public void OnBannerClick(int position) { if (carouseList != null) { CarouseModel model = carouseList.get(position); if (model != null) { if ("0".equals(model.atype)) { UIUtils.goLawyerDef(mContext, model.url); }else if("1".equals(model.atype)) { Intent intent = new Intent(mContext, WebViewActivity.class); intent.putExtra("url",model.url); intent.putExtra("title","详情"); mContext.startActivity(intent); }else if("2".equals(model.atype)){ Intent intent = new Intent(); intent.putExtra(LawyerIntroductionActivity.ID, model.url); intent.setClass(mContext, LawyerIntroductionActivity.class); mContext.startActivity(intent); }else if("3".equals(model.atype)){ Intent intent = new Intent(); intent.setClass(mContext, IntegralActivity.class); mContext.startActivity(intent); } } } } }); backTitleView.setLeftGone(); } @Override public void onClick(View view) { if (view.getId() == R.id.layout_litigation) { goActivity(null, LitigationCalculatorActivity.class); } else if (view.getId() == R.id.layout_lawyer) { goActivity(null, LawyerCalculatorActivity.class); } else if (view.getId() == R.id.layout_atax) { goActivity(null, AtaxCalculatorActivity.class); } else if (view.getId() == R.id.layout_date) { goActivity(null, DateCalculatorActivity.class); } } @Override protected void refreshData() { delMsg(true); } private void delMsg(boolean isShow) { if (isShow) { showLoadDialog(); } addNetwork(Api.getInstance().getService(ApiService.class).getHomeKanfa() , new Action1<ProductListModel>() { @Override public void call(ProductListModel model) { hideLoadDialog(); if (model != null && model.getCode() == NET_SUC_CODE) { if (model.data != null) { if (model.data.article != null) { adapter.refreshList(model.data.article); } if (model.data.carouse != null) { carouseList = model.data.carouse; banner.setImages(model.data.carouse); banner.start(); // if(model.data.carouse.size()>0) { //// banner.setVisibility(View.VISIBLE); // // }else{ //// banner.setVisibility(View.GONE); // } } else { // banner.setVisibility(View.GONE); } } } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { hideLoadDialog(); } }); } }
false
1,911
8
2,319
8
2,432
8
2,319
8
2,805
16
false
false
false
false
false
true
52566_5
package easy; /** * @author: zhangchen * @date: 2021/1/5 * @description: 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 * 这题主要复习一下str.charAt() str.substring() */ public class Solution14 { public String longestCommonPrefix(String[] strs) { //特殊情况处理 if (strs.length == 0) { return ""; } //首先把答案设成第一个字符串 String ans = strs[0]; //然后从第二个开始跟第一个找 for (int i = 1; i < strs.length; i++) { int j = 0; //判断两个字符串到哪为止一样的 for (; j < ans.length() && j < strs[i].length(); j++) { if (ans.charAt(j) != strs[i].charAt(j)) { break; } } //截取一样的字符串,要是空,那就直接返回答案为空了 ans = ans.substring(0, j); if ("".equals(ans)) { return ans; } } return ans; } }
ZzCoding530/leetcode530
src/easy/Solution14.java
297
//截取一样的字符串,要是空,那就直接返回答案为空了
line_comment
zh-cn
package easy; /** * @author: zhangchen * @date: 2021/1/5 * @description: 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 * 这题主要复习一下str.charAt() str.substring() */ public class Solution14 { public String longestCommonPrefix(String[] strs) { //特殊情况处理 if (strs.length == 0) { return ""; } //首先把答案设成第一个字符串 String ans = strs[0]; //然后从第二个开始跟第一个找 for (int i = 1; i < strs.length; i++) { int j = 0; //判断两个字符串到哪为止一样的 for (; j < ans.length() && j < strs[i].length(); j++) { if (ans.charAt(j) != strs[i].charAt(j)) { break; } } //截取 <SUF> ans = ans.substring(0, j); if ("".equals(ans)) { return ans; } } return ans; } }
false
262
15
297
19
300
15
297
19
401
31
false
false
false
false
false
true
23053_0
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.stage.Stage; import util.TimeUtil; import util.netUtil.NetUtil; import util.netUtil.ParametersBuilder; import util.netUtil.PropertyBuilder; import util.regexUtil.RegexUtil; import util.regexUtil.UnicodeUtil; import java.util.*; public class Main extends Application implements NetUtil.ConnectFinishListener { //控件 private Button test, start, stop; private TextField input_target, input_interval, match_left, match_right, schedule_long; private TextField time_hour, time_minute; private TextArea tv, input_formData, input_headers; private Hyperlink hyperlink; //配置 private String targetUrl = "", formData = "", headers = ""; private String match_left_string = "", match_right_string = ""; private int interval = 50; private int hour, minute; private boolean delay = false;//定时 private Thread delayThread = null; //临时变量 private StringBuilder tvContent = new StringBuilder(); private NetUtil netUtil = null; //应用密码 private static final String KEY = "ziaiscool"; private static final String URL = "http://zzzia.net:8080/key"; private static final String APPNAME = "netrobot"; private boolean hasKey = false; @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("main.fxml")); primaryStage.setTitle("NetRobot"); primaryStage.setScene(new Scene(root)); primaryStage.show(); primaryStage.setOnCloseRequest(event -> { primaryStage.close(); try { stop(); } catch (Exception e) { e.printStackTrace(); } }); //检查是否有应用使用权 checkPassword(primaryStage); //寻找控件 findId(root); //设置点击事件 //测试按钮 test.setOnAction(event -> { appendContent("开始测试"); prepareInput(); test(); }); //开始按钮 start.setOnAction(event -> { if (!prepareInput()) { end(); return; } start.setDisable(true); stop.setDisable(false); if (targetUrl.isEmpty()) return; if (delay) { Date targetDate = TimeUtil.getDate(hour, minute); delayThread = new Thread(() -> { while (true) { try { long restTime = targetDate.getTime() - new Date().getTime();//剩余时间 if (restTime < 1000) {//不到1s,直接开始运行 appendContent("已开始"); long second = 0; if (!schedule_long.isDisable()) { second = Long.parseLong(schedule_long.getText()); } fucking(1000L * second); break; } else { tv.setText("剩余等待时间:" + restTime / 1000 + "秒"); } Thread.sleep(500L);//由于定时引起的误差,每0.5s检查一次 } catch (InterruptedException e) { e.printStackTrace(); } } }); delayThread.start(); } else { appendContent("已开始"); fucking(); } }); //停止按钮 stop.setOnAction(event -> end()); //超链接 hyperlink.setOnAction(event -> { // try { // // 创建一个URI实例 // java.net.URI uri = java.net.URI.create("https://github.com/Zzzia/NetRobot"); // // 获取当前系统桌面扩展 // java.awt.Desktop dp = java.awt.Desktop.getDesktop(); // // 判断系统桌面是否支持要执行的功能 // if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) { // // 获取系统默认浏览器打开链接 // dp.browse(uri); // } // // } catch (Exception e) { // e.printStackTrace(); // } }); //监听是否定时 time_hour.textProperty().addListener((observable, oldValue, newValue) -> { if (!newValue.isEmpty()) { schedule_long.setDisable(false); } else { schedule_long.setDisable(true); } }); //关闭软件监听,防止内存泄漏 primaryStage.setOnCloseRequest(event -> { if (netUtil != null) { netUtil.stop(); } }); } private void checkPassword(Stage primaryStage) { try { String result = new NetUtil .Builder(URL) .doPostAppend("/?key=netrobot") .build() .connect(); if (!result.contains(KEY)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("提示"); alert.setContentText("服务器已关闭对该应用的支持"); alert.show(); primaryStage.close(); } else { hasKey = true; } } catch (Exception e) { e.printStackTrace(); } } private void fucking() { fucking(0); } private void fucking(long timeout) { //预留个空指针bug,看谁敢破解密码 netUtil = getBuilder().build(); netUtil.fuckingConnect(interval); if (timeout != 0) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { end(); } }, timeout); } } private void test() { netUtil = getBuilder().build(); netUtil.connect(1); } private void end() { if (netUtil != null) { netUtil.stop(); } if (delayThread != null && delayThread.isAlive()) { delayThread.stop(); } start.setDisable(false); stop.setDisable(true); appendContent("已结束"); } private NetUtil.Builder getBuilder() { if (!hasKey) return null; NetUtil.Builder builder = new NetUtil .Builder(targetUrl) .openLog(true) .connectFinishListener(this); if (!formData.isEmpty()) { builder = builder.doPost(new ParametersBuilder().put(formData)); } else { builder = builder.doGet(); } if (!headers.isEmpty()) { Map<String, String> headerMap = new HashMap<>(); String[] headerList = headers.split("\n"); for (String header : headerList) { String[] property = header.split(":"); if (property.length == 2) { headerMap.put(property[0].trim(), property[1].trim()); } } System.out.println(headers); PropertyBuilder propertyBuilder = new PropertyBuilder() .addProperty("Referer", targetUrl) .addProperty(headerMap); builder = builder.property(propertyBuilder); } return builder; } private void findId(Parent root) { test = (Button) root.lookup("#button_test"); start = (Button) root.lookup("#button_start"); stop = (Button) root.lookup("#button_stop"); input_target = (TextField) root.lookup("#input_target"); input_interval = (TextField) root.lookup("#input_interval"); time_hour = (TextField) root.lookup("#time_hour"); time_minute = (TextField) root.lookup("#time_minute"); tv = (TextArea) root.lookup("#tv"); input_formData = (TextArea) root.lookup("#input_formData"); input_headers = (TextArea) root.lookup("#input_headers"); match_left = (TextField) root.lookup("#match_left"); match_right = (TextField) root.lookup("#match_right"); hyperlink = (Hyperlink) root.lookup("#hyperlink"); schedule_long = (TextField) root.lookup("#schedule_long"); } private boolean prepareInput() { targetUrl = input_target.getText(); headers = input_headers.getText(); formData = input_formData.getText(); interval = Integer.parseInt(input_interval.getText()); match_left_string = match_left.getText(); match_right_string = match_right.getText(); if (!time_hour.getText().isEmpty() && !time_minute.getText().isEmpty()) { hour = Integer.parseInt(time_hour.getText()); minute = Integer.parseInt(time_minute.getText()); delay = true; } if (targetUrl.isEmpty()) { appendContent("目标网址不能为空"); return false; } else if (hour < 0 || hour > 24 || minute < 0 || minute > 60) { appendContent("时间为24小时制"); return false; } else { return true; } } private void appendContent(String content) { if (tvContent.length() > 1024 * 1024) { tvContent = new StringBuilder(); } tvContent.append(content).append("\n"); tv.setText(tvContent.toString()); tv.setScrollTop(Double.MAX_VALUE); } public static void main(String[] args) { launch(args); } @Override public void onFinish(String result) { if (!match_left_string.isEmpty() && !match_right_string.isEmpty()) { result = RegexUtil.regexInclude(match_left_string, match_right_string, result).get(0); } appendContent(UnicodeUtil.unicodeToString(result)); } }
Zzzia/NetRobot
src/Main.java
2,263
//临时变量
line_comment
zh-cn
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.stage.Stage; import util.TimeUtil; import util.netUtil.NetUtil; import util.netUtil.ParametersBuilder; import util.netUtil.PropertyBuilder; import util.regexUtil.RegexUtil; import util.regexUtil.UnicodeUtil; import java.util.*; public class Main extends Application implements NetUtil.ConnectFinishListener { //控件 private Button test, start, stop; private TextField input_target, input_interval, match_left, match_right, schedule_long; private TextField time_hour, time_minute; private TextArea tv, input_formData, input_headers; private Hyperlink hyperlink; //配置 private String targetUrl = "", formData = "", headers = ""; private String match_left_string = "", match_right_string = ""; private int interval = 50; private int hour, minute; private boolean delay = false;//定时 private Thread delayThread = null; //临时 <SUF> private StringBuilder tvContent = new StringBuilder(); private NetUtil netUtil = null; //应用密码 private static final String KEY = "ziaiscool"; private static final String URL = "http://zzzia.net:8080/key"; private static final String APPNAME = "netrobot"; private boolean hasKey = false; @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("main.fxml")); primaryStage.setTitle("NetRobot"); primaryStage.setScene(new Scene(root)); primaryStage.show(); primaryStage.setOnCloseRequest(event -> { primaryStage.close(); try { stop(); } catch (Exception e) { e.printStackTrace(); } }); //检查是否有应用使用权 checkPassword(primaryStage); //寻找控件 findId(root); //设置点击事件 //测试按钮 test.setOnAction(event -> { appendContent("开始测试"); prepareInput(); test(); }); //开始按钮 start.setOnAction(event -> { if (!prepareInput()) { end(); return; } start.setDisable(true); stop.setDisable(false); if (targetUrl.isEmpty()) return; if (delay) { Date targetDate = TimeUtil.getDate(hour, minute); delayThread = new Thread(() -> { while (true) { try { long restTime = targetDate.getTime() - new Date().getTime();//剩余时间 if (restTime < 1000) {//不到1s,直接开始运行 appendContent("已开始"); long second = 0; if (!schedule_long.isDisable()) { second = Long.parseLong(schedule_long.getText()); } fucking(1000L * second); break; } else { tv.setText("剩余等待时间:" + restTime / 1000 + "秒"); } Thread.sleep(500L);//由于定时引起的误差,每0.5s检查一次 } catch (InterruptedException e) { e.printStackTrace(); } } }); delayThread.start(); } else { appendContent("已开始"); fucking(); } }); //停止按钮 stop.setOnAction(event -> end()); //超链接 hyperlink.setOnAction(event -> { // try { // // 创建一个URI实例 // java.net.URI uri = java.net.URI.create("https://github.com/Zzzia/NetRobot"); // // 获取当前系统桌面扩展 // java.awt.Desktop dp = java.awt.Desktop.getDesktop(); // // 判断系统桌面是否支持要执行的功能 // if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) { // // 获取系统默认浏览器打开链接 // dp.browse(uri); // } // // } catch (Exception e) { // e.printStackTrace(); // } }); //监听是否定时 time_hour.textProperty().addListener((observable, oldValue, newValue) -> { if (!newValue.isEmpty()) { schedule_long.setDisable(false); } else { schedule_long.setDisable(true); } }); //关闭软件监听,防止内存泄漏 primaryStage.setOnCloseRequest(event -> { if (netUtil != null) { netUtil.stop(); } }); } private void checkPassword(Stage primaryStage) { try { String result = new NetUtil .Builder(URL) .doPostAppend("/?key=netrobot") .build() .connect(); if (!result.contains(KEY)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("提示"); alert.setContentText("服务器已关闭对该应用的支持"); alert.show(); primaryStage.close(); } else { hasKey = true; } } catch (Exception e) { e.printStackTrace(); } } private void fucking() { fucking(0); } private void fucking(long timeout) { //预留个空指针bug,看谁敢破解密码 netUtil = getBuilder().build(); netUtil.fuckingConnect(interval); if (timeout != 0) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { end(); } }, timeout); } } private void test() { netUtil = getBuilder().build(); netUtil.connect(1); } private void end() { if (netUtil != null) { netUtil.stop(); } if (delayThread != null && delayThread.isAlive()) { delayThread.stop(); } start.setDisable(false); stop.setDisable(true); appendContent("已结束"); } private NetUtil.Builder getBuilder() { if (!hasKey) return null; NetUtil.Builder builder = new NetUtil .Builder(targetUrl) .openLog(true) .connectFinishListener(this); if (!formData.isEmpty()) { builder = builder.doPost(new ParametersBuilder().put(formData)); } else { builder = builder.doGet(); } if (!headers.isEmpty()) { Map<String, String> headerMap = new HashMap<>(); String[] headerList = headers.split("\n"); for (String header : headerList) { String[] property = header.split(":"); if (property.length == 2) { headerMap.put(property[0].trim(), property[1].trim()); } } System.out.println(headers); PropertyBuilder propertyBuilder = new PropertyBuilder() .addProperty("Referer", targetUrl) .addProperty(headerMap); builder = builder.property(propertyBuilder); } return builder; } private void findId(Parent root) { test = (Button) root.lookup("#button_test"); start = (Button) root.lookup("#button_start"); stop = (Button) root.lookup("#button_stop"); input_target = (TextField) root.lookup("#input_target"); input_interval = (TextField) root.lookup("#input_interval"); time_hour = (TextField) root.lookup("#time_hour"); time_minute = (TextField) root.lookup("#time_minute"); tv = (TextArea) root.lookup("#tv"); input_formData = (TextArea) root.lookup("#input_formData"); input_headers = (TextArea) root.lookup("#input_headers"); match_left = (TextField) root.lookup("#match_left"); match_right = (TextField) root.lookup("#match_right"); hyperlink = (Hyperlink) root.lookup("#hyperlink"); schedule_long = (TextField) root.lookup("#schedule_long"); } private boolean prepareInput() { targetUrl = input_target.getText(); headers = input_headers.getText(); formData = input_formData.getText(); interval = Integer.parseInt(input_interval.getText()); match_left_string = match_left.getText(); match_right_string = match_right.getText(); if (!time_hour.getText().isEmpty() && !time_minute.getText().isEmpty()) { hour = Integer.parseInt(time_hour.getText()); minute = Integer.parseInt(time_minute.getText()); delay = true; } if (targetUrl.isEmpty()) { appendContent("目标网址不能为空"); return false; } else if (hour < 0 || hour > 24 || minute < 0 || minute > 60) { appendContent("时间为24小时制"); return false; } else { return true; } } private void appendContent(String content) { if (tvContent.length() > 1024 * 1024) { tvContent = new StringBuilder(); } tvContent.append(content).append("\n"); tv.setText(tvContent.toString()); tv.setScrollTop(Double.MAX_VALUE); } public static void main(String[] args) { launch(args); } @Override public void onFinish(String result) { if (!match_left_string.isEmpty() && !match_right_string.isEmpty()) { result = RegexUtil.regexInclude(match_left_string, match_right_string, result).get(0); } appendContent(UnicodeUtil.unicodeToString(result)); } }
false
1,959
3
2,263
4
2,438
3
2,263
4
2,806
7
false
false
false
false
false
true
21518_0
import java.util.ArrayList; class Main {     public static void main(String[] args){         // 创建一个数组         ArrayList<String> sites = new ArrayList<>();         sites.add("Google");         sites.add("Runoob");         sites.add("Taobao");         System.out.println("网站列表: " + sites);         // 检查 Runoob 是否在这个数组中         System.out.print("Runoob 是否存在于 arraylist: ");         System.out.println(sites.contains("Runoob"));         // 检查 Weibo 是否在这个数组中         System.out.print("Weibo 是否存在于 arraylist: ");         System.out.println(sites.contains("Weibo"));     } }
a-java-engineer/EveryDayPush
arraylistTest.java
202
// 创建一个数组
line_comment
zh-cn
import java.util.ArrayList; class Main {     public static void main(String[] args){         // 创建 <SUF>         ArrayList<String> sites = new ArrayList<>();         sites.add("Google");         sites.add("Runoob");         sites.add("Taobao");         System.out.println("网站列表: " + sites);         // 检查 Runoob 是否在这个数组中         System.out.print("Runoob 是否存在于 arraylist: ");         System.out.println(sites.contains("Runoob"));         // 检查 Weibo 是否在这个数组中         System.out.print("Weibo 是否存在于 arraylist: ");         System.out.println(sites.contains("Weibo"));     } }
false
171
4
202
4
206
4
202
4
252
8
false
false
false
false
false
true
62713_11
package com.wishes.assistant.myapplication.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.jetradar.desertplaceholder.DesertPlaceholder; import com.majeur.cling.Cling; import com.majeur.cling.ClingManager; import com.majeur.cling.ViewTarget; import com.wishes.assistant.io.sharepreference.SharePreferenceUtils; import com.wishes.assistant.myapplication.R; import com.wishes.assistant.net.download.NewPackageDownloadService; import com.wishes.assistant.otherutils.RedPacketChecker; import com.wishes.assistant.otherutils.UpdateAPKChecker; import com.wishes.assistant.otherutils.UserGuide; import com.yasic.library.particletextview.View.ParticleTextView; import cn.refactor.lib.colordialog.PromptDialog; import es.dmoral.toasty.Toasty; import skin.support.app.SkinCompatActivity; /** * Created by 郑龙 on 2017/4/28. */ public class About extends SkinCompatActivity { //Android cline private ClingManager mClingManager; private static String START_TUTORIAL_KEY = "AboutActivityShowedGuide"; private ImageView mImgBack; private TextView mAppVersion; private ParticleTextView particleTextView; private DesertPlaceholder mPlaceholder; private Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: //不用升级 new PromptDialog(About.this) .setDialogType(PromptDialog.DIALOG_TYPE_SUCCESS) .setAnimationEnable(true) .setTitleText("恭喜!") .setContentText("你已安装最新版!") .setPositiveListener("确定", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { dialog.dismiss(); } }).show(); break; case 1: //需要升级 UpdateAPKChecker.Version version = UpdateAPKChecker.getmVersion(); new PromptDialog(About.this) .setDialogType(PromptDialog.DIALOG_TYPE_INFO) .setAnimationEnable(true) .setTitleText("更新提示") .setContentText("版本:\t" + version.getVersion() + "\n\n" + version.getContent() + "\n\n更新时间:\t" + version .getUpdateTime()) .setPositiveListener("更新", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { Intent service = new Intent(About.this, NewPackageDownloadService.class); startService(service); Toasty.info(About.this, "已开始更新,稍后将进行自动安装", Toast.LENGTH_SHORT, true).show(); dialog.dismiss(); } }) .show(); break; } } }; private Handler redPacketHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 521: //我比较喜欢这个数字~ RedPacketChecker.RedPacket redPacket = (RedPacketChecker.RedPacket) msg.obj; if (redPacket != null) { //如果响应体不为空 new PromptDialog(About.this) .setDialogType(PromptDialog.DIALOG_TYPE_INFO) .setAnimationEnable(true) .setTitleText(redPacket.getRedPacketName()) .setContentText(redPacket.getRedPacketContent() + "\n\n手快有,手慢无!\n" + redPacket.getUpdateTime()) .setPositiveListener("我知道啦", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { dialog.dismiss(); } }) .show(); } break; } } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); //设置沉浸式状态栏 getWindow().setStatusBarColor(Color.argb(255, 216, 243, 255)); mImgBack = (ImageView) findViewById(R.id.title_btn_back); mImgBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mPlaceholder = findViewById(R.id.placeholder); mPlaceholder.setOnButtonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //检测是否有更新 new Thread(new Runnable() { @Override public void run() { if (UpdateAPKChecker.checkNewestVersion(About.this)) { //如果需要更新 Message msg = Message.obtain(); msg.what = 1; updateHandler.sendMessage(msg); } else { Message msg = Message.obtain(); msg.what = 0; updateHandler.sendMessage(msg); } } }).start(); } }); //检测是否显示红包 showRedPacket(); TextView mAppName = findViewById(R.id.tv_app_name); //设置字体 Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/fzse.ttf"); mAppName.setTypeface(tf2); mAppVersion = findViewById(R.id.tv_version); mAppVersion.setText("当前应用版本:" + UpdateAPKChecker.getAppVersionName()); } /** * 显示红包相关 */ private void showRedPacket() { //判断是否登录教务系统 if (SharePreferenceUtils.isLoginJWSystem(About.this)) { //如果登录 SharedPreferences share = About.this.getSharedPreferences("student", Context.MODE_PRIVATE); final String name = share.getString("name", null); new Thread(new Runnable() { @Override public void run() { Message msg = Message.obtain(); msg.obj = RedPacketChecker.checkRedPacket(About.this, name); msg.what = 521; redPacketHandler.sendMessage(msg); } }).start(); } else { //否则不显示 Message msg = Message.obtain(); msg.what = 0; redPacketHandler.sendMessage(msg); } } /** * 用于显示帮助 */ @Override protected void onResume() { if (UserGuide.isFirstStart(About.this, START_TUTORIAL_KEY)) { //当是第一次启动Activity时 mClingManager = new ClingManager(this); // When no Target is set, Target.NONE is used mClingManager.addCling(new Cling.Builder(this) .setTitle("关于") .setContent("这是关于界面,点击下方检测更新按钮可以检测最新版App") .build()); mClingManager.addCling(new Cling.Builder(this) .setTitle("Tips") .setContent("点击这里可以返回主界面") .setMessageBackground(getResources().getColor(R.color.colorPrimary)) .setTarget(new ViewTarget(this, R.id.title_btn_back)) .build()); mClingManager.setCallbacks(new ClingManager.Callbacks() { @Override public boolean onClingClick(int position) { // We return false to tell to cling manager that we didn't handle this, // so it can perform the default action (ie. showing the next Cling). // This is the default value returned by super.onClingClick(position), so // in a real project, we would just leave this method unoverriden. return false; } @Override public void onClingShow(int position) { } @Override public void onClingHide(int position) { // Last Cling has been shown, tutorial is ended. if (position == 1) { //Toasty.success(About.this, "真棒!居然这么快就学会了!", Toast.LENGTH_SHORT, false).show(); mClingManager = null; UserGuide.changeActivityStartTimes(About.this, START_TUTORIAL_KEY); } } }); mClingManager.start(); } super.onResume(); } @Override public void onBackPressed() { finish(); } }
a1098832322/JWSysAssistant-2.0
login/src/main/java/com/wishes/assistant/myapplication/activity/About.java
2,064
/** * 显示红包相关 */
block_comment
zh-cn
package com.wishes.assistant.myapplication.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.jetradar.desertplaceholder.DesertPlaceholder; import com.majeur.cling.Cling; import com.majeur.cling.ClingManager; import com.majeur.cling.ViewTarget; import com.wishes.assistant.io.sharepreference.SharePreferenceUtils; import com.wishes.assistant.myapplication.R; import com.wishes.assistant.net.download.NewPackageDownloadService; import com.wishes.assistant.otherutils.RedPacketChecker; import com.wishes.assistant.otherutils.UpdateAPKChecker; import com.wishes.assistant.otherutils.UserGuide; import com.yasic.library.particletextview.View.ParticleTextView; import cn.refactor.lib.colordialog.PromptDialog; import es.dmoral.toasty.Toasty; import skin.support.app.SkinCompatActivity; /** * Created by 郑龙 on 2017/4/28. */ public class About extends SkinCompatActivity { //Android cline private ClingManager mClingManager; private static String START_TUTORIAL_KEY = "AboutActivityShowedGuide"; private ImageView mImgBack; private TextView mAppVersion; private ParticleTextView particleTextView; private DesertPlaceholder mPlaceholder; private Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: //不用升级 new PromptDialog(About.this) .setDialogType(PromptDialog.DIALOG_TYPE_SUCCESS) .setAnimationEnable(true) .setTitleText("恭喜!") .setContentText("你已安装最新版!") .setPositiveListener("确定", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { dialog.dismiss(); } }).show(); break; case 1: //需要升级 UpdateAPKChecker.Version version = UpdateAPKChecker.getmVersion(); new PromptDialog(About.this) .setDialogType(PromptDialog.DIALOG_TYPE_INFO) .setAnimationEnable(true) .setTitleText("更新提示") .setContentText("版本:\t" + version.getVersion() + "\n\n" + version.getContent() + "\n\n更新时间:\t" + version .getUpdateTime()) .setPositiveListener("更新", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { Intent service = new Intent(About.this, NewPackageDownloadService.class); startService(service); Toasty.info(About.this, "已开始更新,稍后将进行自动安装", Toast.LENGTH_SHORT, true).show(); dialog.dismiss(); } }) .show(); break; } } }; private Handler redPacketHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 521: //我比较喜欢这个数字~ RedPacketChecker.RedPacket redPacket = (RedPacketChecker.RedPacket) msg.obj; if (redPacket != null) { //如果响应体不为空 new PromptDialog(About.this) .setDialogType(PromptDialog.DIALOG_TYPE_INFO) .setAnimationEnable(true) .setTitleText(redPacket.getRedPacketName()) .setContentText(redPacket.getRedPacketContent() + "\n\n手快有,手慢无!\n" + redPacket.getUpdateTime()) .setPositiveListener("我知道啦", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { dialog.dismiss(); } }) .show(); } break; } } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); //设置沉浸式状态栏 getWindow().setStatusBarColor(Color.argb(255, 216, 243, 255)); mImgBack = (ImageView) findViewById(R.id.title_btn_back); mImgBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); mPlaceholder = findViewById(R.id.placeholder); mPlaceholder.setOnButtonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //检测是否有更新 new Thread(new Runnable() { @Override public void run() { if (UpdateAPKChecker.checkNewestVersion(About.this)) { //如果需要更新 Message msg = Message.obtain(); msg.what = 1; updateHandler.sendMessage(msg); } else { Message msg = Message.obtain(); msg.what = 0; updateHandler.sendMessage(msg); } } }).start(); } }); //检测是否显示红包 showRedPacket(); TextView mAppName = findViewById(R.id.tv_app_name); //设置字体 Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/fzse.ttf"); mAppName.setTypeface(tf2); mAppVersion = findViewById(R.id.tv_version); mAppVersion.setText("当前应用版本:" + UpdateAPKChecker.getAppVersionName()); } /** * 显示红 <SUF>*/ private void showRedPacket() { //判断是否登录教务系统 if (SharePreferenceUtils.isLoginJWSystem(About.this)) { //如果登录 SharedPreferences share = About.this.getSharedPreferences("student", Context.MODE_PRIVATE); final String name = share.getString("name", null); new Thread(new Runnable() { @Override public void run() { Message msg = Message.obtain(); msg.obj = RedPacketChecker.checkRedPacket(About.this, name); msg.what = 521; redPacketHandler.sendMessage(msg); } }).start(); } else { //否则不显示 Message msg = Message.obtain(); msg.what = 0; redPacketHandler.sendMessage(msg); } } /** * 用于显示帮助 */ @Override protected void onResume() { if (UserGuide.isFirstStart(About.this, START_TUTORIAL_KEY)) { //当是第一次启动Activity时 mClingManager = new ClingManager(this); // When no Target is set, Target.NONE is used mClingManager.addCling(new Cling.Builder(this) .setTitle("关于") .setContent("这是关于界面,点击下方检测更新按钮可以检测最新版App") .build()); mClingManager.addCling(new Cling.Builder(this) .setTitle("Tips") .setContent("点击这里可以返回主界面") .setMessageBackground(getResources().getColor(R.color.colorPrimary)) .setTarget(new ViewTarget(this, R.id.title_btn_back)) .build()); mClingManager.setCallbacks(new ClingManager.Callbacks() { @Override public boolean onClingClick(int position) { // We return false to tell to cling manager that we didn't handle this, // so it can perform the default action (ie. showing the next Cling). // This is the default value returned by super.onClingClick(position), so // in a real project, we would just leave this method unoverriden. return false; } @Override public void onClingShow(int position) { } @Override public void onClingHide(int position) { // Last Cling has been shown, tutorial is ended. if (position == 1) { //Toasty.success(About.this, "真棒!居然这么快就学会了!", Toast.LENGTH_SHORT, false).show(); mClingManager = null; UserGuide.changeActivityStartTimes(About.this, START_TUTORIAL_KEY); } } }); mClingManager.start(); } super.onResume(); } @Override public void onBackPressed() { finish(); } }
false
1,791
10
2,064
10
2,202
10
2,064
10
2,655
14
false
false
false
false
false
true
22597_7
package constant; /** * 常量池 * * @author 郑龙 * @date 2019/12/16 19:09 */ public class Constant { /** * 设置窗口相关 */ public static class Settings { /** * 设置窗口标题 */ public static final String SETTING_WINDOW_TITLE = "Assistant Setting"; /** * 窗体模型选择器提示文本 */ public static final String SETTING_MODEL_SELECTOR_TEXT = "请选择模型:"; /** * 窗体时间选择器提示文本 */ public static final String SETTING_TIME_SELECTOR_TEXT = "请选择提醒周期(单位:分钟):"; /** * 初始化模型的可选数组 */ public static final String[] MODEL_SELECT_ARRAY = new String[]{"CXK", "锦鲤杨超越", "奥利给", "超励志奥利给", "三點几了,飲茶先啦", "提醒摸魚小助手", "提醒努力工作小助手", "提醒喝水小助手"}; /** * 初始化时间的可选数组 */ public static final String[] TIME_SELECT_ARRAY = new String[]{"30", "60", "90", "120", "240", "360", "480"}; } /** * 停止窗口相关 */ public static class Stop { /** * title */ public static final String TITLE = "提示"; /** * 成功正文 */ public static final String SUCCESS_TEXT = "停止成功!"; /** * 失败正文 */ public static final String FAIL_TEXT = "停止失败!"; } /** * 提示窗相关 */ public enum AlertDialog { /** * CXK */ CXK("/icons/cxk_basketball.gif", "CXK提醒您", "工作{0}分钟辛苦了吧? 欣赏一段鸡你太美休息一下吧~~ !"), /** * 派大星 */ OLG1("/icons/olg1.jpg", "小助手提醒您", "今天也要加油噢~!"), /** * 巨魔 */ OLG2("/icons/olg2.jpg", "巨魔提醒您", "我们不论遇到什么困难,都要微笑着面对它。加油!奥利给!!"), /** * 杨超越 */ YCY("/icons/ycy.gif", "锦鲤祝您", "BUG退散!程序不崩!心想事成!"), /** * 3点饮茶 */ DRINK_TEA("/icons/drink_tea.jpg", "喂!朋友!", "三點几了,飲茶先啦!"), /** * 提醒喝水 */ DRINK_WATER("/icons/drink_water.jpg", "水宝提醒你", "多喝水不得肾结石哟!"), /** * 摸鱼 */ TOUCH_FISH("/icons/moyu.jpg", "摸鱼提醒小助手提醒您", "该摸鱼了!"), /** * 努力工作 */ WORK_HARD("/icons/workhard.jpg", "努力工作提醒小助手提醒您", "别摸了,该努力工作了!"); /** * 装载图片路径 */ String imagePath; /** * 标题文本 */ String title; /** * 提示语文本 */ String text; AlertDialog(String imagePath, String title, String text) { this.imagePath = imagePath; this.title = title; this.text = text; } public String getImagePath() { return imagePath; } public String getTitle() { return title; } public String getText() { return text; } } }
a1098832322/Rest-Assistant
src/constant/Constant.java
982
/** * 停止窗口相关 */
block_comment
zh-cn
package constant; /** * 常量池 * * @author 郑龙 * @date 2019/12/16 19:09 */ public class Constant { /** * 设置窗口相关 */ public static class Settings { /** * 设置窗口标题 */ public static final String SETTING_WINDOW_TITLE = "Assistant Setting"; /** * 窗体模型选择器提示文本 */ public static final String SETTING_MODEL_SELECTOR_TEXT = "请选择模型:"; /** * 窗体时间选择器提示文本 */ public static final String SETTING_TIME_SELECTOR_TEXT = "请选择提醒周期(单位:分钟):"; /** * 初始化模型的可选数组 */ public static final String[] MODEL_SELECT_ARRAY = new String[]{"CXK", "锦鲤杨超越", "奥利给", "超励志奥利给", "三點几了,飲茶先啦", "提醒摸魚小助手", "提醒努力工作小助手", "提醒喝水小助手"}; /** * 初始化时间的可选数组 */ public static final String[] TIME_SELECT_ARRAY = new String[]{"30", "60", "90", "120", "240", "360", "480"}; } /** * 停止窗 <SUF>*/ public static class Stop { /** * title */ public static final String TITLE = "提示"; /** * 成功正文 */ public static final String SUCCESS_TEXT = "停止成功!"; /** * 失败正文 */ public static final String FAIL_TEXT = "停止失败!"; } /** * 提示窗相关 */ public enum AlertDialog { /** * CXK */ CXK("/icons/cxk_basketball.gif", "CXK提醒您", "工作{0}分钟辛苦了吧? 欣赏一段鸡你太美休息一下吧~~ !"), /** * 派大星 */ OLG1("/icons/olg1.jpg", "小助手提醒您", "今天也要加油噢~!"), /** * 巨魔 */ OLG2("/icons/olg2.jpg", "巨魔提醒您", "我们不论遇到什么困难,都要微笑着面对它。加油!奥利给!!"), /** * 杨超越 */ YCY("/icons/ycy.gif", "锦鲤祝您", "BUG退散!程序不崩!心想事成!"), /** * 3点饮茶 */ DRINK_TEA("/icons/drink_tea.jpg", "喂!朋友!", "三點几了,飲茶先啦!"), /** * 提醒喝水 */ DRINK_WATER("/icons/drink_water.jpg", "水宝提醒你", "多喝水不得肾结石哟!"), /** * 摸鱼 */ TOUCH_FISH("/icons/moyu.jpg", "摸鱼提醒小助手提醒您", "该摸鱼了!"), /** * 努力工作 */ WORK_HARD("/icons/workhard.jpg", "努力工作提醒小助手提醒您", "别摸了,该努力工作了!"); /** * 装载图片路径 */ String imagePath; /** * 标题文本 */ String title; /** * 提示语文本 */ String text; AlertDialog(String imagePath, String title, String text) { this.imagePath = imagePath; this.title = title; this.text = text; } public String getImagePath() { return imagePath; } public String getTitle() { return title; } public String getText() { return text; } } }
false
849
12
982
9
936
11
982
9
1,351
18
false
false
false
false
false
true
16357_0
package com.example.androidxdemo.mianshi; import java.io.Serializable; /** * 1. 谈谈MVC、MVP和MVVM,好在哪里,不好在哪里? * MVP的含义: * Model:数据层,负责存储、检索、操纵数据。 * View:UI层,显示数据,并向Presenter报告用户行为。 * Presenter:作为View与Model交互的中间纽带,从Model拿数据,应用到UI层,管理UI的状态,响应用户的行为。 * * MVP相比于MVC的优势: * 分离了视图逻辑和业务逻辑,降低了耦合。 * Activity只处理生命周期的任务,代码变得更加简洁。 * 视图逻辑和业务逻辑分别抽象到了View和Presenter的接口中去,提高代码的可阅读性。 * Presenter被抽象成接口,可以有多种具体的实现,所以方便进行单元测试。 * 把业务逻辑抽到Presenter中去,避免后台线程引用着Activity导致Activity的资源无法被系统回收从而引起内存泄露和OOM。 * * MVVM的含义:与MVP类似,利用数据绑定(Data Binding)、依赖属性(Dependency Property)、命令(Command)、路由事件(Routed Event)等新特性,打造了一个更加灵活高效的架构。 * MVVM相比于MVP的优势:在常规的开发模式中,数据变化需要更新UI的时候,需要先获取UI控件的引用,然后再更新UI, * 获取用户的输入和操作也需要通过UI控件的引用,但在MVVM中,这些都是通过数据驱动来自动完成的,数据变化后会自 * 动更新UI,UI的改变也能自动反馈到数据层,数据成为主导因素。这样MVVM层在业务逻辑处理中只要关心数据,不需要 * 直接和UI打交道,在业务处理过程中简单方便很多。 */ public class DesignDetail { public static class Singleton implements Serializable { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } private Object readResolve() { return singleton; } } }
a1198375223/Demo
app/src/main/java/com/example/androidxdemo/mianshi/DesignDetail.java
587
/** * 1. 谈谈MVC、MVP和MVVM,好在哪里,不好在哪里? * MVP的含义: * Model:数据层,负责存储、检索、操纵数据。 * View:UI层,显示数据,并向Presenter报告用户行为。 * Presenter:作为View与Model交互的中间纽带,从Model拿数据,应用到UI层,管理UI的状态,响应用户的行为。 * * MVP相比于MVC的优势: * 分离了视图逻辑和业务逻辑,降低了耦合。 * Activity只处理生命周期的任务,代码变得更加简洁。 * 视图逻辑和业务逻辑分别抽象到了View和Presenter的接口中去,提高代码的可阅读性。 * Presenter被抽象成接口,可以有多种具体的实现,所以方便进行单元测试。 * 把业务逻辑抽到Presenter中去,避免后台线程引用着Activity导致Activity的资源无法被系统回收从而引起内存泄露和OOM。 * * MVVM的含义:与MVP类似,利用数据绑定(Data Binding)、依赖属性(Dependency Property)、命令(Command)、路由事件(Routed Event)等新特性,打造了一个更加灵活高效的架构。 * MVVM相比于MVP的优势:在常规的开发模式中,数据变化需要更新UI的时候,需要先获取UI控件的引用,然后再更新UI, * 获取用户的输入和操作也需要通过UI控件的引用,但在MVVM中,这些都是通过数据驱动来自动完成的,数据变化后会自 * 动更新UI,UI的改变也能自动反馈到数据层,数据成为主导因素。这样MVVM层在业务逻辑处理中只要关心数据,不需要 * 直接和UI打交道,在业务处理过程中简单方便很多。 */
block_comment
zh-cn
package com.example.androidxdemo.mianshi; import java.io.Serializable; /** * 1. <SUF>*/ public class DesignDetail { public static class Singleton implements Serializable { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } private Object readResolve() { return singleton; } } }
false
486
381
587
469
531
400
587
469
885
730
true
true
true
true
true
false