file_id
stringlengths 5
8
| content
stringlengths 131
14.4k
| repo
stringlengths 9
59
| path
stringlengths 8
120
| token_length
int64 53
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 40
3.27k
| comment-tokens-Qwen/Qwen2-7B
int64 2
459
| file-tokens-bigcode/starcoder2-7b
int64 53
3.49k
| comment-tokens-bigcode/starcoder2-7b
int64 3
483
| file-tokens-google/codegemma-7b
int64 49
3.61k
| comment-tokens-google/codegemma-7b
int64 3
465
| file-tokens-ibm-granite/granite-8b-code-base
int64 53
3.49k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 3
483
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 68
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 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 35