file_id
stringlengths 5
9
| content
stringlengths 128
32.8k
| repo
stringlengths 9
63
| path
stringlengths 8
125
| token_length
int64 36
8.14k
| original_comment
stringlengths 5
1.83k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 111
32.8k
| excluded
float64 0
1
⌀ |
---|---|---|---|---|---|---|---|---|---|
13526_3 | package com.forest.communityproperty.service;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class Forest_MailService {
@Resource
JavaMailSender javaMailSender;
/**
* 最简单的邮件发送
*
* @param from 发送方
* @param to 接收方
* @param cc 第三方(非必填)
* @param subject 标题
* @param content 内容
* @param name 姓名
*/
public void sendSimpleMail(String from, String to, String cc, String subject, String content, String name) throws Exception {
//调用函数
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//接收人的邮件账号
simpleMailMessage.setTo(to);
//
simpleMailMessage.setCc(cc);
//发送邮件的标题
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText("尊敬的:\n" +
name + "" +
"\t先生/女士\n" +
content +
"请你尽快到来!\n" +
"非常感谢你的合作!\n" +
"\n --业务人员:小王");
//邮件发送人
String nick = "FOREST";
simpleMailMessage.setFrom(nick + " <" + from + ">");
//调用spring boot的mail函数
javaMailSender.send(simpleMailMessage);
}
/**
* 代附件的邮件
*
* @param from
* @param to
* @param subject
* @param content
* @param file
*/
public void sendAttachFileMail(String from, String to, String subject, String content, File file) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(content);
mimeMessageHelper.addAttachment(file.getName(), file);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 带图片的邮件
*
* @param from
* @param to
* @param subject
* @param content
* @param srePAth
* @param resIds
*/
public void sendMailWithImg(String from, String to, String subject, String content, String[] srePAth, String[] resIds) {
if (srePAth.length != resIds.length) {
System.out.println("发送失败");
return;
}
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(content, true);
for (int i = 0; i < srePAth.length; i++) {
FileSystemResource res = new FileSystemResource(new File(srePAth[i]));
mimeMessageHelper.addInline(resIds[i], res);
}
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
* 使用thymeleaf模板
*
* @param from
* @param to
* @param subject
* @param context
*/
public void sendHtmlMail(String from, String to, String subject, String context) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setText(context);
mimeMessageHelper.setSubject(subject);
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
} | 1xiaowang1/Communityproperty | src/main/java/com/forest/communityproperty/service/Forest_MailService.java | 1,025 | //发送邮件的标题 | line_comment | zh-cn | package com.forest.communityproperty.service;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class Forest_MailService {
@Resource
JavaMailSender javaMailSender;
/**
* 最简单的邮件发送
*
* @param from 发送方
* @param to 接收方
* @param cc 第三方(非必填)
* @param subject 标题
* @param content 内容
* @param name 姓名
*/
public void sendSimpleMail(String from, String to, String cc, String subject, String content, String name) throws Exception {
//调用函数
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//接收人的邮件账号
simpleMailMessage.setTo(to);
//
simpleMailMessage.setCc(cc);
//发送 <SUF>
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText("尊敬的:\n" +
name + "" +
"\t先生/女士\n" +
content +
"请你尽快到来!\n" +
"非常感谢你的合作!\n" +
"\n --业务人员:小王");
//邮件发送人
String nick = "FOREST";
simpleMailMessage.setFrom(nick + " <" + from + ">");
//调用spring boot的mail函数
javaMailSender.send(simpleMailMessage);
}
/**
* 代附件的邮件
*
* @param from
* @param to
* @param subject
* @param content
* @param file
*/
public void sendAttachFileMail(String from, String to, String subject, String content, File file) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(content);
mimeMessageHelper.addAttachment(file.getName(), file);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 带图片的邮件
*
* @param from
* @param to
* @param subject
* @param content
* @param srePAth
* @param resIds
*/
public void sendMailWithImg(String from, String to, String subject, String content, String[] srePAth, String[] resIds) {
if (srePAth.length != resIds.length) {
System.out.println("发送失败");
return;
}
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(content, true);
for (int i = 0; i < srePAth.length; i++) {
FileSystemResource res = new FileSystemResource(new File(srePAth[i]));
mimeMessageHelper.addInline(resIds[i], res);
}
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
* 使用thymeleaf模板
*
* @param from
* @param to
* @param subject
* @param context
*/
public void sendHtmlMail(String from, String to, String subject, String context) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setText(context);
mimeMessageHelper.setSubject(subject);
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
} | 0 |
5042_11 | package io.github.xxyopen.novel.core.common.constant;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 错误码枚举类。
* <p>
* 错误码为字符串类型,共 5 位,分成两个部分:错误产生来源+四位数字编号。 错误产生来源分为 A/B/C, A 表示错误来源于用户,比如参数错误,用户安装版本过低,用户支付 超时等问题; B
* 表示错误来源于当前系统,往往是业务逻辑出错,或程序健壮性差等问题; C 表示错误来源 于第三方服务,比如 CDN 服务出错,消息投递超时等问题;四位数字编号从 0001 到 9999,大类之间的
* 步长间距预留 100。
* <p>
* 错误码分为一级宏观错误码、二级宏观错误码、三级宏观错误码。 在无法更加具体确定的错误场景中,可以直接使用一级宏观错误码。
*
* @author xiongxiaoyang
* @date 2022/5/11
*/
@Getter
@AllArgsConstructor
public enum ErrorCodeEnum {
/**
* 正确执行后的返回
*/
OK("00000", "一切 ok"),
/**
* 一级宏观错误码,用户端错误
*/
USER_ERROR("A0001", "用户端错误"),
/**
* 二级宏观错误码,用户注册错误
*/
USER_REGISTER_ERROR("A0100", "用户注册错误"),
/**
* 用户未同意隐私协议
*/
USER_NO_AGREE_PRIVATE_ERROR("A0101", "用户未同意隐私协议"),
/**
* 注册国家或地区受限
*/
USER_REGISTER_AREA_LIMIT_ERROR("A0102", "注册国家或地区受限"),
/**
* 用户验证码错误
*/
USER_VERIFY_CODE_ERROR("A0240", "用户验证码错误"),
/**
* 用户名已存在
*/
USER_NAME_EXIST("A0111", "用户名已存在"),
/**
* 用户账号不存在
*/
USER_ACCOUNT_NOT_EXIST("A0201", "用户账号不存在"),
/**
* 用户密码错误
*/
USER_PASSWORD_ERROR("A0210", "用户密码错误"),
/**
* 二级宏观错误码,用户请求参数错误
*/
USER_REQUEST_PARAM_ERROR("A0400", "用户请求参数错误"),
/**
* 用户登录已过期
*/
USER_LOGIN_EXPIRED("A0230", "用户登录已过期"),
/**
* 访问未授权
*/
USER_UN_AUTH("A0301", "访问未授权"),
/**
* 用户请求服务异常
*/
USER_REQ_EXCEPTION("A0500", "用户请求服务异常"),
/**
* 请求超出限制
*/
USER_REQ_MANY("A0501", "请求超出限制"),
/**
* 用户评论异常
*/
USER_COMMENT("A2000", "用户评论异常"),
/**
* 用户评论异常
*/
USER_COMMENTED("A2001", "用户已发表评论"),
/**
* 作家发布异常
*/
AUTHOR_PUBLISH("A3000", "作家发布异常"),
/**
* 小说名已存在
*/
AUTHOR_BOOK_NAME_EXIST("A3001", "小说名已存在"),
/**
* 用户上传文件异常
*/
USER_UPLOAD_FILE_ERROR("A0700", "用户上传文件异常"),
/**
* 用户上传文件类型不匹配
*/
USER_UPLOAD_FILE_TYPE_NOT_MATCH("A0701", "用户上传文件类型不匹配"),
/**
* 一级宏观错误码,系统执行出错
*/
SYSTEM_ERROR("B0001", "系统执行出错"),
/**
* 二级宏观错误码,系统执行超时
*/
SYSTEM_TIMEOUT_ERROR("B0100", "系统执行超时"),
/**
* 一级宏观错误码,调用第三方服务出错
*/
THIRD_SERVICE_ERROR("C0001", "调用第三方服务出错"),
/**
* 一级宏观错误码,中间件服务出错
*/
MIDDLEWARE_SERVICE_ERROR("C0100", "中间件服务出错");
/**
* 错误码
*/
private final String code;
/**
* 中文描述
*/
private final String message;
}
| 201206030/novel | src/main/java/io/github/xxyopen/novel/core/common/constant/ErrorCodeEnum.java | 1,122 | /**
* 用户登录已过期
*/ | block_comment | zh-cn | package io.github.xxyopen.novel.core.common.constant;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 错误码枚举类。
* <p>
* 错误码为字符串类型,共 5 位,分成两个部分:错误产生来源+四位数字编号。 错误产生来源分为 A/B/C, A 表示错误来源于用户,比如参数错误,用户安装版本过低,用户支付 超时等问题; B
* 表示错误来源于当前系统,往往是业务逻辑出错,或程序健壮性差等问题; C 表示错误来源 于第三方服务,比如 CDN 服务出错,消息投递超时等问题;四位数字编号从 0001 到 9999,大类之间的
* 步长间距预留 100。
* <p>
* 错误码分为一级宏观错误码、二级宏观错误码、三级宏观错误码。 在无法更加具体确定的错误场景中,可以直接使用一级宏观错误码。
*
* @author xiongxiaoyang
* @date 2022/5/11
*/
@Getter
@AllArgsConstructor
public enum ErrorCodeEnum {
/**
* 正确执行后的返回
*/
OK("00000", "一切 ok"),
/**
* 一级宏观错误码,用户端错误
*/
USER_ERROR("A0001", "用户端错误"),
/**
* 二级宏观错误码,用户注册错误
*/
USER_REGISTER_ERROR("A0100", "用户注册错误"),
/**
* 用户未同意隐私协议
*/
USER_NO_AGREE_PRIVATE_ERROR("A0101", "用户未同意隐私协议"),
/**
* 注册国家或地区受限
*/
USER_REGISTER_AREA_LIMIT_ERROR("A0102", "注册国家或地区受限"),
/**
* 用户验证码错误
*/
USER_VERIFY_CODE_ERROR("A0240", "用户验证码错误"),
/**
* 用户名已存在
*/
USER_NAME_EXIST("A0111", "用户名已存在"),
/**
* 用户账号不存在
*/
USER_ACCOUNT_NOT_EXIST("A0201", "用户账号不存在"),
/**
* 用户密码错误
*/
USER_PASSWORD_ERROR("A0210", "用户密码错误"),
/**
* 二级宏观错误码,用户请求参数错误
*/
USER_REQUEST_PARAM_ERROR("A0400", "用户请求参数错误"),
/**
* 用户登 <SUF>*/
USER_LOGIN_EXPIRED("A0230", "用户登录已过期"),
/**
* 访问未授权
*/
USER_UN_AUTH("A0301", "访问未授权"),
/**
* 用户请求服务异常
*/
USER_REQ_EXCEPTION("A0500", "用户请求服务异常"),
/**
* 请求超出限制
*/
USER_REQ_MANY("A0501", "请求超出限制"),
/**
* 用户评论异常
*/
USER_COMMENT("A2000", "用户评论异常"),
/**
* 用户评论异常
*/
USER_COMMENTED("A2001", "用户已发表评论"),
/**
* 作家发布异常
*/
AUTHOR_PUBLISH("A3000", "作家发布异常"),
/**
* 小说名已存在
*/
AUTHOR_BOOK_NAME_EXIST("A3001", "小说名已存在"),
/**
* 用户上传文件异常
*/
USER_UPLOAD_FILE_ERROR("A0700", "用户上传文件异常"),
/**
* 用户上传文件类型不匹配
*/
USER_UPLOAD_FILE_TYPE_NOT_MATCH("A0701", "用户上传文件类型不匹配"),
/**
* 一级宏观错误码,系统执行出错
*/
SYSTEM_ERROR("B0001", "系统执行出错"),
/**
* 二级宏观错误码,系统执行超时
*/
SYSTEM_TIMEOUT_ERROR("B0100", "系统执行超时"),
/**
* 一级宏观错误码,调用第三方服务出错
*/
THIRD_SERVICE_ERROR("C0001", "调用第三方服务出错"),
/**
* 一级宏观错误码,中间件服务出错
*/
MIDDLEWARE_SERVICE_ERROR("C0100", "中间件服务出错");
/**
* 错误码
*/
private final String code;
/**
* 中文描述
*/
private final String message;
}
| 0 |
57549_1 | package com.java2nb.novel.core.utils;
import java.util.Random;
/**
* 随机生成小说信息工具类
* @author Administrator
*/
public class RandomBookInfoUtil {
/**
* 根据评分获取访问人数
* */
public static Long getVisitCountByScore(Float score){
Long visitCount ;
if(score > 9){
visitCount = 100000 + new Random(100000).nextLong();
}else if(score > 8){
visitCount = 10000 + new Random(10000).nextLong();
}else if(score > 7){
visitCount = 1000 + new Random(1000).nextLong();
}else if(score > 6){
visitCount = 100 + new Random(100).nextLong();
}else{
visitCount = new Random(100).nextLong();
}
return visitCount;
}
/**
* 根据访问人数获取评分
* */
public static Float getScoreByVisitCount(Long visitCount){
Float score;
if(visitCount>100000) {
score = 8.9f;
}else if(visitCount>10000){
score = 8.0f+(visitCount/10000)*0.1f;
}else if(visitCount>1000){
score = 7.0f+(visitCount/1000)*0.1f;
}else if(visitCount>100){
score = 6.0f+(visitCount/100)*0.1f;
}else{
score = 6.0f;
}
return score;
}
/**
* 获取分类名
* */
public static String getCatNameById(Integer catId) {
String catName = "其他";
switch (catId) {
case 1: {
catName = "玄幻奇幻";
break;
}
case 2: {
catName = "武侠仙侠";
break;
}
case 3: {
catName = "都市言情";
break;
}
case 4: {
catName = "历史军事";
break;
}
case 5: {
catName = "科幻灵异";
break;
}
case 6: {
catName = "网游竞技";
break;
}
case 7: {
catName = "女生频道";
break;
}
case 8: {
catName = "轻小说";
break;
}
case 9: {
catName = "漫画";
break;
}
default: {
break;
}
}
return catName;
}
}
| 201206030/novel-plus | novel-common/src/main/java/com/java2nb/novel/core/utils/RandomBookInfoUtil.java | 673 | /**
* 根据评分获取访问人数
* */ | block_comment | zh-cn | package com.java2nb.novel.core.utils;
import java.util.Random;
/**
* 随机生成小说信息工具类
* @author Administrator
*/
public class RandomBookInfoUtil {
/**
* 根据评 <SUF>*/
public static Long getVisitCountByScore(Float score){
Long visitCount ;
if(score > 9){
visitCount = 100000 + new Random(100000).nextLong();
}else if(score > 8){
visitCount = 10000 + new Random(10000).nextLong();
}else if(score > 7){
visitCount = 1000 + new Random(1000).nextLong();
}else if(score > 6){
visitCount = 100 + new Random(100).nextLong();
}else{
visitCount = new Random(100).nextLong();
}
return visitCount;
}
/**
* 根据访问人数获取评分
* */
public static Float getScoreByVisitCount(Long visitCount){
Float score;
if(visitCount>100000) {
score = 8.9f;
}else if(visitCount>10000){
score = 8.0f+(visitCount/10000)*0.1f;
}else if(visitCount>1000){
score = 7.0f+(visitCount/1000)*0.1f;
}else if(visitCount>100){
score = 6.0f+(visitCount/100)*0.1f;
}else{
score = 6.0f;
}
return score;
}
/**
* 获取分类名
* */
public static String getCatNameById(Integer catId) {
String catName = "其他";
switch (catId) {
case 1: {
catName = "玄幻奇幻";
break;
}
case 2: {
catName = "武侠仙侠";
break;
}
case 3: {
catName = "都市言情";
break;
}
case 4: {
catName = "历史军事";
break;
}
case 5: {
catName = "科幻灵异";
break;
}
case 6: {
catName = "网游竞技";
break;
}
case 7: {
catName = "女生频道";
break;
}
case 8: {
catName = "轻小说";
break;
}
case 9: {
catName = "漫画";
break;
}
default: {
break;
}
}
return catName;
}
}
| 0 |
48954_2 | package com.itheima.mp.domain.po;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.itheima.mp.enums.Gender;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
// 基本信息:包括学生姓名、学生学号、性别、出生日期、民族、籍贯等个人身份信息。
// name, student ID, gender, date of birth, ethnicity, birthplace
/*
基本信息:包括学生姓名、学生学号、性别、出生日期、民族、籍贯等个人身份信息。
联系信息:包括学生家庭住址、家庭电话、父母或监护人信息、学生本人联系电话、电子邮箱等。
学籍信息:包括学生所在班级、所在年级、学生当前状态(如在读、休学、退学等)等信息。
奖惩记录:包括学生荣誉奖项、学术竞赛成绩、违纪记录等。
学习成绩:包括学生各科目的考试成绩、平均分、排名等。
课外活动:包括学生参与的社团、俱乐部、义工活动、实习经历等。
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "student_basic")
public class StudentBasic {
@TableId(type = IdType.AUTO, value = "student_basic_id")
private Integer student_basic_id;
@ApiModelProperty("性别")
@EnumValue
private Gender gender;
@ApiModelProperty("生日")
private LocalDate birthday;
@ApiModelProperty("民族")
private String ethnicity;
@ApiModelProperty("籍贯")
private String birthplace;
@ApiModelProperty("住址")
private String address;
@ApiModelProperty("电话")
private String phone;
@ApiModelProperty("邮箱")
private String email;
}
| 202200300287/mp-demo | src/main/java/com/itheima/mp/domain/po/StudentBasic.java | 510 | /*
基本信息:包括学生姓名、学生学号、性别、出生日期、民族、籍贯等个人身份信息。
联系信息:包括学生家庭住址、家庭电话、父母或监护人信息、学生本人联系电话、电子邮箱等。
学籍信息:包括学生所在班级、所在年级、学生当前状态(如在读、休学、退学等)等信息。
奖惩记录:包括学生荣誉奖项、学术竞赛成绩、违纪记录等。
学习成绩:包括学生各科目的考试成绩、平均分、排名等。
课外活动:包括学生参与的社团、俱乐部、义工活动、实习经历等。
*/ | block_comment | zh-cn | package com.itheima.mp.domain.po;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.itheima.mp.enums.Gender;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
// 基本信息:包括学生姓名、学生学号、性别、出生日期、民族、籍贯等个人身份信息。
// name, student ID, gender, date of birth, ethnicity, birthplace
/*
基本信 <SUF>*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "student_basic")
public class StudentBasic {
@TableId(type = IdType.AUTO, value = "student_basic_id")
private Integer student_basic_id;
@ApiModelProperty("性别")
@EnumValue
private Gender gender;
@ApiModelProperty("生日")
private LocalDate birthday;
@ApiModelProperty("民族")
private String ethnicity;
@ApiModelProperty("籍贯")
private String birthplace;
@ApiModelProperty("住址")
private String address;
@ApiModelProperty("电话")
private String phone;
@ApiModelProperty("邮箱")
private String email;
}
| 1 |
21154_0 | package com.team.decorator;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.mysql.fabric.xmlrpc.base.Array;
public class Sale {
@Before
public void setUp() throws Exception {
}
@Test
public void test() {
//来一块牛肉汉堡
Humburger beef = new HumburgerBeef(2);
System.out.println(beef.getName()+" 售价:"+beef.getPrice());
//老板,牛肉汗煲加火腿,谢谢!^_^
Condiment ham = new CondimentHam(new HumburgerBeef(2));
System.out.println(ham.getName()+" 售价:"+ham.getPrice());
//鸡腿堡一个,打包
Humburger chicken = new HumburgerChicken();
System.out.println(chicken.getName()+" 售价:"+chicken.getPrice());
//再加点芝士吧
Condiment cheese = new CondimentCheese(chicken);
System.out.println(cheese.getName()+" 售价:"+cheese.getPrice());
Dressing chilli = new DressingChilli(ham);
System.out.println(chilli.getName()+" 售价:"+chilli.getPrice());
}
@Test
public void test1() {
List<Integer> list = new ArrayList<Integer>();
int i = 0;
while(true){
list.add(i++);
}
}
}
| 20gg/weChat | src/main/java/com/team/Decorator/Sale.java | 424 | //来一块牛肉汉堡 | line_comment | zh-cn | package com.team.decorator;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.mysql.fabric.xmlrpc.base.Array;
public class Sale {
@Before
public void setUp() throws Exception {
}
@Test
public void test() {
//来一 <SUF>
Humburger beef = new HumburgerBeef(2);
System.out.println(beef.getName()+" 售价:"+beef.getPrice());
//老板,牛肉汗煲加火腿,谢谢!^_^
Condiment ham = new CondimentHam(new HumburgerBeef(2));
System.out.println(ham.getName()+" 售价:"+ham.getPrice());
//鸡腿堡一个,打包
Humburger chicken = new HumburgerChicken();
System.out.println(chicken.getName()+" 售价:"+chicken.getPrice());
//再加点芝士吧
Condiment cheese = new CondimentCheese(chicken);
System.out.println(cheese.getName()+" 售价:"+cheese.getPrice());
Dressing chilli = new DressingChilli(ham);
System.out.println(chilli.getName()+" 售价:"+chilli.getPrice());
}
@Test
public void test1() {
List<Integer> list = new ArrayList<Integer>();
int i = 0;
while(true){
list.add(i++);
}
}
}
| 0 |
26399_9 | package edu.xcdq;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author xujinwei
* @date 2021/3/25 10:34
*/
public class demo08 {
public static void main(String[] args) {
//插入新数组 保持原数组有序
int [] scores = new int[7];
scores[0] = 99;
scores[1] = 88;
scores[2] = 77;
scores[3] = 66;
scores[4] = 55;
scores[5] = 44;
//获取要插入的值
System.out.println("请输入插入的值");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
//2 找到插入新值的位置
int index = 0;
for (int i = 0; i < scores.length; i++) {
if(num > scores[i]){ //找到数组中第一个比num小的值,该位置是num要插入的位置
index = i; //把位置记录在index中
break;
}
}
//3 把元素向后移动 index length-1 之间全部数据向后移动一位
for(int i = scores.length -1; i>index;i--){
System.out.println("把" + (i-1) +"位置的元素" + scores[i-1]+"移动到" +i +"位置"+scores[i]);
scores[i] = scores[i-1];
System.out.println(Arrays.toString(scores));
}
//4 插入新值
System.out.println("在" + index + "位置 " + scores[index] + "插入新值" + num);
scores[index] = num;
//5 打印插入后的结果
//降序
System.out.println("插入后结果为:降序");
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i] + "\t");
}
System.out.println();
System.out.println("升序:");
for(int i = scores.length-1; i>=0;i--){
System.out.println(scores[i] + "\t");
}
}
}
| 2116055490/-note56 | demo08.java | 557 | //降序
| line_comment | zh-cn | package edu.xcdq;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author xujinwei
* @date 2021/3/25 10:34
*/
public class demo08 {
public static void main(String[] args) {
//插入新数组 保持原数组有序
int [] scores = new int[7];
scores[0] = 99;
scores[1] = 88;
scores[2] = 77;
scores[3] = 66;
scores[4] = 55;
scores[5] = 44;
//获取要插入的值
System.out.println("请输入插入的值");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
//2 找到插入新值的位置
int index = 0;
for (int i = 0; i < scores.length; i++) {
if(num > scores[i]){ //找到数组中第一个比num小的值,该位置是num要插入的位置
index = i; //把位置记录在index中
break;
}
}
//3 把元素向后移动 index length-1 之间全部数据向后移动一位
for(int i = scores.length -1; i>index;i--){
System.out.println("把" + (i-1) +"位置的元素" + scores[i-1]+"移动到" +i +"位置"+scores[i]);
scores[i] = scores[i-1];
System.out.println(Arrays.toString(scores));
}
//4 插入新值
System.out.println("在" + index + "位置 " + scores[index] + "插入新值" + num);
scores[index] = num;
//5 打印插入后的结果
//降序 <SUF>
System.out.println("插入后结果为:降序");
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i] + "\t");
}
System.out.println();
System.out.println("升序:");
for(int i = scores.length-1; i>=0;i--){
System.out.println(scores[i] + "\t");
}
}
}
| 1 |
52164_14 | package com.echinacoop.lightos.web.rest.util;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EMailTool {
private EMailTool(){
init();
}
private static final class EMailToolClass {
private static EMailTool mail = new EMailTool();
}
public static EMailTool getInstance(){
return EMailToolClass.mail;
}
private Session session = null;
// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
// PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
// 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
private static String myEmailAccount = "1111111@qq.com";//"admin@yinsin.net";
private static String myEmailPassword = "1111111";//
// 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
// 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
private static String myEmailSMTPHost = "smtp.qq.com";//"smtp.qq.com";
public void init(){
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
// PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
// 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
// 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
final String smtpPort = "465";
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
session = Session.getDefaultInstance(props);
//session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
}
/**
* 创建一封只包含文本的简单邮件
*
* @param session 和服务器交互的会话
* @param sendMail 发件人邮箱
* @param receiveMail 收件人邮箱
* @return
* @throws Exception
*/
public MimeMessage createMimeMessage(Session session, String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList) throws Exception {
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(myEmailAccount, sendName, "UTF-8"));
// 3. To: 收件人
Map<String, String> user = null;
if(null != toUserList && !toUserList.isEmpty()){
int size = toUserList.size();
InternetAddress[] address = new InternetAddress[size];
for (int i = 0; i < size; i++) {
user = toUserList.get(i);
address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8");
}
message.setRecipients(MimeMessage.RecipientType.TO, address);
}
// To: 抄送给
if(null != ccUserList && !ccUserList.isEmpty()){
int size = ccUserList.size();
InternetAddress[] address = new InternetAddress[size];
for (int i = 0; i < size; i++) {
user = ccUserList.get(i);
address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8");
}
message.setRecipients(MimeMessage.RecipientType.CC, address);
}
// To: 密送给
if(null != bccUserList && !bccUserList.isEmpty()){
int size = bccUserList.size();
InternetAddress[] address = new InternetAddress[size];
for (int i = 0; i < size; i++) {
user = bccUserList.get(i);
address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8");
}
message.setRecipients(MimeMessage.RecipientType.BCC, address);
}
// 4. Subject: 邮件主题
message.setSubject(subject, "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
message.setContent(content, "text/html;charset=UTF-8");
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}
/**
* 发送邮件
* @param subject 主题
* @param content 内容
* @param toUserList 接收者
* @param ccUserList 抄送给
* @param bccUserList 暗抄给
*/
public void sendEMail(String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList){
try {
MimeMessage message = createMimeMessage(session, sendName, subject, content, toUserList, ccUserList, bccUserList);
// 4. 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
// 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
//
// PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
// 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
// 类型到对应邮件服务器的帮助网站上查看具体失败原因。
//
// PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
// (1) 邮箱没有开启 SMTP 服务;
// (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
// (3) 邮箱服务器要求必须要使用 SSL 安全连接;
// (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
// (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
//
// PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
transport.connect(myEmailAccount, myEmailPassword);
// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 214175590/lightos | src/main/java/com/echinacoop/lightos/web/rest/util/EMailTool.java | 2,028 | // 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。 | line_comment | zh-cn | package com.echinacoop.lightos.web.rest.util;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EMailTool {
private EMailTool(){
init();
}
private static final class EMailToolClass {
private static EMailTool mail = new EMailTool();
}
public static EMailTool getInstance(){
return EMailToolClass.mail;
}
private Session session = null;
// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
// PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
// 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
private static String myEmailAccount = "1111111@qq.com";//"admin@yinsin.net";
private static String myEmailPassword = "1111111";//
// 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
// 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
private static String myEmailSMTPHost = "smtp.qq.com";//"smtp.qq.com";
public void init(){
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
// PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
// 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
// 打开 <SUF>
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
final String smtpPort = "465";
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
session = Session.getDefaultInstance(props);
//session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
}
/**
* 创建一封只包含文本的简单邮件
*
* @param session 和服务器交互的会话
* @param sendMail 发件人邮箱
* @param receiveMail 收件人邮箱
* @return
* @throws Exception
*/
public MimeMessage createMimeMessage(Session session, String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList) throws Exception {
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(myEmailAccount, sendName, "UTF-8"));
// 3. To: 收件人
Map<String, String> user = null;
if(null != toUserList && !toUserList.isEmpty()){
int size = toUserList.size();
InternetAddress[] address = new InternetAddress[size];
for (int i = 0; i < size; i++) {
user = toUserList.get(i);
address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8");
}
message.setRecipients(MimeMessage.RecipientType.TO, address);
}
// To: 抄送给
if(null != ccUserList && !ccUserList.isEmpty()){
int size = ccUserList.size();
InternetAddress[] address = new InternetAddress[size];
for (int i = 0; i < size; i++) {
user = ccUserList.get(i);
address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8");
}
message.setRecipients(MimeMessage.RecipientType.CC, address);
}
// To: 密送给
if(null != bccUserList && !bccUserList.isEmpty()){
int size = bccUserList.size();
InternetAddress[] address = new InternetAddress[size];
for (int i = 0; i < size; i++) {
user = bccUserList.get(i);
address[i] = new InternetAddress(user.get("email"), user.get("name"), "UTF-8");
}
message.setRecipients(MimeMessage.RecipientType.BCC, address);
}
// 4. Subject: 邮件主题
message.setSubject(subject, "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
message.setContent(content, "text/html;charset=UTF-8");
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}
/**
* 发送邮件
* @param subject 主题
* @param content 内容
* @param toUserList 接收者
* @param ccUserList 抄送给
* @param bccUserList 暗抄给
*/
public void sendEMail(String sendName, String subject, String content, List<Map<String, String>> toUserList, List<Map<String, String>> ccUserList, List<Map<String, String>> bccUserList){
try {
MimeMessage message = createMimeMessage(session, sendName, subject, content, toUserList, ccUserList, bccUserList);
// 4. 根据 Session 获取邮件传输对象
Transport transport = session.getTransport();
// 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
//
// PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
// 仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
// 类型到对应邮件服务器的帮助网站上查看具体失败原因。
//
// PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
// (1) 邮箱没有开启 SMTP 服务;
// (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
// (3) 邮箱服务器要求必须要使用 SSL 安全连接;
// (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
// (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
//
// PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
transport.connect(myEmailAccount, myEmailPassword);
// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 0 |
5558_2 | package com.gpmall.commons.lock.impl.zk;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
/**
* Description: 分布式锁---后台线程
* 用来删除无效节点
* 目录如下
* gpcommons_lock/
* --AAA
* -- orderId:001
* --临时节点 (锁释放后删除)
* --临时节点 (锁释放后删除)
* -- orderId:002
* -- orderId:003
* -- orderId:004
* -- orderId:005
* --BBB
* --CCC
* 上面 gpcommons_lock 为根目录,AAA,BBB代表具体的项目名,锁释放后,AAA下面的 orderId:001 等目录 不会被删除
* 随着时间的推移会造成 大量的 冗余目录堆积。 怕说不明白,小伙伴们可以自行实验一下
* @date 2019年8月12日
* @author msl 1015952139
*/
public class LockBackGroundThread extends Thread{
private Logger logger = LoggerFactory.getLogger(getClass());
CuratorFramework client;
protected LockBackGroundThread(CuratorFramework client){
this.client = client;
this.setDaemon(true);
this.setName("ZkMutexDistributedLock---background");
}
@Override
public synchronized void run() {
super.run();
try {
while (true){
//TODO 后期可以通过配置中心 配置
LockBackGroundConf conf = new LockBackGroundConf();
deleteInvalidNode(conf);
// 默认一小时执行一次(配置中心可配)
Thread.currentThread().wait(conf.getFrequency()*1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void deleteInvalidNode(LockBackGroundConf conf) throws Exception{
String projectDir = ZkMutexDistributedLockFactory.lockPath + ZkMutexDistributedLockFactory.projectName;
Stat exitDir = client.checkExists().forPath(projectDir);
if(exitDir == null){
logger.error("根目录尚未创建,本次清理结束--" + projectDir);
return;
}
List<String> paths = client.getChildren().forPath(projectDir);
Date date = new Date();
paths.forEach(currPath -> {
try{
Stat stat = new Stat();
// 默认删除一天前无效的数据。 子节点为0,说明当前节点无效
if(stat.getMtime()<(date.getTime() - (conf.getBeforeTime()*1000)) && stat.getNumChildren() == 0){
// 只删除空目录
client.delete().forPath(projectDir + currPath);
logger.info("删除路径: " + projectDir + currPath);
}
}catch (Exception e){
logger.error("删除节点失败: ", e);
}
});
}
}
| 2227324689/gpmall | gpmall-commons/commons-lock/src/main/java/com/gpmall/commons/lock/impl/zk/LockBackGroundThread.java | 753 | // 默认一小时执行一次(配置中心可配) | line_comment | zh-cn | package com.gpmall.commons.lock.impl.zk;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;
/**
* Description: 分布式锁---后台线程
* 用来删除无效节点
* 目录如下
* gpcommons_lock/
* --AAA
* -- orderId:001
* --临时节点 (锁释放后删除)
* --临时节点 (锁释放后删除)
* -- orderId:002
* -- orderId:003
* -- orderId:004
* -- orderId:005
* --BBB
* --CCC
* 上面 gpcommons_lock 为根目录,AAA,BBB代表具体的项目名,锁释放后,AAA下面的 orderId:001 等目录 不会被删除
* 随着时间的推移会造成 大量的 冗余目录堆积。 怕说不明白,小伙伴们可以自行实验一下
* @date 2019年8月12日
* @author msl 1015952139
*/
public class LockBackGroundThread extends Thread{
private Logger logger = LoggerFactory.getLogger(getClass());
CuratorFramework client;
protected LockBackGroundThread(CuratorFramework client){
this.client = client;
this.setDaemon(true);
this.setName("ZkMutexDistributedLock---background");
}
@Override
public synchronized void run() {
super.run();
try {
while (true){
//TODO 后期可以通过配置中心 配置
LockBackGroundConf conf = new LockBackGroundConf();
deleteInvalidNode(conf);
// 默认 <SUF>
Thread.currentThread().wait(conf.getFrequency()*1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void deleteInvalidNode(LockBackGroundConf conf) throws Exception{
String projectDir = ZkMutexDistributedLockFactory.lockPath + ZkMutexDistributedLockFactory.projectName;
Stat exitDir = client.checkExists().forPath(projectDir);
if(exitDir == null){
logger.error("根目录尚未创建,本次清理结束--" + projectDir);
return;
}
List<String> paths = client.getChildren().forPath(projectDir);
Date date = new Date();
paths.forEach(currPath -> {
try{
Stat stat = new Stat();
// 默认删除一天前无效的数据。 子节点为0,说明当前节点无效
if(stat.getMtime()<(date.getTime() - (conf.getBeforeTime()*1000)) && stat.getNumChildren() == 0){
// 只删除空目录
client.delete().forPath(projectDir + currPath);
logger.info("删除路径: " + projectDir + currPath);
}
}catch (Exception e){
logger.error("删除节点失败: ", e);
}
});
}
}
| 0 |
11362_1 | package arraySkills;
/**
* @Author ws
* @Date 2021/5/10 21:32
* @Version 1.0
*/
public class LongestLessSumSubArrayLength {
/**
* 假设答案法+淘汰可能性(很难,以后还会见到)
*
* 给定一个整数组成的无序数组arr,值可能正、可能负、可能0
* 给定一个整数值K
* 找到arr的所有子数组里,哪个子数组的累加和<=K,并且是长度最大的
* 返回其长度
*/
// O(N)
public static int maxLengthAwesome(int[] arr, int k) {
if (arr == null || arr.length == 0) {
return 0;
}
// 记录以该下标向右累加和的最小值
int[] minSums = new int[arr.length];
// 最小值的最右边界
int[] minSumEnds = new int[arr.length];
// 最后一个下标的数的值是固定的
minSums[arr.length - 1] = arr[arr.length - 1];
minSumEnds[arr.length - 1] = arr.length - 1;
// 依次赋值两个数组
for (int i = arr.length - 2; i >= 0; i--) {
if (minSums[i + 1] < 0) {
minSums[i] = arr[i] + minSums[i + 1];
minSumEnds[i] = minSumEnds[i + 1];
} else {
minSums[i] = arr[i];
minSumEnds[i] = i;
}
}
int end = 0;
int sum = 0;
int res = 0;
// i是窗口的最左的位置,end扩出来的最右有效块儿的最后一个位置的,再下一个位置
// end也是下一块儿的开始位置
// 窗口:[i~end)
for (int i = 0; i < arr.length; i++) {
// while循环结束之后:
// 1) 如果以i开头的情况下,累加和<=k的最长子数组是arr[i..end-1],看看这个子数组长度能不能更新res;
// 2) 如果以i开头的情况下,累加和<=k的最长子数组比arr[i..end-1]短,更新还是不更新res都不会影响最终结果;
while (end < arr.length && sum + minSums[end] <= k) {
sum += minSums[end];
end = minSumEnds[end] + 1;
}
res = Math.max(res, end - i);
if (end > i) { // 窗口内还有数 [i~end) [4,4)
sum -= arr[i];
} else { // 窗口内已经没有数了,说明从i开头的所有子数组累加和都不可能<=k
end = i + 1;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 5, 4, -7, 0, 5, 0, -2, 6, 2};
int i = maxLengthAwesome(arr, 8);
System.out.println(i);
}
}
| 2276089666/DataStructuresAndAlgorithms | algorithms/arraySkills/LongestLessSumSubArrayLength.java | 820 | /**
* 假设答案法+淘汰可能性(很难,以后还会见到)
*
* 给定一个整数组成的无序数组arr,值可能正、可能负、可能0
* 给定一个整数值K
* 找到arr的所有子数组里,哪个子数组的累加和<=K,并且是长度最大的
* 返回其长度
*/ | block_comment | zh-cn | package arraySkills;
/**
* @Author ws
* @Date 2021/5/10 21:32
* @Version 1.0
*/
public class LongestLessSumSubArrayLength {
/**
* 假设答 <SUF>*/
// O(N)
public static int maxLengthAwesome(int[] arr, int k) {
if (arr == null || arr.length == 0) {
return 0;
}
// 记录以该下标向右累加和的最小值
int[] minSums = new int[arr.length];
// 最小值的最右边界
int[] minSumEnds = new int[arr.length];
// 最后一个下标的数的值是固定的
minSums[arr.length - 1] = arr[arr.length - 1];
minSumEnds[arr.length - 1] = arr.length - 1;
// 依次赋值两个数组
for (int i = arr.length - 2; i >= 0; i--) {
if (minSums[i + 1] < 0) {
minSums[i] = arr[i] + minSums[i + 1];
minSumEnds[i] = minSumEnds[i + 1];
} else {
minSums[i] = arr[i];
minSumEnds[i] = i;
}
}
int end = 0;
int sum = 0;
int res = 0;
// i是窗口的最左的位置,end扩出来的最右有效块儿的最后一个位置的,再下一个位置
// end也是下一块儿的开始位置
// 窗口:[i~end)
for (int i = 0; i < arr.length; i++) {
// while循环结束之后:
// 1) 如果以i开头的情况下,累加和<=k的最长子数组是arr[i..end-1],看看这个子数组长度能不能更新res;
// 2) 如果以i开头的情况下,累加和<=k的最长子数组比arr[i..end-1]短,更新还是不更新res都不会影响最终结果;
while (end < arr.length && sum + minSums[end] <= k) {
sum += minSums[end];
end = minSumEnds[end] + 1;
}
res = Math.max(res, end - i);
if (end > i) { // 窗口内还有数 [i~end) [4,4)
sum -= arr[i];
} else { // 窗口内已经没有数了,说明从i开头的所有子数组累加和都不可能<=k
end = i + 1;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 5, 4, -7, 0, 5, 0, -2, 6, 2};
int i = maxLengthAwesome(arr, 8);
System.out.println(i);
}
}
| 1 |
48088_0 | package com.autumn;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.autumn.util.ToastUtil;
public class DialogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
Button btnDialog1 = findViewById(R.id.btn_dialog1);
Button btnDialog2 = findViewById(R.id.btn_dialog2);
Button btnDialog3 = findViewById(R.id.btn_dialog3);
Button btnDialog4 = findViewById(R.id.btn_dialog4);
Button btnDialog5 = findViewById(R.id.btn_dialog5);
OnClick onClick = new OnClick();
btnDialog1.setOnClickListener(onClick);
btnDialog2.setOnClickListener(onClick);
btnDialog3.setOnClickListener(onClick);
btnDialog4.setOnClickListener(onClick);
btnDialog5.setOnClickListener(onClick);
}
class OnClick implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_dialog1:
//分别是积极的按钮,中性的按钮和消极的按钮
AlertDialog.Builder builder = new AlertDialog.Builder(DialogActivity.this);
builder.setTitle("请回答:").setMessage("你对Android感兴趣吗?").setIcon(R.drawable.icon_user).setPositiveButton("感兴趣", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,"你很诚实!");
}
}).setNeutralButton("还行", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,"真的吗?");
}
}).setNegativeButton("不喜欢", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,"你再想想!");
}
}).show();
break;
case R.id.btn_dialog2:
final String[] array = new String[]{"男","女"};
AlertDialog.Builder builder1 = new AlertDialog.Builder(DialogActivity.this);
builder1.setTitle("请选择性别:").setItems(array, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,array[which]);
}
}).show();
break;
case R.id.btn_dialog3:
final String[] array2 = new String[]{"男","女"};
AlertDialog.Builder builder2 = new AlertDialog.Builder(DialogActivity.this);
//默认选中"女",类似RadioButton样式
builder2.setTitle("请选择性别:").setSingleChoiceItems(array2,1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,array2[which]);
dialog.dismiss();
}
}).setCancelable(false).show();
break;
case R.id.btn_dialog4:
//类似Checkbox的样式
final String[] array3 = new String[]{"吃饭","睡觉","写代码"};
final boolean[] isSelected = new boolean[]{false,false,true};
AlertDialog.Builder builder3 = new AlertDialog.Builder(DialogActivity.this);
builder3.setTitle("请选择日常活动:").setMultiChoiceItems(array3, isSelected, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
ToastUtil.showMsg(DialogActivity.this,array3[which]+":"+isChecked);
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
break;
case R.id.btn_dialog5:
//自定义View样式
AlertDialog.Builder builder4 = new AlertDialog.Builder(DialogActivity.this);
LayoutInflater inflater = LayoutInflater.from(DialogActivity.this);
View loginView = inflater.inflate(R.layout.layout_dialog,null);
EditText etUsername = loginView.findViewById(R.id.et_username);
EditText etPassword = loginView.findViewById(R.id.et_password);
Button btnLogin = loginView.findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
builder4.setTitle("请先登录:").setView(loginView);
builder4.show();
break;
}
}
}
}
| 229394/AndroidBasic | app/src/main/java/com/autumn/DialogActivity.java | 1,172 | //分别是积极的按钮,中性的按钮和消极的按钮 | line_comment | zh-cn | package com.autumn;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.autumn.util.ToastUtil;
public class DialogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
Button btnDialog1 = findViewById(R.id.btn_dialog1);
Button btnDialog2 = findViewById(R.id.btn_dialog2);
Button btnDialog3 = findViewById(R.id.btn_dialog3);
Button btnDialog4 = findViewById(R.id.btn_dialog4);
Button btnDialog5 = findViewById(R.id.btn_dialog5);
OnClick onClick = new OnClick();
btnDialog1.setOnClickListener(onClick);
btnDialog2.setOnClickListener(onClick);
btnDialog3.setOnClickListener(onClick);
btnDialog4.setOnClickListener(onClick);
btnDialog5.setOnClickListener(onClick);
}
class OnClick implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_dialog1:
//分别 <SUF>
AlertDialog.Builder builder = new AlertDialog.Builder(DialogActivity.this);
builder.setTitle("请回答:").setMessage("你对Android感兴趣吗?").setIcon(R.drawable.icon_user).setPositiveButton("感兴趣", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,"你很诚实!");
}
}).setNeutralButton("还行", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,"真的吗?");
}
}).setNegativeButton("不喜欢", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,"你再想想!");
}
}).show();
break;
case R.id.btn_dialog2:
final String[] array = new String[]{"男","女"};
AlertDialog.Builder builder1 = new AlertDialog.Builder(DialogActivity.this);
builder1.setTitle("请选择性别:").setItems(array, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,array[which]);
}
}).show();
break;
case R.id.btn_dialog3:
final String[] array2 = new String[]{"男","女"};
AlertDialog.Builder builder2 = new AlertDialog.Builder(DialogActivity.this);
//默认选中"女",类似RadioButton样式
builder2.setTitle("请选择性别:").setSingleChoiceItems(array2,1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ToastUtil.showMsg(DialogActivity.this,array2[which]);
dialog.dismiss();
}
}).setCancelable(false).show();
break;
case R.id.btn_dialog4:
//类似Checkbox的样式
final String[] array3 = new String[]{"吃饭","睡觉","写代码"};
final boolean[] isSelected = new boolean[]{false,false,true};
AlertDialog.Builder builder3 = new AlertDialog.Builder(DialogActivity.this);
builder3.setTitle("请选择日常活动:").setMultiChoiceItems(array3, isSelected, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
ToastUtil.showMsg(DialogActivity.this,array3[which]+":"+isChecked);
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
break;
case R.id.btn_dialog5:
//自定义View样式
AlertDialog.Builder builder4 = new AlertDialog.Builder(DialogActivity.this);
LayoutInflater inflater = LayoutInflater.from(DialogActivity.this);
View loginView = inflater.inflate(R.layout.layout_dialog,null);
EditText etUsername = loginView.findViewById(R.id.et_username);
EditText etPassword = loginView.findViewById(R.id.et_password);
Button btnLogin = loginView.findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
builder4.setTitle("请先登录:").setView(loginView);
builder4.show();
break;
}
}
}
}
| 0 |
65985_7 | package stone;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author lichengpeng
* @desc 词法分析器
* @date 2020/7/11
**/
public class Lexer {
// pattern = 空白 + (注释 or 字符串 or 标识符)
// 标识符 = (变量 or 逻辑运算符 or 比较运算符 or 标点符号)
public static String regexPat = "\\s*((//.*)|" + "([0-9]+)|" + "(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|" + "([A-Z_a-z][A-Z_a-z0-9]*)|" +
"<=|>=|==|&&|\\|\\||\\p{Punct})?";
private Pattern pattern = Pattern.compile(regexPat);
private ArrayList<Token> queue = new ArrayList<Token>();
private boolean hashMore;
private LineNumberReader reader;
public Lexer(Reader r) {
hashMore = true;
reader = new LineNumberReader(r);
}
// 读取下一个token,并从队列中删除
public Token read() throws ParseException {
if(fillQueue(0)) {
return queue.remove(0);
}else {
return Token.EOF;
}
}
// 读取第i个token
public Token peek(int i) throws ParseException {
if(fillQueue(i)) {
return queue.get(i);
}else {
return Token.EOF;
}
}
// 填充token队列
private boolean fillQueue(int i) throws ParseException {
while(i >= queue.size()) {
if(hashMore) {
readLine();
}else {
return false;
}
}
return true;
}
// 读取一行
protected void readLine() throws ParseException{
String line;
try {
line = reader.readLine();
}catch(IOException e) {
throw new ParseException(e);
}
if(line == null) {
hashMore = false;
return;
}
int lineNo = reader.getLineNumber();
Matcher matcher = pattern.matcher(line);
matcher.useTransparentBounds(true).useAnchoringBounds(false);
int pos = 0;
int endPos = line.length();
while(pos < endPos) {
matcher.region(pos, endPos);
if(matcher.lookingAt()) {
addToken(lineNo, matcher);
pos = matcher.end();
}else {
throw new ParseException("bad token at line: " + lineNo);
}
}
queue.add(new IdToken(lineNo, Token.EOL));
}
protected void addToken(int lineNo, Matcher matcher) {
/**
* java regex group example:
* Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)
*
* String: "!* UserName10 John Smith 01123 *!"
*
* group(0): UserName10 John Smith 01123
* group(1): UserName10
* group(2):
* group(3): John Smith
* group(4):
* group(5): 01123
*
* Regex: \\s*((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct})?
* ((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(1)
* (//.*): group(2)
* ([0-9]+): group(3)
* (\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\"): group(4)
* ([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(5)
*/
String m = matcher.group(1);
// 当是空格的时候,直接退出
if(m == null) {
return;
}
// 当是注释时,直接退出
if(matcher.group(2) != null) {
return;
}
Token token;
if(matcher.group(3) != null) { // 匹配数字
token = new NumToken(lineNo, Integer.parseInt(m));
}else if(matcher.group(4) != null) { // 匹配字符串
token = new StrToken(lineNo, toStringLiteral(m));
}else { // 匹配标识符
token = new IdToken(lineNo, m);
}
queue.add(token);
}
protected String toStringLiteral(String s) {
StringBuilder sb = new StringBuilder();
int len = s.length() - 1;
for(int i = 1; i < len; i ++) { // 这一步相当于是去掉首位字符啊,就是把双引号去掉的意思吧
char c = s.charAt(i);
if(c == '\\' && i + 1 < len) {
char c2 = s.charAt(++ i);
if(c2 == '\\' || c2 == '"') {
c = s.charAt(++ i);
}else if(c2 == 'n') {
++ i;
c = '\n';
}
}
sb.append(c);
}
return sb.toString();
}
}
| 2329408386/stone | src/stone/Lexer.java | 1,388 | // 读取一行 | line_comment | zh-cn | package stone;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author lichengpeng
* @desc 词法分析器
* @date 2020/7/11
**/
public class Lexer {
// pattern = 空白 + (注释 or 字符串 or 标识符)
// 标识符 = (变量 or 逻辑运算符 or 比较运算符 or 标点符号)
public static String regexPat = "\\s*((//.*)|" + "([0-9]+)|" + "(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|" + "([A-Z_a-z][A-Z_a-z0-9]*)|" +
"<=|>=|==|&&|\\|\\||\\p{Punct})?";
private Pattern pattern = Pattern.compile(regexPat);
private ArrayList<Token> queue = new ArrayList<Token>();
private boolean hashMore;
private LineNumberReader reader;
public Lexer(Reader r) {
hashMore = true;
reader = new LineNumberReader(r);
}
// 读取下一个token,并从队列中删除
public Token read() throws ParseException {
if(fillQueue(0)) {
return queue.remove(0);
}else {
return Token.EOF;
}
}
// 读取第i个token
public Token peek(int i) throws ParseException {
if(fillQueue(i)) {
return queue.get(i);
}else {
return Token.EOF;
}
}
// 填充token队列
private boolean fillQueue(int i) throws ParseException {
while(i >= queue.size()) {
if(hashMore) {
readLine();
}else {
return false;
}
}
return true;
}
// 读取 <SUF>
protected void readLine() throws ParseException{
String line;
try {
line = reader.readLine();
}catch(IOException e) {
throw new ParseException(e);
}
if(line == null) {
hashMore = false;
return;
}
int lineNo = reader.getLineNumber();
Matcher matcher = pattern.matcher(line);
matcher.useTransparentBounds(true).useAnchoringBounds(false);
int pos = 0;
int endPos = line.length();
while(pos < endPos) {
matcher.region(pos, endPos);
if(matcher.lookingAt()) {
addToken(lineNo, matcher);
pos = matcher.end();
}else {
throw new ParseException("bad token at line: " + lineNo);
}
}
queue.add(new IdToken(lineNo, Token.EOL));
}
protected void addToken(int lineNo, Matcher matcher) {
/**
* java regex group example:
* Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)
*
* String: "!* UserName10 John Smith 01123 *!"
*
* group(0): UserName10 John Smith 01123
* group(1): UserName10
* group(2):
* group(3): John Smith
* group(4):
* group(5): 01123
*
* Regex: \\s*((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct})?
* ((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(1)
* (//.*): group(2)
* ([0-9]+): group(3)
* (\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\"): group(4)
* ([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(5)
*/
String m = matcher.group(1);
// 当是空格的时候,直接退出
if(m == null) {
return;
}
// 当是注释时,直接退出
if(matcher.group(2) != null) {
return;
}
Token token;
if(matcher.group(3) != null) { // 匹配数字
token = new NumToken(lineNo, Integer.parseInt(m));
}else if(matcher.group(4) != null) { // 匹配字符串
token = new StrToken(lineNo, toStringLiteral(m));
}else { // 匹配标识符
token = new IdToken(lineNo, m);
}
queue.add(token);
}
protected String toStringLiteral(String s) {
StringBuilder sb = new StringBuilder();
int len = s.length() - 1;
for(int i = 1; i < len; i ++) { // 这一步相当于是去掉首位字符啊,就是把双引号去掉的意思吧
char c = s.charAt(i);
if(c == '\\' && i + 1 < len) {
char c2 = s.charAt(++ i);
if(c2 == '\\' || c2 == '"') {
c = s.charAt(++ i);
}else if(c2 == 'n') {
++ i;
c = '\n';
}
}
sb.append(c);
}
return sb.toString();
}
}
| 0 |
64407_1 | package com.utils;
import com.bean.WorkBook;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 字典转换
*
*/
public class FindWorkBook {
public static String landUseType(String id){
if(id ==null || id.equals("") || id.equals("2") || id.equals("住宅") || id.equals("住宅用地")
|| id.equals("公寓") || id.equals("公寓") ){
return "DWELLING";
}else if(id.equals("商业") || id.equals("商业/车库") || id.equals("商业用地") || id.equals("商服用地") || id.equals("网点") || id.equals("车库、库房")){
return "SHOP";
}else {
return "DWELLING";
}
}
public static String landUseType2(String id){
if(id ==null || id.equals("")){
return "DWELLING";
}else if(id.equals("DWELLING_KEY")){
return "DWELLING";
}else if(id.equals("SHOP_HOUSE_KEY")){
return "SHOP";
}else if(id.equals("CAR_STORE")){
return "GARAGE";
}else if(id.equals("STORE_HOUSE") || id.equals("INDUSTRY")){
return "STORE";
}else if(id.equals("OFFICE")){
return "OFFICE";
}else{
return "DWELLING";
}
}
public static WorkBook changeLandSnapshot(String id){
// 没有默认是住宅
WorkBook workBook = new WorkBook();
workBook.setId("01");
workBook.setValue("住宅");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("DWELLING_KEY")){
workBook.setId("DWELLING");
workBook.setValue("住宅");
return workBook;
}else if(id.equals("SHOP_HOUSE_KEY")){
workBook.setId("SHOP");
workBook.setValue("商业用房");
return workBook;
}else if(id.equals("CAR_STORE")) {
workBook.setId("GARAGE");
workBook.setValue("车库");
return workBook;
}else if(id.equals("OFFICE")) {
workBook.setId("OFFICE");
workBook.setValue("办公");
return workBook;
}else if(id.equals("STORE_HOUSE")) {
workBook.setId("STORE");
workBook.setValue("仓储");
return workBook;
}else {
return workBook;
}
}
/**
* @param id
* @return 转换正价类型,个人和企业的证件类型转换
*/
public static WorkBook changeIdType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("RESIDENT_ID");
workBook.setValue("身份证");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("SOLDIER_CARD")) { //士兵证
workBook.setId("SOLDIER");
workBook.setValue("士兵证");
return workBook;
}else if(id.equals("MASTER_ID") ||id.equals("OTHER")){//身份证
workBook.setId("RESIDENT_ID");
workBook.setValue("身份证");
return workBook;
}else if(id.equals("COMPANY_CODE")){//营业执照
workBook.setId("COMPANY");
workBook.setValue("营业执照");
return workBook;
}else if(id.equals("CORP_CODE")){//机构代码证
workBook.setId("ORGANIZATION");
workBook.setValue("机构代码证");
return workBook;
}else if(id.equals("PASSPORT")){//护照
workBook.setId("PASSPORT");
workBook.setValue("护照");
return workBook;
}else if(id.equals("TW_ID")){//台湾通行证
workBook.setId("TAIWAN");
workBook.setValue("台湾通行证");
return workBook;
}else if(id.equals("OFFICER_CARD")){//军官证
workBook.setId("OFFICER");
workBook.setValue("军官证");
return workBook;
}else if(id.equals("GA_ID")){//港澳通行证
workBook.setId("SPECIAL");
workBook.setValue("港澳通行证");
return workBook;
}else {
return workBook;
}
}
public static boolean isNumeric(String str) {
if (str == null || str.isEmpty()) {
return false;
}
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
/**
* @param id
* @return 土地权证类型转换
*/
public static WorkBook changeLandCardType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("2");
workBook.setValue("国有土地使用证");
if(id == null || id.equals("")){
return workBook;
}
if(id.equals("landCardType.collective")){
workBook.setId("3");
workBook.setValue("集体土地使用证");
return workBook;
}else {
workBook.setId("2");
workBook.setValue("国有土地使用证");
return workBook;
}
}
/**
* @param id
* @return 土地性质转换 允许为空
*/
public static WorkBook changeLandProperty(String id){
WorkBook workBook = new WorkBook();
workBook.setId(null);
workBook.setValue(null);
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("100")){
workBook.setId("2");
workBook.setValue("集体");
return workBook;
}else if(id.equals("870")){
workBook.setId("1");
workBook.setValue("国有");
return workBook;
}else {
return workBook;
}
}
/**
* @param id
* @return 土地取得方式 不能为空 字典
*/
public static WorkBook changeLandTakeType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("6");
workBook.setValue("其它");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("180")) {
workBook.setId("1");
workBook.setValue("出让");
return workBook;
}else if(id.equals("181")) {
workBook.setId("2");
workBook.setValue("划拨");
return workBook;
}else if(id.equals("182")) {
workBook.setId("3");
workBook.setValue("集体建设用地");
return workBook;
}else if(id.equals("183")) {
workBook.setId("4");
workBook.setValue("出租");
return workBook;
}else if(id.equals("184")) {
workBook.setId("5");
workBook.setValue("宅基地使用权");
return workBook;
}else {
return workBook;
}
}
public static WorkBook projectSizeType(String id){
WorkBook workBook = new WorkBook();
if(id == null || id.isBlank()){
workBook.setId(null);
workBook.setValue(null);
return workBook;
}
if(id.equals("buildSize.small")){
workBook.setId("SMALL");
workBook.setValue("小");
return workBook;
}else if(id.equals("buildSize.big")){
workBook.setId("BIG");
workBook.setValue("大");
return workBook;
}else {
workBook.setId("MIDDLE");
workBook.setValue("中等");
return workBook;
}
}
public static WorkBook structure(String id){
WorkBook workBook = new WorkBook();
workBook.setId("0");
workBook.setValue("其他结构");
if(id.equals("88")){
workBook.setId("1");
workBook.setValue("钢结构");
return workBook;
}else if(id.equals("822") || id.equals("89")){
workBook.setId("2");
workBook.setValue("钢、钢筋混凝土结构");
return workBook;
}else if(id.equals("823") || id.equals("915")){
workBook.setId("3");
workBook.setValue("钢筋混凝土结构");
return workBook;
}else if(id.equals("824")){
workBook.setId("4");
workBook.setValue("混合结构");
return workBook;
}else if(id.equals("825")){
workBook.setId("5");
workBook.setValue("砖木结构");
return workBook;
}else if(id.equals("4113")){
workBook.setId("8");
workBook.setValue("剪力结构");
return workBook;
}else if(id.equals("826")){
workBook.setId("9");
workBook.setValue("土木结构");
return workBook;
}else if(id.equals("90")){
workBook.setId("10");
workBook.setValue("花岗石结构");
return workBook;
}else if(id.equals("1559")){
workBook.setId("11");
workBook.setValue("砖混结构");
return workBook;
}else if(id.equals("框剪")){
workBook.setId("12");
workBook.setValue("框剪");
return workBook;
}else if(id.equals("框架")){
workBook.setId("13");
workBook.setValue("框架");
return workBook;
}else{
return workBook;
}
}
public static WorkBook buildType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("MULTI");
workBook.setValue("多层");
if(id==null || id.equals("")){
return workBook;
}
if (id.equals("202")){
workBook.setId("MULTI");
workBook.setValue("多层");
return workBook;
}else if(id.equals("203")){
workBook.setId("HIGH");
workBook.setValue("高层");
return workBook;
}else if(id.equals("204")){
workBook.setId("VILLA");
workBook.setValue("别墅");
return workBook;
}else if(id.equals("2772")){
workBook.setId("BUNGALOW");
workBook.setValue("平房");
return workBook;
}else{
return workBook;
}
}
public static int getYearFromDate(java.sql.Timestamp date) {
// 使用Date对象获取年份
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static int getYearMonthFromDate(java.sql.Timestamp date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
String formattedDate = dateFormat.format(date);
int yearMonth = Integer.parseInt(formattedDate);
return yearMonth;
}
public static String getCardStatus(String id){
if (id.equals("COMPLETE")){
return "VALID";
}else if(id.equals("COMPLETE_CANCEL")){
return "DESTROY";
}else{
return "DESTROY";
}
}
public static String getContractStatus(String id){
if (id.equals("COMPLETE")){
return "TRUE";
}else if(id.equals("COMPLETE_CANCEL")){
return "FALSE";
}else{
return "FALSE";
}
}
public static String getEmpType(String id){
if(id==null || id.equals("")){
return "未知";
}
if (id.equals("APPLY_EMP")){
return "受理人";
}else if(id.equals("CHECK_EMP")){
return "审核人";
}else if(id.equals("CREATE_EMP")){
return "建立人";
}else if(id.equals("FIRST_CHECK")){
return "初审人";
}else if(id.equals("LAST_CHECK_EMP")){
return "审批人";
}else if(id.equals("PATCH_EMP")){
return "补录人";
}else if(id.equals("RECORD_EMP")){
return "归档人";
}else if(id.equals("REG_EMP")){
return "登薄人";
}else{
return "未知";
}
}
public static String getPayType(String id){
if(id==null || id.equals("")){
return "OTHER";
}
if (id.equals("ALL_PAY")){//一次性付款
return "ONE_TIME";
}else if(id.equals("PART_PAY")){//分期付款
return "INSTALLMENT";
}else if(id.equals("DEBIT_PAY")){//抵押贷款
return "LOAN";
}else {
return "OTHER";
}
}
public static String getPoolType(String id){
if (id.equals("SINGLE_OWNER")){//单独
return "SINGLE";
}else if(id.equals("TOGETHER_OWNER")){//共同
return "SHARE";
}else if(id.equals("SHARE_OWNER")){//按份共有
return "JOINT";
}else {
return "SINGLE";
}
}
public static WorkBook getMappingCorpId(String id){
WorkBook workBook = new WorkBook();
workBook.setId("3");
workBook.setValue("未知测绘机构");
if(id==null || id.equals("")){
return workBook;
}
if(id.equals("1")){
workBook.setId("1");
workBook.setValue("东港市房产测绘中心");
return workBook;
}else if(id.equals("2")){
workBook.setId("2");
workBook.setValue("东港市村镇建设管理处测绘队");
return workBook;
}else {
return workBook;
}
}
public static String getContractType(String id){
if(id==null || id.equals("")){
return "PRE_SALE";
}
if (id.equals("NOW_SELL")){
return "SALE";
}else{
return "PRE_SALE";
}
}
public static String getProxyType(String id){
if (id.equals("LEGAL")){//法定代理人
return "Legal";
}else{
return "Agent";//委托代理人
}
}
public static String getLockedHouseType(String id){
if(id==null || id.equals("")){
return "FREEZE";
}
if(id.equals("CANT_SALE")){
return "FREEZE";
}else if(id.equals("CLOSE_REG")){
return "SEIZURE";
}else if(id.equals("HOUSE_LOCKED")){
return "FREEZE";
}if(id.equals("MORTGAGE_REEG")){
return "MORTGAGE";
}if(id.equals("OTHER_REG")){
return "FREEZE";
}if(id.equals("PREAPRE_MORTGAGE")){
return "MORTGAGE";
}else {
return "FREEZE";
}
}
public static WorkBook getPoolRelation(String id){
WorkBook workBook = new WorkBook();
workBook.setId("6");
workBook.setValue("其它");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("215")){
workBook.setId("0");
workBook.setValue("夫妻");
return workBook;
}else if (id.equals("3852") || id.equals("3853")){
workBook.setId("1");
workBook.setValue("父子(女)");
return workBook;
}else if (id.equals("3850") || id.equals("3851") ) {
workBook.setId("2");
workBook.setValue("母子(女)");
return workBook;
}else if (id.equals("216") ) {
workBook.setId("4");
workBook.setValue("兄弟");
return workBook;
}else if (id.equals("217") ) {
workBook.setId("5");
workBook.setValue("姐妹");
return workBook;
}else{
workBook.setId("6");
workBook.setValue("其它");
return workBook;
}
}
public static String houseProperty(String id){
// if(id==null || id.equals("")|| id.equals("COMM_USE_HOUSE")|| id.equals("SELF_CREATE")
// || id.equals("STORE_HOUSE")){
// return "null";
// }
if (id.equals("BACK_HOUSE")){
return "RELOCATION";
}else if (id.equals("GROUP_HOUSE")){
return "RAISE";
}else if (id.equals("SALE_HOUSE")){
return "SALE";
}else if (id.equals("WELFARE_HOUSE")){
return "WELFARE";
}else {
return null;
}
}
}
/**
除了houseType useType外的字典处理, 通过调用workbookMapper 通过就字典的ID 取出新字典的ID
use INTEGRATION;
-- 'layer_type 户型结构','layout 户型居室 为空不导入',orientation 房屋朝向 么有
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',3,'集体建设用地',3,'03',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',4,'出租',4,'04',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',5,'宅基地使用权',5,'05',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',6,'其它',6,'06',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_property',3,'其它',3,'03',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',8,'剪力结构',8,'08',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',9,'土木结构',9,'09',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',10,'花岗石结构',10,'10',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',11,'砖混结构',11,'11',null,true);
INSERT INTEGRATION.workBook(id, oid, value) value (3,'landCardType.collective','集体土地使用证');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'landCardType.stateOwned','国有土地使用证');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'870','国有');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'100','集体');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'180','出让');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'181','划拨');
INSERT INTEGRATION.workBook(id, oid, value) value (3,'182','集体建设用地');
INSERT INTEGRATION.workBook(id, oid, value) value (4,'183','出租');
INSERT INTEGRATION.workBook(id, oid, value) value (5,'184','宅基地使用权');
INSERT INTEGRATION.workBook(id, oid, value) value (0,'215','夫妻');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'3852','父子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'3853','父子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'3850','母子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'3851','母子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (4,'216','兄弟');
INSERT INTEGRATION.workBook(id, oid, value) value (5,'217','姐妹');
INSERT INTEGRATION.workBook(id, oid, value) value (6,'3856','其它');
INSERT INTEGRATION.workBook(id, oid, value) value (0,'827','其他结构');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'88','钢结构');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'822','钢、钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'89','钢、钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (3,'823','钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (3,'915','钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (4,'824','混合结构');
INSERT INTEGRATION.workBook(id, oid, value) value (5,'825','砖木结构');
INSERT INTEGRATION.workBook(id, oid, value) value (8,'4113','剪力结构');
INSERT INTEGRATION.workBook(id, oid, value) value (9,'826','土木结构');
INSERT INTEGRATION.workBook(id, oid, value) value (10,'90','花岗石结构');
INSERT INTEGRATION.workBook(id, oid, value) value (11,'1559','砖混结构');
INSERT INTEGRATION.workBook(id, oid, value) value ('SOLDIER','SOLDIER_CARD','士兵证');
INSERT INTEGRATION.workBook(id, oid, value) value ('RESIDENT_ID','MASTER_ID','身份证');
INSERT INTEGRATION.workBook(id, oid, value) value ('COMPANY','COMPANY_CODE','营业执照');
INSERT INTEGRATION.workBook(id, oid, value) value ('ORGANIZATION','CORP_CODE','机构代码证');
INSERT INTEGRATION.workBook(id, oid, value) value ('PASSPORT','PASSPORT','护照');
INSERT INTEGRATION.workBook(id, oid, value) value ('TAIWAN','TW_ID','台湾通行证');
INSERT INTEGRATION.workBook(id, oid, value) value ('OTHER','OTHER','无证件');
INSERT INTEGRATION.workBook(id, oid, value) value ('OFFICER','OFFICER_CARD','军官证');
INSERT INTEGRATION.workBook(id, oid, value) value ('SPECIAL','GA_ID','港澳通行证');
*/
| 23504653/integration | src/main/java/com/utils/FindWorkBook.java | 5,835 | // 没有默认是住宅 | line_comment | zh-cn | package com.utils;
import com.bean.WorkBook;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 字典转换
*
*/
public class FindWorkBook {
public static String landUseType(String id){
if(id ==null || id.equals("") || id.equals("2") || id.equals("住宅") || id.equals("住宅用地")
|| id.equals("公寓") || id.equals("公寓") ){
return "DWELLING";
}else if(id.equals("商业") || id.equals("商业/车库") || id.equals("商业用地") || id.equals("商服用地") || id.equals("网点") || id.equals("车库、库房")){
return "SHOP";
}else {
return "DWELLING";
}
}
public static String landUseType2(String id){
if(id ==null || id.equals("")){
return "DWELLING";
}else if(id.equals("DWELLING_KEY")){
return "DWELLING";
}else if(id.equals("SHOP_HOUSE_KEY")){
return "SHOP";
}else if(id.equals("CAR_STORE")){
return "GARAGE";
}else if(id.equals("STORE_HOUSE") || id.equals("INDUSTRY")){
return "STORE";
}else if(id.equals("OFFICE")){
return "OFFICE";
}else{
return "DWELLING";
}
}
public static WorkBook changeLandSnapshot(String id){
// 没有 <SUF>
WorkBook workBook = new WorkBook();
workBook.setId("01");
workBook.setValue("住宅");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("DWELLING_KEY")){
workBook.setId("DWELLING");
workBook.setValue("住宅");
return workBook;
}else if(id.equals("SHOP_HOUSE_KEY")){
workBook.setId("SHOP");
workBook.setValue("商业用房");
return workBook;
}else if(id.equals("CAR_STORE")) {
workBook.setId("GARAGE");
workBook.setValue("车库");
return workBook;
}else if(id.equals("OFFICE")) {
workBook.setId("OFFICE");
workBook.setValue("办公");
return workBook;
}else if(id.equals("STORE_HOUSE")) {
workBook.setId("STORE");
workBook.setValue("仓储");
return workBook;
}else {
return workBook;
}
}
/**
* @param id
* @return 转换正价类型,个人和企业的证件类型转换
*/
public static WorkBook changeIdType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("RESIDENT_ID");
workBook.setValue("身份证");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("SOLDIER_CARD")) { //士兵证
workBook.setId("SOLDIER");
workBook.setValue("士兵证");
return workBook;
}else if(id.equals("MASTER_ID") ||id.equals("OTHER")){//身份证
workBook.setId("RESIDENT_ID");
workBook.setValue("身份证");
return workBook;
}else if(id.equals("COMPANY_CODE")){//营业执照
workBook.setId("COMPANY");
workBook.setValue("营业执照");
return workBook;
}else if(id.equals("CORP_CODE")){//机构代码证
workBook.setId("ORGANIZATION");
workBook.setValue("机构代码证");
return workBook;
}else if(id.equals("PASSPORT")){//护照
workBook.setId("PASSPORT");
workBook.setValue("护照");
return workBook;
}else if(id.equals("TW_ID")){//台湾通行证
workBook.setId("TAIWAN");
workBook.setValue("台湾通行证");
return workBook;
}else if(id.equals("OFFICER_CARD")){//军官证
workBook.setId("OFFICER");
workBook.setValue("军官证");
return workBook;
}else if(id.equals("GA_ID")){//港澳通行证
workBook.setId("SPECIAL");
workBook.setValue("港澳通行证");
return workBook;
}else {
return workBook;
}
}
public static boolean isNumeric(String str) {
if (str == null || str.isEmpty()) {
return false;
}
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
/**
* @param id
* @return 土地权证类型转换
*/
public static WorkBook changeLandCardType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("2");
workBook.setValue("国有土地使用证");
if(id == null || id.equals("")){
return workBook;
}
if(id.equals("landCardType.collective")){
workBook.setId("3");
workBook.setValue("集体土地使用证");
return workBook;
}else {
workBook.setId("2");
workBook.setValue("国有土地使用证");
return workBook;
}
}
/**
* @param id
* @return 土地性质转换 允许为空
*/
public static WorkBook changeLandProperty(String id){
WorkBook workBook = new WorkBook();
workBook.setId(null);
workBook.setValue(null);
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("100")){
workBook.setId("2");
workBook.setValue("集体");
return workBook;
}else if(id.equals("870")){
workBook.setId("1");
workBook.setValue("国有");
return workBook;
}else {
return workBook;
}
}
/**
* @param id
* @return 土地取得方式 不能为空 字典
*/
public static WorkBook changeLandTakeType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("6");
workBook.setValue("其它");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("180")) {
workBook.setId("1");
workBook.setValue("出让");
return workBook;
}else if(id.equals("181")) {
workBook.setId("2");
workBook.setValue("划拨");
return workBook;
}else if(id.equals("182")) {
workBook.setId("3");
workBook.setValue("集体建设用地");
return workBook;
}else if(id.equals("183")) {
workBook.setId("4");
workBook.setValue("出租");
return workBook;
}else if(id.equals("184")) {
workBook.setId("5");
workBook.setValue("宅基地使用权");
return workBook;
}else {
return workBook;
}
}
public static WorkBook projectSizeType(String id){
WorkBook workBook = new WorkBook();
if(id == null || id.isBlank()){
workBook.setId(null);
workBook.setValue(null);
return workBook;
}
if(id.equals("buildSize.small")){
workBook.setId("SMALL");
workBook.setValue("小");
return workBook;
}else if(id.equals("buildSize.big")){
workBook.setId("BIG");
workBook.setValue("大");
return workBook;
}else {
workBook.setId("MIDDLE");
workBook.setValue("中等");
return workBook;
}
}
public static WorkBook structure(String id){
WorkBook workBook = new WorkBook();
workBook.setId("0");
workBook.setValue("其他结构");
if(id.equals("88")){
workBook.setId("1");
workBook.setValue("钢结构");
return workBook;
}else if(id.equals("822") || id.equals("89")){
workBook.setId("2");
workBook.setValue("钢、钢筋混凝土结构");
return workBook;
}else if(id.equals("823") || id.equals("915")){
workBook.setId("3");
workBook.setValue("钢筋混凝土结构");
return workBook;
}else if(id.equals("824")){
workBook.setId("4");
workBook.setValue("混合结构");
return workBook;
}else if(id.equals("825")){
workBook.setId("5");
workBook.setValue("砖木结构");
return workBook;
}else if(id.equals("4113")){
workBook.setId("8");
workBook.setValue("剪力结构");
return workBook;
}else if(id.equals("826")){
workBook.setId("9");
workBook.setValue("土木结构");
return workBook;
}else if(id.equals("90")){
workBook.setId("10");
workBook.setValue("花岗石结构");
return workBook;
}else if(id.equals("1559")){
workBook.setId("11");
workBook.setValue("砖混结构");
return workBook;
}else if(id.equals("框剪")){
workBook.setId("12");
workBook.setValue("框剪");
return workBook;
}else if(id.equals("框架")){
workBook.setId("13");
workBook.setValue("框架");
return workBook;
}else{
return workBook;
}
}
public static WorkBook buildType(String id){
WorkBook workBook = new WorkBook();
workBook.setId("MULTI");
workBook.setValue("多层");
if(id==null || id.equals("")){
return workBook;
}
if (id.equals("202")){
workBook.setId("MULTI");
workBook.setValue("多层");
return workBook;
}else if(id.equals("203")){
workBook.setId("HIGH");
workBook.setValue("高层");
return workBook;
}else if(id.equals("204")){
workBook.setId("VILLA");
workBook.setValue("别墅");
return workBook;
}else if(id.equals("2772")){
workBook.setId("BUNGALOW");
workBook.setValue("平房");
return workBook;
}else{
return workBook;
}
}
public static int getYearFromDate(java.sql.Timestamp date) {
// 使用Date对象获取年份
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static int getYearMonthFromDate(java.sql.Timestamp date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
String formattedDate = dateFormat.format(date);
int yearMonth = Integer.parseInt(formattedDate);
return yearMonth;
}
public static String getCardStatus(String id){
if (id.equals("COMPLETE")){
return "VALID";
}else if(id.equals("COMPLETE_CANCEL")){
return "DESTROY";
}else{
return "DESTROY";
}
}
public static String getContractStatus(String id){
if (id.equals("COMPLETE")){
return "TRUE";
}else if(id.equals("COMPLETE_CANCEL")){
return "FALSE";
}else{
return "FALSE";
}
}
public static String getEmpType(String id){
if(id==null || id.equals("")){
return "未知";
}
if (id.equals("APPLY_EMP")){
return "受理人";
}else if(id.equals("CHECK_EMP")){
return "审核人";
}else if(id.equals("CREATE_EMP")){
return "建立人";
}else if(id.equals("FIRST_CHECK")){
return "初审人";
}else if(id.equals("LAST_CHECK_EMP")){
return "审批人";
}else if(id.equals("PATCH_EMP")){
return "补录人";
}else if(id.equals("RECORD_EMP")){
return "归档人";
}else if(id.equals("REG_EMP")){
return "登薄人";
}else{
return "未知";
}
}
public static String getPayType(String id){
if(id==null || id.equals("")){
return "OTHER";
}
if (id.equals("ALL_PAY")){//一次性付款
return "ONE_TIME";
}else if(id.equals("PART_PAY")){//分期付款
return "INSTALLMENT";
}else if(id.equals("DEBIT_PAY")){//抵押贷款
return "LOAN";
}else {
return "OTHER";
}
}
public static String getPoolType(String id){
if (id.equals("SINGLE_OWNER")){//单独
return "SINGLE";
}else if(id.equals("TOGETHER_OWNER")){//共同
return "SHARE";
}else if(id.equals("SHARE_OWNER")){//按份共有
return "JOINT";
}else {
return "SINGLE";
}
}
public static WorkBook getMappingCorpId(String id){
WorkBook workBook = new WorkBook();
workBook.setId("3");
workBook.setValue("未知测绘机构");
if(id==null || id.equals("")){
return workBook;
}
if(id.equals("1")){
workBook.setId("1");
workBook.setValue("东港市房产测绘中心");
return workBook;
}else if(id.equals("2")){
workBook.setId("2");
workBook.setValue("东港市村镇建设管理处测绘队");
return workBook;
}else {
return workBook;
}
}
public static String getContractType(String id){
if(id==null || id.equals("")){
return "PRE_SALE";
}
if (id.equals("NOW_SELL")){
return "SALE";
}else{
return "PRE_SALE";
}
}
public static String getProxyType(String id){
if (id.equals("LEGAL")){//法定代理人
return "Legal";
}else{
return "Agent";//委托代理人
}
}
public static String getLockedHouseType(String id){
if(id==null || id.equals("")){
return "FREEZE";
}
if(id.equals("CANT_SALE")){
return "FREEZE";
}else if(id.equals("CLOSE_REG")){
return "SEIZURE";
}else if(id.equals("HOUSE_LOCKED")){
return "FREEZE";
}if(id.equals("MORTGAGE_REEG")){
return "MORTGAGE";
}if(id.equals("OTHER_REG")){
return "FREEZE";
}if(id.equals("PREAPRE_MORTGAGE")){
return "MORTGAGE";
}else {
return "FREEZE";
}
}
public static WorkBook getPoolRelation(String id){
WorkBook workBook = new WorkBook();
workBook.setId("6");
workBook.setValue("其它");
if(id == null || id.equals("") || id.isBlank()){
return workBook;
}
if(id.equals("215")){
workBook.setId("0");
workBook.setValue("夫妻");
return workBook;
}else if (id.equals("3852") || id.equals("3853")){
workBook.setId("1");
workBook.setValue("父子(女)");
return workBook;
}else if (id.equals("3850") || id.equals("3851") ) {
workBook.setId("2");
workBook.setValue("母子(女)");
return workBook;
}else if (id.equals("216") ) {
workBook.setId("4");
workBook.setValue("兄弟");
return workBook;
}else if (id.equals("217") ) {
workBook.setId("5");
workBook.setValue("姐妹");
return workBook;
}else{
workBook.setId("6");
workBook.setValue("其它");
return workBook;
}
}
public static String houseProperty(String id){
// if(id==null || id.equals("")|| id.equals("COMM_USE_HOUSE")|| id.equals("SELF_CREATE")
// || id.equals("STORE_HOUSE")){
// return "null";
// }
if (id.equals("BACK_HOUSE")){
return "RELOCATION";
}else if (id.equals("GROUP_HOUSE")){
return "RAISE";
}else if (id.equals("SALE_HOUSE")){
return "SALE";
}else if (id.equals("WELFARE_HOUSE")){
return "WELFARE";
}else {
return null;
}
}
}
/**
除了houseType useType外的字典处理, 通过调用workbookMapper 通过就字典的ID 取出新字典的ID
use INTEGRATION;
-- 'layer_type 户型结构','layout 户型居室 为空不导入',orientation 房屋朝向 么有
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',3,'集体建设用地',3,'03',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',4,'出租',4,'04',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',5,'宅基地使用权',5,'05',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_takeType',6,'其它',6,'06',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('land_property',3,'其它',3,'03',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',8,'剪力结构',8,'08',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',9,'土木结构',9,'09',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',10,'花岗石结构',10,'10',null,true);
INSERT dictionary.dictionary_word (category, value, label, seq, report_value, _group, enabled) value
('structure',11,'砖混结构',11,'11',null,true);
INSERT INTEGRATION.workBook(id, oid, value) value (3,'landCardType.collective','集体土地使用证');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'landCardType.stateOwned','国有土地使用证');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'870','国有');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'100','集体');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'180','出让');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'181','划拨');
INSERT INTEGRATION.workBook(id, oid, value) value (3,'182','集体建设用地');
INSERT INTEGRATION.workBook(id, oid, value) value (4,'183','出租');
INSERT INTEGRATION.workBook(id, oid, value) value (5,'184','宅基地使用权');
INSERT INTEGRATION.workBook(id, oid, value) value (0,'215','夫妻');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'3852','父子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'3853','父子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'3850','母子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'3851','母子(女)');
INSERT INTEGRATION.workBook(id, oid, value) value (4,'216','兄弟');
INSERT INTEGRATION.workBook(id, oid, value) value (5,'217','姐妹');
INSERT INTEGRATION.workBook(id, oid, value) value (6,'3856','其它');
INSERT INTEGRATION.workBook(id, oid, value) value (0,'827','其他结构');
INSERT INTEGRATION.workBook(id, oid, value) value (1,'88','钢结构');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'822','钢、钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (2,'89','钢、钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (3,'823','钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (3,'915','钢筋混凝土结构');
INSERT INTEGRATION.workBook(id, oid, value) value (4,'824','混合结构');
INSERT INTEGRATION.workBook(id, oid, value) value (5,'825','砖木结构');
INSERT INTEGRATION.workBook(id, oid, value) value (8,'4113','剪力结构');
INSERT INTEGRATION.workBook(id, oid, value) value (9,'826','土木结构');
INSERT INTEGRATION.workBook(id, oid, value) value (10,'90','花岗石结构');
INSERT INTEGRATION.workBook(id, oid, value) value (11,'1559','砖混结构');
INSERT INTEGRATION.workBook(id, oid, value) value ('SOLDIER','SOLDIER_CARD','士兵证');
INSERT INTEGRATION.workBook(id, oid, value) value ('RESIDENT_ID','MASTER_ID','身份证');
INSERT INTEGRATION.workBook(id, oid, value) value ('COMPANY','COMPANY_CODE','营业执照');
INSERT INTEGRATION.workBook(id, oid, value) value ('ORGANIZATION','CORP_CODE','机构代码证');
INSERT INTEGRATION.workBook(id, oid, value) value ('PASSPORT','PASSPORT','护照');
INSERT INTEGRATION.workBook(id, oid, value) value ('TAIWAN','TW_ID','台湾通行证');
INSERT INTEGRATION.workBook(id, oid, value) value ('OTHER','OTHER','无证件');
INSERT INTEGRATION.workBook(id, oid, value) value ('OFFICER','OFFICER_CARD','军官证');
INSERT INTEGRATION.workBook(id, oid, value) value ('SPECIAL','GA_ID','港澳通行证');
*/
| 0 |
53005_1 | package study;
/**
* @author : 小何
* @Description :
* @date : 2022-10-11 17:29
*/
public class Edge {
// 这条边的权重(距离)
public Integer weight;
// 边的起点
public Node from;
// 边的终点
public Node to;
public Edge(Node from, Node to,Integer weight) {
this.weight = weight;
this.from = from;
this.to = to;
}
}
| 2382546457/algorithm | src/study/Edge.java | 128 | // 这条边的权重(距离) | line_comment | zh-cn | package study;
/**
* @author : 小何
* @Description :
* @date : 2022-10-11 17:29
*/
public class Edge {
// 这条 <SUF>
public Integer weight;
// 边的起点
public Node from;
// 边的终点
public Node to;
public Edge(Node from, Node to,Integer weight) {
this.weight = weight;
this.from = from;
this.to = to;
}
}
| 0 |
38298_20 | //Alice 和 Bob 两个人轮流玩一个游戏,Alice 先手。
//
// 一开始,有 n 个石子堆在一起。每个人轮流操作,正在操作的玩家可以从石子堆里拿走 任意 非零 平方数 个石子。
//
// 如果石子堆里没有石子了,则无法操作的玩家输掉游戏。
//
// 给你正整数 n ,且已知两个人都采取最优策略。如果 Alice 会赢得比赛,那么返回 True ,否则返回 False 。
//
//
//
// 示例 1:
//
//
//输入:n = 1
//输出:true
//解释:Alice 拿走 1 个石子并赢得胜利,因为 Bob 无法进行任何操作。
//
// 示例 2:
//
//
//输入:n = 2
//输出:false
//解释:Alice 只能拿走 1 个石子,然后 Bob 拿走最后一个石子并赢得胜利(2 -> 1 -> 0)。
//
// 示例 3:
//
//
//输入:n = 4
//输出:true
//解释:n 已经是一个平方数,Alice 可以一次全拿掉 4 个石子并赢得胜利(4 -> 0)。
//
//
// 示例 4:
//
//
//输入:n = 7
//输出:false
//解释:当 Bob 采取最优策略时,Alice 无法赢得比赛。
//如果 Alice 一开始拿走 4 个石子, Bob 会拿走 1 个石子,然后 Alice 只能拿走 1 个石子,Bob 拿走最后一个石子并赢得胜利(7 ->
// 3 -> 2 -> 1 -> 0)。
//如果 Alice 一开始拿走 1 个石子, Bob 会拿走 4 个石子,然后 Alice 只能拿走 1 个石子,Bob 拿走最后一个石子并赢得胜利(7 ->
// 6 -> 2 -> 1 -> 0)。
//
// 示例 5:
//
//
//输入:n = 17
//输出:false
//解释:如果 Bob 采取最优策略,Alice 无法赢得胜利。
//
//
//
//
// 提示:
//
//
// 1 <= n <= 10^5
//
//
// Related Topics 数学 动态规划 博弈 👍 49 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
int[] squareNum = {1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801, 10000, 10201, 10404, 10609, 10816, 11025, 11236, 11449, 11664, 11881, 12100, 12321, 12544, 12769, 12996, 13225, 13456, 13689, 13924, 14161, 14400, 14641, 14884, 15129, 15376, 15625, 15876, 16129, 16384, 16641, 16900, 17161, 17424, 17689, 17956, 18225, 18496, 18769, 19044, 19321, 19600, 19881, 20164, 20449, 20736, 21025, 21316, 21609, 21904, 22201, 22500, 22801, 23104, 23409, 23716, 24025, 24336, 24649, 24964, 25281, 25600, 25921, 26244, 26569, 26896, 27225, 27556, 27889, 28224, 28561, 28900, 29241, 29584, 29929, 30276, 30625, 30976, 31329, 31684, 32041, 32400, 32761, 33124, 33489, 33856, 34225, 34596, 34969, 35344, 35721, 36100, 36481, 36864, 37249, 37636, 38025, 38416, 38809, 39204, 39601, 40000, 40401, 40804, 41209, 41616, 42025, 42436, 42849, 43264, 43681, 44100, 44521, 44944, 45369, 45796, 46225, 46656, 47089, 47524, 47961, 48400, 48841, 49284, 49729, 50176, 50625, 51076, 51529, 51984, 52441, 52900, 53361, 53824, 54289, 54756, 55225, 55696, 56169, 56644, 57121, 57600, 58081, 58564, 59049, 59536, 60025, 60516, 61009, 61504, 62001, 62500, 63001, 63504, 64009, 64516, 65025, 65536, 66049, 66564, 67081, 67600, 68121, 68644, 69169, 69696, 70225, 70756, 71289, 71824, 72361, 72900, 73441, 73984, 74529, 75076, 75625, 76176, 76729, 77284, 77841, 78400, 78961, 79524, 80089, 80656, 81225, 81796, 82369, 82944, 83521, 84100, 84681, 85264, 85849, 86436, 87025, 87616, 88209, 88804, 89401, 90000, 90601, 91204, 91809, 92416, 93025, 93636, 94249, 94864, 95481, 96100, 96721, 97344, 97969, 98596, 99225, 99856};
public boolean winnerSquareGame(int n) {
boolean[] wins = new boolean[n + 1];
Arrays.fill(wins, false);
wins[0] = false;
wins[1] = true;
for (int i = 2; i < n + 1; i++) {
for (int j = 0; j < squareNum.length; j++) {
if (i - squareNum[j] < 0) {
break;
}
if (!wins[i - squareNum[j]]) {
wins[i] = true;
break;
}
}
}
return wins[n];
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 2394215175/leetcode | src/main/code/editor/cn/[1510]石子游戏 IV.java | 2,891 | //如果 Alice 一开始拿走 4 个石子, Bob 会拿走 1 个石子,然后 Alice 只能拿走 1 个石子,Bob 拿走最后一个石子并赢得胜利(7 -> | line_comment | zh-cn | //Alice 和 Bob 两个人轮流玩一个游戏,Alice 先手。
//
// 一开始,有 n 个石子堆在一起。每个人轮流操作,正在操作的玩家可以从石子堆里拿走 任意 非零 平方数 个石子。
//
// 如果石子堆里没有石子了,则无法操作的玩家输掉游戏。
//
// 给你正整数 n ,且已知两个人都采取最优策略。如果 Alice 会赢得比赛,那么返回 True ,否则返回 False 。
//
//
//
// 示例 1:
//
//
//输入:n = 1
//输出:true
//解释:Alice 拿走 1 个石子并赢得胜利,因为 Bob 无法进行任何操作。
//
// 示例 2:
//
//
//输入:n = 2
//输出:false
//解释:Alice 只能拿走 1 个石子,然后 Bob 拿走最后一个石子并赢得胜利(2 -> 1 -> 0)。
//
// 示例 3:
//
//
//输入:n = 4
//输出:true
//解释:n 已经是一个平方数,Alice 可以一次全拿掉 4 个石子并赢得胜利(4 -> 0)。
//
//
// 示例 4:
//
//
//输入:n = 7
//输出:false
//解释:当 Bob 采取最优策略时,Alice 无法赢得比赛。
//如果 <SUF>
// 3 -> 2 -> 1 -> 0)。
//如果 Alice 一开始拿走 1 个石子, Bob 会拿走 4 个石子,然后 Alice 只能拿走 1 个石子,Bob 拿走最后一个石子并赢得胜利(7 ->
// 6 -> 2 -> 1 -> 0)。
//
// 示例 5:
//
//
//输入:n = 17
//输出:false
//解释:如果 Bob 采取最优策略,Alice 无法赢得胜利。
//
//
//
//
// 提示:
//
//
// 1 <= n <= 10^5
//
//
// Related Topics 数学 动态规划 博弈 👍 49 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
int[] squareNum = {1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801, 10000, 10201, 10404, 10609, 10816, 11025, 11236, 11449, 11664, 11881, 12100, 12321, 12544, 12769, 12996, 13225, 13456, 13689, 13924, 14161, 14400, 14641, 14884, 15129, 15376, 15625, 15876, 16129, 16384, 16641, 16900, 17161, 17424, 17689, 17956, 18225, 18496, 18769, 19044, 19321, 19600, 19881, 20164, 20449, 20736, 21025, 21316, 21609, 21904, 22201, 22500, 22801, 23104, 23409, 23716, 24025, 24336, 24649, 24964, 25281, 25600, 25921, 26244, 26569, 26896, 27225, 27556, 27889, 28224, 28561, 28900, 29241, 29584, 29929, 30276, 30625, 30976, 31329, 31684, 32041, 32400, 32761, 33124, 33489, 33856, 34225, 34596, 34969, 35344, 35721, 36100, 36481, 36864, 37249, 37636, 38025, 38416, 38809, 39204, 39601, 40000, 40401, 40804, 41209, 41616, 42025, 42436, 42849, 43264, 43681, 44100, 44521, 44944, 45369, 45796, 46225, 46656, 47089, 47524, 47961, 48400, 48841, 49284, 49729, 50176, 50625, 51076, 51529, 51984, 52441, 52900, 53361, 53824, 54289, 54756, 55225, 55696, 56169, 56644, 57121, 57600, 58081, 58564, 59049, 59536, 60025, 60516, 61009, 61504, 62001, 62500, 63001, 63504, 64009, 64516, 65025, 65536, 66049, 66564, 67081, 67600, 68121, 68644, 69169, 69696, 70225, 70756, 71289, 71824, 72361, 72900, 73441, 73984, 74529, 75076, 75625, 76176, 76729, 77284, 77841, 78400, 78961, 79524, 80089, 80656, 81225, 81796, 82369, 82944, 83521, 84100, 84681, 85264, 85849, 86436, 87025, 87616, 88209, 88804, 89401, 90000, 90601, 91204, 91809, 92416, 93025, 93636, 94249, 94864, 95481, 96100, 96721, 97344, 97969, 98596, 99225, 99856};
public boolean winnerSquareGame(int n) {
boolean[] wins = new boolean[n + 1];
Arrays.fill(wins, false);
wins[0] = false;
wins[1] = true;
for (int i = 2; i < n + 1; i++) {
for (int j = 0; j < squareNum.length; j++) {
if (i - squareNum[j] < 0) {
break;
}
if (!wins[i - squareNum[j]]) {
wins[i] = true;
break;
}
}
}
return wins[n];
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 1 |
39004_14 | package site.day.blog.pojo.vo;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @ClassName CommentVO
* @Author 23DAY
* @Date 2023/01/18 20:48
* @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "CommentHomeVO", description = "评论表")
public class CommentHomeVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(name = "id", value = "主键", dataType = "Integer")
private Integer id;
/**
* 评论用户Id
*/
@ApiModelProperty(name = "userId", value = "评论用户Id", dataType = "Integer")
private Integer userId;
/**
* 用户名
*/
@ApiModelProperty(name = "nickName", value = "用户名", dataType = "String")
private String nickName;
/**
* 头像
*/
@ApiModelProperty(name = "avatar", value = "头像", dataType = "String")
private String avatar;
/**
* 用户网站
*/
@ApiModelProperty(name = "website", value = "用户网站", dataType = "String")
private String website;
/**
* 所属主体id
*/
@ApiModelProperty(name = "affiliationId", value = "所属主体id", dataType = "Integer")
private Integer affiliationId;
/**
* 评论内容
*/
@ApiModelProperty(name = "commentContent", value = "评论内容", dataType = "String")
private String commentContent;
/**
* 被回复用户id
*/
@ApiModelProperty(name = "replyUserId", value = "被回复用户id", dataType = "Integer")
private Integer replyUserId;
/**
* 被回复用户名
*/
@ApiModelProperty(name = "replyNickname", value = "被回复用户名", dataType = "String")
private String replyNickname;
/**
* 被回复用户网站
*/
@ApiModelProperty(name = "replyWebsite", value = "被回复用户网站", dataType = "String")
private String replyWebsite;
/**
* 父评论id
*/
@ApiModelProperty(name = "parentId", value = "父评论id", dataType = "Integer")
private Integer parentId;
/**
* 顶级评论id,默认为自身id
*/
@ApiModelProperty(name = "topId", value = "顶级评论id,默认为自身id", dataType = "Integer")
private Integer topId;
/**
* 评论类型 1.文章 2.友链 3.说说
*/
@ApiModelProperty(name = "type", value = "评论类型 1.文章 2.友链 3.说说", dataType = "Integer")
private Integer type;
/**
* 是否审核
*/
@ApiModelProperty(name = "isReview", value = "是否审核", dataType = "Boolean")
private Boolean isReview;
/**
* 创建时间
*/
@ApiModelProperty(name = "createTime", value = "创建时间", dataType = "LocalDateTime")
private LocalDateTime createTime;
/**
* 点赞量
*/
@ApiModelProperty(name = "likeCount", value = "点赞量", dataType = "Integer")
private Integer likeCount;
/**
* 回复量
*/
@ApiModelProperty(name = "replyCount", value = "回复量", dataType = "Integer")
private Integer replyCount;
/**
* 当前评论的回复
*/
@ApiModelProperty(name = "replyList", value = "当前评论的回复", dataType = "List<CommentHomeVO>")
private List<CommentHomeVO> replyList;
}
| 23DAY01/blog_23DAY | src/main/java/site/day/blog/pojo/vo/CommentHomeVO.java | 900 | /**
* 是否审核
*/ | block_comment | zh-cn | package site.day.blog.pojo.vo;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @ClassName CommentVO
* @Author 23DAY
* @Date 2023/01/18 20:48
* @Version 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "CommentHomeVO", description = "评论表")
public class CommentHomeVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(name = "id", value = "主键", dataType = "Integer")
private Integer id;
/**
* 评论用户Id
*/
@ApiModelProperty(name = "userId", value = "评论用户Id", dataType = "Integer")
private Integer userId;
/**
* 用户名
*/
@ApiModelProperty(name = "nickName", value = "用户名", dataType = "String")
private String nickName;
/**
* 头像
*/
@ApiModelProperty(name = "avatar", value = "头像", dataType = "String")
private String avatar;
/**
* 用户网站
*/
@ApiModelProperty(name = "website", value = "用户网站", dataType = "String")
private String website;
/**
* 所属主体id
*/
@ApiModelProperty(name = "affiliationId", value = "所属主体id", dataType = "Integer")
private Integer affiliationId;
/**
* 评论内容
*/
@ApiModelProperty(name = "commentContent", value = "评论内容", dataType = "String")
private String commentContent;
/**
* 被回复用户id
*/
@ApiModelProperty(name = "replyUserId", value = "被回复用户id", dataType = "Integer")
private Integer replyUserId;
/**
* 被回复用户名
*/
@ApiModelProperty(name = "replyNickname", value = "被回复用户名", dataType = "String")
private String replyNickname;
/**
* 被回复用户网站
*/
@ApiModelProperty(name = "replyWebsite", value = "被回复用户网站", dataType = "String")
private String replyWebsite;
/**
* 父评论id
*/
@ApiModelProperty(name = "parentId", value = "父评论id", dataType = "Integer")
private Integer parentId;
/**
* 顶级评论id,默认为自身id
*/
@ApiModelProperty(name = "topId", value = "顶级评论id,默认为自身id", dataType = "Integer")
private Integer topId;
/**
* 评论类型 1.文章 2.友链 3.说说
*/
@ApiModelProperty(name = "type", value = "评论类型 1.文章 2.友链 3.说说", dataType = "Integer")
private Integer type;
/**
* 是否审 <SUF>*/
@ApiModelProperty(name = "isReview", value = "是否审核", dataType = "Boolean")
private Boolean isReview;
/**
* 创建时间
*/
@ApiModelProperty(name = "createTime", value = "创建时间", dataType = "LocalDateTime")
private LocalDateTime createTime;
/**
* 点赞量
*/
@ApiModelProperty(name = "likeCount", value = "点赞量", dataType = "Integer")
private Integer likeCount;
/**
* 回复量
*/
@ApiModelProperty(name = "replyCount", value = "回复量", dataType = "Integer")
private Integer replyCount;
/**
* 当前评论的回复
*/
@ApiModelProperty(name = "replyList", value = "当前评论的回复", dataType = "List<CommentHomeVO>")
private List<CommentHomeVO> replyList;
}
| 0 |
41704_2 |
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class jim{
static final JFrame jm=new JFrame();
static int cssd=0;
static int cszd=100;
static JLabel zidan=new JLabel("剩余子弹:"+String.valueOf(cszd));
static JLabel shadi=new JLabel("杀敌数:"+String.valueOf(cssd));
//英雄级
private static int w=0;
private Timer timer;
private static JLabel a;
private static ImageIcon icon;
private static int x;
private static int y;
//敌机
private static JLabel a2[]=new JLabel[4];
private static int x1[]=new int[4];
private static int y1[]=new int[4];
private static ImageIcon icon1[]=new ImageIcon[4];
//子弹
private static JLabel a3[]=new JLabel[100];
private static int x2[]=new int[100];
private static int y2[]=new int[100];
private static ImageIcon icon2[]=new ImageIcon[100];
static{
try{
zidan.setBounds(0, 0, 100, 50);
shadi.setBounds(0, 50, 100, 50);
a=new JLabel();
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
x=(500-icon.getIconWidth())/2;
y=980-icon.getIconHeight();
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
for(int i=0;i<4;i++){
a2[i]=new JLabel();
icon1[i]=new ImageIcon("airplane.png");
a2[i].setIcon(icon1[i]);
x1[i]=new Random().nextInt(500);
y1[i]=-icon1[i].getIconHeight()-i*100;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
}
for(int i=0;i<100;i++){
a3[i]=new JLabel();
icon2[i]=new ImageIcon("bullet.png");
a3[i].setIcon(icon2[i]);
}
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
/*x2=x+icon.getIconWidth()/2;
y2=y;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/
timer = new Timer(); //创建定时器对象
timer.schedule(new TimerTask(){
@Override
public void run(){ //定时干的那个事-每10毫秒走一次
for(int i=0;i<4;i++){
x1[i]+=i-1;
y1[i]+=2;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
if(x1[i]>=x&&x1[i]<=x+icon.getIconWidth()&&y1[i]>=y&&y1[i]<=y+icon.getIconHeight()){
x1[i]=new Random().nextInt(500);
y1[i]=-icon1[i].getIconHeight()-i*100;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
x=10000;
y=10000;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight());
jm.setVisible(false);
new shibai();
}
if(x1[i]>500||y1[i]>980){
x1[i]=new Random().nextInt(500);
y1[i]=-icon1[i].getIconHeight()-i*100;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
}
}
/*y2-=2;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/
/*if(x2>=x1&&x2<=x1+icon1.getIconWidth()&&y2>=y1&&y2<y1+icon1.getIconHeight()){
x2=x+icon.getIconWidth()/2;
y2=y;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );
x1=new Random().nextInt(500);
y1=-icon1.getIconHeight();
a2.setBounds(x1, y1, icon1.getIconWidth(),icon1.getIconHeight() );
}*/
/*if(y2<0){
x2=x+icon.getIconWidth()/2;
y2=y;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );
}
*/
}
},10,10);
}
public void run1(final int i){
x2[i]=x+icon.getIconWidth()/2;
y2[i]=y;
a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() );
timer = new Timer(); //创建定时器对象
timer.schedule(new TimerTask(){
public void run(){ //定时干的那个事-每10毫秒走一次
y2[i]-=2;
a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() );
for(int j=0;j<4;j++){
if(x2[i]>=x1[j]&&x2[i]<=x1[j]+icon1[j].getIconWidth()&&y2[i]>=y1[j]&&y2[i]<y1[j]+icon1[j].getIconHeight()){
x2[i]=-100;
y2[i]=-100;
a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() );
x1[j]=new Random().nextInt(500);
y1[j]=-icon1[j].getIconHeight()-i*100;
a2[j].setBounds(x1[j], y1[j], icon1[j].getIconWidth(),icon1[j].getIconHeight() );
cssd=cssd-1;
shadi.setText("杀敌数:"+String.valueOf(cssd));
}
}
}
},10,10);
}
public static void main(String[] agrs){
jm.setBounds(0,0,500,1000);
jm.setLayout(null);
jm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭操作(窗口关闭时退出程序)
jm.setLocationRelativeTo(null); //设置窗口初始位置(居中)
jm.setVisible(true);
for(int i=0;i<4;i++){
jm.add(a2[i]);
}
jm.add(a);
jm.add(zidan);
jm.add(shadi);
new jim().run();
jm.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
{
if(e.getKeyCode()==KeyEvent.VK_A){
if(x>0){
x-=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero0.png");
a.setIcon(icon);
}
}
else if(e.getKeyCode()==KeyEvent.VK_W){
if(y>0){
y-=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero0.png");
a.setIcon(icon);
}
}
else if(e.getKeyCode()==KeyEvent.VK_S){
if(y<980-icon.getIconHeight()){
y+=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
}
else if(e.getKeyCode()==KeyEvent.VK_D){
if(x<485-icon.getIconWidth()){
x+=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero0.png");
a.setIcon(icon);
}
}else if(e.getKeyCode()==KeyEvent.VK_J){
cszd=cszd-1;
zidan.setText("剩余子弹:"+String.valueOf(cszd));
if(w>=100){
x=10000;
y=10000;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight());
jm.setVisible(false);
new shibai();
}else{
jm.add(a3[w]);
new jim().run1(w);
w=w+1;
}
}
}
}
public void keyReleased(KeyEvent e){
{
if(e.getKeyCode()==KeyEvent.VK_A){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
else if(e.getKeyCode()==KeyEvent.VK_W){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
else if(e.getKeyCode()==KeyEvent.VK_S){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
else if(e.getKeyCode()==KeyEvent.VK_D){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
}
}
});
}
}
| 2425358736/ProjectPackage | aircraftWar/src/jim.java | 2,737 | //创建定时器对象 | line_comment | zh-cn |
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class jim{
static final JFrame jm=new JFrame();
static int cssd=0;
static int cszd=100;
static JLabel zidan=new JLabel("剩余子弹:"+String.valueOf(cszd));
static JLabel shadi=new JLabel("杀敌数:"+String.valueOf(cssd));
//英雄级
private static int w=0;
private Timer timer;
private static JLabel a;
private static ImageIcon icon;
private static int x;
private static int y;
//敌机
private static JLabel a2[]=new JLabel[4];
private static int x1[]=new int[4];
private static int y1[]=new int[4];
private static ImageIcon icon1[]=new ImageIcon[4];
//子弹
private static JLabel a3[]=new JLabel[100];
private static int x2[]=new int[100];
private static int y2[]=new int[100];
private static ImageIcon icon2[]=new ImageIcon[100];
static{
try{
zidan.setBounds(0, 0, 100, 50);
shadi.setBounds(0, 50, 100, 50);
a=new JLabel();
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
x=(500-icon.getIconWidth())/2;
y=980-icon.getIconHeight();
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
for(int i=0;i<4;i++){
a2[i]=new JLabel();
icon1[i]=new ImageIcon("airplane.png");
a2[i].setIcon(icon1[i]);
x1[i]=new Random().nextInt(500);
y1[i]=-icon1[i].getIconHeight()-i*100;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
}
for(int i=0;i<100;i++){
a3[i]=new JLabel();
icon2[i]=new ImageIcon("bullet.png");
a3[i].setIcon(icon2[i]);
}
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
/*x2=x+icon.getIconWidth()/2;
y2=y;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/
timer = new Timer(); //创建 <SUF>
timer.schedule(new TimerTask(){
@Override
public void run(){ //定时干的那个事-每10毫秒走一次
for(int i=0;i<4;i++){
x1[i]+=i-1;
y1[i]+=2;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
if(x1[i]>=x&&x1[i]<=x+icon.getIconWidth()&&y1[i]>=y&&y1[i]<=y+icon.getIconHeight()){
x1[i]=new Random().nextInt(500);
y1[i]=-icon1[i].getIconHeight()-i*100;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
x=10000;
y=10000;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight());
jm.setVisible(false);
new shibai();
}
if(x1[i]>500||y1[i]>980){
x1[i]=new Random().nextInt(500);
y1[i]=-icon1[i].getIconHeight()-i*100;
a2[i].setBounds(x1[i], y1[i], icon1[i].getIconWidth(),icon1[i].getIconHeight() );
}
}
/*y2-=2;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );*/
/*if(x2>=x1&&x2<=x1+icon1.getIconWidth()&&y2>=y1&&y2<y1+icon1.getIconHeight()){
x2=x+icon.getIconWidth()/2;
y2=y;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );
x1=new Random().nextInt(500);
y1=-icon1.getIconHeight();
a2.setBounds(x1, y1, icon1.getIconWidth(),icon1.getIconHeight() );
}*/
/*if(y2<0){
x2=x+icon.getIconWidth()/2;
y2=y;
a3.setBounds(x2, y2, icon2.getIconWidth(),icon2.getIconHeight() );
}
*/
}
},10,10);
}
public void run1(final int i){
x2[i]=x+icon.getIconWidth()/2;
y2[i]=y;
a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() );
timer = new Timer(); //创建定时器对象
timer.schedule(new TimerTask(){
public void run(){ //定时干的那个事-每10毫秒走一次
y2[i]-=2;
a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() );
for(int j=0;j<4;j++){
if(x2[i]>=x1[j]&&x2[i]<=x1[j]+icon1[j].getIconWidth()&&y2[i]>=y1[j]&&y2[i]<y1[j]+icon1[j].getIconHeight()){
x2[i]=-100;
y2[i]=-100;
a3[i].setBounds(x2[i], y2[i], icon2[i].getIconWidth(),icon2[i].getIconHeight() );
x1[j]=new Random().nextInt(500);
y1[j]=-icon1[j].getIconHeight()-i*100;
a2[j].setBounds(x1[j], y1[j], icon1[j].getIconWidth(),icon1[j].getIconHeight() );
cssd=cssd-1;
shadi.setText("杀敌数:"+String.valueOf(cssd));
}
}
}
},10,10);
}
public static void main(String[] agrs){
jm.setBounds(0,0,500,1000);
jm.setLayout(null);
jm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭操作(窗口关闭时退出程序)
jm.setLocationRelativeTo(null); //设置窗口初始位置(居中)
jm.setVisible(true);
for(int i=0;i<4;i++){
jm.add(a2[i]);
}
jm.add(a);
jm.add(zidan);
jm.add(shadi);
new jim().run();
jm.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
{
if(e.getKeyCode()==KeyEvent.VK_A){
if(x>0){
x-=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero0.png");
a.setIcon(icon);
}
}
else if(e.getKeyCode()==KeyEvent.VK_W){
if(y>0){
y-=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero0.png");
a.setIcon(icon);
}
}
else if(e.getKeyCode()==KeyEvent.VK_S){
if(y<980-icon.getIconHeight()){
y+=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
}
else if(e.getKeyCode()==KeyEvent.VK_D){
if(x<485-icon.getIconWidth()){
x+=10;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight() );
icon=new ImageIcon("hero0.png");
a.setIcon(icon);
}
}else if(e.getKeyCode()==KeyEvent.VK_J){
cszd=cszd-1;
zidan.setText("剩余子弹:"+String.valueOf(cszd));
if(w>=100){
x=10000;
y=10000;
a.setBounds(x, y, icon.getIconWidth(),icon.getIconHeight());
jm.setVisible(false);
new shibai();
}else{
jm.add(a3[w]);
new jim().run1(w);
w=w+1;
}
}
}
}
public void keyReleased(KeyEvent e){
{
if(e.getKeyCode()==KeyEvent.VK_A){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
else if(e.getKeyCode()==KeyEvent.VK_W){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
else if(e.getKeyCode()==KeyEvent.VK_S){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
else if(e.getKeyCode()==KeyEvent.VK_D){
icon=new ImageIcon("hero1.png");
a.setIcon(icon);
}
}
}
});
}
}
| 0 |
27745_23 | package dao;
import cn.itcast.jdbc.TxQueryRunner;
import domain.Customer;
import domain.pageBean;
import org.apache.commons.collections.buffer.CircularFifoBuffer;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.spi.CurrencyNameProvider;
/**
* dao是Data Access Object的缩写(数据访问接口),进行数据库相关操作
* TxQueryRunner它是QueryRunner的子类!(引自commons-dbutils.jar)
* 可用起来与QueryRunner相似的!
* 支持事务!它底层使用了JdbcUtils来获取连接!
*
* 简化jdbc的操作
* QueryRunner的三个方法:
* * update() --> insert、update、delete
* * query() --> select
* * batch() --> 批处理
* 详细信息请查看“关于引入第三方包的说明.txt”
*/
public class CustomerDao {
private QueryRunner qr=new TxQueryRunner(); //没有给对象提供连接池
//使用sql添加客户信息
public void add(Customer c) {
try {
String sql = "insert into t_customer values(?,?,?,?,?,?)";
Object[] paramas = {c.getId(), c.getName(), c.getGender(), c.getPhone(),
c.getEmail(), c.getDescription()}; //要确保数据顺序与数据库中插入元素顺序一致
qr.update(sql, paramas); //更新数据库,执行sql,不提供连接,它内部会使用JdbcUtils来获取连接
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//查询所有
public pageBean<Customer> findAll(int pageNum,int pageRecord){
/**
* 创建pb对象
* 设置pb的(当前页码)pageNum和(每页记录数)pageRecord
* 得到(总记录数)totalRecord,设置给pb
* 得到(当前页面记录数)beanlist,赋值给pb
* 最后返回pb
*
* 实际上没有使用这个方法,而是用下面的query方法
* query方法包含了findAll方法的这种情况(即传递的参数都为空)
*/
try{
pageBean<Customer> pb=new pageBean<Customer>();
pb.setPageNum(pageNum);
pb.setPageRecord(pageRecord);
String sql="select count(*) from t_customer";
Number number=(Number) qr.query(sql,new ScalarHandler<>()); //ScalarHandler参数为空,返回第一行第一列的数据
int totalRecord=number.intValue(); //总记录数
pb.setTotalRecord(totalRecord);
//sql="select * from t_customer order by name limit ?,?"; //mysql数据库中 :从第m行开始,向下取第n行的写法
/**sqlserver 分页写法(使用于sqlserver2012以上)
* 要取从第m行开始之后n行的记录时
* 固定传递每页的记录数
* 可以按某一属性排序(order by)
*/
StringBuilder firstSql=new StringBuilder("select * from t_customer");
StringBuilder whereSql=new StringBuilder(" where 1=1 ");
StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only");
List<Object> params=new ArrayList<>();
params.add((pageNum-1)*pageRecord);
params.add(pageRecord);
List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray());
//Object[] params={pageRecord,(pageNum-1)*pageRecord}; //第m行开始后n行数据,即每一页固定显示的数据
//List<Customer> beanList=qr.query(sql,new BeanListHandler<>(Customer.class),params);//获取结果集的第一行数据,并将其封装到JavaBean对象
pb.setBeanList(beanList);
return pb;
}catch(Exception e){
throw new RuntimeException(e);
}
}
//根据id查询加载客户
public Customer find(String id){
try{
String sql="select * from t_customer where id=?";
return qr.query(sql,new BeanHandler<Customer>(Customer.class),id);//同上面注释
}catch(Exception e){
throw new RuntimeException(e);
}
}
//修改操作
public void edit(Customer customer){
try{
String sql="update t_customer set name=?,gender=?,phone=?,email=?,description=? where id=?";
Object[] params={customer.getName(),customer.getGender(),customer.getPhone(),customer.getEmail(),customer.getDescription(),customer.getId()};
qr.update(sql,params);
}catch(Exception e){
throw new RuntimeException(e);
}
}
//删除操作
public void delete(String id){
try{
String sql="delete from t_customer where id=?";
qr.update(sql,id);
}catch(Exception e){
throw new RuntimeException(e);
}
}
//多条件组合查询
public pageBean<Customer> query(Customer customer,int pageNum,int pageRecord){
try{
pageBean<Customer> pb=new pageBean<Customer>();
pb.setPageNum(pageNum);
pb.setPageRecord(pageRecord);
StringBuilder cntSql=new StringBuilder("select count(*) from t_customer"); //StringBuilder对象为动态对象,允许扩充它所封装字符串中字符的数量
StringBuilder whereSql=new StringBuilder(" where 1=1 "); //条件始终为true,在不定数量查询条件下,可以很好的规范语句
List<Object> params=new ArrayList<>(); //创建一个ArrayList,用来装载参数值
//按名字查询
String name=customer.getName();
if(name!=null && !name.trim().isEmpty()){
whereSql.append(" and name like ? ");
params.add("%"+name+"%"); //模糊查询,含有输入的name的字符串都会被找出
}
//按性别查询
String gender=customer.getGender();
if(gender!=null && !gender.trim().isEmpty()){
whereSql.append(" and gender=? ");
params.add(gender);
}
//按电话号码查询
String phone=customer.getPhone();
if(phone!=null && !phone.trim().isEmpty()){
whereSql.append(" and phone like ? ");
params.add("%"+phone+"%"); //模糊查询,含有输入的phone的字符串都会被找出
}
//按邮箱查询
String email=customer.getEmail();
if(email!=null && !email.trim().isEmpty()){
whereSql.append(" and email like ? ");
params.add("%"+email+"%"); //模糊查询,含有输入的email的字符串都会被找出
}
//得到总记录数,赋给totalRecord
Number num=qr.query(cntSql.append(whereSql).toString(),new ScalarHandler<>(),params.toArray());
int totalRecord=num.intValue();
pb.setTotalRecord(totalRecord);
//取每一页的记录
StringBuilder firstSql=new StringBuilder("select * from t_customer");
StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only");
params.add((pageNum-1)*pageRecord);
params.add(pageRecord);
List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray());
pb.setBeanList(beanList);
return pb;
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
| 2427595858/Customer-Information-Management | src/dao/CustomerDao.java | 1,827 | //按性别查询 | line_comment | zh-cn | package dao;
import cn.itcast.jdbc.TxQueryRunner;
import domain.Customer;
import domain.pageBean;
import org.apache.commons.collections.buffer.CircularFifoBuffer;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.spi.CurrencyNameProvider;
/**
* dao是Data Access Object的缩写(数据访问接口),进行数据库相关操作
* TxQueryRunner它是QueryRunner的子类!(引自commons-dbutils.jar)
* 可用起来与QueryRunner相似的!
* 支持事务!它底层使用了JdbcUtils来获取连接!
*
* 简化jdbc的操作
* QueryRunner的三个方法:
* * update() --> insert、update、delete
* * query() --> select
* * batch() --> 批处理
* 详细信息请查看“关于引入第三方包的说明.txt”
*/
public class CustomerDao {
private QueryRunner qr=new TxQueryRunner(); //没有给对象提供连接池
//使用sql添加客户信息
public void add(Customer c) {
try {
String sql = "insert into t_customer values(?,?,?,?,?,?)";
Object[] paramas = {c.getId(), c.getName(), c.getGender(), c.getPhone(),
c.getEmail(), c.getDescription()}; //要确保数据顺序与数据库中插入元素顺序一致
qr.update(sql, paramas); //更新数据库,执行sql,不提供连接,它内部会使用JdbcUtils来获取连接
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//查询所有
public pageBean<Customer> findAll(int pageNum,int pageRecord){
/**
* 创建pb对象
* 设置pb的(当前页码)pageNum和(每页记录数)pageRecord
* 得到(总记录数)totalRecord,设置给pb
* 得到(当前页面记录数)beanlist,赋值给pb
* 最后返回pb
*
* 实际上没有使用这个方法,而是用下面的query方法
* query方法包含了findAll方法的这种情况(即传递的参数都为空)
*/
try{
pageBean<Customer> pb=new pageBean<Customer>();
pb.setPageNum(pageNum);
pb.setPageRecord(pageRecord);
String sql="select count(*) from t_customer";
Number number=(Number) qr.query(sql,new ScalarHandler<>()); //ScalarHandler参数为空,返回第一行第一列的数据
int totalRecord=number.intValue(); //总记录数
pb.setTotalRecord(totalRecord);
//sql="select * from t_customer order by name limit ?,?"; //mysql数据库中 :从第m行开始,向下取第n行的写法
/**sqlserver 分页写法(使用于sqlserver2012以上)
* 要取从第m行开始之后n行的记录时
* 固定传递每页的记录数
* 可以按某一属性排序(order by)
*/
StringBuilder firstSql=new StringBuilder("select * from t_customer");
StringBuilder whereSql=new StringBuilder(" where 1=1 ");
StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only");
List<Object> params=new ArrayList<>();
params.add((pageNum-1)*pageRecord);
params.add(pageRecord);
List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray());
//Object[] params={pageRecord,(pageNum-1)*pageRecord}; //第m行开始后n行数据,即每一页固定显示的数据
//List<Customer> beanList=qr.query(sql,new BeanListHandler<>(Customer.class),params);//获取结果集的第一行数据,并将其封装到JavaBean对象
pb.setBeanList(beanList);
return pb;
}catch(Exception e){
throw new RuntimeException(e);
}
}
//根据id查询加载客户
public Customer find(String id){
try{
String sql="select * from t_customer where id=?";
return qr.query(sql,new BeanHandler<Customer>(Customer.class),id);//同上面注释
}catch(Exception e){
throw new RuntimeException(e);
}
}
//修改操作
public void edit(Customer customer){
try{
String sql="update t_customer set name=?,gender=?,phone=?,email=?,description=? where id=?";
Object[] params={customer.getName(),customer.getGender(),customer.getPhone(),customer.getEmail(),customer.getDescription(),customer.getId()};
qr.update(sql,params);
}catch(Exception e){
throw new RuntimeException(e);
}
}
//删除操作
public void delete(String id){
try{
String sql="delete from t_customer where id=?";
qr.update(sql,id);
}catch(Exception e){
throw new RuntimeException(e);
}
}
//多条件组合查询
public pageBean<Customer> query(Customer customer,int pageNum,int pageRecord){
try{
pageBean<Customer> pb=new pageBean<Customer>();
pb.setPageNum(pageNum);
pb.setPageRecord(pageRecord);
StringBuilder cntSql=new StringBuilder("select count(*) from t_customer"); //StringBuilder对象为动态对象,允许扩充它所封装字符串中字符的数量
StringBuilder whereSql=new StringBuilder(" where 1=1 "); //条件始终为true,在不定数量查询条件下,可以很好的规范语句
List<Object> params=new ArrayList<>(); //创建一个ArrayList,用来装载参数值
//按名字查询
String name=customer.getName();
if(name!=null && !name.trim().isEmpty()){
whereSql.append(" and name like ? ");
params.add("%"+name+"%"); //模糊查询,含有输入的name的字符串都会被找出
}
//按性 <SUF>
String gender=customer.getGender();
if(gender!=null && !gender.trim().isEmpty()){
whereSql.append(" and gender=? ");
params.add(gender);
}
//按电话号码查询
String phone=customer.getPhone();
if(phone!=null && !phone.trim().isEmpty()){
whereSql.append(" and phone like ? ");
params.add("%"+phone+"%"); //模糊查询,含有输入的phone的字符串都会被找出
}
//按邮箱查询
String email=customer.getEmail();
if(email!=null && !email.trim().isEmpty()){
whereSql.append(" and email like ? ");
params.add("%"+email+"%"); //模糊查询,含有输入的email的字符串都会被找出
}
//得到总记录数,赋给totalRecord
Number num=qr.query(cntSql.append(whereSql).toString(),new ScalarHandler<>(),params.toArray());
int totalRecord=num.intValue();
pb.setTotalRecord(totalRecord);
//取每一页的记录
StringBuilder firstSql=new StringBuilder("select * from t_customer");
StringBuilder nextSql=new StringBuilder(" order by id offset ? row fetch next ? row only");
params.add((pageNum-1)*pageRecord);
params.add(pageRecord);
List<Customer> beanList=qr.query(firstSql.append(whereSql).append(nextSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray());
pb.setBeanList(beanList);
return pb;
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
| 0 |
46687_5 | package com.xy.xydoctor.bean.community_manamer;
import java.io.Serializable;
import java.util.List;
/**
* Author: LYD
* Date: 2021/9/10 9:37
* Description:
*/
public class SearchInfo implements Serializable {
/**
*
*/
private String userid;
/**
*
*/
private String nickname="";
/**
* 手机号
*/
private String tel="";
/**
* 身份证
*/
private String idcard="";
/**
*
*/
private String sex = "0";
/**
*
*/
private String age="";
/**
*
*/
private String birthtime="";
/**
* 糖尿病类型
*/
private String diabeteslei;
/**
* 高血压 0:无 1:一级 2:二级 在家庭成员model中
* 这个仅表示为是否高血压
*/
private String hypertension;
/**
* 血压等级 1:一级 2:二级
*/
private String bloodLevel;
/**
* 医院id
*/
private String hos_userid;
private String house_id;
private String build_id;
/**
* 医院名字
*/
private String hospitalname;
/**
* 科室id
*/
private String dep_userid;
/**
* 科室名字
*/
private String depname;
/**
* 医生id
*/
private String doc_id;
/**
* 医生名字
*/
private String docname;
/**
* 血糖仪设备号
*/
private String sugar_imei;
/**
* 血压设备号
*/
private String blood_imei;
/**
* 冠心病 1是 2否
*/
private String coronary;
/**
* 脂肪肝 1是 2否
*/
private String fattyliver;
/**
* 肥胖 1是 2否
*/
private String fat;
/**
* 脑卒中 1是 2否
*/
private String stroke;
/**
* 党员 1是 2否
*/
private String party_member;
/**
* 残疾 1是 2否
*/
private String disability;
/**
* 低保
*/
private String dibao;
/**
* 重慢病
*/
private String scd;
/**
* 特殊家庭
*/
private String special_family;
/**
* 疫情防控
*/
private String epidemic;
/**
* 精神病 1是 2否
*/
private String mental_illness;
/**
* 怀孕
*/
private String pregnant;
/**
* 结核
*/
private String tuberculosis;
/**
* 关注 1是 2否
*/
private String iscare;
private DepartmentInfo hospital;
private DepartmentInfo hosInfo;
/**
* 楼栋信息
*/
private String houseinfo;
/**
* 随访状态,
* 0:不显示待随访
* 1:显示待随访
*/
private String follow_status;
/**
* 血糖数据是否为空
* 1:为空
* 2:不为空
*/
private String sugarEmpty;
/**
* 血压数据是否为空
* 1:为空
* 2:不为空
*/
private String bloodEmpty;
/**
* 血糖值
*/
private String glucosevalue;
/**
* 时间
*/
private String datetime;
/**
* 测量时间点 早餐后
*/
private String category;
/**
* 1偏高 2偏低 3正常
*/
private String ishight;
/**
* 收缩
*/
private String systolic;
/**
* 舒张
*/
private String diastole;
/**
* 户主关系 1 户主 2配偶 3子女 4儿媳 5女婿 6父母 0其他
*/
private String relation;
/**
* 小区的名字
*/
private String com_name;
/**
* 单元的名字
*/
private String unit_name;
/**
* 楼号的名字
*/
private String build_name;
/**
* 房间的名字
*/
private String housenum;
/**
* 房间号
*/
private String house_num;
/**
* 是否死亡
*/
private String isdeath;
/**
* 位置信息
*/
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getIsdeath() {
return isdeath;
}
public void setIsdeath(String isdeath) {
this.isdeath = isdeath;
}
public String getEpidemic() {
return epidemic;
}
public void setEpidemic(String epidemic) {
this.epidemic = epidemic;
}
public String getSpecial_family() {
return special_family;
}
public void setSpecial_family(String special_family) {
this.special_family = special_family;
}
public String getScd() {
return scd;
}
public void setScd(String scd) {
this.scd = scd;
}
public String getDibao() {
return dibao;
}
public void setDibao(String dibao) {
this.dibao = dibao;
}
public String getTuberculosis() {
return tuberculosis;
}
public void setTuberculosis(String tuberculosis) {
this.tuberculosis = tuberculosis;
}
public String getPregnant() {
return pregnant;
}
public void setPregnant(String pregnant) {
this.pregnant = pregnant;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getHouse_num() {
return house_num;
}
public void setHouse_num(String house_num) {
this.house_num = house_num;
}
public String getCom_name() {
return com_name;
}
public void setCom_name(String com_name) {
this.com_name = com_name;
}
public String getUnit_name() {
return unit_name;
}
public void setUnit_name(String unit_name) {
this.unit_name = unit_name;
}
public String getBuild_name() {
return build_name;
}
public void setBuild_name(String build_name) {
this.build_name = build_name;
}
public String getHousenum() {
return housenum;
}
public void setHousenum(String housenum) {
this.housenum = housenum;
}
private List<DepartmentInfo> doc_list;
public String getHouse_id() {
return house_id;
}
public void setHouse_id(String house_id) {
this.house_id = house_id;
}
public String getBuild_id() {
return build_id;
}
public void setBuild_id(String build_id) {
this.build_id = build_id;
}
public List<DepartmentInfo> getDoc_list() {
return doc_list;
}
public void setDoc_list(List<DepartmentInfo> doc_list) {
this.doc_list = doc_list;
}
public String getRelation() {
return relation;
}
public void setRelation(String relation) {
this.relation = relation;
}
public String getSystolic() {
return systolic;
}
public void setSystolic(String systolic) {
this.systolic = systolic;
}
public String getDiastole() {
return diastole;
}
public void setDiastole(String diastole) {
this.diastole = diastole;
}
public String getGlucosevalue() {
return glucosevalue;
}
public void setGlucosevalue(String glucosevalue) {
this.glucosevalue = glucosevalue;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getIshight() {
return ishight;
}
public void setIshight(String ishight) {
this.ishight = ishight;
}
private SugarOrPressureInfo sugar;
private SugarOrPressureInfo blood;
private List<String> img;
private String sugar_follow;
private String blood_follow;
public String getSugar_follow() {
return sugar_follow;
}
public void setSugar_follow(String sugar_follow) {
this.sugar_follow = sugar_follow;
}
public String getBlood_follow() {
return blood_follow;
}
public void setBlood_follow(String blood_follow) {
this.blood_follow = blood_follow;
}
public String getBloodLevel() {
return bloodLevel;
}
public void setBloodLevel(String bloodLevel) {
this.bloodLevel = bloodLevel;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getHouseinfo() {
return houseinfo;
}
public void setHouseinfo(String houseinfo) {
this.houseinfo = houseinfo;
}
public String getFollow_status() {
return follow_status;
}
public void setFollow_status(String follow_status) {
this.follow_status = follow_status;
}
public String getSugarEmpty() {
return sugarEmpty;
}
public void setSugarEmpty(String sugarEmpty) {
this.sugarEmpty = sugarEmpty;
}
public String getBloodEmpty() {
return bloodEmpty;
}
public void setBloodEmpty(String bloodEmpty) {
this.bloodEmpty = bloodEmpty;
}
public List<String> getImg() {
return img;
}
public void setImg(List<String> img) {
this.img = img;
}
public SugarOrPressureInfo getSugar() {
return sugar;
}
public void setSugar(SugarOrPressureInfo sugar) {
this.sugar = sugar;
}
public SugarOrPressureInfo getBlood() {
return blood;
}
public void setBlood(SugarOrPressureInfo blood) {
this.blood = blood;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthtime() {
return birthtime;
}
public void setBirthtime(String birthtime) {
this.birthtime = birthtime;
}
public String getDiabeteslei() {
return diabeteslei;
}
public void setDiabeteslei(String diabeteslei) {
this.diabeteslei = diabeteslei;
}
public String getHypertension() {
return hypertension;
}
public void setHypertension(String hypertension) {
this.hypertension = hypertension;
}
public String getHos_userid() {
return hos_userid;
}
public void setHos_userid(String hos_userid) {
this.hos_userid = hos_userid;
}
public String getHospitalname() {
return hospitalname;
}
public void setHospitalname(String hospitalname) {
this.hospitalname = hospitalname;
}
public String getDep_userid() {
return dep_userid;
}
public void setDep_userid(String dep_userid) {
this.dep_userid = dep_userid;
}
public String getDepname() {
return depname;
}
public void setDepname(String depname) {
this.depname = depname;
}
public String getDoc_id() {
return doc_id;
}
public void setDoc_id(String doc_id) {
this.doc_id = doc_id;
}
public String getDocname() {
return docname;
}
public void setDocname(String docname) {
this.docname = docname;
}
public String getSugar_imei() {
return sugar_imei;
}
public void setSugar_imei(String sugar_imei) {
this.sugar_imei = sugar_imei;
}
public String getBlood_imei() {
return blood_imei;
}
public void setBlood_imei(String blood_imei) {
this.blood_imei = blood_imei;
}
public String getCoronary() {
return coronary;
}
public void setCoronary(String coronary) {
this.coronary = coronary;
}
public String getFattyliver() {
return fattyliver;
}
public void setFattyliver(String fattyliver) {
this.fattyliver = fattyliver;
}
public String getFat() {
return fat;
}
public void setFat(String fat) {
this.fat = fat;
}
public String getStroke() {
return stroke;
}
public void setStroke(String stroke) {
this.stroke = stroke;
}
public String getParty_member() {
return party_member;
}
public void setParty_member(String party_member) {
this.party_member = party_member;
}
public String getDisability() {
return disability;
}
public void setDisability(String disability) {
this.disability = disability;
}
public String getMental_illness() {
return mental_illness;
}
public void setMental_illness(String mental_illness) {
this.mental_illness = mental_illness;
}
public String getIscare() {
return iscare;
}
public void setIscare(String iscare) {
this.iscare = iscare;
}
public DepartmentInfo getHospital() {
return hospital;
}
public void setHospital(DepartmentInfo hospital) {
this.hospital = hospital;
}
public DepartmentInfo getHosInfo() {
return hosInfo;
}
public void setHosInfo(DepartmentInfo hosInfo) {
this.hosInfo = hosInfo;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
}
| 243640yinyisen243640/MyXyDoctor | app/src/main/java/com/xy/xydoctor/bean/community_manamer/SearchInfo.java | 3,676 | /**
* 血压等级 1:一级 2:二级
*/ | block_comment | zh-cn | package com.xy.xydoctor.bean.community_manamer;
import java.io.Serializable;
import java.util.List;
/**
* Author: LYD
* Date: 2021/9/10 9:37
* Description:
*/
public class SearchInfo implements Serializable {
/**
*
*/
private String userid;
/**
*
*/
private String nickname="";
/**
* 手机号
*/
private String tel="";
/**
* 身份证
*/
private String idcard="";
/**
*
*/
private String sex = "0";
/**
*
*/
private String age="";
/**
*
*/
private String birthtime="";
/**
* 糖尿病类型
*/
private String diabeteslei;
/**
* 高血压 0:无 1:一级 2:二级 在家庭成员model中
* 这个仅表示为是否高血压
*/
private String hypertension;
/**
* 血压等 <SUF>*/
private String bloodLevel;
/**
* 医院id
*/
private String hos_userid;
private String house_id;
private String build_id;
/**
* 医院名字
*/
private String hospitalname;
/**
* 科室id
*/
private String dep_userid;
/**
* 科室名字
*/
private String depname;
/**
* 医生id
*/
private String doc_id;
/**
* 医生名字
*/
private String docname;
/**
* 血糖仪设备号
*/
private String sugar_imei;
/**
* 血压设备号
*/
private String blood_imei;
/**
* 冠心病 1是 2否
*/
private String coronary;
/**
* 脂肪肝 1是 2否
*/
private String fattyliver;
/**
* 肥胖 1是 2否
*/
private String fat;
/**
* 脑卒中 1是 2否
*/
private String stroke;
/**
* 党员 1是 2否
*/
private String party_member;
/**
* 残疾 1是 2否
*/
private String disability;
/**
* 低保
*/
private String dibao;
/**
* 重慢病
*/
private String scd;
/**
* 特殊家庭
*/
private String special_family;
/**
* 疫情防控
*/
private String epidemic;
/**
* 精神病 1是 2否
*/
private String mental_illness;
/**
* 怀孕
*/
private String pregnant;
/**
* 结核
*/
private String tuberculosis;
/**
* 关注 1是 2否
*/
private String iscare;
private DepartmentInfo hospital;
private DepartmentInfo hosInfo;
/**
* 楼栋信息
*/
private String houseinfo;
/**
* 随访状态,
* 0:不显示待随访
* 1:显示待随访
*/
private String follow_status;
/**
* 血糖数据是否为空
* 1:为空
* 2:不为空
*/
private String sugarEmpty;
/**
* 血压数据是否为空
* 1:为空
* 2:不为空
*/
private String bloodEmpty;
/**
* 血糖值
*/
private String glucosevalue;
/**
* 时间
*/
private String datetime;
/**
* 测量时间点 早餐后
*/
private String category;
/**
* 1偏高 2偏低 3正常
*/
private String ishight;
/**
* 收缩
*/
private String systolic;
/**
* 舒张
*/
private String diastole;
/**
* 户主关系 1 户主 2配偶 3子女 4儿媳 5女婿 6父母 0其他
*/
private String relation;
/**
* 小区的名字
*/
private String com_name;
/**
* 单元的名字
*/
private String unit_name;
/**
* 楼号的名字
*/
private String build_name;
/**
* 房间的名字
*/
private String housenum;
/**
* 房间号
*/
private String house_num;
/**
* 是否死亡
*/
private String isdeath;
/**
* 位置信息
*/
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getIsdeath() {
return isdeath;
}
public void setIsdeath(String isdeath) {
this.isdeath = isdeath;
}
public String getEpidemic() {
return epidemic;
}
public void setEpidemic(String epidemic) {
this.epidemic = epidemic;
}
public String getSpecial_family() {
return special_family;
}
public void setSpecial_family(String special_family) {
this.special_family = special_family;
}
public String getScd() {
return scd;
}
public void setScd(String scd) {
this.scd = scd;
}
public String getDibao() {
return dibao;
}
public void setDibao(String dibao) {
this.dibao = dibao;
}
public String getTuberculosis() {
return tuberculosis;
}
public void setTuberculosis(String tuberculosis) {
this.tuberculosis = tuberculosis;
}
public String getPregnant() {
return pregnant;
}
public void setPregnant(String pregnant) {
this.pregnant = pregnant;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getHouse_num() {
return house_num;
}
public void setHouse_num(String house_num) {
this.house_num = house_num;
}
public String getCom_name() {
return com_name;
}
public void setCom_name(String com_name) {
this.com_name = com_name;
}
public String getUnit_name() {
return unit_name;
}
public void setUnit_name(String unit_name) {
this.unit_name = unit_name;
}
public String getBuild_name() {
return build_name;
}
public void setBuild_name(String build_name) {
this.build_name = build_name;
}
public String getHousenum() {
return housenum;
}
public void setHousenum(String housenum) {
this.housenum = housenum;
}
private List<DepartmentInfo> doc_list;
public String getHouse_id() {
return house_id;
}
public void setHouse_id(String house_id) {
this.house_id = house_id;
}
public String getBuild_id() {
return build_id;
}
public void setBuild_id(String build_id) {
this.build_id = build_id;
}
public List<DepartmentInfo> getDoc_list() {
return doc_list;
}
public void setDoc_list(List<DepartmentInfo> doc_list) {
this.doc_list = doc_list;
}
public String getRelation() {
return relation;
}
public void setRelation(String relation) {
this.relation = relation;
}
public String getSystolic() {
return systolic;
}
public void setSystolic(String systolic) {
this.systolic = systolic;
}
public String getDiastole() {
return diastole;
}
public void setDiastole(String diastole) {
this.diastole = diastole;
}
public String getGlucosevalue() {
return glucosevalue;
}
public void setGlucosevalue(String glucosevalue) {
this.glucosevalue = glucosevalue;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getIshight() {
return ishight;
}
public void setIshight(String ishight) {
this.ishight = ishight;
}
private SugarOrPressureInfo sugar;
private SugarOrPressureInfo blood;
private List<String> img;
private String sugar_follow;
private String blood_follow;
public String getSugar_follow() {
return sugar_follow;
}
public void setSugar_follow(String sugar_follow) {
this.sugar_follow = sugar_follow;
}
public String getBlood_follow() {
return blood_follow;
}
public void setBlood_follow(String blood_follow) {
this.blood_follow = blood_follow;
}
public String getBloodLevel() {
return bloodLevel;
}
public void setBloodLevel(String bloodLevel) {
this.bloodLevel = bloodLevel;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getHouseinfo() {
return houseinfo;
}
public void setHouseinfo(String houseinfo) {
this.houseinfo = houseinfo;
}
public String getFollow_status() {
return follow_status;
}
public void setFollow_status(String follow_status) {
this.follow_status = follow_status;
}
public String getSugarEmpty() {
return sugarEmpty;
}
public void setSugarEmpty(String sugarEmpty) {
this.sugarEmpty = sugarEmpty;
}
public String getBloodEmpty() {
return bloodEmpty;
}
public void setBloodEmpty(String bloodEmpty) {
this.bloodEmpty = bloodEmpty;
}
public List<String> getImg() {
return img;
}
public void setImg(List<String> img) {
this.img = img;
}
public SugarOrPressureInfo getSugar() {
return sugar;
}
public void setSugar(SugarOrPressureInfo sugar) {
this.sugar = sugar;
}
public SugarOrPressureInfo getBlood() {
return blood;
}
public void setBlood(SugarOrPressureInfo blood) {
this.blood = blood;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthtime() {
return birthtime;
}
public void setBirthtime(String birthtime) {
this.birthtime = birthtime;
}
public String getDiabeteslei() {
return diabeteslei;
}
public void setDiabeteslei(String diabeteslei) {
this.diabeteslei = diabeteslei;
}
public String getHypertension() {
return hypertension;
}
public void setHypertension(String hypertension) {
this.hypertension = hypertension;
}
public String getHos_userid() {
return hos_userid;
}
public void setHos_userid(String hos_userid) {
this.hos_userid = hos_userid;
}
public String getHospitalname() {
return hospitalname;
}
public void setHospitalname(String hospitalname) {
this.hospitalname = hospitalname;
}
public String getDep_userid() {
return dep_userid;
}
public void setDep_userid(String dep_userid) {
this.dep_userid = dep_userid;
}
public String getDepname() {
return depname;
}
public void setDepname(String depname) {
this.depname = depname;
}
public String getDoc_id() {
return doc_id;
}
public void setDoc_id(String doc_id) {
this.doc_id = doc_id;
}
public String getDocname() {
return docname;
}
public void setDocname(String docname) {
this.docname = docname;
}
public String getSugar_imei() {
return sugar_imei;
}
public void setSugar_imei(String sugar_imei) {
this.sugar_imei = sugar_imei;
}
public String getBlood_imei() {
return blood_imei;
}
public void setBlood_imei(String blood_imei) {
this.blood_imei = blood_imei;
}
public String getCoronary() {
return coronary;
}
public void setCoronary(String coronary) {
this.coronary = coronary;
}
public String getFattyliver() {
return fattyliver;
}
public void setFattyliver(String fattyliver) {
this.fattyliver = fattyliver;
}
public String getFat() {
return fat;
}
public void setFat(String fat) {
this.fat = fat;
}
public String getStroke() {
return stroke;
}
public void setStroke(String stroke) {
this.stroke = stroke;
}
public String getParty_member() {
return party_member;
}
public void setParty_member(String party_member) {
this.party_member = party_member;
}
public String getDisability() {
return disability;
}
public void setDisability(String disability) {
this.disability = disability;
}
public String getMental_illness() {
return mental_illness;
}
public void setMental_illness(String mental_illness) {
this.mental_illness = mental_illness;
}
public String getIscare() {
return iscare;
}
public void setIscare(String iscare) {
this.iscare = iscare;
}
public DepartmentInfo getHospital() {
return hospital;
}
public void setHospital(DepartmentInfo hospital) {
this.hospital = hospital;
}
public DepartmentInfo getHosInfo() {
return hosInfo;
}
public void setHosInfo(DepartmentInfo hosInfo) {
this.hosInfo = hosInfo;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
}
| 0 |
41472_4 | package cn.addapp.pickers.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.math.RoundingMode;
import java.net.NetworkInterface;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
private final static long hourLevelValue = 60 * 60 * 1000;
private final static long minuteLevelValue = 60 * 1000;
private final static long secondLevelValue = 1000;
private static String mYear;
private static String mMonth;
private static String mDay;
private static String mWay;
public static boolean isStringDataNull(String checkData) {
if ("".equals(checkData) || checkData == null
|| "null".equals(checkData) || checkData == null) {
return true;
}
return false;
}
public static boolean isListDataNull(List list) {
if (list == null || list.size() <= 0) {
return true;
}
return false;
}
public static String replaceBlankCharacter(String string) {
if (string != null) {
string = string.replace(" ", "");
return string;
}
return null;
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*
* @param pxValue
* @param (DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将sp值转换为px值,保证文字大小不变
*
* @param spValue
* @param (DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
public static boolean isConnect(Context context) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
try {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
// 获取网络连接管理的对象
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 判断当前网络是否已经连接
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
/**
* 获取手机的MAC地址
*
* @return
*/
// public static String getMac() {
// String str = "";
// String macSerial = "";
// try {
// Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
// InputStreamReader ir = new InputStreamReader(pp.getInputStream());
// LineNumberReader input = new LineNumberReader(ir);
//
// for (; null != str;) {
// str = input.readLine();
// if (str != null) {
// macSerial = str.trim();// 去空格
// break;
// }
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// if (null == macSerial || "".equals(macSerial)) {
// try {
// return loadFileAsString("/sys/class/net/eth0/address")
// .toUpperCase().substring(0, 17);
// } catch (Exception e) {
// e.printStackTrace();
// macSerial="02:00:00:00:00:00";
// }
// }
// return macSerial;
// }
public static String getMacAddress() {
String str = "";
String macSerial = "";
try {
Process pp = Runtime.getRuntime().exec(
"cat /sys/class/net/wlan0/address ");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (macSerial == null || "".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/eth0/address")
.toUpperCase().substring(0, 17);
} catch (Exception e) {
e.printStackTrace();
}
}
if (macSerial == null || "".equals(macSerial)) {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
macSerial = "02:00:00:00:00:00";
}
}
return macSerial;
}
public static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
public static String loadReaderAsString(Reader reader) throws Exception {
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
int readLength = reader.read(buffer);
while (readLength >= 0) {
builder.append(buffer, 0, readLength);
readLength = reader.read(buffer);
}
return builder.toString();
}
public static boolean isNull(String str) {
if (str == null || str.equals("")) {
return true;
} else {
return false;
}
}
public static String get2XXDa(double data) {
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.UP);
String d = df.format(data);
if (d.indexOf(".") == 0) {
d = "0" + d;
}
System.out.println(d);
return d;
}
/**
* 向下取整
*
* @param data
* @return
*/
public static String get2XXDown(double data) {
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
// df.setRoundingMode(RoundingMode.DOWN);
String d = df.format(data);
if (d.indexOf(".") == 0) {
d = "0" + d;
}
System.out.println(d);
return d;
}
public static String get2XXDat(double data) {
System.out.println(data);
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.DOWN);
String d = df.format(data);
if (d.indexOf(".") == 0) {
d = "0" + d;
}
System.out.println(d);
return d;
}
public static double get2XX(double data) {
double f = data;
//
// String s = String.valueOf(f);
//
// s = s.substring(s.indexOf('.') + 1);
//
// System.out.println(s.length());
//
// if (s.length() > 2) {
// data += 0.01;
// }
//
// System.out.println(data);
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.UP);
String d = df.format(data);
System.out.println(d);
return Double.valueOf(d);
}
public static String getFormat_s1(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormatYYMMDD(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormat(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormatWithoutSS(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
/**
* 2月2日 下午17:49
*
* @param times
* @return
*/
public static String getFormatForAMPM(long times) {
Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"MM月dd日");
String sb = format.format(c.getTime());
String morning = " 上午 ";
String afternoon = " 下午 ";
String amOrpm = "";
int hour = 0;
if (c.get(c.HOUR_OF_DAY) > 12) {
amOrpm = afternoon;
hour = c.get(c.HOUR_OF_DAY) - 12;
return sb + amOrpm + hour + ":" + String.format("%02d", c.get(c.MINUTE));
} else {
amOrpm = morning;
hour = c.get(c.HOUR_OF_DAY);
return sb + amOrpm + String.format("%02d", hour) + ":" + String.format("%02d", c.get(c.MINUTE));
}
}
public static String getFormatHHMMSS(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"HH:mm:ss");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormatHHMM(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
public static String getOnlyHHMM(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
/**
* 剩余的小时,精确到分钟
*
* @param sd
* @return
*/
public static String getRemainHHMM(long sd) {
String remainHM = "请等待上车";
GregorianCalendar gc = new GregorianCalendar();
long now = gc.getTimeInMillis();
long remainMills = sd - now;
if (remainMills >= 0) {
int hour = (int) (remainMills / hourLevelValue);
int minute = (int) ((remainMills - hour * hourLevelValue) / minuteLevelValue);
int second = (int) ((remainMills - hour * hourLevelValue - minute * minuteLevelValue) / secondLevelValue);
remainHM = getStringFromat02d(hour) + " : " + getStringFromat02d(minute) + " : " + getStringFromat02d(second);
} else {
remainHM = "请等待上车";
}
return remainHM;
}
/**
* 数字带0两位
*
* @param num
* @return
*/
public static String getStringFromat02d(int num) {
return String.format("%02d", num);
}
public static String getFormat1(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy.MM.dd", Locale.US);
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormat3(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"MM-dd HH:mm", Locale.CHINA);
String sb = format.format(dat);
return sb;
}
public static String getFormat4(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"HH:mm", Locale.US);
String sb = format.format(gc.getTime());
return sb;
}
public static SpannableString getSpannableString(String keyword,
String content, int color) {
Pattern pattern;// = Pattern.compile("abc");
Matcher matcher;// = p.matcher(s);
SpannableString spannableString;
if (!StringUtils.isStringDataNull(keyword)
&& !StringUtils.isStringDataNull(content)) {
spannableString = new SpannableString(content);
pattern = Pattern.compile(keyword);
matcher = pattern.matcher(content);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
spannableString.setSpan(new ForegroundColorSpan(color), start,
end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannableString;
} else {
return new SpannableString(content);
}
}
public static boolean isAvilible(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
for (int i = 0; i < pinfo.size(); i++) {
if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
return true;
}
return false;
}
public static long getLastWeek() {
// TODO Auto-generated method stub
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
calendar.set(Calendar.WEEK_OF_YEAR,
calendar.get(Calendar.WEEK_OF_YEAR) - 1);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTimeInMillis();
}
public static long getThisWeek() {
// TODO Auto-generated method stub
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTimeInMillis();
}
/**
* 检查当前网络是否可用
*
* @param
* @return
*/
public static boolean isNetworkAvailable(Context c) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
} else {
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0) {
for (int i = 0; i < networkInfo.length; i++) {
System.out.println(i + "===状态==="
+ networkInfo[i].getState());
System.out.println(i + "===类型==="
+ networkInfo[i].getTypeName());
// 判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
/**
* 获取版本号
*
* @param c
* @return
*/
public static String getVersion(Context c) {
try {
PackageManager manager = c.getPackageManager();
PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
String version = info.versionName;
return TextUtils.isEmpty(version) ? "" : version;
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
public static String getVer(Context c) {
try {
PackageManager manager = c.getPackageManager();
PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
String version = info.versionName;
return "version:" + version;
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
* 获取当前系统的android版本号
*
* @param c
* @return
*/
public static String getPlatform(Context c) {
int sdk_int = android.os.Build.VERSION.SDK_INT;
String version = android.os.Build.VERSION.RELEASE;
return "android platform: " + version + ",sdk: " + sdk_int;
}
public static int getVersionCode(Context context)// 获取版本号(内部识别号)
{
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return pi.versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
public static String StringData(String sd) {
final Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return mYear + "-" + mMonth + "-" + mDay + "日" + " 星期" + mWay;
}
public static String getDateFors(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return " 星期" + mWay;
}
public static String getFormatYMDW(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return mYear + "-" + mMonth + "-" + mDay + " 星期" + mWay;
}
public static String getDateFors2(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return mWay;
}
public static String getDateMMSS(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
int sec = c.get(Calendar.MINUTE);
if (c.get(Calendar.HOUR_OF_DAY) > 12) {
return "下午" + c.get(Calendar.HOUR) + ":" + sec;
} else {
return "上午" + c.get(Calendar.HOUR) + ":" + sec;
}
}
public static String getDateMMSS12(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
int miao = c.get(Calendar.SECOND);
int sec = c.get(Calendar.MINUTE);
if (c.get(Calendar.HOUR_OF_DAY) > 12) {
return "下午" + c.get(Calendar.HOUR) + ":" + sec + ":" + miao;
} else {
return "上午" + c.get(Calendar.HOUR) + ":" + sec + ":" + miao;
}
}
public static String getLocalMacAddress(Context context) {
WifiManager wifi = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}
}
| 243640yinyisen243640/MyXyPatient | libpickers/src/main/java/cn/addapp/pickers/util/StringUtils.java | 6,399 | // 获取网络连接管理的对象 | line_comment | zh-cn | package cn.addapp.pickers.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.math.RoundingMode;
import java.net.NetworkInterface;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
private final static long hourLevelValue = 60 * 60 * 1000;
private final static long minuteLevelValue = 60 * 1000;
private final static long secondLevelValue = 1000;
private static String mYear;
private static String mMonth;
private static String mDay;
private static String mWay;
public static boolean isStringDataNull(String checkData) {
if ("".equals(checkData) || checkData == null
|| "null".equals(checkData) || checkData == null) {
return true;
}
return false;
}
public static boolean isListDataNull(List list) {
if (list == null || list.size() <= 0) {
return true;
}
return false;
}
public static String replaceBlankCharacter(String string) {
if (string != null) {
string = string.replace(" ", "");
return string;
}
return null;
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*
* @param pxValue
* @param (DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将sp值转换为px值,保证文字大小不变
*
* @param spValue
* @param (DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
public static boolean isConnect(Context context) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
try {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
// 获取 <SUF>
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 判断当前网络是否已经连接
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
/**
* 获取手机的MAC地址
*
* @return
*/
// public static String getMac() {
// String str = "";
// String macSerial = "";
// try {
// Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
// InputStreamReader ir = new InputStreamReader(pp.getInputStream());
// LineNumberReader input = new LineNumberReader(ir);
//
// for (; null != str;) {
// str = input.readLine();
// if (str != null) {
// macSerial = str.trim();// 去空格
// break;
// }
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// if (null == macSerial || "".equals(macSerial)) {
// try {
// return loadFileAsString("/sys/class/net/eth0/address")
// .toUpperCase().substring(0, 17);
// } catch (Exception e) {
// e.printStackTrace();
// macSerial="02:00:00:00:00:00";
// }
// }
// return macSerial;
// }
public static String getMacAddress() {
String str = "";
String macSerial = "";
try {
Process pp = Runtime.getRuntime().exec(
"cat /sys/class/net/wlan0/address ");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (macSerial == null || "".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/eth0/address")
.toUpperCase().substring(0, 17);
} catch (Exception e) {
e.printStackTrace();
}
}
if (macSerial == null || "".equals(macSerial)) {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
macSerial = "02:00:00:00:00:00";
}
}
return macSerial;
}
public static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
public static String loadReaderAsString(Reader reader) throws Exception {
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
int readLength = reader.read(buffer);
while (readLength >= 0) {
builder.append(buffer, 0, readLength);
readLength = reader.read(buffer);
}
return builder.toString();
}
public static boolean isNull(String str) {
if (str == null || str.equals("")) {
return true;
} else {
return false;
}
}
public static String get2XXDa(double data) {
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.UP);
String d = df.format(data);
if (d.indexOf(".") == 0) {
d = "0" + d;
}
System.out.println(d);
return d;
}
/**
* 向下取整
*
* @param data
* @return
*/
public static String get2XXDown(double data) {
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
// df.setRoundingMode(RoundingMode.DOWN);
String d = df.format(data);
if (d.indexOf(".") == 0) {
d = "0" + d;
}
System.out.println(d);
return d;
}
public static String get2XXDat(double data) {
System.out.println(data);
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.DOWN);
String d = df.format(data);
if (d.indexOf(".") == 0) {
d = "0" + d;
}
System.out.println(d);
return d;
}
public static double get2XX(double data) {
double f = data;
//
// String s = String.valueOf(f);
//
// s = s.substring(s.indexOf('.') + 1);
//
// System.out.println(s.length());
//
// if (s.length() > 2) {
// data += 0.01;
// }
//
// System.out.println(data);
DecimalFormat df = new DecimalFormat("###.00");
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.UP);
String d = df.format(data);
System.out.println(d);
return Double.valueOf(d);
}
public static String getFormat_s1(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormatYYMMDD(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormat(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormatWithoutSS(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
/**
* 2月2日 下午17:49
*
* @param times
* @return
*/
public static String getFormatForAMPM(long times) {
Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"MM月dd日");
String sb = format.format(c.getTime());
String morning = " 上午 ";
String afternoon = " 下午 ";
String amOrpm = "";
int hour = 0;
if (c.get(c.HOUR_OF_DAY) > 12) {
amOrpm = afternoon;
hour = c.get(c.HOUR_OF_DAY) - 12;
return sb + amOrpm + hour + ":" + String.format("%02d", c.get(c.MINUTE));
} else {
amOrpm = morning;
hour = c.get(c.HOUR_OF_DAY);
return sb + amOrpm + String.format("%02d", hour) + ":" + String.format("%02d", c.get(c.MINUTE));
}
}
public static String getFormatHHMMSS(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"HH:mm:ss");
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormatHHMM(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"MM-dd HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
public static String getOnlyHHMM(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"HH:mm");
String sb = format.format(gc.getTime());
return sb;
}
/**
* 剩余的小时,精确到分钟
*
* @param sd
* @return
*/
public static String getRemainHHMM(long sd) {
String remainHM = "请等待上车";
GregorianCalendar gc = new GregorianCalendar();
long now = gc.getTimeInMillis();
long remainMills = sd - now;
if (remainMills >= 0) {
int hour = (int) (remainMills / hourLevelValue);
int minute = (int) ((remainMills - hour * hourLevelValue) / minuteLevelValue);
int second = (int) ((remainMills - hour * hourLevelValue - minute * minuteLevelValue) / secondLevelValue);
remainHM = getStringFromat02d(hour) + " : " + getStringFromat02d(minute) + " : " + getStringFromat02d(second);
} else {
remainHM = "请等待上车";
}
return remainHM;
}
/**
* 数字带0两位
*
* @param num
* @return
*/
public static String getStringFromat02d(int num) {
return String.format("%02d", num);
}
public static String getFormat1(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"yyyy.MM.dd", Locale.US);
String sb = format.format(gc.getTime());
return sb;
}
public static String getFormat3(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"MM-dd HH:mm", Locale.CHINA);
String sb = format.format(dat);
return sb;
}
public static String getFormat4(long sd) {
Date dat = new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dat);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
"HH:mm", Locale.US);
String sb = format.format(gc.getTime());
return sb;
}
public static SpannableString getSpannableString(String keyword,
String content, int color) {
Pattern pattern;// = Pattern.compile("abc");
Matcher matcher;// = p.matcher(s);
SpannableString spannableString;
if (!StringUtils.isStringDataNull(keyword)
&& !StringUtils.isStringDataNull(content)) {
spannableString = new SpannableString(content);
pattern = Pattern.compile(keyword);
matcher = pattern.matcher(content);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
spannableString.setSpan(new ForegroundColorSpan(color), start,
end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannableString;
} else {
return new SpannableString(content);
}
}
public static boolean isAvilible(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
for (int i = 0; i < pinfo.size(); i++) {
if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
return true;
}
return false;
}
public static long getLastWeek() {
// TODO Auto-generated method stub
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
calendar.set(Calendar.WEEK_OF_YEAR,
calendar.get(Calendar.WEEK_OF_YEAR) - 1);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTimeInMillis();
}
public static long getThisWeek() {
// TODO Auto-generated method stub
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTimeInMillis();
}
/**
* 检查当前网络是否可用
*
* @param
* @return
*/
public static boolean isNetworkAvailable(Context c) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
} else {
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0) {
for (int i = 0; i < networkInfo.length; i++) {
System.out.println(i + "===状态==="
+ networkInfo[i].getState());
System.out.println(i + "===类型==="
+ networkInfo[i].getTypeName());
// 判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
/**
* 获取版本号
*
* @param c
* @return
*/
public static String getVersion(Context c) {
try {
PackageManager manager = c.getPackageManager();
PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
String version = info.versionName;
return TextUtils.isEmpty(version) ? "" : version;
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
public static String getVer(Context c) {
try {
PackageManager manager = c.getPackageManager();
PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
String version = info.versionName;
return "version:" + version;
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
* 获取当前系统的android版本号
*
* @param c
* @return
*/
public static String getPlatform(Context c) {
int sdk_int = android.os.Build.VERSION.SDK_INT;
String version = android.os.Build.VERSION.RELEASE;
return "android platform: " + version + ",sdk: " + sdk_int;
}
public static int getVersionCode(Context context)// 获取版本号(内部识别号)
{
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return pi.versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
public static String StringData(String sd) {
final Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return mYear + "-" + mMonth + "-" + mDay + "日" + " 星期" + mWay;
}
public static String getDateFors(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return " 星期" + mWay;
}
public static String getFormatYMDW(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return mYear + "-" + mMonth + "-" + mDay + " 星期" + mWay;
}
public static String getDateFors2(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
if ("1".equals(mWay)) {
mWay = "天";
} else if ("2".equals(mWay)) {
mWay = "一";
} else if ("3".equals(mWay)) {
mWay = "二";
} else if ("4".equals(mWay)) {
mWay = "三";
} else if ("5".equals(mWay)) {
mWay = "四";
} else if ("6".equals(mWay)) {
mWay = "五";
} else if ("7".equals(mWay)) {
mWay = "六";
}
return mWay;
}
public static String getDateMMSS(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
int sec = c.get(Calendar.MINUTE);
if (c.get(Calendar.HOUR_OF_DAY) > 12) {
return "下午" + c.get(Calendar.HOUR) + ":" + sec;
} else {
return "上午" + c.get(Calendar.HOUR) + ":" + sec;
}
}
public static String getDateMMSS12(long times) {
final Calendar c = Calendar.getInstance();
Date dat = new Date(times);
c.setTime(dat);
c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
int miao = c.get(Calendar.SECOND);
int sec = c.get(Calendar.MINUTE);
if (c.get(Calendar.HOUR_OF_DAY) > 12) {
return "下午" + c.get(Calendar.HOUR) + ":" + sec + ":" + miao;
} else {
return "上午" + c.get(Calendar.HOUR) + ":" + sec + ":" + miao;
}
}
public static String getLocalMacAddress(Context context) {
WifiManager wifi = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}
}
| 0 |
32696_2 | package com.vice.bloodpressure.activity.auser;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.vice.bloodpressure.R;
import com.vice.bloodpressure.baseui.UIBaseActivity;
import com.vice.bloodpressure.utils.PickerViewUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 作者: beauty
* 类名:
* 传参:type 1:抽烟 2:喝酒
* 描述:抽烟喝酒的编辑数量
*/
public class UserSmokeDrinkActivity extends UIBaseActivity {
private TextView titleTextView;
private CheckBox yesCb;
private CheckBox noCb;
private LinearLayout smokeLinerLayout;
private EditText smokeNumEt;
private ImageView arrowImageView;
private TextView typeTv;
private EditText drinkNumEt;
private LinearLayout drinkLinerLayout;
private TextView sureTv;
/**
* 1:抽烟 2:喝酒
*/
private String type;
private String drinkType = "0";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
type = getIntent().getStringExtra("type");
initView();
initListener();
}
private void initListener() {
yesCb.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
noCb.setChecked(false);
arrowImageView.setVisibility(View.VISIBLE);
arrowImageView.setVisibility(View.VISIBLE);
} else {
noCb.setChecked(true);
}
});
noCb.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
yesCb.setChecked(false);
} else {
yesCb.setChecked(true);
}
});
typeTv.setOnClickListener(v -> {
chooseDrinkTypeWindow();
});
sureTv.setOnClickListener(v -> {
Intent intent = new Intent();
if ("1".equals(type)) {
intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0");
intent.putExtra("smokeNum", smokeNumEt.getText().toString().trim());
} else {
intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0");
intent.putExtra("drinkNum", drinkNumEt.getText().toString().trim());
intent.putExtra("drinkType", drinkType);
}
setResult(RESULT_OK, intent);
finish();
});
}
/**
* 酒的种类
*/
private void chooseDrinkTypeWindow() {
List<String> exerciseList = new ArrayList<>();
exerciseList.add("白酒");
exerciseList.add("啤酒");
exerciseList.add("红酒");
exerciseList.add("黄酒");
PickerViewUtils.showChooseSinglePicker(getPageContext(), "酒类", exerciseList, object -> {
typeTv.setText(exerciseList.get(Integer.parseInt(String.valueOf(object))));
drinkType = exerciseList.get(Integer.parseInt(String.valueOf(object)));
}
);
}
private void initView() {
View view = View.inflate(getPageContext(), R.layout.activity_user_smoke_drink, null);
containerView().addView(view);
titleTextView = view.findViewById(R.id.tv_files_smoke_drink_title);
yesCb = view.findViewById(R.id.cb_files_smoke_drink_yes);
noCb = view.findViewById(R.id.cb_files_smoke_drink_no);
smokeNumEt = view.findViewById(R.id.iv_files_smoke);
arrowImageView = view.findViewById(R.id.et_files_smoke_drink_smoke_num);
smokeLinerLayout = view.findViewById(R.id.ll_files_smoke);
typeTv = view.findViewById(R.id.tv_files_smoke_drink_type);
drinkNumEt = view.findViewById(R.id.et_files_smoke_drink_num);
drinkLinerLayout = view.findViewById(R.id.ll_files_drink);
sureTv = view.findViewById(R.id.tv_files_smoke_drink_sure);
if ("1".equals(type)) {
titleTextView.setText("是否吸烟");
smokeLinerLayout.setVisibility(View.VISIBLE);
drinkLinerLayout.setVisibility(View.GONE);
} else {
titleTextView.setText("是否饮酒");
smokeLinerLayout.setVisibility(View.GONE);
drinkLinerLayout.setVisibility(View.VISIBLE);
}
}
}
| 243640yinyisen243640/NewPatient | app/src/main/java/com/vice/bloodpressure/activity/auser/UserSmokeDrinkActivity.java | 1,142 | /**
* 酒的种类
*/ | block_comment | zh-cn | package com.vice.bloodpressure.activity.auser;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.vice.bloodpressure.R;
import com.vice.bloodpressure.baseui.UIBaseActivity;
import com.vice.bloodpressure.utils.PickerViewUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 作者: beauty
* 类名:
* 传参:type 1:抽烟 2:喝酒
* 描述:抽烟喝酒的编辑数量
*/
public class UserSmokeDrinkActivity extends UIBaseActivity {
private TextView titleTextView;
private CheckBox yesCb;
private CheckBox noCb;
private LinearLayout smokeLinerLayout;
private EditText smokeNumEt;
private ImageView arrowImageView;
private TextView typeTv;
private EditText drinkNumEt;
private LinearLayout drinkLinerLayout;
private TextView sureTv;
/**
* 1:抽烟 2:喝酒
*/
private String type;
private String drinkType = "0";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
type = getIntent().getStringExtra("type");
initView();
initListener();
}
private void initListener() {
yesCb.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
noCb.setChecked(false);
arrowImageView.setVisibility(View.VISIBLE);
arrowImageView.setVisibility(View.VISIBLE);
} else {
noCb.setChecked(true);
}
});
noCb.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
yesCb.setChecked(false);
} else {
yesCb.setChecked(true);
}
});
typeTv.setOnClickListener(v -> {
chooseDrinkTypeWindow();
});
sureTv.setOnClickListener(v -> {
Intent intent = new Intent();
if ("1".equals(type)) {
intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0");
intent.putExtra("smokeNum", smokeNumEt.getText().toString().trim());
} else {
intent.putExtra("isCheck", yesCb.isChecked() ? "1" : "0");
intent.putExtra("drinkNum", drinkNumEt.getText().toString().trim());
intent.putExtra("drinkType", drinkType);
}
setResult(RESULT_OK, intent);
finish();
});
}
/**
* 酒的种 <SUF>*/
private void chooseDrinkTypeWindow() {
List<String> exerciseList = new ArrayList<>();
exerciseList.add("白酒");
exerciseList.add("啤酒");
exerciseList.add("红酒");
exerciseList.add("黄酒");
PickerViewUtils.showChooseSinglePicker(getPageContext(), "酒类", exerciseList, object -> {
typeTv.setText(exerciseList.get(Integer.parseInt(String.valueOf(object))));
drinkType = exerciseList.get(Integer.parseInt(String.valueOf(object)));
}
);
}
private void initView() {
View view = View.inflate(getPageContext(), R.layout.activity_user_smoke_drink, null);
containerView().addView(view);
titleTextView = view.findViewById(R.id.tv_files_smoke_drink_title);
yesCb = view.findViewById(R.id.cb_files_smoke_drink_yes);
noCb = view.findViewById(R.id.cb_files_smoke_drink_no);
smokeNumEt = view.findViewById(R.id.iv_files_smoke);
arrowImageView = view.findViewById(R.id.et_files_smoke_drink_smoke_num);
smokeLinerLayout = view.findViewById(R.id.ll_files_smoke);
typeTv = view.findViewById(R.id.tv_files_smoke_drink_type);
drinkNumEt = view.findViewById(R.id.et_files_smoke_drink_num);
drinkLinerLayout = view.findViewById(R.id.ll_files_drink);
sureTv = view.findViewById(R.id.tv_files_smoke_drink_sure);
if ("1".equals(type)) {
titleTextView.setText("是否吸烟");
smokeLinerLayout.setVisibility(View.VISIBLE);
drinkLinerLayout.setVisibility(View.GONE);
} else {
titleTextView.setText("是否饮酒");
smokeLinerLayout.setVisibility(View.GONE);
drinkLinerLayout.setVisibility(View.VISIBLE);
}
}
}
| 0 |
61614_4 | package com.lgp.aop.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: a247292980
* Date: 2017/08/14
* <p>
* 方法的aop
*/
@Aspect
@Component
public class FunctionAspect {
protected org.slf4j.Logger logger = LoggerFactory.getLogger(FunctionAspect.class);
/**
* execution函数
* 用于匹配方法执行的连接点,语法为:execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选))
* 参数部分允许使用通配符:
* * 匹配任意字符,但只能匹配一个元素
* .. 匹配任意字符,可以匹配任意多个元素,表示类时,必须和*联合使用
* + 必须跟在类名后面,如Horseman+,表示类本身和继承或扩展指定类的所有类
* 除了execution(),Spring中还支持其他多个函数,这里列出名称和简单介绍,以方便根据需要进行更详细的查询
* @annotation() 表示标注了指定注解的目标类方法
* 例如 @annotation(org.springframework.transaction.annotation.Transactional) 表示标注了@Transactional的方法
* args()通过目标类方法的参数类型指定切点 例如 args(String) 表示有且仅有一个String型参数的方法
* @args() 通过目标类参数的对象类型是否标注了指定注解指定切点 如 @args(org.springframework.stereotype.Service) 表示有且仅有一个标注了@Service的类参数的方法
* within()通过类名指定切点 如 with(examples.chap03.Horseman) 表示Horseman的所有方法
* @within() 匹配标注了指定注解的类及其所有子类 如 @within(org.springframework.stereotype.Service) 给Horseman加上@Service标注,则Horseman和Elephantman 的所有方法都匹配
* target()通过类名指定,同时包含所有子类 如 target(examples.chap03.Horseman) 且Elephantman extends Horseman,则两个类的所有方法都匹配
* @target() 所有标注了指定注解的类 如 @target(org.springframework.stereotype.Service) 表示所有标注了@Service的类的所有方法
* this() 大部分时候和target()相同,区别是this是在运行时生成代理类后,才判断代理类与指定的对象类型是否匹配
* */
/**
* 定义有一个切入点,范围为service包下的类
*/
@Pointcut("execution(public * com.lgp.aop.service.*.*(..))")
public void service() {
}
@Around("service()")
public void doAround(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
System.out.println("URL : " + request.getRequestURL().toString());
System.out.println("HTTP_METHOD : " + request.getMethod());
System.out.println("IP : " + request.getRemoteAddr());
System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
}
| 247292980/spring-boot | aop/src/main/java/com/lgp/aop/aop/FunctionAspect.java | 926 | // 记录下请求内容 | line_comment | zh-cn | package com.lgp.aop.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: a247292980
* Date: 2017/08/14
* <p>
* 方法的aop
*/
@Aspect
@Component
public class FunctionAspect {
protected org.slf4j.Logger logger = LoggerFactory.getLogger(FunctionAspect.class);
/**
* execution函数
* 用于匹配方法执行的连接点,语法为:execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选))
* 参数部分允许使用通配符:
* * 匹配任意字符,但只能匹配一个元素
* .. 匹配任意字符,可以匹配任意多个元素,表示类时,必须和*联合使用
* + 必须跟在类名后面,如Horseman+,表示类本身和继承或扩展指定类的所有类
* 除了execution(),Spring中还支持其他多个函数,这里列出名称和简单介绍,以方便根据需要进行更详细的查询
* @annotation() 表示标注了指定注解的目标类方法
* 例如 @annotation(org.springframework.transaction.annotation.Transactional) 表示标注了@Transactional的方法
* args()通过目标类方法的参数类型指定切点 例如 args(String) 表示有且仅有一个String型参数的方法
* @args() 通过目标类参数的对象类型是否标注了指定注解指定切点 如 @args(org.springframework.stereotype.Service) 表示有且仅有一个标注了@Service的类参数的方法
* within()通过类名指定切点 如 with(examples.chap03.Horseman) 表示Horseman的所有方法
* @within() 匹配标注了指定注解的类及其所有子类 如 @within(org.springframework.stereotype.Service) 给Horseman加上@Service标注,则Horseman和Elephantman 的所有方法都匹配
* target()通过类名指定,同时包含所有子类 如 target(examples.chap03.Horseman) 且Elephantman extends Horseman,则两个类的所有方法都匹配
* @target() 所有标注了指定注解的类 如 @target(org.springframework.stereotype.Service) 表示所有标注了@Service的类的所有方法
* this() 大部分时候和target()相同,区别是this是在运行时生成代理类后,才判断代理类与指定的对象类型是否匹配
* */
/**
* 定义有一个切入点,范围为service包下的类
*/
@Pointcut("execution(public * com.lgp.aop.service.*.*(..))")
public void service() {
}
@Around("service()")
public void doAround(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录 <SUF>
System.out.println("URL : " + request.getRequestURL().toString());
System.out.println("HTTP_METHOD : " + request.getMethod());
System.out.println("IP : " + request.getRemoteAddr());
System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
}
| 0 |
60051_18 | package 大厂算法题.微软DNF遍历;
// 来自微软
// 给定两个数组A和B,比如
// A = { 0, 1, 1 }
// B = { 1, 2, 3 }
// A[0] = 0, B[0] = 1,表示0到1有双向道路
// A[1] = 1, B[1] = 2,表示1到2有双向道路
// A[2] = 1, B[2] = 3,表示1到3有双向道路
// 给定数字N,编号从0~N,所以一共N+1个节点
// 题目输入一定保证所有节点都联通,并且一定没有环
// 默认办公室是0节点,其他1~N节点上,每个节点上都有一个居民
// 每天所有居民都去往0节点上班
// 所有的居民都有一辆5座的车,也都乐意和别人一起坐车
// 车不管负重是多少,只要走过一条路,就耗费1的汽油
// 比如A、B、C的居民,开着自己的车来到D居民的位置,一共耗费3的汽油
// D居民和E居民之间,假设有一条路
// 那么D居民可以接上A、B、C,4个人可以用一辆车,去往E的话,就再耗费1的汽油
// 求所有居民去办公室的路上,最少耗费多少汽油
import java.util.ArrayList;
public class TravelMinFuel {
public static int cnt = 0;
public static int minFuel(int[] a, int[] b, int n) {
// 先建图
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < a.length; i++) {
graph.get(a[i]).add(b[i]);
graph.get(b[i]).add(a[i]);
}
// 建图完毕
// 根据题目描述,办公室一定是0号点
// 所有员工一定是往0号点汇聚
int[] dfn = new int[n + 1];
int[] size = new int[n + 1];
int[] cost = new int[n + 1];
cnt = 0;
dfs(graph, 0, -1, dfn, size, cost);
return cost[0];
}
public static void dfs(ArrayList<ArrayList<Integer>> graph, int cur, int pre, int[] dfn, int[] size, int[] cost) {
dfn[cur] = ++cnt;
size[cur] = 1;
for (int next : graph.get(cur)) {
if (next == pre) {
continue;
}
dfs(graph, next, cur, dfn, size, cost);
size[cur] += size[next];
cost[cur] += cost[next];
cost[cur] += (size[next] + 4) / 5;
}
}
public static void main(String[] args) {
int[] a1 = {0, 1, 1};
int[] b1 = {1, 2, 3};
int n1 = 3;
System.out.println(minFuel(a1, b1, n1));
int[] a2 = {1, 1, 1, 9, 9, 9, 9, 7, 8};
int[] b2 = {2, 0, 3, 1, 6, 5, 4, 0, 0};
int n2 = 9;
System.out.println(minFuel(a2, b2, n2));
}
} | 2497296400/LeetCode-Chi | src/大厂算法题/微软DNF遍历/TravelMinFuel.java | 941 | // 建图完毕 | line_comment | zh-cn | package 大厂算法题.微软DNF遍历;
// 来自微软
// 给定两个数组A和B,比如
// A = { 0, 1, 1 }
// B = { 1, 2, 3 }
// A[0] = 0, B[0] = 1,表示0到1有双向道路
// A[1] = 1, B[1] = 2,表示1到2有双向道路
// A[2] = 1, B[2] = 3,表示1到3有双向道路
// 给定数字N,编号从0~N,所以一共N+1个节点
// 题目输入一定保证所有节点都联通,并且一定没有环
// 默认办公室是0节点,其他1~N节点上,每个节点上都有一个居民
// 每天所有居民都去往0节点上班
// 所有的居民都有一辆5座的车,也都乐意和别人一起坐车
// 车不管负重是多少,只要走过一条路,就耗费1的汽油
// 比如A、B、C的居民,开着自己的车来到D居民的位置,一共耗费3的汽油
// D居民和E居民之间,假设有一条路
// 那么D居民可以接上A、B、C,4个人可以用一辆车,去往E的话,就再耗费1的汽油
// 求所有居民去办公室的路上,最少耗费多少汽油
import java.util.ArrayList;
public class TravelMinFuel {
public static int cnt = 0;
public static int minFuel(int[] a, int[] b, int n) {
// 先建图
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < a.length; i++) {
graph.get(a[i]).add(b[i]);
graph.get(b[i]).add(a[i]);
}
// 建图 <SUF>
// 根据题目描述,办公室一定是0号点
// 所有员工一定是往0号点汇聚
int[] dfn = new int[n + 1];
int[] size = new int[n + 1];
int[] cost = new int[n + 1];
cnt = 0;
dfs(graph, 0, -1, dfn, size, cost);
return cost[0];
}
public static void dfs(ArrayList<ArrayList<Integer>> graph, int cur, int pre, int[] dfn, int[] size, int[] cost) {
dfn[cur] = ++cnt;
size[cur] = 1;
for (int next : graph.get(cur)) {
if (next == pre) {
continue;
}
dfs(graph, next, cur, dfn, size, cost);
size[cur] += size[next];
cost[cur] += cost[next];
cost[cur] += (size[next] + 4) / 5;
}
}
public static void main(String[] args) {
int[] a1 = {0, 1, 1};
int[] b1 = {1, 2, 3};
int n1 = 3;
System.out.println(minFuel(a1, b1, n1));
int[] a2 = {1, 1, 1, 9, 9, 9, 9, 7, 8};
int[] b2 = {2, 0, 3, 1, 6, 5, 4, 0, 0};
int n2 = 9;
System.out.println(minFuel(a2, b2, n2));
}
} | 0 |
27072_7 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.artw.almanac.luozhuangpaipan;
/**
* 吕才合婚算法
*
* @author luozhuang 大师♂罗莊
*/
public class luozhuanglvhehun {
enum sex {
man,
woman;
}
public final String[] jiazhi = {
"甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", "辛未", "壬申", "癸酉",
"甲戌", "乙亥", "丙子", "丁丑", "戊寅", "己卯", "庚辰", "辛巳", "壬午", "癸未",
"甲申", "乙酉", "丙戌", "丁亥", "戊子", "己丑", "庚寅", "辛卯", "壬辰", "癸巳",
"甲午", "乙未", "丙申", "丁酉", "戊戌", "己亥", "庚子", "辛丑", "壬寅", "癸卯",
"甲辰", "乙巳", "丙午", "丁未", "戊申", "己酉", "庚戌", "辛亥", "壬子", "癸丑",
"甲寅", "乙卯", "丙辰", "丁巳", "戊午", "己未", "庚申", "辛酉", "壬戌", "癸亥"
};
//注意数组没有第5行和第5列
public final String[][] resultarray = {
{"伏位", "绝命", "天医", "生气", "六煞", "祸害", "五鬼", "延年"},
{"绝命", "伏位", "祸害", "五鬼", "延年", "天医", "生气", "六煞"},
{"天医", "祸害", "伏位", "延年", "五鬼", "绝命", "六煞", "生气"},
{"生气", "五鬼", "延年", "伏位", "祸害", "六煞", "绝命", "天医"},
{"六煞", "延年", "五鬼", "祸害", "伏位", "生气", "天医", "绝命"},
{"祸害", "天医", "绝命", "六煞", "生气", "伏位", "延年", "五鬼"},
{"五鬼", "生气", "六煞", "绝命", "天医", "延年", "伏位", "祸害"},
{"延年", "六煞", "生气", "天医", "绝命", "五鬼", "祸害", "伏位"},};
public final String[][] numsix = {
//干支,纳音,岁数,男,女
{"丙戌", "屋上土", "1", "3", "3"},
{"乙酉", "泉中水", "2", "4", "2"},
{"甲申", "泉中水", "3", "5", "1"},
{"癸未", "杨柳木", "4", "6", "9"},
{"壬午", "杨柳木", "5", "7", "8"},
{"辛巳", "白蜡金", "6", "8", "7"},
{"庚辰", "白蜡金", "7", "9", "6"},
{"己卯", "城墙土", "8", "1", "5"},
{"戊寅", "城墙土", "9", "2", "4"},
{"丁丑", "涧下水", "10", "3", "3"},
{"丙子", "涧下水", "11", "4", "2"},
{"乙亥", "山头火", "12", "5", "1"},
{"甲戌", "山头火", "13", "6", "9"},
{"癸酉", "剑锋金", "14", "7", "8"},
{"壬申", "剑锋金", "15", "8", "7"},
{"辛未", "路旁土", "16", "9", "6"},
{"庚午", "路旁土", "17", "1", "5"},
{"己巳", "大林木", "18", "2", "4"},
{"戊辰", "大林木", "19", "3", "3"},
{"丁卯", "炉中火", "20", "4", "2"},
{"丙寅", "炉中火", "21", "5", "1"},
{"乙丑", "海中金", "22", "6", "9"},
{"甲子", "海中金", "23", "7", "8"},
{"癸亥", "大海水", "24", "8", "7"},
{"壬戌", "大海水", "25", "9", "6"},
{"辛酉", "石榴木", "26", "1", "5"},
{"庚申", "石榴木", "27", "2", "4"},
{"己未", "天上火", "28", "3", "3"},
{"戊午", "天上火", "29", "4", "2"},
{"丁巳", "沙中土", "30", "5", "1"},
{"丙辰", "沙中土", "31", "6", "9"},
{"乙卯", "大溪水", "32", "7", "8"},
{"甲寅", "大溪水", "33", "8", "7"},
{"癸丑", "桑松木", "34", "9", "6"},
{"壬子", "桑松木", "35", "1", "5"},
{"辛亥", "钗钏金", "36", "2", "4"},
{"庚戌", "钗钏金", "37", "3", "3"},
{"己酉", "大驿土", "38", "4", "2"},
{"戊申", "大驿土", "39", "5", "1"},
{"丁未", "天河水", "40", "6", "9"},
{"丙午", "天河水", "41", "7", "8"},
{"乙巳", "佛灯火", "42", "8", "7"},
{"甲辰", "佛灯火", "43", "9", "6"},
{"癸卯", "金箔金", "44", "1", "5"},
{"壬寅", "金箔金", "45", "2", "4"},
{"辛丑", "壁上土", "46", "3", "3"},
{"庚子", "壁上土", "47", "4", "2"},
{"己亥", "平地木", "48", "5", "1"},
{"戊戌", "平地木", "49", "6", "9"},
{"丁酉", "山下火", "50", "7", "8"},
{"丙申", "山下火", "51", "8", "7"},
{"乙未", "沙中金", "52", "9", "6"},
{"甲午", "沙中金", "53", "1", "5"},
{"癸巳", "长流水", "54", "2", "4"},
{"壬辰", "长流水", "55", "3", "3"},
{"辛卯", "松柏木", "56", "4", "2"},
{"庚寅", "松柏木", "57", "5", "1"},
{"己丑", "霹雳火", "58", "6", "9"},
{"戊子", "霹雳火", "59", "7", "8"},
{"丁亥", "屋上土", "60", "8", "7"},};
/**
*
* @param man 男方年份字符串
* @param woman 女方年份字符串
* @return
*/
public String hehun(String man, String woman) {
if (man.length() != 4 || woman.length() != 4) {
return "输入不正确";
}
return peihun(man, woman);
}
public String peihun(String manyear, String womanyear) {
return peihun(getnumber(manyear), getnumber(womanyear));
}
private String peihun(int manyear, int womanyear) {
String mang = getnumsix(yearnumber(manyear), sex.man);
String womang = getnumsix(yearnumber(womanyear), sex.woman);
int man = getnumber(mang);
int woman = getnumber(womang);
//数组从0开始,而我们计算从1开始
man--;
woman--;
//注意数组没有第5行和第5列
if (man >= 5) {
man--;
}
if (woman >= 5) {
woman--;
}
//根据表格取结果
return resultarray[man][woman];//顺序一样的
}
/**
*
* @param year 年份
* @param isman 男的么
* @return 返回宫挂数
*/
public String getnumsix(String year, sex isman) {
for (int i = 0; i < 60; i++) {
if (year.equalsIgnoreCase(numsix[i][0])) {
if (isman == sex.man) {
return numsix[i][3];
} else {
return numsix[i][4];
}
}
}
return null;
}
/**
* 字符串-》数字
*
* @param year 字符串
* @return 字符串对应数字
* @throws NumberFormatException
*/
public int getnumber(String year) throws NumberFormatException {
int yearnumber = Short.parseShort(year);
return yearnumber;
}
/**
* 年份取出年柱
*
* @param year 年数
* @return 求的年份的干支
*/
public String yearnumber(int year) {
//1864年是甲子年,每隔六十年一个甲子
int idx = (Math.abs(year - 1864)) % 60;
//没有过春节的话那么年还算上一年的,此处求的年份的干支
String result = jiazhi[idx];
return result;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
luozhuanglvhehun my = new luozhuanglvhehun();
String result = my.hehun("1947", "1853");
System.out.println(result);
}
}
| 2666fff/ChineseAlmanac | app/src/main/java/com/artw/almanac/luozhuangpaipan/luozhuanglvhehun.java | 2,844 | //根据表格取结果 | line_comment | zh-cn | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.artw.almanac.luozhuangpaipan;
/**
* 吕才合婚算法
*
* @author luozhuang 大师♂罗莊
*/
public class luozhuanglvhehun {
enum sex {
man,
woman;
}
public final String[] jiazhi = {
"甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", "辛未", "壬申", "癸酉",
"甲戌", "乙亥", "丙子", "丁丑", "戊寅", "己卯", "庚辰", "辛巳", "壬午", "癸未",
"甲申", "乙酉", "丙戌", "丁亥", "戊子", "己丑", "庚寅", "辛卯", "壬辰", "癸巳",
"甲午", "乙未", "丙申", "丁酉", "戊戌", "己亥", "庚子", "辛丑", "壬寅", "癸卯",
"甲辰", "乙巳", "丙午", "丁未", "戊申", "己酉", "庚戌", "辛亥", "壬子", "癸丑",
"甲寅", "乙卯", "丙辰", "丁巳", "戊午", "己未", "庚申", "辛酉", "壬戌", "癸亥"
};
//注意数组没有第5行和第5列
public final String[][] resultarray = {
{"伏位", "绝命", "天医", "生气", "六煞", "祸害", "五鬼", "延年"},
{"绝命", "伏位", "祸害", "五鬼", "延年", "天医", "生气", "六煞"},
{"天医", "祸害", "伏位", "延年", "五鬼", "绝命", "六煞", "生气"},
{"生气", "五鬼", "延年", "伏位", "祸害", "六煞", "绝命", "天医"},
{"六煞", "延年", "五鬼", "祸害", "伏位", "生气", "天医", "绝命"},
{"祸害", "天医", "绝命", "六煞", "生气", "伏位", "延年", "五鬼"},
{"五鬼", "生气", "六煞", "绝命", "天医", "延年", "伏位", "祸害"},
{"延年", "六煞", "生气", "天医", "绝命", "五鬼", "祸害", "伏位"},};
public final String[][] numsix = {
//干支,纳音,岁数,男,女
{"丙戌", "屋上土", "1", "3", "3"},
{"乙酉", "泉中水", "2", "4", "2"},
{"甲申", "泉中水", "3", "5", "1"},
{"癸未", "杨柳木", "4", "6", "9"},
{"壬午", "杨柳木", "5", "7", "8"},
{"辛巳", "白蜡金", "6", "8", "7"},
{"庚辰", "白蜡金", "7", "9", "6"},
{"己卯", "城墙土", "8", "1", "5"},
{"戊寅", "城墙土", "9", "2", "4"},
{"丁丑", "涧下水", "10", "3", "3"},
{"丙子", "涧下水", "11", "4", "2"},
{"乙亥", "山头火", "12", "5", "1"},
{"甲戌", "山头火", "13", "6", "9"},
{"癸酉", "剑锋金", "14", "7", "8"},
{"壬申", "剑锋金", "15", "8", "7"},
{"辛未", "路旁土", "16", "9", "6"},
{"庚午", "路旁土", "17", "1", "5"},
{"己巳", "大林木", "18", "2", "4"},
{"戊辰", "大林木", "19", "3", "3"},
{"丁卯", "炉中火", "20", "4", "2"},
{"丙寅", "炉中火", "21", "5", "1"},
{"乙丑", "海中金", "22", "6", "9"},
{"甲子", "海中金", "23", "7", "8"},
{"癸亥", "大海水", "24", "8", "7"},
{"壬戌", "大海水", "25", "9", "6"},
{"辛酉", "石榴木", "26", "1", "5"},
{"庚申", "石榴木", "27", "2", "4"},
{"己未", "天上火", "28", "3", "3"},
{"戊午", "天上火", "29", "4", "2"},
{"丁巳", "沙中土", "30", "5", "1"},
{"丙辰", "沙中土", "31", "6", "9"},
{"乙卯", "大溪水", "32", "7", "8"},
{"甲寅", "大溪水", "33", "8", "7"},
{"癸丑", "桑松木", "34", "9", "6"},
{"壬子", "桑松木", "35", "1", "5"},
{"辛亥", "钗钏金", "36", "2", "4"},
{"庚戌", "钗钏金", "37", "3", "3"},
{"己酉", "大驿土", "38", "4", "2"},
{"戊申", "大驿土", "39", "5", "1"},
{"丁未", "天河水", "40", "6", "9"},
{"丙午", "天河水", "41", "7", "8"},
{"乙巳", "佛灯火", "42", "8", "7"},
{"甲辰", "佛灯火", "43", "9", "6"},
{"癸卯", "金箔金", "44", "1", "5"},
{"壬寅", "金箔金", "45", "2", "4"},
{"辛丑", "壁上土", "46", "3", "3"},
{"庚子", "壁上土", "47", "4", "2"},
{"己亥", "平地木", "48", "5", "1"},
{"戊戌", "平地木", "49", "6", "9"},
{"丁酉", "山下火", "50", "7", "8"},
{"丙申", "山下火", "51", "8", "7"},
{"乙未", "沙中金", "52", "9", "6"},
{"甲午", "沙中金", "53", "1", "5"},
{"癸巳", "长流水", "54", "2", "4"},
{"壬辰", "长流水", "55", "3", "3"},
{"辛卯", "松柏木", "56", "4", "2"},
{"庚寅", "松柏木", "57", "5", "1"},
{"己丑", "霹雳火", "58", "6", "9"},
{"戊子", "霹雳火", "59", "7", "8"},
{"丁亥", "屋上土", "60", "8", "7"},};
/**
*
* @param man 男方年份字符串
* @param woman 女方年份字符串
* @return
*/
public String hehun(String man, String woman) {
if (man.length() != 4 || woman.length() != 4) {
return "输入不正确";
}
return peihun(man, woman);
}
public String peihun(String manyear, String womanyear) {
return peihun(getnumber(manyear), getnumber(womanyear));
}
private String peihun(int manyear, int womanyear) {
String mang = getnumsix(yearnumber(manyear), sex.man);
String womang = getnumsix(yearnumber(womanyear), sex.woman);
int man = getnumber(mang);
int woman = getnumber(womang);
//数组从0开始,而我们计算从1开始
man--;
woman--;
//注意数组没有第5行和第5列
if (man >= 5) {
man--;
}
if (woman >= 5) {
woman--;
}
//根据 <SUF>
return resultarray[man][woman];//顺序一样的
}
/**
*
* @param year 年份
* @param isman 男的么
* @return 返回宫挂数
*/
public String getnumsix(String year, sex isman) {
for (int i = 0; i < 60; i++) {
if (year.equalsIgnoreCase(numsix[i][0])) {
if (isman == sex.man) {
return numsix[i][3];
} else {
return numsix[i][4];
}
}
}
return null;
}
/**
* 字符串-》数字
*
* @param year 字符串
* @return 字符串对应数字
* @throws NumberFormatException
*/
public int getnumber(String year) throws NumberFormatException {
int yearnumber = Short.parseShort(year);
return yearnumber;
}
/**
* 年份取出年柱
*
* @param year 年数
* @return 求的年份的干支
*/
public String yearnumber(int year) {
//1864年是甲子年,每隔六十年一个甲子
int idx = (Math.abs(year - 1864)) % 60;
//没有过春节的话那么年还算上一年的,此处求的年份的干支
String result = jiazhi[idx];
return result;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
luozhuanglvhehun my = new luozhuanglvhehun();
String result = my.hehun("1947", "1853");
System.out.println(result);
}
}
| 0 |
47306_19 | package final_task; //ディレクトリの関係で記述
import java.util.*;
// デバッグモード
public class LogMode{
public static boolean isLogMode = false;
}
// すべての生物が備える機能
interface Life {
void eat();
void sleep();
void play(Creature p);
}
// 生物の基底クラス
abstract class Creature implements Life {
private String label;
private int hitPoint;
private int point;
public Creature(String label, int hitPoint, int happyPoint) {
this.setName(label);
this.setHp(hitPoint);
this.setHappy(happyPoint);
}
public void stress(int hpDamage, int happyDamage) {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "に" + hpDamage + "の体力ストレス");
System.out.println(this.getName() + "に" + happyDamage + "の幸福度ストレス");
}
this.setHp(this.getHp() - hpDamage);
this.setHappy(this.getHappy() - happyDamage);
if (this.getHp() == 0) {
this.die();
}
}
public void happy (int point) {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "に" + point + "の幸福");
}
this.setHappy(this.getHappy() + point);
}
public void die() {
this.setHp(0);
System.out.println(this.getName() + "は亡くなってしまった...なむさん");
System.exit(0);
}
public void setHp(int hitPoint) {
if (hitPoint > 0 && hitPoint <= 100) {
this.hitPoint = hitPoint;
}
else if(hitPoint >= 100){
this.hitPoint = 100;
} else if (hitPoint <= 0) {
this.hitPoint = 0;
}
}
public int getHp() {
return this.hitPoint;
}
public void setHappy(int point){
if (point > 0 && point <= 100) {
this.point = point;
}
else if(point >= 100){
this.point = 100;
} else if (point <= 0) {
this.point = 0;
}
}
public int getHappy() {
return this.point;
}
public void setName(String label) {
this.label = label;
}
public String getName() {
return this.label;
}
}
// 登場人物の抽象クラス
abstract class Character extends Creature {
public Character(String label, int hitPoint, int happyPoint) {
super(label, hitPoint, happyPoint);
}
public void eat() {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "はご飯を食べた");
}
setHp(this.getHp() + 45);
setHappy(this.getHappy() + 30);
}
public void sleep() {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "は熟睡した");
}
setHp(this.getHp() + 35);
setHappy(this.getHappy() + 40);
}
}
// 猫ちゃんクラス
class Cat extends Character {
public Cat(String label, int hitPoint, int happyPoint) {
super(label, hitPoint, happyPoint);
}
public void play(Creature p){
if(LogMode.isLogMode ==true){
System.out.println(this.getName()+ "は沢山遊んだ");
}
p.happy(getHappy() + 20);
}
}
// プレイヤークラス
class Player extends Character {
public Player(String label, int hitPoint, int happyPoint) {
super(label, hitPoint, happyPoint);
}
public void play(Creature c){
if(LogMode.isLogMode ==true){
System.out.println(this.getName()+ "は沢山遊んだ");
}
c.happy(getHappy() + 30);
}
}
// 現実クラス
public class Main {
public static void main(String[] args) throws Exception {
// 入力値の取得
Scanner sc = new Scanner(System.in);
String[] labels = new String[4];
String[] name_description = {"プレイヤー名", "猫ちゃんの名前"};
for (int i = 0; i < 2; i++) {
System.out.println(name_description[i]+"を入力してください.");
String items = sc.nextLine();
labels[i] = items;
}
// デバッグモードの切り替え
if(labels[0].split(" ").length < 2){
System.out.println("--------------------");
}
else if(labels[0].split(" ")[1].equals("debug")){
LogMode.isLogMode = true;
System.out.println("----デバッグモード----");
labels[0] = "testUser";
}
else{
System.out.println("--------------------");
}
// 入力値の説明
System.out.println("行動コマンド入力方法");
System.out.println("猫ちゃん,プレイヤーの順に食事,遊び,睡眠の有無を入力してください.");
System.out.println("例)110010->猫ちゃんは食事,遊び,プレイヤーは遊びを行う.");
System.out.println("--------------------");
// sc.close();
// 具体的な処理
// 登場人物の生成
int day = 1;
Creature[] lives = new Creature[2];
lives[0] = new Player(labels[0], 100, 100);
lives[1] = new Cat(labels[1], 100, 100);
//コマンド入力に応じて処理を繰り返す
// - 猫ちゃんとプレイヤーの1日ごとの行動をeat,play,sleepの順でコマンド入力で行う
//例1)
//ターミナル出力cat/player
//ターミナル入力111111->猫ちゃんとプレイヤーに対してeat,play,sleepが実行される
//例2)
//ターミナルターミナル出力cat/player
//入力101110->猫ちゃんはeat,sleep,プレイヤーはeat,play,が実行される
//実行されてい項目に対してはstressが実行される
//ターミナルの流れとしては以下の通り
//--------------------
//day1
//cat/player
//111110
//いい調子です
//day2
//猫ちゃんかプレイヤーのhpが0になるまで以下同様
//--------------------
// 体力がある限り実行
while (lives[0].getHp() > 0 || lives[1].getHp() > 0) {
String command = "";
//入力の処理
boolean isValidCommand = false;
while (!isValidCommand) {
System.out.println("day" + day + "の動作を入力");
command = sc.nextLine();
// 正規表現を使用して条件をチェック
if (command.matches("[01]{6}")) {
isValidCommand = true;
} else {
System.out.println("無効な入力です.1か0の6文字で入力してください.");
}
}
// 登場人物ごとの動作
for (Creature live : lives) {
for(int i = 0; i < 3; i++){
char action = command.charAt(i + (lives[0] == live ? 0 : 3));
// それぞれの動作
switch (i % 3) {
case 0:
if(action == '1'){
live.eat();
}else{
live.stress(25,20);
}
break;
case 1:
if(action == '1'){
//猫ちゃんの時はプレイヤーを,プレイヤーの時は猫ちゃんを引数に渡す
live.play(lives[(lives[0] == live) ? 1 : 0]);
}
else{
live.stress(15,10);
}
break;
case 2:
if(action == '1'){
live.sleep();
}
else{
live.stress(20,10);
}
break;
default:
break;
}
}
}
// 相対的な状態の計算
float playerState = (((float)lives[0].getHp() / 100) + ((float)lives[0].getHappy() / 100)) / 2;
float catState = (((float)lives[1].getHp() / 100) + ((float)lives[1].getHappy() / 100)) / 2;
float totalState = (playerState + catState) / 2;
// その日の状態表示
if (totalState >= 0.95) {
System.out.println("お互い幸せです!!");
}
else if(totalState < 0.95 && totalState >= 0.8){
System.out.println("その調子です!");
}
else if(totalState < 0.8 && totalState >= 0.5){
System.out.println("嫌な予感がしますね...");
}
else if(totalState < 0.5){
System.out.println("非常にまずいです");
}
// 上記のデバッグ用表示
if(LogMode.isLogMode ==true){
for (Creature life : lives) {
System.out.println(life.getName() + "の体力: " + life.getHp() + "%");
System.out.println(life.getName() + "の幸福度: " + life.getHappy() + "%");
}
System.out.println("playerState" + playerState);
System.out.println("catState" + catState);
System.out.println("totalState" + totalState);
}
day++;
System.out.println("--------------------");
// sc.close();
}
}
} | 273Do/CatSimulator | Main.java | 2,575 | //例2) | line_comment | zh-cn | package final_task; //ディレクトリの関係で記述
import java.util.*;
// デバッグモード
public class LogMode{
public static boolean isLogMode = false;
}
// すべての生物が備える機能
interface Life {
void eat();
void sleep();
void play(Creature p);
}
// 生物の基底クラス
abstract class Creature implements Life {
private String label;
private int hitPoint;
private int point;
public Creature(String label, int hitPoint, int happyPoint) {
this.setName(label);
this.setHp(hitPoint);
this.setHappy(happyPoint);
}
public void stress(int hpDamage, int happyDamage) {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "に" + hpDamage + "の体力ストレス");
System.out.println(this.getName() + "に" + happyDamage + "の幸福度ストレス");
}
this.setHp(this.getHp() - hpDamage);
this.setHappy(this.getHappy() - happyDamage);
if (this.getHp() == 0) {
this.die();
}
}
public void happy (int point) {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "に" + point + "の幸福");
}
this.setHappy(this.getHappy() + point);
}
public void die() {
this.setHp(0);
System.out.println(this.getName() + "は亡くなってしまった...なむさん");
System.exit(0);
}
public void setHp(int hitPoint) {
if (hitPoint > 0 && hitPoint <= 100) {
this.hitPoint = hitPoint;
}
else if(hitPoint >= 100){
this.hitPoint = 100;
} else if (hitPoint <= 0) {
this.hitPoint = 0;
}
}
public int getHp() {
return this.hitPoint;
}
public void setHappy(int point){
if (point > 0 && point <= 100) {
this.point = point;
}
else if(point >= 100){
this.point = 100;
} else if (point <= 0) {
this.point = 0;
}
}
public int getHappy() {
return this.point;
}
public void setName(String label) {
this.label = label;
}
public String getName() {
return this.label;
}
}
// 登場人物の抽象クラス
abstract class Character extends Creature {
public Character(String label, int hitPoint, int happyPoint) {
super(label, hitPoint, happyPoint);
}
public void eat() {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "はご飯を食べた");
}
setHp(this.getHp() + 45);
setHappy(this.getHappy() + 30);
}
public void sleep() {
if(LogMode.isLogMode ==true){
System.out.println(this.getName() + "は熟睡した");
}
setHp(this.getHp() + 35);
setHappy(this.getHappy() + 40);
}
}
// 猫ちゃんクラス
class Cat extends Character {
public Cat(String label, int hitPoint, int happyPoint) {
super(label, hitPoint, happyPoint);
}
public void play(Creature p){
if(LogMode.isLogMode ==true){
System.out.println(this.getName()+ "は沢山遊んだ");
}
p.happy(getHappy() + 20);
}
}
// プレイヤークラス
class Player extends Character {
public Player(String label, int hitPoint, int happyPoint) {
super(label, hitPoint, happyPoint);
}
public void play(Creature c){
if(LogMode.isLogMode ==true){
System.out.println(this.getName()+ "は沢山遊んだ");
}
c.happy(getHappy() + 30);
}
}
// 現実クラス
public class Main {
public static void main(String[] args) throws Exception {
// 入力値の取得
Scanner sc = new Scanner(System.in);
String[] labels = new String[4];
String[] name_description = {"プレイヤー名", "猫ちゃんの名前"};
for (int i = 0; i < 2; i++) {
System.out.println(name_description[i]+"を入力してください.");
String items = sc.nextLine();
labels[i] = items;
}
// デバッグモードの切り替え
if(labels[0].split(" ").length < 2){
System.out.println("--------------------");
}
else if(labels[0].split(" ")[1].equals("debug")){
LogMode.isLogMode = true;
System.out.println("----デバッグモード----");
labels[0] = "testUser";
}
else{
System.out.println("--------------------");
}
// 入力値の説明
System.out.println("行動コマンド入力方法");
System.out.println("猫ちゃん,プレイヤーの順に食事,遊び,睡眠の有無を入力してください.");
System.out.println("例)110010->猫ちゃんは食事,遊び,プレイヤーは遊びを行う.");
System.out.println("--------------------");
// sc.close();
// 具体的な処理
// 登場人物の生成
int day = 1;
Creature[] lives = new Creature[2];
lives[0] = new Player(labels[0], 100, 100);
lives[1] = new Cat(labels[1], 100, 100);
//コマンド入力に応じて処理を繰り返す
// - 猫ちゃんとプレイヤーの1日ごとの行動をeat,play,sleepの順でコマンド入力で行う
//例1)
//ターミナル出力cat/player
//ターミナル入力111111->猫ちゃんとプレイヤーに対してeat,play,sleepが実行される
//例2 <SUF>
//ターミナルターミナル出力cat/player
//入力101110->猫ちゃんはeat,sleep,プレイヤーはeat,play,が実行される
//実行されてい項目に対してはstressが実行される
//ターミナルの流れとしては以下の通り
//--------------------
//day1
//cat/player
//111110
//いい調子です
//day2
//猫ちゃんかプレイヤーのhpが0になるまで以下同様
//--------------------
// 体力がある限り実行
while (lives[0].getHp() > 0 || lives[1].getHp() > 0) {
String command = "";
//入力の処理
boolean isValidCommand = false;
while (!isValidCommand) {
System.out.println("day" + day + "の動作を入力");
command = sc.nextLine();
// 正規表現を使用して条件をチェック
if (command.matches("[01]{6}")) {
isValidCommand = true;
} else {
System.out.println("無効な入力です.1か0の6文字で入力してください.");
}
}
// 登場人物ごとの動作
for (Creature live : lives) {
for(int i = 0; i < 3; i++){
char action = command.charAt(i + (lives[0] == live ? 0 : 3));
// それぞれの動作
switch (i % 3) {
case 0:
if(action == '1'){
live.eat();
}else{
live.stress(25,20);
}
break;
case 1:
if(action == '1'){
//猫ちゃんの時はプレイヤーを,プレイヤーの時は猫ちゃんを引数に渡す
live.play(lives[(lives[0] == live) ? 1 : 0]);
}
else{
live.stress(15,10);
}
break;
case 2:
if(action == '1'){
live.sleep();
}
else{
live.stress(20,10);
}
break;
default:
break;
}
}
}
// 相対的な状態の計算
float playerState = (((float)lives[0].getHp() / 100) + ((float)lives[0].getHappy() / 100)) / 2;
float catState = (((float)lives[1].getHp() / 100) + ((float)lives[1].getHappy() / 100)) / 2;
float totalState = (playerState + catState) / 2;
// その日の状態表示
if (totalState >= 0.95) {
System.out.println("お互い幸せです!!");
}
else if(totalState < 0.95 && totalState >= 0.8){
System.out.println("その調子です!");
}
else if(totalState < 0.8 && totalState >= 0.5){
System.out.println("嫌な予感がしますね...");
}
else if(totalState < 0.5){
System.out.println("非常にまずいです");
}
// 上記のデバッグ用表示
if(LogMode.isLogMode ==true){
for (Creature life : lives) {
System.out.println(life.getName() + "の体力: " + life.getHp() + "%");
System.out.println(life.getName() + "の幸福度: " + life.getHappy() + "%");
}
System.out.println("playerState" + playerState);
System.out.println("catState" + catState);
System.out.println("totalState" + totalState);
}
day++;
System.out.println("--------------------");
// sc.close();
}
}
} | 1 |
44599_8 | /*
* Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the dreamlu.net developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: Chill 庄骞 (smallchill@163.com)
*/
package org.springblade.modules.mjkj.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
*后台相关
*/
public interface MngMapper {
/**
* 聊天记录
* @return
*/
IPage<Map<String, Object>> getMessageHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 更多好玩-聊天记录
* @return
*/
IPage<Map<String, Object>> getMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 十牛 - 更多好玩-聊天记录
* @return
*/
IPage<Map<String, Object>> getShiniuMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 十牛 - 更多好玩-聊天记录2
* @param page
* @param params
* @return
*/
IPage getShiniuMessageMoreFunHistoryListTwo(Page page, Map<String, Object> params);
/**
* 获取用户列表
* @return
*/
IPage<Map<String, Object>> getWxUserList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
//获取最近三十天的数据-提问次数
List<Map<String,Object>> getMessageCouList();
//获取最近三十天的数据-注册人数
List<Map<String,Object>> getRegisterCouList();
//获取最近三十天的数据-使用人数
List<Map<String,Object>> getUseWuserCouList();
//获取最近三十天的数据-分享次数
List<Map<String,Object>> getShareCouList();
//获取最近三十天的数据-签到次数
List<Map<String,Object>> getSignCouList();
//获取最近三十天的数据-文件下载次数
List<Map<String,Object>> getFileCouList();
/**
* 分享记录
* @return
*/
IPage<Map<String, Object>> getShareHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 消息次数详情
* @return
*/
IPage<Map<String, Object>> getNumLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 今日统计
* @return
*/
IPage<Map<String, Object>> getTodayCountList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 佣金记录
* @return
*/
IPage<Map<String, Object>> getCommissionLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 钱包记录
* @return
*/
IPage<Map<String, Object>> getWalletHistoryLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 订单列表
* @return
*/
IPage<Map<String, Object>> getOrderList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 绘图记录
* @return
*/
IPage<Map<String, Object>> getViewImageList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 绘图记录-待审核
* @return
*/
IPage<Map<String, Object>> getViewImageTodoList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
}
| 274056675/springboot-openai-chatgpt | chatgpt-boot/src/main/java/org/springblade/modules/mjkj/mapper/MngMapper.java | 1,260 | //获取最近三十天的数据-注册人数 | line_comment | zh-cn | /*
* Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the dreamlu.net developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: Chill 庄骞 (smallchill@163.com)
*/
package org.springblade.modules.mjkj.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
*后台相关
*/
public interface MngMapper {
/**
* 聊天记录
* @return
*/
IPage<Map<String, Object>> getMessageHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 更多好玩-聊天记录
* @return
*/
IPage<Map<String, Object>> getMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 十牛 - 更多好玩-聊天记录
* @return
*/
IPage<Map<String, Object>> getShiniuMessageMoreFunHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 十牛 - 更多好玩-聊天记录2
* @param page
* @param params
* @return
*/
IPage getShiniuMessageMoreFunHistoryListTwo(Page page, Map<String, Object> params);
/**
* 获取用户列表
* @return
*/
IPage<Map<String, Object>> getWxUserList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
//获取最近三十天的数据-提问次数
List<Map<String,Object>> getMessageCouList();
//获取 <SUF>
List<Map<String,Object>> getRegisterCouList();
//获取最近三十天的数据-使用人数
List<Map<String,Object>> getUseWuserCouList();
//获取最近三十天的数据-分享次数
List<Map<String,Object>> getShareCouList();
//获取最近三十天的数据-签到次数
List<Map<String,Object>> getSignCouList();
//获取最近三十天的数据-文件下载次数
List<Map<String,Object>> getFileCouList();
/**
* 分享记录
* @return
*/
IPage<Map<String, Object>> getShareHistoryList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 消息次数详情
* @return
*/
IPage<Map<String, Object>> getNumLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 今日统计
* @return
*/
IPage<Map<String, Object>> getTodayCountList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 佣金记录
* @return
*/
IPage<Map<String, Object>> getCommissionLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 钱包记录
* @return
*/
IPage<Map<String, Object>> getWalletHistoryLogList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 订单列表
* @return
*/
IPage<Map<String, Object>> getOrderList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 绘图记录
* @return
*/
IPage<Map<String, Object>> getViewImageList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
/**
* 绘图记录-待审核
* @return
*/
IPage<Map<String, Object>> getViewImageTodoList(@Param("page") IPage<Map<String, Object>> page, @Param("params") Map<String, Object> params);
}
| 0 |
62147_7 | package com.jnhlxd.doudou.model;
import java.util.List;
import com.jnhlxd.doudou.db.PunchDao;
import com.jnhlxd.doudou.manager.PunchMgr;
import com.qianjiang.framework.orm.BaseModel;
/**
* 考勤模块model
*
* @version 1.0
* @author zou.sq
*/
public class DropPickModel extends BaseModel {
public static final String IS_CURRENT_MODEL = "IS_CURRENT_MODEL";
public static final String SIGN_MODE = "SIGN_MODE";
// 上学上车签到模块
public static final int SIGN_TYPE_UP_BUS_TO_SCHOOL = 1;
// 上学下车签到模块
public static final int SIGN_TYPE_DOWN_BUS_TO_SCHOOL = 2;
// 上学入园签到模块
public static final int SIGN_TYPE_IN_SCHOOL = 3;
// 放学出园签到模块
public static final int SIGN_TYPE_OUT_SCHOOL = 4;
// 放学上车签到模块
public static final int SIGN_TYPE_UP_BUS_TO_HOME = 5;
// 放学下车签到模块
public static final int SIGN_TYPE_DOWN_BUS_TO_HOME = 6;
// 病假
public static final int SIGN_TYPE_SICK_LEAVE = 7;
// 事假
public static final int SIGN_TYPE_CASUAL_LEAVE = 8;
private static final long serialVersionUID = 3353521583726991281L;
private int signMode; // 模式类型
private String signModeName; // 模式类型
private String signToast; // 语音播报提示音
private int isCurrentModel; // 是否是当前选择模式,1表示当前模式,0不是当前模式
public int getSignMode() {
return signMode;
}
public void setSignMode(int signMode) {
this.signMode = signMode;
}
public String getSignToast() {
return null == signToast ? "" : signToast;
}
public void setSignToast(String signToast) {
this.signToast = signToast;
}
public boolean isCurrentModel() {
return 1 == isCurrentModel;
}
public void setCurrentModel(int isCurrentModel) {
this.isCurrentModel = isCurrentModel;
}
public String getSignModeName() {
return signModeName;
}
public void setSignModeName(String signModeName) {
this.signModeName = signModeName;
}
/**
* 获取当前的签到模式
*
* @return int 当前的签到模式
*/
public static int getCurrentMode() {
DropPickModel model = PunchDao.getCurrentModule();
if (null != model && 1 == model.isCurrentModel) {
return model.getSignMode();
}
return SIGN_TYPE_IN_SCHOOL;
}
/**
* 获取语音提示信息
*
* @param mode
* 考勤模式
* @return String 语音提示信息
*/
public static String getSpeechMsg(int mode) {
DropPickModel model = PunchDao.getModule(mode);
if (null != model) {
return model.getSignToast();
}
return "";
}
/**
* 更新提示信息
*
* @param mode
* 指定模块
* @param speechMsg
* 提示信息
*/
public static void updateSpeechMsg(int mode, String speechMsg) {
DropPickModel model = PunchDao.getModule(mode);
if (null != model) {
model.setSignToast(speechMsg);
PunchDao.updateModel(model);
}
}
/**
* @Description 设置当前的签到模式
* @param mode
* 当前的签到模式
*/
public static void updateCurrentMode(int mode) {
List<DropPickModel> models = PunchMgr.getSignModules();
if (null != models && !models.isEmpty()) {
for (int i = 0; i < models.size(); i++) {
DropPickModel model = models.get(i);
model.setCurrentModel(model.getSignMode() == mode ? 1 : 0);
PunchDao.updateModel(model);
}
}
}
}
| 280017423/Doudou | src/com/jnhlxd/doudou/model/DropPickModel.java | 1,118 | // 病假
| line_comment | zh-cn | package com.jnhlxd.doudou.model;
import java.util.List;
import com.jnhlxd.doudou.db.PunchDao;
import com.jnhlxd.doudou.manager.PunchMgr;
import com.qianjiang.framework.orm.BaseModel;
/**
* 考勤模块model
*
* @version 1.0
* @author zou.sq
*/
public class DropPickModel extends BaseModel {
public static final String IS_CURRENT_MODEL = "IS_CURRENT_MODEL";
public static final String SIGN_MODE = "SIGN_MODE";
// 上学上车签到模块
public static final int SIGN_TYPE_UP_BUS_TO_SCHOOL = 1;
// 上学下车签到模块
public static final int SIGN_TYPE_DOWN_BUS_TO_SCHOOL = 2;
// 上学入园签到模块
public static final int SIGN_TYPE_IN_SCHOOL = 3;
// 放学出园签到模块
public static final int SIGN_TYPE_OUT_SCHOOL = 4;
// 放学上车签到模块
public static final int SIGN_TYPE_UP_BUS_TO_HOME = 5;
// 放学下车签到模块
public static final int SIGN_TYPE_DOWN_BUS_TO_HOME = 6;
// 病假 <SUF>
public static final int SIGN_TYPE_SICK_LEAVE = 7;
// 事假
public static final int SIGN_TYPE_CASUAL_LEAVE = 8;
private static final long serialVersionUID = 3353521583726991281L;
private int signMode; // 模式类型
private String signModeName; // 模式类型
private String signToast; // 语音播报提示音
private int isCurrentModel; // 是否是当前选择模式,1表示当前模式,0不是当前模式
public int getSignMode() {
return signMode;
}
public void setSignMode(int signMode) {
this.signMode = signMode;
}
public String getSignToast() {
return null == signToast ? "" : signToast;
}
public void setSignToast(String signToast) {
this.signToast = signToast;
}
public boolean isCurrentModel() {
return 1 == isCurrentModel;
}
public void setCurrentModel(int isCurrentModel) {
this.isCurrentModel = isCurrentModel;
}
public String getSignModeName() {
return signModeName;
}
public void setSignModeName(String signModeName) {
this.signModeName = signModeName;
}
/**
* 获取当前的签到模式
*
* @return int 当前的签到模式
*/
public static int getCurrentMode() {
DropPickModel model = PunchDao.getCurrentModule();
if (null != model && 1 == model.isCurrentModel) {
return model.getSignMode();
}
return SIGN_TYPE_IN_SCHOOL;
}
/**
* 获取语音提示信息
*
* @param mode
* 考勤模式
* @return String 语音提示信息
*/
public static String getSpeechMsg(int mode) {
DropPickModel model = PunchDao.getModule(mode);
if (null != model) {
return model.getSignToast();
}
return "";
}
/**
* 更新提示信息
*
* @param mode
* 指定模块
* @param speechMsg
* 提示信息
*/
public static void updateSpeechMsg(int mode, String speechMsg) {
DropPickModel model = PunchDao.getModule(mode);
if (null != model) {
model.setSignToast(speechMsg);
PunchDao.updateModel(model);
}
}
/**
* @Description 设置当前的签到模式
* @param mode
* 当前的签到模式
*/
public static void updateCurrentMode(int mode) {
List<DropPickModel> models = PunchMgr.getSignModules();
if (null != models && !models.isEmpty()) {
for (int i = 0; i < models.size(); i++) {
DropPickModel model = models.get(i);
model.setCurrentModel(model.getSignMode() == mode ? 1 : 0);
PunchDao.updateModel(model);
}
}
}
}
| 1 |
17399_22 | package util;
import core.util.Base64Util;
import core.util.FileReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.net.URL;
public class PdfUtil {
//多页pdf转1张图片
public static String pdf2multiImage(String pdfFile, String outpath) {
try {
URL url = new URL(pdfFile);
InputStream is = url.openStream();
List<BufferedImage> piclist = new ArrayList<BufferedImage>();
PDDocument pdDocument = PDDocument.load(is);
org.apache.pdfbox.rendering.PDFRenderer renderer = new org.apache.pdfbox.rendering.PDFRenderer(pdDocument);
com.lowagie.text.pdf.PdfReader reader = new com.lowagie.text.pdf.PdfReader(pdfFile);
BufferedImage image = null;
for (int i = 0; i < reader.getNumberOfPages(); i++) {
image = renderer.renderImageWithDPI(i, 144); // dpi越大转换后越清晰,相对转换速度越慢
piclist.add(image);
}
imageIOWrite(piclist, outpath);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return outpath;
}
private static void imageIOWrite(List<BufferedImage> piclist, String outPath) {
if (piclist == null || piclist.size() <= 0) {
System.out.println("图片数组为空!");
return;
}
try {
int height = 0, // 总高度
width = 0, // 总宽度
_height = 0, // 临时的高度 , 或保存偏移高度
__height = 0, // 临时的高度,主要保存每个高度
picNum = piclist.size();// 图片的数量
int[] heightArray = new int[picNum]; // 保存每个文件的高度
BufferedImage buffer = null; // 保存图片流
List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
int[] _imgRGB; // 保存一张图片中的RGB数据
for (int i = 0; i < picNum; i++) {
buffer = piclist.get(i);
heightArray[i] = _height = buffer.getHeight();// 图片高度
if (i == 0) {
width = buffer.getWidth();// 图片宽度
}
height += _height; // 获取总高度
_imgRGB = new int[width * _height];// 从图片中读取RGB
_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
imgRGB.add(_imgRGB);
}
_height = 0; // 设置偏移高度为0
// 生成新图片
BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < picNum; i++) {
__height = heightArray[i];
if (i != 0)
_height += __height; // 计算偏移高度
imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
}
File outFile = new File(outPath);
ImageIO.write(imageResult, "jpg", outFile);// 写图片
imageResult.flush();
imgRGB = null;
} catch (Exception e) {
e.printStackTrace();
}
}
private static Map<String,Object> uploadSysFile(String url, String uploadUrl) {
String httpUrl = null;
int id=0;
File file = null;
Map<String,Object> rmap=null;
file = new File(url);
PostMethod filePost = new PostMethod(uploadUrl);
FileReader fr = new FileReader(url);
int status = -1;
try {
InputStream input = new FileInputStream(file);
String strFileName = fr.getFileName();
String base64FileName = Base64Util.getBase64(strFileName);
filePost.setRequestBody(input);
filePost.setRequestHeader("FileName", base64FileName);
filePost.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8");
filePost.setRequestHeader("Content-Length", String.valueOf(file.length()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
input.close();
deleteFile(url);
rmap=new HashMap<String,Object>();
try {
byte[] reSlt = null;
reSlt = filePost.getResponseBody();
String strReSlt = new String(reSlt,"UTF-8");
JSONObject jo = new JSONObject(strReSlt);
if (!jo.isNull("status") && jo.getBoolean("status")) {
if (!jo.isNull("data")) {
String strDate = jo.getString("data");
JSONObject date = new JSONObject(strDate);
httpUrl = date.getString("SourceUrl");
id=date.getInt("Id");
rmap.put("id",id);
rmap.put("url",httpUrl);
return rmap;
}
} else {
// 上传失败
System.out.println("上传失败");
}
} catch (UnsupportedEncodingException u) {
//
u.printStackTrace();
System.out.println(u.getMessage());
} catch (IOException ioe) {
//
ioe.printStackTrace();
System.out.println(ioe.getMessage());
} catch (Exception e) {
//
e.printStackTrace();
System.out.println(e.getMessage());
}
} else {
// 上传失败
System.out.println("上传失败");
}
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
e.printStackTrace();
} catch (IOException e) {
//发生网络异常
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
return null;
}
private static boolean deleteFile(String sPath) {
System.out.println("删除文件开始");
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
System.out.println("文件删除");
file.delete();
flag = true;
}
System.out.println("删除文件结束");
return flag;
}
public static void main(String args[]) {
Map<String, Object> map = null;
try {
map = uploadSysFile(pdf2multiImage("C:\\Users\\Desktop\\aaa.pdf", "C:\\Users\\Desktop\\aaa.jpg"), Constants.getUploadUrl());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(map.get("id").toString());
}
}
| 280868756/canvasStamp | pdfUtil.java | 1,893 | //发生致命的异常,可能是协议不对或者返回的内容有问题 | line_comment | zh-cn | package util;
import core.util.Base64Util;
import core.util.FileReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.net.URL;
public class PdfUtil {
//多页pdf转1张图片
public static String pdf2multiImage(String pdfFile, String outpath) {
try {
URL url = new URL(pdfFile);
InputStream is = url.openStream();
List<BufferedImage> piclist = new ArrayList<BufferedImage>();
PDDocument pdDocument = PDDocument.load(is);
org.apache.pdfbox.rendering.PDFRenderer renderer = new org.apache.pdfbox.rendering.PDFRenderer(pdDocument);
com.lowagie.text.pdf.PdfReader reader = new com.lowagie.text.pdf.PdfReader(pdfFile);
BufferedImage image = null;
for (int i = 0; i < reader.getNumberOfPages(); i++) {
image = renderer.renderImageWithDPI(i, 144); // dpi越大转换后越清晰,相对转换速度越慢
piclist.add(image);
}
imageIOWrite(piclist, outpath);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return outpath;
}
private static void imageIOWrite(List<BufferedImage> piclist, String outPath) {
if (piclist == null || piclist.size() <= 0) {
System.out.println("图片数组为空!");
return;
}
try {
int height = 0, // 总高度
width = 0, // 总宽度
_height = 0, // 临时的高度 , 或保存偏移高度
__height = 0, // 临时的高度,主要保存每个高度
picNum = piclist.size();// 图片的数量
int[] heightArray = new int[picNum]; // 保存每个文件的高度
BufferedImage buffer = null; // 保存图片流
List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
int[] _imgRGB; // 保存一张图片中的RGB数据
for (int i = 0; i < picNum; i++) {
buffer = piclist.get(i);
heightArray[i] = _height = buffer.getHeight();// 图片高度
if (i == 0) {
width = buffer.getWidth();// 图片宽度
}
height += _height; // 获取总高度
_imgRGB = new int[width * _height];// 从图片中读取RGB
_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
imgRGB.add(_imgRGB);
}
_height = 0; // 设置偏移高度为0
// 生成新图片
BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < picNum; i++) {
__height = heightArray[i];
if (i != 0)
_height += __height; // 计算偏移高度
imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
}
File outFile = new File(outPath);
ImageIO.write(imageResult, "jpg", outFile);// 写图片
imageResult.flush();
imgRGB = null;
} catch (Exception e) {
e.printStackTrace();
}
}
private static Map<String,Object> uploadSysFile(String url, String uploadUrl) {
String httpUrl = null;
int id=0;
File file = null;
Map<String,Object> rmap=null;
file = new File(url);
PostMethod filePost = new PostMethod(uploadUrl);
FileReader fr = new FileReader(url);
int status = -1;
try {
InputStream input = new FileInputStream(file);
String strFileName = fr.getFileName();
String base64FileName = Base64Util.getBase64(strFileName);
filePost.setRequestBody(input);
filePost.setRequestHeader("FileName", base64FileName);
filePost.setRequestHeader("Content-Type", "multipart/form-data;charset=utf-8");
filePost.setRequestHeader("Content-Length", String.valueOf(file.length()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
input.close();
deleteFile(url);
rmap=new HashMap<String,Object>();
try {
byte[] reSlt = null;
reSlt = filePost.getResponseBody();
String strReSlt = new String(reSlt,"UTF-8");
JSONObject jo = new JSONObject(strReSlt);
if (!jo.isNull("status") && jo.getBoolean("status")) {
if (!jo.isNull("data")) {
String strDate = jo.getString("data");
JSONObject date = new JSONObject(strDate);
httpUrl = date.getString("SourceUrl");
id=date.getInt("Id");
rmap.put("id",id);
rmap.put("url",httpUrl);
return rmap;
}
} else {
// 上传失败
System.out.println("上传失败");
}
} catch (UnsupportedEncodingException u) {
//
u.printStackTrace();
System.out.println(u.getMessage());
} catch (IOException ioe) {
//
ioe.printStackTrace();
System.out.println(ioe.getMessage());
} catch (Exception e) {
//
e.printStackTrace();
System.out.println(e.getMessage());
}
} else {
// 上传失败
System.out.println("上传失败");
}
} catch (HttpException e) {
//发生 <SUF>
e.printStackTrace();
} catch (IOException e) {
//发生网络异常
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
return null;
}
private static boolean deleteFile(String sPath) {
System.out.println("删除文件开始");
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
System.out.println("文件删除");
file.delete();
flag = true;
}
System.out.println("删除文件结束");
return flag;
}
public static void main(String args[]) {
Map<String, Object> map = null;
try {
map = uploadSysFile(pdf2multiImage("C:\\Users\\Desktop\\aaa.pdf", "C:\\Users\\Desktop\\aaa.jpg"), Constants.getUploadUrl());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(map.get("id").toString());
}
}
| 0 |
19250_0 | package array;
import java.util.ArrayList;
import java.util.List;
/**
* 8 间牢房排成一排,每间牢房不是有人住就是空着。
* <p>
* 每天,无论牢房是被占用或空置,都会根据以下规则进行更改:
* <p>
* 如果一间牢房的两个相邻的房间都被占用或都是空的,那么该牢房就会被占用。
* 否则,它就会被空置。
* (请注意,由于监狱中的牢房排成一行,所以行中的第一个和最后一个房间无法有两个相邻的房间。)
* <p>
* 我们用以下方式描述监狱的当前状态:如果第 i 间牢房被占用,则 cell[i]==1,否则 cell[i]==0。
* <p>
* 根据监狱的初始状态,在 N 天后返回监狱的状况(和上述 N 种变化)。
* <p>
* 示例 1:
* <p>
* 输入:cells = [0,1,0,1,1,0,0,1], N = 7
* 输出:[0,0,1,1,0,0,0,0]
* 解释:
* 下表概述了监狱每天的状况:
* Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
* Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
* Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
* Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
* Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
* Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
* Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
* Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
* <p>
* 示例 2:
* <p>
* 输入:cells = [1,0,0,1,0,0,1,0], N = 1000000000
* 输出:[0,0,1,1,1,1,1,0]
*/
public class PrisonAfterNDays {
public static int[] prisonAfterNDays(int[] cells, int N) {
if (N == 0) {
return cells;
}
int count = N;
boolean flag = false;
List<List<Integer>> ceshi = new ArrayList<>();
while (N > 0) {
int[] result = new int[cells.length];
result[0] = 0;
result[cells.length - 1] = 0;
List<Integer> tp = new ArrayList<>();
for (int i = 1; i < cells.length - 1; i++) {
if ((cells[i - 1] == 1 && cells[i + 1] == 1) || (cells[i - 1] == 0 && cells[i + 1] == 0)) {
result[i] = 1;
} else {
result[i] = 0;
}
}
for (int i = 0; i < cells.length; i++) {
cells[i] = result[i];
tp.add(result[i]);
}
if (ceshi.contains(tp)) {
flag = true;
break;
} else {
ceshi.add(tp);
}
N--;
}
if (flag) {
int a = count - 1;
int b = a % ceshi.size();
List<Integer> r = ceshi.get(b);
int[] s = new int[r.size()];
for (int i = 0 ; i < r.size() ; i++){
s[i] = r.get(i);
}
return s;
} else {
return cells;
}
}
public static void main(String[] args) {
int[] cells = new int[]{0, 1, 0, 1, 1, 0, 0, 1};
prisonAfterNDays(cells, 100);
}
}
| 281613520/leetcode | src/array/PrisonAfterNDays.java | 1,113 | /**
* 8 间牢房排成一排,每间牢房不是有人住就是空着。
* <p>
* 每天,无论牢房是被占用或空置,都会根据以下规则进行更改:
* <p>
* 如果一间牢房的两个相邻的房间都被占用或都是空的,那么该牢房就会被占用。
* 否则,它就会被空置。
* (请注意,由于监狱中的牢房排成一行,所以行中的第一个和最后一个房间无法有两个相邻的房间。)
* <p>
* 我们用以下方式描述监狱的当前状态:如果第 i 间牢房被占用,则 cell[i]==1,否则 cell[i]==0。
* <p>
* 根据监狱的初始状态,在 N 天后返回监狱的状况(和上述 N 种变化)。
* <p>
* 示例 1:
* <p>
* 输入:cells = [0,1,0,1,1,0,0,1], N = 7
* 输出:[0,0,1,1,0,0,0,0]
* 解释:
* 下表概述了监狱每天的状况:
* Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
* Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
* Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
* Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
* Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
* Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
* Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
* Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
* <p>
* 示例 2:
* <p>
* 输入:cells = [1,0,0,1,0,0,1,0], N = 1000000000
* 输出:[0,0,1,1,1,1,1,0]
*/ | block_comment | zh-cn | package array;
import java.util.ArrayList;
import java.util.List;
/**
* 8 间 <SUF>*/
public class PrisonAfterNDays {
public static int[] prisonAfterNDays(int[] cells, int N) {
if (N == 0) {
return cells;
}
int count = N;
boolean flag = false;
List<List<Integer>> ceshi = new ArrayList<>();
while (N > 0) {
int[] result = new int[cells.length];
result[0] = 0;
result[cells.length - 1] = 0;
List<Integer> tp = new ArrayList<>();
for (int i = 1; i < cells.length - 1; i++) {
if ((cells[i - 1] == 1 && cells[i + 1] == 1) || (cells[i - 1] == 0 && cells[i + 1] == 0)) {
result[i] = 1;
} else {
result[i] = 0;
}
}
for (int i = 0; i < cells.length; i++) {
cells[i] = result[i];
tp.add(result[i]);
}
if (ceshi.contains(tp)) {
flag = true;
break;
} else {
ceshi.add(tp);
}
N--;
}
if (flag) {
int a = count - 1;
int b = a % ceshi.size();
List<Integer> r = ceshi.get(b);
int[] s = new int[r.size()];
for (int i = 0 ; i < r.size() ; i++){
s[i] = r.get(i);
}
return s;
} else {
return cells;
}
}
public static void main(String[] args) {
int[] cells = new int[]{0, 1, 0, 1, 1, 0, 0, 1};
prisonAfterNDays(cells, 100);
}
}
| 1 |
34458_4 | package com.textrank;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary;
import com.hankcs.hanlp.seg.common.Term;
import java.util.*;
/**
* TextRank 自动摘要
* @author hankcs
*/
public class TextRankSummary
{
/**
* 阻尼系数(DampingFactor),一般取值为0.85
*/
final double d = 0.85f;
/**
* 最大迭代次数
*/
final int max_iter = 200;
final double min_diff = 0.001f;
/**
* 文档句子的个数
*/
int D;
/**
* 拆分为[句子[单词]]形式的文档
*/
List<List<String>> docs;
/**
* 排序后的最终结果 score <-> index
*/
TreeMap<Double, Integer> top;
/**
* 句子和其他句子的相关程度
*/
double[][] weight;
/**
* 该句子和其他句子相关程度之和
*/
double[] weight_sum;
/**
* 迭代之后收敛的权重
*/
double[] vertex;
/**
* BM25相似度
*/
BM25 bm25;
public TextRankSummary(List<List<String>> docs)
{
this.docs = docs;
bm25 = new BM25(docs);
D = docs.size();
weight = new double[D][D];
weight_sum = new double[D];
vertex = new double[D];
top = new TreeMap<Double, Integer>(Collections.reverseOrder());
solve();
}
private void solve()
{
int cnt = 0;
for (List<String> sentence : docs)
{
double[] scores = bm25.simAll(sentence);
// System.out.println(Arrays.toString(scores));
weight[cnt] = scores;
weight_sum[cnt] = sum(scores) - scores[cnt]; // 减掉自己,自己跟自己肯定最相似
vertex[cnt] = 1.0;
++cnt;
}
for (int _ = 0; _ < max_iter; ++_)
{
double[] m = new double[D];
double max_diff = 0;
for (int i = 0; i < D; ++i)
{
m[i] = 1 - d;
for (int j = 0; j < D; ++j)
{
if (j == i || weight_sum[j] == 0) continue;
m[i] += (d * weight[j][i] / weight_sum[j] * vertex[j]);
}
double diff = Math.abs(m[i] - vertex[i]);
if (diff > max_diff)
{
max_diff = diff;
}
}
vertex = m;
if (max_diff <= min_diff) break;
}
// 我们来排个序吧
for (int i = 0; i < D; ++i)
{
top.put(vertex[i], i);
}
}
/**
* 获取前几个关键句子
* @param size 要几个
* @return 关键句子的下标
*/
public int[] getTopSentence(int size)
{
Collection<Integer> values = top.values();
size = Math.min(size, values.size());
int[] indexArray = new int[size];
Iterator<Integer> it = values.iterator();
for (int i = 0; i < size; ++i)
{
indexArray[i] = it.next();
}
return indexArray;
}
/**
* 简单的求和
* @param array
* @return
*/
private static double sum(double[] array)
{
double total = 0;
for (double v : array)
{
total += v;
}
return total;
}
public static void main(String[] args)
{
String document = "新榜连续2年全国公众号总排名前5 欢迎转载,须署名并注明来自占豪微信,否则追究法律责任。 特朗普治国有多随意?4月9日美国美国政治类网络媒体Axios爆出猛料:之前特朗普在中国清明节假期突然宣布要再对1000亿美元中国产品加征关税的相关决定,根本没有与任何幕僚商量,而是自己突然心血来潮拍脑门的结果! 我勒个天!如果美国真的要再对中国追加1000亿美元的商品征税,那不仅仅意味着贸易战的升级,更意味着中美之间的贸易关系将会受到重创,中美贸易战的规模将立刻上升两个量级,非常危险!当今世界,中美关系是世界上最重要的双边关系。美俄斗成那样,世界都没有乱,但如果中美关系进一步因为特朗普的政策严重恶化,那么全世界都将受到严重威胁,这一切都是因为中国经济的规模太大了,中国经济的影响力太大了! 然而,这么大的事,特朗普和任何人都没商量,直接就宣布了! 这家媒体写道: “白宫里没有召开过哪怕一次会议去探讨这个史上最狠的威胁会有什么好处和坏处,特朗普甚至都没有和他的首席经济顾问库德洛咨询过此事,就直接把他的计划以既定事实的口吻公布了……” 甚至,这件事连白宫幕僚长在事前都没有听说过。由此可见,特朗普施政的随意性和独断性,而这恐怕也是特朗普的重要幕僚一个个辞职的根本原因之一。而从最近的情况看,甚至连他的女儿、女婿都有些噤声了。接下来,相信特朗普的施政还将具有这样的问题,那么大概率还是会有幕僚不断从他的麾下辞职! 然而,现在的问题是,美国接下来怎么办?是继续公布一千亿美元的商品清单?还是对中国进行妥协,放下姿态与中国展开平等互利的谈判?当然,如果美国没有做好向中国出口高科技产品的准备,又有什么资格要求中国在关税上对美国予以照顾呢? 现在,被架在火上烤的是白宫,是特朗普!在没有台阶下的情况下,难道找叙利亚和普京的茬就是好的金蝉脱壳之计吗? 朗普:赶紧坐下吧号主,都被你说中我就没法混了! 点赞、分享,是最好的支持! 占豪系列作品签名版长按二维码订购 战友临走点下方留个手印。如觉文章不错,转发亲朋让大家看到咱的中国立场。 思考者在阅读,点击下面链接查阅 贸易战被中国怼懵了,美国要打击叙利亚普京下令反击! 博鳌中国拱手迎客,却对美迎面一锤,留给特朗普的时间不多了! 外交部狠怼美国一把又亮了!特朗普最新意图在推特曝光! 特朗普突然发推谈贸易战,释放强烈信号! 刚刚,美国软肋彻底暴露!这次中国要狠狠打,把特朗普打回谈判桌! 特朗普再甩千亿,欧日也想捅刀中国?不惜一切代价,打退来犯之敌! 惹毛雄起中国!特朗普,你这次真要“掉得大”! 狠狠打!打出30年经济和平!中国直击美国要害! 贸易战逼中俄联手!中东终于捂不住了,一夜大乱! 中美贸易战,最倒霉的竟是他们,你绝对想不到! 强力实锤反击,中国对美加关税!中国打赢这场贸易战,能得到什么,会损失什么? 中美贸易战,原来有大秘密,中国为何必须打赢? 中国放的这句狠话,美国再听不懂就要出大事了! 中国反击又一重锤!人民币代替美元结算,真是拳拳到肉! 神秘而重磅的访问,他向世界释放7大信号!(文末大福利) 辽宁舰与至少40艘舰南海军演,中国展示势将贸易战打到底的决心! 中国这记重锤,让美国内伤!上海原油期货上市,意义重磅! 中美贸易战,美国必败的3大原因在此! 中国已反击美国!贸易战,中国5招制敌! 中美贸易战背后,是特朗普中东大阴谋! 特朗普炮轰中国,贸易战找错对象,白宫犯三大战略性错误! ";
System.out.println(TextRankSummary.getTopSentenceList(document, 3));
}
/**
* 将文章分割为句子
* @param document
* @return
*/
static List<String> spiltSentence(String document)
{
List<String> sentences = new ArrayList<String>();
if (document == null) return sentences;
for (String line : document.split("[\r\n]"))
{
line = line.trim();
if (line.length() == 0) continue;
for (String sent : line.split("[,,。::“”??!!;;]"))
{
sent = sent.trim();
if (sent.length() == 0) continue;
sentences.add(sent);
}
}
return sentences;
}
/**
* 是否应当将这个term纳入计算,词性属于名词、动词、副词、形容词
* @param term
* @return 是否应当
*/
public static boolean shouldInclude(Term term)
{
return CoreStopWordDictionary.shouldInclude(term);
}
/**
* 一句话调用接口
* @param document 目标文档
* @param size 需要的关键句的个数
* @return 关键句列表
*/
public static List<String> getTopSentenceList(String document, int size)
{
List<String> sentenceList = spiltSentence(document);
List<List<String>> docs = new ArrayList<List<String>>();
for (String sentence : sentenceList)
{
List<Term> termList = HanLP.segment(sentence);
List<String> wordList = new LinkedList<String>();
for (Term term : termList)
{
if (shouldInclude(term))
{
wordList.add(term.word);
}
}
docs.add(wordList);
}
TextRankSummary textRankSummary = new TextRankSummary(docs);
int[] topSentence = textRankSummary.getTopSentence(size);
List<String> resultList = new LinkedList<String>();
for (int i : topSentence)
{
resultList.add(sentenceList.get(i));
}
return resultList;
}
}
| 2817748290/gxtj | src/main/java/com/textrank/TextRankSummary.java | 2,930 | /**
* 拆分为[句子[单词]]形式的文档
*/ | block_comment | zh-cn | package com.textrank;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary;
import com.hankcs.hanlp.seg.common.Term;
import java.util.*;
/**
* TextRank 自动摘要
* @author hankcs
*/
public class TextRankSummary
{
/**
* 阻尼系数(DampingFactor),一般取值为0.85
*/
final double d = 0.85f;
/**
* 最大迭代次数
*/
final int max_iter = 200;
final double min_diff = 0.001f;
/**
* 文档句子的个数
*/
int D;
/**
* 拆分为 <SUF>*/
List<List<String>> docs;
/**
* 排序后的最终结果 score <-> index
*/
TreeMap<Double, Integer> top;
/**
* 句子和其他句子的相关程度
*/
double[][] weight;
/**
* 该句子和其他句子相关程度之和
*/
double[] weight_sum;
/**
* 迭代之后收敛的权重
*/
double[] vertex;
/**
* BM25相似度
*/
BM25 bm25;
public TextRankSummary(List<List<String>> docs)
{
this.docs = docs;
bm25 = new BM25(docs);
D = docs.size();
weight = new double[D][D];
weight_sum = new double[D];
vertex = new double[D];
top = new TreeMap<Double, Integer>(Collections.reverseOrder());
solve();
}
private void solve()
{
int cnt = 0;
for (List<String> sentence : docs)
{
double[] scores = bm25.simAll(sentence);
// System.out.println(Arrays.toString(scores));
weight[cnt] = scores;
weight_sum[cnt] = sum(scores) - scores[cnt]; // 减掉自己,自己跟自己肯定最相似
vertex[cnt] = 1.0;
++cnt;
}
for (int _ = 0; _ < max_iter; ++_)
{
double[] m = new double[D];
double max_diff = 0;
for (int i = 0; i < D; ++i)
{
m[i] = 1 - d;
for (int j = 0; j < D; ++j)
{
if (j == i || weight_sum[j] == 0) continue;
m[i] += (d * weight[j][i] / weight_sum[j] * vertex[j]);
}
double diff = Math.abs(m[i] - vertex[i]);
if (diff > max_diff)
{
max_diff = diff;
}
}
vertex = m;
if (max_diff <= min_diff) break;
}
// 我们来排个序吧
for (int i = 0; i < D; ++i)
{
top.put(vertex[i], i);
}
}
/**
* 获取前几个关键句子
* @param size 要几个
* @return 关键句子的下标
*/
public int[] getTopSentence(int size)
{
Collection<Integer> values = top.values();
size = Math.min(size, values.size());
int[] indexArray = new int[size];
Iterator<Integer> it = values.iterator();
for (int i = 0; i < size; ++i)
{
indexArray[i] = it.next();
}
return indexArray;
}
/**
* 简单的求和
* @param array
* @return
*/
private static double sum(double[] array)
{
double total = 0;
for (double v : array)
{
total += v;
}
return total;
}
public static void main(String[] args)
{
String document = "新榜连续2年全国公众号总排名前5 欢迎转载,须署名并注明来自占豪微信,否则追究法律责任。 特朗普治国有多随意?4月9日美国美国政治类网络媒体Axios爆出猛料:之前特朗普在中国清明节假期突然宣布要再对1000亿美元中国产品加征关税的相关决定,根本没有与任何幕僚商量,而是自己突然心血来潮拍脑门的结果! 我勒个天!如果美国真的要再对中国追加1000亿美元的商品征税,那不仅仅意味着贸易战的升级,更意味着中美之间的贸易关系将会受到重创,中美贸易战的规模将立刻上升两个量级,非常危险!当今世界,中美关系是世界上最重要的双边关系。美俄斗成那样,世界都没有乱,但如果中美关系进一步因为特朗普的政策严重恶化,那么全世界都将受到严重威胁,这一切都是因为中国经济的规模太大了,中国经济的影响力太大了! 然而,这么大的事,特朗普和任何人都没商量,直接就宣布了! 这家媒体写道: “白宫里没有召开过哪怕一次会议去探讨这个史上最狠的威胁会有什么好处和坏处,特朗普甚至都没有和他的首席经济顾问库德洛咨询过此事,就直接把他的计划以既定事实的口吻公布了……” 甚至,这件事连白宫幕僚长在事前都没有听说过。由此可见,特朗普施政的随意性和独断性,而这恐怕也是特朗普的重要幕僚一个个辞职的根本原因之一。而从最近的情况看,甚至连他的女儿、女婿都有些噤声了。接下来,相信特朗普的施政还将具有这样的问题,那么大概率还是会有幕僚不断从他的麾下辞职! 然而,现在的问题是,美国接下来怎么办?是继续公布一千亿美元的商品清单?还是对中国进行妥协,放下姿态与中国展开平等互利的谈判?当然,如果美国没有做好向中国出口高科技产品的准备,又有什么资格要求中国在关税上对美国予以照顾呢? 现在,被架在火上烤的是白宫,是特朗普!在没有台阶下的情况下,难道找叙利亚和普京的茬就是好的金蝉脱壳之计吗? 朗普:赶紧坐下吧号主,都被你说中我就没法混了! 点赞、分享,是最好的支持! 占豪系列作品签名版长按二维码订购 战友临走点下方留个手印。如觉文章不错,转发亲朋让大家看到咱的中国立场。 思考者在阅读,点击下面链接查阅 贸易战被中国怼懵了,美国要打击叙利亚普京下令反击! 博鳌中国拱手迎客,却对美迎面一锤,留给特朗普的时间不多了! 外交部狠怼美国一把又亮了!特朗普最新意图在推特曝光! 特朗普突然发推谈贸易战,释放强烈信号! 刚刚,美国软肋彻底暴露!这次中国要狠狠打,把特朗普打回谈判桌! 特朗普再甩千亿,欧日也想捅刀中国?不惜一切代价,打退来犯之敌! 惹毛雄起中国!特朗普,你这次真要“掉得大”! 狠狠打!打出30年经济和平!中国直击美国要害! 贸易战逼中俄联手!中东终于捂不住了,一夜大乱! 中美贸易战,最倒霉的竟是他们,你绝对想不到! 强力实锤反击,中国对美加关税!中国打赢这场贸易战,能得到什么,会损失什么? 中美贸易战,原来有大秘密,中国为何必须打赢? 中国放的这句狠话,美国再听不懂就要出大事了! 中国反击又一重锤!人民币代替美元结算,真是拳拳到肉! 神秘而重磅的访问,他向世界释放7大信号!(文末大福利) 辽宁舰与至少40艘舰南海军演,中国展示势将贸易战打到底的决心! 中国这记重锤,让美国内伤!上海原油期货上市,意义重磅! 中美贸易战,美国必败的3大原因在此! 中国已反击美国!贸易战,中国5招制敌! 中美贸易战背后,是特朗普中东大阴谋! 特朗普炮轰中国,贸易战找错对象,白宫犯三大战略性错误! ";
System.out.println(TextRankSummary.getTopSentenceList(document, 3));
}
/**
* 将文章分割为句子
* @param document
* @return
*/
static List<String> spiltSentence(String document)
{
List<String> sentences = new ArrayList<String>();
if (document == null) return sentences;
for (String line : document.split("[\r\n]"))
{
line = line.trim();
if (line.length() == 0) continue;
for (String sent : line.split("[,,。::“”??!!;;]"))
{
sent = sent.trim();
if (sent.length() == 0) continue;
sentences.add(sent);
}
}
return sentences;
}
/**
* 是否应当将这个term纳入计算,词性属于名词、动词、副词、形容词
* @param term
* @return 是否应当
*/
public static boolean shouldInclude(Term term)
{
return CoreStopWordDictionary.shouldInclude(term);
}
/**
* 一句话调用接口
* @param document 目标文档
* @param size 需要的关键句的个数
* @return 关键句列表
*/
public static List<String> getTopSentenceList(String document, int size)
{
List<String> sentenceList = spiltSentence(document);
List<List<String>> docs = new ArrayList<List<String>>();
for (String sentence : sentenceList)
{
List<Term> termList = HanLP.segment(sentence);
List<String> wordList = new LinkedList<String>();
for (Term term : termList)
{
if (shouldInclude(term))
{
wordList.add(term.word);
}
}
docs.add(wordList);
}
TextRankSummary textRankSummary = new TextRankSummary(docs);
int[] topSentence = textRankSummary.getTopSentence(size);
List<String> resultList = new LinkedList<String>();
for (int i : topSentence)
{
resultList.add(sentenceList.get(i));
}
return resultList;
}
}
| 0 |
9418_1 | package io.github.biezhi.wechat.api;
import io.github.biezhi.wechat.WeChatBot;
import io.github.biezhi.wechat.api.model.SyncCheckRet;
import io.github.biezhi.wechat.api.response.WebSyncResponse;
import io.github.biezhi.wechat.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import static io.github.biezhi.wechat.api.enums.RetCode.*;
/**
* 轮训监听消息
*
* @author biezhi
* @date 2018/1/21
*/
@Slf4j
public class ChatLoop implements Runnable {
private WeChatBot bot;
private WeChatApi api;
private int retryCount = 0;
ChatLoop(WeChatBot bot) {
this.bot = bot;
this.api = bot.api();
}
@Override
public void run() {
while (bot.isRunning()) {
try {
SyncCheckRet syncCheckRet = api.syncCheck();
if (syncCheckRet.getRetCode() == UNKNOWN) {
log.info("未知状态");
continue;
} else if (syncCheckRet.getRetCode() == MOBILE_LOGIN_OUT) {
log.info("你在手机上登出了微信,再见");
api.logout();
break;
} else if (syncCheckRet.getRetCode() == LOGIN_OTHERWISE) {
log.info("你在其他地方登录了 WEB 版微信,再见");
api.logout();
break;
} else if (syncCheckRet.getRetCode() == NORMAL) {
// 更新最后一次正常检查时间
bot.updateLastCheck();
WebSyncResponse webSyncResponse = api.webSync();
switch (syncCheckRet.getSelector()) {
case 2:
if (null == webSyncResponse) {
break;
}
bot.addMessages(api.handleMsg(webSyncResponse.getAddMessageList()));
break;
case 6:
log.info("收到疑似红包消息");
break;
default:
break;
}
}
if (System.currentTimeMillis() - bot.getLastCheckTs() <= 30) {
DateUtils.sleep(System.currentTimeMillis() - bot.getLastCheckTs());
}
} catch (Exception e) {
log.warn(e.getMessage());
retryCount += 1;
if (bot.getReceiveRetryCount() < retryCount) {
bot.setRunning(false);
} else {
DateUtils.sleep(1000);
}
}
}
}
}
| 282919088/wechat-api | src/main/java/io/github/biezhi/wechat/api/ChatLoop.java | 612 | // 更新最后一次正常检查时间 | line_comment | zh-cn | package io.github.biezhi.wechat.api;
import io.github.biezhi.wechat.WeChatBot;
import io.github.biezhi.wechat.api.model.SyncCheckRet;
import io.github.biezhi.wechat.api.response.WebSyncResponse;
import io.github.biezhi.wechat.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import static io.github.biezhi.wechat.api.enums.RetCode.*;
/**
* 轮训监听消息
*
* @author biezhi
* @date 2018/1/21
*/
@Slf4j
public class ChatLoop implements Runnable {
private WeChatBot bot;
private WeChatApi api;
private int retryCount = 0;
ChatLoop(WeChatBot bot) {
this.bot = bot;
this.api = bot.api();
}
@Override
public void run() {
while (bot.isRunning()) {
try {
SyncCheckRet syncCheckRet = api.syncCheck();
if (syncCheckRet.getRetCode() == UNKNOWN) {
log.info("未知状态");
continue;
} else if (syncCheckRet.getRetCode() == MOBILE_LOGIN_OUT) {
log.info("你在手机上登出了微信,再见");
api.logout();
break;
} else if (syncCheckRet.getRetCode() == LOGIN_OTHERWISE) {
log.info("你在其他地方登录了 WEB 版微信,再见");
api.logout();
break;
} else if (syncCheckRet.getRetCode() == NORMAL) {
// 更新 <SUF>
bot.updateLastCheck();
WebSyncResponse webSyncResponse = api.webSync();
switch (syncCheckRet.getSelector()) {
case 2:
if (null == webSyncResponse) {
break;
}
bot.addMessages(api.handleMsg(webSyncResponse.getAddMessageList()));
break;
case 6:
log.info("收到疑似红包消息");
break;
default:
break;
}
}
if (System.currentTimeMillis() - bot.getLastCheckTs() <= 30) {
DateUtils.sleep(System.currentTimeMillis() - bot.getLastCheckTs());
}
} catch (Exception e) {
log.warn(e.getMessage());
retryCount += 1;
if (bot.getReceiveRetryCount() < retryCount) {
bot.setRunning(false);
} else {
DateUtils.sleep(1000);
}
}
}
}
}
| 0 |
22655_30 | // _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖镇楼 BUG辟易
// 佛曰:
// 写字楼里写字间,写字间里程序员;
// 程序人员写程序,又拿程序换酒钱。
// 酒醒只在网上坐,酒醉还来网下眠;
// 酒醉酒醒日复日,网上网下年复年。
// 但愿老死电脑间,不愿鞠躬老板前;
// 奔驰宝马贵者趣,公交自行程序员。
// 别人笑我忒疯癫,我笑自己命太贱;
// 不见满街漂亮妹,哪个归得程序员?
package com.lb.wecharenglish.global;
/**
* 项目名称:ysp-android<br>
* 作者:IceLee<br>
* 邮箱:lb291700351@live.cn<br>
* 时间:2016/7/5 20:42<br>
* 类描述:程序中使用的键 <br>
*/
public interface Keys {
/**
* 是否是第一次运行app的键
*/
String Key_IS_FIRST_RUN_APP = "isFirstRunApp";
/**
* 页面传递每日一句的键
*/
String KEY_ENGLISH_BEAN = "englishBean";
/**
* 用户名
*/
String USER_NAME = "user_name";
}
| 291700351/WeCharEnglish | app/src/main/java/com/lb/wecharenglish/global/Keys.java | 629 | /**
* 是否是第一次运行app的键
*/ | block_comment | zh-cn | // _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// . ' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
//
// .............................................
// 佛祖镇楼 BUG辟易
// 佛曰:
// 写字楼里写字间,写字间里程序员;
// 程序人员写程序,又拿程序换酒钱。
// 酒醒只在网上坐,酒醉还来网下眠;
// 酒醉酒醒日复日,网上网下年复年。
// 但愿老死电脑间,不愿鞠躬老板前;
// 奔驰宝马贵者趣,公交自行程序员。
// 别人笑我忒疯癫,我笑自己命太贱;
// 不见满街漂亮妹,哪个归得程序员?
package com.lb.wecharenglish.global;
/**
* 项目名称:ysp-android<br>
* 作者:IceLee<br>
* 邮箱:lb291700351@live.cn<br>
* 时间:2016/7/5 20:42<br>
* 类描述:程序中使用的键 <br>
*/
public interface Keys {
/**
* 是否是 <SUF>*/
String Key_IS_FIRST_RUN_APP = "isFirstRunApp";
/**
* 页面传递每日一句的键
*/
String KEY_ENGLISH_BEAN = "englishBean";
/**
* 用户名
*/
String USER_NAME = "user_name";
}
| 0 |
11109_2 | package yplugin.Ajob;
import net.mamoe.mirai.contact.Friend;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import yplugin.Plugin;
import yplugin.Utils.AJobScheduler;
/**
* @Description YWX打卡提醒任务
* @author pan
* @Since 2023年2月24日17:41:13
*/
public class YWXJobTip implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
Plugin.INSTANCE.getLogger().info("YWX打卡提醒任务 启动成功");
// 指定人发送信息 宝贝
Friend friend = AJobScheduler.bot.getFriend(2779072927L);
if(friend == null){
Plugin.INSTANCE.getLogger().info("您还没有该好友");
}else {
friend.sendMessage("宝贝~你今天打卡了么? \n (づ ̄3 ̄)づ╭❤~");
}
// 指定人发送信息 田璐
Friend tian = AJobScheduler.bot.getFriend(1512396422L);
if(tian == null){
Plugin.INSTANCE.getLogger().info("您还没有该好友");
}else {
tian.sendMessage("嗨~你今天打卡了吗 \n ~(๑•̀ㅂ•́)و✧");
}
}
}
| 296711867/mirai-console-QQ-Robot-yPlugin | src/main/java/yplugin/Ajob/YWXJobTip.java | 360 | // 指定人发送信息 田璐 | line_comment | zh-cn | package yplugin.Ajob;
import net.mamoe.mirai.contact.Friend;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import yplugin.Plugin;
import yplugin.Utils.AJobScheduler;
/**
* @Description YWX打卡提醒任务
* @author pan
* @Since 2023年2月24日17:41:13
*/
public class YWXJobTip implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
Plugin.INSTANCE.getLogger().info("YWX打卡提醒任务 启动成功");
// 指定人发送信息 宝贝
Friend friend = AJobScheduler.bot.getFriend(2779072927L);
if(friend == null){
Plugin.INSTANCE.getLogger().info("您还没有该好友");
}else {
friend.sendMessage("宝贝~你今天打卡了么? \n (づ ̄3 ̄)づ╭❤~");
}
// 指定 <SUF>
Friend tian = AJobScheduler.bot.getFriend(1512396422L);
if(tian == null){
Plugin.INSTANCE.getLogger().info("您还没有该好友");
}else {
tian.sendMessage("嗨~你今天打卡了吗 \n ~(๑•̀ㅂ•́)و✧");
}
}
}
| 1 |
44813_5 | package com.bit.pedometer.ui.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bit.pedometer.R;
import com.bit.pedometer.ui.view.MyDialog;
/**
* Created by Android Studio. author: liyachao Date: 15/5/20 Time: 16:31
*/
public abstract class BaseActivity extends FragmentActivity {
/**
* 自定义的吐司
*/
private Toast toast;
// /**
// * 吐司中显示的文字
// */
// private TextView toastTextView;
/**
* 使用handler发送吐司
*/
private Handler handler = new Handler();
/**
* 显示对话框
*/
private MyDialog dialog;
/**
* 现实进度条
*/
private ProgressDialog progressDialog;
/**
* 软键盘管理工具
*/
InputMethodManager imm;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setContentView();
initView();
setTitle();
initData();
setEvent();
}
/**
* 初始化布局
*/
protected abstract void setContentView();
/**
* 初始化控件
*/
protected abstract void initView();
/**
* 设置标头
*/
protected abstract void setTitle();
/**
* 初始化值
*/
protected abstract void initData();
/**
* 设置事件
*/
protected abstract void setEvent();
private void init() {
context = this;
/**
* 初始化吐司和吐司的布局文件
*/
// LayoutInflater inflater = LayoutInflater.from(this);
// View view = inflater.inflate(R.layout.toast_layout, null);
// toastTextView = (TextView) view.findViewById(R.id.toast_text);
// toast = new Toast(getApplicationContext());
// toast.setView(view);
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
/**
* 初始化进度框
*/
progressDialog = new ProgressDialog(this, R.style.ProgressDialog);
/**
* 初始化软键盘管理工具
*/
imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
}
protected <T extends View> T getView(int viewId) {
View view = findViewById(viewId);
return (T) view;
}
/**
* 设置标题栏
*
* @param str 标题栏文字
*/
protected void setTitleText(String str) {
TextView titleText = (TextView) findViewById(R.id.center_title);
titleText.setText(str);
}
/**
* 设置标题栏颜色
*
* @param colorStr 标题栏颜色
*/
protected void setMyTitleColor(String colorStr) {
RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
titleLayout.setBackgroundColor(Color.parseColor(colorStr));
}
/**
* 设置标题栏颜色
*
* @param color 标题栏颜色
*/
protected void setMyTitleColor(int color) {
RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
titleLayout.setBackgroundColor(color);
}
/**
* 显示标题栏左部图片
*
* @param resId 图片资源的ID
* @param clickListener 点击事件
*/
protected void showLeftWithImage(int resId,
View.OnClickListener clickListener) {
ImageView leftImage = (ImageView) findViewById(R.id.left_title_image);
leftImage.setVisibility(View.VISIBLE);
leftImage.setImageResource(resId);
//设置点击区域
LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout);
leftClickRange.setOnClickListener(clickListener);
}
/**
* 显示左部的文字
*
* @param str 所要显示的文字
* @param clickListener 点击事件
*/
protected void showLeftWithText(String str,
View.OnClickListener clickListener) {
TextView leftText = (TextView) findViewById(R.id.left_title_text);
leftText.setVisibility(View.VISIBLE);
leftText.setText(str);
//设置点击区域
LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout);
leftClickRange.setOnClickListener(clickListener);
}
/**
* 显示标题栏右部图片
*
* @param resId 图片资源的ID
* @param clickListener 点击事件
*/
protected void showRightWithImage(int resId,
View.OnClickListener clickListener) {
ImageView rightImage = (ImageView) findViewById(R.id.right_title_image);
rightImage.setVisibility(View.VISIBLE);
rightImage.setImageResource(resId);
//设置点击区域
LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout);
rightClickRange.setOnClickListener(clickListener);
}
/**
* 显示标题栏右部第二个图片
*
* @param resId 图片资源的ID
* @param clickListener 点击事件
*/
protected void showRightWithSecondImage(int resId,
View.OnClickListener clickListener) {
ImageView rightImage = (ImageView) findViewById(R.id.right_second_title_image);
rightImage.setVisibility(View.VISIBLE);
rightImage.setImageResource(resId);
//设置点击区域
LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_second_title_layout);
rightClickRange.setOnClickListener(clickListener);
}
/**
* 显示右部的文字
*
* @param str 所要显示的文字
* @param clickListener 点击事件
*/
protected void showRightWithText(String str,
View.OnClickListener clickListener) {
TextView rightText = (TextView) findViewById(R.id.right_title_text);
rightText.setVisibility(View.VISIBLE);
rightText.setText(str);
//设置点击区域
LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout);
rightClickRange.setOnClickListener(clickListener);
}
/**
* 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同
*
* @param strId 在strings.xml对应的字符串
* @param booleans
*/
protected void showToast(int strId, boolean[] booleans) {
String str = getResources().getString(strId);
showToast(str, booleans);
}
/**
* 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同
*
* @param str 吐司的内容
* @param booleans 输入框是否有焦点
*/
protected void showToast(final String str, final boolean[] booleans) {
runOnUiThread(new Runnable() {
@Override
public void run() {
toast.setText(str);
// toast.setGravity(Gravity.TOP, 0, dp2px(60));
boolean isAllFocused = false;//是否输入框一个都没有选中
if (booleans != null) {
for (boolean b : booleans) {
if (b) {
isAllFocused = true;
break;
}
}
}
if (isAllFocused) {
closeSoftKeyboard();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.show();
// Toast toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
}
}, 300);
} else {
toast.show();
// Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* 关闭软键盘
*/
protected void closeSoftKeyboard() {
if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
/**
* 开启软键盘
*/
protected void showSoftKeyboard() {
imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
}
protected void showToast(String str) {
showToast(str, null);
}
protected void showToast(int strId) {
showToast(strId, null);
}
/**
* 显示进度框
*
* @param message 传入显示的文字
*/
protected void showProgressDialog(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && (progressDialog.isShowing())) {
progressDialog.dismiss();
return true;
}
return false;
}
});
}
});
}
/**
* 显示进度框
*
* @param message
* @param keyListener 监听点击返回按钮
*/
protected void showProgressDialog(final String message, final DialogInterface.OnKeyListener keyListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setOnKeyListener(keyListener);
}
});
}
/**
* 现实对话框
*
* @param message 输入显示的文字
* @param sureListener 监听事件
*/
protected void showDialog(final String message, final View.OnClickListener sureListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* 初始化对话框
*/
dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog);
dialog.setCancelable(false);
dialog.setDialogTitle("提示");
dialog.setDialogContent(message);
dialog.setMyOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
}, sureListener);
dialog.show();
}
});
}
/**
* 现实对话框
*
* @param message 输入显示的文字
* @param sureListener 监听事件
*/
protected void showDialog(final String message,
final String leftButtonStr, final String rightButtonStr,
final View.OnClickListener sureListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* 初始化对话框
*/
dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog);
dialog.setCancelable(false);
dialog.setDialogTitle("提示");
dialog.setButtonText(leftButtonStr, rightButtonStr);
dialog.setDialogContent(message);
dialog.setMyOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
}, sureListener);
dialog.show();
}
});
}
/**
* 现实对话框
*
* @param message 输入显示的文字
* @param sureListener 监听事件
*/
protected void showDialog(final String message, final View.OnClickListener sureListener
, final View.OnClickListener cancelListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* 初始化对话框
*/
dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog);
dialog.setCancelable(false);
dialog.setDialogTitle("提示");
dialog.setDialogContent(message);
dialog.setMyOnclickListener(cancelListener, sureListener);
dialog.show();
}
});
}
/**
* 关闭对话框
*/
protected void cancelProgressDialog() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.cancel();
}
/**
* 关闭进度框
*/
protected void cancelDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
/**
* popupwindow关闭,显示正常
*/
protected void onLight() {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1.0f;
getWindow().setAttributes(lp);
}
/**
* popupwindow开启,显示暗色
*/
protected void offLight() {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.7f;
getWindow().setAttributes(lp);
}
} | 296777513/pedometer | pedometer/src/com/bit/pedometer/ui/activity/BaseActivity.java | 3,063 | /**
* 显示对话框
*/ | block_comment | zh-cn | package com.bit.pedometer.ui.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bit.pedometer.R;
import com.bit.pedometer.ui.view.MyDialog;
/**
* Created by Android Studio. author: liyachao Date: 15/5/20 Time: 16:31
*/
public abstract class BaseActivity extends FragmentActivity {
/**
* 自定义的吐司
*/
private Toast toast;
// /**
// * 吐司中显示的文字
// */
// private TextView toastTextView;
/**
* 使用handler发送吐司
*/
private Handler handler = new Handler();
/**
* 显示对 <SUF>*/
private MyDialog dialog;
/**
* 现实进度条
*/
private ProgressDialog progressDialog;
/**
* 软键盘管理工具
*/
InputMethodManager imm;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setContentView();
initView();
setTitle();
initData();
setEvent();
}
/**
* 初始化布局
*/
protected abstract void setContentView();
/**
* 初始化控件
*/
protected abstract void initView();
/**
* 设置标头
*/
protected abstract void setTitle();
/**
* 初始化值
*/
protected abstract void initData();
/**
* 设置事件
*/
protected abstract void setEvent();
private void init() {
context = this;
/**
* 初始化吐司和吐司的布局文件
*/
// LayoutInflater inflater = LayoutInflater.from(this);
// View view = inflater.inflate(R.layout.toast_layout, null);
// toastTextView = (TextView) view.findViewById(R.id.toast_text);
// toast = new Toast(getApplicationContext());
// toast.setView(view);
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
/**
* 初始化进度框
*/
progressDialog = new ProgressDialog(this, R.style.ProgressDialog);
/**
* 初始化软键盘管理工具
*/
imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
}
protected <T extends View> T getView(int viewId) {
View view = findViewById(viewId);
return (T) view;
}
/**
* 设置标题栏
*
* @param str 标题栏文字
*/
protected void setTitleText(String str) {
TextView titleText = (TextView) findViewById(R.id.center_title);
titleText.setText(str);
}
/**
* 设置标题栏颜色
*
* @param colorStr 标题栏颜色
*/
protected void setMyTitleColor(String colorStr) {
RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
titleLayout.setBackgroundColor(Color.parseColor(colorStr));
}
/**
* 设置标题栏颜色
*
* @param color 标题栏颜色
*/
protected void setMyTitleColor(int color) {
RelativeLayout titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
titleLayout.setBackgroundColor(color);
}
/**
* 显示标题栏左部图片
*
* @param resId 图片资源的ID
* @param clickListener 点击事件
*/
protected void showLeftWithImage(int resId,
View.OnClickListener clickListener) {
ImageView leftImage = (ImageView) findViewById(R.id.left_title_image);
leftImage.setVisibility(View.VISIBLE);
leftImage.setImageResource(resId);
//设置点击区域
LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout);
leftClickRange.setOnClickListener(clickListener);
}
/**
* 显示左部的文字
*
* @param str 所要显示的文字
* @param clickListener 点击事件
*/
protected void showLeftWithText(String str,
View.OnClickListener clickListener) {
TextView leftText = (TextView) findViewById(R.id.left_title_text);
leftText.setVisibility(View.VISIBLE);
leftText.setText(str);
//设置点击区域
LinearLayout leftClickRange = (LinearLayout) findViewById(R.id.left_title_layout);
leftClickRange.setOnClickListener(clickListener);
}
/**
* 显示标题栏右部图片
*
* @param resId 图片资源的ID
* @param clickListener 点击事件
*/
protected void showRightWithImage(int resId,
View.OnClickListener clickListener) {
ImageView rightImage = (ImageView) findViewById(R.id.right_title_image);
rightImage.setVisibility(View.VISIBLE);
rightImage.setImageResource(resId);
//设置点击区域
LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout);
rightClickRange.setOnClickListener(clickListener);
}
/**
* 显示标题栏右部第二个图片
*
* @param resId 图片资源的ID
* @param clickListener 点击事件
*/
protected void showRightWithSecondImage(int resId,
View.OnClickListener clickListener) {
ImageView rightImage = (ImageView) findViewById(R.id.right_second_title_image);
rightImage.setVisibility(View.VISIBLE);
rightImage.setImageResource(resId);
//设置点击区域
LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_second_title_layout);
rightClickRange.setOnClickListener(clickListener);
}
/**
* 显示右部的文字
*
* @param str 所要显示的文字
* @param clickListener 点击事件
*/
protected void showRightWithText(String str,
View.OnClickListener clickListener) {
TextView rightText = (TextView) findViewById(R.id.right_title_text);
rightText.setVisibility(View.VISIBLE);
rightText.setText(str);
//设置点击区域
LinearLayout rightClickRange = (LinearLayout) findViewById(R.id.right_title_layout);
rightClickRange.setOnClickListener(clickListener);
}
/**
* 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同
*
* @param strId 在strings.xml对应的字符串
* @param booleans
*/
protected void showToast(int strId, boolean[] booleans) {
String str = getResources().getString(strId);
showToast(str, booleans);
}
/**
* 显示自定义的Toast,并在有软键盘和没有软键盘弹出时间不相同
*
* @param str 吐司的内容
* @param booleans 输入框是否有焦点
*/
protected void showToast(final String str, final boolean[] booleans) {
runOnUiThread(new Runnable() {
@Override
public void run() {
toast.setText(str);
// toast.setGravity(Gravity.TOP, 0, dp2px(60));
boolean isAllFocused = false;//是否输入框一个都没有选中
if (booleans != null) {
for (boolean b : booleans) {
if (b) {
isAllFocused = true;
break;
}
}
}
if (isAllFocused) {
closeSoftKeyboard();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.show();
// Toast toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
}
}, 300);
} else {
toast.show();
// Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* 关闭软键盘
*/
protected void closeSoftKeyboard() {
if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
/**
* 开启软键盘
*/
protected void showSoftKeyboard() {
imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
}
protected void showToast(String str) {
showToast(str, null);
}
protected void showToast(int strId) {
showToast(strId, null);
}
/**
* 显示进度框
*
* @param message 传入显示的文字
*/
protected void showProgressDialog(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && (progressDialog.isShowing())) {
progressDialog.dismiss();
return true;
}
return false;
}
});
}
});
}
/**
* 显示进度框
*
* @param message
* @param keyListener 监听点击返回按钮
*/
protected void showProgressDialog(final String message, final DialogInterface.OnKeyListener keyListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setOnKeyListener(keyListener);
}
});
}
/**
* 现实对话框
*
* @param message 输入显示的文字
* @param sureListener 监听事件
*/
protected void showDialog(final String message, final View.OnClickListener sureListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* 初始化对话框
*/
dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog);
dialog.setCancelable(false);
dialog.setDialogTitle("提示");
dialog.setDialogContent(message);
dialog.setMyOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
}, sureListener);
dialog.show();
}
});
}
/**
* 现实对话框
*
* @param message 输入显示的文字
* @param sureListener 监听事件
*/
protected void showDialog(final String message,
final String leftButtonStr, final String rightButtonStr,
final View.OnClickListener sureListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* 初始化对话框
*/
dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog);
dialog.setCancelable(false);
dialog.setDialogTitle("提示");
dialog.setButtonText(leftButtonStr, rightButtonStr);
dialog.setDialogContent(message);
dialog.setMyOnclickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
}, sureListener);
dialog.show();
}
});
}
/**
* 现实对话框
*
* @param message 输入显示的文字
* @param sureListener 监听事件
*/
protected void showDialog(final String message, final View.OnClickListener sureListener
, final View.OnClickListener cancelListener) {
runOnUiThread(new Runnable() {
@Override
public void run() {
/**
* 初始化对话框
*/
dialog = new MyDialog(BaseActivity.this, R.style.TransparentDialog);
dialog.setCancelable(false);
dialog.setDialogTitle("提示");
dialog.setDialogContent(message);
dialog.setMyOnclickListener(cancelListener, sureListener);
dialog.show();
}
});
}
/**
* 关闭对话框
*/
protected void cancelProgressDialog() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.cancel();
}
/**
* 关闭进度框
*/
protected void cancelDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
/**
* popupwindow关闭,显示正常
*/
protected void onLight() {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1.0f;
getWindow().setAttributes(lp);
}
/**
* popupwindow开启,显示暗色
*/
protected void offLight() {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.7f;
getWindow().setAttributes(lp);
}
} | 0 |
48608_22 | package com.example.pay.controller;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePayRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeRefundRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPayResult;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FRefundResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.example.pay.configuration.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* 支付宝-当面付 控制器.
* https://openclub.alipay.com/read.php?tid=1720&fid=40
*
* https://docs.open.alipay.com/203/105910
*
*/
@Slf4j
@RestController
@RequestMapping("/alipay/f2fpay")
public class AlipayF2FPayController {
@Autowired
private AlipayTradeService alipayTradeService;
@Autowired
private AlipayProperties aliPayProperties;
/**
* 当面付-条码付
*
* 商家使用扫码工具(扫码枪等)扫描用户支付宝的付款码
*
* @param authCode
*/
@PostMapping("/barCodePay")
public String barCodePay(String authCode){
// 实际使用时需要根据商品id查询商品的基本信息并计算价格(可能还有什么优惠),这里只是写死值来测试
// (必填) 商户网站订单系统中唯一订单号,64个字符以内,只能包含字母、数字、下划线,
String outTradeNo = UUID.randomUUID().toString();
// (必填) 订单标题,粗略描述用户的支付目的。如“喜士多(浦东店)消费”
String subject = "测试订单";
// 订单描述,可以对交易或商品进行一个详细地描述,比如填写"购买商品2件共15.00元"
String body = "购买商品2件共20.05元";
// (必填) 订单总金额,单位为元,不能超过1亿元
// 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
String totalAmount = "0.01";
// (可选) 订单不可打折金额,可以配合商家平台配置折扣活动,如果酒水不参与打折,则将对应金额填写至此字段
// 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
String undiscountableAmount = "";
// (必填) 商户门店编号,通过门店号和商家后台可以配置精准到门店的折扣信息,详询支付宝技术支持
String storeId = "test_store_id";
// 商户操作员编号,添加此参数可以为商户操作员做销售统计
String operatorId = "test_operator_id";
// 商品明细列表,需填写购买商品详细信息,
List<GoodsDetail> goodsDetailList = new ArrayList<>();
GoodsDetail goods1 = GoodsDetail.newInstance("goods_id001", "全麦小面包", 1, 1);
goodsDetailList.add(goods1);
GoodsDetail goods2 = GoodsDetail.newInstance("goods_id002", "黑人牙刷", 1, 2);
goodsDetailList.add(goods2);
// 支付超时,线下扫码交易定义为5分钟
String timeoutExpress = "5m";
AlipayTradePayRequestBuilder builder = new AlipayTradePayRequestBuilder()
.setOutTradeNo(outTradeNo)
.setSubject(subject)
.setBody(body)
.setTotalAmount(totalAmount)
.setAuthCode(authCode)
.setTotalAmount(totalAmount)
.setStoreId(storeId)
.setOperatorId(operatorId)
.setGoodsDetailList(goodsDetailList)
.setTimeoutExpress(timeoutExpress);
// 当面付,面对面付,face to face pay -> face 2 face pay -> f2f pay
// 同步返回支付结果
AlipayF2FPayResult f2FPayResult = alipayTradeService.tradePay(builder);
// 注意:一定要处理支付的结果,因为不是每次支付都一定会成功,可能会失败
switch (f2FPayResult.getTradeStatus()) {
case SUCCESS:
log.info("支付宝支付成功: )");
break;
case FAILED:
log.error("支付宝支付失败!!!");
break;
case UNKNOWN:
log.error("系统异常,订单状态未知!!!");
break;
default:
log.error("不支持的交易状态,交易返回异常!!!");
break;
}
/**
* {
* "alipay_trade_pay_response": {
* "code": "10000",
* "msg": "Success",
* "buyer_logon_id": "ekf***@sandbox.com",
* "buyer_pay_amount": "0.01",
* "buyer_user_id": "2088102176027680",
* "buyer_user_type": "PRIVATE",
* "fund_bill_list": [
* {
* "amount": "0.01",
* "fund_channel": "ALIPAYACCOUNT"
* }
* ],
* "gmt_payment": "2018-06-10 14:54:16",
* "invoice_amount": "0.01",
* "out_trade_no": "91fbd3fa-8558-443a-82c2-bd8e941d7e71",
* "point_amount": "0.00",
* "receipt_amount": "0.01",
* "total_amount": "0.01",
* "trade_no": "2018061021001004680200326495"
* },
* "sign": "BNgMmA2t8fwFZNSa39kyEKgL6hV45DVOKOsdyyzTzsQnX8HEkKOzVevQEDyK083dNYewip1KK/K92BTDY2KMAsrOEqcCNxsk9NLAvK9ZQVxQzFbAFKqs5EBAEzncSWnChJcb7VMhDakUxHZFmclHg38dLJiHE2bEcF8ar9R1zj0p4V0Jr+BXO10kLtaSTc9NeaCwJZ89sPHKitNnUWRroU7t0xPHc1hWpstObwixKmAWnsFyb9eyGwPQnqNBsUVNSNWCJ7Pg3rb03Tx6J3zNsqH5f0YhWilMi09npPe33URFc6zG1HJSfhEm4Gq1zwQrPoA/anW8BbdmEUUmNo1dEw=="
* }
*/
String result = f2FPayResult.getResponse().getBody();
return result;
}
/**
* 当面付-扫码付
*
* 扫码支付,指用户打开支付宝钱包中的“扫一扫”功能,扫描商户针对每个订单实时生成的订单二维码,并在手机端确认支付。
*
* 发起预下单请求,同步返回订单二维码
*
* 适用场景:商家获取二维码展示在屏幕上,然后用户去扫描屏幕上的二维码
* @return
* @throws AlipayApiException
*/
@PostMapping("/precreate")
public void precreate(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 实际使用时需要根据商品id查询商品的基本信息并计算价格(可能还有什么优惠),这里只是写死值来测试
// (必填) 商户网站订单系统中唯一订单号,64个字符以内,只能包含字母、数字、下划线,
String outTradeNo = UUID.randomUUID().toString();
// (必填) 订单标题,粗略描述用户的支付目的。如“喜士多(浦东店)消费”
String subject = "测试订单";
// 订单描述,可以对交易或商品进行一个详细地描述,比如填写"购买商品2件共15.00元"
String body = "购买商品2件共20.05元";
// (必填) 订单总金额,单位为元,不能超过1亿元
// 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
String totalAmount = "0.01";
// (可选) 订单不可打折金额,可以配合商家平台配置折扣活动,如果酒水不参与打折,则将对应金额填写至此字段
// 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
String undiscountableAmount = "";
// 卖家支付宝账号ID,用于支持一个签约账号下支持打款到不同的收款账号,(打款到sellerId对应的支付宝账号)
// 如果该字段为空,则默认为与支付宝签约的商户的PID,也就是appid对应的PID
String sellerId = "";
// (必填) 商户门店编号,通过门店号和商家后台可以配置精准到门店的折扣信息,详询支付宝技术支持
String storeId = "test_store_id";
// 商户操作员编号,添加此参数可以为商户操作员做销售统计
String operatorId = "test_operator_id";
// 商品明细列表,需填写购买商品详细信息,
List<GoodsDetail> goodsDetailList = new ArrayList<>();
GoodsDetail goods1 = GoodsDetail.newInstance("goods_id001", "全麦小面包", 1, 1);
goodsDetailList.add(goods1);
GoodsDetail goods2 = GoodsDetail.newInstance("goods_id002", "黑人牙刷", 1, 2);
goodsDetailList.add(goods2);
// 支付超时,线下扫码交易定义为5分钟
String timeoutExpress = "5m";
AlipayTradePrecreateRequestBuilder builder =new AlipayTradePrecreateRequestBuilder()
.setSubject(subject)
.setTotalAmount(totalAmount)
.setOutTradeNo(outTradeNo)
.setUndiscountableAmount(undiscountableAmount)
.setSellerId(sellerId)
.setBody(body)
.setOperatorId(operatorId)
.setStoreId(storeId)
.setTimeoutExpress(timeoutExpress)
//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
.setNotifyUrl(aliPayProperties.getNotifyUrl())
.setGoodsDetailList(goodsDetailList);
AlipayF2FPrecreateResult result = alipayTradeService.tradePrecreate(builder);
String qrCodeUrl = null;
switch (result.getTradeStatus()) {
case SUCCESS:
log.info("支付宝预下单成功: )");
AlipayTradePrecreateResponse res = result.getResponse();
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "images/");
if (!file.exists()) {
file.mkdirs();
}
String absolutePath = file.getAbsolutePath();
String fileName = String.format("%sqr-%s.png", File.separator, res.getOutTradeNo());
String filePath = new StringBuilder(absolutePath).append(fileName).toString();
// 这里只是演示将图片写到服务器中,实际可以返回二维码让前端去生成
String basePath = request.getScheme()+ "://"+request.getServerName()+":"+ request.getServerPort()+request.getContextPath()+"/";
qrCodeUrl = basePath + fileName;
response.getWriter().write("<img src=\"" + qrCodeUrl + "\" />");
ZxingUtils.getQRCodeImge(res.getQrCode(), 256, filePath);
break;
case FAILED:
log.error("支付宝预下单失败!!!");
break;
case UNKNOWN:
log.error("系统异常,预下单状态未知!!!");
break;
default:
log.error("不支持的交易状态,交易返回异常!!!");
break;
}
}
/**
* 退款
* @param orderNo 商户订单号
* @return
*/
@PostMapping("/refund")
public String refund(String orderNo){
AlipayTradeRefundRequestBuilder builder = new AlipayTradeRefundRequestBuilder()
.setOutTradeNo(orderNo)
.setRefundAmount("0.01")
.setRefundReason("当面付退款测试")
.setOutRequestNo(String.valueOf(System.nanoTime()))
.setStoreId("A1");
AlipayF2FRefundResult result = alipayTradeService.tradeRefund(builder);
switch (result.getTradeStatus()) {
case SUCCESS:
log.info("支付宝退款成功: )");
break;
case FAILED:
log.error("支付宝退款失败!!!");
break;
case UNKNOWN:
log.error("系统异常,订单退款状态未知!!!");
break;
default:
log.error("不支持的交易状态,交易返回异常!!!");
break;
}
return result.getResponse().getBody();
}
}
| 29DCH/LovingHome-Real-Estate-Platform | springboot-pay-example/src/main/java/com/example/pay/controller/AlipayF2FPayController.java | 3,559 | // 订单描述,可以对交易或商品进行一个详细地描述,比如填写"购买商品2件共15.00元" | line_comment | zh-cn | package com.example.pay.controller;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePayRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeRefundRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPayResult;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FRefundResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.example.pay.configuration.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* 支付宝-当面付 控制器.
* https://openclub.alipay.com/read.php?tid=1720&fid=40
*
* https://docs.open.alipay.com/203/105910
*
*/
@Slf4j
@RestController
@RequestMapping("/alipay/f2fpay")
public class AlipayF2FPayController {
@Autowired
private AlipayTradeService alipayTradeService;
@Autowired
private AlipayProperties aliPayProperties;
/**
* 当面付-条码付
*
* 商家使用扫码工具(扫码枪等)扫描用户支付宝的付款码
*
* @param authCode
*/
@PostMapping("/barCodePay")
public String barCodePay(String authCode){
// 实际使用时需要根据商品id查询商品的基本信息并计算价格(可能还有什么优惠),这里只是写死值来测试
// (必填) 商户网站订单系统中唯一订单号,64个字符以内,只能包含字母、数字、下划线,
String outTradeNo = UUID.randomUUID().toString();
// (必填) 订单标题,粗略描述用户的支付目的。如“喜士多(浦东店)消费”
String subject = "测试订单";
// 订单描述,可以对交易或商品进行一个详细地描述,比如填写"购买商品2件共15.00元"
String body = "购买商品2件共20.05元";
// (必填) 订单总金额,单位为元,不能超过1亿元
// 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
String totalAmount = "0.01";
// (可选) 订单不可打折金额,可以配合商家平台配置折扣活动,如果酒水不参与打折,则将对应金额填写至此字段
// 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
String undiscountableAmount = "";
// (必填) 商户门店编号,通过门店号和商家后台可以配置精准到门店的折扣信息,详询支付宝技术支持
String storeId = "test_store_id";
// 商户操作员编号,添加此参数可以为商户操作员做销售统计
String operatorId = "test_operator_id";
// 商品明细列表,需填写购买商品详细信息,
List<GoodsDetail> goodsDetailList = new ArrayList<>();
GoodsDetail goods1 = GoodsDetail.newInstance("goods_id001", "全麦小面包", 1, 1);
goodsDetailList.add(goods1);
GoodsDetail goods2 = GoodsDetail.newInstance("goods_id002", "黑人牙刷", 1, 2);
goodsDetailList.add(goods2);
// 支付超时,线下扫码交易定义为5分钟
String timeoutExpress = "5m";
AlipayTradePayRequestBuilder builder = new AlipayTradePayRequestBuilder()
.setOutTradeNo(outTradeNo)
.setSubject(subject)
.setBody(body)
.setTotalAmount(totalAmount)
.setAuthCode(authCode)
.setTotalAmount(totalAmount)
.setStoreId(storeId)
.setOperatorId(operatorId)
.setGoodsDetailList(goodsDetailList)
.setTimeoutExpress(timeoutExpress);
// 当面付,面对面付,face to face pay -> face 2 face pay -> f2f pay
// 同步返回支付结果
AlipayF2FPayResult f2FPayResult = alipayTradeService.tradePay(builder);
// 注意:一定要处理支付的结果,因为不是每次支付都一定会成功,可能会失败
switch (f2FPayResult.getTradeStatus()) {
case SUCCESS:
log.info("支付宝支付成功: )");
break;
case FAILED:
log.error("支付宝支付失败!!!");
break;
case UNKNOWN:
log.error("系统异常,订单状态未知!!!");
break;
default:
log.error("不支持的交易状态,交易返回异常!!!");
break;
}
/**
* {
* "alipay_trade_pay_response": {
* "code": "10000",
* "msg": "Success",
* "buyer_logon_id": "ekf***@sandbox.com",
* "buyer_pay_amount": "0.01",
* "buyer_user_id": "2088102176027680",
* "buyer_user_type": "PRIVATE",
* "fund_bill_list": [
* {
* "amount": "0.01",
* "fund_channel": "ALIPAYACCOUNT"
* }
* ],
* "gmt_payment": "2018-06-10 14:54:16",
* "invoice_amount": "0.01",
* "out_trade_no": "91fbd3fa-8558-443a-82c2-bd8e941d7e71",
* "point_amount": "0.00",
* "receipt_amount": "0.01",
* "total_amount": "0.01",
* "trade_no": "2018061021001004680200326495"
* },
* "sign": "BNgMmA2t8fwFZNSa39kyEKgL6hV45DVOKOsdyyzTzsQnX8HEkKOzVevQEDyK083dNYewip1KK/K92BTDY2KMAsrOEqcCNxsk9NLAvK9ZQVxQzFbAFKqs5EBAEzncSWnChJcb7VMhDakUxHZFmclHg38dLJiHE2bEcF8ar9R1zj0p4V0Jr+BXO10kLtaSTc9NeaCwJZ89sPHKitNnUWRroU7t0xPHc1hWpstObwixKmAWnsFyb9eyGwPQnqNBsUVNSNWCJ7Pg3rb03Tx6J3zNsqH5f0YhWilMi09npPe33URFc6zG1HJSfhEm4Gq1zwQrPoA/anW8BbdmEUUmNo1dEw=="
* }
*/
String result = f2FPayResult.getResponse().getBody();
return result;
}
/**
* 当面付-扫码付
*
* 扫码支付,指用户打开支付宝钱包中的“扫一扫”功能,扫描商户针对每个订单实时生成的订单二维码,并在手机端确认支付。
*
* 发起预下单请求,同步返回订单二维码
*
* 适用场景:商家获取二维码展示在屏幕上,然后用户去扫描屏幕上的二维码
* @return
* @throws AlipayApiException
*/
@PostMapping("/precreate")
public void precreate(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 实际使用时需要根据商品id查询商品的基本信息并计算价格(可能还有什么优惠),这里只是写死值来测试
// (必填) 商户网站订单系统中唯一订单号,64个字符以内,只能包含字母、数字、下划线,
String outTradeNo = UUID.randomUUID().toString();
// (必填) 订单标题,粗略描述用户的支付目的。如“喜士多(浦东店)消费”
String subject = "测试订单";
// 订单 <SUF>
String body = "购买商品2件共20.05元";
// (必填) 订单总金额,单位为元,不能超过1亿元
// 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
String totalAmount = "0.01";
// (可选) 订单不可打折金额,可以配合商家平台配置折扣活动,如果酒水不参与打折,则将对应金额填写至此字段
// 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
String undiscountableAmount = "";
// 卖家支付宝账号ID,用于支持一个签约账号下支持打款到不同的收款账号,(打款到sellerId对应的支付宝账号)
// 如果该字段为空,则默认为与支付宝签约的商户的PID,也就是appid对应的PID
String sellerId = "";
// (必填) 商户门店编号,通过门店号和商家后台可以配置精准到门店的折扣信息,详询支付宝技术支持
String storeId = "test_store_id";
// 商户操作员编号,添加此参数可以为商户操作员做销售统计
String operatorId = "test_operator_id";
// 商品明细列表,需填写购买商品详细信息,
List<GoodsDetail> goodsDetailList = new ArrayList<>();
GoodsDetail goods1 = GoodsDetail.newInstance("goods_id001", "全麦小面包", 1, 1);
goodsDetailList.add(goods1);
GoodsDetail goods2 = GoodsDetail.newInstance("goods_id002", "黑人牙刷", 1, 2);
goodsDetailList.add(goods2);
// 支付超时,线下扫码交易定义为5分钟
String timeoutExpress = "5m";
AlipayTradePrecreateRequestBuilder builder =new AlipayTradePrecreateRequestBuilder()
.setSubject(subject)
.setTotalAmount(totalAmount)
.setOutTradeNo(outTradeNo)
.setUndiscountableAmount(undiscountableAmount)
.setSellerId(sellerId)
.setBody(body)
.setOperatorId(operatorId)
.setStoreId(storeId)
.setTimeoutExpress(timeoutExpress)
//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
.setNotifyUrl(aliPayProperties.getNotifyUrl())
.setGoodsDetailList(goodsDetailList);
AlipayF2FPrecreateResult result = alipayTradeService.tradePrecreate(builder);
String qrCodeUrl = null;
switch (result.getTradeStatus()) {
case SUCCESS:
log.info("支付宝预下单成功: )");
AlipayTradePrecreateResponse res = result.getResponse();
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "images/");
if (!file.exists()) {
file.mkdirs();
}
String absolutePath = file.getAbsolutePath();
String fileName = String.format("%sqr-%s.png", File.separator, res.getOutTradeNo());
String filePath = new StringBuilder(absolutePath).append(fileName).toString();
// 这里只是演示将图片写到服务器中,实际可以返回二维码让前端去生成
String basePath = request.getScheme()+ "://"+request.getServerName()+":"+ request.getServerPort()+request.getContextPath()+"/";
qrCodeUrl = basePath + fileName;
response.getWriter().write("<img src=\"" + qrCodeUrl + "\" />");
ZxingUtils.getQRCodeImge(res.getQrCode(), 256, filePath);
break;
case FAILED:
log.error("支付宝预下单失败!!!");
break;
case UNKNOWN:
log.error("系统异常,预下单状态未知!!!");
break;
default:
log.error("不支持的交易状态,交易返回异常!!!");
break;
}
}
/**
* 退款
* @param orderNo 商户订单号
* @return
*/
@PostMapping("/refund")
public String refund(String orderNo){
AlipayTradeRefundRequestBuilder builder = new AlipayTradeRefundRequestBuilder()
.setOutTradeNo(orderNo)
.setRefundAmount("0.01")
.setRefundReason("当面付退款测试")
.setOutRequestNo(String.valueOf(System.nanoTime()))
.setStoreId("A1");
AlipayF2FRefundResult result = alipayTradeService.tradeRefund(builder);
switch (result.getTradeStatus()) {
case SUCCESS:
log.info("支付宝退款成功: )");
break;
case FAILED:
log.error("支付宝退款失败!!!");
break;
case UNKNOWN:
log.error("系统异常,订单退款状态未知!!!");
break;
default:
log.error("不支持的交易状态,交易返回异常!!!");
break;
}
return result.getResponse().getBody();
}
}
| 0 |
65108_0 | package com.example.jingbin.cloudreader.bean.book;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import com.example.jingbin.cloudreader.BR;
import com.example.jingbin.cloudreader.bean.moviechild.ImagesBean;
import java.io.Serializable;
import java.util.List;
import me.jingbin.bymvvm.http.ParamNames;
public class BooksBean extends BaseObservable implements Serializable{
/**
* rating : {"max":10,"numRaters":116375,"average":"7.9","min":0}
* subtitle :
* author : ["韩寒"]
* pubdate : 2010-9
* tags : [{"count":38955,"name":"韩寒","title":"韩寒"},{"count":16343,"name":"小说","title":"小说"},{"count":12037,"name":"我想和这个世界谈谈","title":"我想和这个世界谈谈"},{"count":10674,"name":"公路小说","title":"公路小说"},{"count":6392,"name":"1988","title":"1988"},{"count":5868,"name":"中国文学","title":"中国文学"},{"count":5260,"name":"中国","title":"中国"},{"count":4730,"name":"文学","title":"文学"}]
* origin_title :
* image : https://img5.doubanio.com/mpic/s4477716.jpg
* binding : 平装
* translator : []
* catalog : 曹操与刘备的一生
* pages : 215
* images : {"small":"https://img5.doubanio.com/spic/s4477716.jpg","large":"https://img5.doubanio.com/lpic/s4477716.jpg","medium":"https://img5.doubanio.com/mpic/s4477716.jpg"}
* alt : https://book.douban.com/subject/5275059/
* id : 5275059
* publisher : 国际文化出版公司
* isbn10 : 751250098X
* isbn13 : 9787512500983
* title : 1988:我想和这个世界谈谈
* url : https://api.douban.com/v2/book/5275059
* alt_title :
* author_intro : 韩寒 1982年9月23日出生。作家,赛车手。已出版作品:《三重门》、《零下一度》、《像少年啦飞驰》、《通稿2003》、《毒》、《韩寒五年文集》、《长安乱》、《就这么漂来漂去》、《一座城池》、《寒》、《光荣日》、《杂的文》或有其他。
* summary : 系列主题:《我想和这个世界谈谈》
* 目前在韩寒主编的杂志《独唱团》中首度连载,这是韩寒预谋已久的一个系列,也是国内首度实际尝试“公路小说”这一概念的第一本——《1988》。
* 所谓“公路小说”就是以路途为载体反应人生观,现实观的小说。
* 如果说一件真正的艺术品的面世具有任何重大意义的话,韩寒新书的出版将会在中国创造一个历史事件,文章开头“空气越来越差,我必须上路了。我开着一台1988年出厂的旅行车,在说不清是迷雾还是毒气的夜色里拐上了318国道。”用一部旅行车为载体,通过在路上的见闻、过去的回忆、扑朔迷离的人物关系等各种现实场景,以韩寒本人对路上所见、所闻引发自己的观点,这场真正的旅途在精神层面;如果说似乎逾越了部分法律和道德的界限,但出发点也仅仅是希望在另一侧找到信仰。韩寒是“叛逆的”,他“试图用能给世界一些新意的眼光来看世界。试图寻找令人信服的价值”。他认为这一切通过文学都可以实现,产生了要创造一种批判现有一切社会习俗的“新幻象”的念头——《1988》就此问世。
* 目前“公路小说”的系列已经开始策划,韩寒的作品首当其冲,韩寒表示将会撰写三部作品与聚石文华联合打造“公路小说”这一品牌
* price : 25.00元
*/
@ParamNames("rating")
private RatingBean rating;
@ParamNames("subtitle")
private String subtitle;
@ParamNames("pubdate")
private String pubdate;
@ParamNames("image")
private String image;
@ParamNames("images")
private ImagesBean images;
@ParamNames("alt")
private String alt;
@ParamNames("id")
private String id;
@ParamNames("publisher")
private String publisher;
@ParamNames("title")
private String title;
@ParamNames("url")
private String url;
@ParamNames("author")
private List<String> author;
public static class RatingBean extends BaseObservable implements Serializable{
/**
* max : 10
* numRaters : 116375
* average : 7.9
* min : 0
*/
@ParamNames("max")
private int max;
@ParamNames("numRaters")
private int numRaters;
@ParamNames("average")
private String average;
@ParamNames("min")
private int min;
@Bindable
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
notifyPropertyChanged(BR.max);
}
@Bindable
public int getNumRaters() {
return numRaters;
}
public void setNumRaters(int numRaters) {
this.numRaters = numRaters;
notifyPropertyChanged(BR.numRaters);
}
@Bindable
public String getAverage() {
return average;
}
public void setAverage(String average) {
this.average = average;
notifyPropertyChanged(BR.average);
}
@Bindable
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
notifyPropertyChanged(BR.min);
}
}
public static class TagsBean extends BaseObservable implements Serializable{
/**
* count : 38955
* name : 韩寒
* title : 韩寒
*/
@ParamNames("count")
private int count;
@ParamNames("name")
private String name;
@ParamNames("title")
private String title;
@Bindable
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
notifyPropertyChanged(BR.count);
}
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
@Bindable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
notifyPropertyChanged(BR.title);
}
}
@Bindable
public RatingBean getRating() {
return rating;
}
public void setRating(RatingBean rating) {
this.rating = rating;
notifyPropertyChanged(BR.rating);
}
@Bindable
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
notifyPropertyChanged(BR.subtitle);
}
@Bindable
public String getPubdate() {
return pubdate;
}
public void setPubdate(String pubdate) {
this.pubdate = pubdate;
notifyPropertyChanged(BR.pubdate);
}
@Bindable
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
notifyPropertyChanged(BR.image);
}
@Bindable
public ImagesBean getImages() {
return images;
}
public void setImages(ImagesBean images) {
this.images = images;
notifyPropertyChanged(BR.images);
}
@Bindable
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
notifyPropertyChanged(BR.alt);
}
@Bindable
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
notifyPropertyChanged(BR.id);
}
@Bindable
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
notifyPropertyChanged(BR.publisher);
}
@Bindable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
notifyPropertyChanged(BR.title);
}
@Bindable
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
notifyPropertyChanged(BR.url);
}
@Bindable
public List<String> getAuthor() {
return author;
}
public void setAuthor(List<String> author) {
this.author = author;
notifyPropertyChanged(BR.author);
}
}
| 3025077330/-Cloudread | app/src/main/java/com/example/jingbin/cloudreader/bean/book/BooksBean.java | 2,416 | /**
* rating : {"max":10,"numRaters":116375,"average":"7.9","min":0}
* subtitle :
* author : ["韩寒"]
* pubdate : 2010-9
* tags : [{"count":38955,"name":"韩寒","title":"韩寒"},{"count":16343,"name":"小说","title":"小说"},{"count":12037,"name":"我想和这个世界谈谈","title":"我想和这个世界谈谈"},{"count":10674,"name":"公路小说","title":"公路小说"},{"count":6392,"name":"1988","title":"1988"},{"count":5868,"name":"中国文学","title":"中国文学"},{"count":5260,"name":"中国","title":"中国"},{"count":4730,"name":"文学","title":"文学"}]
* origin_title :
* image : https://img5.doubanio.com/mpic/s4477716.jpg
* binding : 平装
* translator : []
* catalog : 曹操与刘备的一生
* pages : 215
* images : {"small":"https://img5.doubanio.com/spic/s4477716.jpg","large":"https://img5.doubanio.com/lpic/s4477716.jpg","medium":"https://img5.doubanio.com/mpic/s4477716.jpg"}
* alt : https://book.douban.com/subject/5275059/
* id : 5275059
* publisher : 国际文化出版公司
* isbn10 : 751250098X
* isbn13 : 9787512500983
* title : 1988:我想和这个世界谈谈
* url : https://api.douban.com/v2/book/5275059
* alt_title :
* author_intro : 韩寒 1982年9月23日出生。作家,赛车手。已出版作品:《三重门》、《零下一度》、《像少年啦飞驰》、《通稿2003》、《毒》、《韩寒五年文集》、《长安乱》、《就这么漂来漂去》、《一座城池》、《寒》、《光荣日》、《杂的文》或有其他。
* summary : 系列主题:《我想和这个世界谈谈》
* 目前在韩寒主编的杂志《独唱团》中首度连载,这是韩寒预谋已久的一个系列,也是国内首度实际尝试“公路小说”这一概念的第一本——《1988》。
* 所谓“公路小说”就是以路途为载体反应人生观,现实观的小说。
* 如果说一件真正的艺术品的面世具有任何重大意义的话,韩寒新书的出版将会在中国创造一个历史事件,文章开头“空气越来越差,我必须上路了。我开着一台1988年出厂的旅行车,在说不清是迷雾还是毒气的夜色里拐上了318国道。”用一部旅行车为载体,通过在路上的见闻、过去的回忆、扑朔迷离的人物关系等各种现实场景,以韩寒本人对路上所见、所闻引发自己的观点,这场真正的旅途在精神层面;如果说似乎逾越了部分法律和道德的界限,但出发点也仅仅是希望在另一侧找到信仰。韩寒是“叛逆的”,他“试图用能给世界一些新意的眼光来看世界。试图寻找令人信服的价值”。他认为这一切通过文学都可以实现,产生了要创造一种批判现有一切社会习俗的“新幻象”的念头——《1988》就此问世。
* 目前“公路小说”的系列已经开始策划,韩寒的作品首当其冲,韩寒表示将会撰写三部作品与聚石文华联合打造“公路小说”这一品牌
* price : 25.00元
*/ | block_comment | zh-cn | package com.example.jingbin.cloudreader.bean.book;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import com.example.jingbin.cloudreader.BR;
import com.example.jingbin.cloudreader.bean.moviechild.ImagesBean;
import java.io.Serializable;
import java.util.List;
import me.jingbin.bymvvm.http.ParamNames;
public class BooksBean extends BaseObservable implements Serializable{
/**
* rat <SUF>*/
@ParamNames("rating")
private RatingBean rating;
@ParamNames("subtitle")
private String subtitle;
@ParamNames("pubdate")
private String pubdate;
@ParamNames("image")
private String image;
@ParamNames("images")
private ImagesBean images;
@ParamNames("alt")
private String alt;
@ParamNames("id")
private String id;
@ParamNames("publisher")
private String publisher;
@ParamNames("title")
private String title;
@ParamNames("url")
private String url;
@ParamNames("author")
private List<String> author;
public static class RatingBean extends BaseObservable implements Serializable{
/**
* max : 10
* numRaters : 116375
* average : 7.9
* min : 0
*/
@ParamNames("max")
private int max;
@ParamNames("numRaters")
private int numRaters;
@ParamNames("average")
private String average;
@ParamNames("min")
private int min;
@Bindable
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
notifyPropertyChanged(BR.max);
}
@Bindable
public int getNumRaters() {
return numRaters;
}
public void setNumRaters(int numRaters) {
this.numRaters = numRaters;
notifyPropertyChanged(BR.numRaters);
}
@Bindable
public String getAverage() {
return average;
}
public void setAverage(String average) {
this.average = average;
notifyPropertyChanged(BR.average);
}
@Bindable
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
notifyPropertyChanged(BR.min);
}
}
public static class TagsBean extends BaseObservable implements Serializable{
/**
* count : 38955
* name : 韩寒
* title : 韩寒
*/
@ParamNames("count")
private int count;
@ParamNames("name")
private String name;
@ParamNames("title")
private String title;
@Bindable
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
notifyPropertyChanged(BR.count);
}
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
@Bindable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
notifyPropertyChanged(BR.title);
}
}
@Bindable
public RatingBean getRating() {
return rating;
}
public void setRating(RatingBean rating) {
this.rating = rating;
notifyPropertyChanged(BR.rating);
}
@Bindable
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
notifyPropertyChanged(BR.subtitle);
}
@Bindable
public String getPubdate() {
return pubdate;
}
public void setPubdate(String pubdate) {
this.pubdate = pubdate;
notifyPropertyChanged(BR.pubdate);
}
@Bindable
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
notifyPropertyChanged(BR.image);
}
@Bindable
public ImagesBean getImages() {
return images;
}
public void setImages(ImagesBean images) {
this.images = images;
notifyPropertyChanged(BR.images);
}
@Bindable
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
notifyPropertyChanged(BR.alt);
}
@Bindable
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
notifyPropertyChanged(BR.id);
}
@Bindable
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
notifyPropertyChanged(BR.publisher);
}
@Bindable
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
notifyPropertyChanged(BR.title);
}
@Bindable
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
notifyPropertyChanged(BR.url);
}
@Bindable
public List<String> getAuthor() {
return author;
}
public void setAuthor(List<String> author) {
this.author = author;
notifyPropertyChanged(BR.author);
}
}
| 1 |
37994_8 | package demoinfo.struts2.tag;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Validateable;
import com.opensymphony.xwork2.ognl.OgnlValueStack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.File;
/**
* struts2标签实例
*/
@SuppressWarnings("all")
public class TagAction extends ActionSupport implements Validateable {
private static final long serialVersionUID = -94044809860988047L;
String name; //姓名
Date birthday; //生日
String bio; //传记
String film; //电影
List<String> friends; //朋友
boolean legalAge; //是否成年
String region; //地区
String state; //地区下的某个小地区
File picture; //照片
String pictureContentType; //照片类型
String pictureFileName; //照片名字
String favouriteLanguage; //喜欢的语言
String favouriteVehicalType = "MotorcycleKey"; //喜欢的汽车种类
String favouriteVehicalSpecific = "YamahaKey"; //喜欢汽车种类中的某个品牌的汽车
@SuppressWarnings("rawtypes")
List leftSideCartoonCharacters;
List rightSideCartoonCharacters;
List favouriteLanguages = new ArrayList();
List vehicalTypeList = new ArrayList();
Map vehicalSpecificMap = new HashMap();
/**
* 构造函数添加下拉框选项 语言、地区、汽车
*/
public TagAction() {
favouriteLanguages.add(new Language("EnglishKey", "English Language"));
favouriteLanguages.add(new Language("FrenchKey", "French Language"));
favouriteLanguages.add(new Language("SpanishKey", "Spanish Language"));
VehicalType car = new VehicalType("CarKey", "Car");
VehicalType motorcycle = new VehicalType("MotorcycleKey", "Motorcycle");
vehicalTypeList.add(car);
vehicalTypeList.add(motorcycle);
List cars = new ArrayList();
cars.add(new VehicalSpecific("MercedesKey", "Mercedes"));
cars.add(new VehicalSpecific("HondaKey", "Honda"));
cars.add(new VehicalSpecific("FordKey", "Ford"));
List motorcycles = new ArrayList();
motorcycles.add(new VehicalSpecific("SuzukiKey", "Suzuki"));
motorcycles.add(new VehicalSpecific("YamahaKey", "Yamaha"));
vehicalSpecificMap.put(car, cars);
vehicalSpecificMap.put(motorcycle, motorcycles);
}
public List getVehicalSpecificList() {
OgnlValueStack stack = (OgnlValueStack) ServletActionContext.getValueStack(ServletActionContext.getRequest());
Object vehicalType = stack.findValue("top");
if (vehicalType != null && vehicalType instanceof VehicalType) {
List l = (List) vehicalSpecificMap.get(vehicalType);
return l;
}
return Collections.EMPTY_LIST;
}
//初始化时
public String execute() throws Exception {
return "input";
}
//提交表单后
public String doSubmit() {
return SUCCESS;
}
// === inner class
public static class Language {
String description;
String key;
public Language(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() {
return key;
}
public String getDescription() {
return description;
}
}
public static class VehicalType {
String key;
String description;
public VehicalType(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() { return this.key; }
public String getDescription() { return this.description; }
public boolean equals(Object obj) {
if (! (obj instanceof VehicalType)) {
return false;
}
else {
return key.equals(((VehicalType)obj).getKey());
}
}
public int hashCode() {
return key.hashCode();
}
}
public static class VehicalSpecific {
String key;
String description;
public VehicalSpecific(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() { return this.key; }
public String getDescription() { return this.description; }
public boolean equals(Object obj) {
if (! (obj instanceof VehicalSpecific)) {
return false;
}
else {
return key.equals(((VehicalSpecific)obj).getKey());
}
}
public int hashCode() {
return key.hashCode();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getFilm() {
return film;
}
public void setFilm(String film) {
this.film = film;
}
public List<String> getFriends() {
return friends;
}
public void setFriends(List<String> friends) {
this.friends = friends;
}
public boolean isLegalAge() {
return legalAge;
}
public void setLegalAge(boolean legalAge) {
this.legalAge = legalAge;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public File getPicture() {
return picture;
}
public void setPicture(File picture) {
this.picture = picture;
}
public String getPictureContentType() {
return pictureContentType;
}
public void setPictureContentType(String pictureContentType) {
this.pictureContentType = pictureContentType;
}
public String getPictureFileName() {
return pictureFileName;
}
public void setPictureFileName(String pictureFileName) {
this.pictureFileName = pictureFileName;
}
public String getFavouriteLanguage() {
return favouriteLanguage;
}
public void setFavouriteLanguage(String favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}
public String getFavouriteVehicalType() {
return favouriteVehicalType;
}
public void setFavouriteVehicalType(String favouriteVehicalType) {
this.favouriteVehicalType = favouriteVehicalType;
}
public String getFavouriteVehicalSpecific() {
return favouriteVehicalSpecific;
}
public void setFavouriteVehicalSpecific(String favouriteVehicalSpecific) {
this.favouriteVehicalSpecific = favouriteVehicalSpecific;
}
public List getLeftSideCartoonCharacters() {
return leftSideCartoonCharacters;
}
public void setLeftSideCartoonCharacters(List leftSideCartoonCharacters) {
this.leftSideCartoonCharacters = leftSideCartoonCharacters;
}
public List getRightSideCartoonCharacters() {
return rightSideCartoonCharacters;
}
public void setRightSideCartoonCharacters(List rightSideCartoonCharacters) {
this.rightSideCartoonCharacters = rightSideCartoonCharacters;
}
public List getFavouriteLanguages() {
return favouriteLanguages;
}
public void setFavouriteLanguages(List favouriteLanguages) {
this.favouriteLanguages = favouriteLanguages;
}
public List getVehicalTypeList() {
return vehicalTypeList;
}
public void setVehicalTypeList(List vehicalTypeList) {
this.vehicalTypeList = vehicalTypeList;
}
public Map getVehicalSpecificMap() {
return vehicalSpecificMap;
}
public void setVehicalSpecificMap(Map vehicalSpecificMap) {
this.vehicalSpecificMap = vehicalSpecificMap;
}
} | 309633415/MyHttp | MyHttp/src/demoinfo/struts2/tag/TagAction.java | 2,259 | /**
* 构造函数添加下拉框选项 语言、地区、汽车
*/ | block_comment | zh-cn | package demoinfo.struts2.tag;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Validateable;
import com.opensymphony.xwork2.ognl.OgnlValueStack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.File;
/**
* struts2标签实例
*/
@SuppressWarnings("all")
public class TagAction extends ActionSupport implements Validateable {
private static final long serialVersionUID = -94044809860988047L;
String name; //姓名
Date birthday; //生日
String bio; //传记
String film; //电影
List<String> friends; //朋友
boolean legalAge; //是否成年
String region; //地区
String state; //地区下的某个小地区
File picture; //照片
String pictureContentType; //照片类型
String pictureFileName; //照片名字
String favouriteLanguage; //喜欢的语言
String favouriteVehicalType = "MotorcycleKey"; //喜欢的汽车种类
String favouriteVehicalSpecific = "YamahaKey"; //喜欢汽车种类中的某个品牌的汽车
@SuppressWarnings("rawtypes")
List leftSideCartoonCharacters;
List rightSideCartoonCharacters;
List favouriteLanguages = new ArrayList();
List vehicalTypeList = new ArrayList();
Map vehicalSpecificMap = new HashMap();
/**
* 构造函 <SUF>*/
public TagAction() {
favouriteLanguages.add(new Language("EnglishKey", "English Language"));
favouriteLanguages.add(new Language("FrenchKey", "French Language"));
favouriteLanguages.add(new Language("SpanishKey", "Spanish Language"));
VehicalType car = new VehicalType("CarKey", "Car");
VehicalType motorcycle = new VehicalType("MotorcycleKey", "Motorcycle");
vehicalTypeList.add(car);
vehicalTypeList.add(motorcycle);
List cars = new ArrayList();
cars.add(new VehicalSpecific("MercedesKey", "Mercedes"));
cars.add(new VehicalSpecific("HondaKey", "Honda"));
cars.add(new VehicalSpecific("FordKey", "Ford"));
List motorcycles = new ArrayList();
motorcycles.add(new VehicalSpecific("SuzukiKey", "Suzuki"));
motorcycles.add(new VehicalSpecific("YamahaKey", "Yamaha"));
vehicalSpecificMap.put(car, cars);
vehicalSpecificMap.put(motorcycle, motorcycles);
}
public List getVehicalSpecificList() {
OgnlValueStack stack = (OgnlValueStack) ServletActionContext.getValueStack(ServletActionContext.getRequest());
Object vehicalType = stack.findValue("top");
if (vehicalType != null && vehicalType instanceof VehicalType) {
List l = (List) vehicalSpecificMap.get(vehicalType);
return l;
}
return Collections.EMPTY_LIST;
}
//初始化时
public String execute() throws Exception {
return "input";
}
//提交表单后
public String doSubmit() {
return SUCCESS;
}
// === inner class
public static class Language {
String description;
String key;
public Language(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() {
return key;
}
public String getDescription() {
return description;
}
}
public static class VehicalType {
String key;
String description;
public VehicalType(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() { return this.key; }
public String getDescription() { return this.description; }
public boolean equals(Object obj) {
if (! (obj instanceof VehicalType)) {
return false;
}
else {
return key.equals(((VehicalType)obj).getKey());
}
}
public int hashCode() {
return key.hashCode();
}
}
public static class VehicalSpecific {
String key;
String description;
public VehicalSpecific(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() { return this.key; }
public String getDescription() { return this.description; }
public boolean equals(Object obj) {
if (! (obj instanceof VehicalSpecific)) {
return false;
}
else {
return key.equals(((VehicalSpecific)obj).getKey());
}
}
public int hashCode() {
return key.hashCode();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getFilm() {
return film;
}
public void setFilm(String film) {
this.film = film;
}
public List<String> getFriends() {
return friends;
}
public void setFriends(List<String> friends) {
this.friends = friends;
}
public boolean isLegalAge() {
return legalAge;
}
public void setLegalAge(boolean legalAge) {
this.legalAge = legalAge;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public File getPicture() {
return picture;
}
public void setPicture(File picture) {
this.picture = picture;
}
public String getPictureContentType() {
return pictureContentType;
}
public void setPictureContentType(String pictureContentType) {
this.pictureContentType = pictureContentType;
}
public String getPictureFileName() {
return pictureFileName;
}
public void setPictureFileName(String pictureFileName) {
this.pictureFileName = pictureFileName;
}
public String getFavouriteLanguage() {
return favouriteLanguage;
}
public void setFavouriteLanguage(String favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}
public String getFavouriteVehicalType() {
return favouriteVehicalType;
}
public void setFavouriteVehicalType(String favouriteVehicalType) {
this.favouriteVehicalType = favouriteVehicalType;
}
public String getFavouriteVehicalSpecific() {
return favouriteVehicalSpecific;
}
public void setFavouriteVehicalSpecific(String favouriteVehicalSpecific) {
this.favouriteVehicalSpecific = favouriteVehicalSpecific;
}
public List getLeftSideCartoonCharacters() {
return leftSideCartoonCharacters;
}
public void setLeftSideCartoonCharacters(List leftSideCartoonCharacters) {
this.leftSideCartoonCharacters = leftSideCartoonCharacters;
}
public List getRightSideCartoonCharacters() {
return rightSideCartoonCharacters;
}
public void setRightSideCartoonCharacters(List rightSideCartoonCharacters) {
this.rightSideCartoonCharacters = rightSideCartoonCharacters;
}
public List getFavouriteLanguages() {
return favouriteLanguages;
}
public void setFavouriteLanguages(List favouriteLanguages) {
this.favouriteLanguages = favouriteLanguages;
}
public List getVehicalTypeList() {
return vehicalTypeList;
}
public void setVehicalTypeList(List vehicalTypeList) {
this.vehicalTypeList = vehicalTypeList;
}
public Map getVehicalSpecificMap() {
return vehicalSpecificMap;
}
public void setVehicalSpecificMap(Map vehicalSpecificMap) {
this.vehicalSpecificMap = vehicalSpecificMap;
}
} | 0 |
45943_8 | /**********************************************************
* 项目名称:山寨腾讯“爱消除”游戏7日教程
* 作 者:郑敏新
* 腾讯微博:SuperCube3D
* 日 期:2013年12月
* 声 明:版权所有 侵权必究
* 本源代码供网友研究学习OpenGL ES开发Android应用用,
* 请勿全部或部分用于商业用途
********************************************************/
package elong.CrazyLink.Control;
import android.os.Bundle;
import android.os.Message;
import elong.CrazyLink.Core.ControlCenter;
public class CtlExchange extends CtlBase{
int mCol1 = 0; //坐标值
int mCol2 = 0;
int mRow1 = 0;
int mRow2 = 0;
int mDeltaX1 = 0; //偏移量
int mDeltaY1 = 0;
int mDeltaX2 = 0;
int mDeltaY2 = 0;
int mStep = 10; //偏移步长
boolean mDirectionX = true; //运动方向控制
boolean mDirectionY = true;
boolean mNeedMoveX = false; //是否需要偏移
boolean mNeedMoveY = false;
public void init(int token, int col1, int row1, int col2, int row2)
{
super.setToken(token);
mNeedMoveX = false;
mNeedMoveY = false;
mCol1 = col1;
mCol2 = col2;
mRow1 = row1;
mRow2 = row2;
if(col1 == col2)
{
mDeltaX1 = 0;
mDeltaX2 = 0;
}
else
{
//根据坐标位置来决定运动的初始方向
mNeedMoveX = true;
if(col1 > col2)
{
mDirectionX = true;
mDeltaX1 = 40;
}
else
{
mDirectionX = false;
mDeltaX1 = -40;
}
}
if(row1 == row2)
{
mDeltaY1 = 0;
mDeltaY2 = 0;
}
else
{
//根据坐标位置来决定运动的初始方向
mNeedMoveY = true;
if(row1 > row2)
{
mDirectionY = true;
mDeltaY1 = 40;
}
else
{
mDirectionY = false;
mDeltaY1 = -40;
}
}
mStop = false;
}
public void run()
{
if(mStop) return;
//将偏移范围限定在-0.5~0.5间,超出指定区间即掉头
if(mNeedMoveX)
{
if(mDeltaX1 >= 50)
{
mDirectionX = true;
mStop = true;
}
else if (mDeltaX1 <= -50)
{
mDirectionX = false;
mStop = true;
}
if(mDirectionX)
{
mDeltaX1 -= mStep;
mDeltaX2 = -mDeltaX1;
}
else
{
mDeltaX1 += mStep;
mDeltaX2 = -mDeltaX1;
}
}
if(mNeedMoveY)
{
if(mDeltaY1 >= 50)
{
mDirectionY = true;
mStop = true;
}
else if (mDeltaY1 <= -50)
{
mDirectionY = false;
mStop = true;
}
if(mDirectionY)
{
mDeltaY1 -= mStep;
mDeltaY2 = -mDeltaY1;
}
else
{
mDeltaY1 += mStep;
mDeltaY2 = -mDeltaY1;
}
}
if(mStop)
{
sendMsg();
}
}
public float getX1()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mCol1 > mCol2)
{
delta = -0.5f;
}
else if(mCol1 < mCol2)
{
delta = 0.5f;
}
return delta + mDeltaX1/100.0f;
}
public float getX2()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mCol1 > mCol2)
{
delta = 0.5f;
}
else if(mCol1 < mCol2)
{
delta = -0.5f;
}
return delta + mDeltaX2/100.0f;
}
public float getY1()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mRow1 > mRow2)
{
delta = -0.5f;
}
else if(mRow1 < mRow2)
{
delta = 0.5f;
}
return delta + mDeltaY1/100.0f;
}
public float getY2()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mRow1 > mRow2)
{
delta = 0.5f;
}
else if(mRow1 < mRow2)
{
delta = -0.5f;
}
return delta + mDeltaY2/100.0f;
}
public void sendMsg()
{
Bundle b = new Bundle();
b.putInt("token", mToken);
setToken(-1);
b.putInt("col1", mCol1);
b.putInt("row1", mRow1);
b.putInt("col2", mCol2);
b.putInt("row2", mRow2);
Message msg = new Message();
msg.what = ControlCenter.EXCHANGE_END;
msg.setData(b);
ControlCenter.mHandler.sendMessage(msg);
}
}
| 3125788/CrazyLink | src/elong/CrazyLink/Control/CtlExchange.java | 1,715 | //将偏移范围限定在-0.5~0.5间,超出指定区间即掉头 | line_comment | zh-cn | /**********************************************************
* 项目名称:山寨腾讯“爱消除”游戏7日教程
* 作 者:郑敏新
* 腾讯微博:SuperCube3D
* 日 期:2013年12月
* 声 明:版权所有 侵权必究
* 本源代码供网友研究学习OpenGL ES开发Android应用用,
* 请勿全部或部分用于商业用途
********************************************************/
package elong.CrazyLink.Control;
import android.os.Bundle;
import android.os.Message;
import elong.CrazyLink.Core.ControlCenter;
public class CtlExchange extends CtlBase{
int mCol1 = 0; //坐标值
int mCol2 = 0;
int mRow1 = 0;
int mRow2 = 0;
int mDeltaX1 = 0; //偏移量
int mDeltaY1 = 0;
int mDeltaX2 = 0;
int mDeltaY2 = 0;
int mStep = 10; //偏移步长
boolean mDirectionX = true; //运动方向控制
boolean mDirectionY = true;
boolean mNeedMoveX = false; //是否需要偏移
boolean mNeedMoveY = false;
public void init(int token, int col1, int row1, int col2, int row2)
{
super.setToken(token);
mNeedMoveX = false;
mNeedMoveY = false;
mCol1 = col1;
mCol2 = col2;
mRow1 = row1;
mRow2 = row2;
if(col1 == col2)
{
mDeltaX1 = 0;
mDeltaX2 = 0;
}
else
{
//根据坐标位置来决定运动的初始方向
mNeedMoveX = true;
if(col1 > col2)
{
mDirectionX = true;
mDeltaX1 = 40;
}
else
{
mDirectionX = false;
mDeltaX1 = -40;
}
}
if(row1 == row2)
{
mDeltaY1 = 0;
mDeltaY2 = 0;
}
else
{
//根据坐标位置来决定运动的初始方向
mNeedMoveY = true;
if(row1 > row2)
{
mDirectionY = true;
mDeltaY1 = 40;
}
else
{
mDirectionY = false;
mDeltaY1 = -40;
}
}
mStop = false;
}
public void run()
{
if(mStop) return;
//将偏 <SUF>
if(mNeedMoveX)
{
if(mDeltaX1 >= 50)
{
mDirectionX = true;
mStop = true;
}
else if (mDeltaX1 <= -50)
{
mDirectionX = false;
mStop = true;
}
if(mDirectionX)
{
mDeltaX1 -= mStep;
mDeltaX2 = -mDeltaX1;
}
else
{
mDeltaX1 += mStep;
mDeltaX2 = -mDeltaX1;
}
}
if(mNeedMoveY)
{
if(mDeltaY1 >= 50)
{
mDirectionY = true;
mStop = true;
}
else if (mDeltaY1 <= -50)
{
mDirectionY = false;
mStop = true;
}
if(mDirectionY)
{
mDeltaY1 -= mStep;
mDeltaY2 = -mDeltaY1;
}
else
{
mDeltaY1 += mStep;
mDeltaY2 = -mDeltaY1;
}
}
if(mStop)
{
sendMsg();
}
}
public float getX1()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mCol1 > mCol2)
{
delta = -0.5f;
}
else if(mCol1 < mCol2)
{
delta = 0.5f;
}
return delta + mDeltaX1/100.0f;
}
public float getX2()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mCol1 > mCol2)
{
delta = 0.5f;
}
else if(mCol1 < mCol2)
{
delta = -0.5f;
}
return delta + mDeltaX2/100.0f;
}
public float getY1()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mRow1 > mRow2)
{
delta = -0.5f;
}
else if(mRow1 < mRow2)
{
delta = 0.5f;
}
return delta + mDeltaY1/100.0f;
}
public float getY2()
{
float delta = 0;
//根据给定坐标设置初始偏移量,将运动范围控制在0~1或0~-1区间
if(mRow1 > mRow2)
{
delta = 0.5f;
}
else if(mRow1 < mRow2)
{
delta = -0.5f;
}
return delta + mDeltaY2/100.0f;
}
public void sendMsg()
{
Bundle b = new Bundle();
b.putInt("token", mToken);
setToken(-1);
b.putInt("col1", mCol1);
b.putInt("row1", mRow1);
b.putInt("col2", mCol2);
b.putInt("row2", mRow2);
Message msg = new Message();
msg.what = ControlCenter.EXCHANGE_END;
msg.setData(b);
ControlCenter.mHandler.sendMessage(msg);
}
}
| 0 |
54693_15 | package com.edu.zucc.ygg.movie.util;
import com.edu.zucc.ygg.movie.domain.Movie;
import com.edu.zucc.ygg.movie.exception.ImgException;
import com.edu.zucc.ygg.movie.service.UpImgService;
import com.edu.zucc.ygg.movie.service.impl.UpImgServiceImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.xmlunit.util.Nodes;
import tk.mybatis.mapper.util.StringUtil;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Test {
public static void uploadMovieImg(Movie movie){
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "Ygg&cc970528";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
PreparedStatement ps = con.prepareStatement("insert into movie(" +
"name,foreign_name,img_url,release_time," +
"sheet_length,make_state,type,director,screenwriter," +
"actors,language,introduction)" +
"values(?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,movie.getName());
ps.setString(2,movie.getForeignName());
ps.setString(3,movie.getImgUrl());
ps.setDate(4, new java.sql.Date(movie.getReleaseTime().getTime()));
ps.setInt(5,movie.getSheetLength());
ps.setString(6,movie.getMakeState());
ps.setString(7,movie.getType());
ps.setString(8,movie.getDirector());
ps.setString(9,movie.getScreenwriter());
ps.setString(10,movie.getActors());
ps.setString(11,movie.getLanguage());
ps.setString(12,movie.getIntroduction());
ps.execute();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
}
public static List<Movie> searchMovieAll(){
List<Movie> movieList = new ArrayList<>();
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "Ygg&cc970528";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
PreparedStatement ps = con.prepareStatement("select id,img_url from movie ");
ResultSet resultSet = ps.executeQuery();
while(resultSet.next()) {
Movie movie = new Movie();
movie.setId(resultSet.getInt("id"));
movie.setImgUrl(resultSet.getString("img_url"));
movieList.add(movie);
}
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
return movieList;
}
public static void updateMovieImg(Movie movie){
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "Ygg&cc970528";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
PreparedStatement ps = con.prepareStatement("update movie set img_url = ? where id = ?");
ps.setString(1,movie.getImgUrl());
ps.setInt(2,movie.getId());
ps.execute();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
}
public static void main(String[] args){
// String img = "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2516578307.jpg";
// getHtmlPicture(img,filePath,null);
// uploadImg("C:/Users/de'l'l/Desktop/testImg/p2233971046.jpg");
// List<Movie> movieList = Test.searchMovieAll();
// for (Movie movie:movieList){
// String filePath = "C:\\Users\\de'l'l\\Desktop\\testImg";
// String oldImgUrl = movie.getImgUrl();
// String fileName = getHtmlPicture(oldImgUrl,filePath,null);
// String newImgUrl = uploadImg("C:/Users/de'l'l/Desktop/testImg/"+fileName);
// if (newImgUrl!=null){
// movie.setImgUrl(newImgUrl);
// updateMovieImg(movie);
// }
// }
String content = "<p>骋和梅利两兄弟被强兽人抓走,亚拉冈和佛罗多兵分两路,分别前往末日山脉焚毁至尊魔戒和追赶并救援被抓的霍比特人,佛罗多和山姆一路,亚拉冈,金利,莱戈拉斯一路。佛罗多的食物不多,路线不明,征途迷茫,却发现了穷追不舍的史麦戈,后者渴望拿回他曾经拥有的魔戒。</p><p>佛罗多意识到史麦戈的悲惨遭遇,又得知史麦戈知道前往摩多的路线,自然的让他成为了向导。山姆是佛罗多的后勤管理人员,贴身保镖,迷茫时的开导者,可谓兢兢业业,没有他,佛罗多不可能成功地完成使命。亚拉冈这边呢,遇到了白袍甘道夫,发现两个霍比特人进入了树林,并参加了树人会议,后来成功摧毁了萨鲁曼的基地。甘道夫带领亚拉冈他们拯救了受到控制的落汗国王,并抵御兽人大军的侵略。</p><p>魔戒远征队的传奇故事告一段落,从头到尾,向我们展示了霍比特人的冒险,勇敢,重情重义的优良品格,以及甘道夫的运筹帷幄,亚拉冈的沉稳,男子汉的气概,精灵的能力出众,矮人的任劳任怨。也从一些人的言行中展示了贪婪,残忍的特点。不可否认,人性中好的坏的兼备,就连向来理性的佛罗多也会迷失,我们应该正视这一点。</p><p>忽然想到这一句</p><p><span class=\"fr-img-caption fr-fic fr-dib\" style=\"width: 300px;\"><span class=\"fr-img-wrap\"><img src=\"http://ygg-31501102-bucket.oss-cn-shenzhen.aliyuncs.com/commentary_img/1547908633647.jpg\"><span class=\"fr-inner\">测试图片<br><br></span></span></span></p><p>"或许我们努力的活着不是去让这个世界善良而是不让自己丑恶。"</p>";
}
public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
URL url; //定义URL对象url
BufferedInputStream in; //定义输入字节缓冲流对象in
FileOutputStream file; //定义文件输出流对象file
try {
String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名)
url = new URL(httpUrl); //初始化url对象
in = new BufferedInputStream(url.openStream()); //初始化in对象,也就是获得url字节流
file = new FileOutputStream(mkdirsmy(filePath,fileName));
int t;
while ((t = in.read()) != -1) {
file.write(t);
}
file.close();
in.close();
return fileName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static File mkdirsmy(String dir, String realName) throws IOException{
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
return file;
}
public static String uploadImg(String path){
String url="";
if (!StringUtil.isEmpty(path)){
try {
url = new UpImgServiceImpl().updateHead(path);
System.out.println("电影图片上传到图片库成功"+url);
return url;
} catch (ImgException e) {
System.out.println("电影图片上传到图片库失败");
}
}
return null;
}
}
| 31501102ygg/2019GraduationProject | src/main/java/com/edu/zucc/ygg/movie/util/Test.java | 2,972 | //驱动程序名 | line_comment | zh-cn | package com.edu.zucc.ygg.movie.util;
import com.edu.zucc.ygg.movie.domain.Movie;
import com.edu.zucc.ygg.movie.exception.ImgException;
import com.edu.zucc.ygg.movie.service.UpImgService;
import com.edu.zucc.ygg.movie.service.impl.UpImgServiceImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.xmlunit.util.Nodes;
import tk.mybatis.mapper.util.StringUtil;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Test {
public static void uploadMovieImg(Movie movie){
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "Ygg&cc970528";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
PreparedStatement ps = con.prepareStatement("insert into movie(" +
"name,foreign_name,img_url,release_time," +
"sheet_length,make_state,type,director,screenwriter," +
"actors,language,introduction)" +
"values(?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,movie.getName());
ps.setString(2,movie.getForeignName());
ps.setString(3,movie.getImgUrl());
ps.setDate(4, new java.sql.Date(movie.getReleaseTime().getTime()));
ps.setInt(5,movie.getSheetLength());
ps.setString(6,movie.getMakeState());
ps.setString(7,movie.getType());
ps.setString(8,movie.getDirector());
ps.setString(9,movie.getScreenwriter());
ps.setString(10,movie.getActors());
ps.setString(11,movie.getLanguage());
ps.setString(12,movie.getIntroduction());
ps.execute();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
}
public static List<Movie> searchMovieAll(){
List<Movie> movieList = new ArrayList<>();
//声明Connection对象
Connection con;
//驱动 <SUF>
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "Ygg&cc970528";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
PreparedStatement ps = con.prepareStatement("select id,img_url from movie ");
ResultSet resultSet = ps.executeQuery();
while(resultSet.next()) {
Movie movie = new Movie();
movie.setId(resultSet.getInt("id"));
movie.setImgUrl(resultSet.getString("img_url"));
movieList.add(movie);
}
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
return movieList;
}
public static void updateMovieImg(Movie movie){
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://47.107.70.187:3306/movie?useUnicode=true&characterEncoding=utf8&useSSL=false";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "Ygg&cc970528";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
PreparedStatement ps = con.prepareStatement("update movie set img_url = ? where id = ?");
ps.setString(1,movie.getImgUrl());
ps.setInt(2,movie.getId());
ps.execute();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
}
public static void main(String[] args){
// String img = "https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2516578307.jpg";
// getHtmlPicture(img,filePath,null);
// uploadImg("C:/Users/de'l'l/Desktop/testImg/p2233971046.jpg");
// List<Movie> movieList = Test.searchMovieAll();
// for (Movie movie:movieList){
// String filePath = "C:\\Users\\de'l'l\\Desktop\\testImg";
// String oldImgUrl = movie.getImgUrl();
// String fileName = getHtmlPicture(oldImgUrl,filePath,null);
// String newImgUrl = uploadImg("C:/Users/de'l'l/Desktop/testImg/"+fileName);
// if (newImgUrl!=null){
// movie.setImgUrl(newImgUrl);
// updateMovieImg(movie);
// }
// }
String content = "<p>骋和梅利两兄弟被强兽人抓走,亚拉冈和佛罗多兵分两路,分别前往末日山脉焚毁至尊魔戒和追赶并救援被抓的霍比特人,佛罗多和山姆一路,亚拉冈,金利,莱戈拉斯一路。佛罗多的食物不多,路线不明,征途迷茫,却发现了穷追不舍的史麦戈,后者渴望拿回他曾经拥有的魔戒。</p><p>佛罗多意识到史麦戈的悲惨遭遇,又得知史麦戈知道前往摩多的路线,自然的让他成为了向导。山姆是佛罗多的后勤管理人员,贴身保镖,迷茫时的开导者,可谓兢兢业业,没有他,佛罗多不可能成功地完成使命。亚拉冈这边呢,遇到了白袍甘道夫,发现两个霍比特人进入了树林,并参加了树人会议,后来成功摧毁了萨鲁曼的基地。甘道夫带领亚拉冈他们拯救了受到控制的落汗国王,并抵御兽人大军的侵略。</p><p>魔戒远征队的传奇故事告一段落,从头到尾,向我们展示了霍比特人的冒险,勇敢,重情重义的优良品格,以及甘道夫的运筹帷幄,亚拉冈的沉稳,男子汉的气概,精灵的能力出众,矮人的任劳任怨。也从一些人的言行中展示了贪婪,残忍的特点。不可否认,人性中好的坏的兼备,就连向来理性的佛罗多也会迷失,我们应该正视这一点。</p><p>忽然想到这一句</p><p><span class=\"fr-img-caption fr-fic fr-dib\" style=\"width: 300px;\"><span class=\"fr-img-wrap\"><img src=\"http://ygg-31501102-bucket.oss-cn-shenzhen.aliyuncs.com/commentary_img/1547908633647.jpg\"><span class=\"fr-inner\">测试图片<br><br></span></span></span></p><p>"或许我们努力的活着不是去让这个世界善良而是不让自己丑恶。"</p>";
}
public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
URL url; //定义URL对象url
BufferedInputStream in; //定义输入字节缓冲流对象in
FileOutputStream file; //定义文件输出流对象file
try {
String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名)
url = new URL(httpUrl); //初始化url对象
in = new BufferedInputStream(url.openStream()); //初始化in对象,也就是获得url字节流
file = new FileOutputStream(mkdirsmy(filePath,fileName));
int t;
while ((t = in.read()) != -1) {
file.write(t);
}
file.close();
in.close();
return fileName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static File mkdirsmy(String dir, String realName) throws IOException{
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
return file;
}
public static String uploadImg(String path){
String url="";
if (!StringUtil.isEmpty(path)){
try {
url = new UpImgServiceImpl().updateHead(path);
System.out.println("电影图片上传到图片库成功"+url);
return url;
} catch (ImgException e) {
System.out.println("电影图片上传到图片库失败");
}
}
return null;
}
}
| 0 |
58553_16 | package cn.yumi.daka.utils;
import cn.junechiu.junecore.utils.Base64Java;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESCoder {
//南瓜IV
public static final byte[] zero_iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//常用iv
public static final byte[] commmon_iv = "0102030405060708".getBytes();
private static final byte[] iv1 = "DJ@#dd'a'asl;dfk".getBytes();//人人加密,人人解密,短视频,定位使用的iv
/**
* 加密
* 人人,定位城市,定位
*/
public static String Encrypt_First(String sSrc, String sKey) throws Exception {
return Encrypt(sSrc, sKey, iv1);
}
/**
* 南瓜解密
*/
public static String Decrypt_Second(String sSrc, String sKey) throws Exception {
return Decrypt(sSrc, sKey, AESCoder.zero_iv);
}
/**
* 解密
* 人人,短视频,定位
*/
public static String Decrypt_First(String sSrc, String sKey) throws Exception {
return Decrypt(sSrc, sKey, iv1);
}
/**
* 基础加密方法
*/
public static String Encrypt(String sSrc, String sKey, byte[] iv) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return new String(Base64Java.getEncoder().encode(encrypted));//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
/**
* 基础解密方法
*/
public static String Decrypt(String sSrc, String sKey, byte[] iv) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("UTF8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
/**
* 测试类方法
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
/*
* 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
* 此处使用AES-128-CBC加密模式,key需要为16位。
*/
String cKey = "8q(yd98^&76d7typ";
// 需要加密的字串
String cSrc = "seasonMark=&area=USK&category=%E5%85%A8%E9%83%A8%E7%B1%BB%E5%9E%8B&page=1&token=&query=lastUpdate&rows=18&t=1527865961514";
System.out.println(cSrc);
// 加密
long lStart = System.currentTimeMillis();
String enString = AESCoder.Encrypt_First(cSrc, cKey);
System.out.println("加密后的字串是:" + enString);
long lUseTime = System.currentTimeMillis() - lStart;
System.out.println("加密耗时:" + lUseTime + "毫秒");
// 解密
enString = "VkyH8nZ6bCaRpM64JrjLLFZiXGummrjqwvO8CBEkqVGp0pzBnsbBP2LyzZ35LQ1VRRJodo1R5Pso" +
"tj7iN5vi7vW+HZXCHmCReBfQUiV9MZ2iWuVIMpWenpF1Q38kk55BozsUasRIhY94lVNzrcyHC8RW" +
"cPJq7Qsj5NarGR589DBXbPFBBKvJboCsMYZV4+DnqKsej/b9ZLkt4+ElL9rgw0D2euWz2EZhFH/N" +
"0e528MuBf6P/ZlOuzHzhTe+6yfwcJIkdUNqG/BDCeh84jG/3TBaFW/AZrb4HH2brkTPM1uudzR2l" +
"6tvrNcTN9Ra8mRd+rIJ9cm6pHBZgl/li1JOTj5Ppnb/b3BYHRWw86GMAMSfs7pM+TxHoMLIarUL+" +
"/IdiL8CHEvP58jbKaaYuAL2qNpKBGGXRuFfVSFccXMk/sw19nJ4vJlOk7rJLO3Pw+4/G9km8RglQ" +
"Ti/uDKZ7E9O68+ySTPScJm78GXKbYlDRULQp2h+YvFly1Gpuv12vN4P27uMjBaShMyoKh4NRnuBY" +
"EhyGALXMhi6Tjsvg4/Cyh/HMLofoIgf3GEaBcvKe7rrehmWui5X19F6yu96/NRC0skF5hVmevUL5" +
"RDHZEsvHBam0A7A4BjUtcf4aA7AHQ99mztf5R3YRCo19TBIWvF1CYUwRAgOnJqNR0ZcBoiAM6nZM" +
"/HH64/M/LXgCB5ozk2wgXI9x1IAEUR6aqTqiYL3BfVpIAZ+DxumOm4s8oztpA/BsWrxAxBY80Uh1" +
"zsln/OX7lV1AYjF2kwb7fXdsCuIWtbtx/nMFh0PKgI8IUi7G17J1jetML8MuaXIhXM14ARAcWTQJ" +
"VmS8zpwHq9juBlvn/KgNXj8Wl2oR8DeJ2t+WHl4=";
lStart = System.currentTimeMillis();
String DeString = Decrypt_First(enString, cKey);
System.out.println("解密后的字串是:" + DeString);
String keyA = "DN7SgBmdeS!WgO@G";
String keyB = "5UD6afzH@0PlUhJC";
String DeStringA = AESCoder.Decrypt_First(enString, keyB);
System.out.println("解密后的字串是:A" + DeStringA);
enString = "4ObazwsM2RHhA0JlydYJnA==";
String DeStringB = AESCoder.Decrypt_First(enString, keyA);
System.out.println("解密后的字串是:B" + DeStringB);
lUseTime = System.currentTimeMillis() - lStart;
System.out.println("解密耗时:" + lUseTime + "毫秒");
}
// 解密m3u8 内容
public static String decrypt2(byte[] sSrc, String sKey) {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("UTF8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
// byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(sSrc);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
}
| 316011989/DingDian | app/src/main/java/cn/yumi/daka/utils/AESCoder.java | 2,401 | /*
* 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
* 此处使用AES-128-CBC加密模式,key需要为16位。
*/ | block_comment | zh-cn | package cn.yumi.daka.utils;
import cn.junechiu.junecore.utils.Base64Java;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESCoder {
//南瓜IV
public static final byte[] zero_iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//常用iv
public static final byte[] commmon_iv = "0102030405060708".getBytes();
private static final byte[] iv1 = "DJ@#dd'a'asl;dfk".getBytes();//人人加密,人人解密,短视频,定位使用的iv
/**
* 加密
* 人人,定位城市,定位
*/
public static String Encrypt_First(String sSrc, String sKey) throws Exception {
return Encrypt(sSrc, sKey, iv1);
}
/**
* 南瓜解密
*/
public static String Decrypt_Second(String sSrc, String sKey) throws Exception {
return Decrypt(sSrc, sKey, AESCoder.zero_iv);
}
/**
* 解密
* 人人,短视频,定位
*/
public static String Decrypt_First(String sSrc, String sKey) throws Exception {
return Decrypt(sSrc, sKey, iv1);
}
/**
* 基础加密方法
*/
public static String Encrypt(String sSrc, String sKey, byte[] iv) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return new String(Base64Java.getEncoder().encode(encrypted));//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
/**
* 基础解密方法
*/
public static String Decrypt(String sSrc, String sKey, byte[] iv) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("UTF8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
/**
* 测试类方法
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
/*
* 加密用 <SUF>*/
String cKey = "8q(yd98^&76d7typ";
// 需要加密的字串
String cSrc = "seasonMark=&area=USK&category=%E5%85%A8%E9%83%A8%E7%B1%BB%E5%9E%8B&page=1&token=&query=lastUpdate&rows=18&t=1527865961514";
System.out.println(cSrc);
// 加密
long lStart = System.currentTimeMillis();
String enString = AESCoder.Encrypt_First(cSrc, cKey);
System.out.println("加密后的字串是:" + enString);
long lUseTime = System.currentTimeMillis() - lStart;
System.out.println("加密耗时:" + lUseTime + "毫秒");
// 解密
enString = "VkyH8nZ6bCaRpM64JrjLLFZiXGummrjqwvO8CBEkqVGp0pzBnsbBP2LyzZ35LQ1VRRJodo1R5Pso" +
"tj7iN5vi7vW+HZXCHmCReBfQUiV9MZ2iWuVIMpWenpF1Q38kk55BozsUasRIhY94lVNzrcyHC8RW" +
"cPJq7Qsj5NarGR589DBXbPFBBKvJboCsMYZV4+DnqKsej/b9ZLkt4+ElL9rgw0D2euWz2EZhFH/N" +
"0e528MuBf6P/ZlOuzHzhTe+6yfwcJIkdUNqG/BDCeh84jG/3TBaFW/AZrb4HH2brkTPM1uudzR2l" +
"6tvrNcTN9Ra8mRd+rIJ9cm6pHBZgl/li1JOTj5Ppnb/b3BYHRWw86GMAMSfs7pM+TxHoMLIarUL+" +
"/IdiL8CHEvP58jbKaaYuAL2qNpKBGGXRuFfVSFccXMk/sw19nJ4vJlOk7rJLO3Pw+4/G9km8RglQ" +
"Ti/uDKZ7E9O68+ySTPScJm78GXKbYlDRULQp2h+YvFly1Gpuv12vN4P27uMjBaShMyoKh4NRnuBY" +
"EhyGALXMhi6Tjsvg4/Cyh/HMLofoIgf3GEaBcvKe7rrehmWui5X19F6yu96/NRC0skF5hVmevUL5" +
"RDHZEsvHBam0A7A4BjUtcf4aA7AHQ99mztf5R3YRCo19TBIWvF1CYUwRAgOnJqNR0ZcBoiAM6nZM" +
"/HH64/M/LXgCB5ozk2wgXI9x1IAEUR6aqTqiYL3BfVpIAZ+DxumOm4s8oztpA/BsWrxAxBY80Uh1" +
"zsln/OX7lV1AYjF2kwb7fXdsCuIWtbtx/nMFh0PKgI8IUi7G17J1jetML8MuaXIhXM14ARAcWTQJ" +
"VmS8zpwHq9juBlvn/KgNXj8Wl2oR8DeJ2t+WHl4=";
lStart = System.currentTimeMillis();
String DeString = Decrypt_First(enString, cKey);
System.out.println("解密后的字串是:" + DeString);
String keyA = "DN7SgBmdeS!WgO@G";
String keyB = "5UD6afzH@0PlUhJC";
String DeStringA = AESCoder.Decrypt_First(enString, keyB);
System.out.println("解密后的字串是:A" + DeStringA);
enString = "4ObazwsM2RHhA0JlydYJnA==";
String DeStringB = AESCoder.Decrypt_First(enString, keyA);
System.out.println("解密后的字串是:B" + DeStringB);
lUseTime = System.currentTimeMillis() - lStart;
System.out.println("解密耗时:" + lUseTime + "毫秒");
}
// 解密m3u8 内容
public static String decrypt2(byte[] sSrc, String sKey) {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("UTF8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
// byte[] encrypted1 = Base64Java.getDecoder().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(sSrc);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
}
| 0 |
37846_7 | package weidong.com.ys1106.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import weidong.com.ys1106.MainActivity;
import weidong.com.ys1106.R;
import weidong.com.ys1106.Utils.AnalysisUtils;
import weidong.com.ys1106.Utils.CommonRequest;
import weidong.com.ys1106.Utils.CommonResponse;
import weidong.com.ys1106.Utils.Constant;
import weidong.com.ys1106.Utils.MD5Utils;
import weidong.com.ys1106.Utils.MyToast;
import weidong.com.ys1106.Utils.ResponseHandle;
public class ChangePassActivity extends BasicActivity {
private EditText mOldPsw;
private EditText mNewPsw;
private TextView Wrong_old, Wrong_new;
private boolean OLDWrongtype = true;
private boolean NEWWrongtype = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_pass);
init();
}
private void init() {
mOldPsw = findViewById(R.id.et_oldpass);
mNewPsw = findViewById(R.id.et_newpass);
ImageView mBack = findViewById(R.id.btn_finish);
Button mChangePsw = findViewById(R.id.btn_commit);
Wrong_old = findViewById(R.id.oldwrong);
Wrong_new = findViewById(R.id.newwrong);
//设置监听
mOldPsw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//格式判断
if (s.length() < 6) {
Wrong_old.setText("不能少于6位");
Wrong_old.setVisibility(View.VISIBLE);
OLDWrongtype = true;
} else {
Wrong_old.setVisibility(View.GONE);
OLDWrongtype = false;
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
mNewPsw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//格式判断
if (s.length() < 6) {
Wrong_new.setText("不能少于6位");
Wrong_new.setVisibility(View.VISIBLE);
NEWWrongtype = true;
} else {
Wrong_new.setVisibility(View.GONE);
NEWWrongtype = false;
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
//返回键
mBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//提交更改
mChangePsw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (PswEmpty()) {
MyToast.MyToastShow(ChangePassActivity.this, "请填写完整的信息!");
} else if (NEWWrongtype || OLDWrongtype) {
MyToast.MyToastShow(ChangePassActivity.this, "密码格式不正确!");
} else if (SameOldNew()) {
MyToast.MyToastShow(ChangePassActivity.this, "新旧密码不能相同");
} else {
//change pass
DoChange(AnalysisUtils.readloginUserName(ChangePassActivity.this),
MD5Utils.ToMD5(mNewPsw.getText().toString().trim()),
MD5Utils.ToMD5(mOldPsw.getText().toString().trim()));
}
}
});
}
private void DoChange(String name, String psw, String oldpsw) {
CommonRequest request = new CommonRequest();
//设置更新用户信息码
request.setRequestCode("6");
//设置需要更新的用户的用户名、旧密码和新密码
request.addRequestParam("account", name);
request.addRequestParam("oldpass", oldpsw);
request.addRequestParam("newpass", psw);
sendHttpPostRequst(Constant.URL_Login, request, new ResponseHandle() {
@Override
public void success(CommonResponse response) {
doSuccess();
}
@Override
public void failure(String failCode) {
doFail(failCode);
}
});
}
private void doFail(String fialCode) {
switch (fialCode) {
case "10":
MyToast.MyToastShow(ChangePassActivity.this, "遗憾,修改失败");
break;
case "01":
MyToast.MyToastShow(ChangePassActivity.this, "遗憾,旧密码错误");
break;
}
}
private void doSuccess() {
AlertDialog.Builder builder = new AlertDialog.Builder(ChangePassActivity.this);
builder.setTitle("修改成功").
setMessage("请重新登录").
setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//清除登录状态
AnalysisUtils.cleanlogin(ChangePassActivity.this);
Intent intent = new Intent(ChangePassActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}).setCancelable(false).show();
}
//旧密码和新密码是否相同
private boolean SameOldNew() {
return mOldPsw.getText().toString().equals(mNewPsw.getText().toString());
}
//是否为空
private boolean PswEmpty() {
if (mOldPsw.getText().toString().isEmpty()) {
return true;
} else
return mNewPsw.getText().toString().isEmpty();
}
}
| 321Oscar/YS1106 | app/src/main/java/weidong/com/ys1106/Activity/ChangePassActivity.java | 1,494 | //设置需要更新的用户的用户名、旧密码和新密码 | line_comment | zh-cn | package weidong.com.ys1106.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import weidong.com.ys1106.MainActivity;
import weidong.com.ys1106.R;
import weidong.com.ys1106.Utils.AnalysisUtils;
import weidong.com.ys1106.Utils.CommonRequest;
import weidong.com.ys1106.Utils.CommonResponse;
import weidong.com.ys1106.Utils.Constant;
import weidong.com.ys1106.Utils.MD5Utils;
import weidong.com.ys1106.Utils.MyToast;
import weidong.com.ys1106.Utils.ResponseHandle;
public class ChangePassActivity extends BasicActivity {
private EditText mOldPsw;
private EditText mNewPsw;
private TextView Wrong_old, Wrong_new;
private boolean OLDWrongtype = true;
private boolean NEWWrongtype = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_pass);
init();
}
private void init() {
mOldPsw = findViewById(R.id.et_oldpass);
mNewPsw = findViewById(R.id.et_newpass);
ImageView mBack = findViewById(R.id.btn_finish);
Button mChangePsw = findViewById(R.id.btn_commit);
Wrong_old = findViewById(R.id.oldwrong);
Wrong_new = findViewById(R.id.newwrong);
//设置监听
mOldPsw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//格式判断
if (s.length() < 6) {
Wrong_old.setText("不能少于6位");
Wrong_old.setVisibility(View.VISIBLE);
OLDWrongtype = true;
} else {
Wrong_old.setVisibility(View.GONE);
OLDWrongtype = false;
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
mNewPsw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//格式判断
if (s.length() < 6) {
Wrong_new.setText("不能少于6位");
Wrong_new.setVisibility(View.VISIBLE);
NEWWrongtype = true;
} else {
Wrong_new.setVisibility(View.GONE);
NEWWrongtype = false;
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
//返回键
mBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//提交更改
mChangePsw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (PswEmpty()) {
MyToast.MyToastShow(ChangePassActivity.this, "请填写完整的信息!");
} else if (NEWWrongtype || OLDWrongtype) {
MyToast.MyToastShow(ChangePassActivity.this, "密码格式不正确!");
} else if (SameOldNew()) {
MyToast.MyToastShow(ChangePassActivity.this, "新旧密码不能相同");
} else {
//change pass
DoChange(AnalysisUtils.readloginUserName(ChangePassActivity.this),
MD5Utils.ToMD5(mNewPsw.getText().toString().trim()),
MD5Utils.ToMD5(mOldPsw.getText().toString().trim()));
}
}
});
}
private void DoChange(String name, String psw, String oldpsw) {
CommonRequest request = new CommonRequest();
//设置更新用户信息码
request.setRequestCode("6");
//设置 <SUF>
request.addRequestParam("account", name);
request.addRequestParam("oldpass", oldpsw);
request.addRequestParam("newpass", psw);
sendHttpPostRequst(Constant.URL_Login, request, new ResponseHandle() {
@Override
public void success(CommonResponse response) {
doSuccess();
}
@Override
public void failure(String failCode) {
doFail(failCode);
}
});
}
private void doFail(String fialCode) {
switch (fialCode) {
case "10":
MyToast.MyToastShow(ChangePassActivity.this, "遗憾,修改失败");
break;
case "01":
MyToast.MyToastShow(ChangePassActivity.this, "遗憾,旧密码错误");
break;
}
}
private void doSuccess() {
AlertDialog.Builder builder = new AlertDialog.Builder(ChangePassActivity.this);
builder.setTitle("修改成功").
setMessage("请重新登录").
setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//清除登录状态
AnalysisUtils.cleanlogin(ChangePassActivity.this);
Intent intent = new Intent(ChangePassActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}).setCancelable(false).show();
}
//旧密码和新密码是否相同
private boolean SameOldNew() {
return mOldPsw.getText().toString().equals(mNewPsw.getText().toString());
}
//是否为空
private boolean PswEmpty() {
if (mOldPsw.getText().toString().isEmpty()) {
return true;
} else
return mNewPsw.getText().toString().isEmpty();
}
}
| 0 |
57905_5 | package com.property.sys.model;
import java.io.Serializable;
/**
* 文章表
*/
public class Article implements Serializable{
private static final long serialVersionUID = 3870996444951119364L;
public static final String TYPE_COMMUNITY_ACTIVITIES="活动";
public static final String TYPE_COMMUNITY_ISSUES="议题";
public static final String TYPE_VOTE="投票";
public static final String TYPE_COMPLAINT="投诉";
public static final String TYPE_CONSULT="咨询";
public static final String TYPE_NOTICE="公告";
private Integer id;
private String type;//类型(社区活动、社区信息、投票、投诉、咨询)
private String title;//标题
private String content;//内容
private Integer userId;//用户id
private String author;//发布人
private String publishDate;//发布时间
private long visitors;//访问人数
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public long getVisitors() {
return visitors;
}
public void setVisitors(long visitors) {
this.visitors = visitors;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
}
| 336Project/property-sys | property-sys/src/com/property/sys/model/Article.java | 554 | //发布人
| line_comment | zh-cn | package com.property.sys.model;
import java.io.Serializable;
/**
* 文章表
*/
public class Article implements Serializable{
private static final long serialVersionUID = 3870996444951119364L;
public static final String TYPE_COMMUNITY_ACTIVITIES="活动";
public static final String TYPE_COMMUNITY_ISSUES="议题";
public static final String TYPE_VOTE="投票";
public static final String TYPE_COMPLAINT="投诉";
public static final String TYPE_CONSULT="咨询";
public static final String TYPE_NOTICE="公告";
private Integer id;
private String type;//类型(社区活动、社区信息、投票、投诉、咨询)
private String title;//标题
private String content;//内容
private Integer userId;//用户id
private String author;//发布 <SUF>
private String publishDate;//发布时间
private long visitors;//访问人数
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public long getVisitors() {
return visitors;
}
public void setVisitors(long visitors) {
this.visitors = visitors;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
}
| 0 |
63338_5 | package com.example.chaomianqiandao;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.example.chaomianqiandao.utils.Fileutils;
import com.example.chaomianqiandao.utils.Network;
import com.example.chaomianqiandao.utils.PermissionUtil;
import com.example.chaomianqiandao.utils.ResponseInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.leefeng.promptlibrary.PromptDialog;
public class Sign extends AppCompatActivity {
private int type;
private final static int SIGN0 = 100;
private final static int SIGN1 = 101;
private final static int SIGN4 = 104;
private final static int TAKE_PHOTO = 150;
private final static int Referer = 200;
private final static int UPLOAD_IMAGE = 201;
private final static int ScanCode = 202;
private final static int Token = 110;
private boolean flag = false;
private FirstApplication mFirstApplication = FirstApplication.getInstance();
String[] PERMISSON = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private String objectId;
private String token;
@SuppressLint("HandlerLeak")
private final Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SIGN0:
ResponseInfo info = (ResponseInfo) msg.obj;
if (info.BodyInfo.contains("签到成功")) {
promptDialog.showSuccess("签到成功!");
Toast.makeText(Sign.this, "签到成功!", Toast.LENGTH_SHORT).show();
finish();
} else {
promptDialog.showError("未知错误~");
Toast.makeText(Sign.this, "", Toast.LENGTH_SHORT).show();
}
break;
case SIGN1:
ResponseInfo info1 = (ResponseInfo) msg.obj;
Log.e("SIGN1", info1.BodyInfo);
promptDialog.showSuccess("签到成功!");
Toast.makeText(Sign.this, "签到成功!", Toast.LENGTH_SHORT).show();
finish();
break;
case SIGN4:
ResponseInfo info4 = (ResponseInfo) msg.obj;
Log.e("SIGN4", info4.BodyInfo);
Toast.makeText(mFirstApplication, info4.BodyInfo, Toast.LENGTH_SHORT).show();
if (info4.BodyInfo.equals("success")) {
promptDialog.showSuccess("签到成功!");
Toast.makeText(Sign.this, "签到成功!", Toast.LENGTH_SHORT).show();
finish();
} else {
promptDialog.showError(info4.BodyInfo);
Toast.makeText(Sign.this, info4.BodyInfo, Toast.LENGTH_SHORT).show();
}
break;
case Referer:
flag = true;
sign();
break;
case UPLOAD_IMAGE:
ResponseInfo info9 = (ResponseInfo) msg.obj;
JSONObject jsonObject = JSONObject.parseObject(info9.BodyInfo);
if (jsonObject.getString("msg").equals("success")) {
promptDialog.showSuccess("上传成功!");
objectId = jsonObject.getString("objectId");
} else {
promptDialog.showError("上传失败...未知错误");
}
break;
case Token:
ResponseInfo info10 = (ResponseInfo) msg.obj;
Log.e("Token", info10.BodyInfo);
JSONObject jsonObject10 = JSONObject.parseObject(info10.BodyInfo);
token = jsonObject10.getString("_token");
break;
}
}
};
private String aid;
private String sign_code;
private String content;
private EditText address;
private EditText wei;
private EditText jing;
private ImageView imageView;
private TextView tv_sign_code;
private String realPath;
private PromptDialog promptDialog;
private SharedPreferences shared_address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign);
TextView sign_name = findViewById(R.id.sign_name);
TextView sign_course_name = findViewById(R.id.sign_course_name);
TextView hint=findViewById(R.id.hint);
Intent intent = getIntent();
sign_course_name.setText(intent.getStringExtra("name"));
aid = intent.getStringExtra("aid");
sign_code = String.valueOf(getIntent().getStringExtra("sign_code"));
tv_sign_code = findViewById(R.id.sign_code);
content = getIntent().getStringExtra("content");
//签到按钮监听
findViewById(R.id.sign_button).setOnClickListener(v -> {
sign();
});
if (content != null)
content = content.replace("\\", "");
promptDialog = new PromptDialog(this);
//选取图片
imageView = findViewById(R.id.video_profile);
imageView.setOnClickListener(v -> gotoPic());
//经纬度输入框
jing = findViewById(R.id.jing);
wei = findViewById(R.id.wei);
address = findViewById(R.id.address);
shared_address = getSharedPreferences("account_and_password", MODE_PRIVATE);
if (shared_address.contains("address")) {
address.setText(shared_address.getString("address", ""));
}
if (content != null&&content.length()>25) {
JSONObject con = JSONObject.parseObject(content);
jing.setText(con.getString("locationLongitude"));
wei.setText(con.getString("locationLatitude"));
}
//获取token
Network.getSync("https://pan-yz.chaoxing.com/api/token/uservalid", handler, Token);
//设置签到类型名称
sign_name.setText(getIntent().getStringExtra("sign_name"));
type = getIntent().getIntExtra("sign_type", 0);
switch (type) {
case 0:
hint.setText("直接点击签到即可!");
break;
case 1:
imageView.setVisibility(View.VISIBLE);
hint.setText("从相册选择图片后点击签到按钮\n如果直接点击签到为不上传图片!");
break;
case 2:
case 3:
hint.setText("请点击签到按钮\n然后选择直接扫码或者相册打开图片\n如果二维码图片不清晰,请多试几次");
break;
case 4:
tv_sign_code.setText("签到手势是:" + sign_code);
tv_sign_code.setVisibility(View.VISIBLE);
hint.setText("直接点击签到即可,手势可以分享小伙伴!");
break;
case 5:
findViewById(R.id.dingwei).setVisibility(View.VISIBLE);
hint.setText("一定要修改地址显示\n这是老师可以看到的定位信息\n经纬度默认是签到范围的中心点\n如果教师未指定位置请自行设定经纬度");
break;
case 6:
tv_sign_code.setText("签到码是:" + sign_code);
tv_sign_code.setVisibility(View.VISIBLE);
hint.setText("直接点击签到即可,签到码可以分享小伙伴!");
break;
}
}
@Override
protected void onStart() {
super.onStart();
PermissionUtil.checkPermissions(Sign.this,PERMISSON,0);
}
void sign(){
//保存地址
SharedPreferences.Editor editor = shared_address.edit();
editor.putString("address",address.getText().toString());
editor.commit();
switch (type){
case 0:
//普通签到
promptDialog.showLoading("正在签到中...");
String url0="https://mobilelearn.chaoxing.com/widget/sign/pcStuSignController/preSign?activeId="+getIntent().getStringExtra("aid");
Network.getSync(url0,handler,SIGN0);
break;
case 1:
//拍照签到
promptDialog.showLoading("正在签到中...");
if(flag){
String url1;
if(objectId!=null){
url1="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+"&appType=15&fid=0&objectId="+objectId;
}else {
url1="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+
"&clientip=&useragent=&latitude=-1&longitude=-1&appType=15&fid=0&objectId="+"";
}
Network.getSync(url1,handler,SIGN1);
}else{
Network.getSync(getReferer(),handler,Referer);
}
break;
case 2:
case 3:
promptDialog.showLoading("跳转到扫码页面...");
if(flag){
Intent intent=new Intent(this,CodeScanning.class);
startActivityForResult(intent,ScanCode);
}else {
Network.getSync(getReferer(),handler,Referer);
}
break;
case 4:
case 6:
promptDialog.showLoading("正在签到中...");
//签到码签到、手势签到
//先访问referer,才能进一步签到
if (flag){
String url4="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid;
Network.getSync(url4,handler,SIGN4);
}else {
Network.getSync(getReferer(),handler,Referer);
}
break;
case 5:
promptDialog.showLoading("正在签到中...");
//定位签到
if (flag){
String url5="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?address="+urlEncodeChinese(address.getText().toString())
+"&activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+"&clientip=&latitude="+
wei.getText().toString()+"&longitude="+jing.getText().toString();
Network.getSync(url5,handler,SIGN4);
}else {
Network.getSync(getReferer(),handler,Referer);
}
break;
}
}
String getReferer(){
return getIntent().getStringExtra("url");
}
//将字符串改编码
private String urlEncodeChinese(String url) {
try {
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
String tmp = "";
while (matcher.find()) {
tmp = matcher.group();
url = url.replaceAll(tmp, URLEncoder.encode(tmp, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url.replace(" ", "%20");
}
void gotoPic(){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
TAKE_PHOTO);
} else {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, TAKE_PHOTO);
}
}
private void uploadImage(String path) {
promptDialog.showLoading("上传图片中...");
String url_upload="https://pan-yz.chaoxing.com/upload?_token="+token;
File file=new File(path);
Bitmap bitmap= BitmapFactory.decodeFile(path);
int width=bitmap.getWidth();
int scale=width/500;
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=scale;
String[] s=path.split("\\.");
String format=s[s.length-1];
//文件大于 1mb
if(scale>1||file.length()>500*1000){
String fileName= Fileutils.checkDirPath(Sign.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+"/image")+System.currentTimeMillis()+"."+format;
if(format.startsWith("jp")){
try {
OutputStream os=new FileOutputStream(fileName);
bitmap=BitmapFactory.decodeFile(path,options);
bitmap.compress(Bitmap.CompressFormat.JPEG,60,os);
os.close();
File temp=new File(fileName);
Network.postFile(url_upload,temp,handler,UPLOAD_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}else if (format.startsWith("png")){
try {
OutputStream os=new FileOutputStream(fileName);
bitmap=BitmapFactory.decodeFile(path,options);
bitmap.compress(Bitmap.CompressFormat.PNG,60,os);
os.close();
File temp=new File(fileName);
Network.postFile(url_upload,temp,handler,UPLOAD_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Network.postFile(url_upload,file,handler,UPLOAD_IMAGE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
switch (requestCode){
case TAKE_PHOTO:
realPath = Fileutils.getRealFilePathFromUri(this,data.getData());
if (realPath!=null&&realPath.length()>1){
Log.e("realPath",realPath);
Log.e("data",data.getData().toString());
uploadImage(realPath);
imageView.setImageBitmap(BitmapFactory.decodeFile(realPath));
}
else{
Toast.makeText(mFirstApplication, "选择照片失败!", Toast.LENGTH_SHORT).show();
promptDialog.showError("选择照片失败!");
}
break;
case ScanCode:
Log.e("result",data.getStringExtra("result"));
String enc=data.getStringExtra("result");
for (String temp:enc.split("&")){
if(temp.startsWith("enc"))
{
enc="&"+temp;
break;
}
}
if(enc.length()>5){
String url1="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+enc;
Network.getSync(url1,handler,SIGN4);
}
break;
}
}else {
promptDialog.showError("操作失败!");
}
}
} | 3425734131/GoodSign | app/src/main/java/com/example/chaomianqiandao/Sign.java | 3,673 | //设置签到类型名称 | line_comment | zh-cn | package com.example.chaomianqiandao;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONObject;
import com.example.chaomianqiandao.utils.Fileutils;
import com.example.chaomianqiandao.utils.Network;
import com.example.chaomianqiandao.utils.PermissionUtil;
import com.example.chaomianqiandao.utils.ResponseInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.leefeng.promptlibrary.PromptDialog;
public class Sign extends AppCompatActivity {
private int type;
private final static int SIGN0 = 100;
private final static int SIGN1 = 101;
private final static int SIGN4 = 104;
private final static int TAKE_PHOTO = 150;
private final static int Referer = 200;
private final static int UPLOAD_IMAGE = 201;
private final static int ScanCode = 202;
private final static int Token = 110;
private boolean flag = false;
private FirstApplication mFirstApplication = FirstApplication.getInstance();
String[] PERMISSON = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private String objectId;
private String token;
@SuppressLint("HandlerLeak")
private final Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SIGN0:
ResponseInfo info = (ResponseInfo) msg.obj;
if (info.BodyInfo.contains("签到成功")) {
promptDialog.showSuccess("签到成功!");
Toast.makeText(Sign.this, "签到成功!", Toast.LENGTH_SHORT).show();
finish();
} else {
promptDialog.showError("未知错误~");
Toast.makeText(Sign.this, "", Toast.LENGTH_SHORT).show();
}
break;
case SIGN1:
ResponseInfo info1 = (ResponseInfo) msg.obj;
Log.e("SIGN1", info1.BodyInfo);
promptDialog.showSuccess("签到成功!");
Toast.makeText(Sign.this, "签到成功!", Toast.LENGTH_SHORT).show();
finish();
break;
case SIGN4:
ResponseInfo info4 = (ResponseInfo) msg.obj;
Log.e("SIGN4", info4.BodyInfo);
Toast.makeText(mFirstApplication, info4.BodyInfo, Toast.LENGTH_SHORT).show();
if (info4.BodyInfo.equals("success")) {
promptDialog.showSuccess("签到成功!");
Toast.makeText(Sign.this, "签到成功!", Toast.LENGTH_SHORT).show();
finish();
} else {
promptDialog.showError(info4.BodyInfo);
Toast.makeText(Sign.this, info4.BodyInfo, Toast.LENGTH_SHORT).show();
}
break;
case Referer:
flag = true;
sign();
break;
case UPLOAD_IMAGE:
ResponseInfo info9 = (ResponseInfo) msg.obj;
JSONObject jsonObject = JSONObject.parseObject(info9.BodyInfo);
if (jsonObject.getString("msg").equals("success")) {
promptDialog.showSuccess("上传成功!");
objectId = jsonObject.getString("objectId");
} else {
promptDialog.showError("上传失败...未知错误");
}
break;
case Token:
ResponseInfo info10 = (ResponseInfo) msg.obj;
Log.e("Token", info10.BodyInfo);
JSONObject jsonObject10 = JSONObject.parseObject(info10.BodyInfo);
token = jsonObject10.getString("_token");
break;
}
}
};
private String aid;
private String sign_code;
private String content;
private EditText address;
private EditText wei;
private EditText jing;
private ImageView imageView;
private TextView tv_sign_code;
private String realPath;
private PromptDialog promptDialog;
private SharedPreferences shared_address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign);
TextView sign_name = findViewById(R.id.sign_name);
TextView sign_course_name = findViewById(R.id.sign_course_name);
TextView hint=findViewById(R.id.hint);
Intent intent = getIntent();
sign_course_name.setText(intent.getStringExtra("name"));
aid = intent.getStringExtra("aid");
sign_code = String.valueOf(getIntent().getStringExtra("sign_code"));
tv_sign_code = findViewById(R.id.sign_code);
content = getIntent().getStringExtra("content");
//签到按钮监听
findViewById(R.id.sign_button).setOnClickListener(v -> {
sign();
});
if (content != null)
content = content.replace("\\", "");
promptDialog = new PromptDialog(this);
//选取图片
imageView = findViewById(R.id.video_profile);
imageView.setOnClickListener(v -> gotoPic());
//经纬度输入框
jing = findViewById(R.id.jing);
wei = findViewById(R.id.wei);
address = findViewById(R.id.address);
shared_address = getSharedPreferences("account_and_password", MODE_PRIVATE);
if (shared_address.contains("address")) {
address.setText(shared_address.getString("address", ""));
}
if (content != null&&content.length()>25) {
JSONObject con = JSONObject.parseObject(content);
jing.setText(con.getString("locationLongitude"));
wei.setText(con.getString("locationLatitude"));
}
//获取token
Network.getSync("https://pan-yz.chaoxing.com/api/token/uservalid", handler, Token);
//设置 <SUF>
sign_name.setText(getIntent().getStringExtra("sign_name"));
type = getIntent().getIntExtra("sign_type", 0);
switch (type) {
case 0:
hint.setText("直接点击签到即可!");
break;
case 1:
imageView.setVisibility(View.VISIBLE);
hint.setText("从相册选择图片后点击签到按钮\n如果直接点击签到为不上传图片!");
break;
case 2:
case 3:
hint.setText("请点击签到按钮\n然后选择直接扫码或者相册打开图片\n如果二维码图片不清晰,请多试几次");
break;
case 4:
tv_sign_code.setText("签到手势是:" + sign_code);
tv_sign_code.setVisibility(View.VISIBLE);
hint.setText("直接点击签到即可,手势可以分享小伙伴!");
break;
case 5:
findViewById(R.id.dingwei).setVisibility(View.VISIBLE);
hint.setText("一定要修改地址显示\n这是老师可以看到的定位信息\n经纬度默认是签到范围的中心点\n如果教师未指定位置请自行设定经纬度");
break;
case 6:
tv_sign_code.setText("签到码是:" + sign_code);
tv_sign_code.setVisibility(View.VISIBLE);
hint.setText("直接点击签到即可,签到码可以分享小伙伴!");
break;
}
}
@Override
protected void onStart() {
super.onStart();
PermissionUtil.checkPermissions(Sign.this,PERMISSON,0);
}
void sign(){
//保存地址
SharedPreferences.Editor editor = shared_address.edit();
editor.putString("address",address.getText().toString());
editor.commit();
switch (type){
case 0:
//普通签到
promptDialog.showLoading("正在签到中...");
String url0="https://mobilelearn.chaoxing.com/widget/sign/pcStuSignController/preSign?activeId="+getIntent().getStringExtra("aid");
Network.getSync(url0,handler,SIGN0);
break;
case 1:
//拍照签到
promptDialog.showLoading("正在签到中...");
if(flag){
String url1;
if(objectId!=null){
url1="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+"&appType=15&fid=0&objectId="+objectId;
}else {
url1="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+
"&clientip=&useragent=&latitude=-1&longitude=-1&appType=15&fid=0&objectId="+"";
}
Network.getSync(url1,handler,SIGN1);
}else{
Network.getSync(getReferer(),handler,Referer);
}
break;
case 2:
case 3:
promptDialog.showLoading("跳转到扫码页面...");
if(flag){
Intent intent=new Intent(this,CodeScanning.class);
startActivityForResult(intent,ScanCode);
}else {
Network.getSync(getReferer(),handler,Referer);
}
break;
case 4:
case 6:
promptDialog.showLoading("正在签到中...");
//签到码签到、手势签到
//先访问referer,才能进一步签到
if (flag){
String url4="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid;
Network.getSync(url4,handler,SIGN4);
}else {
Network.getSync(getReferer(),handler,Referer);
}
break;
case 5:
promptDialog.showLoading("正在签到中...");
//定位签到
if (flag){
String url5="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?address="+urlEncodeChinese(address.getText().toString())
+"&activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+"&clientip=&latitude="+
wei.getText().toString()+"&longitude="+jing.getText().toString();
Network.getSync(url5,handler,SIGN4);
}else {
Network.getSync(getReferer(),handler,Referer);
}
break;
}
}
String getReferer(){
return getIntent().getStringExtra("url");
}
//将字符串改编码
private String urlEncodeChinese(String url) {
try {
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
String tmp = "";
while (matcher.find()) {
tmp = matcher.group();
url = url.replaceAll(tmp, URLEncoder.encode(tmp, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url.replace(" ", "%20");
}
void gotoPic(){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
TAKE_PHOTO);
} else {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, TAKE_PHOTO);
}
}
private void uploadImage(String path) {
promptDialog.showLoading("上传图片中...");
String url_upload="https://pan-yz.chaoxing.com/upload?_token="+token;
File file=new File(path);
Bitmap bitmap= BitmapFactory.decodeFile(path);
int width=bitmap.getWidth();
int scale=width/500;
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=scale;
String[] s=path.split("\\.");
String format=s[s.length-1];
//文件大于 1mb
if(scale>1||file.length()>500*1000){
String fileName= Fileutils.checkDirPath(Sign.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+"/image")+System.currentTimeMillis()+"."+format;
if(format.startsWith("jp")){
try {
OutputStream os=new FileOutputStream(fileName);
bitmap=BitmapFactory.decodeFile(path,options);
bitmap.compress(Bitmap.CompressFormat.JPEG,60,os);
os.close();
File temp=new File(fileName);
Network.postFile(url_upload,temp,handler,UPLOAD_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}else if (format.startsWith("png")){
try {
OutputStream os=new FileOutputStream(fileName);
bitmap=BitmapFactory.decodeFile(path,options);
bitmap.compress(Bitmap.CompressFormat.PNG,60,os);
os.close();
File temp=new File(fileName);
Network.postFile(url_upload,temp,handler,UPLOAD_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Network.postFile(url_upload,file,handler,UPLOAD_IMAGE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
switch (requestCode){
case TAKE_PHOTO:
realPath = Fileutils.getRealFilePathFromUri(this,data.getData());
if (realPath!=null&&realPath.length()>1){
Log.e("realPath",realPath);
Log.e("data",data.getData().toString());
uploadImage(realPath);
imageView.setImageBitmap(BitmapFactory.decodeFile(realPath));
}
else{
Toast.makeText(mFirstApplication, "选择照片失败!", Toast.LENGTH_SHORT).show();
promptDialog.showError("选择照片失败!");
}
break;
case ScanCode:
Log.e("result",data.getStringExtra("result"));
String enc=data.getStringExtra("result");
for (String temp:enc.split("&")){
if(temp.startsWith("enc"))
{
enc="&"+temp;
break;
}
}
if(enc.length()>5){
String url1="https://mobilelearn.chaoxing.com/pptSign/stuSignajax?activeId="+aid+"&uid="+mFirstApplication.infoMap.get("uid")+enc;
Network.getSync(url1,handler,SIGN4);
}
break;
}
}else {
promptDialog.showError("操作失败!");
}
}
} | 0 |
21776_7 | import utils.Constants;
import java.io.*;
public class Reload {
private final static String app_dir=System.getProperty("user.dir");
/**
* 输出字符文件序列
* @return
*/
public static Boolean play() {
//Console c = System.console();
boolean result=true;
try{
new ProcessBuilder("cmd", "/c", "mode con cols=1920 lines=1080").inheritIO().start().waitFor();
}
catch (Exception e){
result = false;
e.printStackTrace();
}
//
File file = new File(app_dir+"\\"+Constants.txt_dir);
if(file.isDirectory() && file.exists()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for(int i=0;i<files.length;i++){
try {
// //清屏,防抖动
new ProcessBuilder("cmd", "/c", "cls")
// 将 ProcessBuilder 对象的输出管道和 Java 的进程进行关联,这个函数的返回值也是一个
// ProcessBuilder
.inheritIO()
// 开始执行 ProcessBuilder 中的命令
.start()
// 等待 ProcessBuilder 中的清屏命令执行完毕
// 如果不等待则会出现清屏代码后面的输出被清掉的情况
.waitFor(); // 清屏命令
File file1 = new File(app_dir+"\\"+Constants.txt_dir+"\\"+(i+1)+".txt");
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file1));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line=bufferedReader.readLine())!=null){
//c.writer().println(line);
System.out.println(line);
}
Thread.sleep(40);
} catch (Exception e) {
result = false;
e.printStackTrace();
}
}
}
}
return result;
}
}
| 343701675/video2text | src/Reload.java | 453 | // 如果不等待则会出现清屏代码后面的输出被清掉的情况 | line_comment | zh-cn | import utils.Constants;
import java.io.*;
public class Reload {
private final static String app_dir=System.getProperty("user.dir");
/**
* 输出字符文件序列
* @return
*/
public static Boolean play() {
//Console c = System.console();
boolean result=true;
try{
new ProcessBuilder("cmd", "/c", "mode con cols=1920 lines=1080").inheritIO().start().waitFor();
}
catch (Exception e){
result = false;
e.printStackTrace();
}
//
File file = new File(app_dir+"\\"+Constants.txt_dir);
if(file.isDirectory() && file.exists()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for(int i=0;i<files.length;i++){
try {
// //清屏,防抖动
new ProcessBuilder("cmd", "/c", "cls")
// 将 ProcessBuilder 对象的输出管道和 Java 的进程进行关联,这个函数的返回值也是一个
// ProcessBuilder
.inheritIO()
// 开始执行 ProcessBuilder 中的命令
.start()
// 等待 ProcessBuilder 中的清屏命令执行完毕
// 如果 <SUF>
.waitFor(); // 清屏命令
File file1 = new File(app_dir+"\\"+Constants.txt_dir+"\\"+(i+1)+".txt");
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file1));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line=bufferedReader.readLine())!=null){
//c.writer().println(line);
System.out.println(line);
}
Thread.sleep(40);
} catch (Exception e) {
result = false;
e.printStackTrace();
}
}
}
}
return result;
}
}
| 0 |
27254_20 | package com.hongx.zhibo;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.hongx.zhibo.utils.DisplayUtil;
import com.hongx.zhibo.utils.HorizontalListView;
import com.hongx.zhibo.utils.MagicTextView;
import com.hongx.zhibo.utils.SoftKeyBoardListener;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author: fuchenming
* @create: 2020-02-01 15:50
*/
public class LayerFrag extends Fragment implements View.OnClickListener {
// 礼物
private int[] GiftIcon = new int[]{R.drawable.zem72,
R.drawable.zem70,
R.drawable.zem68,
R.drawable.zem63};
private NumberAnim giftNumberAnim;
private List<String> messageData = new LinkedList<>();
private MessageAdapter messageAdapter;
private ListView lv_message;
private HorizontalListView hlv_audience;
private LinearLayout ll_gift_group;
private TranslateAnimation outAnim;
private TranslateAnimation inAnim;
private LinearLayout ll_inputparent;
private Button tv_chat;
private TextView tv_send;
private EditText et_chat;
private LinearLayout ll_anchor;
private RelativeLayout rl_num;
private Context myContext;
private Button btn_gift01;
private Button btn_gift02;
private Button btn_gift03;
private Button btn_gift04;
private View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.frag_layer, null);
myContext = getActivity();
initView(view);
initData();
return view;
}
public void initView(View view) {
lv_message = view.findViewById(R.id.lv_message);
hlv_audience = view.findViewById(R.id.hlv_audience);
ll_gift_group = view.findViewById(R.id.ll_gift_group);
ll_inputparent = view.findViewById(R.id.ll_inputparent);
tv_chat = view.findViewById(R.id.tv_chat);
tv_send = view.findViewById(R.id.tv_send);
et_chat = view.findViewById(R.id.et_chat);
ll_anchor = view.findViewById(R.id.ll_anchor);
rl_num = view.findViewById(R.id.rl_num);
btn_gift01 = view.findViewById(R.id.btn_gift01);
btn_gift02 = view.findViewById(R.id.btn_gift02);
btn_gift03 = view.findViewById(R.id.btn_gift03);
btn_gift04 = view.findViewById(R.id.btn_gift04);
}
private void initData() {
initAudience(); // 初始化观众
initMessage(); // 初始化评论
initListener();
clearTiming(); // 开启定时清理礼物列表
initAnim(); // 初始化动画
}
/**
* 初始化观众列表
*/
private void initAudience() {
hlv_audience.setAdapter(new AudienceAdapter(myContext));
}
/**
* 初始化评论列表
*/
private void initMessage() {
for (int x = 0; x < 20; x++) {
messageData.add("小明: 主播好漂亮啊" + x);
}
messageAdapter = new MessageAdapter(getActivity(), messageData);
lv_message.setAdapter(messageAdapter);
lv_message.setSelection(messageData.size());
}
private void initListener() {
btn_gift01.setOnClickListener(this);
btn_gift02.setOnClickListener(this);
btn_gift03.setOnClickListener(this);
btn_gift04.setOnClickListener(this);
tv_chat.setOnClickListener(this);
tv_send.setOnClickListener(this);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ll_inputparent.getVisibility() == View.VISIBLE) {
tv_chat.setVisibility(View.VISIBLE);
ll_inputparent.setVisibility(View.GONE);
hideKeyboard();
}
}
});
// 软键盘监听
SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
@Override
public void keyBoardShow(int height) {/*软键盘显示:执行隐藏title动画,并修改listview高度和装载礼物容器的高度*/
// 输入文字时的界面退出动画
AnimatorSet animatorSetHide = new AnimatorSet();
ObjectAnimator leftOutAnim = ObjectAnimator.ofFloat(rl_num, "translationX", 0, -rl_num.getWidth());
ObjectAnimator topOutAnim = ObjectAnimator.ofFloat(ll_anchor, "translationY", 0, -ll_anchor.getHeight());
animatorSetHide.playTogether(leftOutAnim, topOutAnim);
animatorSetHide.setDuration(300);
animatorSetHide.start();
// 改变listview的高度
dynamicChangeListviewH(90);
dynamicChangeGiftParentH(true);
}
@Override
public void keyBoardHide(int height) {/*软键盘隐藏:隐藏聊天输入框并显示聊天按钮,执行显示title动画,并修改listview高度和装载礼物容器的高度*/
tv_chat.setVisibility(View.VISIBLE);
ll_inputparent.setVisibility(View.GONE);
// 输入文字时的界面进入时的动画
AnimatorSet animatorSetShow = new AnimatorSet();
ObjectAnimator leftInAnim = ObjectAnimator.ofFloat(rl_num, "translationX", -rl_num.getWidth(), 0);
ObjectAnimator topInAnim = ObjectAnimator.ofFloat(ll_anchor, "translationY", -ll_anchor.getHeight(), 0);
animatorSetShow.playTogether(leftInAnim, topInAnim);
animatorSetShow.setDuration(300);
animatorSetShow.start();
// 改变listview的高度
dynamicChangeListviewH(150);
dynamicChangeGiftParentH(false);
}
});
}
/**
* 初始化动画
*/
private void initAnim() {
giftNumberAnim = new NumberAnim(); // 初始化数字动画
inAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_in); // 礼物进入时动画
outAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_out); // 礼物退出时动画
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_gift01: // 礼物1,送香皂
showGift("gift01");
break;
case R.id.btn_gift02: // 礼物2,送玫瑰
showGift("gift02");
break;
case R.id.btn_gift03: // 礼物3,送爱心
showGift("gift03");
break;
case R.id.btn_gift04: // 礼物4,送蛋糕
showGift("gift04");
break;
case R.id.tv_chat:// 聊天
tv_chat.setVisibility(View.GONE);
ll_inputparent.setVisibility(View.VISIBLE);
ll_inputparent.requestFocus(); // 获取焦点
showKeyboard();
break;
case R.id.tv_send:// 发送消息
String chatMsg = et_chat.getText().toString();
if (!TextUtils.isEmpty(chatMsg)) {
messageData.add("小明: " + chatMsg);
et_chat.setText("");
messageAdapter.NotifyAdapter(messageData);
lv_message.setSelection(messageData.size());
}
hideKeyboard();
break;
}
}
public class NumberAnim {
private Animator lastAnimator;
public void showAnimator(View v) {
if (lastAnimator != null) {
lastAnimator.removeAllListeners();
lastAnimator.cancel();
lastAnimator.end();
}
ObjectAnimator animScaleX = ObjectAnimator.ofFloat(v, "scaleX", 1.3f, 1.0f);
ObjectAnimator animScaleY = ObjectAnimator.ofFloat(v, "scaleY", 1.3f, 1.0f);
AnimatorSet animSet = new AnimatorSet();
animSet.playTogether(animScaleX, animScaleY);
animSet.setDuration(200);
lastAnimator = animSet;
animSet.start();
}
}
/**
* 刷礼物的方法
*/
private void showGift(String tag) {
View newGiftView = ll_gift_group.findViewWithTag(tag);
// 是否有该tag类型的礼物
if (newGiftView == null) {
// 判断礼物列表是否已经有3个了,如果有那么删除掉一个没更新过的, 然后再添加新进来的礼物,始终保持只有3个
if (ll_gift_group.getChildCount() >= 3) {
// 获取前2个元素的最后更新时间
View giftView01 = ll_gift_group.getChildAt(0);
ImageView iv_gift01 = giftView01.findViewById(R.id.iv_gift);
long lastTime1 = (long) iv_gift01.getTag();
View giftView02 = ll_gift_group.getChildAt(1);
ImageView iv_gift02 = giftView02.findViewById(R.id.iv_gift);
long lastTime2 = (long) iv_gift02.getTag();
if (lastTime1 > lastTime2) { // 如果第二个View显示的时间比较长
removeGiftView(1);
} else { // 如果第一个View显示的时间长
removeGiftView(0);
}
}
// 获取礼物
newGiftView = getNewGiftView(tag);
ll_gift_group.addView(newGiftView);
// 播放动画
newGiftView.startAnimation(inAnim);
final MagicTextView mtv_giftNum = newGiftView.findViewById(R.id.mtv_giftNum);
inAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
giftNumberAnim.showAnimator(mtv_giftNum);
}
});
} else {
// 如果列表中已经有了该类型的礼物,则不再新建,直接拿出
// 更新标识,记录最新修改的时间,用于回收判断
ImageView iv_gift = newGiftView.findViewById(R.id.iv_gift);
iv_gift.setTag(System.currentTimeMillis());
// 更新标识,更新记录礼物个数
MagicTextView mtv_giftNum = newGiftView.findViewById(R.id.mtv_giftNum);
int giftCount = (int) mtv_giftNum.getTag() + 1; // 递增
mtv_giftNum.setText("x" + giftCount);
mtv_giftNum.setTag(giftCount);
giftNumberAnim.showAnimator(mtv_giftNum);
}
}
/**
* 获取礼物
*/
private View getNewGiftView(String tag) {
// 添加标识, 该view若在layout中存在,就不在生成(用于findViewWithTag判断是否存在)
View giftView = LayoutInflater.from(myContext).inflate(R.layout.item_gift, null);
giftView.setTag(tag);
// 添加标识, 记录生成时间,回收时用于判断是否是最新的,回收最老的
ImageView iv_gift = giftView.findViewById(R.id.iv_gift);
iv_gift.setTag(System.currentTimeMillis());
// 添加标识,记录礼物个数
MagicTextView mtv_giftNum = giftView.findViewById(R.id.mtv_giftNum);
mtv_giftNum.setTag(1);
mtv_giftNum.setText("x1");
switch (tag) {
case "gift01":
iv_gift.setImageResource(GiftIcon[0]);
break;
case "gift02":
iv_gift.setImageResource(GiftIcon[1]);
break;
case "gift03":
iv_gift.setImageResource(GiftIcon[2]);
break;
case "gift04":
iv_gift.setImageResource(GiftIcon[3]);
break;
}
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.topMargin = 10;
giftView.setLayoutParams(lp);
return giftView;
}
/**
* 移除礼物列表里的giftView
*/
private void removeGiftView(final int index) {
// 移除列表,外加退出动画
final View removeGiftView = ll_gift_group.getChildAt(index);
outAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
ll_gift_group.removeViewAt(index);
}
});
// 开启动画,因为定时原因,所以可能是在子线程
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
removeGiftView.startAnimation(outAnim);
}
});
}
/**
* 定时清理礼物列表信息
*/
private void clearTiming() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
int childCount = ll_gift_group.getChildCount();
long nowTime = System.currentTimeMillis();
for (int i = 0; i < childCount; i++) {
View childView = ll_gift_group.getChildAt(i);
ImageView iv_gift = (ImageView) childView.findViewById(R.id.iv_gift);
long lastUpdateTime = (long) iv_gift.getTag();
// 更新超过3秒就刷新
if (nowTime - lastUpdateTime >= 3000) {
removeGiftView(i);
}
}
}
}, 0, 3000);
}
/**
* 显示软键盘
*/
private void showKeyboard() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et_chat, InputMethodManager.SHOW_FORCED);
}
/**
* 隐藏软键盘
*/
public void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et_chat.getWindowToken(), 0);
}
/**
* 动态的修改listview的高度
*/
private void dynamicChangeListviewH(int heightPX) {
ViewGroup.LayoutParams layoutParams = lv_message.getLayoutParams();
layoutParams.height = DisplayUtil.dip2px(getActivity(), heightPX);
lv_message.setLayoutParams(layoutParams);
}
/**
* 动态修改礼物父布局的高度
*/
private void dynamicChangeGiftParentH(boolean showhide) {
if (showhide) {// 如果软键盘显示中
if (ll_gift_group.getChildCount() != 0) {
// 判断是否有礼物显示,如果有就修改父布局高度,如果没有就不作任何操作
ViewGroup.LayoutParams layoutParams = ll_gift_group.getLayoutParams();
layoutParams.height = ll_gift_group.getChildAt(0).getHeight();
ll_gift_group.setLayoutParams(layoutParams);
}
} else {
// 如果软键盘隐藏中
// 就将装载礼物的容器的高度设置为包裹内容
ViewGroup.LayoutParams layoutParams = ll_gift_group.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
ll_gift_group.setLayoutParams(layoutParams);
}
}
}
| 345166018/AndroidUI | HxZhibo/app/src/main/java/com/hongx/zhibo/LayerFrag.java | 4,015 | // 礼物3,送爱心 | line_comment | zh-cn | package com.hongx.zhibo;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.hongx.zhibo.utils.DisplayUtil;
import com.hongx.zhibo.utils.HorizontalListView;
import com.hongx.zhibo.utils.MagicTextView;
import com.hongx.zhibo.utils.SoftKeyBoardListener;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author: fuchenming
* @create: 2020-02-01 15:50
*/
public class LayerFrag extends Fragment implements View.OnClickListener {
// 礼物
private int[] GiftIcon = new int[]{R.drawable.zem72,
R.drawable.zem70,
R.drawable.zem68,
R.drawable.zem63};
private NumberAnim giftNumberAnim;
private List<String> messageData = new LinkedList<>();
private MessageAdapter messageAdapter;
private ListView lv_message;
private HorizontalListView hlv_audience;
private LinearLayout ll_gift_group;
private TranslateAnimation outAnim;
private TranslateAnimation inAnim;
private LinearLayout ll_inputparent;
private Button tv_chat;
private TextView tv_send;
private EditText et_chat;
private LinearLayout ll_anchor;
private RelativeLayout rl_num;
private Context myContext;
private Button btn_gift01;
private Button btn_gift02;
private Button btn_gift03;
private Button btn_gift04;
private View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.frag_layer, null);
myContext = getActivity();
initView(view);
initData();
return view;
}
public void initView(View view) {
lv_message = view.findViewById(R.id.lv_message);
hlv_audience = view.findViewById(R.id.hlv_audience);
ll_gift_group = view.findViewById(R.id.ll_gift_group);
ll_inputparent = view.findViewById(R.id.ll_inputparent);
tv_chat = view.findViewById(R.id.tv_chat);
tv_send = view.findViewById(R.id.tv_send);
et_chat = view.findViewById(R.id.et_chat);
ll_anchor = view.findViewById(R.id.ll_anchor);
rl_num = view.findViewById(R.id.rl_num);
btn_gift01 = view.findViewById(R.id.btn_gift01);
btn_gift02 = view.findViewById(R.id.btn_gift02);
btn_gift03 = view.findViewById(R.id.btn_gift03);
btn_gift04 = view.findViewById(R.id.btn_gift04);
}
private void initData() {
initAudience(); // 初始化观众
initMessage(); // 初始化评论
initListener();
clearTiming(); // 开启定时清理礼物列表
initAnim(); // 初始化动画
}
/**
* 初始化观众列表
*/
private void initAudience() {
hlv_audience.setAdapter(new AudienceAdapter(myContext));
}
/**
* 初始化评论列表
*/
private void initMessage() {
for (int x = 0; x < 20; x++) {
messageData.add("小明: 主播好漂亮啊" + x);
}
messageAdapter = new MessageAdapter(getActivity(), messageData);
lv_message.setAdapter(messageAdapter);
lv_message.setSelection(messageData.size());
}
private void initListener() {
btn_gift01.setOnClickListener(this);
btn_gift02.setOnClickListener(this);
btn_gift03.setOnClickListener(this);
btn_gift04.setOnClickListener(this);
tv_chat.setOnClickListener(this);
tv_send.setOnClickListener(this);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ll_inputparent.getVisibility() == View.VISIBLE) {
tv_chat.setVisibility(View.VISIBLE);
ll_inputparent.setVisibility(View.GONE);
hideKeyboard();
}
}
});
// 软键盘监听
SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
@Override
public void keyBoardShow(int height) {/*软键盘显示:执行隐藏title动画,并修改listview高度和装载礼物容器的高度*/
// 输入文字时的界面退出动画
AnimatorSet animatorSetHide = new AnimatorSet();
ObjectAnimator leftOutAnim = ObjectAnimator.ofFloat(rl_num, "translationX", 0, -rl_num.getWidth());
ObjectAnimator topOutAnim = ObjectAnimator.ofFloat(ll_anchor, "translationY", 0, -ll_anchor.getHeight());
animatorSetHide.playTogether(leftOutAnim, topOutAnim);
animatorSetHide.setDuration(300);
animatorSetHide.start();
// 改变listview的高度
dynamicChangeListviewH(90);
dynamicChangeGiftParentH(true);
}
@Override
public void keyBoardHide(int height) {/*软键盘隐藏:隐藏聊天输入框并显示聊天按钮,执行显示title动画,并修改listview高度和装载礼物容器的高度*/
tv_chat.setVisibility(View.VISIBLE);
ll_inputparent.setVisibility(View.GONE);
// 输入文字时的界面进入时的动画
AnimatorSet animatorSetShow = new AnimatorSet();
ObjectAnimator leftInAnim = ObjectAnimator.ofFloat(rl_num, "translationX", -rl_num.getWidth(), 0);
ObjectAnimator topInAnim = ObjectAnimator.ofFloat(ll_anchor, "translationY", -ll_anchor.getHeight(), 0);
animatorSetShow.playTogether(leftInAnim, topInAnim);
animatorSetShow.setDuration(300);
animatorSetShow.start();
// 改变listview的高度
dynamicChangeListviewH(150);
dynamicChangeGiftParentH(false);
}
});
}
/**
* 初始化动画
*/
private void initAnim() {
giftNumberAnim = new NumberAnim(); // 初始化数字动画
inAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_in); // 礼物进入时动画
outAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_out); // 礼物退出时动画
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_gift01: // 礼物1,送香皂
showGift("gift01");
break;
case R.id.btn_gift02: // 礼物2,送玫瑰
showGift("gift02");
break;
case R.id.btn_gift03: // 礼物 <SUF>
showGift("gift03");
break;
case R.id.btn_gift04: // 礼物4,送蛋糕
showGift("gift04");
break;
case R.id.tv_chat:// 聊天
tv_chat.setVisibility(View.GONE);
ll_inputparent.setVisibility(View.VISIBLE);
ll_inputparent.requestFocus(); // 获取焦点
showKeyboard();
break;
case R.id.tv_send:// 发送消息
String chatMsg = et_chat.getText().toString();
if (!TextUtils.isEmpty(chatMsg)) {
messageData.add("小明: " + chatMsg);
et_chat.setText("");
messageAdapter.NotifyAdapter(messageData);
lv_message.setSelection(messageData.size());
}
hideKeyboard();
break;
}
}
public class NumberAnim {
private Animator lastAnimator;
public void showAnimator(View v) {
if (lastAnimator != null) {
lastAnimator.removeAllListeners();
lastAnimator.cancel();
lastAnimator.end();
}
ObjectAnimator animScaleX = ObjectAnimator.ofFloat(v, "scaleX", 1.3f, 1.0f);
ObjectAnimator animScaleY = ObjectAnimator.ofFloat(v, "scaleY", 1.3f, 1.0f);
AnimatorSet animSet = new AnimatorSet();
animSet.playTogether(animScaleX, animScaleY);
animSet.setDuration(200);
lastAnimator = animSet;
animSet.start();
}
}
/**
* 刷礼物的方法
*/
private void showGift(String tag) {
View newGiftView = ll_gift_group.findViewWithTag(tag);
// 是否有该tag类型的礼物
if (newGiftView == null) {
// 判断礼物列表是否已经有3个了,如果有那么删除掉一个没更新过的, 然后再添加新进来的礼物,始终保持只有3个
if (ll_gift_group.getChildCount() >= 3) {
// 获取前2个元素的最后更新时间
View giftView01 = ll_gift_group.getChildAt(0);
ImageView iv_gift01 = giftView01.findViewById(R.id.iv_gift);
long lastTime1 = (long) iv_gift01.getTag();
View giftView02 = ll_gift_group.getChildAt(1);
ImageView iv_gift02 = giftView02.findViewById(R.id.iv_gift);
long lastTime2 = (long) iv_gift02.getTag();
if (lastTime1 > lastTime2) { // 如果第二个View显示的时间比较长
removeGiftView(1);
} else { // 如果第一个View显示的时间长
removeGiftView(0);
}
}
// 获取礼物
newGiftView = getNewGiftView(tag);
ll_gift_group.addView(newGiftView);
// 播放动画
newGiftView.startAnimation(inAnim);
final MagicTextView mtv_giftNum = newGiftView.findViewById(R.id.mtv_giftNum);
inAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
giftNumberAnim.showAnimator(mtv_giftNum);
}
});
} else {
// 如果列表中已经有了该类型的礼物,则不再新建,直接拿出
// 更新标识,记录最新修改的时间,用于回收判断
ImageView iv_gift = newGiftView.findViewById(R.id.iv_gift);
iv_gift.setTag(System.currentTimeMillis());
// 更新标识,更新记录礼物个数
MagicTextView mtv_giftNum = newGiftView.findViewById(R.id.mtv_giftNum);
int giftCount = (int) mtv_giftNum.getTag() + 1; // 递增
mtv_giftNum.setText("x" + giftCount);
mtv_giftNum.setTag(giftCount);
giftNumberAnim.showAnimator(mtv_giftNum);
}
}
/**
* 获取礼物
*/
private View getNewGiftView(String tag) {
// 添加标识, 该view若在layout中存在,就不在生成(用于findViewWithTag判断是否存在)
View giftView = LayoutInflater.from(myContext).inflate(R.layout.item_gift, null);
giftView.setTag(tag);
// 添加标识, 记录生成时间,回收时用于判断是否是最新的,回收最老的
ImageView iv_gift = giftView.findViewById(R.id.iv_gift);
iv_gift.setTag(System.currentTimeMillis());
// 添加标识,记录礼物个数
MagicTextView mtv_giftNum = giftView.findViewById(R.id.mtv_giftNum);
mtv_giftNum.setTag(1);
mtv_giftNum.setText("x1");
switch (tag) {
case "gift01":
iv_gift.setImageResource(GiftIcon[0]);
break;
case "gift02":
iv_gift.setImageResource(GiftIcon[1]);
break;
case "gift03":
iv_gift.setImageResource(GiftIcon[2]);
break;
case "gift04":
iv_gift.setImageResource(GiftIcon[3]);
break;
}
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.topMargin = 10;
giftView.setLayoutParams(lp);
return giftView;
}
/**
* 移除礼物列表里的giftView
*/
private void removeGiftView(final int index) {
// 移除列表,外加退出动画
final View removeGiftView = ll_gift_group.getChildAt(index);
outAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
ll_gift_group.removeViewAt(index);
}
});
// 开启动画,因为定时原因,所以可能是在子线程
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
removeGiftView.startAnimation(outAnim);
}
});
}
/**
* 定时清理礼物列表信息
*/
private void clearTiming() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
int childCount = ll_gift_group.getChildCount();
long nowTime = System.currentTimeMillis();
for (int i = 0; i < childCount; i++) {
View childView = ll_gift_group.getChildAt(i);
ImageView iv_gift = (ImageView) childView.findViewById(R.id.iv_gift);
long lastUpdateTime = (long) iv_gift.getTag();
// 更新超过3秒就刷新
if (nowTime - lastUpdateTime >= 3000) {
removeGiftView(i);
}
}
}
}, 0, 3000);
}
/**
* 显示软键盘
*/
private void showKeyboard() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et_chat, InputMethodManager.SHOW_FORCED);
}
/**
* 隐藏软键盘
*/
public void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et_chat.getWindowToken(), 0);
}
/**
* 动态的修改listview的高度
*/
private void dynamicChangeListviewH(int heightPX) {
ViewGroup.LayoutParams layoutParams = lv_message.getLayoutParams();
layoutParams.height = DisplayUtil.dip2px(getActivity(), heightPX);
lv_message.setLayoutParams(layoutParams);
}
/**
* 动态修改礼物父布局的高度
*/
private void dynamicChangeGiftParentH(boolean showhide) {
if (showhide) {// 如果软键盘显示中
if (ll_gift_group.getChildCount() != 0) {
// 判断是否有礼物显示,如果有就修改父布局高度,如果没有就不作任何操作
ViewGroup.LayoutParams layoutParams = ll_gift_group.getLayoutParams();
layoutParams.height = ll_gift_group.getChildAt(0).getHeight();
ll_gift_group.setLayoutParams(layoutParams);
}
} else {
// 如果软键盘隐藏中
// 就将装载礼物的容器的高度设置为包裹内容
ViewGroup.LayoutParams layoutParams = ll_gift_group.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
ll_gift_group.setLayoutParams(layoutParams);
}
}
}
| 0 |
26167_1 | package chapter04;
public class Java02_object {
public static void main(String[] args) {
//TODO 面向对象
//类:动物
//对象:猫,狗
Animal a1 = new Animal();
a1.type ="狗";
a1.name ="旺财";
a1.run() ;
Animal a2 = new Animal();
a2.type ="猫";
a2.name ="罗小黑";
a2.run() ;
}
}
class Animal{
String type;
String name;
void run(){
System.out.println(type+ " " + name + "跑开了");
}
} | 3471437753/Java | src/chapter04/Java02_object.java | 163 | //类:动物
| line_comment | zh-cn | package chapter04;
public class Java02_object {
public static void main(String[] args) {
//TODO 面向对象
//类: <SUF>
//对象:猫,狗
Animal a1 = new Animal();
a1.type ="狗";
a1.name ="旺财";
a1.run() ;
Animal a2 = new Animal();
a2.type ="猫";
a2.name ="罗小黑";
a2.run() ;
}
}
class Animal{
String type;
String name;
void run(){
System.out.println(type+ " " + name + "跑开了");
}
} | 0 |
66711_4 | /*
* Copyright [2016-2026] wangcheng(wantedonline@outlook.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.wantedonline.puppy.httpserver.system;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import cn.wantedonline.puppy.httpserver.common.HttpServerConfig;
import cn.wantedonline.puppy.spring.annotation.AfterBootstrap;
import cn.wantedonline.puppy.spring.annotation.Config;
import cn.wantedonline.puppy.util.Log;
import cn.wantedonline.puppy.util.concurrent.ConcurrentUtil;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SystemChecker {
private static final Logger log = Log.getLogger(SystemMonitor.class);
private static SystemChecker INSTANCE;
private SystemChecker() {
INSTANCE = this;
}
public static SystemChecker getInstance() {
return INSTANCE;
}
@Autowired
protected HttpServerConfig config;
private static volatile boolean denialOfService = false;
/** 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */
private static volatile boolean denialOfServiceAlmost = false;
/** 系统最重要的线程池的监控,要很实时 */
@Config
private int dosMonitorCheckSec = 1;
/** 垃圾回收监控,建议5分钟监控一次(因为是总回收时间的对比) */
@Config
private int gcMonitorSec = 5 * 60;
private static volatile boolean lastTestDenialOfService = false;
@Config(resetable = true)
private double loadMonitorErrorThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM;
/** 系统负载监控,建议半分钟监控一次(因为是平均负载) */
@Config
private int loadMonitorSec = 1 * 30;
/** 数值的界定,请参考http://blog.csdn.net/marising/article/details/5182771 */
@Config(resetable = true)
private double loadMonitorWarnThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM * 0.7;
/** 线程cpu时间监控,建议每半分钟监控一次 */
@Config
private int threadCpuTimeMonitorSec = 1 * 30;
@Config(resetable = true)
private int threadMonitorQueueThreshold = 1000;
/** 线程池监控,建议每5秒钟监控一次(因为每时每刻的queue的数量都可能在大幅度变化) */
@Config
private int threadMonitorSec = 5;
/** log线程池监控,要严防队列过大导致IO过高和内存溢出 */
@Config
private int logMonitorCheckSec = 10;
@Config(resetable = true)
private int logMonitorLimit = 20000;
private static volatile boolean logEnabled = true;
private static volatile boolean logAlreadyExceeded = false;
/** 为了防止启动时候突然飙高而报,启动时候第一次不报,可以防止服务器启动时突然的堆积日志把服务器搞崩溃 */
private static volatile boolean logExceededFirstTime = true;
/** 线程池允许等待的线程数 */
@Config(resetable = true)
private int threadPoolQueueCountLimit = 30000;
@AfterBootstrap
protected void init() {
SystemMonitor.initGarbageCollectMonitor(gcMonitorSec);
SystemMonitor.initLoadAverageMonitor(loadMonitorSec);
SystemMonitor.initThreadCpuTimeMonitor(threadCpuTimeMonitorSec);
SystemMonitor.initThreadPoolMonitor(threadMonitorSec, threadMonitorQueueThreshold);
initDenialOfServiceMonitor();
initLogMonitor();
}
public void initDenialOfServiceMonitor() {
if (dosMonitorCheckSec > 0) {
log.info("DenialOfServiceMonitor ON, interval:{}sec, Worker EventLoop Size:{}", dosMonitorCheckSec, config.getWorkerEventLoopGroup().executorCount());
ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() {
/**
* check denialOfServiceAlmost
*/
private boolean check2(NioEventLoopGroup workerEventLoop) {
int _threadPoolQueueCountLimit = threadPoolQueueCountLimit - 500;// 几乎要拒绝服务的等待队列阀值
//TODO:如何实现DOS防范
/*
int activeCount = executor.getActiveCount();
int queueCount = executor.getQueue().size(); // 等待队列的大小
int largestPoolSize = executor.getLargestPoolSize();
int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) {
ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS
activeCount = executor.getActiveCount();
int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > _threadPoolQueueCountLimit) {
denialOfServiceAlmost = true;
return true;
}
}
*/
return false;
}
/**
* check denialOfService
*/
private boolean check(NioEventLoopGroup workerEventLoop) {
/*
int activeCount = executor.getActiveCount();
int queueCount = executor.getQueue().size(); // 等待队列的大小
int largestPoolSize = executor.getLargestPoolSize();
int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) {
String pipelineInfo = SystemInfo.getThreadsDetailInfo("PIPELINE", true, 20); // 先打印好
ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS
activeCount = executor.getActiveCount();
int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > threadPoolQueueCountLimit) { // 打印好了,线程池仍然大量占用,就发出报警邮件
if (!lastTestDenialOfService) {
MDC.put("mailTitle", "DenialOfService");
log.error("DENIAL OF SERVICE, ACTIVE_SIZE:{}, WAITTING_QUEUE_SIZE:{}, RUNNING PIPELINE:\n{}\n\n", activeCount, currQueueCount, pipelineInfo);
}
denialOfService = true;
lastTestDenialOfService = true;
denialOfServiceAlmost = true;
return true;
}
}
*/
return false;
}
@Override
public void run() {
boolean r = check(config.getWorkerEventLoopGroup());
boolean r1 = check(config.getWorkerEventLoopGroup());
if (!r && !r1) {
denialOfService = false;
lastTestDenialOfService = false;
}
boolean r2 = check2(config.getWorkerEventLoopGroup());
boolean r21 = check2(config.getWorkerEventLoopGroup());
if (!r2 && !r21) {
denialOfServiceAlmost = false;
}
}
}, dosMonitorCheckSec * 5, dosMonitorCheckSec, TimeUnit.SECONDS);// httpServer刚启动时,很有可能很多请求冲进来,先不拒绝服务,所以暂定5s后再开始定时
}
}
public void initLogMonitor() {
if (logMonitorCheckSec > 0) {
final ThreadPoolExecutor logExecutor = (ThreadPoolExecutor) ConcurrentUtil.getLogExecutor();
log.info("LogMonitor ON, interval:{}sec, logExecutorSize:{}", logMonitorCheckSec, logExecutor.getQueue().size());
ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
boolean r = isLogExceeded(logExecutor);
if (!r) {
logEnabled = true;
logAlreadyExceeded = false;
}
}
/**
* 检查日志线程池队列任务数
*
* @return 如果超过限值返回true,没超过返回false
*/
private boolean isLogExceeded(ThreadPoolExecutor executor) {
int queueCount = executor.getQueue().size(); // 如果队列的log超过限制,就临时把日志功能关闭
if (queueCount > logMonitorLimit) {
if (!logAlreadyExceeded) { // 保证超过限定值之后只报出一次,如果回退到限定值内,再超过才再报
if (logExceededFirstTime) {
logExceededFirstTime = false;
} else {
MDC.put("mailTitle", "TOO MANY LOGS");
log.error("TOO MANY LOGS,WAITTING_QUEUE_SIZE:{}\n", queueCount);
}
}
logEnabled = false;
logAlreadyExceeded = true;
return true;
}
return false;
}
}, logMonitorCheckSec, logMonitorCheckSec, TimeUnit.SECONDS);
}
}
/**
* 是否达到拒绝服务的阀值
*/
public static boolean isDenialOfService() {
return denialOfService;
}
/**
* 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500
*/
public static boolean isDenialOfServiceAlmost() {
return denialOfServiceAlmost;
}
/**
* 如果日志功能打开了,才记录日志
*/
public static boolean isLogEnabled() {
return logEnabled;
}
public double getLoadMonitorErrorThreshold() {
return loadMonitorErrorThreshold;
}
public double getLoadMonitorWarnThreshold() {
return loadMonitorWarnThreshold;
}
}
| 34benma/Puppy | src/main/java/cn/wantedonline/puppy/httpserver/system/SystemChecker.java | 2,577 | /** 系统负载监控,建议半分钟监控一次(因为是平均负载) */ | block_comment | zh-cn | /*
* Copyright [2016-2026] wangcheng(wantedonline@outlook.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.wantedonline.puppy.httpserver.system;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import cn.wantedonline.puppy.httpserver.common.HttpServerConfig;
import cn.wantedonline.puppy.spring.annotation.AfterBootstrap;
import cn.wantedonline.puppy.spring.annotation.Config;
import cn.wantedonline.puppy.util.Log;
import cn.wantedonline.puppy.util.concurrent.ConcurrentUtil;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SystemChecker {
private static final Logger log = Log.getLogger(SystemMonitor.class);
private static SystemChecker INSTANCE;
private SystemChecker() {
INSTANCE = this;
}
public static SystemChecker getInstance() {
return INSTANCE;
}
@Autowired
protected HttpServerConfig config;
private static volatile boolean denialOfService = false;
/** 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */
private static volatile boolean denialOfServiceAlmost = false;
/** 系统最重要的线程池的监控,要很实时 */
@Config
private int dosMonitorCheckSec = 1;
/** 垃圾回收监控,建议5分钟监控一次(因为是总回收时间的对比) */
@Config
private int gcMonitorSec = 5 * 60;
private static volatile boolean lastTestDenialOfService = false;
@Config(resetable = true)
private double loadMonitorErrorThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM;
/** 系统负 <SUF>*/
@Config
private int loadMonitorSec = 1 * 30;
/** 数值的界定,请参考http://blog.csdn.net/marising/article/details/5182771 */
@Config(resetable = true)
private double loadMonitorWarnThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM * 0.7;
/** 线程cpu时间监控,建议每半分钟监控一次 */
@Config
private int threadCpuTimeMonitorSec = 1 * 30;
@Config(resetable = true)
private int threadMonitorQueueThreshold = 1000;
/** 线程池监控,建议每5秒钟监控一次(因为每时每刻的queue的数量都可能在大幅度变化) */
@Config
private int threadMonitorSec = 5;
/** log线程池监控,要严防队列过大导致IO过高和内存溢出 */
@Config
private int logMonitorCheckSec = 10;
@Config(resetable = true)
private int logMonitorLimit = 20000;
private static volatile boolean logEnabled = true;
private static volatile boolean logAlreadyExceeded = false;
/** 为了防止启动时候突然飙高而报,启动时候第一次不报,可以防止服务器启动时突然的堆积日志把服务器搞崩溃 */
private static volatile boolean logExceededFirstTime = true;
/** 线程池允许等待的线程数 */
@Config(resetable = true)
private int threadPoolQueueCountLimit = 30000;
@AfterBootstrap
protected void init() {
SystemMonitor.initGarbageCollectMonitor(gcMonitorSec);
SystemMonitor.initLoadAverageMonitor(loadMonitorSec);
SystemMonitor.initThreadCpuTimeMonitor(threadCpuTimeMonitorSec);
SystemMonitor.initThreadPoolMonitor(threadMonitorSec, threadMonitorQueueThreshold);
initDenialOfServiceMonitor();
initLogMonitor();
}
public void initDenialOfServiceMonitor() {
if (dosMonitorCheckSec > 0) {
log.info("DenialOfServiceMonitor ON, interval:{}sec, Worker EventLoop Size:{}", dosMonitorCheckSec, config.getWorkerEventLoopGroup().executorCount());
ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() {
/**
* check denialOfServiceAlmost
*/
private boolean check2(NioEventLoopGroup workerEventLoop) {
int _threadPoolQueueCountLimit = threadPoolQueueCountLimit - 500;// 几乎要拒绝服务的等待队列阀值
//TODO:如何实现DOS防范
/*
int activeCount = executor.getActiveCount();
int queueCount = executor.getQueue().size(); // 等待队列的大小
int largestPoolSize = executor.getLargestPoolSize();
int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) {
ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS
activeCount = executor.getActiveCount();
int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > _threadPoolQueueCountLimit) {
denialOfServiceAlmost = true;
return true;
}
}
*/
return false;
}
/**
* check denialOfService
*/
private boolean check(NioEventLoopGroup workerEventLoop) {
/*
int activeCount = executor.getActiveCount();
int queueCount = executor.getQueue().size(); // 等待队列的大小
int largestPoolSize = executor.getLargestPoolSize();
int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) {
String pipelineInfo = SystemInfo.getThreadsDetailInfo("PIPELINE", true, 20); // 先打印好
ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS
activeCount = executor.getActiveCount();
int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS
if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > threadPoolQueueCountLimit) { // 打印好了,线程池仍然大量占用,就发出报警邮件
if (!lastTestDenialOfService) {
MDC.put("mailTitle", "DenialOfService");
log.error("DENIAL OF SERVICE, ACTIVE_SIZE:{}, WAITTING_QUEUE_SIZE:{}, RUNNING PIPELINE:\n{}\n\n", activeCount, currQueueCount, pipelineInfo);
}
denialOfService = true;
lastTestDenialOfService = true;
denialOfServiceAlmost = true;
return true;
}
}
*/
return false;
}
@Override
public void run() {
boolean r = check(config.getWorkerEventLoopGroup());
boolean r1 = check(config.getWorkerEventLoopGroup());
if (!r && !r1) {
denialOfService = false;
lastTestDenialOfService = false;
}
boolean r2 = check2(config.getWorkerEventLoopGroup());
boolean r21 = check2(config.getWorkerEventLoopGroup());
if (!r2 && !r21) {
denialOfServiceAlmost = false;
}
}
}, dosMonitorCheckSec * 5, dosMonitorCheckSec, TimeUnit.SECONDS);// httpServer刚启动时,很有可能很多请求冲进来,先不拒绝服务,所以暂定5s后再开始定时
}
}
public void initLogMonitor() {
if (logMonitorCheckSec > 0) {
final ThreadPoolExecutor logExecutor = (ThreadPoolExecutor) ConcurrentUtil.getLogExecutor();
log.info("LogMonitor ON, interval:{}sec, logExecutorSize:{}", logMonitorCheckSec, logExecutor.getQueue().size());
ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
boolean r = isLogExceeded(logExecutor);
if (!r) {
logEnabled = true;
logAlreadyExceeded = false;
}
}
/**
* 检查日志线程池队列任务数
*
* @return 如果超过限值返回true,没超过返回false
*/
private boolean isLogExceeded(ThreadPoolExecutor executor) {
int queueCount = executor.getQueue().size(); // 如果队列的log超过限制,就临时把日志功能关闭
if (queueCount > logMonitorLimit) {
if (!logAlreadyExceeded) { // 保证超过限定值之后只报出一次,如果回退到限定值内,再超过才再报
if (logExceededFirstTime) {
logExceededFirstTime = false;
} else {
MDC.put("mailTitle", "TOO MANY LOGS");
log.error("TOO MANY LOGS,WAITTING_QUEUE_SIZE:{}\n", queueCount);
}
}
logEnabled = false;
logAlreadyExceeded = true;
return true;
}
return false;
}
}, logMonitorCheckSec, logMonitorCheckSec, TimeUnit.SECONDS);
}
}
/**
* 是否达到拒绝服务的阀值
*/
public static boolean isDenialOfService() {
return denialOfService;
}
/**
* 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500
*/
public static boolean isDenialOfServiceAlmost() {
return denialOfServiceAlmost;
}
/**
* 如果日志功能打开了,才记录日志
*/
public static boolean isLogEnabled() {
return logEnabled;
}
public double getLoadMonitorErrorThreshold() {
return loadMonitorErrorThreshold;
}
public double getLoadMonitorWarnThreshold() {
return loadMonitorWarnThreshold;
}
}
| 0 |
22606_1 | package IO;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class IOTest06 {
/*
* 文件字符流 输出流 Writer
*/
public static void main(String[] args) {
//1、创建源
File file = new File("b.txt");
//2、选择流
Writer writer = null;
//3、操作 Writer 字符输出流
try {
writer = new FileWriter(file);
String msg = "hello stxt 加油,冲刺!";
char[] data = msg.toCharArray(); //字符串--》字符数组
writer.write(data, 0, data.length);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != writer) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//4、关闭流
}
}
| 3546514206/base | Java/_java_examples/src/main/java/IO/IOTest06.java | 274 | //1、创建源 | line_comment | zh-cn | package IO;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class IOTest06 {
/*
* 文件字符流 输出流 Writer
*/
public static void main(String[] args) {
//1、 <SUF>
File file = new File("b.txt");
//2、选择流
Writer writer = null;
//3、操作 Writer 字符输出流
try {
writer = new FileWriter(file);
String msg = "hello stxt 加油,冲刺!";
char[] data = msg.toCharArray(); //字符串--》字符数组
writer.write(data, 0, data.length);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != writer) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//4、关闭流
}
}
| 0 |
22563_30 | import cn.snailpad.easyjson.EasyJSONArray;
import cn.snailpad.easyjson.EasyJSONBase;
import cn.snailpad.easyjson.EasyJSONObject;
import cn.snailpad.easyjson.FieldName;
import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_ARRAY;
import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_OBJECT;
public class Lab {
/////////////////////////////////////////////////////
// Java Bean类
// 用于展示EasyJSONBase.jsonEncode()和EasyJSONBase.jsonDecode()方法的使用
/////////////////////////////////////////////////////
public static class Data {
// 访问属性必须指定为public
public int id;
public String name;
// 如果使用EasyJSONBase.jsonDecode()方法,必须要有默认构造函数,或不能定义任何构造函数
public Data() {
}
public Data(int id, String name) {
this.id = id;
this.name = name;
}
}
/////////////////////////////////////////////////////
// Java Bean类
// 用于展示重命名字段的使用
/////////////////////////////////////////////////////
public static class Data2 {
// 访问属性必须指定为public
public int id;
// jsonEncode时,将字段name重命名为MyName
@FieldName("MyName")
public String name;
public Data2(int id, String name) {
this.id = id;
this.name = name;
}
}
public static void main(String[] args) throws Exception {
/////////////////////////////////////////////////////
// 生成JSON字符串(对象)示例
/////////////////////////////////////////////////////
EasyJSONObject object1 = EasyJSONObject.generate("name", "Hello", "female", false);
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false}
// 添加字段age
object1.put("age", 18);
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false,"age":18}
// 修改字段age(如果字段age不存在,则添加;如果已经存在,则修改)
object1.put("age", 19);
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false,"age":19}
// 添加数组
object1.put("language", EasyJSONArray.generate("Chinese", "English", "French"));
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]}
// 上述JSON字符串也可以用一条语句直接生成
EasyJSONObject object2 = EasyJSONObject.generate(
"name", "Hello",
"female", false,
"age", 19,
"language", EasyJSONArray.generate("Chinese", "English", "French"));
System.out.println(object2.toString());
// 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]}
/////////////////////////////////////////////////////
// 生成JSON字符串(数组)
/////////////////////////////////////////////////////
EasyJSONArray array1 = EasyJSONArray.generate("Hello", 2, true, EasyJSONObject.generate("age", 18));
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18}]
// 共有4个元素,其中第1个为字符串,第2个为数字,第3个为布尔值,第4个为对象
// 在尾部添加一个元素
array1.put("World");
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18},"World"]
// 在尾部添加一个数组
array1.put(EasyJSONArray.generate("new", "old"));
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18},"World",["new","old"]]
// 在尾部添加一个对象
array1.put(EasyJSONObject.generate("female", false));
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}]
/////////////////////////////////////////////////////
// 从JSON字符串解析回EasyJSONObject或EasyJSONArray
// 解析JSON对象字符串 {"name":"Hello","female":false,"age":18}
/////////////////////////////////////////////////////
String jsonStr1 = "{\"name\":\"Hello\",\"female\":false,\"age\":18}";
EasyJSONObject object3 = (EasyJSONObject) EasyJSONObject.parse(jsonStr1);
String name = object3.getString("name"); // 值为 "Hello"
int age = object3.getInt("age"); // 值为 18
/////////////////////////////////////////////////////
// 从JSON字符串解析回EasyJSONObject或EasyJSONArray
// 解析JSON数组字符串 ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}]
/////////////////////////////////////////////////////
String jsonStr2 = "[\"Hello\",2,true,{\"age\":18},\"World\",[\"new\",\"old\"],{\"female\":false}]";
EasyJSONArray array2 = (EasyJSONArray) EasyJSONArray.parse(jsonStr2);
String str = array2.getString(0);
System.out.println(str); // 输出: Hello
int val = array2.getInt(1);
System.out.println(val); // 输出: 2
boolean bool = array2.getBoolean(2);
System.out.println(bool); // 输出: true
EasyJSONObject object4 = array2.getObject(3);
System.out.println(object4); // 输出: {"age":18}
EasyJSONArray array3 = array2.getArray(5);
System.out.println(array3); // 输出: ["new","old"]
/////////////////////////////////////////////////////
// 编码Java Bean
/////////////////////////////////////////////////////
Data data1 = new Data(3, "Hello");
String data1JSON = EasyJSONBase.jsonEncode(data1);
System.out.println(data1JSON); // 输出: {"id":3,"name":"Hello"}
/////////////////////////////////////////////////////
// 重命名字段
/////////////////////////////////////////////////////
Data2 data2 = new Data2(4, "World");
String data2JSON = EasyJSONBase.jsonEncode(data2);
System.out.println(data2JSON); // 输出: {"id":4,"MyName":"World"}
String newDataJSON = "{\"id\":3,\"name\":\"Hello\"}";
Data newData = (Data) EasyJSONBase.jsonDecode(Data.class, newDataJSON);
System.out.println(newData.id); // 输出: 3
System.out.println(newData.name); // 输出: Hello
/////////////////////////////////////////////////////
// 检测JSON字符串类型: 是否为对象或数组
/////////////////////////////////////////////////////
String jsonString1 = "{\"id\":3,\"name\":\"Hello\"}";
System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_OBJECT); // 输出: true
System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_ARRAY); // 输出: false
String jsonString2 = "[1,2,3]";
System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_OBJECT); // 输出: false
System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_ARRAY); // 输出: true
}
}
| 373518155/EasyJSON | demo/Lab.java | 1,742 | // 值为 18
| line_comment | zh-cn | import cn.snailpad.easyjson.EasyJSONArray;
import cn.snailpad.easyjson.EasyJSONBase;
import cn.snailpad.easyjson.EasyJSONObject;
import cn.snailpad.easyjson.FieldName;
import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_ARRAY;
import static cn.snailpad.easyjson.EasyJSONBase.JSON_TYPE_OBJECT;
public class Lab {
/////////////////////////////////////////////////////
// Java Bean类
// 用于展示EasyJSONBase.jsonEncode()和EasyJSONBase.jsonDecode()方法的使用
/////////////////////////////////////////////////////
public static class Data {
// 访问属性必须指定为public
public int id;
public String name;
// 如果使用EasyJSONBase.jsonDecode()方法,必须要有默认构造函数,或不能定义任何构造函数
public Data() {
}
public Data(int id, String name) {
this.id = id;
this.name = name;
}
}
/////////////////////////////////////////////////////
// Java Bean类
// 用于展示重命名字段的使用
/////////////////////////////////////////////////////
public static class Data2 {
// 访问属性必须指定为public
public int id;
// jsonEncode时,将字段name重命名为MyName
@FieldName("MyName")
public String name;
public Data2(int id, String name) {
this.id = id;
this.name = name;
}
}
public static void main(String[] args) throws Exception {
/////////////////////////////////////////////////////
// 生成JSON字符串(对象)示例
/////////////////////////////////////////////////////
EasyJSONObject object1 = EasyJSONObject.generate("name", "Hello", "female", false);
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false}
// 添加字段age
object1.put("age", 18);
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false,"age":18}
// 修改字段age(如果字段age不存在,则添加;如果已经存在,则修改)
object1.put("age", 19);
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false,"age":19}
// 添加数组
object1.put("language", EasyJSONArray.generate("Chinese", "English", "French"));
System.out.println(object1.toString());
// 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]}
// 上述JSON字符串也可以用一条语句直接生成
EasyJSONObject object2 = EasyJSONObject.generate(
"name", "Hello",
"female", false,
"age", 19,
"language", EasyJSONArray.generate("Chinese", "English", "French"));
System.out.println(object2.toString());
// 输出: {"name":"Hello","female":false,"age":19,"language":["Chinese","English","French"]}
/////////////////////////////////////////////////////
// 生成JSON字符串(数组)
/////////////////////////////////////////////////////
EasyJSONArray array1 = EasyJSONArray.generate("Hello", 2, true, EasyJSONObject.generate("age", 18));
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18}]
// 共有4个元素,其中第1个为字符串,第2个为数字,第3个为布尔值,第4个为对象
// 在尾部添加一个元素
array1.put("World");
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18},"World"]
// 在尾部添加一个数组
array1.put(EasyJSONArray.generate("new", "old"));
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18},"World",["new","old"]]
// 在尾部添加一个对象
array1.put(EasyJSONObject.generate("female", false));
System.out.println(array1.toString());
// 输出: ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}]
/////////////////////////////////////////////////////
// 从JSON字符串解析回EasyJSONObject或EasyJSONArray
// 解析JSON对象字符串 {"name":"Hello","female":false,"age":18}
/////////////////////////////////////////////////////
String jsonStr1 = "{\"name\":\"Hello\",\"female\":false,\"age\":18}";
EasyJSONObject object3 = (EasyJSONObject) EasyJSONObject.parse(jsonStr1);
String name = object3.getString("name"); // 值为 "Hello"
int age = object3.getInt("age"); // 值为 <SUF>
/////////////////////////////////////////////////////
// 从JSON字符串解析回EasyJSONObject或EasyJSONArray
// 解析JSON数组字符串 ["Hello",2,true,{"age":18},"World",["new","old"],{"female":false}]
/////////////////////////////////////////////////////
String jsonStr2 = "[\"Hello\",2,true,{\"age\":18},\"World\",[\"new\",\"old\"],{\"female\":false}]";
EasyJSONArray array2 = (EasyJSONArray) EasyJSONArray.parse(jsonStr2);
String str = array2.getString(0);
System.out.println(str); // 输出: Hello
int val = array2.getInt(1);
System.out.println(val); // 输出: 2
boolean bool = array2.getBoolean(2);
System.out.println(bool); // 输出: true
EasyJSONObject object4 = array2.getObject(3);
System.out.println(object4); // 输出: {"age":18}
EasyJSONArray array3 = array2.getArray(5);
System.out.println(array3); // 输出: ["new","old"]
/////////////////////////////////////////////////////
// 编码Java Bean
/////////////////////////////////////////////////////
Data data1 = new Data(3, "Hello");
String data1JSON = EasyJSONBase.jsonEncode(data1);
System.out.println(data1JSON); // 输出: {"id":3,"name":"Hello"}
/////////////////////////////////////////////////////
// 重命名字段
/////////////////////////////////////////////////////
Data2 data2 = new Data2(4, "World");
String data2JSON = EasyJSONBase.jsonEncode(data2);
System.out.println(data2JSON); // 输出: {"id":4,"MyName":"World"}
String newDataJSON = "{\"id\":3,\"name\":\"Hello\"}";
Data newData = (Data) EasyJSONBase.jsonDecode(Data.class, newDataJSON);
System.out.println(newData.id); // 输出: 3
System.out.println(newData.name); // 输出: Hello
/////////////////////////////////////////////////////
// 检测JSON字符串类型: 是否为对象或数组
/////////////////////////////////////////////////////
String jsonString1 = "{\"id\":3,\"name\":\"Hello\"}";
System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_OBJECT); // 输出: true
System.out.println(EasyJSONBase.guessJSONType(jsonString1) == JSON_TYPE_ARRAY); // 输出: false
String jsonString2 = "[1,2,3]";
System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_OBJECT); // 输出: false
System.out.println(EasyJSONBase.guessJSONType(jsonString2) == JSON_TYPE_ARRAY); // 输出: true
}
}
| 0 |
46283_7 | package world.xuewei.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import world.xuewei.entity.Meeting;
import world.xuewei.entity.Report;
import world.xuewei.entity.Teacher;
/**
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MeetingVo {
/**
* 报告
*/
private Report report;
/**
* 报告人
*/
private Teacher reporter;
/**
* 主持人
*/
private Teacher host;
/**
* 会议
*/
private Meeting meeting;
/**
* 预约数
*/
private int appointmentCount;
/**
* 签到数
*/
private int arriveCount;
/**
* 预约百分比 = 预约人数/会议容量 * 100%
*/
private int appointmentPercent;
/**
* 状态【1:已预约】【0:未预约】【2:预约已满】
*/
private int status;
} | 373675032/academic-report | src/main/java/world/xuewei/vo/MeetingVo.java | 479 | /**
* 预约百分比 = 预约人数/会议容量 * 100%
*/ | block_comment | zh-cn | package world.xuewei.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import world.xuewei.entity.Meeting;
import world.xuewei.entity.Report;
import world.xuewei.entity.Teacher;
/**
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MeetingVo {
/**
* 报告
*/
private Report report;
/**
* 报告人
*/
private Teacher reporter;
/**
* 主持人
*/
private Teacher host;
/**
* 会议
*/
private Meeting meeting;
/**
* 预约数
*/
private int appointmentCount;
/**
* 签到数
*/
private int arriveCount;
/**
* 预约百 <SUF>*/
private int appointmentPercent;
/**
* 状态【1:已预约】【0:未预约】【2:预约已满】
*/
private int status;
} | 0 |
37848_0 | package com.charity.utils;
/**
* 消息数据处理
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
public class MessageUtils {
/**
* 文章/项目评论的内容处理
* name 被评论的文章的名字 userName评论者的用户名 content消息内容 type文章/项目
*/
public static String CommentHandle(String name, String userName, String content, Integer type) {
String typeName = "";
if (type == 1) {
typeName = "项目";
} else {
typeName = "文章";
}
String content1 = "<b>" + userName + "</b> 评论了您的" + typeName + " <b><<" + name + ">></b> 内容如下: <b>" + content + "</b>";
return content1;
}
/**
* 文章/项目平路回复的消息处理
*/
public static String relplyCommentHandle(String articleName, String userName, String content, Integer type) {
String typeName = "";
if (type == 1) {
typeName = "项目";
} else {
typeName = "文章";
}
String content1 = "<b>" + userName + "</b> 回复了您关于" + typeName + " <b><<" + articleName + ">></b>的评论,内容如下: <b>" + content + "</b>";
return content1;
}
/**
* 文章审核消息处理
* articleName 文章名字 flag为1表示通过审核,为2表示不通过审核 info处理信息
*/
public static String articleCheckHandle(String articleName, Integer flag, String info) {
String content = "";
if (flag == 1) {
content = "<b>恭喜您,您的文章</b><b><<" + articleName + ">>已通过审核!</b>";
} else {
content = "<b>很遗憾,您的文章</b><b><<" + articleName + ">>未通过审核!原因为:</b><b>" + info + "</b>";
}
return content;
}
/**
* 认证审核消息处理
* flag为1表示通c过审核,为2表示不通过审核 info处理信息
*/
public static String certificationCheckHandle(Integer flag, String info) {
String content = "";
if (flag == 1) {
content = "<b>恭喜您,您已成功通过认证!</b>";
} else {
content = "<b>很遗憾,您未能通过认证!原因为:</b><b>" + info + "</b>";
}
return content;
}
}
| 373675032/love-charity | src/main/java/com/charity/utils/MessageUtils.java | 808 | /**
* 消息数据处理
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/ | block_comment | zh-cn | package com.charity.utils;
/**
* 消息数 <SUF>*/
public class MessageUtils {
/**
* 文章/项目评论的内容处理
* name 被评论的文章的名字 userName评论者的用户名 content消息内容 type文章/项目
*/
public static String CommentHandle(String name, String userName, String content, Integer type) {
String typeName = "";
if (type == 1) {
typeName = "项目";
} else {
typeName = "文章";
}
String content1 = "<b>" + userName + "</b> 评论了您的" + typeName + " <b><<" + name + ">></b> 内容如下: <b>" + content + "</b>";
return content1;
}
/**
* 文章/项目平路回复的消息处理
*/
public static String relplyCommentHandle(String articleName, String userName, String content, Integer type) {
String typeName = "";
if (type == 1) {
typeName = "项目";
} else {
typeName = "文章";
}
String content1 = "<b>" + userName + "</b> 回复了您关于" + typeName + " <b><<" + articleName + ">></b>的评论,内容如下: <b>" + content + "</b>";
return content1;
}
/**
* 文章审核消息处理
* articleName 文章名字 flag为1表示通过审核,为2表示不通过审核 info处理信息
*/
public static String articleCheckHandle(String articleName, Integer flag, String info) {
String content = "";
if (flag == 1) {
content = "<b>恭喜您,您的文章</b><b><<" + articleName + ">>已通过审核!</b>";
} else {
content = "<b>很遗憾,您的文章</b><b><<" + articleName + ">>未通过审核!原因为:</b><b>" + info + "</b>";
}
return content;
}
/**
* 认证审核消息处理
* flag为1表示通c过审核,为2表示不通过审核 info处理信息
*/
public static String certificationCheckHandle(Integer flag, String info) {
String content = "";
if (flag == 1) {
content = "<b>恭喜您,您已成功通过认证!</b>";
} else {
content = "<b>很遗憾,您未能通过认证!原因为:</b><b>" + info + "</b>";
}
return content;
}
}
| 1 |
39880_16 | package com.moti.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* (Admin)实体类
*
* @author 莫提
* @since 2020-08-30 22:34:34
*/
public class Admin implements Serializable {
private static final long serialVersionUID = -10283078166005266L;
/**
* 主键ID
*/
private Integer id;
/**
* 绑定QQ登录的ID
*/
private String openId;
/**
* 头像地址
*/
private String img;
/**
* 作者昵称
*/
private String name;
/**
* 登录密码
*/
private String password;
/**
* 加密盐
*/
private String salt;
/**
* 性别:男、女、保密
*/
private String sex;
/**
* 出生年月日
*/
private Date birthday;
/**
* 地区
*/
private String address;
/**
* 邮箱
*/
private String email;
/**
* 手机号码
*/
private String phone;
/**
* QQ号码
*/
private String qq;
/**
* 微信号图片地址
*/
private String wechat;
/**
* 微信公众号图片地址
*/
private String publicWechat;
/**
* 职业
*/
private String career;
/**
* 个人说明
*/
private String info;
/**
* 最近登录
*/
private Date recentLogin;
public Admin() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getWechat() {
return wechat;
}
public void setWechat(String wechat) {
this.wechat = wechat;
}
public String getPublicWechat() {
return publicWechat;
}
public void setPublicWechat(String publicWechat) {
this.publicWechat = publicWechat;
}
public String getCareer() {
return career;
}
public void setCareer(String career) {
this.career = career;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Date getRecentLogin() {
return recentLogin;
}
public void setRecentLogin(Date recentLogin) {
this.recentLogin = recentLogin;
}
@Override
public String toString() {
return "Admin{" +
"id=" + id +
", openId='" + openId + '\'' +
", img='" + img + '\'' +
", name='" + name + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", address='" + address + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", qq='" + qq + '\'' +
", wechat='" + wechat + '\'' +
", publicWechat='" + publicWechat + '\'' +
", career='" + career + '\'' +
", info='" + info + '\'' +
", recentLogin=" + recentLogin +
'}';
}
} | 373675032/moti-blog | src/main/java/com/moti/entity/Admin.java | 1,148 | /**
* 个人说明
*/ | block_comment | zh-cn | package com.moti.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* (Admin)实体类
*
* @author 莫提
* @since 2020-08-30 22:34:34
*/
public class Admin implements Serializable {
private static final long serialVersionUID = -10283078166005266L;
/**
* 主键ID
*/
private Integer id;
/**
* 绑定QQ登录的ID
*/
private String openId;
/**
* 头像地址
*/
private String img;
/**
* 作者昵称
*/
private String name;
/**
* 登录密码
*/
private String password;
/**
* 加密盐
*/
private String salt;
/**
* 性别:男、女、保密
*/
private String sex;
/**
* 出生年月日
*/
private Date birthday;
/**
* 地区
*/
private String address;
/**
* 邮箱
*/
private String email;
/**
* 手机号码
*/
private String phone;
/**
* QQ号码
*/
private String qq;
/**
* 微信号图片地址
*/
private String wechat;
/**
* 微信公众号图片地址
*/
private String publicWechat;
/**
* 职业
*/
private String career;
/**
* 个人说 <SUF>*/
private String info;
/**
* 最近登录
*/
private Date recentLogin;
public Admin() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getWechat() {
return wechat;
}
public void setWechat(String wechat) {
this.wechat = wechat;
}
public String getPublicWechat() {
return publicWechat;
}
public void setPublicWechat(String publicWechat) {
this.publicWechat = publicWechat;
}
public String getCareer() {
return career;
}
public void setCareer(String career) {
this.career = career;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Date getRecentLogin() {
return recentLogin;
}
public void setRecentLogin(Date recentLogin) {
this.recentLogin = recentLogin;
}
@Override
public String toString() {
return "Admin{" +
"id=" + id +
", openId='" + openId + '\'' +
", img='" + img + '\'' +
", name='" + name + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", address='" + address + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", qq='" + qq + '\'' +
", wechat='" + wechat + '\'' +
", publicWechat='" + publicWechat + '\'' +
", career='" + career + '\'' +
", info='" + info + '\'' +
", recentLogin=" + recentLogin +
'}';
}
} | 0 |
56597_0 | package com.moti.utils;
import org.slf4j.Logger;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
public class MailUtils {
//邮件发送器
private JavaMailSenderImpl mailSender;
Logger logger = LogUtils.getInstance(MailUtils.class);
public MailUtils(JavaMailSenderImpl mailSender){
this.mailSender = mailSender;
}
/**
* 发送简单邮件
* @param title 邮件标题
* @param text 邮件内容(简单邮件不支持HTML标签)
* @param acceptEmail 接收方邮件
*/
public void sendSimpleMailMessage(String title,String text,String acceptEmail){
logger.info("开始发送简单邮件...");
logger.info("mailSender对象为:"+mailSender);
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject(title);
message.setText(text);
message.setFrom("你需要修改此处为你的QQ邮箱");
message.setTo(acceptEmail);
System.out.println(mailSender);
logger.info("message对象为:"+message);
mailSender.send(message);
}
/**
* 发送复杂邮件(支持邮件内容HTML解析)
* @param title 邮件标题
* @param text 邮件内容(简单邮件不支持HTML标签)
* @param acceptEmail 接收方邮件
* @throws MessagingException
*/
public void sentComplexMailMessage(String title,String text,String acceptEmail){
logger.info("开始发送复杂邮件...");
logger.info("mailSender对象为:"+mailSender);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setSubject(title);
helper.setText(text,true);
helper.setFrom("你需要修改此处为你的QQ邮箱");
helper.setTo(acceptEmail);
} catch (MessagingException e) {
e.printStackTrace();
}
logger.info("mimeMessage对象为:"+mimeMessage);
mailSender.send(mimeMessage);
}
public String sendCode(String email,String userName,String password){
int code = (int) ((Math.random() * 9 + 1) * 100000);
logger.info("开始发送复杂邮件...");
logger.info("mailSender对象为:"+mailSender);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setSubject("莫提网盘-邮箱验证");
helper.setText("<h2 >莫提网盘-简洁、优雅、免费</h2>" +
"<h3>用户注册-邮箱验证<h3/>" +
"您现在正在注册莫提网盘账号<br>" +
"验证码: <span style='color : red'>"+code+"</span><br>" +
"用户名 :"+userName+
"<br>密码 :"+password+
"<hr>"+
"<h5 style='color : red'>如果并非本人操作,请忽略本邮件</h5>",true);
helper.setFrom("你需要修改此处为你的QQ邮箱");
helper.setTo(email);
} catch (MessagingException e) {
e.printStackTrace();
}
logger.info("mimeMessage对象为:"+mimeMessage);
mailSender.send(mimeMessage);
return String.valueOf(code);
}
}
| 373675032/moti-cloud | src/main/java/com/moti/utils/MailUtils.java | 834 | //邮件发送器 | line_comment | zh-cn | package com.moti.utils;
import org.slf4j.Logger;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
public class MailUtils {
//邮件 <SUF>
private JavaMailSenderImpl mailSender;
Logger logger = LogUtils.getInstance(MailUtils.class);
public MailUtils(JavaMailSenderImpl mailSender){
this.mailSender = mailSender;
}
/**
* 发送简单邮件
* @param title 邮件标题
* @param text 邮件内容(简单邮件不支持HTML标签)
* @param acceptEmail 接收方邮件
*/
public void sendSimpleMailMessage(String title,String text,String acceptEmail){
logger.info("开始发送简单邮件...");
logger.info("mailSender对象为:"+mailSender);
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject(title);
message.setText(text);
message.setFrom("你需要修改此处为你的QQ邮箱");
message.setTo(acceptEmail);
System.out.println(mailSender);
logger.info("message对象为:"+message);
mailSender.send(message);
}
/**
* 发送复杂邮件(支持邮件内容HTML解析)
* @param title 邮件标题
* @param text 邮件内容(简单邮件不支持HTML标签)
* @param acceptEmail 接收方邮件
* @throws MessagingException
*/
public void sentComplexMailMessage(String title,String text,String acceptEmail){
logger.info("开始发送复杂邮件...");
logger.info("mailSender对象为:"+mailSender);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setSubject(title);
helper.setText(text,true);
helper.setFrom("你需要修改此处为你的QQ邮箱");
helper.setTo(acceptEmail);
} catch (MessagingException e) {
e.printStackTrace();
}
logger.info("mimeMessage对象为:"+mimeMessage);
mailSender.send(mimeMessage);
}
public String sendCode(String email,String userName,String password){
int code = (int) ((Math.random() * 9 + 1) * 100000);
logger.info("开始发送复杂邮件...");
logger.info("mailSender对象为:"+mailSender);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
try {
helper.setSubject("莫提网盘-邮箱验证");
helper.setText("<h2 >莫提网盘-简洁、优雅、免费</h2>" +
"<h3>用户注册-邮箱验证<h3/>" +
"您现在正在注册莫提网盘账号<br>" +
"验证码: <span style='color : red'>"+code+"</span><br>" +
"用户名 :"+userName+
"<br>密码 :"+password+
"<hr>"+
"<h5 style='color : red'>如果并非本人操作,请忽略本邮件</h5>",true);
helper.setFrom("你需要修改此处为你的QQ邮箱");
helper.setTo(email);
} catch (MessagingException e) {
e.printStackTrace();
}
logger.info("mimeMessage对象为:"+mimeMessage);
mailSender.send(mimeMessage);
return String.valueOf(code);
}
}
| 0 |
55104_7 | package world.xuewei.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* 疾病实体
*
* @author XUEW
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("illness")
public class Illness {
/**
* 主键ID
*/
@TableId(type = IdType.AUTO)
private Integer id;
/**
* 疾病所属种类id
*/
private Integer kindId;
/**
* 疾病的名字
*/
private String illnessName;
/**
* 引起的原因
*/
private String includeReason;
/**
* 主要的症状
*/
private String illnessSymptom;
/**
* 特殊的症状
*/
private String specialSymptom;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
@TableField(exist = false)
private IllnessKind kind;
@TableField(exist = false)
private IllnessMedicine illnessMedicine;
}
| 373675032/smart-medicine | src/main/java/world/xuewei/entity/Illness.java | 327 | /**
* 创建时间
*/ | block_comment | zh-cn | package world.xuewei.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* 疾病实体
*
* @author XUEW
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("illness")
public class Illness {
/**
* 主键ID
*/
@TableId(type = IdType.AUTO)
private Integer id;
/**
* 疾病所属种类id
*/
private Integer kindId;
/**
* 疾病的名字
*/
private String illnessName;
/**
* 引起的原因
*/
private String includeReason;
/**
* 主要的症状
*/
private String illnessSymptom;
/**
* 特殊的症状
*/
private String specialSymptom;
/**
* 创建时 <SUF>*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
@TableField(exist = false)
private IllnessKind kind;
@TableField(exist = false)
private IllnessMedicine illnessMedicine;
}
| 0 |
66633_3 | package chapter08_05_Queue集合;
import java.util.*;
/**
* Description:
* 1.属于List接口实现类
* 2.实现Deque接口,可以被当成双端队列使用。因此也可以被当成栈来使用。
*
* 1.LinkedList、ArrayList、ArrayDeque实现机制完全不同
* ArrayList、ArrayDeque内部以数组形式保存集合元素,随机访问集合元素性能好
* LinkedList内部以链表保存集合元素,随机访问性能差,插入、删除元素性能出色,只改变指针所指向地址。
*
* 1.ArrayList.get()性能好
* 2.LinkedList,采用迭代器Iterator遍历性能好
*/
public class LinkedListTest
{
public static void main(String[] args)
{
LinkedList books = new LinkedList();
// 将字符串元素加入队列的尾部
books.offer("疯狂Java讲义");
// 将一个字符串元素加入栈的顶部
books.push("轻量级Java EE企业应用实战");
// 将字符串元素添加到队列的头部(相当于栈的顶部)
books.offerFirst("疯狂Android讲义");
// 以List的方式(按索引访问的方式)来遍历集合元素
for (int i = 0; i < books.size() ; i++ )
{
System.out.println("遍历中:" + books.get(i));
}
// 访问、并不删除栈顶的元素
System.out.println(books.peekFirst());
// 访问、并不删除队列的最后一个元素
System.out.println(books.peekLast());
// 将栈顶的元素弹出“栈”
System.out.println(books.pop());
// 下面输出将看到队列中第一个元素被删除
System.out.println(books);
// 访问、并删除队列的最后一个元素
System.out.println(books.pollLast());
// 下面输出:[轻量级Java EE企业应用实战]
System.out.println(books);
}
}
| 3792274/crazyJava3 | 第8章Java集合/chapter08_05_Queue集合/LinkedListTest.java | 501 | // 将字符串元素添加到队列的头部(相当于栈的顶部)
| line_comment | zh-cn | package chapter08_05_Queue集合;
import java.util.*;
/**
* Description:
* 1.属于List接口实现类
* 2.实现Deque接口,可以被当成双端队列使用。因此也可以被当成栈来使用。
*
* 1.LinkedList、ArrayList、ArrayDeque实现机制完全不同
* ArrayList、ArrayDeque内部以数组形式保存集合元素,随机访问集合元素性能好
* LinkedList内部以链表保存集合元素,随机访问性能差,插入、删除元素性能出色,只改变指针所指向地址。
*
* 1.ArrayList.get()性能好
* 2.LinkedList,采用迭代器Iterator遍历性能好
*/
public class LinkedListTest
{
public static void main(String[] args)
{
LinkedList books = new LinkedList();
// 将字符串元素加入队列的尾部
books.offer("疯狂Java讲义");
// 将一个字符串元素加入栈的顶部
books.push("轻量级Java EE企业应用实战");
// 将字 <SUF>
books.offerFirst("疯狂Android讲义");
// 以List的方式(按索引访问的方式)来遍历集合元素
for (int i = 0; i < books.size() ; i++ )
{
System.out.println("遍历中:" + books.get(i));
}
// 访问、并不删除栈顶的元素
System.out.println(books.peekFirst());
// 访问、并不删除队列的最后一个元素
System.out.println(books.peekLast());
// 将栈顶的元素弹出“栈”
System.out.println(books.pop());
// 下面输出将看到队列中第一个元素被删除
System.out.println(books);
// 访问、并删除队列的最后一个元素
System.out.println(books.pollLast());
// 下面输出:[轻量级Java EE企业应用实战]
System.out.println(books);
}
}
| 0 |
56061_10 | package com.borqs.se.home3d;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.borqs.se.engine.SEScene;
import com.borqs.se.engine.SECommand;
import com.borqs.se.engine.SELoadResThread;
import com.borqs.se.engine.SEObject;
import com.borqs.se.engine.SESceneManager;
import com.borqs.se.engine.SEVector.SEVector3f;
import com.borqs.se.home3d.ProviderUtils.ModelColumns;
import com.borqs.se.widget3d.House;
import com.borqs.se.widget3d.NormalObject;
import com.borqs.se.widget3d.ObjectInfo;
import com.support.StaticUtil;
public class ModelObjectsManager {
public HashMap<String, ModelInfo> mModels;
private boolean mInitFailed = false;
public ModelObjectsManager() {
init();
}
public boolean initFailed() {
return mInitFailed;
}
private void init() {
Context context = SESceneManager.getInstance().getContext();
ContentResolver resolver = context.getContentResolver();
Cursor modelCursor = resolver.query(ModelColumns.CONTENT_URI, null, null, null, null);
if (modelCursor == null) {
mInitFailed = true;
return;
}
while (modelCursor.moveToNext()) {
ModelInfo modelInfo = ModelInfo.CreateFromDB(modelCursor);
if (mModels == null) {
mModels = new HashMap<String, ModelInfo>();
}
// #########判断模型文件是否存在,假如不存在不加入列表中###########
boolean modelExist = true;
if (modelInfo.mAssetsPath.startsWith("assets/")) {
try {
InputStream is = context.getAssets()
.open(modelInfo.mAssetsPath.substring(7) + "/models_config.xml");
if (is == null) {
modelExist = false;
} else {
is.close();
}
} catch (IOException e) {
modelExist = false;
} catch (NullPointerException e) {
modelCursor.close();
mInitFailed = true;
return;
}
} else {
File modelFile = new File(modelInfo.mAssetsPath);
if (!modelFile.exists()) {
modelExist = false;
}
}
if (modelExist) {
mModels.put(modelInfo.mName, modelInfo);
}
}
modelCursor.close();
}
/**
* When the 3Dscene started, will load the preload models which for
* can be added into the scene quickly.
* @param finish the finish behavior after preloaded.
*/
public void loadPreLoadModel(final SEScene scene, final Runnable finish) {
Iterator<Entry<String, ModelInfo>> iter = mModels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ModelInfo> entry = iter.next();
final ModelInfo modelInfo = entry.getValue();
if (modelInfo.mType.equals("Shelf")) {
if (!modelInfo.hasInstance()) {
final SEObject baseModel = new SEObject(scene, modelInfo.mName, 0);
modelInfo.load3DMAXModel(scene, scene.getContentObject(), baseModel, false, new Runnable() {
public void run() {
baseModel.setVisible(false);
scene.getContentObject().addChild(baseModel, false);
register(baseModel);
// adjust the size of 3DMax model begin
resizeModel(scene, modelInfo);
// adjust the size of 3DMax model end
}
});
}
}
}
SELoadResThread.getInstance().process(new Runnable() {
public void run() {
new SECommand(scene) {
public void run() {
if (finish != null) {
finish.run();
}
}
}.execute();
}
});
}
/**
* When the 3Dscene started,After load all objects finished, will load the preload models which for
* can be added into the scene quickly.
* @param finish the finish behavior after afterloaded.
*/
public void loadAfterLoadModel(final SEScene scene, final Runnable finish) {
Iterator<Entry<String, ModelInfo>> iter = mModels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ModelInfo> entry = iter.next();
final ModelInfo modelInfo = entry.getValue();
if (modelInfo.mType.equals("Folder") || modelInfo.mType.equals("Recycle")) {
if (!modelInfo.hasInstance()) {
final SEObject baseModel = new SEObject(scene, modelInfo.mName, 0);
modelInfo.load3DMAXModel(scene, scene.getContentObject(), baseModel, false, new Runnable() {
public void run() {
baseModel.setVisible(false);
scene.getContentObject().addChild(baseModel, false);
register(baseModel);
// adjust the size of 3DMax model begin
resizeModel(scene, modelInfo);
// adjust the size of 3DMax model end
}
});
}
}
}
SELoadResThread.getInstance().process(new Runnable() {
public void run() {
new SECommand(scene) {
public void run() {
if (finish != null) {
finish.run();
}
}
}.execute();
}
});
}
public void clearModelStatus() {
Iterator<Entry<String, ModelInfo>> iter = mModels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ModelInfo> entry = iter.next();
ModelInfo modelInfo = entry.getValue();
modelInfo.getInstances().clear();
}
}
/**
* 克隆物体,并且对物体大小进行适配
*/
public boolean createQuickly(SEObject parent, SEObject modelObject) {
ModelInfo modelInfo = mModels.get(modelObject.mName);
if (modelInfo.hasInstance()) {
if (parent.hasBeenReleased()) {
Context context = SESceneManager.getInstance().getContext();
StaticUtil.reportError(context, "on clone, but parent of " + modelObject.mName + " is null");
}
// clone from base model
SEObject baseModel = modelInfo.getInstances().get(0);
baseModel.cloneObject_JNI(parent, modelObject.mIndex);
modelObject.setHasBeenAddedToEngine(true);
parent.addChild(modelObject, false);
register(modelObject);
adjustTheSizeOfObject(modelInfo, modelObject);
return true;
}
return false;
}
/**
* 调整添加入房间物体的大小,以及物体占用的格子数
* 注意在墙上的物体其Z坐标上的点最大不能超过0,否则可能会被嵌入墙面
*/
private void adjustTheSizeOfObject(ModelInfo modelInfo, SEObject modelObject) {
if (modelObject instanceof NormalObject) {
NormalObject normalObject = (NormalObject) modelObject;
if (modelInfo.mSlotType == ObjectInfo.SLOT_TYPE_DESKTOP) {
// 对应桌面的物体只调整中心点的位置,使得中心点的位置为物体的底部
} else if (modelInfo.mSlotType == ObjectInfo.SLOT_TYPE_WALL) {
House house;
if (modelObject.getParent().getParent() instanceof House) {
house = (House) modelObject.getParent().getParent();
} else {
house = HomeManager.getInstance().getHomeScene().getHouse();
}
ObjectInfo objectInfo = normalObject.getObjectInfo();
SEObject modelComponenet = normalObject.getModelComponenet();
float maxWidth = getWidthOfWidget(house, Float.MAX_VALUE);
float maxHight = getHeightOfWidget(house, Float.MAX_VALUE);
float scale;
SEVector3f translate;
float sizeX = 2 * Math.max(modelInfo.mMaxPoint.getX(), -modelInfo.mMinPoint.getX());
float sizeZ = 2 * Math.max(modelInfo.mMaxPoint.getZ(), -modelInfo.mMinPoint.getZ());
// 假如在配置文件中没有指定物体的占用的格子数,那么我们根据物体的最小点和最大点来计算物体应该占用几个格子
if (objectInfo.getSpanX() <= 0 || objectInfo.getSpanY() <= 0) {
if (sizeX > maxWidth || sizeZ > maxHight) {
scale = Math.min(maxWidth / sizeX, maxHight / sizeZ);
translate = new SEVector3f(0, -objectInfo.mMaxPoint.getY() * scale, 0);
objectInfo.setSpanX(house.mCellCountX);
objectInfo.setSpanX(house.mCellCountY);
} else {
int spanX = 0;
int spanY = 0;
while (sizeX <= getWidthOfWidget(house, spanX)) {
spanX++;
}
while (sizeZ <= getHeightOfWidget(house, spanY)) {
spanY++;
}
spanX--;
spanY--;
maxWidth = getWidthOfWidget(house, spanX);
maxHight = getHeightOfWidget(house, spanY);
scale = Math.min(maxWidth / sizeX, maxHight / sizeZ);
translate = new SEVector3f(0, -objectInfo.mMaxPoint.getY() * scale, 0);
objectInfo.setSpanX(spanX);
objectInfo.setSpanX(spanY);
}
// 假如在配置文件中指定了物体应该占用几个格子,那么我们根据格子的大小对物体进行缩放
} else {
int oldSpanX = objectInfo.getSpanX();
if (oldSpanX > house.mCellCountX) {
objectInfo.setSpanX(house.mCellCountX);
objectInfo
.setSpanY(objectInfo.getSpanY() - oldSpanX + house.mCellCountX);
}
int oldSpanY = objectInfo.getSpanY();
if (oldSpanY > house.mCellCountY) {
objectInfo.setSpanY(house.mCellCountY);
objectInfo.setSpanX(objectInfo.getSpanX() - oldSpanY + house.mCellCountY);
}
maxWidth = getWidthOfWidget(house, objectInfo.getSpanX());
maxHight = getHeightOfWidget(house, objectInfo.getSpanY());
scale = Math.min(maxWidth / sizeX, maxHight / sizeZ);
translate = new SEVector3f(0, -objectInfo.mMaxPoint.getY() * scale, 0);
}
objectInfo.mMinPoint = modelInfo.mMinPoint.mul(scale);
objectInfo.mMaxPoint = modelInfo.mMaxPoint.mul(scale);
objectInfo.mMinPoint.selfAdd(translate);
objectInfo.mMaxPoint.selfAdd(translate);
modelComponenet.setUserTranslate(translate);
modelComponenet.setUserScale(new SEVector3f(scale, scale, scale));
}
}
}
private float getWidthOfWidget(House house, float spanX) {
float gridSizeX = house.mCellWidth + house.mWidthGap;
if (spanX > house.mCellCountX) {
return house.mCellCountX * gridSizeX - house.mWidthGap;
} else {
return spanX * gridSizeX - house.mWidthGap;
}
}
private float getHeightOfWidget(House house, float spanY) {
float gridSizeY = house.mCellHeight + house.mHeightGap;
if (spanY > house.mCellCountY) {
return house.mCellCountY * gridSizeY - house.mHeightGap;
} else {
return spanY * gridSizeY - house.mHeightGap;
}
}
/**
* If modelObject's mIndex does not equals 0, we will save a base object
* which index is 0. All objects are cloned from the base object
*/
public void create(final SEObject parent, final SEObject modelObject, final Runnable finish) {
final ModelInfo modelInfo = mModels.get(modelObject.mName);
if (modelObject.mIndex == 0) {
throw new IllegalArgumentException(
"If the object is created from 3DMax model, its index should not equals 0");
}
if (modelInfo.hasInstance()) {
//假如模型在场景中已经有实例了,直接克隆出一个
createQuickly(parent, modelObject);
if (finish != null) {
finish.run();
}
} else if (modelInfo.isOnLoading()) {
//假如模型正在加载,那么等加载完了后克隆出一个
SELoadResThread.getInstance().process(new Runnable() {
public void run() {
new SECommand(parent.getScene()) {
public void run() {
createQuickly(parent, modelObject);
if (finish != null) {
finish.run();
}
}
}.execute();
}
});
} else {
//假如模型还没有加载,那么开始加载,等加载完了后克隆出一个
final SEObject baseModel = new SEObject(parent.getScene(), modelInfo.mName, 0);
createBaseObject(parent.getScene().getContentObject(), baseModel, new Runnable() {
public void run() {
baseModel.setVisible(false);
createQuickly(parent, modelObject);
if (finish != null) {
finish.run();
}
}
});
}
}
/**
* 模型文件结构如桌子(相机和电话是在桌子加载完成后加入桌子的节点):
* 桌子
* _____|_____
* ___|___ |
* | | 桌子_model
* 相机 ... 电话 ___|___
* | |
* 桌子腿...桌面
*
* 根据配置文件中localTrans来调整模型的大小,如桌子:
* 我们只需要调整“桌子_model”物体的大小而不用调整相机和电话的大小
*/
private void resizeModel(SEScene scene, ModelInfo modelInfo) {
SEObject modelOf3DMax = new SEObject(scene, modelInfo.mName + "_model");
if (modelInfo.mCompensationTrans != null) {
modelOf3DMax.setHasBeenAddedToEngine(true);
modelOf3DMax.setLocalTranslate(modelInfo.mCompensationTrans.mTranslate);
modelOf3DMax.setLocalRotate(modelInfo.mCompensationTrans.mRotate);
modelOf3DMax.setLocalScale(modelInfo.mCompensationTrans.mScale);
}
}
public ModelInfo findModelInfo(String name) {
return mModels.get(name);
}
public ModelInfo findModelInfoByID(String id) {
for (Map.Entry<String, ModelInfo> entry : mModels.entrySet()) {
ModelInfo modelInfo = entry.getValue();
if (id.equals(modelInfo.mProductId)) {
return modelInfo;
}
}
return null;
}
public ArrayList<ModelInfo> findModelInfoByType(String type) {
ArrayList<ModelInfo> flyers = new ArrayList<ModelInfo>();
for (Map.Entry<String, ModelInfo> entry : mModels.entrySet()) {
ModelInfo flyer = entry.getValue();
if (!flyer.mType.equals(type)) {
continue;
}
flyers.add(flyer);
}
return flyers;
}
/**
* Objects menu can call this method, or we dose not need clone this object
*/
public void createBaseObject(final SEObject parent, final SEObject modelObject, final Runnable finish) {
final ModelInfo modelInfo = mModels.get(modelObject.mName);
if (modelObject.mIndex == 0) {
// for single instance object
modelInfo.load3DMAXModel(parent.getScene(), parent, modelObject, false, new Runnable() {
public void run() {
parent.addChild(modelObject, false);
resizeModel(parent.getScene(), modelInfo);
register(modelObject);
if (finish != null) {
finish.run();
}
}
});
} else {
throw new IllegalArgumentException("The index of base object should equals 0");
}
}
public void register(SEObject instance) {
ModelInfo modelInfo = mModels.get(instance.mName);
if (modelInfo == null) {
return;
}
if (!modelInfo.getInstances().contains(instance)) {
if (HomeUtils.DEBUG) {
Log.d("ModelObjectsManager", "################register############" + instance.getName());
}
modelInfo.getInstances().add(instance);
}
}
public void unRegister(SEObject instance) {
ModelInfo modelInfo = mModels.get(instance.mName);
if (modelInfo == null) {
return;
}
if (modelInfo.getInstances().contains(instance)) {
modelInfo.getInstances().remove(instance);
if (HomeUtils.DEBUG) {
Log.d("ModelObjectsManager", "################unRegister############" + instance.getName());
}
if (modelInfo.getInstances().size() == 1) {
releaseBaseObjectWhileNoObjectCloneFromIt(modelInfo);
}
}
}
/**
* We will release the last object if we do not need it no longer
*/
private void releaseBaseObjectWhileNoObjectCloneFromIt(ModelInfo modelInfo) {
if (!modelInfo.mType.equals("Folder") && !modelInfo.mType.equals("Recycle")
&& !modelInfo.mType.equals("shop")
&& !modelInfo.mType.equals("House") && !modelInfo.mType.equals("Sky")
&& !modelInfo.mType.equals("showbox")) {
if (HomeUtils.DEBUG) {
Log.d("ModelObjectsManager", "################release model############" + modelInfo.mName);
}
SEObject theLastInstance = modelInfo.getInstances().get(0);
theLastInstance.getParent().removeChild(theLastInstance, true);
modelInfo.getInstances().clear();
}
}
/**
* 我们CBF里面包含的模型结构是: desk子节点为{desk_model}, desk_model子节点为{desktop, desk_legs,
* desk_circle}。加载模型时可以选择是否需要最上层节点也就是desk节点,当模型需要更新时我们希望保留桌面上的东西,这时可以只替换desk_model
*/
public void loadModelOnly(final ModelInfo modelInfo, final SEObject parent, final SEObject modelObject,
final Runnable finish) {
modelInfo.load3DMAXModel(parent.getScene(), parent, modelObject, true, new Runnable() {
public void run() {
resizeModel(parent.getScene(), modelInfo);
if (finish != null) {
finish.run();
}
}
});
}
}
| 3DHome/3DHome | 3DHome/src/main/java/com/borqs/se/home3d/ModelObjectsManager.java | 4,551 | // 对应桌面的物体只调整中心点的位置,使得中心点的位置为物体的底部 | line_comment | zh-cn | package com.borqs.se.home3d;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.borqs.se.engine.SEScene;
import com.borqs.se.engine.SECommand;
import com.borqs.se.engine.SELoadResThread;
import com.borqs.se.engine.SEObject;
import com.borqs.se.engine.SESceneManager;
import com.borqs.se.engine.SEVector.SEVector3f;
import com.borqs.se.home3d.ProviderUtils.ModelColumns;
import com.borqs.se.widget3d.House;
import com.borqs.se.widget3d.NormalObject;
import com.borqs.se.widget3d.ObjectInfo;
import com.support.StaticUtil;
public class ModelObjectsManager {
public HashMap<String, ModelInfo> mModels;
private boolean mInitFailed = false;
public ModelObjectsManager() {
init();
}
public boolean initFailed() {
return mInitFailed;
}
private void init() {
Context context = SESceneManager.getInstance().getContext();
ContentResolver resolver = context.getContentResolver();
Cursor modelCursor = resolver.query(ModelColumns.CONTENT_URI, null, null, null, null);
if (modelCursor == null) {
mInitFailed = true;
return;
}
while (modelCursor.moveToNext()) {
ModelInfo modelInfo = ModelInfo.CreateFromDB(modelCursor);
if (mModels == null) {
mModels = new HashMap<String, ModelInfo>();
}
// #########判断模型文件是否存在,假如不存在不加入列表中###########
boolean modelExist = true;
if (modelInfo.mAssetsPath.startsWith("assets/")) {
try {
InputStream is = context.getAssets()
.open(modelInfo.mAssetsPath.substring(7) + "/models_config.xml");
if (is == null) {
modelExist = false;
} else {
is.close();
}
} catch (IOException e) {
modelExist = false;
} catch (NullPointerException e) {
modelCursor.close();
mInitFailed = true;
return;
}
} else {
File modelFile = new File(modelInfo.mAssetsPath);
if (!modelFile.exists()) {
modelExist = false;
}
}
if (modelExist) {
mModels.put(modelInfo.mName, modelInfo);
}
}
modelCursor.close();
}
/**
* When the 3Dscene started, will load the preload models which for
* can be added into the scene quickly.
* @param finish the finish behavior after preloaded.
*/
public void loadPreLoadModel(final SEScene scene, final Runnable finish) {
Iterator<Entry<String, ModelInfo>> iter = mModels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ModelInfo> entry = iter.next();
final ModelInfo modelInfo = entry.getValue();
if (modelInfo.mType.equals("Shelf")) {
if (!modelInfo.hasInstance()) {
final SEObject baseModel = new SEObject(scene, modelInfo.mName, 0);
modelInfo.load3DMAXModel(scene, scene.getContentObject(), baseModel, false, new Runnable() {
public void run() {
baseModel.setVisible(false);
scene.getContentObject().addChild(baseModel, false);
register(baseModel);
// adjust the size of 3DMax model begin
resizeModel(scene, modelInfo);
// adjust the size of 3DMax model end
}
});
}
}
}
SELoadResThread.getInstance().process(new Runnable() {
public void run() {
new SECommand(scene) {
public void run() {
if (finish != null) {
finish.run();
}
}
}.execute();
}
});
}
/**
* When the 3Dscene started,After load all objects finished, will load the preload models which for
* can be added into the scene quickly.
* @param finish the finish behavior after afterloaded.
*/
public void loadAfterLoadModel(final SEScene scene, final Runnable finish) {
Iterator<Entry<String, ModelInfo>> iter = mModels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ModelInfo> entry = iter.next();
final ModelInfo modelInfo = entry.getValue();
if (modelInfo.mType.equals("Folder") || modelInfo.mType.equals("Recycle")) {
if (!modelInfo.hasInstance()) {
final SEObject baseModel = new SEObject(scene, modelInfo.mName, 0);
modelInfo.load3DMAXModel(scene, scene.getContentObject(), baseModel, false, new Runnable() {
public void run() {
baseModel.setVisible(false);
scene.getContentObject().addChild(baseModel, false);
register(baseModel);
// adjust the size of 3DMax model begin
resizeModel(scene, modelInfo);
// adjust the size of 3DMax model end
}
});
}
}
}
SELoadResThread.getInstance().process(new Runnable() {
public void run() {
new SECommand(scene) {
public void run() {
if (finish != null) {
finish.run();
}
}
}.execute();
}
});
}
public void clearModelStatus() {
Iterator<Entry<String, ModelInfo>> iter = mModels.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ModelInfo> entry = iter.next();
ModelInfo modelInfo = entry.getValue();
modelInfo.getInstances().clear();
}
}
/**
* 克隆物体,并且对物体大小进行适配
*/
public boolean createQuickly(SEObject parent, SEObject modelObject) {
ModelInfo modelInfo = mModels.get(modelObject.mName);
if (modelInfo.hasInstance()) {
if (parent.hasBeenReleased()) {
Context context = SESceneManager.getInstance().getContext();
StaticUtil.reportError(context, "on clone, but parent of " + modelObject.mName + " is null");
}
// clone from base model
SEObject baseModel = modelInfo.getInstances().get(0);
baseModel.cloneObject_JNI(parent, modelObject.mIndex);
modelObject.setHasBeenAddedToEngine(true);
parent.addChild(modelObject, false);
register(modelObject);
adjustTheSizeOfObject(modelInfo, modelObject);
return true;
}
return false;
}
/**
* 调整添加入房间物体的大小,以及物体占用的格子数
* 注意在墙上的物体其Z坐标上的点最大不能超过0,否则可能会被嵌入墙面
*/
private void adjustTheSizeOfObject(ModelInfo modelInfo, SEObject modelObject) {
if (modelObject instanceof NormalObject) {
NormalObject normalObject = (NormalObject) modelObject;
if (modelInfo.mSlotType == ObjectInfo.SLOT_TYPE_DESKTOP) {
// 对应 <SUF>
} else if (modelInfo.mSlotType == ObjectInfo.SLOT_TYPE_WALL) {
House house;
if (modelObject.getParent().getParent() instanceof House) {
house = (House) modelObject.getParent().getParent();
} else {
house = HomeManager.getInstance().getHomeScene().getHouse();
}
ObjectInfo objectInfo = normalObject.getObjectInfo();
SEObject modelComponenet = normalObject.getModelComponenet();
float maxWidth = getWidthOfWidget(house, Float.MAX_VALUE);
float maxHight = getHeightOfWidget(house, Float.MAX_VALUE);
float scale;
SEVector3f translate;
float sizeX = 2 * Math.max(modelInfo.mMaxPoint.getX(), -modelInfo.mMinPoint.getX());
float sizeZ = 2 * Math.max(modelInfo.mMaxPoint.getZ(), -modelInfo.mMinPoint.getZ());
// 假如在配置文件中没有指定物体的占用的格子数,那么我们根据物体的最小点和最大点来计算物体应该占用几个格子
if (objectInfo.getSpanX() <= 0 || objectInfo.getSpanY() <= 0) {
if (sizeX > maxWidth || sizeZ > maxHight) {
scale = Math.min(maxWidth / sizeX, maxHight / sizeZ);
translate = new SEVector3f(0, -objectInfo.mMaxPoint.getY() * scale, 0);
objectInfo.setSpanX(house.mCellCountX);
objectInfo.setSpanX(house.mCellCountY);
} else {
int spanX = 0;
int spanY = 0;
while (sizeX <= getWidthOfWidget(house, spanX)) {
spanX++;
}
while (sizeZ <= getHeightOfWidget(house, spanY)) {
spanY++;
}
spanX--;
spanY--;
maxWidth = getWidthOfWidget(house, spanX);
maxHight = getHeightOfWidget(house, spanY);
scale = Math.min(maxWidth / sizeX, maxHight / sizeZ);
translate = new SEVector3f(0, -objectInfo.mMaxPoint.getY() * scale, 0);
objectInfo.setSpanX(spanX);
objectInfo.setSpanX(spanY);
}
// 假如在配置文件中指定了物体应该占用几个格子,那么我们根据格子的大小对物体进行缩放
} else {
int oldSpanX = objectInfo.getSpanX();
if (oldSpanX > house.mCellCountX) {
objectInfo.setSpanX(house.mCellCountX);
objectInfo
.setSpanY(objectInfo.getSpanY() - oldSpanX + house.mCellCountX);
}
int oldSpanY = objectInfo.getSpanY();
if (oldSpanY > house.mCellCountY) {
objectInfo.setSpanY(house.mCellCountY);
objectInfo.setSpanX(objectInfo.getSpanX() - oldSpanY + house.mCellCountY);
}
maxWidth = getWidthOfWidget(house, objectInfo.getSpanX());
maxHight = getHeightOfWidget(house, objectInfo.getSpanY());
scale = Math.min(maxWidth / sizeX, maxHight / sizeZ);
translate = new SEVector3f(0, -objectInfo.mMaxPoint.getY() * scale, 0);
}
objectInfo.mMinPoint = modelInfo.mMinPoint.mul(scale);
objectInfo.mMaxPoint = modelInfo.mMaxPoint.mul(scale);
objectInfo.mMinPoint.selfAdd(translate);
objectInfo.mMaxPoint.selfAdd(translate);
modelComponenet.setUserTranslate(translate);
modelComponenet.setUserScale(new SEVector3f(scale, scale, scale));
}
}
}
private float getWidthOfWidget(House house, float spanX) {
float gridSizeX = house.mCellWidth + house.mWidthGap;
if (spanX > house.mCellCountX) {
return house.mCellCountX * gridSizeX - house.mWidthGap;
} else {
return spanX * gridSizeX - house.mWidthGap;
}
}
private float getHeightOfWidget(House house, float spanY) {
float gridSizeY = house.mCellHeight + house.mHeightGap;
if (spanY > house.mCellCountY) {
return house.mCellCountY * gridSizeY - house.mHeightGap;
} else {
return spanY * gridSizeY - house.mHeightGap;
}
}
/**
* If modelObject's mIndex does not equals 0, we will save a base object
* which index is 0. All objects are cloned from the base object
*/
public void create(final SEObject parent, final SEObject modelObject, final Runnable finish) {
final ModelInfo modelInfo = mModels.get(modelObject.mName);
if (modelObject.mIndex == 0) {
throw new IllegalArgumentException(
"If the object is created from 3DMax model, its index should not equals 0");
}
if (modelInfo.hasInstance()) {
//假如模型在场景中已经有实例了,直接克隆出一个
createQuickly(parent, modelObject);
if (finish != null) {
finish.run();
}
} else if (modelInfo.isOnLoading()) {
//假如模型正在加载,那么等加载完了后克隆出一个
SELoadResThread.getInstance().process(new Runnable() {
public void run() {
new SECommand(parent.getScene()) {
public void run() {
createQuickly(parent, modelObject);
if (finish != null) {
finish.run();
}
}
}.execute();
}
});
} else {
//假如模型还没有加载,那么开始加载,等加载完了后克隆出一个
final SEObject baseModel = new SEObject(parent.getScene(), modelInfo.mName, 0);
createBaseObject(parent.getScene().getContentObject(), baseModel, new Runnable() {
public void run() {
baseModel.setVisible(false);
createQuickly(parent, modelObject);
if (finish != null) {
finish.run();
}
}
});
}
}
/**
* 模型文件结构如桌子(相机和电话是在桌子加载完成后加入桌子的节点):
* 桌子
* _____|_____
* ___|___ |
* | | 桌子_model
* 相机 ... 电话 ___|___
* | |
* 桌子腿...桌面
*
* 根据配置文件中localTrans来调整模型的大小,如桌子:
* 我们只需要调整“桌子_model”物体的大小而不用调整相机和电话的大小
*/
private void resizeModel(SEScene scene, ModelInfo modelInfo) {
SEObject modelOf3DMax = new SEObject(scene, modelInfo.mName + "_model");
if (modelInfo.mCompensationTrans != null) {
modelOf3DMax.setHasBeenAddedToEngine(true);
modelOf3DMax.setLocalTranslate(modelInfo.mCompensationTrans.mTranslate);
modelOf3DMax.setLocalRotate(modelInfo.mCompensationTrans.mRotate);
modelOf3DMax.setLocalScale(modelInfo.mCompensationTrans.mScale);
}
}
public ModelInfo findModelInfo(String name) {
return mModels.get(name);
}
public ModelInfo findModelInfoByID(String id) {
for (Map.Entry<String, ModelInfo> entry : mModels.entrySet()) {
ModelInfo modelInfo = entry.getValue();
if (id.equals(modelInfo.mProductId)) {
return modelInfo;
}
}
return null;
}
public ArrayList<ModelInfo> findModelInfoByType(String type) {
ArrayList<ModelInfo> flyers = new ArrayList<ModelInfo>();
for (Map.Entry<String, ModelInfo> entry : mModels.entrySet()) {
ModelInfo flyer = entry.getValue();
if (!flyer.mType.equals(type)) {
continue;
}
flyers.add(flyer);
}
return flyers;
}
/**
* Objects menu can call this method, or we dose not need clone this object
*/
public void createBaseObject(final SEObject parent, final SEObject modelObject, final Runnable finish) {
final ModelInfo modelInfo = mModels.get(modelObject.mName);
if (modelObject.mIndex == 0) {
// for single instance object
modelInfo.load3DMAXModel(parent.getScene(), parent, modelObject, false, new Runnable() {
public void run() {
parent.addChild(modelObject, false);
resizeModel(parent.getScene(), modelInfo);
register(modelObject);
if (finish != null) {
finish.run();
}
}
});
} else {
throw new IllegalArgumentException("The index of base object should equals 0");
}
}
public void register(SEObject instance) {
ModelInfo modelInfo = mModels.get(instance.mName);
if (modelInfo == null) {
return;
}
if (!modelInfo.getInstances().contains(instance)) {
if (HomeUtils.DEBUG) {
Log.d("ModelObjectsManager", "################register############" + instance.getName());
}
modelInfo.getInstances().add(instance);
}
}
public void unRegister(SEObject instance) {
ModelInfo modelInfo = mModels.get(instance.mName);
if (modelInfo == null) {
return;
}
if (modelInfo.getInstances().contains(instance)) {
modelInfo.getInstances().remove(instance);
if (HomeUtils.DEBUG) {
Log.d("ModelObjectsManager", "################unRegister############" + instance.getName());
}
if (modelInfo.getInstances().size() == 1) {
releaseBaseObjectWhileNoObjectCloneFromIt(modelInfo);
}
}
}
/**
* We will release the last object if we do not need it no longer
*/
private void releaseBaseObjectWhileNoObjectCloneFromIt(ModelInfo modelInfo) {
if (!modelInfo.mType.equals("Folder") && !modelInfo.mType.equals("Recycle")
&& !modelInfo.mType.equals("shop")
&& !modelInfo.mType.equals("House") && !modelInfo.mType.equals("Sky")
&& !modelInfo.mType.equals("showbox")) {
if (HomeUtils.DEBUG) {
Log.d("ModelObjectsManager", "################release model############" + modelInfo.mName);
}
SEObject theLastInstance = modelInfo.getInstances().get(0);
theLastInstance.getParent().removeChild(theLastInstance, true);
modelInfo.getInstances().clear();
}
}
/**
* 我们CBF里面包含的模型结构是: desk子节点为{desk_model}, desk_model子节点为{desktop, desk_legs,
* desk_circle}。加载模型时可以选择是否需要最上层节点也就是desk节点,当模型需要更新时我们希望保留桌面上的东西,这时可以只替换desk_model
*/
public void loadModelOnly(final ModelInfo modelInfo, final SEObject parent, final SEObject modelObject,
final Runnable finish) {
modelInfo.load3DMAXModel(parent.getScene(), parent, modelObject, true, new Runnable() {
public void run() {
resizeModel(parent.getScene(), modelInfo);
if (finish != null) {
finish.run();
}
}
});
}
}
| 0 |
59062_0 | package com.hydrogen.mqtt.connector.msghandle.agv.handler;
import org.apache.mina.core.session.IoSession;
import com.hydrogen.mqtt.connector.car.House;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgHandlerInterface;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgInterface;
import com.hydrogen.mqtt.connector.msghandle.agv.AGVCar;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVBaseMsg;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVInfoRspMsg;
public abstract class AGVMsgHandler<T extends AGVBaseMsg> implements AGVMsgHandlerInterface{
@SuppressWarnings("unchecked")
@Override
public AGVMsgInterface process(AGVMsgInterface taskMsg, IoSession session) {
T msg = (T)taskMsg;
AGVInfoRspMsg rsp = new AGVInfoRspMsg(msg.getMsgseq());
AGVCar car = initCar(msg,session);
//改为异步操作车子
handler(msg,car);
return getCarInfo(rsp,car);
}
public abstract AGVBaseMsg handler(T italkmsg,AGVCar car);
public AGVCar initCar(AGVBaseMsg italkmsg,IoSession session) {
int carid = italkmsg.agvid();
if(carid!=0) {
session.setAttribute("carid", carid);
}
AGVCar car = (AGVCar)House.getCar(carid);
if(car!=null) {
return car;
}
car = new AGVCar();
car.setId(carid);
House.addCar(car);
car.init();
car.start();
return car;
}
public AGVInfoRspMsg getCarInfo(AGVInfoRspMsg rsp, AGVCar car) {
rsp.setStatus(car.getStatus());
rsp.setTaskComplete(car.getTaskComplete());
rsp.setTaskRedo(car.getTaskRedo());
rsp.setX(car.getX());
rsp.setY(car.getY());
rsp.setW(car.getW());
rsp.setOnTop(car.getOnTop());
rsp.setFlip(car.getFlip());
rsp.setHand(car.getHand());
rsp.setPower(car.getPower());
rsp.setSpeed(car.getSpeed());
rsp.setAlarmLength(car.getAlarmLength());
return rsp;
}
}
| 3dudu/simulatoragv | src/main/java/com/hydrogen/mqtt/connector/msghandle/agv/handler/AGVMsgHandler.java | 641 | //改为异步操作车子 | line_comment | zh-cn | package com.hydrogen.mqtt.connector.msghandle.agv.handler;
import org.apache.mina.core.session.IoSession;
import com.hydrogen.mqtt.connector.car.House;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgHandlerInterface;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgInterface;
import com.hydrogen.mqtt.connector.msghandle.agv.AGVCar;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVBaseMsg;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVInfoRspMsg;
public abstract class AGVMsgHandler<T extends AGVBaseMsg> implements AGVMsgHandlerInterface{
@SuppressWarnings("unchecked")
@Override
public AGVMsgInterface process(AGVMsgInterface taskMsg, IoSession session) {
T msg = (T)taskMsg;
AGVInfoRspMsg rsp = new AGVInfoRspMsg(msg.getMsgseq());
AGVCar car = initCar(msg,session);
//改为 <SUF>
handler(msg,car);
return getCarInfo(rsp,car);
}
public abstract AGVBaseMsg handler(T italkmsg,AGVCar car);
public AGVCar initCar(AGVBaseMsg italkmsg,IoSession session) {
int carid = italkmsg.agvid();
if(carid!=0) {
session.setAttribute("carid", carid);
}
AGVCar car = (AGVCar)House.getCar(carid);
if(car!=null) {
return car;
}
car = new AGVCar();
car.setId(carid);
House.addCar(car);
car.init();
car.start();
return car;
}
public AGVInfoRspMsg getCarInfo(AGVInfoRspMsg rsp, AGVCar car) {
rsp.setStatus(car.getStatus());
rsp.setTaskComplete(car.getTaskComplete());
rsp.setTaskRedo(car.getTaskRedo());
rsp.setX(car.getX());
rsp.setY(car.getY());
rsp.setW(car.getW());
rsp.setOnTop(car.getOnTop());
rsp.setFlip(car.getFlip());
rsp.setHand(car.getHand());
rsp.setPower(car.getPower());
rsp.setSpeed(car.getSpeed());
rsp.setAlarmLength(car.getAlarmLength());
return rsp;
}
}
| 0 |
66562_53 | package hardware;
import file.DiskInode;
import file.UserFileItem;
import interrupt.*;
import kernel.Instruction;
import kernel.PCB;
import kernel.Page;
import kernel.Schedule;
import os.Manager;
import java.util.Iterator;
/**
* CPU中央处理器,负责程序运行的相关操作
*
* 用以处理中断,执行指令等
*
* @author ZJC
*/
public class CPU implements InterruptVector {
/**
* 系统管理器,用以获取系统资源
*/
private Manager manager;
/**
* 程序计数器,下一条指令的执行编号
*/
private int PC;
/**
* 指令寄存器,正在执行的指令编号
*/
private int IR;
/**
* 状态寄存器 0用户态 1内核态
*/
private int PSW;
public static final int USER_STATE = 0;
public static final int KERNEL_STATE = 1;
/**
* 当前运行态的PCB指针
*/
private PCB runningPCB;
/**
* 允许调度标志,控制调度时机
* 只有该标志打开后,才可以进行三级调度,否则CPU执行指令和调度操作将会出现混乱
*/
private volatile boolean canSchedule;
/**
* 当前剩余时间片
*/
private int timeSlice;
/**
* 因缺页中断而剩余的时间片
*/
private int missPageRemainTimeSlice;
public CPU(Manager manager) {
this.manager = manager;
this.PC = 1;
this.IR = 0;
this.PSW = USER_STATE;
this.runningPCB = null;
this.canSchedule = false;
this.timeSlice = 0;
this.missPageRemainTimeSlice = 0;
this.manager.getDashboard().consoleSuccess("CPU初始化完成");
}
/**
* 中断处理
* @param interruptVector 中断向量 用以区别中断例程
* @param index 中断处理的附加参数
*/
public synchronized void interrupt(int interruptVector, int index) {
switch (interruptVector) {
// 时钟中断处理
case CLOCK_INTERRUPT: {
// 允许调度
this.openSchedule();
break;
}
// 缺页中断处理
case MISS_PAGE_INTERRUPT: {
this.switchToKernelState();
// 缺页中断线程启动, index为缺页的逻辑页号
new MissPageInterrupt(this.manager, this.runningPCB, index).start();
// 设置缺页标志
this.runningPCB.setMissPage(true);
// 当前进程阻塞
this.runningPCB.block(this.manager.getSchedule().getBlockQueue());
break;
}
// 资源申请中断处理
case APPLY_RESOURCE_INTERRUPT: {
// 申请资源,index为资源种类
this.manager.getDeadlock().applyResource(this.runningPCB, index);
// 尝试分配资源
int allocateResult = this.manager.getDeadlock().tryAllocateResource(this.runningPCB, index);
// 如果返回阻塞标志,则阻塞进程
if (allocateResult == -1) {
this.manager.getDashboard().consoleError("资源 " + index + " 分配失败,进程 " + this.runningPCB.getId() + " 阻塞");
this.runningPCB.block(this.manager.getSchedule().getResourceBlockQueues()[index]);
}
break;
}
// 资源释放中断处理
case RELEASE_RESOURCE_INTERRUPT: {
// 释放资源,index为资源种类
this.manager.getDeadlock().releaseResource(this.runningPCB, index);
// 尝试重分配资源
if (this.manager.getSchedule().getResourceBlockQueues()[index].size() > 0) {
int reallocateResult = this.manager.getDeadlock().tryReallocateResource(this.manager.getSchedule().getResourceBlockQueues()[index].get(0), index);
// 如果返回唤醒标志,则唤醒阻塞队列队首进程
if (reallocateResult == -1) {
this.manager.getSchedule().getResourceBlockQueues()[index].get(0).wakeUp(this.manager.getSchedule().getResourceBlockQueues()[index]);
}
}
break;
}
// 输入中断
case INPUT_INTERRUPT: {
// index 为页框号
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
String filePath = tempPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra().split(" ")[1];
Iterator<UserFileItem> iterator = tempPCB.getUserOpenFileTable().iterator();
while (iterator.hasNext()) {
UserFileItem userFileItem = iterator.next();
try {
DiskInode currentInode = this.manager.getFileSystem().getDiskInodeMap().get("" + userFileItem.getFp().getInode().getInodeNo());
DiskInode targetInode = this.manager.getFileSystem().getDiskInodeByPath(filePath);
if (currentInode == targetInode) {
this.switchToKernelState();
new IOInterrupt(this.manager, tempPCB, IOInterrupt.INPUT, index, userFileItem.getFd()).start();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
// 输出中断
case OUTPUT_INTERRUPT: {
// index 为页框号
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
String filePath = tempPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra().split(" ")[1];
Iterator<UserFileItem> iterator = tempPCB.getUserOpenFileTable().iterator();
while (iterator.hasNext()) {
UserFileItem userFileItem = iterator.next();
try {
if (this.manager.getFileSystem().getDiskInodeMap().get("" + userFileItem.getFp().getInode().getInodeNo())
== this.manager.getFileSystem().getDiskInodeByPath(filePath)) {
this.switchToKernelState();
new IOInterrupt(this.manager, tempPCB, IOInterrupt.OUTPUT, index, userFileItem.getFd()).start();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
// 作业请求中断
case JOB_REQUEST_INTERRUPT: {
this.switchToKernelState();
new JobRequestInterrupt(this.manager).start();
break;
}
// 文件创建中断
case CREATE_FILE_INTERRUPT: {
this.switchToKernelState();
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
new FileOperationInterrupt(this.manager, tempPCB, FileOperationInterrupt.CREATE_FILE).start();
break;
}
// 文件关闭中断
case CLOSE_FILE_INTERRUPT: {
this.switchToKernelState();
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
new FileOperationInterrupt(this.manager, tempPCB, FileOperationInterrupt.CLOSE_FILE).start();
break;
}
default: {
break;
}
}
this.switchToUserState();
}
/**
* 执行当前指令
*/
public synchronized void execute() {
// 刷新GUI
this.manager.getDashboard().refreshRunningProcess();
if (this.runningPCB == null) {
return;
}
// 执行指令需要内存中有代码段数据
int codeSegmentPageItemAddress = this.runningPCB.getPageTableBaseAddress() +
this.runningPCB.getCodeSegment().getLogicPageStartNo() * InternalMem.PAGE_TABLE_ITEM_SIZE;
this.manager.getAddressLine().setAddress((short) codeSegmentPageItemAddress);
Page codePage = this.manager.getInMem().readPageItem(this.manager.getAddressLine());
if (codePage.getCallFlag() == 0) {
// 代码段页面未装入,则执行缺页中断,装入代码页
this.manager.getDashboard().consoleLog("代码段数据未装入内存,优先装入代码段");
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, codePage.getLogicPageNo());
return;
} else {
// 代码段页面已经装入,则看作一次访问内存,并更新快表
this.manager.getInMem().readPage(codePage);
this.runningPCB.accessPage(codePage.getLogicPageNo());
this.manager.getMmu().updateTLB(codePage.getLogicPageNo(), codePage.getInternalFrameNo());
}
// 指令指针自增并获取当前指令
this.IR = this.PC++;
Instruction currentInstrction = new Instruction();
int id = ((((int) codePage.getData()[8 * (IR - 1) + 1]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 0]) & 0x0000FF);
int state = ((((int) codePage.getData()[8 * (IR - 1) + 3]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 2]) & 0x0000FF);
int argument = ((((int) codePage.getData()[8 * (IR - 1) + 5]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 4]) & 0x0000FF);
currentInstrction.setId(id);
currentInstrction.setState(state);
currentInstrction.setArgument(argument);
currentInstrction.setExtra(this.runningPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra());
this.manager.getDashboard().consoleLog("执行进程 " + this.runningPCB.getId() + " :" +
" 指令 " + currentInstrction.getId() +
" 类型 " + currentInstrction.getState() +
" 参数 " + currentInstrction.getArgument() +
" 附加数据 " + currentInstrction.getExtra());
switch (currentInstrction.getState()) {
// 0 system 系统调用,本系统中仿真为输入、输出、创建文件操作
case 0: {
int type = currentInstrction.getArgument();
String extra = currentInstrction.getExtra();
if (type == 0) {
// 创建文件
this.interrupt(InterruptVector.CREATE_FILE_INTERRUPT, 0);
} else if (type == 1) {
// 输入操作
try {
int logicAddress = (this.runningPCB.getDataSegment().getLogicPageStartNo() + Integer.parseInt(extra.split(" ")[0])) * InternalMem.PAGE_SIZE;
String filePath = extra.split(" ")[1];
short physicAddress = this.manager.getMmu().resolveLogicAddress((short) logicAddress, this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存当前时间片
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, logicAddress / InternalMem.PAGE_SIZE);
} else {
this.runningPCB.accessPage(logicAddress / InternalMem.PAGE_SIZE);
this.interrupt(InterruptVector.INPUT_INTERRUPT, physicAddress / InternalMem.PAGE_SIZE);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (type == 2) {
// 输出操作
int logicAddress = (this.runningPCB.getDataSegment().getLogicPageStartNo() + Integer.parseInt(extra.split(" ")[0])) * InternalMem.PAGE_SIZE;
String filePath = extra.split(" ")[1];
short physicAddress = this.manager.getMmu().resolveLogicAddress((short) logicAddress, this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存当前时间片
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, logicAddress / InternalMem.PAGE_SIZE);
} else {
this.runningPCB.accessPage(logicAddress / InternalMem.PAGE_SIZE);
this.interrupt(InterruptVector.OUTPUT_INTERRUPT, physicAddress / InternalMem.PAGE_SIZE);
}
} else if (type == 3) {
// 关闭文件
this.interrupt(InterruptVector.CLOSE_FILE_INTERRUPT, 0);
}
break;
}
// 1 calculate 计算指令,CPU不需要调用任何额外资源,可直接运行
case 1: {
// CPU内部进行计算操作,不做任何处理
this.manager.getDashboard().consoleLog("计算指令");
break;
}
// 2 load 读取指令,对内存数据进行读取
case 2: {
// 解析逻辑地址,返回 -1,则表示缺页
short physicAddress = this.manager.getMmu().resolveLogicAddress((short)currentInstrction.getArgument(), this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存当前时间片
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
} else {
this.manager.getAddressLine().setAddress(physicAddress);
short loadData = this.manager.getInMem().readData(this.manager.getAddressLine());
this.runningPCB.accessPage(currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
this.manager.getDashboard().consoleLog("从内存地址" + physicAddress + " 读取数据 " + loadData);
}
break;
}
// 3 store 写入指令,对内存数据进行写入
case 3: {
// 解析逻辑地址,返回 -1,则表示缺页
short physicAddress = this.manager.getMmu().resolveLogicAddress((short)currentInstrction.getArgument(), this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存当前时间片
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
} else {
this.manager.getAddressLine().setAddress(physicAddress);
this.manager.getDataLine().setData((short)0x6666);
this.manager.getInMem().writeData(this.manager.getAddressLine(), this.manager.getDataLine());
this.runningPCB.accessPage(currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
// 设置页表项修改位为1
int pageItemAddress = this.runningPCB.getPageTableBaseAddress() +
currentInstrction.getArgument() / InternalMem.PAGE_SIZE * InternalMem.PAGE_TABLE_ITEM_SIZE;
this.manager.getAddressLine().setAddress((short) pageItemAddress);
Page page = this.manager.getInMem().readPageItem(this.manager.getAddressLine());
page.setModifyFlag(1);
this.manager.getAddressLine().setAddress((short) pageItemAddress);
this.manager.getInMem().writePageItem(this.manager.getAddressLine(), page);
this.manager.getDashboard().consoleLog("向内存地址" + physicAddress + " 写入数据 " + 0x6666);
}
break;
}
// 4 switch 进程切换,直接进行调度
case 4: {
// 时间片置1,执行指令后时间片统一 -1,完成进程强制切换
this.timeSlice = 1;
this.manager.getDashboard().consoleLog("切换指令");
break;
}
// 5 jump 跳转指令,跳过代码段执行
case 5: {
// 设置PC指向跳转地址
this.PC = currentInstrction.getArgument();
this.manager.getDashboard().consoleLog("跳转指令");
break;
}
// 6 apply 资源申请,申请一个系统资源
case 6: {
// 发出资源申请中断
this.interrupt(InterruptVector.APPLY_RESOURCE_INTERRUPT, currentInstrction.getArgument());
break;
}
// 7 release 资源释放,释放一个系统资源
case 7: {
// 发出资源释放中断
this.interrupt(InterruptVector.RELEASE_RESOURCE_INTERRUPT, currentInstrction.getArgument());
break;
}
default: {
break;
}
}
// 时间片 -1
--this.timeSlice;
}
/**
* 恢复CPU现场
* @param pcb 即将进入运行态的进程 PCB
*/
public synchronized void recoverSpot(PCB pcb) {
this.PC = pcb.getPC();
this.IR = pcb.getIR();
this.timeSlice = Schedule.SYSTEM_TIME_SLICE;
// 进程设置运行态
this.runningPCB = pcb;
// 初始化快表
this.manager.getMmu().initTLB();
// 如果因为缺页中断而恢复CPU现场,则使用之前的时间片
if (this.missPageRemainTimeSlice != 0) {
this.timeSlice = this.missPageRemainTimeSlice;
this.missPageRemainTimeSlice = 0;
}
// 更新GUI
this.manager.getDashboard().refreshRunningProcess();
}
/**
* 保护CPU现场
*/
public synchronized void protectSpot() {
this.runningPCB.setIR((short)this.IR);
this.runningPCB.setPC((short)this.PC);
// 进程解除运行态
this.runningPCB = null;
// 更新GUI
this.manager.getDashboard().refreshRunningProcess();
}
/**
* 打开调度
*/
public synchronized void openSchedule() {
this.canSchedule = true;
}
/**
* 关闭调度
*/
public synchronized void closeSchedule() {
this.canSchedule = false;
}
/**
* 切换内核态
*/
public synchronized void switchToKernelState() {
if (this.PSW == KERNEL_STATE) {
return;
}
this.PSW = KERNEL_STATE;
this.manager.getDashboard().consoleLog("CPU -> 内核态");
this.manager.getDashboard().refreshCPU();
}
/**
* 切换用户态
*/
public synchronized void switchToUserState() {
if (this.PSW == USER_STATE) {
return;
}
this.PSW = USER_STATE;
this.manager.getDashboard().consoleLog("CPU -> 用户态");
this.manager.getDashboard().refreshCPU();
}
public Manager getManager() {
return manager;
}
public void setManager(Manager manager) {
this.manager = manager;
}
public int getPC() {
return PC;
}
public void setPC(int PC) {
this.PC = PC;
}
public int getIR() {
return IR;
}
public void setIR(int IR) {
this.IR = IR;
}
public int getPSW() {
return PSW;
}
public void setPSW(int PSW) {
this.PSW = PSW;
}
public PCB getRunningPCB() {
return runningPCB;
}
public void setRunningPCB(PCB runningPCB) {
this.runningPCB = runningPCB;
}
public boolean isCanSchedule() {
return canSchedule;
}
public void setCanSchedule(boolean canSchedule) {
this.canSchedule = canSchedule;
}
public int getTimeSlice() {
return timeSlice;
}
public void setTimeSlice(int timeSlice) {
this.timeSlice = timeSlice;
}
}
| 404874351/NJAU-OS-course-design-simulated-linux | src/hardware/CPU.java | 4,896 | // 保存当前时间片 | line_comment | zh-cn | package hardware;
import file.DiskInode;
import file.UserFileItem;
import interrupt.*;
import kernel.Instruction;
import kernel.PCB;
import kernel.Page;
import kernel.Schedule;
import os.Manager;
import java.util.Iterator;
/**
* CPU中央处理器,负责程序运行的相关操作
*
* 用以处理中断,执行指令等
*
* @author ZJC
*/
public class CPU implements InterruptVector {
/**
* 系统管理器,用以获取系统资源
*/
private Manager manager;
/**
* 程序计数器,下一条指令的执行编号
*/
private int PC;
/**
* 指令寄存器,正在执行的指令编号
*/
private int IR;
/**
* 状态寄存器 0用户态 1内核态
*/
private int PSW;
public static final int USER_STATE = 0;
public static final int KERNEL_STATE = 1;
/**
* 当前运行态的PCB指针
*/
private PCB runningPCB;
/**
* 允许调度标志,控制调度时机
* 只有该标志打开后,才可以进行三级调度,否则CPU执行指令和调度操作将会出现混乱
*/
private volatile boolean canSchedule;
/**
* 当前剩余时间片
*/
private int timeSlice;
/**
* 因缺页中断而剩余的时间片
*/
private int missPageRemainTimeSlice;
public CPU(Manager manager) {
this.manager = manager;
this.PC = 1;
this.IR = 0;
this.PSW = USER_STATE;
this.runningPCB = null;
this.canSchedule = false;
this.timeSlice = 0;
this.missPageRemainTimeSlice = 0;
this.manager.getDashboard().consoleSuccess("CPU初始化完成");
}
/**
* 中断处理
* @param interruptVector 中断向量 用以区别中断例程
* @param index 中断处理的附加参数
*/
public synchronized void interrupt(int interruptVector, int index) {
switch (interruptVector) {
// 时钟中断处理
case CLOCK_INTERRUPT: {
// 允许调度
this.openSchedule();
break;
}
// 缺页中断处理
case MISS_PAGE_INTERRUPT: {
this.switchToKernelState();
// 缺页中断线程启动, index为缺页的逻辑页号
new MissPageInterrupt(this.manager, this.runningPCB, index).start();
// 设置缺页标志
this.runningPCB.setMissPage(true);
// 当前进程阻塞
this.runningPCB.block(this.manager.getSchedule().getBlockQueue());
break;
}
// 资源申请中断处理
case APPLY_RESOURCE_INTERRUPT: {
// 申请资源,index为资源种类
this.manager.getDeadlock().applyResource(this.runningPCB, index);
// 尝试分配资源
int allocateResult = this.manager.getDeadlock().tryAllocateResource(this.runningPCB, index);
// 如果返回阻塞标志,则阻塞进程
if (allocateResult == -1) {
this.manager.getDashboard().consoleError("资源 " + index + " 分配失败,进程 " + this.runningPCB.getId() + " 阻塞");
this.runningPCB.block(this.manager.getSchedule().getResourceBlockQueues()[index]);
}
break;
}
// 资源释放中断处理
case RELEASE_RESOURCE_INTERRUPT: {
// 释放资源,index为资源种类
this.manager.getDeadlock().releaseResource(this.runningPCB, index);
// 尝试重分配资源
if (this.manager.getSchedule().getResourceBlockQueues()[index].size() > 0) {
int reallocateResult = this.manager.getDeadlock().tryReallocateResource(this.manager.getSchedule().getResourceBlockQueues()[index].get(0), index);
// 如果返回唤醒标志,则唤醒阻塞队列队首进程
if (reallocateResult == -1) {
this.manager.getSchedule().getResourceBlockQueues()[index].get(0).wakeUp(this.manager.getSchedule().getResourceBlockQueues()[index]);
}
}
break;
}
// 输入中断
case INPUT_INTERRUPT: {
// index 为页框号
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
String filePath = tempPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra().split(" ")[1];
Iterator<UserFileItem> iterator = tempPCB.getUserOpenFileTable().iterator();
while (iterator.hasNext()) {
UserFileItem userFileItem = iterator.next();
try {
DiskInode currentInode = this.manager.getFileSystem().getDiskInodeMap().get("" + userFileItem.getFp().getInode().getInodeNo());
DiskInode targetInode = this.manager.getFileSystem().getDiskInodeByPath(filePath);
if (currentInode == targetInode) {
this.switchToKernelState();
new IOInterrupt(this.manager, tempPCB, IOInterrupt.INPUT, index, userFileItem.getFd()).start();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
// 输出中断
case OUTPUT_INTERRUPT: {
// index 为页框号
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
String filePath = tempPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra().split(" ")[1];
Iterator<UserFileItem> iterator = tempPCB.getUserOpenFileTable().iterator();
while (iterator.hasNext()) {
UserFileItem userFileItem = iterator.next();
try {
if (this.manager.getFileSystem().getDiskInodeMap().get("" + userFileItem.getFp().getInode().getInodeNo())
== this.manager.getFileSystem().getDiskInodeByPath(filePath)) {
this.switchToKernelState();
new IOInterrupt(this.manager, tempPCB, IOInterrupt.OUTPUT, index, userFileItem.getFd()).start();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
// 作业请求中断
case JOB_REQUEST_INTERRUPT: {
this.switchToKernelState();
new JobRequestInterrupt(this.manager).start();
break;
}
// 文件创建中断
case CREATE_FILE_INTERRUPT: {
this.switchToKernelState();
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
new FileOperationInterrupt(this.manager, tempPCB, FileOperationInterrupt.CREATE_FILE).start();
break;
}
// 文件关闭中断
case CLOSE_FILE_INTERRUPT: {
this.switchToKernelState();
PCB tempPCB = this.runningPCB;
tempPCB.block(this.manager.getSchedule().getBlockQueue());
new FileOperationInterrupt(this.manager, tempPCB, FileOperationInterrupt.CLOSE_FILE).start();
break;
}
default: {
break;
}
}
this.switchToUserState();
}
/**
* 执行当前指令
*/
public synchronized void execute() {
// 刷新GUI
this.manager.getDashboard().refreshRunningProcess();
if (this.runningPCB == null) {
return;
}
// 执行指令需要内存中有代码段数据
int codeSegmentPageItemAddress = this.runningPCB.getPageTableBaseAddress() +
this.runningPCB.getCodeSegment().getLogicPageStartNo() * InternalMem.PAGE_TABLE_ITEM_SIZE;
this.manager.getAddressLine().setAddress((short) codeSegmentPageItemAddress);
Page codePage = this.manager.getInMem().readPageItem(this.manager.getAddressLine());
if (codePage.getCallFlag() == 0) {
// 代码段页面未装入,则执行缺页中断,装入代码页
this.manager.getDashboard().consoleLog("代码段数据未装入内存,优先装入代码段");
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, codePage.getLogicPageNo());
return;
} else {
// 代码段页面已经装入,则看作一次访问内存,并更新快表
this.manager.getInMem().readPage(codePage);
this.runningPCB.accessPage(codePage.getLogicPageNo());
this.manager.getMmu().updateTLB(codePage.getLogicPageNo(), codePage.getInternalFrameNo());
}
// 指令指针自增并获取当前指令
this.IR = this.PC++;
Instruction currentInstrction = new Instruction();
int id = ((((int) codePage.getData()[8 * (IR - 1) + 1]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 0]) & 0x0000FF);
int state = ((((int) codePage.getData()[8 * (IR - 1) + 3]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 2]) & 0x0000FF);
int argument = ((((int) codePage.getData()[8 * (IR - 1) + 5]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 4]) & 0x0000FF);
currentInstrction.setId(id);
currentInstrction.setState(state);
currentInstrction.setArgument(argument);
currentInstrction.setExtra(this.runningPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra());
this.manager.getDashboard().consoleLog("执行进程 " + this.runningPCB.getId() + " :" +
" 指令 " + currentInstrction.getId() +
" 类型 " + currentInstrction.getState() +
" 参数 " + currentInstrction.getArgument() +
" 附加数据 " + currentInstrction.getExtra());
switch (currentInstrction.getState()) {
// 0 system 系统调用,本系统中仿真为输入、输出、创建文件操作
case 0: {
int type = currentInstrction.getArgument();
String extra = currentInstrction.getExtra();
if (type == 0) {
// 创建文件
this.interrupt(InterruptVector.CREATE_FILE_INTERRUPT, 0);
} else if (type == 1) {
// 输入操作
try {
int logicAddress = (this.runningPCB.getDataSegment().getLogicPageStartNo() + Integer.parseInt(extra.split(" ")[0])) * InternalMem.PAGE_SIZE;
String filePath = extra.split(" ")[1];
short physicAddress = this.manager.getMmu().resolveLogicAddress((short) logicAddress, this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存当前时间片
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, logicAddress / InternalMem.PAGE_SIZE);
} else {
this.runningPCB.accessPage(logicAddress / InternalMem.PAGE_SIZE);
this.interrupt(InterruptVector.INPUT_INTERRUPT, physicAddress / InternalMem.PAGE_SIZE);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (type == 2) {
// 输出操作
int logicAddress = (this.runningPCB.getDataSegment().getLogicPageStartNo() + Integer.parseInt(extra.split(" ")[0])) * InternalMem.PAGE_SIZE;
String filePath = extra.split(" ")[1];
short physicAddress = this.manager.getMmu().resolveLogicAddress((short) logicAddress, this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存当前时间片
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, logicAddress / InternalMem.PAGE_SIZE);
} else {
this.runningPCB.accessPage(logicAddress / InternalMem.PAGE_SIZE);
this.interrupt(InterruptVector.OUTPUT_INTERRUPT, physicAddress / InternalMem.PAGE_SIZE);
}
} else if (type == 3) {
// 关闭文件
this.interrupt(InterruptVector.CLOSE_FILE_INTERRUPT, 0);
}
break;
}
// 1 calculate 计算指令,CPU不需要调用任何额外资源,可直接运行
case 1: {
// CPU内部进行计算操作,不做任何处理
this.manager.getDashboard().consoleLog("计算指令");
break;
}
// 2 load 读取指令,对内存数据进行读取
case 2: {
// 解析逻辑地址,返回 -1,则表示缺页
short physicAddress = this.manager.getMmu().resolveLogicAddress((short)currentInstrction.getArgument(), this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存 <SUF>
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
} else {
this.manager.getAddressLine().setAddress(physicAddress);
short loadData = this.manager.getInMem().readData(this.manager.getAddressLine());
this.runningPCB.accessPage(currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
this.manager.getDashboard().consoleLog("从内存地址" + physicAddress + " 读取数据 " + loadData);
}
break;
}
// 3 store 写入指令,对内存数据进行写入
case 3: {
// 解析逻辑地址,返回 -1,则表示缺页
short physicAddress = this.manager.getMmu().resolveLogicAddress((short)currentInstrction.getArgument(), this.runningPCB.getPageTableBaseAddress());
if (physicAddress == -1) {
// 出现缺页,则PC、IR回退一步
--this.IR;
--this.PC;
// 保存当前时间片
this.missPageRemainTimeSlice = this.timeSlice;
// 发出缺页中断请求
this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
} else {
this.manager.getAddressLine().setAddress(physicAddress);
this.manager.getDataLine().setData((short)0x6666);
this.manager.getInMem().writeData(this.manager.getAddressLine(), this.manager.getDataLine());
this.runningPCB.accessPage(currentInstrction.getArgument() / InternalMem.PAGE_SIZE);
// 设置页表项修改位为1
int pageItemAddress = this.runningPCB.getPageTableBaseAddress() +
currentInstrction.getArgument() / InternalMem.PAGE_SIZE * InternalMem.PAGE_TABLE_ITEM_SIZE;
this.manager.getAddressLine().setAddress((short) pageItemAddress);
Page page = this.manager.getInMem().readPageItem(this.manager.getAddressLine());
page.setModifyFlag(1);
this.manager.getAddressLine().setAddress((short) pageItemAddress);
this.manager.getInMem().writePageItem(this.manager.getAddressLine(), page);
this.manager.getDashboard().consoleLog("向内存地址" + physicAddress + " 写入数据 " + 0x6666);
}
break;
}
// 4 switch 进程切换,直接进行调度
case 4: {
// 时间片置1,执行指令后时间片统一 -1,完成进程强制切换
this.timeSlice = 1;
this.manager.getDashboard().consoleLog("切换指令");
break;
}
// 5 jump 跳转指令,跳过代码段执行
case 5: {
// 设置PC指向跳转地址
this.PC = currentInstrction.getArgument();
this.manager.getDashboard().consoleLog("跳转指令");
break;
}
// 6 apply 资源申请,申请一个系统资源
case 6: {
// 发出资源申请中断
this.interrupt(InterruptVector.APPLY_RESOURCE_INTERRUPT, currentInstrction.getArgument());
break;
}
// 7 release 资源释放,释放一个系统资源
case 7: {
// 发出资源释放中断
this.interrupt(InterruptVector.RELEASE_RESOURCE_INTERRUPT, currentInstrction.getArgument());
break;
}
default: {
break;
}
}
// 时间片 -1
--this.timeSlice;
}
/**
* 恢复CPU现场
* @param pcb 即将进入运行态的进程 PCB
*/
public synchronized void recoverSpot(PCB pcb) {
this.PC = pcb.getPC();
this.IR = pcb.getIR();
this.timeSlice = Schedule.SYSTEM_TIME_SLICE;
// 进程设置运行态
this.runningPCB = pcb;
// 初始化快表
this.manager.getMmu().initTLB();
// 如果因为缺页中断而恢复CPU现场,则使用之前的时间片
if (this.missPageRemainTimeSlice != 0) {
this.timeSlice = this.missPageRemainTimeSlice;
this.missPageRemainTimeSlice = 0;
}
// 更新GUI
this.manager.getDashboard().refreshRunningProcess();
}
/**
* 保护CPU现场
*/
public synchronized void protectSpot() {
this.runningPCB.setIR((short)this.IR);
this.runningPCB.setPC((short)this.PC);
// 进程解除运行态
this.runningPCB = null;
// 更新GUI
this.manager.getDashboard().refreshRunningProcess();
}
/**
* 打开调度
*/
public synchronized void openSchedule() {
this.canSchedule = true;
}
/**
* 关闭调度
*/
public synchronized void closeSchedule() {
this.canSchedule = false;
}
/**
* 切换内核态
*/
public synchronized void switchToKernelState() {
if (this.PSW == KERNEL_STATE) {
return;
}
this.PSW = KERNEL_STATE;
this.manager.getDashboard().consoleLog("CPU -> 内核态");
this.manager.getDashboard().refreshCPU();
}
/**
* 切换用户态
*/
public synchronized void switchToUserState() {
if (this.PSW == USER_STATE) {
return;
}
this.PSW = USER_STATE;
this.manager.getDashboard().consoleLog("CPU -> 用户态");
this.manager.getDashboard().refreshCPU();
}
public Manager getManager() {
return manager;
}
public void setManager(Manager manager) {
this.manager = manager;
}
public int getPC() {
return PC;
}
public void setPC(int PC) {
this.PC = PC;
}
public int getIR() {
return IR;
}
public void setIR(int IR) {
this.IR = IR;
}
public int getPSW() {
return PSW;
}
public void setPSW(int PSW) {
this.PSW = PSW;
}
public PCB getRunningPCB() {
return runningPCB;
}
public void setRunningPCB(PCB runningPCB) {
this.runningPCB = runningPCB;
}
public boolean isCanSchedule() {
return canSchedule;
}
public void setCanSchedule(boolean canSchedule) {
this.canSchedule = canSchedule;
}
public int getTimeSlice() {
return timeSlice;
}
public void setTimeSlice(int timeSlice) {
this.timeSlice = timeSlice;
}
}
| 0 |
33085_3 | package com.zhangfan.learn.classfile.attributeinfo;
//import com.sun.org.apache.bcel.internal.generic.Instruction;
import com.zhangfan.learn.UKind;
import com.zhangfan.learn.classfile.Count;
import com.zhangfan.learn.classfile.constant.ConstantInfo;
import com.zhangfan.learn.classfile.instruction.Instruction;
import com.zhangfan.learn.classfile.instruction.InstructionFactory;
import java.io.FileInputStream;
import java.util.stream.IntStream;
public class Code extends Attribute {
// Code出现在方法的属性集合表中
private Count maxStack; // 操作数栈深度的最大值。在方法执行的任意时刻,操作数栈都不会超过这个深度。
private Count maxLocals; // 局部变量所需的存储空间。在这里,max_local的单位是slot,slot是虚拟机为局部变量分配内存所使用的最小单位
/**
* code_length 和 code用来存储Java
* 源程序编译后生成的字节码指令。
* code_length 用来代表字节码的长度,
* code 是用于存储字节码指令的一系列字节流。
* 既然叫字节码指令,那么每个指令就是一个u1类型的单字节,当虚拟机读取到code中的一个字节码的时候,
* 就可以找到对应这个字节码代表的是什么指令,并且可以知道这条指令后面是否需要跟随参数,以及参数应当如何理解
* 我们知道一个u1数据结构的取值范围是0-255,也就是总共256条指令,目前,java虚拟机规范定义了其中约200条
* 对应的指令含义,编码与指令之间的对应关系可以啥表得知
* 既然
* ***/
private Count codeLength;
private Instruction[] codes; // 长度为codeLength
private Count exceptionTableLength;
private CodeException[] exceptionTable; // 长度为exceptionTableLength
private Count attributesCount;
private Attribute[] attributes;
public Code(FileInputStream fi, ConstantInfo[] constantPool) {
super(fi);
maxStack = new Count(fi);
maxLocals = new Count(fi);
codeLength = new Count(fi, UKind.U4);
codes = new Instruction[codeLength.getNum()];
// IntStream.range(0,codeLength.getNum()).forEach(i->
// codes[i] = InstructionFactory.getInstruction(fi)
// );
exceptionTableLength = new Count(fi);
exceptionTable = new CodeException[exceptionTableLength.getNum()];
IntStream.range(0, exceptionTableLength.getNum()).forEach(i->{
exceptionTable[i] = new CodeException(fi);
});
attributesCount = new Count(fi);
attributes = new Attribute[attributesCount.getNum()];
IntStream.range(0,attributesCount.getNum()).forEach(i->{
attributes[i] = Attribute.readAttribute(fi, constantPool);
});
}
}
| 413180794/JavaDecompiler | src/com/zhangfan/learn/classfile/attributeinfo/Code.java | 694 | // 局部变量所需的存储空间。在这里,max_local的单位是slot,slot是虚拟机为局部变量分配内存所使用的最小单位 | line_comment | zh-cn | package com.zhangfan.learn.classfile.attributeinfo;
//import com.sun.org.apache.bcel.internal.generic.Instruction;
import com.zhangfan.learn.UKind;
import com.zhangfan.learn.classfile.Count;
import com.zhangfan.learn.classfile.constant.ConstantInfo;
import com.zhangfan.learn.classfile.instruction.Instruction;
import com.zhangfan.learn.classfile.instruction.InstructionFactory;
import java.io.FileInputStream;
import java.util.stream.IntStream;
public class Code extends Attribute {
// Code出现在方法的属性集合表中
private Count maxStack; // 操作数栈深度的最大值。在方法执行的任意时刻,操作数栈都不会超过这个深度。
private Count maxLocals; // 局部 <SUF>
/**
* code_length 和 code用来存储Java
* 源程序编译后生成的字节码指令。
* code_length 用来代表字节码的长度,
* code 是用于存储字节码指令的一系列字节流。
* 既然叫字节码指令,那么每个指令就是一个u1类型的单字节,当虚拟机读取到code中的一个字节码的时候,
* 就可以找到对应这个字节码代表的是什么指令,并且可以知道这条指令后面是否需要跟随参数,以及参数应当如何理解
* 我们知道一个u1数据结构的取值范围是0-255,也就是总共256条指令,目前,java虚拟机规范定义了其中约200条
* 对应的指令含义,编码与指令之间的对应关系可以啥表得知
* 既然
* ***/
private Count codeLength;
private Instruction[] codes; // 长度为codeLength
private Count exceptionTableLength;
private CodeException[] exceptionTable; // 长度为exceptionTableLength
private Count attributesCount;
private Attribute[] attributes;
public Code(FileInputStream fi, ConstantInfo[] constantPool) {
super(fi);
maxStack = new Count(fi);
maxLocals = new Count(fi);
codeLength = new Count(fi, UKind.U4);
codes = new Instruction[codeLength.getNum()];
// IntStream.range(0,codeLength.getNum()).forEach(i->
// codes[i] = InstructionFactory.getInstruction(fi)
// );
exceptionTableLength = new Count(fi);
exceptionTable = new CodeException[exceptionTableLength.getNum()];
IntStream.range(0, exceptionTableLength.getNum()).forEach(i->{
exceptionTable[i] = new CodeException(fi);
});
attributesCount = new Count(fi);
attributes = new Attribute[attributesCount.getNum()];
IntStream.range(0,attributesCount.getNum()).forEach(i->{
attributes[i] = Attribute.readAttribute(fi, constantPool);
});
}
}
| 0 |
17583_23 | //傻瓜理解版
package GUI;
import Listener.*;
import ProjectViewer.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Vector;
public class GUI extends JFrame {
public static JFrame j1;//主窗口
public static Container c1;//主窗口的容器
public static Container pv1,pv2,pv3,pv4,pv5,pv6;//项目管理器的容器
public static JTextArea jt1;//写字区域
public static JList jlt1;//代码提示窗口
public static JList pvl1,pvl2,pvl3,pvl4,pvl5,pvl6;//项目管理器窗口栏
public static Vector vector1;//代码提示容器
public static Vector pvv1,pvv2,pvv3,pvv4,pvv5,pvv6;//项目管理器容器
public static JMenuBar jm1;//菜单栏
public static JMenu jmu1;//菜单容器
public static JMenuItem jmi1,jmi2,jmi3,jmi4;//仨菜单按钮
public static JTabbedPane jp1;//项目结构
public GUI(){
//给主窗口设置它的属性
j1=new JFrame("Mindustry Mod Maker");//创建新对象
j1.setLayout(null);//更改组件的排序(null是不自动排序)
j1.setSize(1500,800);//窗口大小
j1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//点击退出按钮的时候发生什么
c1=j1.getContentPane();//把c1这个容器设置成j1用的(容器是用来装组件的)
//菜单栏的设置
jm1=new JMenuBar();;
//下拉内容的设置
jmu1=new JMenu("选项");
jm1.add(jmu1);
//仨按钮
jmi1=new JMenuItem("保存");//保存
jmi1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION){
File file=jfc.getSelectedFile();
try {
FileWriter f=new FileWriter(file);
f.write(jt1.getText());
f.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi2=new JMenuItem("打开");
jmi2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION) {
File file=jfc.getSelectedFile();
StringBuilder result = new StringBuilder();
try {
BufferedReader bf=new BufferedReader(new FileReader(file));
String s;
while((s = bf.readLine())!=null){
result.append(System.lineSeparator()+s);
}
bf.close();
jt1.setText(result.toString());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi3=new JMenuItem("打开项目");
jmi3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectViewer pj=new ProjectViewer();
}
});
jmi4=new JMenuItem("项目管理器");
jmi4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectManagement pj=new ProjectManagement("项目管理器");
}
});
//
pv1=new Container();
pv2=new Container();
pv3=new Container();
pv4=new Container();
pv5=new Container();
pv6=new Container();
//
jmu1.add(jmi1);
jmu1.add(jmi2);
jmu1.add(jmi3);
jmu1.add(jmi4);
jmi2=new JMenuItem();//打开
//项目管理器
jp1=new JTabbedPane();
jp1.setBounds(0,300,300,300);
jp1.addTab("items",pv1);
jp1.addTab("liquids",pv2);
jp1.addTab("blocks",pv3);
jp1.addTab("mechs",pv4);
jp1.addTab("units",pv5);
jp1.addTab("scripts",pv6);
//
pvv1=new Vector();
pvv2=new Vector();
pvv3=new Vector();
pvv4=new Vector();
pvv5=new Vector();
pvv6=new Vector();
//
pvl1=new JList(pvv1);
pvl1.setSize(300,300);
pvl1.addListSelectionListener(new ItemProjectListener());
pvl2=new JList(pvv2);
pvl2.setSize(300,300);
pvl2.addListSelectionListener(new LiquidProjectListener());
pvl3=new JList(pvv3);
pvl3.setSize(300,300);
pvl3.addListSelectionListener(new BlockProjectListener());
pvl4=new JList(pvv4);
pvl4.setSize(300,300);
pvl4.addListSelectionListener(new MechProjectListener());
pvl5=new JList(pvv5);
pvl5.setSize(300,300);
pvl5.addListSelectionListener(new UnitProjectListener());
pvl6=new JList(pvv6);
pvl6.setSize(300,300);
pvl6.addListSelectionListener(new ScriptProjectListener());
//
pv1.add(pvl1);
pv2.add(pvl2);
pv3.add(pvl3);
pv4.add(pvl4);
pv5.add(pvl5);
pv6.add(pvl6);
c1.add(jp1);
// 给写字的地方设置属性
jt1=new JTextArea();
jt1.setBounds(325,25,750,700);
jt1.addKeyListener(new CodeLIstener());
c1.add(jt1);
//向量初始化
vector1=new Vector();
//代码提示
jlt1=new JList(vector1);
jlt1.addListSelectionListener(new ListLIstener());
jlt1.setBounds(0,0,300,300);
c1.add(jlt1);
j1.setJMenuBar(jm1);
j1.setVisible(true);//主窗口是否可见(放在最后免得刷新)
}
}
| 4156/MindustryModMaker | src/GUI/GUI.java | 1,667 | // 给写字的地方设置属性 | line_comment | zh-cn | //傻瓜理解版
package GUI;
import Listener.*;
import ProjectViewer.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Vector;
public class GUI extends JFrame {
public static JFrame j1;//主窗口
public static Container c1;//主窗口的容器
public static Container pv1,pv2,pv3,pv4,pv5,pv6;//项目管理器的容器
public static JTextArea jt1;//写字区域
public static JList jlt1;//代码提示窗口
public static JList pvl1,pvl2,pvl3,pvl4,pvl5,pvl6;//项目管理器窗口栏
public static Vector vector1;//代码提示容器
public static Vector pvv1,pvv2,pvv3,pvv4,pvv5,pvv6;//项目管理器容器
public static JMenuBar jm1;//菜单栏
public static JMenu jmu1;//菜单容器
public static JMenuItem jmi1,jmi2,jmi3,jmi4;//仨菜单按钮
public static JTabbedPane jp1;//项目结构
public GUI(){
//给主窗口设置它的属性
j1=new JFrame("Mindustry Mod Maker");//创建新对象
j1.setLayout(null);//更改组件的排序(null是不自动排序)
j1.setSize(1500,800);//窗口大小
j1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//点击退出按钮的时候发生什么
c1=j1.getContentPane();//把c1这个容器设置成j1用的(容器是用来装组件的)
//菜单栏的设置
jm1=new JMenuBar();;
//下拉内容的设置
jmu1=new JMenu("选项");
jm1.add(jmu1);
//仨按钮
jmi1=new JMenuItem("保存");//保存
jmi1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION){
File file=jfc.getSelectedFile();
try {
FileWriter f=new FileWriter(file);
f.write(jt1.getText());
f.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi2=new JMenuItem("打开");
jmi2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION) {
File file=jfc.getSelectedFile();
StringBuilder result = new StringBuilder();
try {
BufferedReader bf=new BufferedReader(new FileReader(file));
String s;
while((s = bf.readLine())!=null){
result.append(System.lineSeparator()+s);
}
bf.close();
jt1.setText(result.toString());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi3=new JMenuItem("打开项目");
jmi3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectViewer pj=new ProjectViewer();
}
});
jmi4=new JMenuItem("项目管理器");
jmi4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectManagement pj=new ProjectManagement("项目管理器");
}
});
//
pv1=new Container();
pv2=new Container();
pv3=new Container();
pv4=new Container();
pv5=new Container();
pv6=new Container();
//
jmu1.add(jmi1);
jmu1.add(jmi2);
jmu1.add(jmi3);
jmu1.add(jmi4);
jmi2=new JMenuItem();//打开
//项目管理器
jp1=new JTabbedPane();
jp1.setBounds(0,300,300,300);
jp1.addTab("items",pv1);
jp1.addTab("liquids",pv2);
jp1.addTab("blocks",pv3);
jp1.addTab("mechs",pv4);
jp1.addTab("units",pv5);
jp1.addTab("scripts",pv6);
//
pvv1=new Vector();
pvv2=new Vector();
pvv3=new Vector();
pvv4=new Vector();
pvv5=new Vector();
pvv6=new Vector();
//
pvl1=new JList(pvv1);
pvl1.setSize(300,300);
pvl1.addListSelectionListener(new ItemProjectListener());
pvl2=new JList(pvv2);
pvl2.setSize(300,300);
pvl2.addListSelectionListener(new LiquidProjectListener());
pvl3=new JList(pvv3);
pvl3.setSize(300,300);
pvl3.addListSelectionListener(new BlockProjectListener());
pvl4=new JList(pvv4);
pvl4.setSize(300,300);
pvl4.addListSelectionListener(new MechProjectListener());
pvl5=new JList(pvv5);
pvl5.setSize(300,300);
pvl5.addListSelectionListener(new UnitProjectListener());
pvl6=new JList(pvv6);
pvl6.setSize(300,300);
pvl6.addListSelectionListener(new ScriptProjectListener());
//
pv1.add(pvl1);
pv2.add(pvl2);
pv3.add(pvl3);
pv4.add(pvl4);
pv5.add(pvl5);
pv6.add(pvl6);
c1.add(jp1);
// 给写 <SUF>
jt1=new JTextArea();
jt1.setBounds(325,25,750,700);
jt1.addKeyListener(new CodeLIstener());
c1.add(jt1);
//向量初始化
vector1=new Vector();
//代码提示
jlt1=new JList(vector1);
jlt1.addListSelectionListener(new ListLIstener());
jlt1.setBounds(0,0,300,300);
c1.add(jlt1);
j1.setJMenuBar(jm1);
j1.setVisible(true);//主窗口是否可见(放在最后免得刷新)
}
}
| 0 |
43655_1 | package Models;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import main.Main;
//本类用于显示一个弹出提示窗口
public class WarningStage extends Stage {
private VBox pane;
private static Button OKbutton;
private static Text TextTitle, TextWarning, TextTips;
public WarningStage() {
super();
pane = new VBox();
pane.setSpacing(30);
TextTitle = new Text();
TextWarning = new Text();
TextTips = new Text();
//增加确认按钮
OKbutton = new Button("确认");
OKbutton.setMinSize(100, 50);
OKbutton.setCursor(Cursor.CLOSED_HAND);
//绑定按钮处理器
OKbutton.setOnAction(new ConfirmHandle(this));
//设置面板内容
TextWarning.setFill(Color.RED);
TextTitle.setFill(Color.RED);
TextWarning.setFont(Font.font(25));
pane.getChildren().add(TextWarning);
pane.getChildren().add(TextTips);
pane.getChildren().add(OKbutton);
pane.setAlignment(Pos.TOP_CENTER);
// 窗体属性设置
this.setResizable(false);
this.setScene(new Scene(pane, 400, 200));
this.getIcons().add(new Image(Main.class.getResourceAsStream("/resource/images/warning.png")));
/*阻止stage对象在隐藏时被系统关闭,防止产生空指针异常*/
this.setOnCloseRequest(e -> {
this.hide();
e.consume();
});
}
/*设置提示内容*/
public void setContents(String stagetitle, String warningText, String Tips) {
TextTitle.setText(stagetitle);
TextWarning.setText(warningText);
TextTips.setText(Tips);
this.setTitle(TextTitle.getText().toString());
this.centerOnScreen();
this.setAlwaysOnTop(true);
this.requestFocus();
this.show();
}
//关闭提示窗口
class ConfirmHandle implements EventHandler<ActionEvent> {
Stage closestag;
public ConfirmHandle(Stage stg) {
// TODO Auto-generated constructor stub
closestag = stg;
}
@Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
closestag.hide();
}
}
}
| 425868130/CpuDemo | src/Models/WarningStage.java | 636 | //增加确认按钮 | line_comment | zh-cn | package Models;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import main.Main;
//本类用于显示一个弹出提示窗口
public class WarningStage extends Stage {
private VBox pane;
private static Button OKbutton;
private static Text TextTitle, TextWarning, TextTips;
public WarningStage() {
super();
pane = new VBox();
pane.setSpacing(30);
TextTitle = new Text();
TextWarning = new Text();
TextTips = new Text();
//增加 <SUF>
OKbutton = new Button("确认");
OKbutton.setMinSize(100, 50);
OKbutton.setCursor(Cursor.CLOSED_HAND);
//绑定按钮处理器
OKbutton.setOnAction(new ConfirmHandle(this));
//设置面板内容
TextWarning.setFill(Color.RED);
TextTitle.setFill(Color.RED);
TextWarning.setFont(Font.font(25));
pane.getChildren().add(TextWarning);
pane.getChildren().add(TextTips);
pane.getChildren().add(OKbutton);
pane.setAlignment(Pos.TOP_CENTER);
// 窗体属性设置
this.setResizable(false);
this.setScene(new Scene(pane, 400, 200));
this.getIcons().add(new Image(Main.class.getResourceAsStream("/resource/images/warning.png")));
/*阻止stage对象在隐藏时被系统关闭,防止产生空指针异常*/
this.setOnCloseRequest(e -> {
this.hide();
e.consume();
});
}
/*设置提示内容*/
public void setContents(String stagetitle, String warningText, String Tips) {
TextTitle.setText(stagetitle);
TextWarning.setText(warningText);
TextTips.setText(Tips);
this.setTitle(TextTitle.getText().toString());
this.centerOnScreen();
this.setAlwaysOnTop(true);
this.requestFocus();
this.show();
}
//关闭提示窗口
class ConfirmHandle implements EventHandler<ActionEvent> {
Stage closestag;
public ConfirmHandle(Stage stg) {
// TODO Auto-generated constructor stub
closestag = stg;
}
@Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
closestag.hide();
}
}
}
| 0 |
56026_10 | package com.live.fox.ui.live;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.github.mmin18.widget.RealtimeBlurView;
import com.live.fox.AppIMManager;
import com.live.fox.Constant;
import com.live.fox.R;
import com.live.fox.common.CommonApp;
import com.live.fox.dialog.DialogFactory;
import com.live.fox.entity.Anchor;
import com.live.fox.receiver.TXPhoneStateListener;
import com.live.fox.utils.ActivityUtils;
import com.live.fox.utils.ClickUtil;
import com.live.fox.utils.GlideUtils;
import com.live.fox.utils.LogUtils;
import com.live.fox.utils.PlayerUtils;
import com.live.fox.utils.TCConstants;
import com.live.fox.utils.ToastUtils;
import com.live.fox.windowmanager.WindowUtils;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
/**
* Date: 2016/3/27
* Time: 19:40
*/
public class VideoFragment extends Fragment implements ITXLivePlayListener, View.OnClickListener {
private ImageView iv_bg;
private TXCloudVideoView mTXCloudVideoView;
private ImageView mLoadingView; //正在加载
private ImageView coverIv; //视频封面
private RealtimeBlurView blurView; //视频封面
private RelativeLayout videoFrameLayout;
private ImageView ivCloseWindow;
private TextView tv_window;
private Anchor anchor;
private TXLivePlayConfig mTXPlayConfig;
private static String roomPaid;
private static String roomPassword;
public static VideoFragment newInstance(Anchor anchor) {
VideoFragment fragment = new VideoFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("anchor", anchor);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (getArguments() != null) {
this.anchor = (Anchor) bundle.getSerializable("anchor");
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.video_fragment, container, false);
initView(view);
if (anchor != null) {
GlideUtils.loadImage(requireActivity(), anchor.getAvatar(),
R.drawable.liveing_star,
R.drawable.liveing_star, coverIv);
try {
initPlayer();
} catch (Exception e) {
ToastUtils.showShort(getString(R.string.playerInitialException));
}
//电话状态监听
CommonApp.mPhoneListener = new TXPhoneStateListener(Constant.mTXLivePlayer);
TelephonyManager tm = (TelephonyManager)
requireActivity().getSystemService(Service.TELEPHONY_SERVICE);
tm.listen(CommonApp.mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
return view;
}
private void initView(View bindSource) {
iv_bg = bindSource.findViewById(R.id.iv_bg);
mTXCloudVideoView = bindSource.findViewById(R.id.live_play_video_view);
mLoadingView = bindSource.findViewById(R.id.loading);
coverIv = bindSource.findViewById(R.id.iv_conver);
blurView = bindSource.findViewById(R.id.blur);
videoFrameLayout = bindSource.findViewById(R.id.frame_video_layout_push);
ivCloseWindow = bindSource.findViewById(R.id.iv_close_window);
tv_window = bindSource.findViewById(R.id.tv_window);
bindSource.findViewById(R.id.iv_close_window).setOnClickListener(this);
bindSource.findViewById(R.id.live_play_video_view).setOnClickListener(this);
bindSource.findViewById(R.id.iv_conver).setOnClickListener(this);
roomPaid = getString(R.string.live_change_to_paid);
roomPassword = getString(R.string.live_change_to_password);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//打开fragment后加载video 不是1和3状态
if(anchor!=null && anchor.getLiveStatus()!=1 && anchor.getLiveStatus()!=3)
{
startPlay(anchor);
}
}
private void initPlayer() {
if (Constant.mTXLivePlayer == null) {
Constant.mTXLivePlayer = new TXLivePlayer(requireContext());
}
mTXPlayConfig = new TXLivePlayConfig();
setPlayMode(2);
}
//设置播放器模式
public void setPlayMode(int strategy) {
if (mTXPlayConfig == null) {
return;
}
switch (strategy) {
case 0: // 極速
mTXPlayConfig.setAutoAdjustCacheTime(true);
mTXPlayConfig.setMinAutoAdjustCacheTime(1);
mTXPlayConfig.setMaxAutoAdjustCacheTime(1);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
break;
case 1: // 流暢
mTXPlayConfig.setAutoAdjustCacheTime(false);
mTXPlayConfig.setMinAutoAdjustCacheTime(5);
mTXPlayConfig.setMaxAutoAdjustCacheTime(5);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
break;
case 2: // 自動
mTXPlayConfig.setAutoAdjustCacheTime(true);
mTXPlayConfig.setMinAutoAdjustCacheTime(1);
mTXPlayConfig.setMaxAutoAdjustCacheTime(5);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
break;
}
}
/**
* 切换房间时 根据状态显示 不一样的界面
*
* @param state
* @param anchor
*/
public void switchRoomByState(int state, Anchor anchor) {
LogUtils.e("切换房间时 根据状态显示 不一样的界面" + state);
this.anchor = anchor;
if (!isAdded()) return;
if (state == 1) {//切换后请求接口时的处理
if (Constant.mTXLivePlayer != null && Constant.mTXLivePlayer.isPlaying()) {
Constant.mTXLivePlayer.stopPlay(true);
}
if (coverIv != null) {
coverIv.setVisibility(View.VISIBLE);
blurView.setVisibility(View.VISIBLE);
GlideUtils.loadDefaultImage(getActivity(), anchor.getAvatar(), coverIv);
}
showLiveLoadingAnimation();
}
}
public void startPlay(Anchor anchor) {
this.anchor = anchor;
if (!isAdded()) return;
playRTMP(anchor.getPullStreamUrl());
}
private void fromWindow() {
if (Constant.isOpenWindow) {
AppIMManager.ins().removeMessageReceivedListener(PlayLiveActivity.class);
Constant.isOpenWindow = false;
PlayLiveActivity.startActivity(ActivityUtils.getTopActivity(), Constant.windowAnchor);
}
}
public void changeWindowText(Anchor currentAnchor) {
anchor = currentAnchor;
if (3 == anchor.getType()) {
tv_window.setVisibility(View.VISIBLE);
tv_window.setText(roomPaid);
coverIv.setVisibility(View.VISIBLE);
GlideUtils.loadImage(CommonApp.getInstance(), currentAnchor.getAvatar(),
R.drawable.liveing_star, R.drawable.liveing_star, coverIv);
stopPlay(true);
} else if (0 == anchor.getType()) {
tv_window.setVisibility(View.GONE);
coverIv.setVisibility(View.GONE);
playRTMP(anchor.getPullStreamUrl());
} else {
tv_window.setVisibility(View.VISIBLE);
tv_window.setText(roomPassword);
coverIv.setVisibility(View.VISIBLE);
GlideUtils.loadImage(CommonApp.getInstance(), currentAnchor.getAvatar(),
R.drawable.liveing_star, R.drawable.liveing_star, coverIv);
stopPlay(true);
}
}
/**
* 添加到Window
*/
public void onClickAddToWindow() {
if (Constant.isShowWindow) {
ivCloseWindow.setVisibility(View.VISIBLE);
Constant.isOpenWindow = true;//是否开启小窗口
}
}
/**
* 从Window移除
*/
public void onClickRemoveFromWindow() {
Constant.isShowWindow = false;
Constant.isOpenWindow = false;
if (Constant.windowAnchor != null) {
AppIMManager.ins().loginOutGroup(String.valueOf(Constant.windowAnchor.getLiveId()));
}
WindowUtils.closeWindowResource(PlayLiveActivity.class);
}
//停止播放并清空播放事件
public void clearStop() {
LogUtils.e("clearStop");
if (Constant.mTXLivePlayer != null) {
Constant.mTXLivePlayer.stopPlay(false);
Constant.mTXLivePlayer.setPlayerView(null);
Constant.mTXLivePlayer.setPlayListener(null);
}
}
public void changePKVideo(boolean isPK) {
LogUtils.e("isPK==" + isPK);
Constant.isPK = isPK;
mTXPlayConfig.enableAEC(isPK);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
if (!Constant.isOpenWindow) {
adjustFullScreenVideoView(!isPK);
}
}
public void adjustFullScreenVideoView(boolean fullScreen) {
if (videoFrameLayout.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) videoFrameLayout.getLayoutParams();
if (fullScreen) {
LogUtils.e("全屏");
layoutParams.removeRule(RelativeLayout.BELOW);
layoutParams.removeRule(RelativeLayout.ABOVE);
iv_bg.setVisibility(View.GONE);
} else {
LogUtils.e("PK 小屏");
layoutParams.addRule(RelativeLayout.BELOW, R.id.frame_layout_pross);
layoutParams.addRule(RelativeLayout.ABOVE, R.id.view_center);
iv_bg.setVisibility(View.VISIBLE);
}
videoFrameLayout.setLayoutParams(layoutParams);
}
}
private void playRTMP(String streamUrl) {
LogUtils.e("streamUrl " + streamUrl);
int mUrlPlayType = TXLivePlayer.PLAY_TYPE_LIVE_RTMP;
if (0 == anchor.getLiveStatus()) {
streamUrl = anchor.getAdJumpUrl();
mUrlPlayType = TXLivePlayer.PLAY_TYPE_VOD_MP4;
} else if (1 == anchor.getLiveStatus() || 3 == anchor.getLiveStatus()) {
if (!PlayerUtils.checkPlayUrl(streamUrl, requireContext())) {
ToastUtils.showShort(getString(R.string.illegalStreaming));
return;
}
if (Constant.mTXLivePlayer == null) {
LogUtils.e("Constant.mTXLivePlayer为空");
return;
}
if ((streamUrl.startsWith(PlayerUtils.HTTP) ||
streamUrl.startsWith(PlayerUtils.HTTPS)) && streamUrl.contains(PlayerUtils.FLV)) {
mUrlPlayType = TXLivePlayer.PLAY_TYPE_LIVE_FLV;
}
}
Constant.mTXLivePlayer.setPlayerView(mTXCloudVideoView);
Constant.mTXLivePlayer.setPlayListener(this);
// 硬件加速在1080p解码场景下效果显著,但细节之处并不如想象的那么美好:
// (1) 只有 4.3 以上android系统才支持
// (2) 兼容性我们目前还仅过了小米华为等常见机型,故这里的返回值您先不要太当真
Constant.mTXLivePlayer.enableHardwareDecode(false);
Constant.mTXLivePlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
Constant.mTXLivePlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
LogUtils.e("直播流 " + streamUrl + "," + mUrlPlayType);
int result = Constant.mTXLivePlayer.startPlay(streamUrl, mUrlPlayType);
Constant.isShowWindow = true;
LogUtils.e("拉流返回值 result " + result);
if (0 != result) {
Intent rstData = new Intent();
if (-1 != result) {
ToastUtils.showShort(R.string.splbfsb);
}
rstData.putExtra(TCConstants.ACTIVITY_RESULT, getString(R.string.linkRestrictions));
if (mTXCloudVideoView != null) {
mTXCloudVideoView.onPause();
}
}
showLiveLoadingAnimation();
}
private void showLiveLoadingAnimation() {
if (mLoadingView != null) {
mLoadingView.setVisibility(View.VISIBLE);
((AnimationDrawable) mLoadingView.getDrawable()).start();
}
}
public void dismissLiveLoadingAnimation() {
if (!isAdded()) return;
if (coverIv != null) {
LogUtils.e("dimissLiveLoadingAnimation()");
coverIv.setVisibility(View.GONE);
blurView.setVisibility(View.GONE);
}
if (mLoadingView != null) {
mLoadingView.setVisibility(View.GONE);
((AnimationDrawable) mLoadingView.getDrawable()).stop();
}
}
/**
* 播放事件
* 正常流程:
* 2007, 视频缓冲中...
* 2001, 已连接服务器
* 2002, 开始拉流
* 2004, 视频播放开始
* 2008, 启动软解
* (如果网络慢,到下一步会有一段时间)
* 2003, 渲染首个视频数据包(IDR)
* 2009, 分辨率改变为368x640
* <p>
* 出现卡顿流程:
* 2007, 视频缓冲中...
* 2004, 视频播放开始
* 2105, 当前视频播放出现卡顿1816ms
*/
@Override
public void onPlayEvent(int event, Bundle param) {
LogUtils.e("视频播放状态监听 " + event + ", " + param.getString(TXLiveConstants.EVT_DESCRIPTION));
if (event == TXLiveConstants.PLAY_EVT_CONNECT_SUCC) {
// 2001 連接服務器成功
} else if (event == TXLiveConstants.PLAY_EVT_RTMP_STREAM_BEGIN) {
// 2002 已經連接服務器,開始拉流(僅播放RTMP地址時會抛送)
// dimissLiveLoadingAnimation();
// content.setBackground(null);
} else if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {
// 2003 網絡接收到首個可渲染的視頻數據包(IDR)
dismissLiveLoadingAnimation();
LogUtils.e(Constant.mTXLivePlayer.isPlaying() + ",");
LogUtils.e((Constant.mTXLivePlayer == null) + ",");
LogUtils.e((mTXCloudVideoView == null) + ",");
listener.onPlayIsFinish(true);
} else if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {
// 2004 視頻播放開始,如果有轉菊花什麽的這個時候該停了
if (coverIv.getVisibility() == View.VISIBLE) {
//说明是第一次加载 则不做任何处理
} else {
// 卡顿后的流恢复
dismissLiveLoadingAnimation();
}
} else if (event == TXLiveConstants.PLAY_EVT_PLAY_LOADING) {
// 2007 視頻播放loading,如果能夠恢複,之後會有BEGIN事件
showLiveLoadingAnimation();
} else if (event == TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION) {
//2009 分辨率改变
// Constant.mTXLivePlayer.stopRecord();
// Constant.pkHeight = param.getInt(TXLiveConstants.EVT_PARAM2);
} else if (event == TXLiveConstants.PUSH_WARNING_NET_BUSY) {
}
/**
* 結束事件
*/
if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
// 2006 視頻播放結束
} else if (event == TXLiveConstants.PLAY_ERR_NET_DISCONNECT) {
// -2301 网络多次重连失败失败后 会返回此值
clearStop();
if (isAdded()) {
networkDisconnect();
}
}
}
/**
* 网络连接提示
*/
public void networkDisconnect() {
if (requireActivity().isFinishing()) return;
DialogFactory.showTwoBtnDialog(requireActivity(), getString(R.string.networkDelay),
getString(R.string.exit), getString(R.string.retryConnect), (button, dialog) -> {
dialog.dismiss();
Constant.mTXLivePlayer.stopPlay(true);
((PlayLiveActivity) requireActivity())
.closeRoomAndStopPlay(false, true, true);
}, (button, dialog) -> {
dialog.dismiss();
playRTMP(anchor.getPullStreamUrl());
});
}
public void showCover() {
if (coverIv != null) {
coverIv.setVisibility(View.VISIBLE);
blurView.setVisibility(View.VISIBLE);
}
}
// 網絡連接狀態
@Override
public void onNetStatus(Bundle param) {
// LogUtils.e("播放實時數據:"+param);
}
//停止播放 是否留最后一帧
public void stopPlay(boolean isKeepLastFrame) {
LogUtils.e("stopPlay ");
if (Constant.mTXLivePlayer != null && Constant.mTXLivePlayer.isPlaying()) {
try {
Constant.mTXLivePlayer.stopPlay(isKeepLastFrame); // true 代表清除最后一帧画面
} catch (Exception e) {
e.getStackTrace();
}
}
}
public boolean isPlay() {
if (Constant.mTXLivePlayer != null) {
return Constant.mTXLivePlayer.isPlaying();
} else {
return false;
}
}
@Override
public void onResume() {
super.onResume();
mTXCloudVideoView.onResume();
if (Constant.isOpenWindow) {
ivCloseWindow.setVisibility(View.GONE);
}
}
@Override
public void onPause() {
super.onPause();
mTXCloudVideoView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private OnVideoPlayStateListener listener;
public void setOnVideoPlayStateListener(OnVideoPlayStateListener listener) {
this.listener = listener;
}
@Override
public void onClick(View view) {
if (ClickUtil.isFastDoubleClick()) return;
switch (view.getId()) {
case R.id.iv_close_window:
onClickRemoveFromWindow();
break;
case R.id.live_play_video_view:
case R.id.iv_conver:
fromWindow();
break;
}
}
public interface OnVideoPlayStateListener {
void onPlayIsFinish(boolean isFinish);
}
}
| 4318471pk/ppav365 | app/src/main/java/com/live/fox/ui/live/VideoFragment.java | 4,800 | //是否开启小窗口 | line_comment | zh-cn | package com.live.fox.ui.live;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.github.mmin18.widget.RealtimeBlurView;
import com.live.fox.AppIMManager;
import com.live.fox.Constant;
import com.live.fox.R;
import com.live.fox.common.CommonApp;
import com.live.fox.dialog.DialogFactory;
import com.live.fox.entity.Anchor;
import com.live.fox.receiver.TXPhoneStateListener;
import com.live.fox.utils.ActivityUtils;
import com.live.fox.utils.ClickUtil;
import com.live.fox.utils.GlideUtils;
import com.live.fox.utils.LogUtils;
import com.live.fox.utils.PlayerUtils;
import com.live.fox.utils.TCConstants;
import com.live.fox.utils.ToastUtils;
import com.live.fox.windowmanager.WindowUtils;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
/**
* Date: 2016/3/27
* Time: 19:40
*/
public class VideoFragment extends Fragment implements ITXLivePlayListener, View.OnClickListener {
private ImageView iv_bg;
private TXCloudVideoView mTXCloudVideoView;
private ImageView mLoadingView; //正在加载
private ImageView coverIv; //视频封面
private RealtimeBlurView blurView; //视频封面
private RelativeLayout videoFrameLayout;
private ImageView ivCloseWindow;
private TextView tv_window;
private Anchor anchor;
private TXLivePlayConfig mTXPlayConfig;
private static String roomPaid;
private static String roomPassword;
public static VideoFragment newInstance(Anchor anchor) {
VideoFragment fragment = new VideoFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("anchor", anchor);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (getArguments() != null) {
this.anchor = (Anchor) bundle.getSerializable("anchor");
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.video_fragment, container, false);
initView(view);
if (anchor != null) {
GlideUtils.loadImage(requireActivity(), anchor.getAvatar(),
R.drawable.liveing_star,
R.drawable.liveing_star, coverIv);
try {
initPlayer();
} catch (Exception e) {
ToastUtils.showShort(getString(R.string.playerInitialException));
}
//电话状态监听
CommonApp.mPhoneListener = new TXPhoneStateListener(Constant.mTXLivePlayer);
TelephonyManager tm = (TelephonyManager)
requireActivity().getSystemService(Service.TELEPHONY_SERVICE);
tm.listen(CommonApp.mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
return view;
}
private void initView(View bindSource) {
iv_bg = bindSource.findViewById(R.id.iv_bg);
mTXCloudVideoView = bindSource.findViewById(R.id.live_play_video_view);
mLoadingView = bindSource.findViewById(R.id.loading);
coverIv = bindSource.findViewById(R.id.iv_conver);
blurView = bindSource.findViewById(R.id.blur);
videoFrameLayout = bindSource.findViewById(R.id.frame_video_layout_push);
ivCloseWindow = bindSource.findViewById(R.id.iv_close_window);
tv_window = bindSource.findViewById(R.id.tv_window);
bindSource.findViewById(R.id.iv_close_window).setOnClickListener(this);
bindSource.findViewById(R.id.live_play_video_view).setOnClickListener(this);
bindSource.findViewById(R.id.iv_conver).setOnClickListener(this);
roomPaid = getString(R.string.live_change_to_paid);
roomPassword = getString(R.string.live_change_to_password);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//打开fragment后加载video 不是1和3状态
if(anchor!=null && anchor.getLiveStatus()!=1 && anchor.getLiveStatus()!=3)
{
startPlay(anchor);
}
}
private void initPlayer() {
if (Constant.mTXLivePlayer == null) {
Constant.mTXLivePlayer = new TXLivePlayer(requireContext());
}
mTXPlayConfig = new TXLivePlayConfig();
setPlayMode(2);
}
//设置播放器模式
public void setPlayMode(int strategy) {
if (mTXPlayConfig == null) {
return;
}
switch (strategy) {
case 0: // 極速
mTXPlayConfig.setAutoAdjustCacheTime(true);
mTXPlayConfig.setMinAutoAdjustCacheTime(1);
mTXPlayConfig.setMaxAutoAdjustCacheTime(1);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
break;
case 1: // 流暢
mTXPlayConfig.setAutoAdjustCacheTime(false);
mTXPlayConfig.setMinAutoAdjustCacheTime(5);
mTXPlayConfig.setMaxAutoAdjustCacheTime(5);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
break;
case 2: // 自動
mTXPlayConfig.setAutoAdjustCacheTime(true);
mTXPlayConfig.setMinAutoAdjustCacheTime(1);
mTXPlayConfig.setMaxAutoAdjustCacheTime(5);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
break;
}
}
/**
* 切换房间时 根据状态显示 不一样的界面
*
* @param state
* @param anchor
*/
public void switchRoomByState(int state, Anchor anchor) {
LogUtils.e("切换房间时 根据状态显示 不一样的界面" + state);
this.anchor = anchor;
if (!isAdded()) return;
if (state == 1) {//切换后请求接口时的处理
if (Constant.mTXLivePlayer != null && Constant.mTXLivePlayer.isPlaying()) {
Constant.mTXLivePlayer.stopPlay(true);
}
if (coverIv != null) {
coverIv.setVisibility(View.VISIBLE);
blurView.setVisibility(View.VISIBLE);
GlideUtils.loadDefaultImage(getActivity(), anchor.getAvatar(), coverIv);
}
showLiveLoadingAnimation();
}
}
public void startPlay(Anchor anchor) {
this.anchor = anchor;
if (!isAdded()) return;
playRTMP(anchor.getPullStreamUrl());
}
private void fromWindow() {
if (Constant.isOpenWindow) {
AppIMManager.ins().removeMessageReceivedListener(PlayLiveActivity.class);
Constant.isOpenWindow = false;
PlayLiveActivity.startActivity(ActivityUtils.getTopActivity(), Constant.windowAnchor);
}
}
public void changeWindowText(Anchor currentAnchor) {
anchor = currentAnchor;
if (3 == anchor.getType()) {
tv_window.setVisibility(View.VISIBLE);
tv_window.setText(roomPaid);
coverIv.setVisibility(View.VISIBLE);
GlideUtils.loadImage(CommonApp.getInstance(), currentAnchor.getAvatar(),
R.drawable.liveing_star, R.drawable.liveing_star, coverIv);
stopPlay(true);
} else if (0 == anchor.getType()) {
tv_window.setVisibility(View.GONE);
coverIv.setVisibility(View.GONE);
playRTMP(anchor.getPullStreamUrl());
} else {
tv_window.setVisibility(View.VISIBLE);
tv_window.setText(roomPassword);
coverIv.setVisibility(View.VISIBLE);
GlideUtils.loadImage(CommonApp.getInstance(), currentAnchor.getAvatar(),
R.drawable.liveing_star, R.drawable.liveing_star, coverIv);
stopPlay(true);
}
}
/**
* 添加到Window
*/
public void onClickAddToWindow() {
if (Constant.isShowWindow) {
ivCloseWindow.setVisibility(View.VISIBLE);
Constant.isOpenWindow = true;//是否 <SUF>
}
}
/**
* 从Window移除
*/
public void onClickRemoveFromWindow() {
Constant.isShowWindow = false;
Constant.isOpenWindow = false;
if (Constant.windowAnchor != null) {
AppIMManager.ins().loginOutGroup(String.valueOf(Constant.windowAnchor.getLiveId()));
}
WindowUtils.closeWindowResource(PlayLiveActivity.class);
}
//停止播放并清空播放事件
public void clearStop() {
LogUtils.e("clearStop");
if (Constant.mTXLivePlayer != null) {
Constant.mTXLivePlayer.stopPlay(false);
Constant.mTXLivePlayer.setPlayerView(null);
Constant.mTXLivePlayer.setPlayListener(null);
}
}
public void changePKVideo(boolean isPK) {
LogUtils.e("isPK==" + isPK);
Constant.isPK = isPK;
mTXPlayConfig.enableAEC(isPK);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
if (!Constant.isOpenWindow) {
adjustFullScreenVideoView(!isPK);
}
}
public void adjustFullScreenVideoView(boolean fullScreen) {
if (videoFrameLayout.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) videoFrameLayout.getLayoutParams();
if (fullScreen) {
LogUtils.e("全屏");
layoutParams.removeRule(RelativeLayout.BELOW);
layoutParams.removeRule(RelativeLayout.ABOVE);
iv_bg.setVisibility(View.GONE);
} else {
LogUtils.e("PK 小屏");
layoutParams.addRule(RelativeLayout.BELOW, R.id.frame_layout_pross);
layoutParams.addRule(RelativeLayout.ABOVE, R.id.view_center);
iv_bg.setVisibility(View.VISIBLE);
}
videoFrameLayout.setLayoutParams(layoutParams);
}
}
private void playRTMP(String streamUrl) {
LogUtils.e("streamUrl " + streamUrl);
int mUrlPlayType = TXLivePlayer.PLAY_TYPE_LIVE_RTMP;
if (0 == anchor.getLiveStatus()) {
streamUrl = anchor.getAdJumpUrl();
mUrlPlayType = TXLivePlayer.PLAY_TYPE_VOD_MP4;
} else if (1 == anchor.getLiveStatus() || 3 == anchor.getLiveStatus()) {
if (!PlayerUtils.checkPlayUrl(streamUrl, requireContext())) {
ToastUtils.showShort(getString(R.string.illegalStreaming));
return;
}
if (Constant.mTXLivePlayer == null) {
LogUtils.e("Constant.mTXLivePlayer为空");
return;
}
if ((streamUrl.startsWith(PlayerUtils.HTTP) ||
streamUrl.startsWith(PlayerUtils.HTTPS)) && streamUrl.contains(PlayerUtils.FLV)) {
mUrlPlayType = TXLivePlayer.PLAY_TYPE_LIVE_FLV;
}
}
Constant.mTXLivePlayer.setPlayerView(mTXCloudVideoView);
Constant.mTXLivePlayer.setPlayListener(this);
// 硬件加速在1080p解码场景下效果显著,但细节之处并不如想象的那么美好:
// (1) 只有 4.3 以上android系统才支持
// (2) 兼容性我们目前还仅过了小米华为等常见机型,故这里的返回值您先不要太当真
Constant.mTXLivePlayer.enableHardwareDecode(false);
Constant.mTXLivePlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
Constant.mTXLivePlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
Constant.mTXLivePlayer.setConfig(mTXPlayConfig);
LogUtils.e("直播流 " + streamUrl + "," + mUrlPlayType);
int result = Constant.mTXLivePlayer.startPlay(streamUrl, mUrlPlayType);
Constant.isShowWindow = true;
LogUtils.e("拉流返回值 result " + result);
if (0 != result) {
Intent rstData = new Intent();
if (-1 != result) {
ToastUtils.showShort(R.string.splbfsb);
}
rstData.putExtra(TCConstants.ACTIVITY_RESULT, getString(R.string.linkRestrictions));
if (mTXCloudVideoView != null) {
mTXCloudVideoView.onPause();
}
}
showLiveLoadingAnimation();
}
private void showLiveLoadingAnimation() {
if (mLoadingView != null) {
mLoadingView.setVisibility(View.VISIBLE);
((AnimationDrawable) mLoadingView.getDrawable()).start();
}
}
public void dismissLiveLoadingAnimation() {
if (!isAdded()) return;
if (coverIv != null) {
LogUtils.e("dimissLiveLoadingAnimation()");
coverIv.setVisibility(View.GONE);
blurView.setVisibility(View.GONE);
}
if (mLoadingView != null) {
mLoadingView.setVisibility(View.GONE);
((AnimationDrawable) mLoadingView.getDrawable()).stop();
}
}
/**
* 播放事件
* 正常流程:
* 2007, 视频缓冲中...
* 2001, 已连接服务器
* 2002, 开始拉流
* 2004, 视频播放开始
* 2008, 启动软解
* (如果网络慢,到下一步会有一段时间)
* 2003, 渲染首个视频数据包(IDR)
* 2009, 分辨率改变为368x640
* <p>
* 出现卡顿流程:
* 2007, 视频缓冲中...
* 2004, 视频播放开始
* 2105, 当前视频播放出现卡顿1816ms
*/
@Override
public void onPlayEvent(int event, Bundle param) {
LogUtils.e("视频播放状态监听 " + event + ", " + param.getString(TXLiveConstants.EVT_DESCRIPTION));
if (event == TXLiveConstants.PLAY_EVT_CONNECT_SUCC) {
// 2001 連接服務器成功
} else if (event == TXLiveConstants.PLAY_EVT_RTMP_STREAM_BEGIN) {
// 2002 已經連接服務器,開始拉流(僅播放RTMP地址時會抛送)
// dimissLiveLoadingAnimation();
// content.setBackground(null);
} else if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {
// 2003 網絡接收到首個可渲染的視頻數據包(IDR)
dismissLiveLoadingAnimation();
LogUtils.e(Constant.mTXLivePlayer.isPlaying() + ",");
LogUtils.e((Constant.mTXLivePlayer == null) + ",");
LogUtils.e((mTXCloudVideoView == null) + ",");
listener.onPlayIsFinish(true);
} else if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {
// 2004 視頻播放開始,如果有轉菊花什麽的這個時候該停了
if (coverIv.getVisibility() == View.VISIBLE) {
//说明是第一次加载 则不做任何处理
} else {
// 卡顿后的流恢复
dismissLiveLoadingAnimation();
}
} else if (event == TXLiveConstants.PLAY_EVT_PLAY_LOADING) {
// 2007 視頻播放loading,如果能夠恢複,之後會有BEGIN事件
showLiveLoadingAnimation();
} else if (event == TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION) {
//2009 分辨率改变
// Constant.mTXLivePlayer.stopRecord();
// Constant.pkHeight = param.getInt(TXLiveConstants.EVT_PARAM2);
} else if (event == TXLiveConstants.PUSH_WARNING_NET_BUSY) {
}
/**
* 結束事件
*/
if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
// 2006 視頻播放結束
} else if (event == TXLiveConstants.PLAY_ERR_NET_DISCONNECT) {
// -2301 网络多次重连失败失败后 会返回此值
clearStop();
if (isAdded()) {
networkDisconnect();
}
}
}
/**
* 网络连接提示
*/
public void networkDisconnect() {
if (requireActivity().isFinishing()) return;
DialogFactory.showTwoBtnDialog(requireActivity(), getString(R.string.networkDelay),
getString(R.string.exit), getString(R.string.retryConnect), (button, dialog) -> {
dialog.dismiss();
Constant.mTXLivePlayer.stopPlay(true);
((PlayLiveActivity) requireActivity())
.closeRoomAndStopPlay(false, true, true);
}, (button, dialog) -> {
dialog.dismiss();
playRTMP(anchor.getPullStreamUrl());
});
}
public void showCover() {
if (coverIv != null) {
coverIv.setVisibility(View.VISIBLE);
blurView.setVisibility(View.VISIBLE);
}
}
// 網絡連接狀態
@Override
public void onNetStatus(Bundle param) {
// LogUtils.e("播放實時數據:"+param);
}
//停止播放 是否留最后一帧
public void stopPlay(boolean isKeepLastFrame) {
LogUtils.e("stopPlay ");
if (Constant.mTXLivePlayer != null && Constant.mTXLivePlayer.isPlaying()) {
try {
Constant.mTXLivePlayer.stopPlay(isKeepLastFrame); // true 代表清除最后一帧画面
} catch (Exception e) {
e.getStackTrace();
}
}
}
public boolean isPlay() {
if (Constant.mTXLivePlayer != null) {
return Constant.mTXLivePlayer.isPlaying();
} else {
return false;
}
}
@Override
public void onResume() {
super.onResume();
mTXCloudVideoView.onResume();
if (Constant.isOpenWindow) {
ivCloseWindow.setVisibility(View.GONE);
}
}
@Override
public void onPause() {
super.onPause();
mTXCloudVideoView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private OnVideoPlayStateListener listener;
public void setOnVideoPlayStateListener(OnVideoPlayStateListener listener) {
this.listener = listener;
}
@Override
public void onClick(View view) {
if (ClickUtil.isFastDoubleClick()) return;
switch (view.getId()) {
case R.id.iv_close_window:
onClickRemoveFromWindow();
break;
case R.id.live_play_video_view:
case R.id.iv_conver:
fromWindow();
break;
}
}
public interface OnVideoPlayStateListener {
void onPlayIsFinish(boolean isFinish);
}
}
| 0 |
5540_5 | package yalong.site.frame.panel.client;
import lombok.extern.slf4j.Slf4j;
import yalong.site.frame.bo.ComponentBO;
import yalong.site.frame.bo.ItemBO;
import yalong.site.frame.panel.base.BaseComboBox;
import yalong.site.frame.panel.client.listener.GameStatusBoxItemListener;
import java.awt.*;
/**
* @author yaLong
*/
@Slf4j
public class GameStatusBox extends BaseComboBox<ItemBO> {
public GameStatusBox() {
this.setItems();
this.addItemListener(new GameStatusBoxItemListener());
}
/**
* @return 带布局的盒子
*/
public static ComponentBO builder() {
GameStatusBox box = new GameStatusBox();
GridBagConstraints grid = new GridBagConstraints(
// 第(0,3)个格子
0, 3,
// 占1列,占1行
1, 1,
//横向占100%长度,纵向占100%长度
2, 2,
//居中,组件小的话就两边铺满窗格
GridBagConstraints.CENTER, GridBagConstraints.NONE,
// 窗格之间的距离
new Insets(0, 0, 0, 0),
// 增加组件的首选宽度和高度
0, 0
);
return new ComponentBO(box, grid);
}
public void setItems() {
this.addItem(new ItemBO("chat", "在线"));
this.addItem(new ItemBO("away", "离开"));
this.addItem(new ItemBO("dnd", "游戏中"));
this.addItem(new ItemBO("offline", "离线"));
this.addItem(new ItemBO("mobile", "手机在线"));
}
}
| 4379711/lol-helper | src/main/java/yalong/site/frame/panel/client/GameStatusBox.java | 455 | //居中,组件小的话就两边铺满窗格 | line_comment | zh-cn | package yalong.site.frame.panel.client;
import lombok.extern.slf4j.Slf4j;
import yalong.site.frame.bo.ComponentBO;
import yalong.site.frame.bo.ItemBO;
import yalong.site.frame.panel.base.BaseComboBox;
import yalong.site.frame.panel.client.listener.GameStatusBoxItemListener;
import java.awt.*;
/**
* @author yaLong
*/
@Slf4j
public class GameStatusBox extends BaseComboBox<ItemBO> {
public GameStatusBox() {
this.setItems();
this.addItemListener(new GameStatusBoxItemListener());
}
/**
* @return 带布局的盒子
*/
public static ComponentBO builder() {
GameStatusBox box = new GameStatusBox();
GridBagConstraints grid = new GridBagConstraints(
// 第(0,3)个格子
0, 3,
// 占1列,占1行
1, 1,
//横向占100%长度,纵向占100%长度
2, 2,
//居中 <SUF>
GridBagConstraints.CENTER, GridBagConstraints.NONE,
// 窗格之间的距离
new Insets(0, 0, 0, 0),
// 增加组件的首选宽度和高度
0, 0
);
return new ComponentBO(box, grid);
}
public void setItems() {
this.addItem(new ItemBO("chat", "在线"));
this.addItem(new ItemBO("away", "离开"));
this.addItem(new ItemBO("dnd", "游戏中"));
this.addItem(new ItemBO("offline", "离线"));
this.addItem(new ItemBO("mobile", "手机在线"));
}
}
| 0 |
31311_29 | package com.alipush;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class PushUtils {
public static final String NotificationChannelId = "7777777";
private static String AliyunAppKey;
private static String AliyunAppSecret;
// 小米辅助通道
private static String XiaoMiAppId = "2882303761518018487";
private static String XiaoMiAppKey = "5371801843487";
// OPPO辅助通道
private static String OPPOAppKey = "7ac256813b8745928c2102c20dd49fde";
private static String OPPOAppSecret = "9b4ac44b4eee471097243658679910d1";
private SharedPreferences preference;
public PushUtils(Context context) {
this.preference = PreferenceManager.getDefaultSharedPreferences(context) ;
}
public static String getCurProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
/**
* 获取推送配置信息
* @param applicationContext
*/
private static void getConfig(final Context applicationContext) throws PackageManager.NameNotFoundException {
ApplicationInfo appInfo = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);
AliyunAppKey=appInfo.metaData.get("AliyunAppKey")+"";
AliyunAppSecret=appInfo.metaData.get("AliyunAppSecret")+"";
XiaoMiAppId =appInfo.metaData.get("XiaoMiAppId")+"";
XiaoMiAppKey=appInfo.metaData.get("XiaoMiAppKey")+"";
OPPOAppKey = appInfo.metaData.get("OPPOAppKey")+"";
OPPOAppSecret=appInfo.metaData.get("OPPOAppSecret")+"";
}
/**
* 初始化云推送通道
*
* @param applicationContext
*/
static void initPushService(final Context applicationContext) throws PackageManager.NameNotFoundException {
getConfig(applicationContext);
PushServiceFactory.init(applicationContext);
final CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.setLogLevel(CloudPushService.LOG_DEBUG);
pushService.register(applicationContext,AliyunAppKey,AliyunAppSecret, new CommonCallback() {
@Override
public void onSuccess(String response) {
Log.i("==", "init cloudchannel success");
String deviceId=pushService.getDeviceId();
Log.i("== deviceId", deviceId + "");
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.i("==", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
}
});
// 注册NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = NotificationChannelId;
// 用户可以看到的通知渠道的名字.
CharSequence name = "通知";
// 用户可以看到的通知渠道的描述
String description = "通知描述";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
// 最后在notificationmanager中创建该通知渠道
mNotificationManager.createNotificationChannel(mChannel);
// 设置8.0系统的通知小图标,必须要纯色的图
// PushServiceFactory.getCloudPushService().setNotificationSmallIcon(R.drawable.notify);
}
// 5. 在应用中初始化辅助通道
// 注册方法会自动判断是否支持小米系统推送,如不支持会跳过注册。
if(XiaoMiAppId!=null&&XiaoMiAppKey!=null) {
Log.i("XiaoMi Push registered", "XiaoMiAppId:" + XiaoMiAppId + " , XiaoMiAppKey:" + XiaoMiAppKey);
MiPushRegister.register(applicationContext, XiaoMiAppId, XiaoMiAppKey);
}
// 注册方法会自动判断是否支持华为系统推送,如不支持会跳过注册。
HuaWeiRegister.register(applicationContext);
// GCM/FCM辅助通道注册
// GcmRegister.register(this, sendId, applicationId);
// //sendId/applicationId为步骤获得的参数
// OPPO通道注册
if(OPPOAppKey!=null&&OPPOAppSecret!=null) {
Log.i("OPPO Push registered", "OPPOAppKey:" + OPPOAppKey + " , OPPOAppSecret:" + OPPOAppSecret);
OppoRegister.register(applicationContext, OPPOAppKey, OPPOAppSecret); // appKey/appSecret在OPPO通道开发者平台获取
}
}
/**
* 解决androidP 第一次打开程序出现莫名弹窗 弹窗内容“detected problems with api ”
*/
private void closeAndroidPDialog() {
try {
Class aClass = Class.forName("android.content.pm.PackageParser$Package");
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class cls = Class.forName("android.app.ActivityThread");
Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
declaredMethod.setAccessible(true);
Object activityThread = declaredMethod.invoke(null);
Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setNoticeJsonData(String jsonObject) {
//response为后台返回的json数据
preference.edit().putString("NoticeJsonData", jsonObject).apply(); //存入json串
}
public String getNotice() {
String jsonData = preference.getString("NoticeJsonData", "");
//每次取到json数据后,将其清空
preference.edit().putString("NoticeJsonData", "").apply();
try {
JSONObject data=new JSONObject(jsonData);
AliyunPush.pushData(data);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonData;
}
public void setIsShowNoticePermissions(boolean isShow) {
preference.edit().putBoolean("ShowNoticePermissions", isShow).apply();
}
public boolean getIsShowNoticePermissions() {
return preference.getBoolean("ShowNoticePermissions",true);
}
/**
* 请求通知权限
*/
public void isShowNoticeDialog(Activity context,String msg) {
NotificationManagerCompat notification = NotificationManagerCompat.from(context);
boolean isEnabled = notification.areNotificationsEnabled();
if(msg==null){
msg="建议你开启通知权限,第一时间收到提醒";
}
//未打开通知
if (!isEnabled) {
try {
if (preference.getBoolean("ShowNoticePermissions", true)) {
showDialog(context,msg);
} else {
int random = (int) (Math.random() * 10 + 1);
// Log.i("== random", random + "");
//随机数1-10,每次启动,如果除以3为0,则显示弹窗请求权限,否则就不弹窗
if (random % 3 == 0) {
showDialog(context,msg);
}
}
}catch (Exception ex){}
}
}
public void showDialog(Activity context,String msg) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("开启推送通知")
.setMessage(msg)
.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
@Override
public void onClick(DialogInterface dialog, int which) {
preference.edit().putBoolean("ShowNoticePermissions", false).apply();
}
})
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", context.getPackageName());
intent.putExtra("app_uid", context.getApplicationInfo().uid);
context.startActivity(intent);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + context.getPackageName()));
} else if (Build.VERSION.SDK_INT >= 15) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package",context.getPackageName(), null));
}
context.startActivity(intent);
}
})
.create();
if(context.isFinishing())return;
alertDialog.show();
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
}
},5000);
}
}
| 442623641/cordova-plugin-aliyunpush | src/android/PushUtils.java | 2,861 | //随机数1-10,每次启动,如果除以3为0,则显示弹窗请求权限,否则就不弹窗 | line_comment | zh-cn | package com.alipush;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class PushUtils {
public static final String NotificationChannelId = "7777777";
private static String AliyunAppKey;
private static String AliyunAppSecret;
// 小米辅助通道
private static String XiaoMiAppId = "2882303761518018487";
private static String XiaoMiAppKey = "5371801843487";
// OPPO辅助通道
private static String OPPOAppKey = "7ac256813b8745928c2102c20dd49fde";
private static String OPPOAppSecret = "9b4ac44b4eee471097243658679910d1";
private SharedPreferences preference;
public PushUtils(Context context) {
this.preference = PreferenceManager.getDefaultSharedPreferences(context) ;
}
public static String getCurProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
/**
* 获取推送配置信息
* @param applicationContext
*/
private static void getConfig(final Context applicationContext) throws PackageManager.NameNotFoundException {
ApplicationInfo appInfo = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);
AliyunAppKey=appInfo.metaData.get("AliyunAppKey")+"";
AliyunAppSecret=appInfo.metaData.get("AliyunAppSecret")+"";
XiaoMiAppId =appInfo.metaData.get("XiaoMiAppId")+"";
XiaoMiAppKey=appInfo.metaData.get("XiaoMiAppKey")+"";
OPPOAppKey = appInfo.metaData.get("OPPOAppKey")+"";
OPPOAppSecret=appInfo.metaData.get("OPPOAppSecret")+"";
}
/**
* 初始化云推送通道
*
* @param applicationContext
*/
static void initPushService(final Context applicationContext) throws PackageManager.NameNotFoundException {
getConfig(applicationContext);
PushServiceFactory.init(applicationContext);
final CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.setLogLevel(CloudPushService.LOG_DEBUG);
pushService.register(applicationContext,AliyunAppKey,AliyunAppSecret, new CommonCallback() {
@Override
public void onSuccess(String response) {
Log.i("==", "init cloudchannel success");
String deviceId=pushService.getDeviceId();
Log.i("== deviceId", deviceId + "");
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.i("==", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
}
});
// 注册NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = NotificationChannelId;
// 用户可以看到的通知渠道的名字.
CharSequence name = "通知";
// 用户可以看到的通知渠道的描述
String description = "通知描述";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
// 最后在notificationmanager中创建该通知渠道
mNotificationManager.createNotificationChannel(mChannel);
// 设置8.0系统的通知小图标,必须要纯色的图
// PushServiceFactory.getCloudPushService().setNotificationSmallIcon(R.drawable.notify);
}
// 5. 在应用中初始化辅助通道
// 注册方法会自动判断是否支持小米系统推送,如不支持会跳过注册。
if(XiaoMiAppId!=null&&XiaoMiAppKey!=null) {
Log.i("XiaoMi Push registered", "XiaoMiAppId:" + XiaoMiAppId + " , XiaoMiAppKey:" + XiaoMiAppKey);
MiPushRegister.register(applicationContext, XiaoMiAppId, XiaoMiAppKey);
}
// 注册方法会自动判断是否支持华为系统推送,如不支持会跳过注册。
HuaWeiRegister.register(applicationContext);
// GCM/FCM辅助通道注册
// GcmRegister.register(this, sendId, applicationId);
// //sendId/applicationId为步骤获得的参数
// OPPO通道注册
if(OPPOAppKey!=null&&OPPOAppSecret!=null) {
Log.i("OPPO Push registered", "OPPOAppKey:" + OPPOAppKey + " , OPPOAppSecret:" + OPPOAppSecret);
OppoRegister.register(applicationContext, OPPOAppKey, OPPOAppSecret); // appKey/appSecret在OPPO通道开发者平台获取
}
}
/**
* 解决androidP 第一次打开程序出现莫名弹窗 弹窗内容“detected problems with api ”
*/
private void closeAndroidPDialog() {
try {
Class aClass = Class.forName("android.content.pm.PackageParser$Package");
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class cls = Class.forName("android.app.ActivityThread");
Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
declaredMethod.setAccessible(true);
Object activityThread = declaredMethod.invoke(null);
Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setNoticeJsonData(String jsonObject) {
//response为后台返回的json数据
preference.edit().putString("NoticeJsonData", jsonObject).apply(); //存入json串
}
public String getNotice() {
String jsonData = preference.getString("NoticeJsonData", "");
//每次取到json数据后,将其清空
preference.edit().putString("NoticeJsonData", "").apply();
try {
JSONObject data=new JSONObject(jsonData);
AliyunPush.pushData(data);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonData;
}
public void setIsShowNoticePermissions(boolean isShow) {
preference.edit().putBoolean("ShowNoticePermissions", isShow).apply();
}
public boolean getIsShowNoticePermissions() {
return preference.getBoolean("ShowNoticePermissions",true);
}
/**
* 请求通知权限
*/
public void isShowNoticeDialog(Activity context,String msg) {
NotificationManagerCompat notification = NotificationManagerCompat.from(context);
boolean isEnabled = notification.areNotificationsEnabled();
if(msg==null){
msg="建议你开启通知权限,第一时间收到提醒";
}
//未打开通知
if (!isEnabled) {
try {
if (preference.getBoolean("ShowNoticePermissions", true)) {
showDialog(context,msg);
} else {
int random = (int) (Math.random() * 10 + 1);
// Log.i("== random", random + "");
//随机 <SUF>
if (random % 3 == 0) {
showDialog(context,msg);
}
}
}catch (Exception ex){}
}
}
public void showDialog(Activity context,String msg) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("开启推送通知")
.setMessage(msg)
.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
@Override
public void onClick(DialogInterface dialog, int which) {
preference.edit().putBoolean("ShowNoticePermissions", false).apply();
}
})
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", context.getPackageName());
intent.putExtra("app_uid", context.getApplicationInfo().uid);
context.startActivity(intent);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + context.getPackageName()));
} else if (Build.VERSION.SDK_INT >= 15) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package",context.getPackageName(), null));
}
context.startActivity(intent);
}
})
.create();
if(context.isFinishing())return;
alertDialog.show();
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
}
},5000);
}
}
| 0 |
5328_4 | package org.artbot;
public enum MessagerResult {
/**
* 一般是协议层错误,携带错误联系秋洛即可
*/
Error("发送错误", 0),
/**
* 发送成功不意味着发出,只是把包提交给了腾讯
*/
Success("发送成功", 1),
/**
* 例如:声明是群消息但是没有群号
*/
InputError("输入参数有误", 2),
/**
* 消息超过可发送消息的最大长度
*/
MessageLengthMax("爸爸,你这个消息长过头了", 3),
/**
* 消息内没有消息体或消息体无效
*/
EmptyMessage("爸爸,求求你给我个不是空的消息吧!记得里面的消息要有效,别给我个图片链接还是404的就行", 4);
MessagerResult(String msg, int id){
this.msg = msg;
this.id = id;
}
public final String msg;
public final int id;
}
| 448808614/ArtQQ | src/main/java/org/artbot/MessagerResult.java | 254 | /**
* 消息内没有消息体或消息体无效
*/ | block_comment | zh-cn | package org.artbot;
public enum MessagerResult {
/**
* 一般是协议层错误,携带错误联系秋洛即可
*/
Error("发送错误", 0),
/**
* 发送成功不意味着发出,只是把包提交给了腾讯
*/
Success("发送成功", 1),
/**
* 例如:声明是群消息但是没有群号
*/
InputError("输入参数有误", 2),
/**
* 消息超过可发送消息的最大长度
*/
MessageLengthMax("爸爸,你这个消息长过头了", 3),
/**
* 消息内 <SUF>*/
EmptyMessage("爸爸,求求你给我个不是空的消息吧!记得里面的消息要有效,别给我个图片链接还是404的就行", 4);
MessagerResult(String msg, int id){
this.msg = msg;
this.id = id;
}
public final String msg;
public final int id;
}
| 0 |
54062_0 | package com.lin.designpattern.factory;
/**
* 玛莎拉蒂
*/
public class Maserati implements Car{
public String type() {
return "玛莎拉蒂:跑车";
}
}
| 451846939/study | design-pattern/src/main/java/com/lin/designpattern/factory/Maserati.java | 60 | /**
* 玛莎拉蒂
*/ | block_comment | zh-cn | package com.lin.designpattern.factory;
/**
* 玛莎拉 <SUF>*/
public class Maserati implements Car{
public String type() {
return "玛莎拉蒂:跑车";
}
}
| 1 |
41446_2 | package com.liuyao.perfecttable;
public class Column implements IColumn{
private String columnName;
//多级列名支持,index 0是最上面,然后一级一级往下面排
private String[] parentName;
//反射取值
private String property;
//是否固定列,不许左右滑动
private boolean fix;
private Integer minWidthDp;
private Integer maxWidthDp;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String[] getParentName() {
return parentName;
}
public void setParentName(String[] parentName) {
this.parentName = parentName;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public boolean isFix() {
return fix;
}
public void setFix(boolean fix) {
this.fix = fix;
}
public Integer getMinWidthDp() {
return minWidthDp;
}
public void setMinWidthDp(Integer minWidthDp) {
this.minWidthDp = minWidthDp;
}
public Integer getMaxWidthDp() {
return maxWidthDp;
}
public void setMaxWidthDp(Integer maxWidthDp) {
this.maxWidthDp = maxWidthDp;
}
}
| 475789729/perfecttable | src/main/java/com/liuyao/perfecttable/Column.java | 311 | //是否固定列,不许左右滑动 | line_comment | zh-cn | package com.liuyao.perfecttable;
public class Column implements IColumn{
private String columnName;
//多级列名支持,index 0是最上面,然后一级一级往下面排
private String[] parentName;
//反射取值
private String property;
//是否 <SUF>
private boolean fix;
private Integer minWidthDp;
private Integer maxWidthDp;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String[] getParentName() {
return parentName;
}
public void setParentName(String[] parentName) {
this.parentName = parentName;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public boolean isFix() {
return fix;
}
public void setFix(boolean fix) {
this.fix = fix;
}
public Integer getMinWidthDp() {
return minWidthDp;
}
public void setMinWidthDp(Integer minWidthDp) {
this.minWidthDp = minWidthDp;
}
public Integer getMaxWidthDp() {
return maxWidthDp;
}
public void setMaxWidthDp(Integer maxWidthDp) {
this.maxWidthDp = maxWidthDp;
}
}
| 0 |
31409_18 | package org.example.game;
import jakarta.websocket.Session;
import lombok.Getter;
import lombok.Setter;
import org.example.card.*;
import org.example.constant.EffectTiming;
import org.example.system.util.CardPackage;
import org.example.system.util.Lists;
import org.example.system.util.Maps;
import org.example.system.util.Msg;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.example.constant.CounterKey.PLAY_NUM;
import static org.example.constant.CounterKey.POISON;
import static org.example.system.Database.*;
@Getter
@Setter
public class GameInfo implements Serializable {
String room;
// 连锁
boolean canChain = true;
int chainDeep = 3;
boolean inSettle = false;
int turn;
int turnPlayer;
int moreTurn = 0;// 追加回合
boolean gameset = false;
ScheduledFuture<?> rope;
List<Damage> incommingDamages = new ArrayList<>();
Map<Card,EventType> events = new HashMap<>();
List<Effect.EffectInstance> effectInstances = new LinkedList<>();
public boolean hasEvent(){
return !incommingDamages.isEmpty() || !events.isEmpty();
}
public void setCanChain(boolean canChain) {
if (canChain)
msg("本场游戏已启用连锁");
else
msg("本场游戏已禁用连锁");
this.canChain = canChain;
}
PlayerInfo[] playerInfos;
public GameInfo(String room) {
this.room = room;
this.turn = 1;
this.turnPlayer = 0;
this.playerInfos = new PlayerInfo[2];
this.playerInfos[0] = new PlayerInfo(this,true);
this.playerInfos[1] = new PlayerInfo(this,false);
}
public void resetGame(){
msg("游戏重启!");
roomSchedule.get(getRoom()).shutdown();
roomSchedule.remove(getRoom());
rope.cancel(true);
this.turn = 1;
this.turnPlayer = 0;
Session thisSession = thisPlayer().session;
Session oppoSession = oppositePlayer().session;
this.playerInfos = new PlayerInfo[2];
this.playerInfos[0] = new PlayerInfo(this,true);
this.playerInfos[1] = new PlayerInfo(this,false);
zeroTurn(thisSession,oppoSession);
}
public void msg(String msg){
try {
Msg.send(thisPlayer().getSession(),msg);
Msg.send(oppositePlayer().getSession(),msg);
} catch (Exception ignored) {}
}
public void story(String msg){
try {
Msg.story(thisPlayer().getSession(),msg);
Msg.story(oppositePlayer().getSession(),msg);
} catch (Exception ignored) {}
}
public void msgTo(Session session, String msg){
Msg.send(session,msg);
}
public void pushInfo(){
final PlayerInfo thisPlayer = thisPlayer();
thisPlayer.setDeckCount(thisPlayer.getDeck().size());
final PlayerInfo oppositePlayer = oppositePlayer();
oppositePlayer.setDeckCount(oppositePlayer.getDeck().size());
// region 加载补充信息
thisPlayer.getAreaAsCard().forEach(f->f.setSubMarkStr(f.getSubMark()));
thisPlayer.getHand().forEach(f->f.setSubMarkStr(f.getSubMark()));
oppositePlayer.getAreaAsCard().forEach(f->f.setSubMarkStr(f.getSubMark()));
// endregion 加载补充信息
thisPlayer.getAreaAsCard().forEach(f->f.setSubMarkStr(f.getSubMark()));
thisPlayer.getAreaFollowsAsFollow().forEach(f->{
// 回合可攻击数没有打满
final boolean notAttacked = f.getTurnAttack() < f.getTurnAttackMax();
// 状态正常
final boolean normalStatus = !f.hasKeyword("缴械") && !f.hasKeyword("眩晕") && !f.hasKeyword("冻结");
final boolean canAttack = notAttacked && normalStatus &&
(f.getTurnAge() > 0 || f.hasKeyword("疾驰"));
final boolean canDash = notAttacked && normalStatus &&
(f.getTurnAge() == 0 && !f.hasKeyword("疾驰") && f.hasKeyword("突进"));
f.setCanAttack(canAttack);
f.setCanDash(canDash);
});
Msg.send(thisPlayer.getSession(),"battleInfo",
Maps.newMap("me", thisPlayer,"enemy", oppositePlayer));
Msg.send(oppositePlayer.getSession(),"battleInfo",
Maps.newMap("me", oppositePlayer,"enemy", thisPlayer));
}
public void msgToThisPlayer(String msg){
Msg.send(thisPlayer().getSession(),msg);
}
public void msgToOppositePlayer(String msg){
Msg.send(oppositePlayer().getSession(),msg);
}
public void measureLeader(){
if(thisPlayer().getHp()<=0)
gameset(oppositePlayer());
if(oppositePlayer().getHp()<=0)
gameset(thisPlayer());
}
public void measureFollows(){
// msg("——————结算卡牌状态——————");
// 立即结算受伤状态
List<Damage> incommingDamagesCopy = new ArrayList<>(incommingDamages);
incommingDamages = new ArrayList<>();
incommingDamagesCopy.forEach(damage->{
damage.getTo().useEffects(EffectTiming.AfterDamaged,damage);
});
Map<Card, EventType> eventsCopy = events;
events = new HashMap<>();
// 再结算其他状态
eventsCopy.forEach((card, type) -> {
switch (type){
case Destroy -> {
if(card instanceof AreaCard areaCard) areaCard.destroyed();
}
}
});
assert events.isEmpty();
}
public void gameset(PlayerInfo winner){
gameset = true;
msg("游戏结束,获胜者:"+winner.getName());
pushInfo();
final Session winnerSession = winner.getSession();
Msg.send(winnerSession,"alert","你赢了!");
Msg.send(anotherPlayerBySession(winnerSession).getSession(),"alert","你输了!");
// 释放资源
roomGame.remove(getRoom());
// 退出房间
try {
userRoom.remove(thisPlayer().getSession());
msgToThisPlayer("离开房间成功");
userRoom.remove(oppositePlayer().getSession());
msgToOppositePlayer("离开房间成功");
rope.cancel(true);
ScheduledExecutorService ses = roomSchedule.get(getRoom());
ses.shutdown();
roomSchedule.remove(getRoom());
}catch (Exception e){e.printStackTrace();}
throw new RuntimeException("Game Set");
}
public PlayerInfo thisPlayer(){
return playerInfos[turnPlayer];
}
public PlayerInfo oppositePlayer(){
return playerInfos[1-turnPlayer];
}
public PlayerInfo playerBySession(Session session){
if(playerInfos[0].session == session){
return playerInfos[0];
}else {
return playerInfos[1];
}
}
public PlayerInfo anotherPlayerBySession(Session session){
if(playerInfos[0].session == session){
return playerInfos[1];
}else {
return playerInfos[0];
}
}
// region effect
public boolean addEvent(Card card,EventType type){
EventType oldType = events.get(card);
if(oldType != null){
// msg(card.getNameWithOwner() + "已经被" + oldType.getName() + ",无法再被" + type.getName());
return false;
}
// msg(card.getNameWithOwner() + "的" + type.getName() + "状态已加入队列");
events.put(card,type);
return true;
}
public void useAreaCardEffectBatch(List<AreaCard> cards, EffectTiming timing){
List<GameObj> gameObjs = cards.stream().map(p -> (GameObj) p).toList();
tempEffectBatch(gameObjs,timing);
startEffect();
}
public void useAreaCardEffectBatch(List<AreaCard> cards, EffectTiming timing,Object param){
List<GameObj> gameObjs = cards.stream().map(p -> (GameObj) p).toList();
tempEffectBatch(gameObjs,timing,param);
startEffect();
}
public void useEffectBatch(List<GameObj> objs, EffectTiming timing){
tempEffectBatch(objs,timing);
startEffect();
}
public void tempEffectBatch(List<GameObj> objs, EffectTiming timing,Object param){
objs.forEach(obj -> obj.tempEffects(timing,param));
}
public void tempEffectBatch(List<GameObj> objs, EffectTiming timing){
objs.forEach(obj -> obj.tempEffects(timing));
}
public void tempCardEffectBatch(List<Card> objs, EffectTiming timing){
objs.forEach(obj -> obj.tempEffects(timing));
}
public void tempCardEffectBatch(List<Card> objs, EffectTiming timing, Object param) {
objs.forEach(obj -> obj.tempEffects(timing,param));
}
public void tempAreaCardEffectBatch(List<AreaCard> objs, EffectTiming timing){
objs.forEach(obj -> obj.tempEffects(timing));
}
public void tempAreaCardEffectBatch(List<AreaCard> objs, EffectTiming timing,Object param){
objs.forEach(obj -> obj.tempEffects(timing,param));
}
public void tempEffect(Effect.EffectInstance instance){
Effect effect = instance.getEffect();
effectInstances.add(instance);
// msg(effect.getOwnerObj().getNameWithOwner()+"的【"+effect.getTiming().getName()+"】效果已加入队列" +
// "(队列现在有" + effectInstances.size() + "个效果)");
}
// 结算效果
public void startEffect(){
if(inSettle)return;
inSettle = true;
// msg("——————开始结算——————");
consumeEffectChain(chainDeep);
// 计算主战者死亡状况
measureLeader();
inSettle = false;
}
public void consumeEffectChain(int deep){
// msg("——————开始触发事件——————");
measureFollows();
// msg("——————开始触发效果——————");
consumeEffect();
// msg("——————停止触发效果——————");
if(hasEvent()){
if(!canChain || deep==0){
msg("停止连锁!本次死亡结算后不触发任何效果");
measureFollows();
effectInstances.clear();
events.clear();
return;
}
// msg("——————事件连锁("+deep+")——————");
consumeEffectChain(deep - 1);
}
}
public void consumeEffect(){
if(effectInstances.isEmpty()) return;
effectInstances.sort((o1, o2) -> {
for (EffectTiming value : EffectTiming.values()) {
if(value.equals(o1.getEffect().getTiming()))
return -1;
else if(value.equals(o2.getEffect().getTiming()))
return 1;
}
return 0;
});
List<Effect.EffectInstance> instances = new ArrayList<>(effectInstances);
instances.forEach(Effect.EffectInstance::consume);
effectInstances.clear();
}
// endregion effect
// region event
public void transform(Card fromCard, Card toCard){
msg(fromCard.getNameWithOwnerWithPlace()+ "变身成了" + toCard.getId());
if(fromCard.atArea()){
if(fromCard.hasKeyword("魔法免疫")){
fromCard.getInfo().msg(fromCard.getNameWithOwner() + "免疫了本次变身!");
return;
}
if(fromCard.hasKeyword("魔法护盾")){
fromCard.getInfo().msg(fromCard.getNameWithOwner() + "的魔法护盾抵消了本次变身!");
fromCard.removeKeyword("魔法护盾");
return;
}
List<AreaCard> area = fromCard.ownerPlayer().getArea();
int index = area.indexOf(fromCard);
area.remove(index);
fromCard.useEffects(EffectTiming.WhenNoLongerAtArea);
// 要变成随从
if (toCard instanceof AreaCard areaCard) {
area.add(index, areaCard);
areaCard.useEffects(EffectTiming.WhenAtArea);
} else {
msg(toCard.getNameWithOwner()+ "无法留在战场而被除外!");
exile(toCard);
}
}else {
List<Card> where = fromCard.where();
int index = where.indexOf(fromCard);
where.remove(index);
where.add(index,toCard);
}
}
public void exile(Card card){
exile(List.of(card));
}
public void exile(List<Card> cards){
if(cards.isEmpty())return;
msg(cards.stream().map(Card::getNameWithOwner).collect(Collectors.joining("、"))+ "从游戏中除外!");
cards.forEach(card ->{
if(card.where()==null)return;
// 场上卡除外时,有机会发动离场时效果
if (card.atArea() && card instanceof AreaCard areaCard){
if(areaCard.hasKeyword("魔法免疫")){
areaCard.getInfo().msg(areaCard.getNameWithOwner() + "免疫了本次除外!");
return;
}
if(areaCard.hasKeyword("魔法护盾")){
areaCard.getInfo().msg(areaCard.getNameWithOwner() + "的魔法护盾抵消了本次除外!");
areaCard.removeKeyword("魔法护盾");
return;
}
card.removeWhenAtArea();
card.tempEffects(EffectTiming.Leaving);
// 场上随从除外时,装备也除外
if(card instanceof FollowCard followCard && followCard.equipped())
exile(followCard.getEquipment());
}else
card.removeWhenNotAtArea();
card.tempEffects(EffectTiming.Exile);
if(card.hasKeyword("恶魔转生")){
List<Card> totalCard = new ArrayList<>();
totalCard.addAll(thisPlayer().getHand().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(thisPlayer().getArea().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(thisPlayer().getGraveyard().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(thisPlayer().getDeck().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getHand().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getArea().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getGraveyard().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getDeck().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
if(totalCard.isEmpty()){
msg("游戏中只剩下恶魔牌,"+card.getNameWithOwner()+"已经无法转生");
return;
}
Card luckyCard = Lists.randOf(totalCard);
Card newCard = card.createCard(card.getClass());
transform(luckyCard,newCard);
}
});
startEffect();
}
public void damageMulti(GameObj from,List<GameObj> objs, int damage){
List<Damage> damages = objs.stream().map(obj -> new Damage(from, obj, damage)).toList();
new DamageMulti(this,damages).apply();
}
public void damageAttacking(FollowCard from, GameObj to){
if(to instanceof FollowCard && !from.hasKeyword("远程") && !((FollowCard) to).hasKeyword("眩晕"))
new DamageMulti(this,List.of(new Damage(from,to), new Damage(to,from))).apply();
else
new DamageMulti(this,List.of(new Damage(from,to))).apply();
}
public void damageEffect(GameObj from,GameObj to, int damage){
new DamageMulti(this,List.of(new Damage(from,to,damage))).apply();
}
// endregion event
public List<AreaCard> getAreaCardsCopy(){
List<AreaCard> _result = new ArrayList<>();
_result.addAll(thisPlayer().getArea());
_result.addAll(oppositePlayer().getArea());
return _result;
}
public List<GameObj> getTargetableGameObj(){
List<GameObj> _result = new ArrayList<>();
_result.addAll(thisPlayer().getAreaFollows());
_result.addAll(oppositePlayer().getAreaFollows());
_result.add(thisPlayer().getLeader());
_result.add(oppositePlayer().getLeader());
return _result;
}
public List<AreaCard> getAreaFollowsCopy(){
List<AreaCard> _result = new ArrayList<>();
_result.addAll(thisPlayer().getAreaFollows());
_result.addAll(oppositePlayer().getAreaFollows());
return _result;
}
public List<GameObj> getAreaFollowsAsGameObj(){
List<GameObj> _result = new ArrayList<>();
_result.addAll(thisPlayer().getAreaFollows());
_result.addAll(oppositePlayer().getAreaFollows());
return _result;
}
// region turn
public void beginGame(){
Leader leader = thisPlayer().getLeader();
leader.setCanUseSkill(true);
leader.useEffects(EffectTiming.BeginGame);
Leader enemyLeader = oppositePlayer().getLeader();
enemyLeader.useEffects(EffectTiming.BeginGame);
Msg.send(thisPlayer().getSession(),"swapOver","");
Msg.send(oppositePlayer().getSession(),"swapOver","");
}
public void zeroTurn(Session u0, Session u1){
PlayerInfo p0 = thisPlayer();
PlayerDeck playerDeck0 = userDecks.get(u0);
p0.setSession(u0);
p0.setName(userNames.get(u0));
p0.setLeader(playerDeck0.getLeader(0, this));
p0.setDeck(playerDeck0.getActiveDeckInstance(0, this));
Collections.shuffle(p0.getDeck());
PlayerInfo p1 = oppositePlayer();
PlayerDeck playerDeck1 = userDecks.get(u1);
p1.setSession(u1);
p1.setName(userNames.get(u1));
p1.setLeader(playerDeck1.getLeader(1, this));
p1.setDeck(playerDeck1.getActiveDeckInstance(1, this));
Collections.shuffle(p1.getDeck());
p0.getLeader().init();
p1.getLeader().init();
p0.draw(3);
p1.draw(3);
msg("游戏开始,请选择3张手牌交换");
Msg.send(p0.getSession(),"swap",p0.getHand());
Msg.send(p1.getSession(),"swap",p1.getHand());
}
public void startTurn(){
thisPlayer().clearCount(PLAY_NUM);
thisPlayer().getPlayedCard().clear();
if(thisPlayer().ppMax<thisPlayer().getPpLimit()){
thisPlayer().ppMax++;
}
thisPlayer().ppNum = thisPlayer().ppMax;
msg("第" + turn + "回合:" + thisPlayer().getName()+"的回合,有" + thisPlayer().ppNum + "pp");
beforeTurn();
thisPlayer().draw(1);
if(thisPlayer().isShortRope()){
rope = roomSchedule.get(getRoom()).schedule(this::endTurnOfTimeout, 30, TimeUnit.SECONDS);
msg("倒计时30秒!");
}else{
rope = roomSchedule.get(getRoom()).schedule(this::endTurnOfTimeout, 300, TimeUnit.SECONDS);
msg("倒计时300秒!");
}
pushInfo();
msgToThisPlayer("请出牌!");
msgToOppositePlayer("等待对手出牌......");
Msg.send(thisPlayer().getSession(),"yourTurn","");
Msg.send(oppositePlayer().getSession(),"enemyTurn","");
if(turn==10){// TODO 活动模式,第10回合奖励
final List<Class<? extends Card>> classes = CardPackage.randCard("passive", 3);
final List<Card> list = classes.stream().map(clazz -> (Card)thisPlayer().getLeader().createCard(clazz)).toList();
thisPlayer().discoverCard(list,card -> card.getPlay().effect().accept(0,new ArrayList<>()));
}
}
public void endTurnOfTimeout(){
thisPlayer().setShortRope(true);
endTurn();
}
public void endTurnOfCommand(){
thisPlayer().setShortRope(false);
rope.cancel(true);
endTurn();
}
public void endTurn(){
thisPlayer().autoDiscover();
msg(thisPlayer().getName()+"的回合结束");
try {
afterTurn();
}catch (Exception e){
e.printStackTrace();
}
if(thisPlayer().getStep() == -1)return;// 回合结束效果触发了重启游戏
// 是否有追加回合
if(moreTurn>0){
moreTurn--;
}else {
turn += turnPlayer;// 如果是玩家1就加回合数
turnPlayer = 1 ^ turnPlayer;
}
msg("——————————");
startTurn();
}
public void beforeTurn(){
// 场上随从驻场回合+1、攻击次数清零
// 发动回合开始效果
// 场上护符倒数-1
oppositePlayer().getAreaCopy().forEach(enemyAreaCard -> {
if(!enemyAreaCard.atArea())return;
enemyAreaCard.useEffects(EffectTiming.EnemyBeginTurn);
if(!enemyAreaCard.atArea())return;
if(enemyAreaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.EnemyBeginTurn);
}
if(enemyAreaCard instanceof FollowCard followCard){
followCard.setTurnAttack(0);
followCard.removeKeyword("眩晕");
followCard.removeKeyword("冻结");
// followCard.removeKeywordAll("格挡");
}
});
thisPlayer().getAreaCopy().forEach(areaCard -> {
if(!areaCard.atArea())return;
areaCard.useEffects(EffectTiming.BeginTurn);
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.BeginTurn);
}
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard){
int turnAgePlus = followCard.getTurnAge() + 1;
followCard.setTurnAge(turnAgePlus);
followCard.setTurnAttack(0);
}
if(areaCard instanceof AmuletCard amuletCard){
int countDown = amuletCard.getCountDown();
if(countDown > 0){
amuletCard.countDown();
}
}
});
// 查找牌堆是否有瞬召卡牌,同名字卡牌各取一张
Map<String, GameObj> nameCard =
thisPlayer().getDeck().stream().collect(Collectors.toMap(Card::getName, o -> o, (a,b)->a));
// 瞬召卡牌
useEffectBatch(new ArrayList<>(nameCard.values()),EffectTiming.InvocationBegin);
// 主战者技能重置、发动主战者效果和手牌效果
Leader leader = thisPlayer().getLeader();
leader.setCanUseSkill(true);
leader.useEffects(EffectTiming.BeginTurn);
thisPlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.BeginTurnAtHand));
Leader enemyLeader = oppositePlayer().getLeader();
enemyLeader.useEffects(EffectTiming.EnemyBeginTurn);
oppositePlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.EnemyBeginTurnAtHand));
}
public void afterTurn(){
// 对手中毒效果
final Integer poison = oppositePlayer().getCount(POISON);
if(poison>0){
msg(oppositePlayer().getLeader().getNameWithOwner() + "受到"+poison+"点中毒伤害");
damageEffect(thisPlayer().getLeader(), oppositePlayer().getLeader(), poison);
oppositePlayer().count(POISON,-1);
}
oppositePlayer().getAreaCopy().forEach(areaCard -> {
if(areaCard instanceof FollowCard followCard && followCard.hasKeyword("中毒")){
final int poison1 = followCard.countKeyword("中毒");
msg(followCard.getNameWithOwner() + "受到"+poison1+"点中毒伤害");
damageEffect(followCard, followCard, poison1);
}
});
// 发动回合结束效果
oppositePlayer().getAreaCopy().forEach(areaCard -> {
if(!areaCard.atArea())return;
areaCard.useEffects(EffectTiming.EnemyEndTurn);
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.EnemyEndTurn);
}
});
thisPlayer().getAreaCopy().forEach(areaCard -> {
if(!areaCard.atArea())return;
areaCard.useEffects(EffectTiming.EndTurn);
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.EndTurn);
}
});
thisPlayer().getHandCopy().forEach(card -> {
if(card.hasKeyword("虚无")){
thisPlayer().abandon(card);
}
});
// 查找牌堆是否有瞬召卡牌,同名字卡牌各取一张
Map<String, GameObj> nameCard =
thisPlayer().getDeck().stream().collect(Collectors.toMap(Card::getName, o -> o, (a,b)->a));
// 瞬召卡牌
useEffectBatch(new ArrayList<>(nameCard.values()),EffectTiming.InvocationEnd);
// 发动主战者效果
Leader leader = thisPlayer().getLeader();
leader.useEffects(EffectTiming.EndTurn);
leader.expireEffect();
thisPlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.EndTurnAtHand));
thisPlayer().setHandPlayable(card -> true);
Leader enemyLeader = oppositePlayer().getLeader();
enemyLeader.useEffects(EffectTiming.EnemyEndTurn);
enemyLeader.expireEffect();
oppositePlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.EnemyEndTurnAtHand));
}
public void addMoreTurn(){
moreTurn++;
}
// endregion turn
}
| 476106017/ccg4j | src/main/java/org/example/game/GameInfo.java | 6,639 | // msg("——————开始触发事件——————"); | line_comment | zh-cn | package org.example.game;
import jakarta.websocket.Session;
import lombok.Getter;
import lombok.Setter;
import org.example.card.*;
import org.example.constant.EffectTiming;
import org.example.system.util.CardPackage;
import org.example.system.util.Lists;
import org.example.system.util.Maps;
import org.example.system.util.Msg;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.example.constant.CounterKey.PLAY_NUM;
import static org.example.constant.CounterKey.POISON;
import static org.example.system.Database.*;
@Getter
@Setter
public class GameInfo implements Serializable {
String room;
// 连锁
boolean canChain = true;
int chainDeep = 3;
boolean inSettle = false;
int turn;
int turnPlayer;
int moreTurn = 0;// 追加回合
boolean gameset = false;
ScheduledFuture<?> rope;
List<Damage> incommingDamages = new ArrayList<>();
Map<Card,EventType> events = new HashMap<>();
List<Effect.EffectInstance> effectInstances = new LinkedList<>();
public boolean hasEvent(){
return !incommingDamages.isEmpty() || !events.isEmpty();
}
public void setCanChain(boolean canChain) {
if (canChain)
msg("本场游戏已启用连锁");
else
msg("本场游戏已禁用连锁");
this.canChain = canChain;
}
PlayerInfo[] playerInfos;
public GameInfo(String room) {
this.room = room;
this.turn = 1;
this.turnPlayer = 0;
this.playerInfos = new PlayerInfo[2];
this.playerInfos[0] = new PlayerInfo(this,true);
this.playerInfos[1] = new PlayerInfo(this,false);
}
public void resetGame(){
msg("游戏重启!");
roomSchedule.get(getRoom()).shutdown();
roomSchedule.remove(getRoom());
rope.cancel(true);
this.turn = 1;
this.turnPlayer = 0;
Session thisSession = thisPlayer().session;
Session oppoSession = oppositePlayer().session;
this.playerInfos = new PlayerInfo[2];
this.playerInfos[0] = new PlayerInfo(this,true);
this.playerInfos[1] = new PlayerInfo(this,false);
zeroTurn(thisSession,oppoSession);
}
public void msg(String msg){
try {
Msg.send(thisPlayer().getSession(),msg);
Msg.send(oppositePlayer().getSession(),msg);
} catch (Exception ignored) {}
}
public void story(String msg){
try {
Msg.story(thisPlayer().getSession(),msg);
Msg.story(oppositePlayer().getSession(),msg);
} catch (Exception ignored) {}
}
public void msgTo(Session session, String msg){
Msg.send(session,msg);
}
public void pushInfo(){
final PlayerInfo thisPlayer = thisPlayer();
thisPlayer.setDeckCount(thisPlayer.getDeck().size());
final PlayerInfo oppositePlayer = oppositePlayer();
oppositePlayer.setDeckCount(oppositePlayer.getDeck().size());
// region 加载补充信息
thisPlayer.getAreaAsCard().forEach(f->f.setSubMarkStr(f.getSubMark()));
thisPlayer.getHand().forEach(f->f.setSubMarkStr(f.getSubMark()));
oppositePlayer.getAreaAsCard().forEach(f->f.setSubMarkStr(f.getSubMark()));
// endregion 加载补充信息
thisPlayer.getAreaAsCard().forEach(f->f.setSubMarkStr(f.getSubMark()));
thisPlayer.getAreaFollowsAsFollow().forEach(f->{
// 回合可攻击数没有打满
final boolean notAttacked = f.getTurnAttack() < f.getTurnAttackMax();
// 状态正常
final boolean normalStatus = !f.hasKeyword("缴械") && !f.hasKeyword("眩晕") && !f.hasKeyword("冻结");
final boolean canAttack = notAttacked && normalStatus &&
(f.getTurnAge() > 0 || f.hasKeyword("疾驰"));
final boolean canDash = notAttacked && normalStatus &&
(f.getTurnAge() == 0 && !f.hasKeyword("疾驰") && f.hasKeyword("突进"));
f.setCanAttack(canAttack);
f.setCanDash(canDash);
});
Msg.send(thisPlayer.getSession(),"battleInfo",
Maps.newMap("me", thisPlayer,"enemy", oppositePlayer));
Msg.send(oppositePlayer.getSession(),"battleInfo",
Maps.newMap("me", oppositePlayer,"enemy", thisPlayer));
}
public void msgToThisPlayer(String msg){
Msg.send(thisPlayer().getSession(),msg);
}
public void msgToOppositePlayer(String msg){
Msg.send(oppositePlayer().getSession(),msg);
}
public void measureLeader(){
if(thisPlayer().getHp()<=0)
gameset(oppositePlayer());
if(oppositePlayer().getHp()<=0)
gameset(thisPlayer());
}
public void measureFollows(){
// msg("——————结算卡牌状态——————");
// 立即结算受伤状态
List<Damage> incommingDamagesCopy = new ArrayList<>(incommingDamages);
incommingDamages = new ArrayList<>();
incommingDamagesCopy.forEach(damage->{
damage.getTo().useEffects(EffectTiming.AfterDamaged,damage);
});
Map<Card, EventType> eventsCopy = events;
events = new HashMap<>();
// 再结算其他状态
eventsCopy.forEach((card, type) -> {
switch (type){
case Destroy -> {
if(card instanceof AreaCard areaCard) areaCard.destroyed();
}
}
});
assert events.isEmpty();
}
public void gameset(PlayerInfo winner){
gameset = true;
msg("游戏结束,获胜者:"+winner.getName());
pushInfo();
final Session winnerSession = winner.getSession();
Msg.send(winnerSession,"alert","你赢了!");
Msg.send(anotherPlayerBySession(winnerSession).getSession(),"alert","你输了!");
// 释放资源
roomGame.remove(getRoom());
// 退出房间
try {
userRoom.remove(thisPlayer().getSession());
msgToThisPlayer("离开房间成功");
userRoom.remove(oppositePlayer().getSession());
msgToOppositePlayer("离开房间成功");
rope.cancel(true);
ScheduledExecutorService ses = roomSchedule.get(getRoom());
ses.shutdown();
roomSchedule.remove(getRoom());
}catch (Exception e){e.printStackTrace();}
throw new RuntimeException("Game Set");
}
public PlayerInfo thisPlayer(){
return playerInfos[turnPlayer];
}
public PlayerInfo oppositePlayer(){
return playerInfos[1-turnPlayer];
}
public PlayerInfo playerBySession(Session session){
if(playerInfos[0].session == session){
return playerInfos[0];
}else {
return playerInfos[1];
}
}
public PlayerInfo anotherPlayerBySession(Session session){
if(playerInfos[0].session == session){
return playerInfos[1];
}else {
return playerInfos[0];
}
}
// region effect
public boolean addEvent(Card card,EventType type){
EventType oldType = events.get(card);
if(oldType != null){
// msg(card.getNameWithOwner() + "已经被" + oldType.getName() + ",无法再被" + type.getName());
return false;
}
// msg(card.getNameWithOwner() + "的" + type.getName() + "状态已加入队列");
events.put(card,type);
return true;
}
public void useAreaCardEffectBatch(List<AreaCard> cards, EffectTiming timing){
List<GameObj> gameObjs = cards.stream().map(p -> (GameObj) p).toList();
tempEffectBatch(gameObjs,timing);
startEffect();
}
public void useAreaCardEffectBatch(List<AreaCard> cards, EffectTiming timing,Object param){
List<GameObj> gameObjs = cards.stream().map(p -> (GameObj) p).toList();
tempEffectBatch(gameObjs,timing,param);
startEffect();
}
public void useEffectBatch(List<GameObj> objs, EffectTiming timing){
tempEffectBatch(objs,timing);
startEffect();
}
public void tempEffectBatch(List<GameObj> objs, EffectTiming timing,Object param){
objs.forEach(obj -> obj.tempEffects(timing,param));
}
public void tempEffectBatch(List<GameObj> objs, EffectTiming timing){
objs.forEach(obj -> obj.tempEffects(timing));
}
public void tempCardEffectBatch(List<Card> objs, EffectTiming timing){
objs.forEach(obj -> obj.tempEffects(timing));
}
public void tempCardEffectBatch(List<Card> objs, EffectTiming timing, Object param) {
objs.forEach(obj -> obj.tempEffects(timing,param));
}
public void tempAreaCardEffectBatch(List<AreaCard> objs, EffectTiming timing){
objs.forEach(obj -> obj.tempEffects(timing));
}
public void tempAreaCardEffectBatch(List<AreaCard> objs, EffectTiming timing,Object param){
objs.forEach(obj -> obj.tempEffects(timing,param));
}
public void tempEffect(Effect.EffectInstance instance){
Effect effect = instance.getEffect();
effectInstances.add(instance);
// msg(effect.getOwnerObj().getNameWithOwner()+"的【"+effect.getTiming().getName()+"】效果已加入队列" +
// "(队列现在有" + effectInstances.size() + "个效果)");
}
// 结算效果
public void startEffect(){
if(inSettle)return;
inSettle = true;
// msg("——————开始结算——————");
consumeEffectChain(chainDeep);
// 计算主战者死亡状况
measureLeader();
inSettle = false;
}
public void consumeEffectChain(int deep){
// ms <SUF>
measureFollows();
// msg("——————开始触发效果——————");
consumeEffect();
// msg("——————停止触发效果——————");
if(hasEvent()){
if(!canChain || deep==0){
msg("停止连锁!本次死亡结算后不触发任何效果");
measureFollows();
effectInstances.clear();
events.clear();
return;
}
// msg("——————事件连锁("+deep+")——————");
consumeEffectChain(deep - 1);
}
}
public void consumeEffect(){
if(effectInstances.isEmpty()) return;
effectInstances.sort((o1, o2) -> {
for (EffectTiming value : EffectTiming.values()) {
if(value.equals(o1.getEffect().getTiming()))
return -1;
else if(value.equals(o2.getEffect().getTiming()))
return 1;
}
return 0;
});
List<Effect.EffectInstance> instances = new ArrayList<>(effectInstances);
instances.forEach(Effect.EffectInstance::consume);
effectInstances.clear();
}
// endregion effect
// region event
public void transform(Card fromCard, Card toCard){
msg(fromCard.getNameWithOwnerWithPlace()+ "变身成了" + toCard.getId());
if(fromCard.atArea()){
if(fromCard.hasKeyword("魔法免疫")){
fromCard.getInfo().msg(fromCard.getNameWithOwner() + "免疫了本次变身!");
return;
}
if(fromCard.hasKeyword("魔法护盾")){
fromCard.getInfo().msg(fromCard.getNameWithOwner() + "的魔法护盾抵消了本次变身!");
fromCard.removeKeyword("魔法护盾");
return;
}
List<AreaCard> area = fromCard.ownerPlayer().getArea();
int index = area.indexOf(fromCard);
area.remove(index);
fromCard.useEffects(EffectTiming.WhenNoLongerAtArea);
// 要变成随从
if (toCard instanceof AreaCard areaCard) {
area.add(index, areaCard);
areaCard.useEffects(EffectTiming.WhenAtArea);
} else {
msg(toCard.getNameWithOwner()+ "无法留在战场而被除外!");
exile(toCard);
}
}else {
List<Card> where = fromCard.where();
int index = where.indexOf(fromCard);
where.remove(index);
where.add(index,toCard);
}
}
public void exile(Card card){
exile(List.of(card));
}
public void exile(List<Card> cards){
if(cards.isEmpty())return;
msg(cards.stream().map(Card::getNameWithOwner).collect(Collectors.joining("、"))+ "从游戏中除外!");
cards.forEach(card ->{
if(card.where()==null)return;
// 场上卡除外时,有机会发动离场时效果
if (card.atArea() && card instanceof AreaCard areaCard){
if(areaCard.hasKeyword("魔法免疫")){
areaCard.getInfo().msg(areaCard.getNameWithOwner() + "免疫了本次除外!");
return;
}
if(areaCard.hasKeyword("魔法护盾")){
areaCard.getInfo().msg(areaCard.getNameWithOwner() + "的魔法护盾抵消了本次除外!");
areaCard.removeKeyword("魔法护盾");
return;
}
card.removeWhenAtArea();
card.tempEffects(EffectTiming.Leaving);
// 场上随从除外时,装备也除外
if(card instanceof FollowCard followCard && followCard.equipped())
exile(followCard.getEquipment());
}else
card.removeWhenNotAtArea();
card.tempEffects(EffectTiming.Exile);
if(card.hasKeyword("恶魔转生")){
List<Card> totalCard = new ArrayList<>();
totalCard.addAll(thisPlayer().getHand().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(thisPlayer().getArea().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(thisPlayer().getGraveyard().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(thisPlayer().getDeck().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getHand().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getArea().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getGraveyard().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
totalCard.addAll(oppositePlayer().getDeck().stream()
.filter(c -> c instanceof FollowCard f
&& !f.hasKeyword("恶魔转生")).toList());
if(totalCard.isEmpty()){
msg("游戏中只剩下恶魔牌,"+card.getNameWithOwner()+"已经无法转生");
return;
}
Card luckyCard = Lists.randOf(totalCard);
Card newCard = card.createCard(card.getClass());
transform(luckyCard,newCard);
}
});
startEffect();
}
public void damageMulti(GameObj from,List<GameObj> objs, int damage){
List<Damage> damages = objs.stream().map(obj -> new Damage(from, obj, damage)).toList();
new DamageMulti(this,damages).apply();
}
public void damageAttacking(FollowCard from, GameObj to){
if(to instanceof FollowCard && !from.hasKeyword("远程") && !((FollowCard) to).hasKeyword("眩晕"))
new DamageMulti(this,List.of(new Damage(from,to), new Damage(to,from))).apply();
else
new DamageMulti(this,List.of(new Damage(from,to))).apply();
}
public void damageEffect(GameObj from,GameObj to, int damage){
new DamageMulti(this,List.of(new Damage(from,to,damage))).apply();
}
// endregion event
public List<AreaCard> getAreaCardsCopy(){
List<AreaCard> _result = new ArrayList<>();
_result.addAll(thisPlayer().getArea());
_result.addAll(oppositePlayer().getArea());
return _result;
}
public List<GameObj> getTargetableGameObj(){
List<GameObj> _result = new ArrayList<>();
_result.addAll(thisPlayer().getAreaFollows());
_result.addAll(oppositePlayer().getAreaFollows());
_result.add(thisPlayer().getLeader());
_result.add(oppositePlayer().getLeader());
return _result;
}
public List<AreaCard> getAreaFollowsCopy(){
List<AreaCard> _result = new ArrayList<>();
_result.addAll(thisPlayer().getAreaFollows());
_result.addAll(oppositePlayer().getAreaFollows());
return _result;
}
public List<GameObj> getAreaFollowsAsGameObj(){
List<GameObj> _result = new ArrayList<>();
_result.addAll(thisPlayer().getAreaFollows());
_result.addAll(oppositePlayer().getAreaFollows());
return _result;
}
// region turn
public void beginGame(){
Leader leader = thisPlayer().getLeader();
leader.setCanUseSkill(true);
leader.useEffects(EffectTiming.BeginGame);
Leader enemyLeader = oppositePlayer().getLeader();
enemyLeader.useEffects(EffectTiming.BeginGame);
Msg.send(thisPlayer().getSession(),"swapOver","");
Msg.send(oppositePlayer().getSession(),"swapOver","");
}
public void zeroTurn(Session u0, Session u1){
PlayerInfo p0 = thisPlayer();
PlayerDeck playerDeck0 = userDecks.get(u0);
p0.setSession(u0);
p0.setName(userNames.get(u0));
p0.setLeader(playerDeck0.getLeader(0, this));
p0.setDeck(playerDeck0.getActiveDeckInstance(0, this));
Collections.shuffle(p0.getDeck());
PlayerInfo p1 = oppositePlayer();
PlayerDeck playerDeck1 = userDecks.get(u1);
p1.setSession(u1);
p1.setName(userNames.get(u1));
p1.setLeader(playerDeck1.getLeader(1, this));
p1.setDeck(playerDeck1.getActiveDeckInstance(1, this));
Collections.shuffle(p1.getDeck());
p0.getLeader().init();
p1.getLeader().init();
p0.draw(3);
p1.draw(3);
msg("游戏开始,请选择3张手牌交换");
Msg.send(p0.getSession(),"swap",p0.getHand());
Msg.send(p1.getSession(),"swap",p1.getHand());
}
public void startTurn(){
thisPlayer().clearCount(PLAY_NUM);
thisPlayer().getPlayedCard().clear();
if(thisPlayer().ppMax<thisPlayer().getPpLimit()){
thisPlayer().ppMax++;
}
thisPlayer().ppNum = thisPlayer().ppMax;
msg("第" + turn + "回合:" + thisPlayer().getName()+"的回合,有" + thisPlayer().ppNum + "pp");
beforeTurn();
thisPlayer().draw(1);
if(thisPlayer().isShortRope()){
rope = roomSchedule.get(getRoom()).schedule(this::endTurnOfTimeout, 30, TimeUnit.SECONDS);
msg("倒计时30秒!");
}else{
rope = roomSchedule.get(getRoom()).schedule(this::endTurnOfTimeout, 300, TimeUnit.SECONDS);
msg("倒计时300秒!");
}
pushInfo();
msgToThisPlayer("请出牌!");
msgToOppositePlayer("等待对手出牌......");
Msg.send(thisPlayer().getSession(),"yourTurn","");
Msg.send(oppositePlayer().getSession(),"enemyTurn","");
if(turn==10){// TODO 活动模式,第10回合奖励
final List<Class<? extends Card>> classes = CardPackage.randCard("passive", 3);
final List<Card> list = classes.stream().map(clazz -> (Card)thisPlayer().getLeader().createCard(clazz)).toList();
thisPlayer().discoverCard(list,card -> card.getPlay().effect().accept(0,new ArrayList<>()));
}
}
public void endTurnOfTimeout(){
thisPlayer().setShortRope(true);
endTurn();
}
public void endTurnOfCommand(){
thisPlayer().setShortRope(false);
rope.cancel(true);
endTurn();
}
public void endTurn(){
thisPlayer().autoDiscover();
msg(thisPlayer().getName()+"的回合结束");
try {
afterTurn();
}catch (Exception e){
e.printStackTrace();
}
if(thisPlayer().getStep() == -1)return;// 回合结束效果触发了重启游戏
// 是否有追加回合
if(moreTurn>0){
moreTurn--;
}else {
turn += turnPlayer;// 如果是玩家1就加回合数
turnPlayer = 1 ^ turnPlayer;
}
msg("——————————");
startTurn();
}
public void beforeTurn(){
// 场上随从驻场回合+1、攻击次数清零
// 发动回合开始效果
// 场上护符倒数-1
oppositePlayer().getAreaCopy().forEach(enemyAreaCard -> {
if(!enemyAreaCard.atArea())return;
enemyAreaCard.useEffects(EffectTiming.EnemyBeginTurn);
if(!enemyAreaCard.atArea())return;
if(enemyAreaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.EnemyBeginTurn);
}
if(enemyAreaCard instanceof FollowCard followCard){
followCard.setTurnAttack(0);
followCard.removeKeyword("眩晕");
followCard.removeKeyword("冻结");
// followCard.removeKeywordAll("格挡");
}
});
thisPlayer().getAreaCopy().forEach(areaCard -> {
if(!areaCard.atArea())return;
areaCard.useEffects(EffectTiming.BeginTurn);
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.BeginTurn);
}
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard){
int turnAgePlus = followCard.getTurnAge() + 1;
followCard.setTurnAge(turnAgePlus);
followCard.setTurnAttack(0);
}
if(areaCard instanceof AmuletCard amuletCard){
int countDown = amuletCard.getCountDown();
if(countDown > 0){
amuletCard.countDown();
}
}
});
// 查找牌堆是否有瞬召卡牌,同名字卡牌各取一张
Map<String, GameObj> nameCard =
thisPlayer().getDeck().stream().collect(Collectors.toMap(Card::getName, o -> o, (a,b)->a));
// 瞬召卡牌
useEffectBatch(new ArrayList<>(nameCard.values()),EffectTiming.InvocationBegin);
// 主战者技能重置、发动主战者效果和手牌效果
Leader leader = thisPlayer().getLeader();
leader.setCanUseSkill(true);
leader.useEffects(EffectTiming.BeginTurn);
thisPlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.BeginTurnAtHand));
Leader enemyLeader = oppositePlayer().getLeader();
enemyLeader.useEffects(EffectTiming.EnemyBeginTurn);
oppositePlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.EnemyBeginTurnAtHand));
}
public void afterTurn(){
// 对手中毒效果
final Integer poison = oppositePlayer().getCount(POISON);
if(poison>0){
msg(oppositePlayer().getLeader().getNameWithOwner() + "受到"+poison+"点中毒伤害");
damageEffect(thisPlayer().getLeader(), oppositePlayer().getLeader(), poison);
oppositePlayer().count(POISON,-1);
}
oppositePlayer().getAreaCopy().forEach(areaCard -> {
if(areaCard instanceof FollowCard followCard && followCard.hasKeyword("中毒")){
final int poison1 = followCard.countKeyword("中毒");
msg(followCard.getNameWithOwner() + "受到"+poison1+"点中毒伤害");
damageEffect(followCard, followCard, poison1);
}
});
// 发动回合结束效果
oppositePlayer().getAreaCopy().forEach(areaCard -> {
if(!areaCard.atArea())return;
areaCard.useEffects(EffectTiming.EnemyEndTurn);
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.EnemyEndTurn);
}
});
thisPlayer().getAreaCopy().forEach(areaCard -> {
if(!areaCard.atArea())return;
areaCard.useEffects(EffectTiming.EndTurn);
if(!areaCard.atArea())return;
if(areaCard instanceof FollowCard followCard && followCard.equipped()){
EquipmentCard equipment = followCard.getEquipment();
equipment.useEffects(EffectTiming.EndTurn);
}
});
thisPlayer().getHandCopy().forEach(card -> {
if(card.hasKeyword("虚无")){
thisPlayer().abandon(card);
}
});
// 查找牌堆是否有瞬召卡牌,同名字卡牌各取一张
Map<String, GameObj> nameCard =
thisPlayer().getDeck().stream().collect(Collectors.toMap(Card::getName, o -> o, (a,b)->a));
// 瞬召卡牌
useEffectBatch(new ArrayList<>(nameCard.values()),EffectTiming.InvocationEnd);
// 发动主战者效果
Leader leader = thisPlayer().getLeader();
leader.useEffects(EffectTiming.EndTurn);
leader.expireEffect();
thisPlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.EndTurnAtHand));
thisPlayer().setHandPlayable(card -> true);
Leader enemyLeader = oppositePlayer().getLeader();
enemyLeader.useEffects(EffectTiming.EnemyEndTurn);
enemyLeader.expireEffect();
oppositePlayer().getHandCopy().forEach(card -> card.useEffects(EffectTiming.EnemyEndTurnAtHand));
}
public void addMoreTurn(){
moreTurn++;
}
// endregion turn
}
| 0 |
44464_0 | package org.example.constant;
import org.example.system.Database;
import org.example.system.game.Leader;
import org.example.turnobj.FollowCard;
import org.example.turnobj.ThePlayer;
import org.example.system.util.Maps;
import org.example.turnobj.dota.幻影刺客;
import org.example.turnobj.dota.敌法师;
import org.example.turnobj.dota.斧王;
import org.example.turnobj.dota.鱼人夜行者;
import org.example.turnobj.hsr.三月七;
import org.example.turnobj.hsr.丹恒;
import org.example.turnobj.hsr.开拓者;
import org.example.turnobj.hsr.艾丝妲;
import org.example.turnobj.jojo.EnricoPucci;
import org.example.turnobj.pokemon.Fusigidane;
import org.example.turnobj.pokemon.Hitokage;
import org.example.turnobj.pokemon.Pikachu;
import org.example.turnobj.pokemon.Zenigame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 预置牌组
*/
public class DeckPreset {
public static final Map<String,List<Class<? extends FollowCard>>> decks = new HashMap<>();
public static final Map<String,Class<? extends Leader>> deckLeader = new HashMap<>();
static {
decks.put("宝可梦御三家",List.of(
Pikachu.class, Zenigame.class, Hitokage.class, Fusigidane.class
));
decks.put("普奇神父完全体",List.of(
EnricoPucci.class
));
decks.put("星穹列车组",List.of(
开拓者.class, 三月七.class, 丹恒.class, 艾丝妲.class
));
decks.put("DotA",List.of(
鱼人夜行者.class, 敌法师.class, 斧王.class, 幻影刺客.class
));
}
public static List describe(){
List<Map<String,Object>> deckInfo = new ArrayList<>();
decks.forEach((name,cardClassList)-> {
final List<? extends FollowCard> prototypes = cardClassList.stream().map(Database::getPrototype).toList();
Leader leader;
try {
Class<? extends Leader> leaderClass = DeckPreset.deckLeader.get(name);
if(leaderClass==null){
leaderClass = ThePlayer.class;
}
leader = leaderClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
deckInfo.add(Maps.newMap("name", name, "leader", leader,"deck", prototypes));
});
return deckInfo;
}
}
| 476106017/tbs4j | src/main/java/org/example/constant/DeckPreset.java | 738 | /**
* 预置牌组
*/ | block_comment | zh-cn | package org.example.constant;
import org.example.system.Database;
import org.example.system.game.Leader;
import org.example.turnobj.FollowCard;
import org.example.turnobj.ThePlayer;
import org.example.system.util.Maps;
import org.example.turnobj.dota.幻影刺客;
import org.example.turnobj.dota.敌法师;
import org.example.turnobj.dota.斧王;
import org.example.turnobj.dota.鱼人夜行者;
import org.example.turnobj.hsr.三月七;
import org.example.turnobj.hsr.丹恒;
import org.example.turnobj.hsr.开拓者;
import org.example.turnobj.hsr.艾丝妲;
import org.example.turnobj.jojo.EnricoPucci;
import org.example.turnobj.pokemon.Fusigidane;
import org.example.turnobj.pokemon.Hitokage;
import org.example.turnobj.pokemon.Pikachu;
import org.example.turnobj.pokemon.Zenigame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 预置牌 <SUF>*/
public class DeckPreset {
public static final Map<String,List<Class<? extends FollowCard>>> decks = new HashMap<>();
public static final Map<String,Class<? extends Leader>> deckLeader = new HashMap<>();
static {
decks.put("宝可梦御三家",List.of(
Pikachu.class, Zenigame.class, Hitokage.class, Fusigidane.class
));
decks.put("普奇神父完全体",List.of(
EnricoPucci.class
));
decks.put("星穹列车组",List.of(
开拓者.class, 三月七.class, 丹恒.class, 艾丝妲.class
));
decks.put("DotA",List.of(
鱼人夜行者.class, 敌法师.class, 斧王.class, 幻影刺客.class
));
}
public static List describe(){
List<Map<String,Object>> deckInfo = new ArrayList<>();
decks.forEach((name,cardClassList)-> {
final List<? extends FollowCard> prototypes = cardClassList.stream().map(Database::getPrototype).toList();
Leader leader;
try {
Class<? extends Leader> leaderClass = DeckPreset.deckLeader.get(name);
if(leaderClass==null){
leaderClass = ThePlayer.class;
}
leader = leaderClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
deckInfo.add(Maps.newMap("name", name, "leader", leader,"deck", prototypes));
});
return deckInfo;
}
}
| 0 |
40907_7 | package com.itheima.a04;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.support.GenericApplicationContext;
/*
bean 后处理器的作用
*/
public class A04 {
public static void main(String[] args) {
// ⬇️GenericApplicationContext 是一个【干净】的容器
GenericApplicationContext context = new GenericApplicationContext();
// ⬇️用原始方法注册三个 bean
context.registerBean("bean1", Bean1.class);
context.registerBean("bean2", Bean2.class);
context.registerBean("bean3", Bean3.class);
context.registerBean("bean4", Bean4.class);
context.getDefaultListableBeanFactory().setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
context.registerBean(AutowiredAnnotationBeanPostProcessor.class); // @Autowired @Value
context.registerBean(CommonAnnotationBeanPostProcessor.class); // @Resource @PostConstruct @PreDestroy
ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());
// ⬇️初始化容器
context.refresh(); // 执行beanFactory后处理器, 添加bean后处理器, 初始化所有单例
System.out.println(context.getBean(Bean1.class));
// ⬇️销毁容器
context.close();
/*
学到了什么
a. @Autowired 等注解的解析属于 bean 生命周期阶段(依赖注入, 初始化)的扩展功能
b. 这些扩展功能由 bean 后处理器来完成
*/
}
}
| 4rnold/CodeRepo | SpringBoot/spring-samples/src/main/java/com/itheima/a04/A04.java | 441 | // ⬇️销毁容器
| line_comment | zh-cn | package com.itheima.a04;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.support.GenericApplicationContext;
/*
bean 后处理器的作用
*/
public class A04 {
public static void main(String[] args) {
// ⬇️GenericApplicationContext 是一个【干净】的容器
GenericApplicationContext context = new GenericApplicationContext();
// ⬇️用原始方法注册三个 bean
context.registerBean("bean1", Bean1.class);
context.registerBean("bean2", Bean2.class);
context.registerBean("bean3", Bean3.class);
context.registerBean("bean4", Bean4.class);
context.getDefaultListableBeanFactory().setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
context.registerBean(AutowiredAnnotationBeanPostProcessor.class); // @Autowired @Value
context.registerBean(CommonAnnotationBeanPostProcessor.class); // @Resource @PostConstruct @PreDestroy
ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());
// ⬇️初始化容器
context.refresh(); // 执行beanFactory后处理器, 添加bean后处理器, 初始化所有单例
System.out.println(context.getBean(Bean1.class));
// ⬇️ <SUF>
context.close();
/*
学到了什么
a. @Autowired 等注解的解析属于 bean 生命周期阶段(依赖注入, 初始化)的扩展功能
b. 这些扩展功能由 bean 后处理器来完成
*/
}
}
| 0 |
46698_21 | package algorithms.困难;
public class 交错字符串97 {
// 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
//
// 示例 1:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
// 输出: true
// 示例 2:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
// 输出: false
//
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/interleaving-string
public static void main(String[] args) {
交错字符串97 solution = new 交错字符串97();
// int i = solution.romanToInt("IV");
// boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbcbcac");
boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbbaccc");
System.out.println(1);
}
// public boolean isInterleave(String s1, String s2, String s3) {
// if(s1.length() + s2.length() != s3.length()){
// return false;
// }
// List<String> collect3 = new ArrayList<>(Arrays.asList(s3.split("")));
// List<String> collect2 = new ArrayList<>(Arrays.asList(s2.split("")));
// List<String> collect1 = new ArrayList<>(Arrays.asList(s1.split("")));
// for (char c : s1.toCharArray()) {
// s3.indexOf(c);
// collect3.indexOf()
// }
//
//
// return false;
// }
int cur1 = 0, cur2 = 0, cur3 = 0; //三个指针,分别指向s1,s2,s3已经搜索到的位置
public boolean isInterleave(String s1, String s2, String s3) {
if (s1 == null && s2 == null && s3 == null) {
return true;
} else if (s1.length() + s2.length() != s3.length()) {
return false;
}
// 返回回溯结果
return recursive(s1, s2, s3);
}
public boolean recursive(String s1, String s2, String s3) {
// 递归终止条件:如果s3已经全部搜索完,则表明符合题意,返回true
if (cur3 >= s3.length()) {
return true;
}
if (cur1 < s1.length() && s3.charAt(cur3) == s1.charAt(cur1)) {
// 继续下一层回溯
cur1 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
// 还原指针
cur1 -= 1;
cur3 -= 1;
}
if (cur2 < s2.length() && s3.charAt(cur3) == s2.charAt(cur2)) {
cur2 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
cur2 -= 1;
cur3 -= 1;
}
return false;
}
}
| 501658362/JavaAlgorithms | src/main/java/algorithms/困难/交错字符串97.java | 846 | //三个指针,分别指向s1,s2,s3已经搜索到的位置 | line_comment | zh-cn | package algorithms.困难;
public class 交错字符串97 {
// 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
//
// 示例 1:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
// 输出: true
// 示例 2:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
// 输出: false
//
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/interleaving-string
public static void main(String[] args) {
交错字符串97 solution = new 交错字符串97();
// int i = solution.romanToInt("IV");
// boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbcbcac");
boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbbaccc");
System.out.println(1);
}
// public boolean isInterleave(String s1, String s2, String s3) {
// if(s1.length() + s2.length() != s3.length()){
// return false;
// }
// List<String> collect3 = new ArrayList<>(Arrays.asList(s3.split("")));
// List<String> collect2 = new ArrayList<>(Arrays.asList(s2.split("")));
// List<String> collect1 = new ArrayList<>(Arrays.asList(s1.split("")));
// for (char c : s1.toCharArray()) {
// s3.indexOf(c);
// collect3.indexOf()
// }
//
//
// return false;
// }
int cur1 = 0, cur2 = 0, cur3 = 0; //三个 <SUF>
public boolean isInterleave(String s1, String s2, String s3) {
if (s1 == null && s2 == null && s3 == null) {
return true;
} else if (s1.length() + s2.length() != s3.length()) {
return false;
}
// 返回回溯结果
return recursive(s1, s2, s3);
}
public boolean recursive(String s1, String s2, String s3) {
// 递归终止条件:如果s3已经全部搜索完,则表明符合题意,返回true
if (cur3 >= s3.length()) {
return true;
}
if (cur1 < s1.length() && s3.charAt(cur3) == s1.charAt(cur1)) {
// 继续下一层回溯
cur1 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
// 还原指针
cur1 -= 1;
cur3 -= 1;
}
if (cur2 < s2.length() && s3.charAt(cur3) == s2.charAt(cur2)) {
cur2 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
cur2 -= 1;
cur3 -= 1;
}
return false;
}
}
| 0 |
44418_41 | package dao;
/**
* 该类是用于存放SQL语句的 创建于:2016年6月12日21:17:36
*/
public class Maps {
// 查询个人会员
private static final String allPersonalMember = "SELECT count(*) FROM user where GroupNumber=\'1\'";
// 查询企业会员
private static final String allCompanyMember = "SELECT count(*) FROM user where GroupNumber=\'2\'";
// 按条件查询个人会员
private static final String queryPersonalMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'1\' limit ?,?";
// 按条件查询企业会员
private static final String queryCompanyMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'2\' limit ?,?";
// 删除用户
private static final String deletePersonalMemberSql = "delete from user where usernumber=?";
// 删除个人会员详细信息
private static final String deleteUserinfoSql = "delete from userinfo where username=?";
// 删除企业会员详细信息
private static final String deleteCompanyinfoSql = "delete from companyinfo where username=?";
// 管理员添加会员
private static final String AddPersonalMemberSql = "insert into user (usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values (?,?,?,?,?,?,?,?,?,?)";
// 验证登录用户名
private static final String checkUserSql = "select password,username from manager where username=?";
// 会员成功登录时获得两个积分
private static final String UpdateUserPoint = "UPDATE user SET point=point+2 WHERE username=?";
// 注册成功时添加会员用户
private static final String addMemberSql = "insert into user(usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values(?,?,?,?,?,?,?,?,?,?)";
// 从会员表里选取最大会员编号,添加会员编号时使用
private static final String selectMaxIdSql = "select max(usernumber) from user";
// 查询所有会员记录数
private static final String allMemberCount = "SELECT count(*) FROM user";
// 按条件查询全部会员
private static final String queryAllMember = "select usernumber,username,GroupNumber from user limit ?,?";
// 根据会员编号更改该会员会员组编号及会员身份
private static final String updateMemberNumberById = "update user set GroupNumber=?,shenfen=? where usernumber=?";
// 根据会员编号更改该会员资料
private static final String UpdateMemberSql = "update user set question=?,answer=?,safecode=? where usernumber=?";
// 添加商品
private static final String AddProductSql = "insert into product (ProductID,Version,PType,Content,bound,URL_1,addTime) values (?,?,?,?,?,?,?)";
// 查询所有商品记录数
private static final String allProduct = "SELECT count(*) FROM product";
// 根据商品id查询商品名称
private static final String queryProductById = "select ProductID from product where id=?";
// 按条件查询商品
private static final String queryProduct = "SELECT * FROM product limit ?,?";
// 更新商品
private static final String UpdateProductSql = "UPDATE product SET ProductID=?,Version=?,PType=?,Content=? WHERE id=?";
// 删除商品
private static String deleteProductSql;
// 按积分查询商品
private static final String queryBound = "SELECT id,ProductId,Version,PType,Content,bound FROM product limit ?,?";
// 更新积分
private static final String UpdateBoundSql = "UPDATE product SET bound=? WHERE id=?";
// 管理员添加点卡/用户充值点卡
private static final String AddCardSql = "insert into card (CardNumber,CardPassword,Point,username,TimeOutDate,addTime) values (?,?,?,?,?,?)";
// 查询所有点卡
private static final String allCard = "SELECT count(*) FROM card";
// 按条件查询点卡
private static final String queryCard = "SELECT * FROM card limit ?,?";
// 更新商品
private static final String UpdateCardSql = "UPDATE card SET CardNumber=?,CardPassword=?,point=?,TimeOutDate=? WHERE CardID=?";
// 企业会员登录后完善企业信息
private static final String addCompanyMessageSql = "insert into companyuserinfo(username,C_Name,C_PostCode,C_Province,C_City,C_Address,C_ConactName,C_Vocation,C_WebSite,C_size,C_Tel,C_BankName,C_Capital) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 个人会员登录后完善个人信息
private static final String addPersonalMessageSql = "insert into userinfo(username,uname, sex,birthday, zjlb, zjhm, szsf, city, addr,yzbm,Tel,hompage,qq) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 购买点卡后更新会员积分
private static final String RechargeAndAddPointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point+? where t1.username = ?";
// 用户兑换积分
private static final String ExchangeSql = "update user u,card c join (select Point from card where CardNumber=?)as t2 set u.point=u.point+?,c.Point=t2.Point-? where u.username=? and c.CardNumber=?";
// 管理员端展示交易明细
private static final String showBuyProduct = "SELECT count(*) from buyproduct";
// 按条件查询全部交易信息
private static final String queryAllBuyProduct = "SELECT u.username,u.shenfen,p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username limit ?,?";
// 管理员端展示交易明细
private static final String showMemberBuyProduct = "SELECT count(*) from buyproduct where usernme=?";
// 按条件查询个人交易信息
private static final String queryOneMemberBuyProduct = "SELECT p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username and b.username=? limit ?,?";
// 会员购买商品后扣除积分
private static final String updateMemberPoint = "update user set point=point-? where username=?";
// 根据商品编号获得商品id字段
private static final String getProductid = "select id from product where ProductID=?";
// 添加商品
private static final String AddToBuyProduct = "insert into buyproduct (username,id) values (?,?)";
// 用户购买后更新商品表中的已下载次数
private static final String UpdateProductUseNumSql = "UPDATE product SET useNum=useNum+1 WHERE id=?";
// 按积分查询所有会员
private static final String allqueryPointSql = "SELECT username,point FROM user limit ?,?";
// 更新会员积分
private static final String updatePointSql = "UPDATE user SET point=? WHERE username=?";
// 下载后更新会员积分
private static final String usePointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point-? where t1.username = ?";
// 查询所有公告
private static final String allAnnouncement = "SELECT count(*) FROM announcement";
// 按条件查询公告
private static final String queryAnnouncement = "SELECT aid,title,people,pubdate FROM announcement limit ?,?";
// 管理员添加公告
private static final String addAnnouncementSql = "insert into announcement (title, people, pubdate, announcement) values (?,?,?,?)";
// 删除公告
private static String deleteAnnouncementSql;
// 查询已购买的点卡数量
private static final String mycard = "SELECT count(*) FROM card where username=?";
// 按条件查询全部已购买点卡
private static final String queryAllMyCard = "select CardNumber,CardPassword,Point,TimeOutDate,AddTime from card where username=? limit ?,?";
// 用户兑换积分时检查输入的卡号和密码是否正确
private static final String CheckCardNumberSql = "select * from card where CardNumber=? and CardPassword=?";
// 查询某张点卡的点数
private static final String selectPointFromCardSql = "select Point from card where CardNumber=?";
//添加评论
private static final String addCommentSql = "insert into comment(aid,username,content,commentTime) values(?,?,?,now())";
public static String getAllcompanymember() {
return allCompanyMember;
}
public static String getAllpersonalmember() {
return allPersonalMember;
}
public static String getQuerypersonalmember() {
return queryPersonalMember;
}
public static String getQuerycompanymember() {
return queryCompanyMember;
}
public static String getDeletePersonalMemberSql() {
return deletePersonalMemberSql;
}
public static String getAddPersonalMemberSql() {
return AddPersonalMemberSql;
}
public static String getCheckUserSql() {
return checkUserSql;
}
public static String getAddMemberSql() {
return addMemberSql;
}
public static String getSelectMaxIdSql() {
return selectMaxIdSql;
}
public static String getAddProductSql() {
return AddProductSql;
}
public static String getProductCount() {
return allProduct;
}
public static String getQueryProduct() {
return queryProduct;
}
public static String getQueryProductByIdSql() {
return queryProductById;
}
public static String getUpdateProductSql() {
return UpdateProductSql;
}
public static String getDeleteProductSql(String ids) {
deleteProductSql = "update product set UserDel=1 where id in(" + ids
+ ")";
return deleteProductSql;
}
public static String getAllMemberCount() {
return allMemberCount;
}
public static String getQueryAllMember() {
return queryAllMember;
}
public static String getUpdateMemberNumberById() {
return updateMemberNumberById;
}
public static String getAddCardSql() {
return AddCardSql;
}
public static String getCardCount() {
return allCard;
}
public static String getQueryCard() {
return queryCard;
}
public static String getUpdateCardSql() {
return UpdateCardSql;
}
public static String getDeleteCardSql(String ids) {
deleteProductSql = "delete from card where CardID in(" + ids + ")";
return deleteProductSql;
}
public static String getAddCompanyMessageSql() {
return addCompanyMessageSql;
}
public static String getAddPersonalMessageSql() {
return addPersonalMessageSql;
}
public static String getQueryBound() {
return queryBound;
}
public static String getUpdateBoundSql() {
return UpdateBoundSql;
}
public static String getRechargeAndAddPointSql() {
return RechargeAndAddPointSql;
}
public static String getExchangeSql() {
return ExchangeSql;
}
public static String getShowBuyProduct() {
return showBuyProduct;
}
public static String getQueryAllBuyProduct() {
return queryAllBuyProduct;
}
public static String getShowMemberBuyProduct() {
return showMemberBuyProduct;
}
public static String getQueryOneMemberBuyProduct() {
return queryOneMemberBuyProduct;
}
public static String getUpdateMemberPoint() {
return updateMemberPoint;
}
public static String getProductid() {
return getProductid;
}
public static String getAddToBuyProduct() {
return AddToBuyProduct;
}
public static String getUpdateProductUsenumSql() {
return UpdateProductUseNumSql;
}
public static String getUpdateUserPoint() {
return UpdateUserPoint;
}
public static String getUpdatePointSql() {
return updatePointSql;
}
public static String getUsePointSql() {
return usePointSql;
}
public static String getAnnouncementCount() {
return allAnnouncement;
}
public static String getQueryAnnouncement() {
return queryAnnouncement;
}
public static String getAddAnnouncementSql() {
return addAnnouncementSql;
}
public static String getDeleteAnnouncementSql(String ids) {
deleteAnnouncementSql = "delete from announcement where aid in(" + ids
+ ")";
return deleteAnnouncementSql;
}
public static String getAllQueryPoint() {
return allqueryPointSql;
}
public static String getDeleteUserinfoSql() {
return deleteUserinfoSql;
}
public static String getDeleteCompanyInfoSql() {
return deleteCompanyinfoSql;
}
public static String getMyCard() {
return mycard;
}
public static String getQueryAllMyCard() {
return queryAllMyCard;
}
public static String getCheckCardNumberSql() {
return CheckCardNumberSql;
}
public static String getSelectPointFromCardSql() {
return selectPointFromCardSql;
}
public static String getUpdateMemberSql() {
return UpdateMemberSql;
}
public static String getAddCommentSql() {
return addCommentSql;
}
}
| 511733119/Member | src/dao/Maps.java | 3,371 | // 按积分查询所有会员 | line_comment | zh-cn | package dao;
/**
* 该类是用于存放SQL语句的 创建于:2016年6月12日21:17:36
*/
public class Maps {
// 查询个人会员
private static final String allPersonalMember = "SELECT count(*) FROM user where GroupNumber=\'1\'";
// 查询企业会员
private static final String allCompanyMember = "SELECT count(*) FROM user where GroupNumber=\'2\'";
// 按条件查询个人会员
private static final String queryPersonalMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'1\' limit ?,?";
// 按条件查询企业会员
private static final String queryCompanyMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'2\' limit ?,?";
// 删除用户
private static final String deletePersonalMemberSql = "delete from user where usernumber=?";
// 删除个人会员详细信息
private static final String deleteUserinfoSql = "delete from userinfo where username=?";
// 删除企业会员详细信息
private static final String deleteCompanyinfoSql = "delete from companyinfo where username=?";
// 管理员添加会员
private static final String AddPersonalMemberSql = "insert into user (usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values (?,?,?,?,?,?,?,?,?,?)";
// 验证登录用户名
private static final String checkUserSql = "select password,username from manager where username=?";
// 会员成功登录时获得两个积分
private static final String UpdateUserPoint = "UPDATE user SET point=point+2 WHERE username=?";
// 注册成功时添加会员用户
private static final String addMemberSql = "insert into user(usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values(?,?,?,?,?,?,?,?,?,?)";
// 从会员表里选取最大会员编号,添加会员编号时使用
private static final String selectMaxIdSql = "select max(usernumber) from user";
// 查询所有会员记录数
private static final String allMemberCount = "SELECT count(*) FROM user";
// 按条件查询全部会员
private static final String queryAllMember = "select usernumber,username,GroupNumber from user limit ?,?";
// 根据会员编号更改该会员会员组编号及会员身份
private static final String updateMemberNumberById = "update user set GroupNumber=?,shenfen=? where usernumber=?";
// 根据会员编号更改该会员资料
private static final String UpdateMemberSql = "update user set question=?,answer=?,safecode=? where usernumber=?";
// 添加商品
private static final String AddProductSql = "insert into product (ProductID,Version,PType,Content,bound,URL_1,addTime) values (?,?,?,?,?,?,?)";
// 查询所有商品记录数
private static final String allProduct = "SELECT count(*) FROM product";
// 根据商品id查询商品名称
private static final String queryProductById = "select ProductID from product where id=?";
// 按条件查询商品
private static final String queryProduct = "SELECT * FROM product limit ?,?";
// 更新商品
private static final String UpdateProductSql = "UPDATE product SET ProductID=?,Version=?,PType=?,Content=? WHERE id=?";
// 删除商品
private static String deleteProductSql;
// 按积分查询商品
private static final String queryBound = "SELECT id,ProductId,Version,PType,Content,bound FROM product limit ?,?";
// 更新积分
private static final String UpdateBoundSql = "UPDATE product SET bound=? WHERE id=?";
// 管理员添加点卡/用户充值点卡
private static final String AddCardSql = "insert into card (CardNumber,CardPassword,Point,username,TimeOutDate,addTime) values (?,?,?,?,?,?)";
// 查询所有点卡
private static final String allCard = "SELECT count(*) FROM card";
// 按条件查询点卡
private static final String queryCard = "SELECT * FROM card limit ?,?";
// 更新商品
private static final String UpdateCardSql = "UPDATE card SET CardNumber=?,CardPassword=?,point=?,TimeOutDate=? WHERE CardID=?";
// 企业会员登录后完善企业信息
private static final String addCompanyMessageSql = "insert into companyuserinfo(username,C_Name,C_PostCode,C_Province,C_City,C_Address,C_ConactName,C_Vocation,C_WebSite,C_size,C_Tel,C_BankName,C_Capital) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 个人会员登录后完善个人信息
private static final String addPersonalMessageSql = "insert into userinfo(username,uname, sex,birthday, zjlb, zjhm, szsf, city, addr,yzbm,Tel,hompage,qq) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 购买点卡后更新会员积分
private static final String RechargeAndAddPointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point+? where t1.username = ?";
// 用户兑换积分
private static final String ExchangeSql = "update user u,card c join (select Point from card where CardNumber=?)as t2 set u.point=u.point+?,c.Point=t2.Point-? where u.username=? and c.CardNumber=?";
// 管理员端展示交易明细
private static final String showBuyProduct = "SELECT count(*) from buyproduct";
// 按条件查询全部交易信息
private static final String queryAllBuyProduct = "SELECT u.username,u.shenfen,p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username limit ?,?";
// 管理员端展示交易明细
private static final String showMemberBuyProduct = "SELECT count(*) from buyproduct where usernme=?";
// 按条件查询个人交易信息
private static final String queryOneMemberBuyProduct = "SELECT p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username and b.username=? limit ?,?";
// 会员购买商品后扣除积分
private static final String updateMemberPoint = "update user set point=point-? where username=?";
// 根据商品编号获得商品id字段
private static final String getProductid = "select id from product where ProductID=?";
// 添加商品
private static final String AddToBuyProduct = "insert into buyproduct (username,id) values (?,?)";
// 用户购买后更新商品表中的已下载次数
private static final String UpdateProductUseNumSql = "UPDATE product SET useNum=useNum+1 WHERE id=?";
// 按积 <SUF>
private static final String allqueryPointSql = "SELECT username,point FROM user limit ?,?";
// 更新会员积分
private static final String updatePointSql = "UPDATE user SET point=? WHERE username=?";
// 下载后更新会员积分
private static final String usePointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point-? where t1.username = ?";
// 查询所有公告
private static final String allAnnouncement = "SELECT count(*) FROM announcement";
// 按条件查询公告
private static final String queryAnnouncement = "SELECT aid,title,people,pubdate FROM announcement limit ?,?";
// 管理员添加公告
private static final String addAnnouncementSql = "insert into announcement (title, people, pubdate, announcement) values (?,?,?,?)";
// 删除公告
private static String deleteAnnouncementSql;
// 查询已购买的点卡数量
private static final String mycard = "SELECT count(*) FROM card where username=?";
// 按条件查询全部已购买点卡
private static final String queryAllMyCard = "select CardNumber,CardPassword,Point,TimeOutDate,AddTime from card where username=? limit ?,?";
// 用户兑换积分时检查输入的卡号和密码是否正确
private static final String CheckCardNumberSql = "select * from card where CardNumber=? and CardPassword=?";
// 查询某张点卡的点数
private static final String selectPointFromCardSql = "select Point from card where CardNumber=?";
//添加评论
private static final String addCommentSql = "insert into comment(aid,username,content,commentTime) values(?,?,?,now())";
public static String getAllcompanymember() {
return allCompanyMember;
}
public static String getAllpersonalmember() {
return allPersonalMember;
}
public static String getQuerypersonalmember() {
return queryPersonalMember;
}
public static String getQuerycompanymember() {
return queryCompanyMember;
}
public static String getDeletePersonalMemberSql() {
return deletePersonalMemberSql;
}
public static String getAddPersonalMemberSql() {
return AddPersonalMemberSql;
}
public static String getCheckUserSql() {
return checkUserSql;
}
public static String getAddMemberSql() {
return addMemberSql;
}
public static String getSelectMaxIdSql() {
return selectMaxIdSql;
}
public static String getAddProductSql() {
return AddProductSql;
}
public static String getProductCount() {
return allProduct;
}
public static String getQueryProduct() {
return queryProduct;
}
public static String getQueryProductByIdSql() {
return queryProductById;
}
public static String getUpdateProductSql() {
return UpdateProductSql;
}
public static String getDeleteProductSql(String ids) {
deleteProductSql = "update product set UserDel=1 where id in(" + ids
+ ")";
return deleteProductSql;
}
public static String getAllMemberCount() {
return allMemberCount;
}
public static String getQueryAllMember() {
return queryAllMember;
}
public static String getUpdateMemberNumberById() {
return updateMemberNumberById;
}
public static String getAddCardSql() {
return AddCardSql;
}
public static String getCardCount() {
return allCard;
}
public static String getQueryCard() {
return queryCard;
}
public static String getUpdateCardSql() {
return UpdateCardSql;
}
public static String getDeleteCardSql(String ids) {
deleteProductSql = "delete from card where CardID in(" + ids + ")";
return deleteProductSql;
}
public static String getAddCompanyMessageSql() {
return addCompanyMessageSql;
}
public static String getAddPersonalMessageSql() {
return addPersonalMessageSql;
}
public static String getQueryBound() {
return queryBound;
}
public static String getUpdateBoundSql() {
return UpdateBoundSql;
}
public static String getRechargeAndAddPointSql() {
return RechargeAndAddPointSql;
}
public static String getExchangeSql() {
return ExchangeSql;
}
public static String getShowBuyProduct() {
return showBuyProduct;
}
public static String getQueryAllBuyProduct() {
return queryAllBuyProduct;
}
public static String getShowMemberBuyProduct() {
return showMemberBuyProduct;
}
public static String getQueryOneMemberBuyProduct() {
return queryOneMemberBuyProduct;
}
public static String getUpdateMemberPoint() {
return updateMemberPoint;
}
public static String getProductid() {
return getProductid;
}
public static String getAddToBuyProduct() {
return AddToBuyProduct;
}
public static String getUpdateProductUsenumSql() {
return UpdateProductUseNumSql;
}
public static String getUpdateUserPoint() {
return UpdateUserPoint;
}
public static String getUpdatePointSql() {
return updatePointSql;
}
public static String getUsePointSql() {
return usePointSql;
}
public static String getAnnouncementCount() {
return allAnnouncement;
}
public static String getQueryAnnouncement() {
return queryAnnouncement;
}
public static String getAddAnnouncementSql() {
return addAnnouncementSql;
}
public static String getDeleteAnnouncementSql(String ids) {
deleteAnnouncementSql = "delete from announcement where aid in(" + ids
+ ")";
return deleteAnnouncementSql;
}
public static String getAllQueryPoint() {
return allqueryPointSql;
}
public static String getDeleteUserinfoSql() {
return deleteUserinfoSql;
}
public static String getDeleteCompanyInfoSql() {
return deleteCompanyinfoSql;
}
public static String getMyCard() {
return mycard;
}
public static String getQueryAllMyCard() {
return queryAllMyCard;
}
public static String getCheckCardNumberSql() {
return CheckCardNumberSql;
}
public static String getSelectPointFromCardSql() {
return selectPointFromCardSql;
}
public static String getUpdateMemberSql() {
return UpdateMemberSql;
}
public static String getAddCommentSql() {
return addCommentSql;
}
}
| 0 |
30752_2 | package cn.it.shop.serviceImpl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import cn.it.shop.model.Forder;
import cn.it.shop.model.Product;
import cn.it.shop.model.Sorder;
import cn.it.shop.service.SorderService;
/*
* 模块自身的业务逻辑
*/
@Service("sorderService")
public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements SorderService {
@Override
public Forder addSorder(Forder forder,Product product,int num) {
boolean isHave = false;
Sorder sorder = productToSorder(product,num);
//判断当前购物项是否重复,如果重复则增加数量即可
if(forder.getSorderSet()!=null){
for(Sorder old: forder.getSorderSet()){
if(old.getProduct().getId().equals(sorder.getProduct().getId())){
//购物项有重复,增加数量即可
old.setNumber(old.getNumber() + sorder.getNumber());
isHave=true;
break;
}
}
}else{
forder.setSorderSet(new HashSet<Sorder>());
}
if(!isHave){
//建立购物项与购物车的关联,此时forder。id为null,但是在入库的时候是先入库购物车,在入库购物项,那时就有forder就有主键
sorder.setForder(forder);
forder.getSorderSet().add(sorder);
}
return forder;
}
@Override
public Sorder productToSorder(Product product,int num) {
Sorder sorder = new Sorder();
sorder.setName(product.getName());
sorder.setNumber(num);
sorder.setPrice(product.getPrice());
sorder.setProduct(product);
return sorder;
}
@Override
public Forder updateSorder(Forder forder,Sorder sorder) {
for(Sorder temp : forder.getSorderSet()){
if(temp.getProduct().getId().equals(sorder.getProduct().getId())){
temp.setNumber(sorder.getNumber());
}
}
return forder;
}
@Override
public List<Object> querySale(int number) {
return sorderDao.querySale(number);
}
}
| 511733119/shop | src/cn/it/shop/serviceImpl/SorderServiceImpl.java | 646 | //购物项有重复,增加数量即可 | line_comment | zh-cn | package cn.it.shop.serviceImpl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import cn.it.shop.model.Forder;
import cn.it.shop.model.Product;
import cn.it.shop.model.Sorder;
import cn.it.shop.service.SorderService;
/*
* 模块自身的业务逻辑
*/
@Service("sorderService")
public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements SorderService {
@Override
public Forder addSorder(Forder forder,Product product,int num) {
boolean isHave = false;
Sorder sorder = productToSorder(product,num);
//判断当前购物项是否重复,如果重复则增加数量即可
if(forder.getSorderSet()!=null){
for(Sorder old: forder.getSorderSet()){
if(old.getProduct().getId().equals(sorder.getProduct().getId())){
//购物 <SUF>
old.setNumber(old.getNumber() + sorder.getNumber());
isHave=true;
break;
}
}
}else{
forder.setSorderSet(new HashSet<Sorder>());
}
if(!isHave){
//建立购物项与购物车的关联,此时forder。id为null,但是在入库的时候是先入库购物车,在入库购物项,那时就有forder就有主键
sorder.setForder(forder);
forder.getSorderSet().add(sorder);
}
return forder;
}
@Override
public Sorder productToSorder(Product product,int num) {
Sorder sorder = new Sorder();
sorder.setName(product.getName());
sorder.setNumber(num);
sorder.setPrice(product.getPrice());
sorder.setProduct(product);
return sorder;
}
@Override
public Forder updateSorder(Forder forder,Sorder sorder) {
for(Sorder temp : forder.getSorderSet()){
if(temp.getProduct().getId().equals(sorder.getProduct().getId())){
temp.setNumber(sorder.getNumber());
}
}
return forder;
}
@Override
public List<Object> querySale(int number) {
return sorderDao.querySale(number);
}
}
| 0 |
38650_14 | package com.nbclass.model;
import java.io.Serializable;
import lombok.Data;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/**
* zb_comment
* @author nbclass 2019-10-18
*/
@Data
public class BlogComment implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
private Integer id;
/**
* 被评论的文章或者页面的id(-1:留言板)
*/
private Integer sid;
/**
* 主评论id
*/
private Integer mid;
/**
* 父级评论的id
*/
private Integer parentId;
/**
* 父级评论的昵称 (冗余)
*/
private String parentNickname;
/**
* 评论人的qq(未登录用户)
*/
private String qq;
/**
* 评论人的昵称(未登录用户)
*/
private String nickname;
/**
* 评论人的头像地址
*/
private String avatar;
/**
* 评论人的邮箱地址(未登录用户)
*/
private String email;
/**
* 评论时的ip
*/
private String ip;
/**
* 评论时的系统类型
*/
private String os;
/**
* 评论时的浏览器类型
*/
private String browser;
/**
* 评论的内容
*/
private String content;
/**
* 楼层
*/
private Integer floor;
/**
* 支持(赞)数
*/
private Integer supportNum;
/**
* 反对(踩)
*/
private Integer opposeNum;
/**
* 0-待审核,1-通过,2-驳回
*/
private Boolean status;
/**
* 添加时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
@Transient
BlogComment parent;
@Transient
List<BlogComment> nodes;
@Transient
BlogArticle article;
} | 523179414/zb-blog | src/main/java/com/nbclass/model/BlogComment.java | 480 | /**
* 楼层
*/ | block_comment | zh-cn | package com.nbclass.model;
import java.io.Serializable;
import lombok.Data;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/**
* zb_comment
* @author nbclass 2019-10-18
*/
@Data
public class BlogComment implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
private Integer id;
/**
* 被评论的文章或者页面的id(-1:留言板)
*/
private Integer sid;
/**
* 主评论id
*/
private Integer mid;
/**
* 父级评论的id
*/
private Integer parentId;
/**
* 父级评论的昵称 (冗余)
*/
private String parentNickname;
/**
* 评论人的qq(未登录用户)
*/
private String qq;
/**
* 评论人的昵称(未登录用户)
*/
private String nickname;
/**
* 评论人的头像地址
*/
private String avatar;
/**
* 评论人的邮箱地址(未登录用户)
*/
private String email;
/**
* 评论时的ip
*/
private String ip;
/**
* 评论时的系统类型
*/
private String os;
/**
* 评论时的浏览器类型
*/
private String browser;
/**
* 评论的内容
*/
private String content;
/**
* 楼层
<SUF>*/
private Integer floor;
/**
* 支持(赞)数
*/
private Integer supportNum;
/**
* 反对(踩)
*/
private Integer opposeNum;
/**
* 0-待审核,1-通过,2-驳回
*/
private Boolean status;
/**
* 添加时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
@Transient
BlogComment parent;
@Transient
List<BlogComment> nodes;
@Transient
BlogArticle article;
} | 1 |
16217_8 | package com.us.geoip;
import com.fasterxml.jackson.databind.JsonNode;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.io.IOException;
import com.maxmind.db.Reader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.maxmind.db.Reader.FileMode;
import com.maxmind.db.CHMCache;
/**
* https://github.com/maxmind/MaxMind-DB-Reader-java
* <p>
* Java 通过ip 获取 地理位置
*
* @author yyb
* @time 2019/6/19
*/
public class GeoipTest {
private static volatile DatabaseReader readerIp;
public static void main(String[] args) throws Exception {
// noCache("1.180.164.207");
// haveCache("1.180.164.207");
}
private static void haveCache(String ip) throws IOException {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
Reader r = new Reader(database, FileMode.MEMORY_MAPPED, new CHMCache());
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
JsonNode response = r.get(ipAddress);
//国家
System.out.println(response.get("country").get("iso_code"));
System.out.println(response.get("country").get("geoname_id"));
System.out.println(response.get("country").get("names").get("zh-CN"));
//省
System.out.println(response.get("subdivisions").get("iso_code"));
System.out.println(response.get("subdivisions").get("geoname_id"));
System.out.println(response.get("subdivisions").get("names").get("zh-CN"));
//城市
System.out.println(response.get("city").get("iso_code"));
System.out.println(response.get("city").get("geoname_id"));
System.out.println(response.get("city").get("names").get("zh-CN"));
//经纬度
System.out.println(response.get("location").get("latitude"));
System.out.println(response.get("location").get("longitude"));
}
private static String noCache(String ip) throws Exception {
DatabaseReader reader = GeoipTest.getIpInstance();
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
CityResponse response = reader.city(ipAddress);
// 获取国家信息
Country country = response.getCountry();
System.out.println("国家code:" + country.getIsoCode());
System.out.println("国家:" + country.getNames().get("zh-CN"));
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println("省份code:" + subdivision.getIsoCode());
System.out.println("省份:" + subdivision.getNames().get("zh-CN"));
//城市
City city = response.getCity();
System.out.println("城市code:" + city.getGeoNameId());
System.out.println("城市:" + city.getNames().get("zh-CN"));
// 获取经纬度
Location location = response.getLocation();
System.out.println("经度:" + location.getLatitude());
System.out.println("维度:" + location.getLongitude());
return subdivision.getNames().get("zh-CN") + "--";
}
/**
* 获取数据库连接对象,单例
*
* @return
*/
public static DatabaseReader getIpInstance() throws IOException {
if (readerIp == null) {
synchronized (GeoipTest.class) {
if (readerIp == null) {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
readerIp = new DatabaseReader.Builder(database).build();
}
}
}
return readerIp;
}
}
| 527515025/JavaTest | src/main/java/com/us/geoip/GeoipTest.java | 1,036 | // 获取经纬度 | line_comment | zh-cn | package com.us.geoip;
import com.fasterxml.jackson.databind.JsonNode;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.io.IOException;
import com.maxmind.db.Reader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.maxmind.db.Reader.FileMode;
import com.maxmind.db.CHMCache;
/**
* https://github.com/maxmind/MaxMind-DB-Reader-java
* <p>
* Java 通过ip 获取 地理位置
*
* @author yyb
* @time 2019/6/19
*/
public class GeoipTest {
private static volatile DatabaseReader readerIp;
public static void main(String[] args) throws Exception {
// noCache("1.180.164.207");
// haveCache("1.180.164.207");
}
private static void haveCache(String ip) throws IOException {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
Reader r = new Reader(database, FileMode.MEMORY_MAPPED, new CHMCache());
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
JsonNode response = r.get(ipAddress);
//国家
System.out.println(response.get("country").get("iso_code"));
System.out.println(response.get("country").get("geoname_id"));
System.out.println(response.get("country").get("names").get("zh-CN"));
//省
System.out.println(response.get("subdivisions").get("iso_code"));
System.out.println(response.get("subdivisions").get("geoname_id"));
System.out.println(response.get("subdivisions").get("names").get("zh-CN"));
//城市
System.out.println(response.get("city").get("iso_code"));
System.out.println(response.get("city").get("geoname_id"));
System.out.println(response.get("city").get("names").get("zh-CN"));
//经纬度
System.out.println(response.get("location").get("latitude"));
System.out.println(response.get("location").get("longitude"));
}
private static String noCache(String ip) throws Exception {
DatabaseReader reader = GeoipTest.getIpInstance();
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
CityResponse response = reader.city(ipAddress);
// 获取国家信息
Country country = response.getCountry();
System.out.println("国家code:" + country.getIsoCode());
System.out.println("国家:" + country.getNames().get("zh-CN"));
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println("省份code:" + subdivision.getIsoCode());
System.out.println("省份:" + subdivision.getNames().get("zh-CN"));
//城市
City city = response.getCity();
System.out.println("城市code:" + city.getGeoNameId());
System.out.println("城市:" + city.getNames().get("zh-CN"));
// 获取 <SUF>
Location location = response.getLocation();
System.out.println("经度:" + location.getLatitude());
System.out.println("维度:" + location.getLongitude());
return subdivision.getNames().get("zh-CN") + "--";
}
/**
* 获取数据库连接对象,单例
*
* @return
*/
public static DatabaseReader getIpInstance() throws IOException {
if (readerIp == null) {
synchronized (GeoipTest.class) {
if (readerIp == null) {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
readerIp = new DatabaseReader.Builder(database).build();
}
}
}
return readerIp;
}
}
| 0 |
44152_1 | package com.abel.problem;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by yangyibo on 17/11/7.
*/
public class Client {
public static void main(String[] args) {
//随机生成几个女性
Random rand = new Random();
List<IWomen> womens = new ArrayList();
for (int i = 0; i < 5; i++) {
womens.add(new Women(rand.nextInt(3), "我要去逛街"));
}
IHandler father = new Father();
IHandler husband = new Husband();
IHandler son = new Son();
for (IWomen women : womens) {
if (women.getType() == 0) {
// 未婚少女请示父亲
System.out.println("\n--------女儿向父亲请示-------");
father.HandleMessage(women);
} else if (women.getType() == 1) {
//已婚美女请示老公
System.out.println("\n--------老婆向老公请示 -------");
husband.HandleMessage(women);
} else if (women.getType() == 2) {
//妈妈向儿子
System.out.println("\n--------妈妈向儿子请示-------");
son.HandleMessage(women);
} else {
//暂时什么也不做
}
}
}
}
| 527515025/design_pattern | responsibilityChain/src/main/java/com/abel/problem/Client.java | 365 | //随机生成几个女性 | line_comment | zh-cn | package com.abel.problem;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by yangyibo on 17/11/7.
*/
public class Client {
public static void main(String[] args) {
//随机 <SUF>
Random rand = new Random();
List<IWomen> womens = new ArrayList();
for (int i = 0; i < 5; i++) {
womens.add(new Women(rand.nextInt(3), "我要去逛街"));
}
IHandler father = new Father();
IHandler husband = new Husband();
IHandler son = new Son();
for (IWomen women : womens) {
if (women.getType() == 0) {
// 未婚少女请示父亲
System.out.println("\n--------女儿向父亲请示-------");
father.HandleMessage(women);
} else if (women.getType() == 1) {
//已婚美女请示老公
System.out.println("\n--------老婆向老公请示 -------");
husband.HandleMessage(women);
} else if (women.getType() == 2) {
//妈妈向儿子
System.out.println("\n--------妈妈向儿子请示-------");
son.HandleMessage(women);
} else {
//暂时什么也不做
}
}
}
}
| 0 |
7004_3 | package com.us.example.config;
import com.us.example.service.CustomUserService;
import com.us.example.service.MyFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
/**
* Created by yangyibo on 17/1/18.
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
@Bean
UserDetailsService customUserService() { //注册UserDetailsService 的bean
return new CustomUserService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()); //user Details Service验证
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated() //任何请求,登录后可以访问
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.and()
.logout().permitAll(); //注销行为任意访问
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
.csrf().disable();
}
}
| 527515025/springBoot | springboot-springSecurity3/src/main/java/com/us/example/config/WebSecurityConfig.java | 423 | //任何请求,登录后可以访问 | line_comment | zh-cn | package com.us.example.config;
import com.us.example.service.CustomUserService;
import com.us.example.service.MyFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
/**
* Created by yangyibo on 17/1/18.
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
@Bean
UserDetailsService customUserService() { //注册UserDetailsService 的bean
return new CustomUserService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()); //user Details Service验证
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated() //任何 <SUF>
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.and()
.logout().permitAll(); //注销行为任意访问
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
.csrf().disable();
}
}
| 0 |
65851_4 | package com.study.dto.output;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author 大脑补丁
* @project cne-power-operation-facade
* @description: 导出Excel:申请单
* @create 2020-03-26 15:26
*/
@Data
public class SendBillOutput implements Serializable {
// 客户名称
private String customerName;
// 是否一般纳税人
private String isGeneralTaxpayer;
// 税号
private String taxNumber;
// 客户公司地址及电话
private String addressAndPhone;
// 开户银行和账号
private String bankAndAccount;
// 信息列表
private List<StationBillOutput> stationBillList;
// 合计栏
private StationAmountOutput stationAmount;
}
| 541211190/freemarker-excel | src/main/java/com/study/dto/output/SendBillOutput.java | 225 | // 开户银行和账号 | line_comment | zh-cn | package com.study.dto.output;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author 大脑补丁
* @project cne-power-operation-facade
* @description: 导出Excel:申请单
* @create 2020-03-26 15:26
*/
@Data
public class SendBillOutput implements Serializable {
// 客户名称
private String customerName;
// 是否一般纳税人
private String isGeneralTaxpayer;
// 税号
private String taxNumber;
// 客户公司地址及电话
private String addressAndPhone;
// 开户 <SUF>
private String bankAndAccount;
// 信息列表
private List<StationBillOutput> stationBillList;
// 合计栏
private StationAmountOutput stationAmount;
}
| 0 |
31932_33 | /**
* Bp神经网络
* reference https://www.cnblogs.com/hesi/p/7218602.html
*/
public class Bp {
private double[] hide1_x; // 输入层即第一层隐含层的输入; hide1_x[数据的特征数目+1],hide1_w[0]为1
private double[][] hide1_w; // 隐含层权值,hide1_w[本层节点数目][数据的特征数目+1];hide_w[0][0]为偏置量
private double[] hide1_errors; // 隐含层的误差,hide1_errors[节点个数]
private double[] hide1_theta; // 隐含层的阈值,hide1_errors[节点个数]
private double[] out_x; // 输出层的输入值即第二层隐含层的输出 out_x[上一层的节点数+1], out_x[0]为1
private double[][] out_w; // 输出层的权值,hide1_w[节点的数目][上一层的节点数目+1], out_w[0][0]为偏置量
private double[] out_errors; // 输出层的误差,hide1_error[节点个数]
private double[] pre_out_errors; // 上一次输出层的误差,hide1_error[节点个数]
private double[] out_theta; // 输出层的阈值,out_node[节点个数]
private double[] target; // 目标值,target[输出层的节点个数]
private double MS_error; // 计算均方误差
private double rate; // 学习速率
Bp(int input_node, int hide1_node, int out_node, double rate) {
super();
// 输入层即第一层隐含层的输入
hide1_x = new double[input_node + 1];
// 第一层隐含层
hide1_w = new double[hide1_node][input_node + 1];
hide1_errors = new double[hide1_node];
hide1_theta = new double[hide1_node];
// 输出层
out_x = new double[hide1_node + 1];
out_w = new double[out_node][hide1_node + 1];
out_errors = new double[out_node];
out_theta = new double[out_node];
pre_out_errors = new double[out_node];
// 输出层
target = new double[out_node];
// 均方误差为0
MS_error = 0;
// 学习速率
this.rate = rate;
init_weight();// 1.初始化网络的权值
init_theta(); // 2.初始化网络的阈值
}
/**
* 初始化阈值
*/
private void init_theta() {
set_theta(hide1_theta);
set_theta(out_theta);
}
/**
* 初始化阈值
*
* @param theta 阈值
*/
private void set_theta(double[] theta) {
for (int i = 0; i < theta.length; i++) {
theta[i] = Math.random();
}
}
/**
* 初始化权值
*/
private void init_weight() {
set_weight(hide1_w);
set_weight(out_w);
}
/**
* 权值初始化为0
*
* @param weight 传入初始权值
*/
private void set_weight(double[][] weight) {
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
weight[i][j] = Math.random();
}
}
}
/**
* 传入原始数据
*
* @param Data 传入数据
*/
private void setHide1_x(double[] Data) {
if (Data.length != hide1_x.length - 1) {
throw new IllegalArgumentException("数据大小与输出层节点不匹配");
}
System.arraycopy(Data, 0, hide1_x, 1, Data.length);
hide1_x[0] = 1.0;
}
/**
* 设置目标数据
*
* @param target 目标数据
*/
private void setTarget(double[] target) {
this.target = target;
}
public void train(double[] TrainData, double[] target) {
// 2.1.导入训练数据集和目标值
setHide1_x(TrainData);
setTarget(target);
// 2.2.向前传播得到输出值
double[] output = new double[out_w.length + 1];
forword(hide1_x, output);
// 2.3.反向传播
backpropagation(output);
}
/**
* 反向传播过程
*
* @param output 预测结果
*/
private void backpropagation(double[] output) {
// 2.3.1.获取输出层的误差;
get_out_error(output, target, out_errors);
// 2.3.2.获取隐含层的误差;
get_hide_error(out_errors, out_w, out_x, hide1_errors);
// 2.3.3.更新输入层到隐含层的权值;
update_weight(hide1_errors, hide1_w, hide1_x);
// 2.3.4 更新隐含层的阈值;
update_theta(hide1_errors, hide1_theta);
// 2.3.5.更新隐含层到输出层的权值;
update_weight(out_errors, out_w, out_x);
// 2.3.6.更新输出层的阈值;
update_theta(out_errors, out_theta);
}
/**
* 新的阈值=原阈值+(-学习速率×该节点的误差)
*
* @param hide1_errors 该层误差
* @param hide1_theta 原阈值
*/
private void update_theta(double[] hide1_errors, double[] hide1_theta) {
double newTheta = 0.0;
for (int i = 0; i < hide1_errors.length; i++) {
newTheta = - rate * hide1_errors[i];
hide1_theta[i] += newTheta;
}
}
/**
* 新的权值=原权值+学习速率×该节点的误差×激励函数的导函数的值
*
* @param error 该层误差
* @param weight 原来权重
* @param input 上层输出
*/
private void update_weight(double[] error, double[][] weight, double[] input) {
double newWeight = 0.0;
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
newWeight = rate * error[i] * input[j];
weight[i][j] = weight[i][j] + newWeight;
}
}
}
/**
* 获取隐含层的误差,西瓜书eh
*
* @param NextLayorError 下一层的误差
* @param NextWeight 下一层的权值
* @param NextOutput 下一层的输入
* @param error 本层误差数组
*/
private void get_hide_error(double[] NextLayorError, double[][] NextWeight, double[] NextOutput, double[] error) {
for (int i = 0; i < error.length; i++) {
double sum = 0;
for (int j = 0; j < NextWeight.length; j++) {
sum += NextWeight[j][i + 1] * NextLayorError[j];
}
error[i] = sum * NextOutput[i + 1] * (1d - NextOutput[i + 1]);
}
}
/**
* 获取输出层的误差,西瓜树gj
*
* @param output 预测输出值
* @param target 目标值
* @param out_errors 输出层误差
*/
private void get_out_error(double[] output, double[] target, double[] out_errors) {
for (int i = 0; i < target.length; i++) {
pre_out_errors[i] = out_errors[i];
out_errors[i] = (target[i] - output[i + 1]) * output[i + 1] * (1d - output[i + 1]);
}
}
/**
* 向前传播
*
* @param input 输入层输入
* @param output 输出层输出
*/
private void forword(double[] input, double[] output) {
// 2.2.1.获取隐含层的输出
get_net_out(input, hide1_w, hide1_theta, out_x);
// 2.2.2.获取输出层的输出
get_net_out(out_x, out_w, out_theta, output);
}
/**
* 获取网络层的输出
*
* @param input 输入矩阵
* @param weight 权值矩阵
* @param theta 阈值
* @param output 接受网络层的输出数据
*/
private void get_net_out(double[] input, double[][] weight, double[] theta, double[] output) {
output[0] = 1d;
for (int i = 0; i < weight.length; i++) {
output[i + 1] = get_node_put(input, weight[i], theta[i]);
}
}
/**
* 获取单个节点的输出
*
* @param input 输入矩阵
* @param weight 权值
* @param theta 阈值
* @return 输出值
*/
private double get_node_put(double[] input, double[] weight, double theta) {
double z = 0d;
for (int i = 0; i < input.length; i++) {
z += input[i] * weight[i];
}
// 激励函数
return sigmoid(z + theta);
}
/**
* sigmoid激励函数
*
* @param x 输入
* @return 输出
*/
private double sigmoid(double x) {
return 1d / (1d + Math.exp(-x));
}
/**
* 预测函数
*
* @param data 预测输入
* @param output 预测输出
*/
public void predict(double[] data, double[] output, double[] target) {
double[] out_y = new double[out_w.length + 1];
setHide1_x(data);
forword(hide1_x, out_y);
System.arraycopy(out_y, 1, output, 0, output.length);
calc_error(target, output);
}
/**
* 计算前后两次训练的误差
*/
private void calc_error(double[] target, double[] output) {
for (int i = 0; i < target.length; i++) {
MS_error += 0.5 * (Math.pow(target[i], 2) - Math.pow(output[i], 2));
}
}
/**
* 返回均方误差
*
* @return 均方误差
*/
public double getMSError() {
return MS_error;
}
/**
* 计算前后两次训练误差
*
* @return 返回训练误差的绝对值
*/
public double CalcErrDiff() {
double min = 10000;
for (int i = 0; i < pre_out_errors.length; i++) {
double diff = out_errors[i] - pre_out_errors[i];
min = min > diff ? diff : min;
}
return Math.abs(min);
}
/**
* 返回隐含层第一层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightHide1() {
return hide1_w;
}
/**
* 返回输出层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightOutput() {
return out_w;
}
/**
* 返回隐层的阈值
* @return 阈值
*/
public double[] getThetaHide1(){
return hide1_theta;
}
/**
* 返回输出层的阈值
* @return 阈值
*/
public double[] getThetaOutput(){
return out_theta;
}
}
| 543877815/uestc_Internet_plus_course_project | machine-learning/src/Bp.java | 3,030 | // 2.3.3.更新输入层到隐含层的权值; | line_comment | zh-cn | /**
* Bp神经网络
* reference https://www.cnblogs.com/hesi/p/7218602.html
*/
public class Bp {
private double[] hide1_x; // 输入层即第一层隐含层的输入; hide1_x[数据的特征数目+1],hide1_w[0]为1
private double[][] hide1_w; // 隐含层权值,hide1_w[本层节点数目][数据的特征数目+1];hide_w[0][0]为偏置量
private double[] hide1_errors; // 隐含层的误差,hide1_errors[节点个数]
private double[] hide1_theta; // 隐含层的阈值,hide1_errors[节点个数]
private double[] out_x; // 输出层的输入值即第二层隐含层的输出 out_x[上一层的节点数+1], out_x[0]为1
private double[][] out_w; // 输出层的权值,hide1_w[节点的数目][上一层的节点数目+1], out_w[0][0]为偏置量
private double[] out_errors; // 输出层的误差,hide1_error[节点个数]
private double[] pre_out_errors; // 上一次输出层的误差,hide1_error[节点个数]
private double[] out_theta; // 输出层的阈值,out_node[节点个数]
private double[] target; // 目标值,target[输出层的节点个数]
private double MS_error; // 计算均方误差
private double rate; // 学习速率
Bp(int input_node, int hide1_node, int out_node, double rate) {
super();
// 输入层即第一层隐含层的输入
hide1_x = new double[input_node + 1];
// 第一层隐含层
hide1_w = new double[hide1_node][input_node + 1];
hide1_errors = new double[hide1_node];
hide1_theta = new double[hide1_node];
// 输出层
out_x = new double[hide1_node + 1];
out_w = new double[out_node][hide1_node + 1];
out_errors = new double[out_node];
out_theta = new double[out_node];
pre_out_errors = new double[out_node];
// 输出层
target = new double[out_node];
// 均方误差为0
MS_error = 0;
// 学习速率
this.rate = rate;
init_weight();// 1.初始化网络的权值
init_theta(); // 2.初始化网络的阈值
}
/**
* 初始化阈值
*/
private void init_theta() {
set_theta(hide1_theta);
set_theta(out_theta);
}
/**
* 初始化阈值
*
* @param theta 阈值
*/
private void set_theta(double[] theta) {
for (int i = 0; i < theta.length; i++) {
theta[i] = Math.random();
}
}
/**
* 初始化权值
*/
private void init_weight() {
set_weight(hide1_w);
set_weight(out_w);
}
/**
* 权值初始化为0
*
* @param weight 传入初始权值
*/
private void set_weight(double[][] weight) {
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
weight[i][j] = Math.random();
}
}
}
/**
* 传入原始数据
*
* @param Data 传入数据
*/
private void setHide1_x(double[] Data) {
if (Data.length != hide1_x.length - 1) {
throw new IllegalArgumentException("数据大小与输出层节点不匹配");
}
System.arraycopy(Data, 0, hide1_x, 1, Data.length);
hide1_x[0] = 1.0;
}
/**
* 设置目标数据
*
* @param target 目标数据
*/
private void setTarget(double[] target) {
this.target = target;
}
public void train(double[] TrainData, double[] target) {
// 2.1.导入训练数据集和目标值
setHide1_x(TrainData);
setTarget(target);
// 2.2.向前传播得到输出值
double[] output = new double[out_w.length + 1];
forword(hide1_x, output);
// 2.3.反向传播
backpropagation(output);
}
/**
* 反向传播过程
*
* @param output 预测结果
*/
private void backpropagation(double[] output) {
// 2.3.1.获取输出层的误差;
get_out_error(output, target, out_errors);
// 2.3.2.获取隐含层的误差;
get_hide_error(out_errors, out_w, out_x, hide1_errors);
// 2. <SUF>
update_weight(hide1_errors, hide1_w, hide1_x);
// 2.3.4 更新隐含层的阈值;
update_theta(hide1_errors, hide1_theta);
// 2.3.5.更新隐含层到输出层的权值;
update_weight(out_errors, out_w, out_x);
// 2.3.6.更新输出层的阈值;
update_theta(out_errors, out_theta);
}
/**
* 新的阈值=原阈值+(-学习速率×该节点的误差)
*
* @param hide1_errors 该层误差
* @param hide1_theta 原阈值
*/
private void update_theta(double[] hide1_errors, double[] hide1_theta) {
double newTheta = 0.0;
for (int i = 0; i < hide1_errors.length; i++) {
newTheta = - rate * hide1_errors[i];
hide1_theta[i] += newTheta;
}
}
/**
* 新的权值=原权值+学习速率×该节点的误差×激励函数的导函数的值
*
* @param error 该层误差
* @param weight 原来权重
* @param input 上层输出
*/
private void update_weight(double[] error, double[][] weight, double[] input) {
double newWeight = 0.0;
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
newWeight = rate * error[i] * input[j];
weight[i][j] = weight[i][j] + newWeight;
}
}
}
/**
* 获取隐含层的误差,西瓜书eh
*
* @param NextLayorError 下一层的误差
* @param NextWeight 下一层的权值
* @param NextOutput 下一层的输入
* @param error 本层误差数组
*/
private void get_hide_error(double[] NextLayorError, double[][] NextWeight, double[] NextOutput, double[] error) {
for (int i = 0; i < error.length; i++) {
double sum = 0;
for (int j = 0; j < NextWeight.length; j++) {
sum += NextWeight[j][i + 1] * NextLayorError[j];
}
error[i] = sum * NextOutput[i + 1] * (1d - NextOutput[i + 1]);
}
}
/**
* 获取输出层的误差,西瓜树gj
*
* @param output 预测输出值
* @param target 目标值
* @param out_errors 输出层误差
*/
private void get_out_error(double[] output, double[] target, double[] out_errors) {
for (int i = 0; i < target.length; i++) {
pre_out_errors[i] = out_errors[i];
out_errors[i] = (target[i] - output[i + 1]) * output[i + 1] * (1d - output[i + 1]);
}
}
/**
* 向前传播
*
* @param input 输入层输入
* @param output 输出层输出
*/
private void forword(double[] input, double[] output) {
// 2.2.1.获取隐含层的输出
get_net_out(input, hide1_w, hide1_theta, out_x);
// 2.2.2.获取输出层的输出
get_net_out(out_x, out_w, out_theta, output);
}
/**
* 获取网络层的输出
*
* @param input 输入矩阵
* @param weight 权值矩阵
* @param theta 阈值
* @param output 接受网络层的输出数据
*/
private void get_net_out(double[] input, double[][] weight, double[] theta, double[] output) {
output[0] = 1d;
for (int i = 0; i < weight.length; i++) {
output[i + 1] = get_node_put(input, weight[i], theta[i]);
}
}
/**
* 获取单个节点的输出
*
* @param input 输入矩阵
* @param weight 权值
* @param theta 阈值
* @return 输出值
*/
private double get_node_put(double[] input, double[] weight, double theta) {
double z = 0d;
for (int i = 0; i < input.length; i++) {
z += input[i] * weight[i];
}
// 激励函数
return sigmoid(z + theta);
}
/**
* sigmoid激励函数
*
* @param x 输入
* @return 输出
*/
private double sigmoid(double x) {
return 1d / (1d + Math.exp(-x));
}
/**
* 预测函数
*
* @param data 预测输入
* @param output 预测输出
*/
public void predict(double[] data, double[] output, double[] target) {
double[] out_y = new double[out_w.length + 1];
setHide1_x(data);
forword(hide1_x, out_y);
System.arraycopy(out_y, 1, output, 0, output.length);
calc_error(target, output);
}
/**
* 计算前后两次训练的误差
*/
private void calc_error(double[] target, double[] output) {
for (int i = 0; i < target.length; i++) {
MS_error += 0.5 * (Math.pow(target[i], 2) - Math.pow(output[i], 2));
}
}
/**
* 返回均方误差
*
* @return 均方误差
*/
public double getMSError() {
return MS_error;
}
/**
* 计算前后两次训练误差
*
* @return 返回训练误差的绝对值
*/
public double CalcErrDiff() {
double min = 10000;
for (int i = 0; i < pre_out_errors.length; i++) {
double diff = out_errors[i] - pre_out_errors[i];
min = min > diff ? diff : min;
}
return Math.abs(min);
}
/**
* 返回隐含层第一层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightHide1() {
return hide1_w;
}
/**
* 返回输出层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightOutput() {
return out_w;
}
/**
* 返回隐层的阈值
* @return 阈值
*/
public double[] getThetaHide1(){
return hide1_theta;
}
/**
* 返回输出层的阈值
* @return 阈值
*/
public double[] getThetaOutput(){
return out_theta;
}
}
| 0 |
54581_11 | package com.opendata.common.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @title KeywordFilter
* @description TODO
* @author
* @date 2014-4-17
* @version 1.0
*/
public class KeywordFilter {
/** 敏感词集合
* {法={isEnd=0, 轮={isEnd=1}}, 中={isEnd=0, 国={isEnd=0, 人={isEnd=1}, 男={isEnd=0, 人={isEnd=1}}}}}
* */
private HashMap keysMap = new HashMap();
/**
* 添加敏感词
* @param keywords
*/
public void addKeywords(List<String> keywords) {
for (int i = 0; i < keywords.size(); i++) {
String key = keywords.get(i).trim();
HashMap nowhash = keysMap;//初始从最外层遍历
for (int j = 0; j < key.length(); j++) {
char word = key.charAt(j);
Object wordMap = nowhash.get(word);
if (wordMap != null) {
nowhash = (HashMap) wordMap;
} else {
HashMap<String, String> newWordHash = new HashMap<String, String>();
newWordHash.put("isEnd", "0");
nowhash.put(word, newWordHash);
nowhash = newWordHash;
}
if (j == key.length() - 1) {
nowhash.put("isEnd", "1");
}
}
}
}
/**
* 检查一个字符串从begin位置起开始是否有keyword符合,
* 如果没有,则返回0
* 如果有符合的keyword值,继续遍历,直至遇到isEnd = 1,返回匹配的keyword的长度,
*/
private int checkKeyWords(String txt, int begin) {
HashMap nowhash = keysMap;
int res = 0;
for (int i = begin; i < txt.length(); i++) {
char word = txt.charAt(i);
Object wordMap = nowhash.get(word);//得到该字符对应的HashMap
if (wordMap == null) {
return 0;//如果该字符没有对应的HashMap,return 0
}
res++;//如果该字符对应的HashMap不为null,说明匹配到了一个字符,+1
nowhash = (HashMap) wordMap;//将遍历的HashMap指向该字符对应的HashMap
if (((String) nowhash.get("isEnd")).equals("1")) {//如果该字符为敏感词的结束字符,直接返回
return res;
} else {
continue;
}
}
return res;
}
/**
* 判断txt中是否有关键字
*/
public boolean isContentKeyWords(String txt) {
for (int i = 0; i < txt.length(); i++) {
int len = checkKeyWords(txt, i);
if (len > 0) {
return true;
}
}
return false;
}
/**
* 返回txt中关键字的列表
*/
public List<String> getTxtKeyWords(String txt) {
List<String> list = new ArrayList<String>();
int l = txt.length();
for (int i = 0; i < l;) {
int len = checkKeyWords(txt, i);
if (len > 0) {
String tt = txt.substring(i, i + len);
list.add(tt);
i += len;
} else {
i++;
}
}
return list;
}
/**
* 初始化敏感词列表
* */
public void initfiltercode() {
List<String> keywords = new ArrayList<String>();
keywords.add("中国人");
keywords.add("中国男人");
keywords.add("法轮");
this.addKeywords(keywords);
}
public static void main(String[] args) throws IOException {
KeywordFilter filter = new KeywordFilter();
filter.initfiltercode();
String txt = "哈哈,反倒是 法轮热舞功,中国人,";
boolean boo = filter.isContentKeyWords(txt);
System.out.println(boo);
List<String> set = filter.getTxtKeyWords(txt);
System.out.println("包含的敏感词如下:" + set);
}
} | 545473750/zswxsqxt | src/main/java/com/opendata/common/util/KeywordFilter.java | 1,031 | /**
* 返回txt中关键字的列表
*/ | block_comment | zh-cn | package com.opendata.common.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @title KeywordFilter
* @description TODO
* @author
* @date 2014-4-17
* @version 1.0
*/
public class KeywordFilter {
/** 敏感词集合
* {法={isEnd=0, 轮={isEnd=1}}, 中={isEnd=0, 国={isEnd=0, 人={isEnd=1}, 男={isEnd=0, 人={isEnd=1}}}}}
* */
private HashMap keysMap = new HashMap();
/**
* 添加敏感词
* @param keywords
*/
public void addKeywords(List<String> keywords) {
for (int i = 0; i < keywords.size(); i++) {
String key = keywords.get(i).trim();
HashMap nowhash = keysMap;//初始从最外层遍历
for (int j = 0; j < key.length(); j++) {
char word = key.charAt(j);
Object wordMap = nowhash.get(word);
if (wordMap != null) {
nowhash = (HashMap) wordMap;
} else {
HashMap<String, String> newWordHash = new HashMap<String, String>();
newWordHash.put("isEnd", "0");
nowhash.put(word, newWordHash);
nowhash = newWordHash;
}
if (j == key.length() - 1) {
nowhash.put("isEnd", "1");
}
}
}
}
/**
* 检查一个字符串从begin位置起开始是否有keyword符合,
* 如果没有,则返回0
* 如果有符合的keyword值,继续遍历,直至遇到isEnd = 1,返回匹配的keyword的长度,
*/
private int checkKeyWords(String txt, int begin) {
HashMap nowhash = keysMap;
int res = 0;
for (int i = begin; i < txt.length(); i++) {
char word = txt.charAt(i);
Object wordMap = nowhash.get(word);//得到该字符对应的HashMap
if (wordMap == null) {
return 0;//如果该字符没有对应的HashMap,return 0
}
res++;//如果该字符对应的HashMap不为null,说明匹配到了一个字符,+1
nowhash = (HashMap) wordMap;//将遍历的HashMap指向该字符对应的HashMap
if (((String) nowhash.get("isEnd")).equals("1")) {//如果该字符为敏感词的结束字符,直接返回
return res;
} else {
continue;
}
}
return res;
}
/**
* 判断txt中是否有关键字
*/
public boolean isContentKeyWords(String txt) {
for (int i = 0; i < txt.length(); i++) {
int len = checkKeyWords(txt, i);
if (len > 0) {
return true;
}
}
return false;
}
/**
* 返回t <SUF>*/
public List<String> getTxtKeyWords(String txt) {
List<String> list = new ArrayList<String>();
int l = txt.length();
for (int i = 0; i < l;) {
int len = checkKeyWords(txt, i);
if (len > 0) {
String tt = txt.substring(i, i + len);
list.add(tt);
i += len;
} else {
i++;
}
}
return list;
}
/**
* 初始化敏感词列表
* */
public void initfiltercode() {
List<String> keywords = new ArrayList<String>();
keywords.add("中国人");
keywords.add("中国男人");
keywords.add("法轮");
this.addKeywords(keywords);
}
public static void main(String[] args) throws IOException {
KeywordFilter filter = new KeywordFilter();
filter.initfiltercode();
String txt = "哈哈,反倒是 法轮热舞功,中国人,";
boolean boo = filter.isContentKeyWords(txt);
System.out.println(boo);
List<String> set = filter.getTxtKeyWords(txt);
System.out.println("包含的敏感词如下:" + set);
}
} | 0 |
54214_21 | package net.cgt.weixin;
/**
* Static constants for this package.<br>
* 静态常量
*
* @author lijian
* @date 2014-11-22
*/
public interface Constants {
/** SharedPreferences 文件名 **/
String SHARED_PREFERENCE_NAME = "client_preferences";
/********************************** 用户登陆管理 ***************************************************************************************************/
/** 用户最后登陆时间 **/
String LAST_TIME = "LAST_TIME";
/** 一个月内自动登陆 : 60 * 60 * 24 * 30 = 2592000 **/
long AUTO_LOGIN = 2592000;
/** 记录上次退出时页面 **/
String PAGENUMBER = "PAGENUMBER";
/********************************** 偏好设置 ***************************************************************************************************/
/** 回调Activity的包名 **/
String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME";
/** 回调Activity的全类名 **/
String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME";
/** XMPP密钥 **/
String API_KEY = "API_KEY";
/** 版本号 **/
String VERSION = "VERSION";
/** XMPP的IP **/
String XMPP_HOST = "XMPP_HOST";
/** XMPP的端口 **/
String XMPP_PORT = "XMPP_PORT";
/** XMPP的用户名 **/
String XMPP_USERNAME = "XMPP_USERNAME";
/** XMPP的密码 **/
String XMPP_PASSWORD = "XMPP_PASSWORD";
// String USER_KEY = "USER_KEY";
/** 设备ID(手机*#06#) **/
String DEVICE_ID = "DEVICE_ID";
/** 模拟器ID **/
String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID";
/** 通知的logo图片 **/
String NOTIFICATION_ICON = "NOTIFICATION_ICON";
/** 是否显示推送的通知 **/
String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED";
/** 当接到推送通知-->是否播放通知声音 **/
String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED";
/** 当接到推送通知-->是否震动手机 **/
String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED";
/** 当接到推送通知-->是否显示吐司 **/
String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED";
/********************************** 通知 ***************************************************************************************************/
/** 通知的ID **/
String NOTIFICATION_ID = "NOTIFICATION_ID";
/** 通知的密钥 **/
String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY";
/** 通知的标题 **/
String NOTIFICATION_TITLE = "NOTIFICATION_TITLE";
/** 通知的正文 **/
String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE";
/** 通知的Url **/
String NOTIFICATION_URI = "NOTIFICATION_URI";
/********************************** intent动作 ***************************************************************************************************/
/** 显示通知 **/
String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION";
/** 通知被点击 **/
String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED";
/** 清除通知 **/
String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED";
}
| 54cgt/weixin | 微信/src/net/cgt/weixin/Constants.java | 856 | /** 当接到推送通知-->是否震动手机 **/ | block_comment | zh-cn | package net.cgt.weixin;
/**
* Static constants for this package.<br>
* 静态常量
*
* @author lijian
* @date 2014-11-22
*/
public interface Constants {
/** SharedPreferences 文件名 **/
String SHARED_PREFERENCE_NAME = "client_preferences";
/********************************** 用户登陆管理 ***************************************************************************************************/
/** 用户最后登陆时间 **/
String LAST_TIME = "LAST_TIME";
/** 一个月内自动登陆 : 60 * 60 * 24 * 30 = 2592000 **/
long AUTO_LOGIN = 2592000;
/** 记录上次退出时页面 **/
String PAGENUMBER = "PAGENUMBER";
/********************************** 偏好设置 ***************************************************************************************************/
/** 回调Activity的包名 **/
String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME";
/** 回调Activity的全类名 **/
String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME";
/** XMPP密钥 **/
String API_KEY = "API_KEY";
/** 版本号 **/
String VERSION = "VERSION";
/** XMPP的IP **/
String XMPP_HOST = "XMPP_HOST";
/** XMPP的端口 **/
String XMPP_PORT = "XMPP_PORT";
/** XMPP的用户名 **/
String XMPP_USERNAME = "XMPP_USERNAME";
/** XMPP的密码 **/
String XMPP_PASSWORD = "XMPP_PASSWORD";
// String USER_KEY = "USER_KEY";
/** 设备ID(手机*#06#) **/
String DEVICE_ID = "DEVICE_ID";
/** 模拟器ID **/
String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID";
/** 通知的logo图片 **/
String NOTIFICATION_ICON = "NOTIFICATION_ICON";
/** 是否显示推送的通知 **/
String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED";
/** 当接到推送通知-->是否播放通知声音 **/
String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED";
/** 当接到 <SUF>*/
String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED";
/** 当接到推送通知-->是否显示吐司 **/
String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED";
/********************************** 通知 ***************************************************************************************************/
/** 通知的ID **/
String NOTIFICATION_ID = "NOTIFICATION_ID";
/** 通知的密钥 **/
String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY";
/** 通知的标题 **/
String NOTIFICATION_TITLE = "NOTIFICATION_TITLE";
/** 通知的正文 **/
String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE";
/** 通知的Url **/
String NOTIFICATION_URI = "NOTIFICATION_URI";
/********************************** intent动作 ***************************************************************************************************/
/** 显示通知 **/
String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION";
/** 通知被点击 **/
String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED";
/** 清除通知 **/
String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED";
}
| 0 |
52731_6 | package pri.weiqiang.liyujapanese.mvp.bean.zhihu;
import java.util.List;
/**
* Created by yiyi on 2016/12/27.
*/
public class ThemeContentListEntity {
/**
* stories : [{"images":["http://pic1.zhimg.com/e3f596c7ed9e470733f0637adb6124e4.jpg"],"type":0,"id":7468668,"title":"不许无聊在读读日报里等你哟"},{"images":["http://pic4.zhimg.com/b5bb0754c6bab0adec4edd1256efbef7_t.jpg"],"type":2,"id":7315220,"title":"第一天上班 超激动,可惜后来被打了脸\u2026"},{"images":["http://pic3.zhimg.com/508c01ace291bd839dfdf13a8487ea92_t.jpg"],"type":2,"id":7310300,"title":"群众都是重口味,世上再无主流色情杂志这回事"},{"images":["http://pic4.zhimg.com/63a262791c4e2b156d932c7a03b137df_t.jpg"],"type":2,"id":7307922,"title":"11 个关于漫威的冷知识,原来圣诞老人是变种人!"},{"images":["http://pic1.zhimg.com/58bce639a1fea757e3b9053d061936dc_t.jpg"],"type":2,"id":7305993,"title":"7 个日本高阶旅行地,没有中国游客"},{"images":["http://pic1.zhimg.com/4edd2b5b75775da684dab887be15de00_t.jpg"],"type":2,"id":7303298,"title":"11 张本周最热节操图,担心的事情终于发生了"},{"images":["http://pic4.zhimg.com/1b8e2e93aef140349407d2580b16f887_t.jpg"],"type":2,"id":7300302,"title":"我们真的发现了外星人的太空飞船吗?"},{"images":["http://pic4.zhimg.com/1039533776aafebadd11ad377eebde47_t.jpg"],"type":2,"id":7299037,"title":"问题:单身的人可以是幸福的吗?"},{"images":["http://pic1.zhimg.com/cb2045505a5ea2e8e2b3896db181fe90_t.jpg"],"type":2,"id":7295366,"title":"10 个理由告诉你我为什么要停用朋友圈"},{"images":["http://pic1.zhimg.com/8f4f1762130eefa0a310daf324ff3454_t.jpg"],"type":2,"id":7292710,"title":"17 个叼叼的人类隐藏技能,一定是吃了恶魔果实"},{"images":["http://pic1.zhimg.com/8f652c700593e10f4e5ce8ec15774874.jpg"],"type":2,"id":7288286,"title":"《小王子》早就教你该怎么谈恋爱了,单身怪自己"},{"images":["http://pic1.zhimg.com/1750ca43e2a2534dddcca3a813cd7fb4_t.jpg"],"type":2,"id":7285920,"title":"其实每个人内心都想成为一张小浴巾!!"},{"images":["http://pic1.zhimg.com/e512e59a4311e1d9a489fac8144fd670_t.jpg"],"type":2,"id":7281623,"title":"23 个男生永远理解不了的画面"},{"images":["http://pic3.zhimg.com/01d8ab485233cc00631d813d93b51746_t.jpg"],"type":2,"id":7279286,"title":"8 张图完美阐释你和你妈的非凡关系"},{"images":["http://pic2.zhimg.com/2ae9218b5b2ae0de917ca5327f1a62d9_t.jpg"],"type":2,"id":7274499,"title":"王菲小女儿李嫣上了微博热门,因为她实在太可爱了"},{"images":["http://pic1.zhimg.com/5e7e245530ca61296a175c385414982c_t.jpg"],"type":2,"id":7271705,"title":"14 个直播记者比你今天烦躁多了"},{"images":["http://pic4.zhimg.com/2a8b736ff65ac13dfb54dd8eab7d0353_t.jpg"],"type":2,"id":7268620,"title":"有了它们你再也不用吃安利补 VC 了"},{"images":["http://pic3.zhimg.com/fd7eb52781ea04ba6e6962eef86450ce_t.jpg"],"type":2,"id":7267355,"title":"11 个本周冷知识,婚礼除了公主梦其实也可以很酷"},{"images":["http://pic3.zhimg.com/cfe264c81fae5c1438aa9e27a4e3d5a2_t.jpg"],"type":2,"id":7262019,"title":"11 张本周最热节操图,琅琊榜的导演根本不给演员活路啊"}]
* description : 为你发现最有趣的新鲜事,建议在 WiFi 下查看
* background : http://pic1.zhimg.com/a5128188ed788005ad50840a42079c41.jpg
* color : 8307764
* name : 不许无聊
* image : http://pic3.zhimg.com/da1fcaf6a02d1223d130d5b106e828b9.jpg
* editors : [{"url":"http://www.zhihu.com/people/wezeit","bio":"微在 Wezeit 主编","id":70,"avatar":"http://pic4.zhimg.com/068311926_m.jpg","name":"益康糯米"},{"url":"http://www.zhihu.com/people/kuangzhou","bio":"明月般俊朗","id":71,"avatar":"http://pic4.zhimg.com/43d10de2b46c918a9ffe5d0472947b67_m.jpg","name":"顾惜朝"}]
* image_source :
*/
private String description;
private String background;
private int color;
private String name;
private String image;
private String image_source;
private List<StoriesEntity> stories;
private List<EditorsEntity> editors;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBackground() {
return background;
}
public void setBackground(String background) {
this.background = background;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getImage_source() {
return image_source;
}
public void setImage_source(String image_source) {
this.image_source = image_source;
}
public List<StoriesEntity> getStories() {
return stories;
}
public void setStories(List<StoriesEntity> stories) {
this.stories = stories;
}
public List<EditorsEntity> getEditors() {
return editors;
}
public void setEditors(List<EditorsEntity> editors) {
this.editors = editors;
}
// public static class StoriesEntity implements DisplaybleItem{
// /**
// * images : ["http://pic1.zhimg.com/e3f596c7ed9e470733f0637adb6124e4.jpg"]
// * type : 0
// * id : 7468668
// * title : 不许无聊在读读日报里等你哟
// */
//
// private int type;
// private int id;
// private String title;
// private List<String> images;
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<String> getImages() {
// return images;
// }
//
// public void setImages(List<String> images) {
// this.images = images;
// }
// }
}
| 54wall/LiYuJapanese | mvp/MvpLiYu/app/src/main/java/pri/weiqiang/liyujapanese/mvp/bean/zhihu/ThemeContentListEntity.java | 2,581 | // * title : 不许无聊在读读日报里等你哟 | line_comment | zh-cn | package pri.weiqiang.liyujapanese.mvp.bean.zhihu;
import java.util.List;
/**
* Created by yiyi on 2016/12/27.
*/
public class ThemeContentListEntity {
/**
* stories : [{"images":["http://pic1.zhimg.com/e3f596c7ed9e470733f0637adb6124e4.jpg"],"type":0,"id":7468668,"title":"不许无聊在读读日报里等你哟"},{"images":["http://pic4.zhimg.com/b5bb0754c6bab0adec4edd1256efbef7_t.jpg"],"type":2,"id":7315220,"title":"第一天上班 超激动,可惜后来被打了脸\u2026"},{"images":["http://pic3.zhimg.com/508c01ace291bd839dfdf13a8487ea92_t.jpg"],"type":2,"id":7310300,"title":"群众都是重口味,世上再无主流色情杂志这回事"},{"images":["http://pic4.zhimg.com/63a262791c4e2b156d932c7a03b137df_t.jpg"],"type":2,"id":7307922,"title":"11 个关于漫威的冷知识,原来圣诞老人是变种人!"},{"images":["http://pic1.zhimg.com/58bce639a1fea757e3b9053d061936dc_t.jpg"],"type":2,"id":7305993,"title":"7 个日本高阶旅行地,没有中国游客"},{"images":["http://pic1.zhimg.com/4edd2b5b75775da684dab887be15de00_t.jpg"],"type":2,"id":7303298,"title":"11 张本周最热节操图,担心的事情终于发生了"},{"images":["http://pic4.zhimg.com/1b8e2e93aef140349407d2580b16f887_t.jpg"],"type":2,"id":7300302,"title":"我们真的发现了外星人的太空飞船吗?"},{"images":["http://pic4.zhimg.com/1039533776aafebadd11ad377eebde47_t.jpg"],"type":2,"id":7299037,"title":"问题:单身的人可以是幸福的吗?"},{"images":["http://pic1.zhimg.com/cb2045505a5ea2e8e2b3896db181fe90_t.jpg"],"type":2,"id":7295366,"title":"10 个理由告诉你我为什么要停用朋友圈"},{"images":["http://pic1.zhimg.com/8f4f1762130eefa0a310daf324ff3454_t.jpg"],"type":2,"id":7292710,"title":"17 个叼叼的人类隐藏技能,一定是吃了恶魔果实"},{"images":["http://pic1.zhimg.com/8f652c700593e10f4e5ce8ec15774874.jpg"],"type":2,"id":7288286,"title":"《小王子》早就教你该怎么谈恋爱了,单身怪自己"},{"images":["http://pic1.zhimg.com/1750ca43e2a2534dddcca3a813cd7fb4_t.jpg"],"type":2,"id":7285920,"title":"其实每个人内心都想成为一张小浴巾!!"},{"images":["http://pic1.zhimg.com/e512e59a4311e1d9a489fac8144fd670_t.jpg"],"type":2,"id":7281623,"title":"23 个男生永远理解不了的画面"},{"images":["http://pic3.zhimg.com/01d8ab485233cc00631d813d93b51746_t.jpg"],"type":2,"id":7279286,"title":"8 张图完美阐释你和你妈的非凡关系"},{"images":["http://pic2.zhimg.com/2ae9218b5b2ae0de917ca5327f1a62d9_t.jpg"],"type":2,"id":7274499,"title":"王菲小女儿李嫣上了微博热门,因为她实在太可爱了"},{"images":["http://pic1.zhimg.com/5e7e245530ca61296a175c385414982c_t.jpg"],"type":2,"id":7271705,"title":"14 个直播记者比你今天烦躁多了"},{"images":["http://pic4.zhimg.com/2a8b736ff65ac13dfb54dd8eab7d0353_t.jpg"],"type":2,"id":7268620,"title":"有了它们你再也不用吃安利补 VC 了"},{"images":["http://pic3.zhimg.com/fd7eb52781ea04ba6e6962eef86450ce_t.jpg"],"type":2,"id":7267355,"title":"11 个本周冷知识,婚礼除了公主梦其实也可以很酷"},{"images":["http://pic3.zhimg.com/cfe264c81fae5c1438aa9e27a4e3d5a2_t.jpg"],"type":2,"id":7262019,"title":"11 张本周最热节操图,琅琊榜的导演根本不给演员活路啊"}]
* description : 为你发现最有趣的新鲜事,建议在 WiFi 下查看
* background : http://pic1.zhimg.com/a5128188ed788005ad50840a42079c41.jpg
* color : 8307764
* name : 不许无聊
* image : http://pic3.zhimg.com/da1fcaf6a02d1223d130d5b106e828b9.jpg
* editors : [{"url":"http://www.zhihu.com/people/wezeit","bio":"微在 Wezeit 主编","id":70,"avatar":"http://pic4.zhimg.com/068311926_m.jpg","name":"益康糯米"},{"url":"http://www.zhihu.com/people/kuangzhou","bio":"明月般俊朗","id":71,"avatar":"http://pic4.zhimg.com/43d10de2b46c918a9ffe5d0472947b67_m.jpg","name":"顾惜朝"}]
* image_source :
*/
private String description;
private String background;
private int color;
private String name;
private String image;
private String image_source;
private List<StoriesEntity> stories;
private List<EditorsEntity> editors;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBackground() {
return background;
}
public void setBackground(String background) {
this.background = background;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getImage_source() {
return image_source;
}
public void setImage_source(String image_source) {
this.image_source = image_source;
}
public List<StoriesEntity> getStories() {
return stories;
}
public void setStories(List<StoriesEntity> stories) {
this.stories = stories;
}
public List<EditorsEntity> getEditors() {
return editors;
}
public void setEditors(List<EditorsEntity> editors) {
this.editors = editors;
}
// public static class StoriesEntity implements DisplaybleItem{
// /**
// * images : ["http://pic1.zhimg.com/e3f596c7ed9e470733f0637adb6124e4.jpg"]
// * type : 0
// * id : 7468668
// * ti <SUF>
// */
//
// private int type;
// private int id;
// private String title;
// private List<String> images;
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<String> getImages() {
// return images;
// }
//
// public void setImages(List<String> images) {
// this.images = images;
// }
// }
}
| 1 |
28765_18 | package Utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Student;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by Cheung on 2017/12/19.
*
* Apache POI操作Excel对象
* HSSF:操作Excel 2007之前版本(.xls)格式,生成的EXCEL不经过压缩直接导出
* XSSF:操作Excel 2007及之后版本(.xlsx)格式,内存占用高于HSSF
* SXSSF:从POI3.8 beta3开始支持,基于XSSF,低内存占用,专门处理大数据量(建议)。
*
* 注意:
* 值得注意的是SXSSFWorkbook只能写(导出)不能读(导入)
*
* 说明:
* .xls格式的excel(最大行数65536行,最大列数256列)
* .xlsx格式的excel(最大行数1048576行,最大列数16384列)
*/
public class ExcelUtil {
public static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日";// 默认日期格式
public static final int DEFAULT_COLUMN_WIDTH = 17;// 默认列宽
/**
* 导出Excel(.xlsx)格式
* @param titleList 表格头信息集合
* @param dataArray 数据数组
* @param os 文件输出流
*/
public static void exportExcel(ArrayList<LinkedHashMap> titleList, JSONArray dataArray, OutputStream os) {
String datePattern = DEFAULT_DATE_PATTERN;
int minBytes = DEFAULT_COLUMN_WIDTH;
/**
* 声明一个工作薄
*/
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);// 大于1000行时会把之前的行写入硬盘
workbook.setCompressTempFiles(true);
// 表头1样式
CellStyle title1Style = workbook.createCellStyle();
title1Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中
title1Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
Font titleFont = workbook.createFont();// 字体
titleFont.setFontHeightInPoints((short) 20);
titleFont.setBoldweight((short) 700);
title1Style.setFont(titleFont);
// 表头2样式
CellStyle title2Style = workbook.createCellStyle();
title2Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
title2Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
title2Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
title2Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右
title2Style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下
title2Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左
Font title2Font = workbook.createFont();
title2Font.setUnderline((byte) 1);
title2Font.setColor(HSSFColor.BLUE.index);
title2Style.setFont(title2Font);
// head样式
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
headerStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);// 设置颜色
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 前景色纯色填充
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font headerFont = workbook.createFont();
headerFont.setFontHeightInPoints((short) 12);
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerStyle.setFont(headerFont);
// 单元格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font cellFont = workbook.createFont();
cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
cellStyle.setFont(cellFont);
String title1 = (String) titleList.get(0).get("title1");
String title2 = (String) titleList.get(0).get("title2");
LinkedHashMap<String, String> headMap = titleList.get(1);
/**
* 生成一个(带名称)表格
*/
SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(title1);
sheet.createFreezePane(0, 3, 0, 3);// (单独)冻结前三行
/**
* 生成head相关信息+设置每列宽度
*/
int[] colWidthArr = new int[headMap.size()];// 列宽数组
String[] headKeyArr = new String[headMap.size()];// headKey数组
String[] headValArr = new String[headMap.size()];// headVal数组
int i = 0;
for (Map.Entry<String, String> entry : headMap.entrySet()) {
headKeyArr[i] = entry.getKey();
headValArr[i] = entry.getValue();
int bytes = headKeyArr[i].getBytes().length;
colWidthArr[i] = bytes < minBytes ? minBytes : bytes;
sheet.setColumnWidth(i, colWidthArr[i] * 256);// 设置列宽
i++;
}
/**
* 遍历数据集合,产生Excel行数据
*/
int rowIndex = 0;
for (Object obj : dataArray) {
// 生成title+head信息
if (rowIndex == 0) {
SXSSFRow title1Row = (SXSSFRow) sheet.createRow(0);// title1行
title1Row.createCell(0).setCellValue(title1);
title1Row.getCell(0).setCellStyle(title1Style);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));// 合并单元格
SXSSFRow title2Row = (SXSSFRow) sheet.createRow(1);// title2行
title2Row.createCell(0).setCellValue(title2);
CreationHelper createHelper = workbook.getCreationHelper();
XSSFHyperlink hyperLink = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
hyperLink.setAddress(title2);
title2Row.getCell(0).setHyperlink(hyperLink);// 添加超链接
title2Row.getCell(0).setCellStyle(title2Style);
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, headMap.size() - 1));// 合并单元格
SXSSFRow headerRow = (SXSSFRow) sheet.createRow(2);// head行
for (int j = 0; j < headValArr.length; j++) {
headerRow.createCell(j).setCellValue(headValArr[j]);
headerRow.getCell(j).setCellStyle(headerStyle);
}
rowIndex = 3;
}
JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
// 生成数据
SXSSFRow dataRow = (SXSSFRow) sheet.createRow(rowIndex);// 创建行
for (int k = 0; k < headKeyArr.length; k++) {
SXSSFCell cell = (SXSSFCell) dataRow.createCell(k);// 创建单元格
Object o = jo.get(headKeyArr[k]);
String cellValue = "";
if (o == null) {
cellValue = "";
} else if (o instanceof Date) {
cellValue = new SimpleDateFormat(datePattern).format(o);
} else if (o instanceof Float || o instanceof Double) {
cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
} else {
cellValue = o.toString();
}
if (cellValue.equals("true")) {
cellValue = "男";
} else if (cellValue.equals("false")) {
cellValue = "女";
}
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle);
}
rowIndex++;
}
try {
workbook.write(os);
os.flush();// 刷新此输出流并强制将所有缓冲的输出字节写出
os.close();// 关闭流
workbook.dispose();// 释放workbook所占用的所有windows资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 550690513/large-amount-data-export | src/main/java/Utils/ExcelUtil.java | 2,526 | // 列宽数组 | line_comment | zh-cn | package Utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Student;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by Cheung on 2017/12/19.
*
* Apache POI操作Excel对象
* HSSF:操作Excel 2007之前版本(.xls)格式,生成的EXCEL不经过压缩直接导出
* XSSF:操作Excel 2007及之后版本(.xlsx)格式,内存占用高于HSSF
* SXSSF:从POI3.8 beta3开始支持,基于XSSF,低内存占用,专门处理大数据量(建议)。
*
* 注意:
* 值得注意的是SXSSFWorkbook只能写(导出)不能读(导入)
*
* 说明:
* .xls格式的excel(最大行数65536行,最大列数256列)
* .xlsx格式的excel(最大行数1048576行,最大列数16384列)
*/
public class ExcelUtil {
public static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日";// 默认日期格式
public static final int DEFAULT_COLUMN_WIDTH = 17;// 默认列宽
/**
* 导出Excel(.xlsx)格式
* @param titleList 表格头信息集合
* @param dataArray 数据数组
* @param os 文件输出流
*/
public static void exportExcel(ArrayList<LinkedHashMap> titleList, JSONArray dataArray, OutputStream os) {
String datePattern = DEFAULT_DATE_PATTERN;
int minBytes = DEFAULT_COLUMN_WIDTH;
/**
* 声明一个工作薄
*/
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);// 大于1000行时会把之前的行写入硬盘
workbook.setCompressTempFiles(true);
// 表头1样式
CellStyle title1Style = workbook.createCellStyle();
title1Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中
title1Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
Font titleFont = workbook.createFont();// 字体
titleFont.setFontHeightInPoints((short) 20);
titleFont.setBoldweight((short) 700);
title1Style.setFont(titleFont);
// 表头2样式
CellStyle title2Style = workbook.createCellStyle();
title2Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
title2Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
title2Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
title2Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右
title2Style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下
title2Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左
Font title2Font = workbook.createFont();
title2Font.setUnderline((byte) 1);
title2Font.setColor(HSSFColor.BLUE.index);
title2Style.setFont(title2Font);
// head样式
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
headerStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);// 设置颜色
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 前景色纯色填充
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font headerFont = workbook.createFont();
headerFont.setFontHeightInPoints((short) 12);
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerStyle.setFont(headerFont);
// 单元格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font cellFont = workbook.createFont();
cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
cellStyle.setFont(cellFont);
String title1 = (String) titleList.get(0).get("title1");
String title2 = (String) titleList.get(0).get("title2");
LinkedHashMap<String, String> headMap = titleList.get(1);
/**
* 生成一个(带名称)表格
*/
SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(title1);
sheet.createFreezePane(0, 3, 0, 3);// (单独)冻结前三行
/**
* 生成head相关信息+设置每列宽度
*/
int[] colWidthArr = new int[headMap.size()];// 列宽 <SUF>
String[] headKeyArr = new String[headMap.size()];// headKey数组
String[] headValArr = new String[headMap.size()];// headVal数组
int i = 0;
for (Map.Entry<String, String> entry : headMap.entrySet()) {
headKeyArr[i] = entry.getKey();
headValArr[i] = entry.getValue();
int bytes = headKeyArr[i].getBytes().length;
colWidthArr[i] = bytes < minBytes ? minBytes : bytes;
sheet.setColumnWidth(i, colWidthArr[i] * 256);// 设置列宽
i++;
}
/**
* 遍历数据集合,产生Excel行数据
*/
int rowIndex = 0;
for (Object obj : dataArray) {
// 生成title+head信息
if (rowIndex == 0) {
SXSSFRow title1Row = (SXSSFRow) sheet.createRow(0);// title1行
title1Row.createCell(0).setCellValue(title1);
title1Row.getCell(0).setCellStyle(title1Style);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));// 合并单元格
SXSSFRow title2Row = (SXSSFRow) sheet.createRow(1);// title2行
title2Row.createCell(0).setCellValue(title2);
CreationHelper createHelper = workbook.getCreationHelper();
XSSFHyperlink hyperLink = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
hyperLink.setAddress(title2);
title2Row.getCell(0).setHyperlink(hyperLink);// 添加超链接
title2Row.getCell(0).setCellStyle(title2Style);
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, headMap.size() - 1));// 合并单元格
SXSSFRow headerRow = (SXSSFRow) sheet.createRow(2);// head行
for (int j = 0; j < headValArr.length; j++) {
headerRow.createCell(j).setCellValue(headValArr[j]);
headerRow.getCell(j).setCellStyle(headerStyle);
}
rowIndex = 3;
}
JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
// 生成数据
SXSSFRow dataRow = (SXSSFRow) sheet.createRow(rowIndex);// 创建行
for (int k = 0; k < headKeyArr.length; k++) {
SXSSFCell cell = (SXSSFCell) dataRow.createCell(k);// 创建单元格
Object o = jo.get(headKeyArr[k]);
String cellValue = "";
if (o == null) {
cellValue = "";
} else if (o instanceof Date) {
cellValue = new SimpleDateFormat(datePattern).format(o);
} else if (o instanceof Float || o instanceof Double) {
cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
} else {
cellValue = o.toString();
}
if (cellValue.equals("true")) {
cellValue = "男";
} else if (cellValue.equals("false")) {
cellValue = "女";
}
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle);
}
rowIndex++;
}
try {
workbook.write(os);
os.flush();// 刷新此输出流并强制将所有缓冲的输出字节写出
os.close();// 关闭流
workbook.dispose();// 释放workbook所占用的所有windows资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 0 |
57896_0 |
/*建立一个简易的投票软件,基本外观如下:有4根红颜色的柱形图横向摆放,
* 每个柱形图上方显示得票数,每个柱形图下方都有个“投票”按钮。
* 一开始得票数为0,柱形图高度为1像素,点击投票时根据得票的增加柱形图的高度也增加。*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame {
int[] count = new int[4];
final int total = 4;
JButton keys[] = new JButton[total];
JTextField jl[] = new JTextField[total];
public MyFrame() {
Container container = getContentPane();
setLayout(null);
setSize(500, 300);
setVisible(true);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < jl.length; i++) {
jl[i] = new JTextField("0");
jl[i].setBounds(10, 10 + 60 * i, 18, 15);
jl[i].setEditable(false);
container.add(jl[i]);
}
for (int i = 0; i < keys.length; i++) {
keys[i] = new JButton("刷票");
keys[i].setBounds(10, 50 + 60 * i, 60, 20);
container.add(keys[i]);
final int j = i;
keys[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count[j]++;
String str = " " + count[j];
jl[j].setText(str);
repaint();
}
});
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRect(20, 60, 1 + count[0], 10);
g.fillRect(20, 120, 1 + count[1], 10);
g.fillRect(20, 180, 1 + count[2], 10);
g.fillRect(20, 240, 1 + count[3], 10);
}
}
public class Lab9_2 {
public static void main(String[] args) {
new MyFrame();
}
}
| 5522MIKE/JAVA-DRAFT | Lab9/src/Lab9_2.java | 644 | /*建立一个简易的投票软件,基本外观如下:有4根红颜色的柱形图横向摆放,
* 每个柱形图上方显示得票数,每个柱形图下方都有个“投票”按钮。
* 一开始得票数为0,柱形图高度为1像素,点击投票时根据得票的增加柱形图的高度也增加。*/ | block_comment | zh-cn |
/*建立一 <SUF>*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame {
int[] count = new int[4];
final int total = 4;
JButton keys[] = new JButton[total];
JTextField jl[] = new JTextField[total];
public MyFrame() {
Container container = getContentPane();
setLayout(null);
setSize(500, 300);
setVisible(true);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < jl.length; i++) {
jl[i] = new JTextField("0");
jl[i].setBounds(10, 10 + 60 * i, 18, 15);
jl[i].setEditable(false);
container.add(jl[i]);
}
for (int i = 0; i < keys.length; i++) {
keys[i] = new JButton("刷票");
keys[i].setBounds(10, 50 + 60 * i, 60, 20);
container.add(keys[i]);
final int j = i;
keys[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count[j]++;
String str = " " + count[j];
jl[j].setText(str);
repaint();
}
});
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRect(20, 60, 1 + count[0], 10);
g.fillRect(20, 120, 1 + count[1], 10);
g.fillRect(20, 180, 1 + count[2], 10);
g.fillRect(20, 240, 1 + count[3], 10);
}
}
public class Lab9_2 {
public static void main(String[] args) {
new MyFrame();
}
}
| 0 |
17319_22 | import java.util.Arrays;
/**
* @author jzy
* @GitHub <a href="https://github.com/567jin">567jin</a>
* @since 2024-03-18 21:22:07
*/
public class _0_Sort {
public static void main(String[] args) {
int[] arr = {1, 5, 9, -3, 6, 500, 200, 300};
System.out.println("排序前:" + Arrays.toString(arr));
// System.out.println("冒泡排序:" + Arrays.toString(bubbleSort(arr)));
// System.out.println("选则排序:" + Arrays.toString(selectionSort(arr)));
// System.out.println("插入排序:" + Arrays.toString(insertionSort(arr)));
System.out.println("归并排序:" + Arrays.toString(mergeSort(arr)));
// System.out.println("归并排序:" + Arrays.toString(mergeSort2(arr)));
// quickSort(arr, 0, arr.length - 1);
// System.out.println("快速排序:" + Arrays.toString(arr));
// System.out.println("计数排序: " + Arrays.toString(countingSort(arr)));
System.out.println("堆排序:" + Arrays.toString(HeapSort(arr)));
}
public static int[] HeapSort(int[] arr) {
// 建堆
int n = arr.length; // 构建大顶堆 最后一个叶子结点开始 对于一个具有 n 个元素的完全二叉树,它的最后一个非叶子节点的索引是 (n >> 1) - 1
for (int i = (n >> 1) - 1; i >= 0; i--) {
heapModify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--) {
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
heapModify(arr, i, 0);
}
return arr;
}
// n是树的上界 i表示当前最大值
private static void heapModify(int[] arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// 放置largest
if (largest != i) {
int temp = arr[largest];
arr[largest] = arr[i];
arr[i] = temp;
// 一直调整堆 直到 largest 放置到正确的位置
heapModify(arr, n, largest);
}
}
/**
* 冒泡排序 时间复杂度:O(n^2)
* 最好的时间复杂度:O(n)
* 稳定性:不稳定
* 排序方式:In-place
*/
public static int[] bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) { // 外层比较次数为n-i
boolean flag = true; // 做优化,如果上一次没有交换,说明已经有序,直接跳出
for (int j = 0; j < n - i; j++) { // 内层次数为n-i
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
/**
* 选择排序 无论如何时间复杂度都是O(n^2)
* 稳定性:不稳定
* 排序方式:In-place
*/
public static int[] selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
/**
* 插入排序
* 最坏:O(n^2)
* 最好:O(n)
* 稳定性:稳定
* 排序方式:In-place
*/
public static int[] insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int preIndex = i - 1;
int current = arr[i];
while (preIndex >= 0 && current < arr[preIndex]) { // 当前值小于上一个值时 将上一个值往后移
arr[preIndex + 1] = arr[preIndex];
preIndex -= 1;
}
arr[preIndex + 1] = current;
}
return arr;
}
public static int[] mergeSort2(int[] arr) {
if (arr.length <= 1) {
return arr;
}
int[] aux = new int[arr.length]; // 辅助数组 防止频繁创建数组
mergeSort(arr, 0, arr.length - 1, aux);
return arr;
}
private static void mergeSort(int[] arr, int low, int high, int[] aux) {
if (low >= high) {
return;
}
int middle = (low + high) / 2;
mergeSort(arr, low, middle, aux); // 左半部分归并排序
mergeSort(arr, middle + 1, high, aux); // 右半部分归并排序
merge(arr, low, middle, high, aux); // 归并两个有序数组
}
private static void merge(int[] arr, int low, int middle, int high, int[] aux) {
// 将arr[low...middle]和arr[middle+1...high]两部分归并到aux数组中
for (int i = low; i <= high; i++) {
aux[i] = arr[i];
}
int i = low; // 左半部分起始索引
int j = middle + 1; // 右半部分起始索引
int k = low; // 归并后数组的起始索引
// 归并排序
while (i <= middle && j <= high) {
if (aux[i] <= aux[j]) {
arr[k++] = aux[i++];
} else {
arr[k++] = aux[j++];
}
}
// 处理剩余的元素
while (i <= middle) {
arr[k++] = aux[i++];
}
while (j <= high) {
arr[k++] = aux[j++];
}
}
/**
* 归并排序
* 采用分治的思想
*/
public static int[] mergeSort(int[] arr) {
if (arr.length <= 1) { // 边界条件
return arr;
}
int middle = arr.length / 2;
int[] arr_1 = Arrays.copyOfRange(arr, 0, middle);
int[] arr_2 = Arrays.copyOfRange(arr, middle, arr.length);
return merge(mergeSort(arr_1), mergeSort(arr_2));
}
/**
* Merge two sorted arrays
* 合并两个有序数组
*/
public static int[] merge(int[] arr_1, int[] arr_2) {
int[] sorted_arr = new int[arr_1.length + arr_2.length];
int idx = 0, idx_1 = 0, idx_2 = 0;
while (idx_1 < arr_1.length && idx_2 < arr_2.length) {
if (arr_1[idx_1] < arr_2[idx_2]) {
sorted_arr[idx] = arr_1[idx_1];
idx_1 += 1;
} else {
sorted_arr[idx] = arr_2[idx_2];
idx_2 += 1;
}
idx += 1;
}
// 处理剩余的元素
if (idx_1 < arr_1.length) {
while (idx_1 < arr_1.length) {
sorted_arr[idx] = arr_1[idx_1];
idx_1 += 1;
idx += 1;
}
} else {
while (idx_2 < arr_2.length) {
sorted_arr[idx] = arr_2[idx_2];
idx_2 += 1;
idx += 1;
}
}
return sorted_arr;
}
/**
* 对给定的数组进行分区操作,使得所有小于等于基准元素的值位于基准元素的左侧,所有大于基准元素的值位于基准元素的右侧。
*
* @param array 待分区的数组
* @param low 分区的起始索引
* @param high 分区的结束索引(包含)
* @return 基准元素最终位置的索引
*/
public static int partition(int[] array, int low, int high) {
int pivot = array[high]; // 选择最后一个元素作为基准元素
int pointer = low;
// 遍历数组,将所有小于等于基准元素的值放到基准元素的左侧
for (int i = low; i < high; i++) {
if (array[i] <= pivot) {
// 交换当前元素和指针所指元素,逐步将指针向右移动
int temp = array[i];
array[i] = array[pointer];
array[pointer] = temp;
pointer++;
}
// 打印每次交换后的数组状态
// System.out.println(Arrays.toString(array));
}
// 将基准元素放置到正确的位置上 即所有比其小的在其左边 用pointer表示有多少个元素在左边
int temp = array[pointer];
array[pointer] = pivot;
array[high] = temp;
// 返回基准元素的最终位置
return pointer;
}
/**
* 快速排序算法。
* 该算法通过不断划分序列,将待排序数组分为较小的子序列,然后递归地对这些子序列进行排序。
* 划分策略是选择一个基准元素,将小于基准元素的放在基准的左边,大于基准的放在基准的右边,基准元素的位置即为划分后两部分的分界点。
* 这个过程从数组的头部和尾部开始,逐步缩小范围,直到整个数组排序完成。
*
* @param array 待排序的整型数组。
* @param low 排序范围的起始下标。
* @param high 排序范围的终止下标。
*/
public static void quickSort(int[] array, int low, int high) {
// 如果起始下标小于终止下标,即待排序部分不为空,则进行排序
if (low < high) {
// 找到划分位置,使得划分后的两部分满足左边元素均小于右边元素
int position = partition(array, low, high);
// 递归排序基准的左边部分
quickSort(array, low, position - 1);
// 递归排序基准的右边部分
quickSort(array, position + 1, high);
}
}
/**
* Gets the maximum and minimum values in the array
*
* @param arr
* @return
*/
private static int[] getMinAndMax(int[] arr) {
int maxValue = arr[0];
int minValue = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > maxValue) {
maxValue = arr[i];
} else if (arr[i] < minValue) {
minValue = arr[i];
}
}
return new int[]{minValue, maxValue};
}
/**
* Counting Sort 计数排序
* 一种基于计数的排序算法,只能用于整数排序且范围有限。
*
* @param arr 待排序的整数数组
* @return 排序后的整数数组
*/
public static int[] countingSort(int[] arr) {
// 如果数组长度小于2,则无需排序,直接返回
if (arr.length < 2) {
return arr;
}
// 获取数组中的最小值和最大值
int[] extremum = getMinAndMax(arr);
int minValue = extremum[0];
int maxValue = extremum[1];
// 创建计数数组,长度为最大值和最小值之差加1
int[] countArr = new int[maxValue - minValue + 1];
// 遍历原数组,统计每个元素出现的次数
for (int j : arr) {
countArr[j - minValue] += 1;
}
// 计算累加和,以便确定每个元素在排序后数组中的位置
for (int i = 1; i < countArr.length; i++) {
countArr[i] += countArr[i - 1];
}
/*
* 1. 从后往前遍历原数组,将每个元素放置在正确的位置上
* 2. 遍历计数数组,将每个元素放置在正确的位置上
* 3. 从前往后遍历原数组,将每个元素放置在正确的位置上
*/
int[] result = new int[arr.length];
// 根据计数数组,将元素放置在正确的位置上
for (int i = arr.length - 1; i >= 0; i--) {
int idx = countArr[arr[i] - minValue] - 1;
result[idx] = arr[i];
// 更新计数数组 重复数 表示处理了一个了
countArr[arr[i] - minValue] -= 1;
}
return result;
}
}
| 567jin/AlgorithmPractice | src/_0_Sort.java | 3,414 | // 归并两个有序数组 | line_comment | zh-cn | import java.util.Arrays;
/**
* @author jzy
* @GitHub <a href="https://github.com/567jin">567jin</a>
* @since 2024-03-18 21:22:07
*/
public class _0_Sort {
public static void main(String[] args) {
int[] arr = {1, 5, 9, -3, 6, 500, 200, 300};
System.out.println("排序前:" + Arrays.toString(arr));
// System.out.println("冒泡排序:" + Arrays.toString(bubbleSort(arr)));
// System.out.println("选则排序:" + Arrays.toString(selectionSort(arr)));
// System.out.println("插入排序:" + Arrays.toString(insertionSort(arr)));
System.out.println("归并排序:" + Arrays.toString(mergeSort(arr)));
// System.out.println("归并排序:" + Arrays.toString(mergeSort2(arr)));
// quickSort(arr, 0, arr.length - 1);
// System.out.println("快速排序:" + Arrays.toString(arr));
// System.out.println("计数排序: " + Arrays.toString(countingSort(arr)));
System.out.println("堆排序:" + Arrays.toString(HeapSort(arr)));
}
public static int[] HeapSort(int[] arr) {
// 建堆
int n = arr.length; // 构建大顶堆 最后一个叶子结点开始 对于一个具有 n 个元素的完全二叉树,它的最后一个非叶子节点的索引是 (n >> 1) - 1
for (int i = (n >> 1) - 1; i >= 0; i--) {
heapModify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--) {
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
heapModify(arr, i, 0);
}
return arr;
}
// n是树的上界 i表示当前最大值
private static void heapModify(int[] arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// 放置largest
if (largest != i) {
int temp = arr[largest];
arr[largest] = arr[i];
arr[i] = temp;
// 一直调整堆 直到 largest 放置到正确的位置
heapModify(arr, n, largest);
}
}
/**
* 冒泡排序 时间复杂度:O(n^2)
* 最好的时间复杂度:O(n)
* 稳定性:不稳定
* 排序方式:In-place
*/
public static int[] bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) { // 外层比较次数为n-i
boolean flag = true; // 做优化,如果上一次没有交换,说明已经有序,直接跳出
for (int j = 0; j < n - i; j++) { // 内层次数为n-i
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}
/**
* 选择排序 无论如何时间复杂度都是O(n^2)
* 稳定性:不稳定
* 排序方式:In-place
*/
public static int[] selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
/**
* 插入排序
* 最坏:O(n^2)
* 最好:O(n)
* 稳定性:稳定
* 排序方式:In-place
*/
public static int[] insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int preIndex = i - 1;
int current = arr[i];
while (preIndex >= 0 && current < arr[preIndex]) { // 当前值小于上一个值时 将上一个值往后移
arr[preIndex + 1] = arr[preIndex];
preIndex -= 1;
}
arr[preIndex + 1] = current;
}
return arr;
}
public static int[] mergeSort2(int[] arr) {
if (arr.length <= 1) {
return arr;
}
int[] aux = new int[arr.length]; // 辅助数组 防止频繁创建数组
mergeSort(arr, 0, arr.length - 1, aux);
return arr;
}
private static void mergeSort(int[] arr, int low, int high, int[] aux) {
if (low >= high) {
return;
}
int middle = (low + high) / 2;
mergeSort(arr, low, middle, aux); // 左半部分归并排序
mergeSort(arr, middle + 1, high, aux); // 右半部分归并排序
merge(arr, low, middle, high, aux); // 归并 <SUF>
}
private static void merge(int[] arr, int low, int middle, int high, int[] aux) {
// 将arr[low...middle]和arr[middle+1...high]两部分归并到aux数组中
for (int i = low; i <= high; i++) {
aux[i] = arr[i];
}
int i = low; // 左半部分起始索引
int j = middle + 1; // 右半部分起始索引
int k = low; // 归并后数组的起始索引
// 归并排序
while (i <= middle && j <= high) {
if (aux[i] <= aux[j]) {
arr[k++] = aux[i++];
} else {
arr[k++] = aux[j++];
}
}
// 处理剩余的元素
while (i <= middle) {
arr[k++] = aux[i++];
}
while (j <= high) {
arr[k++] = aux[j++];
}
}
/**
* 归并排序
* 采用分治的思想
*/
public static int[] mergeSort(int[] arr) {
if (arr.length <= 1) { // 边界条件
return arr;
}
int middle = arr.length / 2;
int[] arr_1 = Arrays.copyOfRange(arr, 0, middle);
int[] arr_2 = Arrays.copyOfRange(arr, middle, arr.length);
return merge(mergeSort(arr_1), mergeSort(arr_2));
}
/**
* Merge two sorted arrays
* 合并两个有序数组
*/
public static int[] merge(int[] arr_1, int[] arr_2) {
int[] sorted_arr = new int[arr_1.length + arr_2.length];
int idx = 0, idx_1 = 0, idx_2 = 0;
while (idx_1 < arr_1.length && idx_2 < arr_2.length) {
if (arr_1[idx_1] < arr_2[idx_2]) {
sorted_arr[idx] = arr_1[idx_1];
idx_1 += 1;
} else {
sorted_arr[idx] = arr_2[idx_2];
idx_2 += 1;
}
idx += 1;
}
// 处理剩余的元素
if (idx_1 < arr_1.length) {
while (idx_1 < arr_1.length) {
sorted_arr[idx] = arr_1[idx_1];
idx_1 += 1;
idx += 1;
}
} else {
while (idx_2 < arr_2.length) {
sorted_arr[idx] = arr_2[idx_2];
idx_2 += 1;
idx += 1;
}
}
return sorted_arr;
}
/**
* 对给定的数组进行分区操作,使得所有小于等于基准元素的值位于基准元素的左侧,所有大于基准元素的值位于基准元素的右侧。
*
* @param array 待分区的数组
* @param low 分区的起始索引
* @param high 分区的结束索引(包含)
* @return 基准元素最终位置的索引
*/
public static int partition(int[] array, int low, int high) {
int pivot = array[high]; // 选择最后一个元素作为基准元素
int pointer = low;
// 遍历数组,将所有小于等于基准元素的值放到基准元素的左侧
for (int i = low; i < high; i++) {
if (array[i] <= pivot) {
// 交换当前元素和指针所指元素,逐步将指针向右移动
int temp = array[i];
array[i] = array[pointer];
array[pointer] = temp;
pointer++;
}
// 打印每次交换后的数组状态
// System.out.println(Arrays.toString(array));
}
// 将基准元素放置到正确的位置上 即所有比其小的在其左边 用pointer表示有多少个元素在左边
int temp = array[pointer];
array[pointer] = pivot;
array[high] = temp;
// 返回基准元素的最终位置
return pointer;
}
/**
* 快速排序算法。
* 该算法通过不断划分序列,将待排序数组分为较小的子序列,然后递归地对这些子序列进行排序。
* 划分策略是选择一个基准元素,将小于基准元素的放在基准的左边,大于基准的放在基准的右边,基准元素的位置即为划分后两部分的分界点。
* 这个过程从数组的头部和尾部开始,逐步缩小范围,直到整个数组排序完成。
*
* @param array 待排序的整型数组。
* @param low 排序范围的起始下标。
* @param high 排序范围的终止下标。
*/
public static void quickSort(int[] array, int low, int high) {
// 如果起始下标小于终止下标,即待排序部分不为空,则进行排序
if (low < high) {
// 找到划分位置,使得划分后的两部分满足左边元素均小于右边元素
int position = partition(array, low, high);
// 递归排序基准的左边部分
quickSort(array, low, position - 1);
// 递归排序基准的右边部分
quickSort(array, position + 1, high);
}
}
/**
* Gets the maximum and minimum values in the array
*
* @param arr
* @return
*/
private static int[] getMinAndMax(int[] arr) {
int maxValue = arr[0];
int minValue = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > maxValue) {
maxValue = arr[i];
} else if (arr[i] < minValue) {
minValue = arr[i];
}
}
return new int[]{minValue, maxValue};
}
/**
* Counting Sort 计数排序
* 一种基于计数的排序算法,只能用于整数排序且范围有限。
*
* @param arr 待排序的整数数组
* @return 排序后的整数数组
*/
public static int[] countingSort(int[] arr) {
// 如果数组长度小于2,则无需排序,直接返回
if (arr.length < 2) {
return arr;
}
// 获取数组中的最小值和最大值
int[] extremum = getMinAndMax(arr);
int minValue = extremum[0];
int maxValue = extremum[1];
// 创建计数数组,长度为最大值和最小值之差加1
int[] countArr = new int[maxValue - minValue + 1];
// 遍历原数组,统计每个元素出现的次数
for (int j : arr) {
countArr[j - minValue] += 1;
}
// 计算累加和,以便确定每个元素在排序后数组中的位置
for (int i = 1; i < countArr.length; i++) {
countArr[i] += countArr[i - 1];
}
/*
* 1. 从后往前遍历原数组,将每个元素放置在正确的位置上
* 2. 遍历计数数组,将每个元素放置在正确的位置上
* 3. 从前往后遍历原数组,将每个元素放置在正确的位置上
*/
int[] result = new int[arr.length];
// 根据计数数组,将元素放置在正确的位置上
for (int i = arr.length - 1; i >= 0; i--) {
int idx = countArr[arr[i] - minValue] - 1;
result[idx] = arr[i];
// 更新计数数组 重复数 表示处理了一个了
countArr[arr[i] - minValue] -= 1;
}
return result;
}
}
| 0 |
56073_49 | /**
* This file is part of Chinese Workshop
* (https://github.com/574448121/ChineseWorkshop)
*
* Chinese Workshop is an Open-Source project under MIT License
* (https://opensource.org/licenses/MIT)
*/
package cityofskytcd.chineseworkshop.item;
import cityofskytcd.chineseworkshop.CW;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;
@GameRegistry.ObjectHolder(CW.MODID)
public class CWItems
{
/* 图标 */
@GameRegistry.ObjectHolder("logo")
public static final Item LOGO = null;
/* 材料 */
@GameRegistry.ObjectHolder("material")
public static final Item MATERIAL = null;
/* 门 */
// 中式木门
@GameRegistry.ObjectHolder("door")
public static final Item DOOR = null;
// 中式大木门
@GameRegistry.ObjectHolder("high_door")
public static final Item HIGH_DOOR = null;
// 木窗门
@GameRegistry.ObjectHolder("wooden_window_door")
public static final Item WOODEN_WINDOW_DOOR = null;
// 窗门
@GameRegistry.ObjectHolder("window_door")
public static final Item WINDOW_DOOR = null;
// 中式木门
@GameRegistry.ObjectHolder("chinese_oak_door")
public static final Item CHINESE_OAK_DOOR = null;
// 染色红木板窗门
@GameRegistry.ObjectHolder("red_stained_wooden_planks_wooden_window_door")
public static final Item RED_STAINED_WOODEN_PLANKS_WOODEN_WINDOW_DOOR = null;
/* 方块 */
// 黑砖墙
@GameRegistry.ObjectHolder("black_brick_wall")
public static final Item BLACK_BRICK_WALL = null;
// 黑粘土块
@GameRegistry.ObjectHolder("black_clay_block")
public static final Item BLACK_CLAY_BLOCK = null;
// 安山岩路面
@GameRegistry.ObjectHolder("andesite_pavement")
public static final Item ANDESITE_PAVEMENT = null;
// 红柱
@GameRegistry.ObjectHolder("red_pillar")
public static final Item RED_PILLAR = null;
// 绿柱
@GameRegistry.ObjectHolder("dark_green_pillar")
public static final Item DARK_GREEN_PILLAR = null;
// 白灰墙
@GameRegistry.ObjectHolder("white_gray_wall")
public static final Item WHITE_GRAY_WALL = null;
// 福
@GameRegistry.ObjectHolder("fu")
public static final Item FU = null;
// 夯土
@GameRegistry.ObjectHolder("rammed_earth")
public static final Item RAMMED_EARTH = null;
// 胭脂砖
@GameRegistry.ObjectHolder("rouge_brick")
public static final Item ROUGE_BRICK = null;
// 染色红木板
@GameRegistry.ObjectHolder("red_stained_wooden_planks")
public static final Item RED_STAINED_WOODEN_PLANKS = null;
// 建筑彩绘
@GameRegistry.ObjectHolder("architectural_painting")
public static final Item ARCHITECTURAL_PAINTING = null;
/* 灯 */
// 石灯塔
@GameRegistry.ObjectHolder("stone_tower_lamp")
public static final Item STONE_TOWER_LAMP = null;
// 灯笼
@GameRegistry.ObjectHolder("red_lantern")
public static final Item RED_LANTERN = null;
// 蜡烛
@GameRegistry.ObjectHolder("candle")
public static final Item CANDLE = null;
// 白灯笼
@GameRegistry.ObjectHolder("white_lantern")
public static final Item WHITE_LANTERN = null;
// 宫灯
@GameRegistry.ObjectHolder("palace_lantern")
public static final Item PALACE_LANTERN = null;
/* 装饰 */
// 斗栱
@GameRegistry.ObjectHolder("bracket_set")
public static final Item BRACKET_SET = null;
// 门墩
@GameRegistry.ObjectHolder("men_dun")
public static final Item MEN_DUN = null;
// 门槛
@GameRegistry.ObjectHolder("threshold")
public static final Item THRESHOLD = null;
// 雕饰
@GameRegistry.ObjectHolder("carving")
public static final Item CARVING = null;
// 树坛
@GameRegistry.ObjectHolder("tree_altar")
public static final Item TREE_ALTAR = null;
// 板凳
@GameRegistry.ObjectHolder("bench")
public static final Item BENCH = null;
// 桌子
@GameRegistry.ObjectHolder("table")
public static final Item TABLE = null;
// 白灰墙阶梯
@GameRegistry.ObjectHolder("white_gray_wall_stairs")
public static final Item WHITE_GRAY_WALL_STAIRS = null;
// 纸窗
@GameRegistry.ObjectHolder("paper_window")
public static final Item PAPER_WINDOW = null;
// 闪长岩栅栏
@GameRegistry.ObjectHolder("diorite_fence")
public static final Item DIORITE_FENCE = null;
// 小黑砖墙
@GameRegistry.ObjectHolder("small_black_brick_wall")
public static final Item SMALL_BLACK_BRICK_WALL = null;
// 小白灰墙
@GameRegistry.ObjectHolder("small_white_gray_wall")
public static final Item SMALL_WHITE_GRAY_WALL = null;
// 橡木中式栅栏
@GameRegistry.ObjectHolder("oak_chinese_fence")
public static final Item OAK_CHINESE_FENCE = null;
// 安山岩栅栏
@GameRegistry.ObjectHolder("andesite_fence")
public static final Item ANDESITE_FENCE = null;
// 挂落
@GameRegistry.ObjectHolder("lithel_deco")
public static final Item LITHEL_DECO = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("andesite_pavement_stairs")
public static final Item ANDESITE_PAVEMENT_STAIRS = null;
// 橡木墙
@GameRegistry.ObjectHolder("oak_wall")
public static final Item OAK_WALL = null;
// 中式木门
// @GameRegistry.ObjectHolder("door")
// public static final Item DOOR = null;
//
// @GameRegistry.ObjectHolder("high_door")
// public static final Item HIGH_DOOR = null;
// 门顶框
@GameRegistry.ObjectHolder("upper_door_frame")
public static final Item UPPER_DOOR_FRAME = null;
// 夯土墙
@GameRegistry.ObjectHolder("rammed_earth_wall")
public static final Item RAMMED_EARTH_WALL = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("rammed_earth_stairs")
public static final Item RAMMED_EARTH_STAIRS = null;
// 石窗
@GameRegistry.ObjectHolder("stone_window")
public static final Item STONE_WINDOW = null;
// 夯土墙
@GameRegistry.ObjectHolder("rouge_brick_wall")
public static final Item ROUGE_BRICK_WALL = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("rouge_brick_stairs")
public static final Item ROUGE_BRICK_STAIRS = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("black_brick_wall_stairs")
public static final Item BLACK_BRICK_WALL_STAIRS = null;
// 石窗
@GameRegistry.ObjectHolder("wooden_window")
public static final Item WOODEN_WINDOW = null;
// 木门槛
@GameRegistry.ObjectHolder("wooden_threshold")
public static final Item WOODEN_THRESHOLD = null;
// 田埂
@GameRegistry.ObjectHolder("field_ridge")
public static final Item FIELD_RIDGE = null;
// 染色红木板墙
@GameRegistry.ObjectHolder("red_stained_wooden_planks_wall")
public static final Item RED_STAINED_WOODEN_PLANKS_WALL = null;
// 染色红木板纸窗
@GameRegistry.ObjectHolder("red_stained_wooden_planks_paper_window")
public static final Item RED_STAINED_WOODEN_PLANKS_PAPER_WINDOW = null;
// 染色红木板门顶框
@GameRegistry.ObjectHolder("red_stained_wooden_planks_upper_door_frame")
public static final Item RED_STAINED_WOODEN_PLANKS_UPPER_DOOR_FRAME = null;
// 建筑彩绘
@GameRegistry.ObjectHolder("architectural_painting_wall")
public static final Item ARCHITECTURAL_PAINTING_WALL = null;
// 美人靠
@GameRegistry.ObjectHolder("mei_ren_kao")
public static final Item MEI_REN_KAO = null;
// 盆栽
@GameRegistry.ObjectHolder("potted")
public static final Item POTTED = null;
/* 屋顶 */
// 黑瓦屋顶
@GameRegistry.ObjectHolder("black_tile_roof")
public static final Item BLACK_TILE_ROOF = null;
// 黑瓦屋脊top
@GameRegistry.ObjectHolder("black_tile_ridge_roof_top")
public static final Item BLACK_TILE_RIDGE_ROOF_TOP = null;
//黑瓦屋脊边缘
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE = null;
// 黑瓦屋脊边缘top
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_top")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_TOP = null;
// 黑瓦屋脊飞檐
@GameRegistry.ObjectHolder("black_tile_ridge_roof_j")
public static final Item BLACK_TILE_RIDGE_ROOF_J = null;
// 黑瓦屋顶飞檐
@GameRegistry.ObjectHolder("black_tile_roof_j")
public static final Item BLACK_TILE_ROOF_J = null;
// 黑瓦屋顶半砖
@GameRegistry.ObjectHolder("black_tile_roof_slab")
public static final Item BLACK_TILE_ROOF_SLAB = null;
// 黑瓦屋顶半砖top
@GameRegistry.ObjectHolder("black_tile_roof_slab_top")
public static final Item BLACK_TILE_ROOF_SLAB_TOP = null;
// 黑瓦屋顶边缘-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_wb")
public static final Item BLACK_ROOF_TILE_EDGE_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_rr")
public static final Item BLACK_ROOF_TILE_EDGE_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_cw")
public static final Item BLACK_ROOF_TILE_EDGE_CW = null;
// 黑瓦屋顶边缘半砖-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_wb")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_rr")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_cw")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_CW = null;
// 黑瓦屋顶边缘上半砖-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_t_wb")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_T_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_t_rr")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_T_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_t_cw")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_T_CW = null;
// 黑瓦屋顶边缘飞檐-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_j_wb")
public static final Item BLACK_ROOF_TILE_EDGE_J_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_j_rr")
public static final Item BLACK_ROOF_TILE_EDGE_J_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_j_cw")
public static final Item BLACK_ROOF_TILE_EDGE_J_CW = null;
// 黄瓦屋顶
@GameRegistry.ObjectHolder("yellow_tile_roof")
public static final Item YELLOW_TILE_ROOF = null;
// 黄瓦屋脊
@GameRegistry.ObjectHolder("yellow_roof_tile_ridge")
public static final Item YELLOW_ROOF_TILE_RIDGE = null;
// 黄瓦屋脊top
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_top")
public static final Item YELLOW_TILE_RIDGE_ROOF_TOP = null;
// 黄瓦屋脊边缘
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_edge")
public static final Item YELLOW_TILE_RIDGE_ROOF_EDGE = null;
// 黄瓦屋脊飞檐
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_j")
public static final Item YELLOW_TILE_RIDGE_ROOF_J = null;
// 黄瓦屋顶飞檐
@GameRegistry.ObjectHolder("yellow_tile_roof_j")
public static final Item YELLOW_TILE_ROOF_J = null;
// 黄瓦屋顶半砖
@GameRegistry.ObjectHolder("yellow_tile_roof_slab")
public static final Item YELLOW_TILE_ROOF_SLAB = null;
// 黄瓦屋顶半砖top
@GameRegistry.ObjectHolder("yellow_tile_roof_slab_top")
public static final Item YELLOW_TILE_ROOF_SLAB_TOP = null;
// 黄瓦屋脊边缘top
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_edge_top")
public static final Item YELLOW_TILE_RIDGE_ROOF_EDGE_TOP = null;
// 茅草屋顶
@GameRegistry.ObjectHolder("thatch_roof")
public static final Item THATCH_ROOF = null;
// 茅草屋脊
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof")
public static final Item THATCH_TILE_RIDGE_ROOF = null;
// 茅草屋脊top
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof_top")
public static final Item THATCH_TILE_RIDGE_ROOF_TOP = null;
// 茅草屋顶半砖
@GameRegistry.ObjectHolder("thatch_tile_roof_slab")
public static final Item THATCH_TILE_ROOF_SLAB = null;
// 茅草屋顶半砖top
@GameRegistry.ObjectHolder("thatch_tile_roof_slab_top")
public static final Item THATCH_TILE_ROOF_SLAB_TOP = null;
// 茅草屋顶边缘
@GameRegistry.ObjectHolder("thatch_roof_tile_edge")
public static final Item THATCH_ROOF_TILE_EDGE = null;
// 茅草屋顶半砖边缘
@GameRegistry.ObjectHolder("thatch_roof_tile_edge_slab")
public static final Item THATCH_ROOF_TILE_EDGE_SLAB = null;
// 茅草屋脊边缘
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof_edge")
public static final Item THATCH_TILE_RIDGE_ROOF_EDGE = null;
// 茅草屋脊边缘
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof_edge_top")
public static final Item THATCH_TILE_RIDGE_ROOF_EDGE_TOP = null;
/* 薄墙 */
// 薄白灰墙
@GameRegistry.ObjectHolder("thin_white_gray_wall")
public static final Item THIN_WHITE_GRAY_WALL = null;
// 黑瓦屋脊
@GameRegistry.ObjectHolder("black_roof_tile_ridge")
public static final Item BLACK_ROOF_TILE_RIDGE = null;
// 黑瓦屋顶边缘
@GameRegistry.ObjectHolder("black_roof_tile_edge")
public static final Item BLACK_ROOF_TILE_EDGE = null;
// 黑瓦屋顶边缘台阶
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB = null;
// 黄瓦屋顶边缘
@GameRegistry.ObjectHolder("yellow_roof_tile_edge")
public static final Item YELLOW_ROOF_TILE_EDGE = null;
// 黄瓦屋顶边缘台阶
@GameRegistry.ObjectHolder("yellow_roof_tile_edge_slab")
public static final Item YELLOW_ROOF_TILE_EDGE_SLAB = null;
// 薄墙-木、黑砖、圆石、胭脂砖、夯土、白灰
@GameRegistry.ObjectHolder("thin_wall_w")
public static final Item THIN_WALL_W = null;
@GameRegistry.ObjectHolder("thin_wall_bb")
public static final Item THIN_WALL_BB = null;
@GameRegistry.ObjectHolder("thin_wall_c")
public static final Item THIN_WALL_C = null;
@GameRegistry.ObjectHolder("thin_wall_rb")
public static final Item THIN_WALL_RB = null;
@GameRegistry.ObjectHolder("thin_wall_re")
public static final Item THIN_WALL_RE = null;
@GameRegistry.ObjectHolder("thin_wall_wg")
public static final Item THIN_WALL_WG = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_w")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_W = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_bb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_BB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_c")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_C = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_rb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_RB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_re")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_RE = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_wg")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_WG = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_w")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_W = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_bb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_BB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_c")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_C = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_rb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_RB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_re")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_RE = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_wg")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_WG = null;
}
| 574448121/ChineseWorkshop | src/main/java/cityofskytcd/chineseworkshop/item/CWItems.java | 5,226 | //黑瓦屋脊边缘 | line_comment | zh-cn | /**
* This file is part of Chinese Workshop
* (https://github.com/574448121/ChineseWorkshop)
*
* Chinese Workshop is an Open-Source project under MIT License
* (https://opensource.org/licenses/MIT)
*/
package cityofskytcd.chineseworkshop.item;
import cityofskytcd.chineseworkshop.CW;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;
@GameRegistry.ObjectHolder(CW.MODID)
public class CWItems
{
/* 图标 */
@GameRegistry.ObjectHolder("logo")
public static final Item LOGO = null;
/* 材料 */
@GameRegistry.ObjectHolder("material")
public static final Item MATERIAL = null;
/* 门 */
// 中式木门
@GameRegistry.ObjectHolder("door")
public static final Item DOOR = null;
// 中式大木门
@GameRegistry.ObjectHolder("high_door")
public static final Item HIGH_DOOR = null;
// 木窗门
@GameRegistry.ObjectHolder("wooden_window_door")
public static final Item WOODEN_WINDOW_DOOR = null;
// 窗门
@GameRegistry.ObjectHolder("window_door")
public static final Item WINDOW_DOOR = null;
// 中式木门
@GameRegistry.ObjectHolder("chinese_oak_door")
public static final Item CHINESE_OAK_DOOR = null;
// 染色红木板窗门
@GameRegistry.ObjectHolder("red_stained_wooden_planks_wooden_window_door")
public static final Item RED_STAINED_WOODEN_PLANKS_WOODEN_WINDOW_DOOR = null;
/* 方块 */
// 黑砖墙
@GameRegistry.ObjectHolder("black_brick_wall")
public static final Item BLACK_BRICK_WALL = null;
// 黑粘土块
@GameRegistry.ObjectHolder("black_clay_block")
public static final Item BLACK_CLAY_BLOCK = null;
// 安山岩路面
@GameRegistry.ObjectHolder("andesite_pavement")
public static final Item ANDESITE_PAVEMENT = null;
// 红柱
@GameRegistry.ObjectHolder("red_pillar")
public static final Item RED_PILLAR = null;
// 绿柱
@GameRegistry.ObjectHolder("dark_green_pillar")
public static final Item DARK_GREEN_PILLAR = null;
// 白灰墙
@GameRegistry.ObjectHolder("white_gray_wall")
public static final Item WHITE_GRAY_WALL = null;
// 福
@GameRegistry.ObjectHolder("fu")
public static final Item FU = null;
// 夯土
@GameRegistry.ObjectHolder("rammed_earth")
public static final Item RAMMED_EARTH = null;
// 胭脂砖
@GameRegistry.ObjectHolder("rouge_brick")
public static final Item ROUGE_BRICK = null;
// 染色红木板
@GameRegistry.ObjectHolder("red_stained_wooden_planks")
public static final Item RED_STAINED_WOODEN_PLANKS = null;
// 建筑彩绘
@GameRegistry.ObjectHolder("architectural_painting")
public static final Item ARCHITECTURAL_PAINTING = null;
/* 灯 */
// 石灯塔
@GameRegistry.ObjectHolder("stone_tower_lamp")
public static final Item STONE_TOWER_LAMP = null;
// 灯笼
@GameRegistry.ObjectHolder("red_lantern")
public static final Item RED_LANTERN = null;
// 蜡烛
@GameRegistry.ObjectHolder("candle")
public static final Item CANDLE = null;
// 白灯笼
@GameRegistry.ObjectHolder("white_lantern")
public static final Item WHITE_LANTERN = null;
// 宫灯
@GameRegistry.ObjectHolder("palace_lantern")
public static final Item PALACE_LANTERN = null;
/* 装饰 */
// 斗栱
@GameRegistry.ObjectHolder("bracket_set")
public static final Item BRACKET_SET = null;
// 门墩
@GameRegistry.ObjectHolder("men_dun")
public static final Item MEN_DUN = null;
// 门槛
@GameRegistry.ObjectHolder("threshold")
public static final Item THRESHOLD = null;
// 雕饰
@GameRegistry.ObjectHolder("carving")
public static final Item CARVING = null;
// 树坛
@GameRegistry.ObjectHolder("tree_altar")
public static final Item TREE_ALTAR = null;
// 板凳
@GameRegistry.ObjectHolder("bench")
public static final Item BENCH = null;
// 桌子
@GameRegistry.ObjectHolder("table")
public static final Item TABLE = null;
// 白灰墙阶梯
@GameRegistry.ObjectHolder("white_gray_wall_stairs")
public static final Item WHITE_GRAY_WALL_STAIRS = null;
// 纸窗
@GameRegistry.ObjectHolder("paper_window")
public static final Item PAPER_WINDOW = null;
// 闪长岩栅栏
@GameRegistry.ObjectHolder("diorite_fence")
public static final Item DIORITE_FENCE = null;
// 小黑砖墙
@GameRegistry.ObjectHolder("small_black_brick_wall")
public static final Item SMALL_BLACK_BRICK_WALL = null;
// 小白灰墙
@GameRegistry.ObjectHolder("small_white_gray_wall")
public static final Item SMALL_WHITE_GRAY_WALL = null;
// 橡木中式栅栏
@GameRegistry.ObjectHolder("oak_chinese_fence")
public static final Item OAK_CHINESE_FENCE = null;
// 安山岩栅栏
@GameRegistry.ObjectHolder("andesite_fence")
public static final Item ANDESITE_FENCE = null;
// 挂落
@GameRegistry.ObjectHolder("lithel_deco")
public static final Item LITHEL_DECO = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("andesite_pavement_stairs")
public static final Item ANDESITE_PAVEMENT_STAIRS = null;
// 橡木墙
@GameRegistry.ObjectHolder("oak_wall")
public static final Item OAK_WALL = null;
// 中式木门
// @GameRegistry.ObjectHolder("door")
// public static final Item DOOR = null;
//
// @GameRegistry.ObjectHolder("high_door")
// public static final Item HIGH_DOOR = null;
// 门顶框
@GameRegistry.ObjectHolder("upper_door_frame")
public static final Item UPPER_DOOR_FRAME = null;
// 夯土墙
@GameRegistry.ObjectHolder("rammed_earth_wall")
public static final Item RAMMED_EARTH_WALL = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("rammed_earth_stairs")
public static final Item RAMMED_EARTH_STAIRS = null;
// 石窗
@GameRegistry.ObjectHolder("stone_window")
public static final Item STONE_WINDOW = null;
// 夯土墙
@GameRegistry.ObjectHolder("rouge_brick_wall")
public static final Item ROUGE_BRICK_WALL = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("rouge_brick_stairs")
public static final Item ROUGE_BRICK_STAIRS = null;
// 安山岩路面阶梯
@GameRegistry.ObjectHolder("black_brick_wall_stairs")
public static final Item BLACK_BRICK_WALL_STAIRS = null;
// 石窗
@GameRegistry.ObjectHolder("wooden_window")
public static final Item WOODEN_WINDOW = null;
// 木门槛
@GameRegistry.ObjectHolder("wooden_threshold")
public static final Item WOODEN_THRESHOLD = null;
// 田埂
@GameRegistry.ObjectHolder("field_ridge")
public static final Item FIELD_RIDGE = null;
// 染色红木板墙
@GameRegistry.ObjectHolder("red_stained_wooden_planks_wall")
public static final Item RED_STAINED_WOODEN_PLANKS_WALL = null;
// 染色红木板纸窗
@GameRegistry.ObjectHolder("red_stained_wooden_planks_paper_window")
public static final Item RED_STAINED_WOODEN_PLANKS_PAPER_WINDOW = null;
// 染色红木板门顶框
@GameRegistry.ObjectHolder("red_stained_wooden_planks_upper_door_frame")
public static final Item RED_STAINED_WOODEN_PLANKS_UPPER_DOOR_FRAME = null;
// 建筑彩绘
@GameRegistry.ObjectHolder("architectural_painting_wall")
public static final Item ARCHITECTURAL_PAINTING_WALL = null;
// 美人靠
@GameRegistry.ObjectHolder("mei_ren_kao")
public static final Item MEI_REN_KAO = null;
// 盆栽
@GameRegistry.ObjectHolder("potted")
public static final Item POTTED = null;
/* 屋顶 */
// 黑瓦屋顶
@GameRegistry.ObjectHolder("black_tile_roof")
public static final Item BLACK_TILE_ROOF = null;
// 黑瓦屋脊top
@GameRegistry.ObjectHolder("black_tile_ridge_roof_top")
public static final Item BLACK_TILE_RIDGE_ROOF_TOP = null;
//黑瓦 <SUF>
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE = null;
// 黑瓦屋脊边缘top
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_top")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_TOP = null;
// 黑瓦屋脊飞檐
@GameRegistry.ObjectHolder("black_tile_ridge_roof_j")
public static final Item BLACK_TILE_RIDGE_ROOF_J = null;
// 黑瓦屋顶飞檐
@GameRegistry.ObjectHolder("black_tile_roof_j")
public static final Item BLACK_TILE_ROOF_J = null;
// 黑瓦屋顶半砖
@GameRegistry.ObjectHolder("black_tile_roof_slab")
public static final Item BLACK_TILE_ROOF_SLAB = null;
// 黑瓦屋顶半砖top
@GameRegistry.ObjectHolder("black_tile_roof_slab_top")
public static final Item BLACK_TILE_ROOF_SLAB_TOP = null;
// 黑瓦屋顶边缘-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_wb")
public static final Item BLACK_ROOF_TILE_EDGE_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_rr")
public static final Item BLACK_ROOF_TILE_EDGE_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_cw")
public static final Item BLACK_ROOF_TILE_EDGE_CW = null;
// 黑瓦屋顶边缘半砖-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_wb")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_rr")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_cw")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_CW = null;
// 黑瓦屋顶边缘上半砖-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_t_wb")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_T_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_t_rr")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_T_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab_t_cw")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB_T_CW = null;
// 黑瓦屋顶边缘飞檐-木和黑砖、夯土和胭脂、圆石和白灰
@GameRegistry.ObjectHolder("black_roof_tile_edge_j_wb")
public static final Item BLACK_ROOF_TILE_EDGE_J_WB = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_j_rr")
public static final Item BLACK_ROOF_TILE_EDGE_J_RR = null;
@GameRegistry.ObjectHolder("black_roof_tile_edge_j_cw")
public static final Item BLACK_ROOF_TILE_EDGE_J_CW = null;
// 黄瓦屋顶
@GameRegistry.ObjectHolder("yellow_tile_roof")
public static final Item YELLOW_TILE_ROOF = null;
// 黄瓦屋脊
@GameRegistry.ObjectHolder("yellow_roof_tile_ridge")
public static final Item YELLOW_ROOF_TILE_RIDGE = null;
// 黄瓦屋脊top
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_top")
public static final Item YELLOW_TILE_RIDGE_ROOF_TOP = null;
// 黄瓦屋脊边缘
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_edge")
public static final Item YELLOW_TILE_RIDGE_ROOF_EDGE = null;
// 黄瓦屋脊飞檐
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_j")
public static final Item YELLOW_TILE_RIDGE_ROOF_J = null;
// 黄瓦屋顶飞檐
@GameRegistry.ObjectHolder("yellow_tile_roof_j")
public static final Item YELLOW_TILE_ROOF_J = null;
// 黄瓦屋顶半砖
@GameRegistry.ObjectHolder("yellow_tile_roof_slab")
public static final Item YELLOW_TILE_ROOF_SLAB = null;
// 黄瓦屋顶半砖top
@GameRegistry.ObjectHolder("yellow_tile_roof_slab_top")
public static final Item YELLOW_TILE_ROOF_SLAB_TOP = null;
// 黄瓦屋脊边缘top
@GameRegistry.ObjectHolder("yellow_tile_ridge_roof_edge_top")
public static final Item YELLOW_TILE_RIDGE_ROOF_EDGE_TOP = null;
// 茅草屋顶
@GameRegistry.ObjectHolder("thatch_roof")
public static final Item THATCH_ROOF = null;
// 茅草屋脊
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof")
public static final Item THATCH_TILE_RIDGE_ROOF = null;
// 茅草屋脊top
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof_top")
public static final Item THATCH_TILE_RIDGE_ROOF_TOP = null;
// 茅草屋顶半砖
@GameRegistry.ObjectHolder("thatch_tile_roof_slab")
public static final Item THATCH_TILE_ROOF_SLAB = null;
// 茅草屋顶半砖top
@GameRegistry.ObjectHolder("thatch_tile_roof_slab_top")
public static final Item THATCH_TILE_ROOF_SLAB_TOP = null;
// 茅草屋顶边缘
@GameRegistry.ObjectHolder("thatch_roof_tile_edge")
public static final Item THATCH_ROOF_TILE_EDGE = null;
// 茅草屋顶半砖边缘
@GameRegistry.ObjectHolder("thatch_roof_tile_edge_slab")
public static final Item THATCH_ROOF_TILE_EDGE_SLAB = null;
// 茅草屋脊边缘
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof_edge")
public static final Item THATCH_TILE_RIDGE_ROOF_EDGE = null;
// 茅草屋脊边缘
@GameRegistry.ObjectHolder("thatch_tile_ridge_roof_edge_top")
public static final Item THATCH_TILE_RIDGE_ROOF_EDGE_TOP = null;
/* 薄墙 */
// 薄白灰墙
@GameRegistry.ObjectHolder("thin_white_gray_wall")
public static final Item THIN_WHITE_GRAY_WALL = null;
// 黑瓦屋脊
@GameRegistry.ObjectHolder("black_roof_tile_ridge")
public static final Item BLACK_ROOF_TILE_RIDGE = null;
// 黑瓦屋顶边缘
@GameRegistry.ObjectHolder("black_roof_tile_edge")
public static final Item BLACK_ROOF_TILE_EDGE = null;
// 黑瓦屋顶边缘台阶
@GameRegistry.ObjectHolder("black_roof_tile_edge_slab")
public static final Item BLACK_ROOF_TILE_EDGE_SLAB = null;
// 黄瓦屋顶边缘
@GameRegistry.ObjectHolder("yellow_roof_tile_edge")
public static final Item YELLOW_ROOF_TILE_EDGE = null;
// 黄瓦屋顶边缘台阶
@GameRegistry.ObjectHolder("yellow_roof_tile_edge_slab")
public static final Item YELLOW_ROOF_TILE_EDGE_SLAB = null;
// 薄墙-木、黑砖、圆石、胭脂砖、夯土、白灰
@GameRegistry.ObjectHolder("thin_wall_w")
public static final Item THIN_WALL_W = null;
@GameRegistry.ObjectHolder("thin_wall_bb")
public static final Item THIN_WALL_BB = null;
@GameRegistry.ObjectHolder("thin_wall_c")
public static final Item THIN_WALL_C = null;
@GameRegistry.ObjectHolder("thin_wall_rb")
public static final Item THIN_WALL_RB = null;
@GameRegistry.ObjectHolder("thin_wall_re")
public static final Item THIN_WALL_RE = null;
@GameRegistry.ObjectHolder("thin_wall_wg")
public static final Item THIN_WALL_WG = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_w")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_W = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_bb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_BB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_c")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_C = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_rb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_RB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_re")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_RE = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_wg")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_WG = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_w")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_W = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_bb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_BB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_c")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_C = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_rb")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_RB = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_re")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_RE = null;
@GameRegistry.ObjectHolder("black_tile_ridge_roof_edge_t_wg")
public static final Item BLACK_TILE_RIDGE_ROOF_EDGE_T_WG = null;
}
| 1 |
11417_4 | package com.bj58.argo.utils;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassUtils {
private ClassUtils() {}
/**
* 从包package中获取所有的Class
*
* @param pack 包名
* @return
*/
public static Set<Class<?>> getClasses(String pack) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(
packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath,
recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
System.err.println("jar类型的扫描");
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx)
.replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) | recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class")
&& !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(
packageName.length() + 1, name
.length() - 6);
try {
// 添加到classes
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
// log
// .error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
// log.error("在扫描用户定义视图时从jar包获取文件出错");
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
private static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "."
+ file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
//classes.add(Class.forName(packageName + '.' + className));
//经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
/**
* 得到方法参数名称数组
* 由于java没有提供获得参数名称的api,利用了javassist来实现
*
* @return 参数名称数组
*/
public static String[] getMethodParamNames(Class<?> clazz, Method method) {
Class<?>[] paramTypes = method.getParameterTypes();
try {
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(clazz));
CtClass cc = pool.get(clazz.getName());
String[] paramTypeNames = new String[method.getParameterTypes().length];
for (int i = 0; i < paramTypes.length; i++)
paramTypeNames[i] = paramTypes[i].getName();
CtMethod cm = cc.getDeclaredMethod(method.getName(), pool.get(paramTypeNames));
// 使用javaassist的反射方法获取方法的参数名
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
throw new RuntimeException("class:" + clazz.getName()
+ ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file");
}
int startIndex = getStartIndex(attr);
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++)
paramNames[i] = attr.variableName(startIndex + i + pos);
return paramNames;
} catch (NotFoundException e) {
e.printStackTrace();
return new String[0];
}
}
private static int getStartIndex(LocalVariableAttribute attr) {
int startIndex = 0;
for (int i = 0; i < attr.length(); i++) {
if ("this".equals(attr.variableName(i))) {
startIndex = i;
break;
}
}
return startIndex;
}
}
| 58code/Argo | core/src/main/java/com/bj58/argo/utils/ClassUtils.java | 1,911 | // 定义一个枚举的集合 并进行循环来处理这个目录下的things
| line_comment | zh-cn | package com.bj58.argo.utils;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassUtils {
private ClassUtils() {}
/**
* 从包package中获取所有的Class
*
* @param pack 包名
* @return
*/
public static Set<Class<?>> getClasses(String pack) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义 <SUF>
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(
packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath,
recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
System.err.println("jar类型的扫描");
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx)
.replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) | recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class")
&& !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(
packageName.length() + 1, name
.length() - 6);
try {
// 添加到classes
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
// log
// .error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
// log.error("在扫描用户定义视图时从jar包获取文件出错");
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
private static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "."
+ file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
//classes.add(Class.forName(packageName + '.' + className));
//经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
/**
* 得到方法参数名称数组
* 由于java没有提供获得参数名称的api,利用了javassist来实现
*
* @return 参数名称数组
*/
public static String[] getMethodParamNames(Class<?> clazz, Method method) {
Class<?>[] paramTypes = method.getParameterTypes();
try {
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(clazz));
CtClass cc = pool.get(clazz.getName());
String[] paramTypeNames = new String[method.getParameterTypes().length];
for (int i = 0; i < paramTypes.length; i++)
paramTypeNames[i] = paramTypes[i].getName();
CtMethod cm = cc.getDeclaredMethod(method.getName(), pool.get(paramTypeNames));
// 使用javaassist的反射方法获取方法的参数名
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
throw new RuntimeException("class:" + clazz.getName()
+ ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file");
}
int startIndex = getStartIndex(attr);
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++)
paramNames[i] = attr.variableName(startIndex + i + pos);
return paramNames;
} catch (NotFoundException e) {
e.printStackTrace();
return new String[0];
}
}
private static int getStartIndex(LocalVariableAttribute attr) {
int startIndex = 0;
for (int i = 0; i < attr.length(); i++) {
if ("this".equals(attr.variableName(i))) {
startIndex = i;
break;
}
}
return startIndex;
}
}
| 0 |
61452_0 | package com.lintcode;
/**
* 1. A + B 问题
* 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。
*
* 挑战:显然你可以直接 return a + b,但是你是否可以挑战一下不这样做?
*/
public class Solution1 {
/**
* @param a: An integer
* @param b: An integer
* @return: The sum of a and b
*/
public int aplusb(int a, int b) {
// write your code here
if (a == 0) {
return b;
}
if (b == 0){
return a;
}
int c = a ^ b;
int d = (a & b)<<1;
return aplusb(c, d);
}
}
| 5zhu/algorithm-learning | src/com/lintcode/Solution1.java | 202 | /**
* 1. A + B 问题
* 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。
*
* 挑战:显然你可以直接 return a + b,但是你是否可以挑战一下不这样做?
*/ | block_comment | zh-cn | package com.lintcode;
/**
* 1. <SUF>*/
public class Solution1 {
/**
* @param a: An integer
* @param b: An integer
* @return: The sum of a and b
*/
public int aplusb(int a, int b) {
// write your code here
if (a == 0) {
return b;
}
if (b == 0){
return a;
}
int c = a ^ b;
int d = (a & b)<<1;
return aplusb(c, d);
}
}
| 1 |
17087_21 | package com.example.administrator.wechat.Comfig;
/**
* Created by Administrator on 2017-7-16.
*/
import android.os.Environment;
import java.io.File;
public class BmobConfig {
/**
* 当前SDK版本号
*/
public static final String SDK_VERSION="1.1.9";
/**
* 每个人的好友查询个数上限
*/
public static int LIMIT_CONTACTS = 100;
/**
* 录音文件存储目录
*/
public static final String BMOB_VOICE_DIR =Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator+"BmobChat"+File.separator+"voice";
/**
* 消息类型:目前暂支持文本(包含表情)的发送
*/
public static final int TYPE_TEXT=1;
/**
* 消息类型:图片
*/
public static final int TYPE_IMAGE=2;
/**
* 消息类型:位置
*/
public static final int TYPE_LOCATION=3;
/**
* 消息类型:声音
*/
public static final int TYPE_VOICE=4;
/**
* 消息是否未读:未读
*/
public static final int STATE_UNREAD=0;
/**
* 消息是否未读:已读
*/
public static final int STATE_READED=1;
/**
* 消息是否未读:未读但已收到
*/
public static final int STATE_UNREAD_RECEIVED=2;
/**
* 消息发送状态:消息开始发送-
*/
public static final int STATUS_SEND_START=0;
/**
* 消息发送状态:成功
*/
public static final int STATUS_SEND_SUCCESS=1;
/**
* 消息发送状态:失败
*/
public static final int STATUS_SEND_FAIL=2;
/**
* 消息发送状态:发送接收到
*/
public static final int STATUS_SEND_RECEIVERED=3;
/**
* 好友邀请状态:发送添加好友请求时候的状态是未验证--等同于
*/
public static final int INVITE_ADD_NO_VALIDATION=0;//
/**
* 好友邀请状态:对方同意添加好友
*/
public static final int INVITE_ADD_AGREE=1;//
/**
* 好友邀请状态:收到对方的好友请求,但未处理
*/
public static final int INVITE_ADD_NO_VALI_RECEIVED = 2;
/**
* 标签消息种类:添加好友
*/
public static final String TAG_ADD_CONTACT="add";//添加好友
/**
* 标签消息种类:同意添加好友
*/
public static final String TAG_ADD_AGREE="agree";//
/**
* 标签消息种类:已读
*/
public static final String TAG_READED="readed";//
/**
* 标签消息种类:下线
*/
public static final String TAG_OFFLINE="offline";//
/**
* 本地已存在
*/
public static final int CODE_COMMON_EXISTED=1002;//
/**
* 是黑名单用户
*/
public static final String BLACK_YES = "y";
/**
* 不是黑名单用户
*/
public static final String BLACK_NO = "n";
/**
* Tag消息
*/
public static final String BROADCAST_NEW_MESSAGE="cn.bmob.new_msg";
/**
* 标签消息
*/
public static final String BROADCAST_ADD_USER_MESSAGE="cn.bmob.add_user_msg";
/**
* 查询成功,无数据返回
*/
public static final int CODE_COMMON_NONE=1000;//响应成功,无返回值
/**
* 查询失败
*/
public static final int CODE_COMMON_FAILURE=1001;//响应出错
public static final int CODE_USER_NULL=1003;//用户为空
public static final int CODE_USERNAME_NULL=1004;//用户名为空
public static final int CODE_PASSWORD_NULL=1005;//密码为空
public static final int CODE_NETWORK_ERROR=1006;//无网络
}
| 600849155/Wechat | comfig/BmobConfig.java | 998 | /**
* 标签消息种类:已读
*/ | block_comment | zh-cn | package com.example.administrator.wechat.Comfig;
/**
* Created by Administrator on 2017-7-16.
*/
import android.os.Environment;
import java.io.File;
public class BmobConfig {
/**
* 当前SDK版本号
*/
public static final String SDK_VERSION="1.1.9";
/**
* 每个人的好友查询个数上限
*/
public static int LIMIT_CONTACTS = 100;
/**
* 录音文件存储目录
*/
public static final String BMOB_VOICE_DIR =Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator+"BmobChat"+File.separator+"voice";
/**
* 消息类型:目前暂支持文本(包含表情)的发送
*/
public static final int TYPE_TEXT=1;
/**
* 消息类型:图片
*/
public static final int TYPE_IMAGE=2;
/**
* 消息类型:位置
*/
public static final int TYPE_LOCATION=3;
/**
* 消息类型:声音
*/
public static final int TYPE_VOICE=4;
/**
* 消息是否未读:未读
*/
public static final int STATE_UNREAD=0;
/**
* 消息是否未读:已读
*/
public static final int STATE_READED=1;
/**
* 消息是否未读:未读但已收到
*/
public static final int STATE_UNREAD_RECEIVED=2;
/**
* 消息发送状态:消息开始发送-
*/
public static final int STATUS_SEND_START=0;
/**
* 消息发送状态:成功
*/
public static final int STATUS_SEND_SUCCESS=1;
/**
* 消息发送状态:失败
*/
public static final int STATUS_SEND_FAIL=2;
/**
* 消息发送状态:发送接收到
*/
public static final int STATUS_SEND_RECEIVERED=3;
/**
* 好友邀请状态:发送添加好友请求时候的状态是未验证--等同于
*/
public static final int INVITE_ADD_NO_VALIDATION=0;//
/**
* 好友邀请状态:对方同意添加好友
*/
public static final int INVITE_ADD_AGREE=1;//
/**
* 好友邀请状态:收到对方的好友请求,但未处理
*/
public static final int INVITE_ADD_NO_VALI_RECEIVED = 2;
/**
* 标签消息种类:添加好友
*/
public static final String TAG_ADD_CONTACT="add";//添加好友
/**
* 标签消息种类:同意添加好友
*/
public static final String TAG_ADD_AGREE="agree";//
/**
* 标签消 <SUF>*/
public static final String TAG_READED="readed";//
/**
* 标签消息种类:下线
*/
public static final String TAG_OFFLINE="offline";//
/**
* 本地已存在
*/
public static final int CODE_COMMON_EXISTED=1002;//
/**
* 是黑名单用户
*/
public static final String BLACK_YES = "y";
/**
* 不是黑名单用户
*/
public static final String BLACK_NO = "n";
/**
* Tag消息
*/
public static final String BROADCAST_NEW_MESSAGE="cn.bmob.new_msg";
/**
* 标签消息
*/
public static final String BROADCAST_ADD_USER_MESSAGE="cn.bmob.add_user_msg";
/**
* 查询成功,无数据返回
*/
public static final int CODE_COMMON_NONE=1000;//响应成功,无返回值
/**
* 查询失败
*/
public static final int CODE_COMMON_FAILURE=1001;//响应出错
public static final int CODE_USER_NULL=1003;//用户为空
public static final int CODE_USERNAME_NULL=1004;//用户名为空
public static final int CODE_PASSWORD_NULL=1005;//密码为空
public static final int CODE_NETWORK_ERROR=1006;//无网络
}
| 0 |
57844_2 | /**
* java生成线程的四种方式
* 继承Thread类
* 实现Runnable接口
* 使用Executor框架来创建线程池
* 实现Callable接口
*/
public class thread1 {
/**
* 模拟龟兔赛跑
* 1、创建多线程(方式一):继承 CreateThread + 重写run方法(线程体)
* 2、使用线程:创建子类对象 + 对象.start()方法 线程启动
* 启动:创建子类对象+对象.start()
* 缺点:Java只支持单继承,如果我们的类已经从一个类继承,则无法再继承Thread类。
*/
public static void main(String[] args) {
//创建子类对象
Rabbit rab = new Rabbit();
Tortoise tor = new Tortoise();
//调用start方法 ,启动线程。 内部由CPU管控
rab.start(); //不要调用run方法,由内部自己调用。
tor.start();
for (int i = 0; i < 30; i++) {
System.out.println("main-->" + i);
}
}
}
class Rabbit extends Thread {
//线程体 一切从run开始
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("兔子跑了" + i + "步");
}
}
}
class Tortoise extends Thread {
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("乌龟跑了" + i + "步");
}
}
}
| 600849155/thread | src/thread1.java | 405 | //创建子类对象 | line_comment | zh-cn | /**
* java生成线程的四种方式
* 继承Thread类
* 实现Runnable接口
* 使用Executor框架来创建线程池
* 实现Callable接口
*/
public class thread1 {
/**
* 模拟龟兔赛跑
* 1、创建多线程(方式一):继承 CreateThread + 重写run方法(线程体)
* 2、使用线程:创建子类对象 + 对象.start()方法 线程启动
* 启动:创建子类对象+对象.start()
* 缺点:Java只支持单继承,如果我们的类已经从一个类继承,则无法再继承Thread类。
*/
public static void main(String[] args) {
//创建 <SUF>
Rabbit rab = new Rabbit();
Tortoise tor = new Tortoise();
//调用start方法 ,启动线程。 内部由CPU管控
rab.start(); //不要调用run方法,由内部自己调用。
tor.start();
for (int i = 0; i < 30; i++) {
System.out.println("main-->" + i);
}
}
}
class Rabbit extends Thread {
//线程体 一切从run开始
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("兔子跑了" + i + "步");
}
}
}
class Tortoise extends Thread {
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("乌龟跑了" + i + "步");
}
}
}
| 0 |
61956_1 | package com.xiaoazhai.easywechat.enums;
/**
* @author zhai
* @date 2020年5月6日20:32:40
* 语言枚举
*/
public enum LanguageEnum {
//语言默认采用枚举具体释义如下
// 1、简体中文 "zh_CN"
zh_CN,
// 2、繁体中文TW "zh_TW"
zh_TW,
// 3、繁体中文HK "zh_HK"
zh_HK,
// 4、英文 "en"
en,
// 5、印尼 "id"
id,
// 6、马来 "ms"
ms,
// 7、西班牙 "es"
es,
// 8、韩国 "ko"
ko,
// 9、意大利 "it"
it,
// 10、日本 "ja"
ja,
// 11、波兰 "pl"
pl,
// 12、葡萄牙 "pt"
pt,
// 13、俄国 "ru"
ru,
// 14、泰文 "th"
th,
// 15、越南 "vi"
vi,
// 16、阿拉伯语 "ar"
ar,
// 17、北印度 "hi"
hi,
// 18、希伯来 "he"
he,
// 19、土耳其 "tr"
tr,
// 20、德语 "de"
de,
// 21、法语 "fr"
fr,
}
| 602122993/easywechat | src/main/java/com/xiaoazhai/easywechat/enums/LanguageEnum.java | 393 | //语言默认采用枚举具体释义如下 | line_comment | zh-cn | package com.xiaoazhai.easywechat.enums;
/**
* @author zhai
* @date 2020年5月6日20:32:40
* 语言枚举
*/
public enum LanguageEnum {
//语言 <SUF>
// 1、简体中文 "zh_CN"
zh_CN,
// 2、繁体中文TW "zh_TW"
zh_TW,
// 3、繁体中文HK "zh_HK"
zh_HK,
// 4、英文 "en"
en,
// 5、印尼 "id"
id,
// 6、马来 "ms"
ms,
// 7、西班牙 "es"
es,
// 8、韩国 "ko"
ko,
// 9、意大利 "it"
it,
// 10、日本 "ja"
ja,
// 11、波兰 "pl"
pl,
// 12、葡萄牙 "pt"
pt,
// 13、俄国 "ru"
ru,
// 14、泰文 "th"
th,
// 15、越南 "vi"
vi,
// 16、阿拉伯语 "ar"
ar,
// 17、北印度 "hi"
hi,
// 18、希伯来 "he"
he,
// 19、土耳其 "tr"
tr,
// 20、德语 "de"
de,
// 21、法语 "fr"
fr,
}
| 0 |
51513_6 | package utils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
//import com.gson.bean.Attachment;
/**
* https 请求 微信为https的请求
* @author L.cm
* @date 2013-10-9 下午2:40:19
*/
public class HttpKit {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final Logger LOGGER = Logger.getLogger(HttpKit.class);
/**
* 发送Get请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
/**
* 发送Get请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
if(https != null && https){
return get(url);
}else{
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
}
/**
* 发送Get请求
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String get(String url, Map<String, String> params) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
return get(initParams(url, params));
}
/**
* 发送post请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String postNoSSL(String url,String params) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
/**
* 发送Post https请求
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
/**
* 上传媒体文件
* @param url
* @param params
* @param file
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
public static String upload(String url,File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // 定义数据分隔线
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream fs = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = fs.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个
fs.close();
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
InputStream in = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (conn != null) {
// 关闭连接
conn.disconnect();
}
return bufferRes.toString();
}
/**
* 下载资源
* @param url
* @return
* @throws IOException
*/
// public static Attachment download(String url) throws IOException{
// Attachment att = new Attachment();
// URL urlGet = new URL(url);
// HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setRequestMethod("GET");
// conn.connect();
// if(conn.getContentType().equalsIgnoreCase("text/plain")){
// // 定义BufferedReader输入流来读取URL的响应
// InputStream in = conn.getInputStream();
// BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
// String valueString = null;
// StringBuffer bufferRes = new StringBuffer();
// while ((valueString = read.readLine()) != null){
// bufferRes.append(valueString);
// }
// in.close();
// att.setError(bufferRes.toString());
// }else{
// BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
// String ds = conn.getHeaderField("Content-disposition");
// String fullName = ds.substring(ds.indexOf("filename=\"")+10,ds.length()-1);
// String relName = fullName.substring(0, fullName.lastIndexOf("."));
// String suffix = fullName.substring(relName.length()+1);
//
// att.setFullName(fullName);
// att.setFileName(relName);
// att.setSuffix(suffix);
// att.setContentLength(conn.getHeaderField("Content-Length"));
// att.setContentType(conn.getHeaderField("Content-Type"));
//
// att.setFileStream(bis);
// }
// return att;
// }
/**
*
* @param url
* @param params
* @return
*/
private static String initParams(String url, Map<String, String> params){
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
} else {
sb.append("&");
}
boolean first = true;
for (Entry<String, String> entry : params.entrySet()) {
if (first) {
first = false;
} else {
sb.append("&");
}
String key = entry.getKey();
String value = entry.getValue();
sb.append(key).append("=");
if (StringUtils.isNotEmpty(value)) {
try {
sb.append(URLEncoder.encode(value, DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
LOGGER.error(url,e);
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String fname = "dsasdas.mp4";
String s = fname.substring(0, fname.lastIndexOf("."));
String f = fname.substring(s.length()+1);
System.out.println(f);
}
}
/**
* 证书管理
*/
class MyX509TrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
} | 603599551/hrms | src/utils/HttpKit.java | 3,472 | // 关闭连接 | line_comment | zh-cn | package utils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
//import com.gson.bean.Attachment;
/**
* https 请求 微信为https的请求
* @author L.cm
* @date 2013-10-9 下午2:40:19
*/
public class HttpKit {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final Logger LOGGER = Logger.getLogger(HttpKit.class);
/**
* 发送Get请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭 <SUF>
http.disconnect();
}
return bufferRes.toString();
}
/**
* 发送Get请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
if(https != null && https){
return get(url);
}else{
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
}
/**
* 发送Get请求
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String get(String url, Map<String, String> params) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
return get(initParams(url, params));
}
/**
* 发送post请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String postNoSSL(String url,String params) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
/**
* 发送Post https请求
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
/**
* 上传媒体文件
* @param url
* @param params
* @param file
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
public static String upload(String url,File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // 定义数据分隔线
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream fs = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = fs.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个
fs.close();
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
InputStream in = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (conn != null) {
// 关闭连接
conn.disconnect();
}
return bufferRes.toString();
}
/**
* 下载资源
* @param url
* @return
* @throws IOException
*/
// public static Attachment download(String url) throws IOException{
// Attachment att = new Attachment();
// URL urlGet = new URL(url);
// HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setRequestMethod("GET");
// conn.connect();
// if(conn.getContentType().equalsIgnoreCase("text/plain")){
// // 定义BufferedReader输入流来读取URL的响应
// InputStream in = conn.getInputStream();
// BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
// String valueString = null;
// StringBuffer bufferRes = new StringBuffer();
// while ((valueString = read.readLine()) != null){
// bufferRes.append(valueString);
// }
// in.close();
// att.setError(bufferRes.toString());
// }else{
// BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
// String ds = conn.getHeaderField("Content-disposition");
// String fullName = ds.substring(ds.indexOf("filename=\"")+10,ds.length()-1);
// String relName = fullName.substring(0, fullName.lastIndexOf("."));
// String suffix = fullName.substring(relName.length()+1);
//
// att.setFullName(fullName);
// att.setFileName(relName);
// att.setSuffix(suffix);
// att.setContentLength(conn.getHeaderField("Content-Length"));
// att.setContentType(conn.getHeaderField("Content-Type"));
//
// att.setFileStream(bis);
// }
// return att;
// }
/**
*
* @param url
* @param params
* @return
*/
private static String initParams(String url, Map<String, String> params){
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
} else {
sb.append("&");
}
boolean first = true;
for (Entry<String, String> entry : params.entrySet()) {
if (first) {
first = false;
} else {
sb.append("&");
}
String key = entry.getKey();
String value = entry.getValue();
sb.append(key).append("=");
if (StringUtils.isNotEmpty(value)) {
try {
sb.append(URLEncoder.encode(value, DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
LOGGER.error(url,e);
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String fname = "dsasdas.mp4";
String s = fname.substring(0, fname.lastIndexOf("."));
String f = fname.substring(s.length()+1);
System.out.println(f);
}
}
/**
* 证书管理
*/
class MyX509TrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
} | 0 |
54223_1 | package com.example.lixudong.days;
/**
* Created by asus on 2016/12/16.
*/
import java.io.Serializable;
public class whichday implements Serializable {
public String title;
public String days;
public int tag;
public int beforeORafter;
public String Remind_str;
public String check_str;
public whichday(int tag, int beforeORafter, String title, String days) {
this.tag = tag;
this.beforeORafter = beforeORafter;
this.title = title;
this.days = days;
if (beforeORafter == R.mipmap.before) { //这里要改》》》》》》
this.check_str = "已有";
this.Remind_str = "那天的一切你还记得吗?";
} else {
this.check_str = "还有";
if (this.tag == R.mipmap.icon_birthday) {
this.Remind_str = "给TA准备个生日惊喜吧!";
} else if (this.tag == R.mipmap.icon_study || this.tag == R.mipmap.icon_work) {
this.Remind_str = "赶紧动手!时间迫在眉睫!";
} else {
this.Remind_str = "不要忘了这件事喔(*^__^*) ";
}
}
}
public String getTitle() {
return this.title;
}
public int getTag() {
return this.tag;
}
public String getRemind_str() {
return this.Remind_str;
}
public String getDays() {
return this.days;
}
public String getCheck_str() {
return this.check_str;
}
}
| 613-sysu/Days | Days/app/src/main/java/com/example/lixudong/days/whichday.java | 430 | //这里要改》》》》》》 | line_comment | zh-cn | package com.example.lixudong.days;
/**
* Created by asus on 2016/12/16.
*/
import java.io.Serializable;
public class whichday implements Serializable {
public String title;
public String days;
public int tag;
public int beforeORafter;
public String Remind_str;
public String check_str;
public whichday(int tag, int beforeORafter, String title, String days) {
this.tag = tag;
this.beforeORafter = beforeORafter;
this.title = title;
this.days = days;
if (beforeORafter == R.mipmap.before) { //这里 <SUF>
this.check_str = "已有";
this.Remind_str = "那天的一切你还记得吗?";
} else {
this.check_str = "还有";
if (this.tag == R.mipmap.icon_birthday) {
this.Remind_str = "给TA准备个生日惊喜吧!";
} else if (this.tag == R.mipmap.icon_study || this.tag == R.mipmap.icon_work) {
this.Remind_str = "赶紧动手!时间迫在眉睫!";
} else {
this.Remind_str = "不要忘了这件事喔(*^__^*) ";
}
}
}
public String getTitle() {
return this.title;
}
public int getTag() {
return this.tag;
}
public String getRemind_str() {
return this.Remind_str;
}
public String getDays() {
return this.days;
}
public String getCheck_str() {
return this.check_str;
}
}
| 1 |
50095_0 | package question061_serialized_binary_tree;
/**
* https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
*
* 序列化二叉树
*
* 请实现两个函数,分别用来序列化和反序列化二叉树。
*
* 二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。
* 序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),
* 以 ! 表示一个结点值的结束(value!)。
*
* 二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
*
* 运行时间:42ms。占用内存:9544k。
*/
public class Solution {
private StringBuilder preOrder = new StringBuilder();
private int index = -1;
String Serialize(TreeNode root) {
preOrderTraversal(root);
return preOrder.deleteCharAt(0).toString();
}
TreeNode Deserialize(String str) {
return build(str.split(","));
}
private void preOrderTraversal(TreeNode treeNode) {
if (null == treeNode) {
preOrder.append(",#");
return;
}
preOrder.append("," + treeNode.val);
preOrderTraversal(treeNode.left);
preOrderTraversal(treeNode.right);
}
private TreeNode build(String[] strings) {
index++;
if(index < strings.length && !strings[index].equals("#")) {
TreeNode root = new TreeNode(Integer.parseInt(strings[index]));
root.left = build(strings);
root.right = build(strings);
return root;
}
return null;
}
} | 617076674/Coding-Interviews | question061_serialized_binary_tree/Solution.java | 472 | /**
* https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
*
* 序列化二叉树
*
* 请实现两个函数,分别用来序列化和反序列化二叉树。
*
* 二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。
* 序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),
* 以 ! 表示一个结点值的结束(value!)。
*
* 二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
*
* 运行时间:42ms。占用内存:9544k。
*/ | block_comment | zh-cn | package question061_serialized_binary_tree;
/**
* htt <SUF>*/
public class Solution {
private StringBuilder preOrder = new StringBuilder();
private int index = -1;
String Serialize(TreeNode root) {
preOrderTraversal(root);
return preOrder.deleteCharAt(0).toString();
}
TreeNode Deserialize(String str) {
return build(str.split(","));
}
private void preOrderTraversal(TreeNode treeNode) {
if (null == treeNode) {
preOrder.append(",#");
return;
}
preOrder.append("," + treeNode.val);
preOrderTraversal(treeNode.left);
preOrderTraversal(treeNode.right);
}
private TreeNode build(String[] strings) {
index++;
if(index < strings.length && !strings[index].equals("#")) {
TreeNode root = new TreeNode(Integer.parseInt(strings[index]));
root.left = build(strings);
root.right = build(strings);
return root;
}
return null;
}
} | 1 |
46293_0 | package question0253;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author qianyihui
* @date 2019-08-13
*
* 当我们遇到"会议结束"事件时,意味着一些较早开始的会议已经结束。
* 我们并不关心到底是哪个会议结束。我们所需要的只是一些会议结束,从而提供一个空房间。
*
* 时间复杂度是O(nlogn),其中n为会议数量。空间复杂度是O(n)。
*
* 执行用时:7ms,击败92.93%。消耗内存:40.2MB,击败100.00%。
*/
public class Solution2 {
public int minMeetingRooms(int[][] intervals) {
int n;
if (intervals == null || (n = intervals.length) == 0) {
return 0;
}
int[] start = new int[n];
int[] end = new int[n];
for (int i = 0; i < n; i++) {
start[i] = intervals[i][0];
end[i] = intervals[i][1];
}
Arrays.sort(start);
Arrays.sort(end);
int index1 = 0, index2 = 0, result = 0;
while (index1 < n) {
if (start[index1] >= end[index2]) { //说明此时可以房间复用
result--; //由于后面无论是否有房间复用result均加1,故此处如果有房间复用则需要减1
index2++;
}
result++; //此处无论是否有房间复用都加1
index1++;
}
return result;
}
} | 617076674/LeetCode | question0253/Solution2.java | 444 | /**
* @author qianyihui
* @date 2019-08-13
*
* 当我们遇到"会议结束"事件时,意味着一些较早开始的会议已经结束。
* 我们并不关心到底是哪个会议结束。我们所需要的只是一些会议结束,从而提供一个空房间。
*
* 时间复杂度是O(nlogn),其中n为会议数量。空间复杂度是O(n)。
*
* 执行用时:7ms,击败92.93%。消耗内存:40.2MB,击败100.00%。
*/ | block_comment | zh-cn | package question0253;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @au <SUF>*/
public class Solution2 {
public int minMeetingRooms(int[][] intervals) {
int n;
if (intervals == null || (n = intervals.length) == 0) {
return 0;
}
int[] start = new int[n];
int[] end = new int[n];
for (int i = 0; i < n; i++) {
start[i] = intervals[i][0];
end[i] = intervals[i][1];
}
Arrays.sort(start);
Arrays.sort(end);
int index1 = 0, index2 = 0, result = 0;
while (index1 < n) {
if (start[index1] >= end[index2]) { //说明此时可以房间复用
result--; //由于后面无论是否有房间复用result均加1,故此处如果有房间复用则需要减1
index2++;
}
result++; //此处无论是否有房间复用都加1
index1++;
}
return result;
}
} | 1 |
38235_27 | package com.ceit.ebs.ebp.entity;
/**
*@author gr
*@date 2014-8-10 上午10:19:19
*/
public class EbpProject{
// Fields
private Integer id;//id
private Integer planId;//计划id
private String projectName;//项目名称
private String projectCode;//编码方式
private String isPlan;//是否为计划
private String createTime;//创建时间
private Integer budgetMoney;//预算金额
private Integer needDepartmentId;//需求部门
private Integer projectManagerId;//管理id
private String projectRemark;//项目描述
private String projectYear;//招标年份
private String isPublic;//公开/邀请,Y:公开;N:邀请
private String winRule;//中标规则
private String projectStatus;//项目状态:准备状态、招标中、开标等等,具体根据枚举文件详细说明
private String smallStatus;//项目小状态,例如招标准备中分包、分标等,具体根据枚举文件详细说明
private Integer numberTurn;//招标轮次
private Integer creatorId;//招标项目创建人id
private String isValid;
private String updateTime;
private String startBuyTime;//标书开始购买时间
private String endBuyTime;//标书购买截至时间
private String closeBidTime;//截标时间
private String openBidTime;//开标时间
private String singBidTime;//唱标时间
private String sureBidTime;//定标时间
private String replyStartTime;//应答开始时间
private String replyStopTime;//应答结束时间
private String isPrequalification;//是否需要资格认证,Y:需要
private String projectAuditStatus;//项目审核状态:未审核、审核中、审核通过、审核未通过等,根据枚举文件详细说明
private Integer projectAuditId;//审核人编号
private String projectAuditOpinion;//项目审核意见
private String priceUnit;//报价单位,人民币、美元等
private String isObject;//是否分标(三层结构),Y:分
private String comments;//备注
private Integer dispIndex;//索引
/**
* 抽取专家状态字段
*/
private String expertProjectStatus;//备注
// Constructors
/** default constructor */
public EbpProject() {
}
// Property accessors
public Integer getId() {
return this.id;
}
public String getExpertProjectStatus() {
return expertProjectStatus;
}
public void setExpertProjectStatus(String expertProjectStatus) {
this.expertProjectStatus = expertProjectStatus;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPlanId() {
return this.planId;
}
public void setPlanId(Integer planId) {
this.planId = planId;
}
public String getProjectName() {
return this.projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectCode() {
return this.projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getIsPlan() {
return this.isPlan;
}
public void setIsPlan(String isPlan) {
this.isPlan = isPlan;
}
public String getCreateTime() {
return this.createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getBudgetMoney() {
return this.budgetMoney;
}
public void setBudgetMoney(Integer budgetMoney) {
this.budgetMoney = budgetMoney;
}
public Integer getNeedDepartmentId() {
return this.needDepartmentId;
}
public void setNeedDepartmentId(Integer needDepartmentId) {
this.needDepartmentId = needDepartmentId;
}
public Integer getProjectManagerId() {
return this.projectManagerId;
}
public void setProjectManagerId(Integer projectManagerId) {
this.projectManagerId = projectManagerId;
}
public String getProjectRemark() {
return this.projectRemark;
}
public void setProjectRemark(String projectRemark) {
this.projectRemark = projectRemark;
}
public String getProjectYear() {
return this.projectYear;
}
public void setProjectYear(String projectYear) {
this.projectYear = projectYear;
}
public String getIsPublic() {
return this.isPublic;
}
public void setIsPublic(String isPublic) {
this.isPublic = isPublic;
}
public String getWinRule() {
return this.winRule;
}
public void setWinRule(String winRule) {
this.winRule = winRule;
}
public String getProjectStatus() {
return this.projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public String getSmallStatus() {
return this.smallStatus;
}
public void setSmallStatus(String smallStatus) {
this.smallStatus = smallStatus;
}
public Integer getNumberTurn() {
return this.numberTurn;
}
public void setNumberTurn(Integer numberTurn) {
this.numberTurn = numberTurn;
}
public Integer getCreatorId() {
return this.creatorId;
}
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
public String getIsValid() {
return this.isValid;
}
public void setIsValid(String isValid) {
this.isValid = isValid;
}
public String getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getStartBuyTime() {
return this.startBuyTime;
}
public void setStartBuyTime(String startBuyTime) {
this.startBuyTime = startBuyTime;
}
public String getEndBuyTime() {
return this.endBuyTime;
}
public void setEndBuyTime(String endBuyTime) {
this.endBuyTime = endBuyTime;
}
public String getCloseBidTime() {
return this.closeBidTime;
}
public void setCloseBidTime(String closeBidTime) {
this.closeBidTime = closeBidTime;
}
public String getOpenBidTime() {
return this.openBidTime;
}
public void setOpenBidTime(String openBidTime) {
this.openBidTime = openBidTime;
}
public String getSingBidTime() {
return this.singBidTime;
}
public void setSingBidTime(String singBidTime) {
this.singBidTime = singBidTime;
}
public String getSureBidTime() {
return this.sureBidTime;
}
public void setSureBidTime(String sureBidTime) {
this.sureBidTime = sureBidTime;
}
public String getReplyStartTime() {
return this.replyStartTime;
}
public void setReplyStartTime(String replyStartTime) {
this.replyStartTime = replyStartTime;
}
public String getReplyStopTime() {
return this.replyStopTime;
}
public void setReplyStopTime(String replyStopTime) {
this.replyStopTime = replyStopTime;
}
public String getIsPrequalification() {
return this.isPrequalification;
}
public void setIsPrequalification(String isPrequalification) {
this.isPrequalification = isPrequalification;
}
public String getProjectAuditStatus() {
return this.projectAuditStatus;
}
public void setProjectAuditStatus(String projectAuditStatus) {
this.projectAuditStatus = projectAuditStatus;
}
public Integer getProjectAuditId() {
return this.projectAuditId;
}
public void setProjectAuditId(Integer projectAuditId) {
this.projectAuditId = projectAuditId;
}
public String getProjectAuditOpinion() {
return this.projectAuditOpinion;
}
public void setProjectAuditOpinion(String projectAuditOpinion) {
this.projectAuditOpinion = projectAuditOpinion;
}
public String getPriceUnit() {
return this.priceUnit;
}
public void setPriceUnit(String priceUnit) {
this.priceUnit = priceUnit;
}
public String getIsObject() {
return this.isObject;
}
public void setIsObject(String isObject) {
this.isObject = isObject;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Integer getDispIndex() {
return dispIndex;
}
public void setDispIndex(Integer dispIndex) {
this.dispIndex = dispIndex;
}
// public String getExtends1() {
// return this.extends1;
// }
//
// public void setExtends1(String extends1) {
// this.extends1 = extends1;
// }
//
// public String getExtends2() {
// return this.extends2;
// }
//
// public void setExtends2(String extends2) {
// this.extends2 = extends2;
// }
//
// public String getExtends3() {
// return this.extends3;
// }
//
// public void setExtends3(String extends3) {
// this.extends3 = extends3;
// }
//
// public String getExtends4() {
// return this.extends4;
// }
//
// public void setExtends4(String extends4) {
// this.extends4 = extends4;
// }
//
// public String getExtends5() {
// return this.extends5;
// }
//
// public void setExtends5(String extends5) {
// this.extends5 = extends5;
// }
//
// public String getExtends6() {
// return this.extends6;
// }
//
// public void setExtends6(String extends6) {
// this.extends6 = extends6;
// }
//
// public String getExtends7() {
// return this.extends7;
// }
//
// public void setExtends7(String extends7) {
// this.extends7 = extends7;
// }
//
// public String getExtends8() {
// return this.extends8;
// }
//
// public void setExtends8(String extends8) {
// this.extends8 = extends8;
// }
//
// public String getExtends9() {
// return this.extends9;
// }
//
// public void setExtends9(String extends9) {
// this.extends9 = extends9;
// }
//
// public String getExtends10() {
// return this.extends10;
// }
//
// public void setExtends10(String extends10) {
// this.extends10 = extends10;
// }
} | 623860762/EBS | src/com/ceit/ebs/ebp/entity/EbpProject.java | 2,888 | //项目审核状态:未审核、审核中、审核通过、审核未通过等,根据枚举文件详细说明 | line_comment | zh-cn | package com.ceit.ebs.ebp.entity;
/**
*@author gr
*@date 2014-8-10 上午10:19:19
*/
public class EbpProject{
// Fields
private Integer id;//id
private Integer planId;//计划id
private String projectName;//项目名称
private String projectCode;//编码方式
private String isPlan;//是否为计划
private String createTime;//创建时间
private Integer budgetMoney;//预算金额
private Integer needDepartmentId;//需求部门
private Integer projectManagerId;//管理id
private String projectRemark;//项目描述
private String projectYear;//招标年份
private String isPublic;//公开/邀请,Y:公开;N:邀请
private String winRule;//中标规则
private String projectStatus;//项目状态:准备状态、招标中、开标等等,具体根据枚举文件详细说明
private String smallStatus;//项目小状态,例如招标准备中分包、分标等,具体根据枚举文件详细说明
private Integer numberTurn;//招标轮次
private Integer creatorId;//招标项目创建人id
private String isValid;
private String updateTime;
private String startBuyTime;//标书开始购买时间
private String endBuyTime;//标书购买截至时间
private String closeBidTime;//截标时间
private String openBidTime;//开标时间
private String singBidTime;//唱标时间
private String sureBidTime;//定标时间
private String replyStartTime;//应答开始时间
private String replyStopTime;//应答结束时间
private String isPrequalification;//是否需要资格认证,Y:需要
private String projectAuditStatus;//项目 <SUF>
private Integer projectAuditId;//审核人编号
private String projectAuditOpinion;//项目审核意见
private String priceUnit;//报价单位,人民币、美元等
private String isObject;//是否分标(三层结构),Y:分
private String comments;//备注
private Integer dispIndex;//索引
/**
* 抽取专家状态字段
*/
private String expertProjectStatus;//备注
// Constructors
/** default constructor */
public EbpProject() {
}
// Property accessors
public Integer getId() {
return this.id;
}
public String getExpertProjectStatus() {
return expertProjectStatus;
}
public void setExpertProjectStatus(String expertProjectStatus) {
this.expertProjectStatus = expertProjectStatus;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPlanId() {
return this.planId;
}
public void setPlanId(Integer planId) {
this.planId = planId;
}
public String getProjectName() {
return this.projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectCode() {
return this.projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getIsPlan() {
return this.isPlan;
}
public void setIsPlan(String isPlan) {
this.isPlan = isPlan;
}
public String getCreateTime() {
return this.createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getBudgetMoney() {
return this.budgetMoney;
}
public void setBudgetMoney(Integer budgetMoney) {
this.budgetMoney = budgetMoney;
}
public Integer getNeedDepartmentId() {
return this.needDepartmentId;
}
public void setNeedDepartmentId(Integer needDepartmentId) {
this.needDepartmentId = needDepartmentId;
}
public Integer getProjectManagerId() {
return this.projectManagerId;
}
public void setProjectManagerId(Integer projectManagerId) {
this.projectManagerId = projectManagerId;
}
public String getProjectRemark() {
return this.projectRemark;
}
public void setProjectRemark(String projectRemark) {
this.projectRemark = projectRemark;
}
public String getProjectYear() {
return this.projectYear;
}
public void setProjectYear(String projectYear) {
this.projectYear = projectYear;
}
public String getIsPublic() {
return this.isPublic;
}
public void setIsPublic(String isPublic) {
this.isPublic = isPublic;
}
public String getWinRule() {
return this.winRule;
}
public void setWinRule(String winRule) {
this.winRule = winRule;
}
public String getProjectStatus() {
return this.projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public String getSmallStatus() {
return this.smallStatus;
}
public void setSmallStatus(String smallStatus) {
this.smallStatus = smallStatus;
}
public Integer getNumberTurn() {
return this.numberTurn;
}
public void setNumberTurn(Integer numberTurn) {
this.numberTurn = numberTurn;
}
public Integer getCreatorId() {
return this.creatorId;
}
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
public String getIsValid() {
return this.isValid;
}
public void setIsValid(String isValid) {
this.isValid = isValid;
}
public String getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getStartBuyTime() {
return this.startBuyTime;
}
public void setStartBuyTime(String startBuyTime) {
this.startBuyTime = startBuyTime;
}
public String getEndBuyTime() {
return this.endBuyTime;
}
public void setEndBuyTime(String endBuyTime) {
this.endBuyTime = endBuyTime;
}
public String getCloseBidTime() {
return this.closeBidTime;
}
public void setCloseBidTime(String closeBidTime) {
this.closeBidTime = closeBidTime;
}
public String getOpenBidTime() {
return this.openBidTime;
}
public void setOpenBidTime(String openBidTime) {
this.openBidTime = openBidTime;
}
public String getSingBidTime() {
return this.singBidTime;
}
public void setSingBidTime(String singBidTime) {
this.singBidTime = singBidTime;
}
public String getSureBidTime() {
return this.sureBidTime;
}
public void setSureBidTime(String sureBidTime) {
this.sureBidTime = sureBidTime;
}
public String getReplyStartTime() {
return this.replyStartTime;
}
public void setReplyStartTime(String replyStartTime) {
this.replyStartTime = replyStartTime;
}
public String getReplyStopTime() {
return this.replyStopTime;
}
public void setReplyStopTime(String replyStopTime) {
this.replyStopTime = replyStopTime;
}
public String getIsPrequalification() {
return this.isPrequalification;
}
public void setIsPrequalification(String isPrequalification) {
this.isPrequalification = isPrequalification;
}
public String getProjectAuditStatus() {
return this.projectAuditStatus;
}
public void setProjectAuditStatus(String projectAuditStatus) {
this.projectAuditStatus = projectAuditStatus;
}
public Integer getProjectAuditId() {
return this.projectAuditId;
}
public void setProjectAuditId(Integer projectAuditId) {
this.projectAuditId = projectAuditId;
}
public String getProjectAuditOpinion() {
return this.projectAuditOpinion;
}
public void setProjectAuditOpinion(String projectAuditOpinion) {
this.projectAuditOpinion = projectAuditOpinion;
}
public String getPriceUnit() {
return this.priceUnit;
}
public void setPriceUnit(String priceUnit) {
this.priceUnit = priceUnit;
}
public String getIsObject() {
return this.isObject;
}
public void setIsObject(String isObject) {
this.isObject = isObject;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Integer getDispIndex() {
return dispIndex;
}
public void setDispIndex(Integer dispIndex) {
this.dispIndex = dispIndex;
}
// public String getExtends1() {
// return this.extends1;
// }
//
// public void setExtends1(String extends1) {
// this.extends1 = extends1;
// }
//
// public String getExtends2() {
// return this.extends2;
// }
//
// public void setExtends2(String extends2) {
// this.extends2 = extends2;
// }
//
// public String getExtends3() {
// return this.extends3;
// }
//
// public void setExtends3(String extends3) {
// this.extends3 = extends3;
// }
//
// public String getExtends4() {
// return this.extends4;
// }
//
// public void setExtends4(String extends4) {
// this.extends4 = extends4;
// }
//
// public String getExtends5() {
// return this.extends5;
// }
//
// public void setExtends5(String extends5) {
// this.extends5 = extends5;
// }
//
// public String getExtends6() {
// return this.extends6;
// }
//
// public void setExtends6(String extends6) {
// this.extends6 = extends6;
// }
//
// public String getExtends7() {
// return this.extends7;
// }
//
// public void setExtends7(String extends7) {
// this.extends7 = extends7;
// }
//
// public String getExtends8() {
// return this.extends8;
// }
//
// public void setExtends8(String extends8) {
// this.extends8 = extends8;
// }
//
// public String getExtends9() {
// return this.extends9;
// }
//
// public void setExtends9(String extends9) {
// this.extends9 = extends9;
// }
//
// public String getExtends10() {
// return this.extends10;
// }
//
// public void setExtends10(String extends10) {
// this.extends10 = extends10;
// }
} | 0 |
37831_1 | package cn.practice;
import java.util.Random;
/**
* <p>Description:实现一个抽奖效果,中奖率为30%</p>
* <p>Class:Random</p>
* <p>Powered by zxy On 2023-04-10 22:00 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class WinaPrize30 {
public static void main(String[] args) {
//实现一个抽奖效果,中奖率为30%
Random rand = new Random();
int ok = rand.nextInt(1, 101);
if (ok <= 30) {
System.out.println("恭喜,你中奖了," + ok);
} else {
System.err.println("遗憾,未中奖.");
}
}
}
| 629y/javase | demo/Javase/src/cn/practice/WinaPrize30.java | 237 | //实现一个抽奖效果,中奖率为30% | line_comment | zh-cn | package cn.practice;
import java.util.Random;
/**
* <p>Description:实现一个抽奖效果,中奖率为30%</p>
* <p>Class:Random</p>
* <p>Powered by zxy On 2023-04-10 22:00 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class WinaPrize30 {
public static void main(String[] args) {
//实现 <SUF>
Random rand = new Random();
int ok = rand.nextInt(1, 101);
if (ok <= 30) {
System.out.println("恭喜,你中奖了," + ok);
} else {
System.err.println("遗憾,未中奖.");
}
}
}
| 0 |
11937_210 | //package com.genersoft.iot.vmp.utils.redis;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.genersoft.iot.vmp.utils.SpringBeanFactory;
//import org.springframework.data.redis.core.*;
//import org.springframework.util.CollectionUtils;
//
//import java.util.*;
//import java.util.concurrent.TimeUnit;
//
///**
// * Redis工具类
// * @author swwheihei
// * @date 2020年5月6日 下午8:27:29
// */
//@SuppressWarnings(value = {"rawtypes", "unchecked"})
//public class RedisUtil2 {
//
// private static RedisTemplate redisTemplate;
//
// static {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
//
// /**
// * 指定缓存失效时间
// * @param key 键
// * @param time 时间(秒)
// * @return true / false
// */
// public static boolean expire(String key, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// if (time > 0) {
// redisTemplate.expire(key, time, TimeUnit.SECONDS);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 根据 key 获取过期时间
// * @param key 键
// */
// public static long getExpire(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.getExpire(key, TimeUnit.SECONDS);
// }
//
// /**
// * 判断 key 是否存在
// * @param key 键
// * @return true / false
// */
// public static boolean hasKey(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.hasKey(key);
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 删除缓存
// * @SuppressWarnings("unchecked") 忽略类型转换警告
// * @param key 键(一个或者多个)
// */
// public static boolean del(String... key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// if (key != null && key.length > 0) {
// if (key.length == 1) {
// redisTemplate.delete(key[0]);
// } else {
//// 传入一个 Collection<String> 集合
// redisTemplate.delete(CollectionUtils.arrayToList(key));
// }
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
//// ============================== String ==============================
//
// /**
// * 普通缓存获取
// * @param key 键
// * @return 值
// */
// public static Object get(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return key == null ? null : redisTemplate.opsForValue().get(key);
// }
//
// /**
// * 普通缓存放入
// * @param key 键
// * @param value 值
// * @return true / false
// */
// public static boolean set(String key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForValue().set(key, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 普通缓存放入并设置时间
// * @param key 键
// * @param value 值
// * @param time 时间(秒),如果 time < 0 则设置无限时间
// * @return true / false
// */
// public static boolean set(String key, Object value, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// if (time > 0) {
// redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
// } else {
// set(key, value);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 递增
// * @param key 键
// * @param delta 递增大小
// * @return
// */
// public static long incr(String key, long delta) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// if (delta < 0) {
// throw new RuntimeException("递增因子必须大于 0");
// }
// return redisTemplate.opsForValue().increment(key, delta);
// }
//
// /**
// * 递减
// * @param key 键
// * @param delta 递减大小
// * @return
// */
// public static long decr(String key, long delta) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// if (delta < 0) {
// throw new RuntimeException("递减因子必须大于 0");
// }
// return redisTemplate.opsForValue().increment(key, delta);
// }
//
//// ============================== Map ==============================
//
// /**
// * HashGet
// * @param key 键(no null)
// * @param item 项(no null)
// * @return 值
// */
// public static Object hget(String key, String item) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().get(key, item);
// }
//
// /**
// * 获取 key 对应的 map
// * @param key 键(no null)
// * @return 对应的多个键值
// */
// public static Map<Object, Object> hmget(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().entries(key);
// }
//
// /**
// * HashSet
// * @param key 键
// * @param map 值
// * @return true / false
// */
// public static boolean hmset(String key, Map<Object, Object> map) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().putAll(key, map);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * HashSet 并设置时间
// * @param key 键
// * @param map 值
// * @param time 时间
// * @return true / false
// */
// public static boolean hmset(String key, Map<?, ?> map, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().putAll(key, map);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 向一张 Hash表 中放入数据,如不存在则创建
// * @param key 键
// * @param item 项
// * @param value 值
// * @return true / false
// */
// public static boolean hset(String key, String item, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().put(key, item, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 向一张 Hash表 中放入数据,并设置时间,如不存在则创建
// * @param key 键
// * @param item 项
// * @param value 值
// * @param time 时间(如果原来的 Hash表 设置了时间,这里会覆盖)
// * @return true / false
// */
// public static boolean hset(String key, String item, Object value, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().put(key, item, value);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 删除 Hash表 中的值
// * @param key 键
// * @param item 项(可以多个,no null)
// */
// public static void hdel(String key, Object... item) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.opsForHash().delete(key, item);
// }
//
// /**
// * 判断 Hash表 中是否有该键的值
// * @param key 键(no null)
// * @param item 值(no null)
// * @return true / false
// */
// public static boolean hHasKey(String key, String item) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().hasKey(key, item);
// }
//
// /**
// * Hash递增,如果不存在则创建一个,并把新增的值返回
// * @param key 键
// * @param item 项
// * @param by 递增大小 > 0
// * @return
// */
// public static Double hincr(String key, String item, Double by) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().increment(key, item, by);
// }
//
// /**
// * Hash递减
// * @param key 键
// * @param item 项
// * @param by 递减大小
// * @return
// */
// public static Double hdecr(String key, String item, Double by) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().increment(key, item, -by);
// }
//
//// ============================== Set ==============================
//
// /**
// * 根据 key 获取 set 中的所有值
// * @param key 键
// * @return 值
// */
// public static Set<Object> sGet(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().members(key);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 从键为 key 的 set 中,根据 value 查询是否存在
// * @param key 键
// * @param value 值
// * @return true / false
// */
// public static boolean sHasKey(String key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().isMember(key, value);
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将数据放入 set缓存
// * @param key 键值
// * @param values 值(可以多个)
// * @return 成功个数
// */
// public static long sSet(String key, Object... values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().add(key, values);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 将数据放入 set缓存,并设置时间
// * @param key 键
// * @param time 时间
// * @param values 值(可以多个)
// * @return 成功放入个数
// */
// public static long sSet(String key, long time, Object... values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// long count = redisTemplate.opsForSet().add(key, values);
// if (time > 0) {
// expire(key, time);
// }
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 获取 set缓存的长度
// * @param key 键
// * @return 长度
// */
// public static long sGetSetSize(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().size(key);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 移除 set缓存中,值为 value 的
// * @param key 键
// * @param values 值
// * @return 成功移除个数
// */
// public static long setRemove(String key, Object... values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().remove(key, values);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//// ============================== ZSet ==============================
//
// /**
// * 添加一个元素, zset与set最大的区别就是每个元素都有一个score,因此有个排序的辅助功能; zadd
// *
// * @param key
// * @param value
// * @param score
// */
// public static void zAdd(Object key, Object value, double score) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.opsForZSet().add(key, value, score);
// }
//
// /**
// * 删除元素 zrem
// *
// * @param key
// * @param value
// */
// public static void zRemove(Object key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.opsForZSet().remove(key, value);
// }
//
// /**
// * score的增加or减少 zincrby
// *
// * @param key
// * @param value
// * @param delta -1 表示减 1 表示加1
// */
// public static Double zIncrScore(Object key, Object value, double delta) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().incrementScore(key, value, delta);
// }
//
// /**
// * 查询value对应的score zscore
// *
// * @param key
// * @param value
// * @return
// */
// public static Double zScore(Object key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().score(key, value);
// }
//
// /**
// * 判断value在zset中的排名 zrank
// *
// * @param key
// * @param value
// * @return
// */
// public static Long zRank(Object key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().rank(key, value);
// }
//
// /**
// * 返回集合的长度
// *
// * @param key
// * @return
// */
// public static Long zSize(Object key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().zCard(key);
// }
//
// /**
// * 查询集合中指定顺序的值, 0 -1 表示获取全部的集合内容 zrange
// *
// * 返回有序的集合,score小的在前面
// *
// * @param key
// * @param start
// * @param end
// * @return
// */
// public static Set<Object> zRange(Object key, int start, int end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().range(key, start, end);
// }
// /**
// * 查询集合中指定顺序的值和score,0, -1 表示获取全部的集合内容
// *
// * @param key
// * @param start
// * @param end
// * @return
// */
// public static Set<ZSetOperations.TypedTuple<String>> zRangeWithScore(Object key, int start, int end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
// }
// /**
// * 查询集合中指定顺序的值 zrevrange
// *
// * 返回有序的集合中,score大的在前面
// *
// * @param key
// * @param start
// * @param end
// * @return
// */
// public static Set<String> zRevRange(Object key, int start, int end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().reverseRange(key, start, end);
// }
// /**
// * 根据score的值,来获取满足条件的集合 zrangebyscore
// *
// * @param key
// * @param min
// * @param max
// * @return
// */
// public static Set<String> zSortRange(Object key, int min, int max) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().rangeByScore(key, min, max);
// }
//
//
//// ============================== List ==============================
//
// /**
// * 获取 list缓存的内容
// * @param key 键
// * @param start 开始
// * @param end 结束(0 到 -1 代表所有值)
// * @return
// */
// public static List<Object> lGet(String key, long start, long end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().range(key, start, end);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 获取 list缓存的长度
// * @param key 键
// * @return 长度
// */
// public static long lGetListSize(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().size(key);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 根据索引 index 获取键为 key 的 list 中的元素
// * @param key 键
// * @param index 索引
// * 当 index >= 0 时 {0:表头, 1:第二个元素}
// * 当 index < 0 时 {-1:表尾, -2:倒数第二个元素}
// * @return 值
// */
// public static Object lGetIndex(String key, long index) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().index(key, index);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 将值 value 插入键为 key 的 list 中,如果 list 不存在则创建空 list
// * @param key 键
// * @param value 值
// * @return true / false
// */
// public static boolean lSet(String key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPush(key, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将值 value 插入键为 key 的 list 中,并设置时间
// * @param key 键
// * @param value 值
// * @param time 时间
// * @return true / false
// */
// public static boolean lSet(String key, Object value, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPush(key, value);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将 values 插入键为 key 的 list 中
// * @param key 键
// * @param values 值
// * @return true / false
// */
// public static boolean lSetList(String key, List<Object> values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPushAll(key, values);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将 values 插入键为 key 的 list 中,并设置时间
// * @param key 键
// * @param values 值
// * @param time 时间
// * @return true / false
// */
// public static boolean lSetList(String key, List<Object> values, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPushAll(key, values);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 根据索引 index 修改键为 key 的值
// * @param key 键
// * @param index 索引
// * @param value 值
// * @return true / false
// */
// public static boolean lUpdateIndex(String key, long index, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().set(key, index, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 在键为 key 的 list 中删除值为 value 的元素
// * @param key 键
// * @param count 如果 count == 0 则删除 list 中所有值为 value 的元素
// * 如果 count > 0 则删除 list 中最左边那个值为 value 的元素
// * 如果 count < 0 则删除 list 中最右边那个值为 value 的元素
// * @param value
// * @return
// */
// public static long lRemove(String key, long count, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().remove(key, count, value);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 在键为 key 的 list中移除第一个元素
// * @param key 键
// * @return
// */
// public static Object lLeftPop(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForList().leftPop(key);
// }
//
// /**
// * 在键为 key 的 list中移除、最后一个元素
// * @param key 键
// * @return
// */
// public static Object lrightPop(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForList().rightPop(key);
// }
//
// /**
// * 模糊查询
// * @param key 键
// * @return true / false
// */
// public static List<Object> keys(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// Set<String> set = redisTemplate.keys(key);
// return new ArrayList<>(set);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
//
// /**
// * 模糊查询
// * @param query 查询参数
// * @return
// */
//// public static List<Object> scan(String query) {
//// List<Object> result = new ArrayList<>();
//// try {
//// Cursor<Map.Entry<Object,Object>> cursor = redisTemplate.opsForHash().scan("field",
//// ScanOptions.scanOptions().match(query).count(1000).build());
//// while (cursor.hasNext()) {
//// Map.Entry<Object,Object> entry = cursor.next();
//// result.add(entry.getKey());
//// Object key = entry.getKey();
//// Object valueSet = entry.getValue();
//// }
//// //关闭cursor
//// cursor.close();
//// } catch (Exception e) {
//// e.printStackTrace();
//// }
//// return result;
//// }
//
// /**
// * 模糊查询
// * @param query 查询参数
// * @return
// */
// public static List<Object> scan(String query) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// Set<String> resultKeys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
// ScanOptions scanOptions = ScanOptions.scanOptions().match("*" + query + "*").count(1000).build();
// Cursor<byte[]> scan = connection.scan(scanOptions);
// Set<String> keys = new HashSet<>();
// while (scan.hasNext()) {
// byte[] next = scan.next();
// keys.add(new String(next));
// }
// return keys;
// });
//
// return new ArrayList<>(resultKeys);
// }
// public static List<Object> scan2(String query) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// Set<String> keys = redisTemplate.keys(query);
// return new ArrayList<>(keys);
// }
// // ============================== 消息发送与订阅 ==============================
// public static void convertAndSend(String channel, JSONObject msg) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.convertAndSend(channel, msg);
// }
//
//}
| 648540858/wvp-GB28181-pro | src/main/java/com/genersoft/iot/vmp/utils/redis/RedisUtil2.java | 7,845 | // * Hash递增,如果不存在则创建一个,并把新增的值返回 | line_comment | zh-cn | //package com.genersoft.iot.vmp.utils.redis;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.genersoft.iot.vmp.utils.SpringBeanFactory;
//import org.springframework.data.redis.core.*;
//import org.springframework.util.CollectionUtils;
//
//import java.util.*;
//import java.util.concurrent.TimeUnit;
//
///**
// * Redis工具类
// * @author swwheihei
// * @date 2020年5月6日 下午8:27:29
// */
//@SuppressWarnings(value = {"rawtypes", "unchecked"})
//public class RedisUtil2 {
//
// private static RedisTemplate redisTemplate;
//
// static {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
//
// /**
// * 指定缓存失效时间
// * @param key 键
// * @param time 时间(秒)
// * @return true / false
// */
// public static boolean expire(String key, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// if (time > 0) {
// redisTemplate.expire(key, time, TimeUnit.SECONDS);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 根据 key 获取过期时间
// * @param key 键
// */
// public static long getExpire(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.getExpire(key, TimeUnit.SECONDS);
// }
//
// /**
// * 判断 key 是否存在
// * @param key 键
// * @return true / false
// */
// public static boolean hasKey(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.hasKey(key);
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 删除缓存
// * @SuppressWarnings("unchecked") 忽略类型转换警告
// * @param key 键(一个或者多个)
// */
// public static boolean del(String... key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// if (key != null && key.length > 0) {
// if (key.length == 1) {
// redisTemplate.delete(key[0]);
// } else {
//// 传入一个 Collection<String> 集合
// redisTemplate.delete(CollectionUtils.arrayToList(key));
// }
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
//// ============================== String ==============================
//
// /**
// * 普通缓存获取
// * @param key 键
// * @return 值
// */
// public static Object get(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return key == null ? null : redisTemplate.opsForValue().get(key);
// }
//
// /**
// * 普通缓存放入
// * @param key 键
// * @param value 值
// * @return true / false
// */
// public static boolean set(String key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForValue().set(key, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 普通缓存放入并设置时间
// * @param key 键
// * @param value 值
// * @param time 时间(秒),如果 time < 0 则设置无限时间
// * @return true / false
// */
// public static boolean set(String key, Object value, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// if (time > 0) {
// redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
// } else {
// set(key, value);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 递增
// * @param key 键
// * @param delta 递增大小
// * @return
// */
// public static long incr(String key, long delta) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// if (delta < 0) {
// throw new RuntimeException("递增因子必须大于 0");
// }
// return redisTemplate.opsForValue().increment(key, delta);
// }
//
// /**
// * 递减
// * @param key 键
// * @param delta 递减大小
// * @return
// */
// public static long decr(String key, long delta) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// if (delta < 0) {
// throw new RuntimeException("递减因子必须大于 0");
// }
// return redisTemplate.opsForValue().increment(key, delta);
// }
//
//// ============================== Map ==============================
//
// /**
// * HashGet
// * @param key 键(no null)
// * @param item 项(no null)
// * @return 值
// */
// public static Object hget(String key, String item) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().get(key, item);
// }
//
// /**
// * 获取 key 对应的 map
// * @param key 键(no null)
// * @return 对应的多个键值
// */
// public static Map<Object, Object> hmget(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().entries(key);
// }
//
// /**
// * HashSet
// * @param key 键
// * @param map 值
// * @return true / false
// */
// public static boolean hmset(String key, Map<Object, Object> map) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().putAll(key, map);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * HashSet 并设置时间
// * @param key 键
// * @param map 值
// * @param time 时间
// * @return true / false
// */
// public static boolean hmset(String key, Map<?, ?> map, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().putAll(key, map);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 向一张 Hash表 中放入数据,如不存在则创建
// * @param key 键
// * @param item 项
// * @param value 值
// * @return true / false
// */
// public static boolean hset(String key, String item, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().put(key, item, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 向一张 Hash表 中放入数据,并设置时间,如不存在则创建
// * @param key 键
// * @param item 项
// * @param value 值
// * @param time 时间(如果原来的 Hash表 设置了时间,这里会覆盖)
// * @return true / false
// */
// public static boolean hset(String key, String item, Object value, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForHash().put(key, item, value);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 删除 Hash表 中的值
// * @param key 键
// * @param item 项(可以多个,no null)
// */
// public static void hdel(String key, Object... item) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.opsForHash().delete(key, item);
// }
//
// /**
// * 判断 Hash表 中是否有该键的值
// * @param key 键(no null)
// * @param item 值(no null)
// * @return true / false
// */
// public static boolean hHasKey(String key, String item) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().hasKey(key, item);
// }
//
// /**
// * Ha <SUF>
// * @param key 键
// * @param item 项
// * @param by 递增大小 > 0
// * @return
// */
// public static Double hincr(String key, String item, Double by) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().increment(key, item, by);
// }
//
// /**
// * Hash递减
// * @param key 键
// * @param item 项
// * @param by 递减大小
// * @return
// */
// public static Double hdecr(String key, String item, Double by) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForHash().increment(key, item, -by);
// }
//
//// ============================== Set ==============================
//
// /**
// * 根据 key 获取 set 中的所有值
// * @param key 键
// * @return 值
// */
// public static Set<Object> sGet(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().members(key);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 从键为 key 的 set 中,根据 value 查询是否存在
// * @param key 键
// * @param value 值
// * @return true / false
// */
// public static boolean sHasKey(String key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().isMember(key, value);
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将数据放入 set缓存
// * @param key 键值
// * @param values 值(可以多个)
// * @return 成功个数
// */
// public static long sSet(String key, Object... values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().add(key, values);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 将数据放入 set缓存,并设置时间
// * @param key 键
// * @param time 时间
// * @param values 值(可以多个)
// * @return 成功放入个数
// */
// public static long sSet(String key, long time, Object... values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// long count = redisTemplate.opsForSet().add(key, values);
// if (time > 0) {
// expire(key, time);
// }
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 获取 set缓存的长度
// * @param key 键
// * @return 长度
// */
// public static long sGetSetSize(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().size(key);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 移除 set缓存中,值为 value 的
// * @param key 键
// * @param values 值
// * @return 成功移除个数
// */
// public static long setRemove(String key, Object... values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForSet().remove(key, values);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//// ============================== ZSet ==============================
//
// /**
// * 添加一个元素, zset与set最大的区别就是每个元素都有一个score,因此有个排序的辅助功能; zadd
// *
// * @param key
// * @param value
// * @param score
// */
// public static void zAdd(Object key, Object value, double score) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.opsForZSet().add(key, value, score);
// }
//
// /**
// * 删除元素 zrem
// *
// * @param key
// * @param value
// */
// public static void zRemove(Object key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.opsForZSet().remove(key, value);
// }
//
// /**
// * score的增加or减少 zincrby
// *
// * @param key
// * @param value
// * @param delta -1 表示减 1 表示加1
// */
// public static Double zIncrScore(Object key, Object value, double delta) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().incrementScore(key, value, delta);
// }
//
// /**
// * 查询value对应的score zscore
// *
// * @param key
// * @param value
// * @return
// */
// public static Double zScore(Object key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().score(key, value);
// }
//
// /**
// * 判断value在zset中的排名 zrank
// *
// * @param key
// * @param value
// * @return
// */
// public static Long zRank(Object key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().rank(key, value);
// }
//
// /**
// * 返回集合的长度
// *
// * @param key
// * @return
// */
// public static Long zSize(Object key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().zCard(key);
// }
//
// /**
// * 查询集合中指定顺序的值, 0 -1 表示获取全部的集合内容 zrange
// *
// * 返回有序的集合,score小的在前面
// *
// * @param key
// * @param start
// * @param end
// * @return
// */
// public static Set<Object> zRange(Object key, int start, int end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().range(key, start, end);
// }
// /**
// * 查询集合中指定顺序的值和score,0, -1 表示获取全部的集合内容
// *
// * @param key
// * @param start
// * @param end
// * @return
// */
// public static Set<ZSetOperations.TypedTuple<String>> zRangeWithScore(Object key, int start, int end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
// }
// /**
// * 查询集合中指定顺序的值 zrevrange
// *
// * 返回有序的集合中,score大的在前面
// *
// * @param key
// * @param start
// * @param end
// * @return
// */
// public static Set<String> zRevRange(Object key, int start, int end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().reverseRange(key, start, end);
// }
// /**
// * 根据score的值,来获取满足条件的集合 zrangebyscore
// *
// * @param key
// * @param min
// * @param max
// * @return
// */
// public static Set<String> zSortRange(Object key, int min, int max) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForZSet().rangeByScore(key, min, max);
// }
//
//
//// ============================== List ==============================
//
// /**
// * 获取 list缓存的内容
// * @param key 键
// * @param start 开始
// * @param end 结束(0 到 -1 代表所有值)
// * @return
// */
// public static List<Object> lGet(String key, long start, long end) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().range(key, start, end);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 获取 list缓存的长度
// * @param key 键
// * @return 长度
// */
// public static long lGetListSize(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().size(key);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 根据索引 index 获取键为 key 的 list 中的元素
// * @param key 键
// * @param index 索引
// * 当 index >= 0 时 {0:表头, 1:第二个元素}
// * 当 index < 0 时 {-1:表尾, -2:倒数第二个元素}
// * @return 值
// */
// public static Object lGetIndex(String key, long index) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().index(key, index);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 将值 value 插入键为 key 的 list 中,如果 list 不存在则创建空 list
// * @param key 键
// * @param value 值
// * @return true / false
// */
// public static boolean lSet(String key, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPush(key, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将值 value 插入键为 key 的 list 中,并设置时间
// * @param key 键
// * @param value 值
// * @param time 时间
// * @return true / false
// */
// public static boolean lSet(String key, Object value, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPush(key, value);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将 values 插入键为 key 的 list 中
// * @param key 键
// * @param values 值
// * @return true / false
// */
// public static boolean lSetList(String key, List<Object> values) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPushAll(key, values);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 将 values 插入键为 key 的 list 中,并设置时间
// * @param key 键
// * @param values 值
// * @param time 时间
// * @return true / false
// */
// public static boolean lSetList(String key, List<Object> values, long time) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().rightPushAll(key, values);
// if (time > 0) {
// expire(key, time);
// }
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 根据索引 index 修改键为 key 的值
// * @param key 键
// * @param index 索引
// * @param value 值
// * @return true / false
// */
// public static boolean lUpdateIndex(String key, long index, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// redisTemplate.opsForList().set(key, index, value);
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// }
//
// /**
// * 在键为 key 的 list 中删除值为 value 的元素
// * @param key 键
// * @param count 如果 count == 0 则删除 list 中所有值为 value 的元素
// * 如果 count > 0 则删除 list 中最左边那个值为 value 的元素
// * 如果 count < 0 则删除 list 中最右边那个值为 value 的元素
// * @param value
// * @return
// */
// public static long lRemove(String key, long count, Object value) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// return redisTemplate.opsForList().remove(key, count, value);
// } catch (Exception e) {
// e.printStackTrace();
// return 0;
// }
// }
//
// /**
// * 在键为 key 的 list中移除第一个元素
// * @param key 键
// * @return
// */
// public static Object lLeftPop(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForList().leftPop(key);
// }
//
// /**
// * 在键为 key 的 list中移除、最后一个元素
// * @param key 键
// * @return
// */
// public static Object lrightPop(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// return redisTemplate.opsForList().rightPop(key);
// }
//
// /**
// * 模糊查询
// * @param key 键
// * @return true / false
// */
// public static List<Object> keys(String key) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// try {
// Set<String> set = redisTemplate.keys(key);
// return new ArrayList<>(set);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
//
// /**
// * 模糊查询
// * @param query 查询参数
// * @return
// */
//// public static List<Object> scan(String query) {
//// List<Object> result = new ArrayList<>();
//// try {
//// Cursor<Map.Entry<Object,Object>> cursor = redisTemplate.opsForHash().scan("field",
//// ScanOptions.scanOptions().match(query).count(1000).build());
//// while (cursor.hasNext()) {
//// Map.Entry<Object,Object> entry = cursor.next();
//// result.add(entry.getKey());
//// Object key = entry.getKey();
//// Object valueSet = entry.getValue();
//// }
//// //关闭cursor
//// cursor.close();
//// } catch (Exception e) {
//// e.printStackTrace();
//// }
//// return result;
//// }
//
// /**
// * 模糊查询
// * @param query 查询参数
// * @return
// */
// public static List<Object> scan(String query) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// Set<String> resultKeys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
// ScanOptions scanOptions = ScanOptions.scanOptions().match("*" + query + "*").count(1000).build();
// Cursor<byte[]> scan = connection.scan(scanOptions);
// Set<String> keys = new HashSet<>();
// while (scan.hasNext()) {
// byte[] next = scan.next();
// keys.add(new String(next));
// }
// return keys;
// });
//
// return new ArrayList<>(resultKeys);
// }
// public static List<Object> scan2(String query) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// Set<String> keys = redisTemplate.keys(query);
// return new ArrayList<>(keys);
// }
// // ============================== 消息发送与订阅 ==============================
// public static void convertAndSend(String channel, JSONObject msg) {
// if (redisTemplate == null) {
// redisTemplate = SpringBeanFactory.getBean("redisTemplate");
// }
// redisTemplate.convertAndSend(channel, msg);
// }
//
//}
| 0 |
37964_16 | package com.demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.demo.demobean.AreaBean;
import com.demo.demobean.CityBean;
import com.demo.demobean.FilterBean;
import com.demo.demobean.InstitutionPriceBean;
import com.demo.demobean.ProvinceBean;
import com.demo.filter.DropDownMenu;
import com.demo.filter.interfaces.OnFilterDoneListener;
import com.demo.filter.util.MLog;
import com.demo.other.ToastUtil;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnFilterDoneListener {
//控件
DropDownMenu dropDownMenu;
LinearLayout layout_loaddata;
//数据
private FilterBean filterBean;//总数据源
private List<ProvinceBean> provinceBeans;//省
private List<CityBean> cityBeans;//市
private List<AreaBean> areaBeans;//区
private List<InstitutionPriceBean> priceBeans;//价格
private String[] titleList;//标题
private List<String> sortListData;//排序
private List<FilterBean.InstitutionObject> objectbeans;//收住对象
private List<FilterBean.PlaceProperty> propertyBeans;//机构性质
private List<FilterBean.Bed> beds;//床位
private List<FilterBean.InstitutionPlace> places;//类型
private List<FilterBean.InstitutionFeature> features;//特色
//筛选器适配
private DropMenuAdapter dropMenuAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
dropDownMenu = findViewById(R.id.dropDownMenu);
layout_loaddata = findViewById(R.id.layout_loaddata);
initView();
initData();
initFilterDropDownView();
}
/**
* 显示
*/
/**
* 筛选框 初始化+获取列表数据+筛选条件监听
*/
private void initFilterDropDownView() {
//绑定数据源
dropMenuAdapter = new DropMenuAdapter(this, titleList, this);
dropMenuAdapter.setSortListData(sortListData);
dropMenuAdapter.setFilterBean(filterBean);
dropDownMenu.setMenuAdapter(dropMenuAdapter);
//01 省市区 回调参数
dropMenuAdapter.setOnPlaceCallbackListener(new DropMenuAdapter.OnPlaceCallbackListener() {
@Override
public void onPlaceCallbackListener(int provinceId, int cityId, int areaId) {
ToastUtil.ToastShort(MainActivity.this, "省的id=" + provinceId + "--" + cityId + "--" + areaId);
}
});
//02 多条件 回调参数
dropMenuAdapter.setOnMultiFilterCallbackListener(new DropMenuAdapter.OnMultiFilterCallbackListener() {
@Override
public void onMultiFilterCallbackListener(int objId, int propertyId, int bedId, int typeId, String serviceId) {
ToastUtil.ToastShort(MainActivity.this, "多选的i依次是=" + objId + "--" + propertyId + "--" + bedId + "--" + typeId + "--" + serviceId);
}
});
//03 dropMenuAdapter 价格范围回调
dropMenuAdapter.setOnPriceCallbackListener(new DropMenuAdapter.OnPriceCallbackListener() {
@Override
public void onPriceCallbackListener(InstitutionPriceBean item) {
ToastUtil.ToastShort(MainActivity.this, "价格=" + item.getName() + "--id=" + item.getId());
}
});
//04 dropMenuAdapter 排序回调 0 1 2
dropMenuAdapter.setOnSortCallbackListener(new DropMenuAdapter.OnSortCallbackListener() {
@Override
public void onSortCallbackListener(int item) {
ToastUtil.ToastShort(MainActivity.this, "排序id=" + item);
}
});
// //异步加载列表数据
// loadListData();
}
/**
* 初始化
*/
private void initView() {
filterBean = new FilterBean();
provinceBeans = new ArrayList<>();
cityBeans = new ArrayList<>();
areaBeans = new ArrayList<>();
priceBeans = new ArrayList<>();
objectbeans = new ArrayList<>();
propertyBeans = new ArrayList<>();
beds = new ArrayList<>();
places = new ArrayList<>();
features = new ArrayList<>();
}
/**
* 筛选器title的变化
* <p>
* 点击到选中的item,自动收回
*
* @param position
* @param positionTitle
* @param urlValue
*/
@Override
public void onFilterDone(int position, String positionTitle, String urlValue) {
//数据显示到筛选标题中
dropDownMenu.setPositionIndicatorText(position, positionTitle);
dropDownMenu.close();
}
//**************************************************************************************************************************
//*******************************以下是假数据,正常是接口数据,demo中设置假数据方便演示****************************************
//**************************************************************************************************************************
/**
* 制作假数据
* 说明:FilterBean是公司项目接口返回的数据bean,现在用假数据实现,用注释+gif给大家解释
*/
private void initData() {
//筛选标题数据(固定数据)
titleList = new String[]{"区域", "筛选", "价格", "排序"};
//排序数据
sortListData = new ArrayList<>();
sortListData.add("综合排序");
sortListData.add("价格 从高到底");
sortListData.add("价格 从低到高");
//区数据
for (int i = 0; i < 33; i++) {
AreaBean bean = new AreaBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
areaBeans.add(bean);
} else {
bean.setId(i);
bean.setName("房间" + i);
bean.setPid("没用String");
areaBeans.add(bean);
}
}
MLog.d("区的数据:" + areaBeans.size());
//市数据
for (int i = 0; i < 26; i++) {
CityBean bean = new CityBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
} else {
bean.setId(i);
bean.setName("楼层" + i);
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
}
}
//省数据
for (int i = 0; i < 36; i++) {
ProvinceBean bean = new ProvinceBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
} else {
bean.setId(i);
bean.setName("单元号" + i);
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
}
}
//价格
for (int i = 0; i < 10; i++) {
InstitutionPriceBean bean = new InstitutionPriceBean();
if (i == 0) {
bean.setId(i);
bean.setName("2000元以下");
priceBeans.add(bean);
} else if (i == 9) {
bean.setId(i);
bean.setName("xxx元以上");
priceBeans.add(bean);
} else {
bean.setId(i);
bean.setName((2000 + i * 100) + "元");
priceBeans.add(bean);
}
}
//多选数据(5条)
//01收住对象
for (int i = 0; i < 7; i++) {
FilterBean.InstitutionObject bean = new FilterBean.InstitutionObject();
if (i == 0) {
bean.setId(i);
bean.setType("不限");
objectbeans.add(bean);
} else {
bean.setId(i);
bean.setType("对象" + i);
objectbeans.add(bean);
}
}
//02 机构性质
for (int i = 0; i < 3; i++) {
FilterBean.PlaceProperty bean = new FilterBean.PlaceProperty();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
propertyBeans.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setName("公办");
propertyBeans.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setName("民办");
propertyBeans.add(bean);
}
}
//03床位
for (int i = 0; i < 4; i++) {
FilterBean.Bed bean = new FilterBean.Bed();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
beds.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setName("100以下");
beds.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setName("100-500张");
beds.add(bean);
} else if (i == 3) {
bean.setId(i);
bean.setName("500张以上");
beds.add(bean);
}
}
//04机构类型
for (int i = 0; i < 7; i++) {
FilterBean.InstitutionPlace bean = new FilterBean.InstitutionPlace();
if (i == 0) {
bean.setId(i);
bean.setType("不限");
places.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setType("社区养老院");
places.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setType("敬老院");
places.add(bean);
} else if (i == 3) {
bean.setId(i);
bean.setType("疗养院");
places.add(bean);
} else {
bean.setId(i);
bean.setType("其他" + i);
places.add(bean);
}
}
//05特色
for (int i = 0; i < 7; i++) {
FilterBean.InstitutionFeature bean = new FilterBean.InstitutionFeature();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
features.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setName("医养结合");
features.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setName("免费试住");
features.add(bean);
} else if (i == 3) {
bean.setId(i);
bean.setName("合作医院");
features.add(bean);
} else {
bean.setId(i);
bean.setName("其他" + i);
features.add(bean);
}
}
//假数据整合,当成接口返回bean
filterBean.setType((ArrayList<FilterBean.InstitutionPlace>) places);
filterBean.setFeature((ArrayList<FilterBean.InstitutionFeature>) features);
filterBean.setBed((ArrayList<FilterBean.Bed>) beds);
filterBean.setObject((ArrayList<FilterBean.InstitutionObject>) objectbeans);
filterBean.setProperty((ArrayList<FilterBean.PlaceProperty>) propertyBeans);
filterBean.setPrice((ArrayList<InstitutionPriceBean>) priceBeans);
filterBean.setProvince((ArrayList<ProvinceBean>) provinceBeans);
}
/**
* 模拟数据更新
*
* @return
*/
private List<ProvinceBean> updateFilter01() {
List<ProvinceBean> provinceBeans = new ArrayList<>();
List<CityBean> cityBeans = new ArrayList<>();
List<AreaBean> areaBeans = new ArrayList<>();
//区数据
for (int i = 0; i < 10; i++) {
AreaBean bean = new AreaBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
areaBeans.add(bean);
} else {
bean.setId(i);
bean.setName("更新区" + i);
bean.setPid("没用String");
areaBeans.add(bean);
}
}
MLog.d("区的数据:" + areaBeans.size());
//市数据
for (int i = 0; i < 10; i++) {
CityBean bean = new CityBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
} else {
bean.setId(i);
bean.setName("更新市" + i);
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
}
}
//省数据
for (int i = 0; i < 10; i++) {
ProvinceBean bean = new ProvinceBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
} else {
bean.setId(i);
bean.setName("更新省" + i);
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
}
}
return provinceBeans;
}
}
| 66668/DropDownMenuplus | app/src/main/java/com/demo/MainActivity.java | 3,417 | //*******************************以下是假数据,正常是接口数据,demo中设置假数据方便演示**************************************** | line_comment | zh-cn | package com.demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.demo.demobean.AreaBean;
import com.demo.demobean.CityBean;
import com.demo.demobean.FilterBean;
import com.demo.demobean.InstitutionPriceBean;
import com.demo.demobean.ProvinceBean;
import com.demo.filter.DropDownMenu;
import com.demo.filter.interfaces.OnFilterDoneListener;
import com.demo.filter.util.MLog;
import com.demo.other.ToastUtil;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnFilterDoneListener {
//控件
DropDownMenu dropDownMenu;
LinearLayout layout_loaddata;
//数据
private FilterBean filterBean;//总数据源
private List<ProvinceBean> provinceBeans;//省
private List<CityBean> cityBeans;//市
private List<AreaBean> areaBeans;//区
private List<InstitutionPriceBean> priceBeans;//价格
private String[] titleList;//标题
private List<String> sortListData;//排序
private List<FilterBean.InstitutionObject> objectbeans;//收住对象
private List<FilterBean.PlaceProperty> propertyBeans;//机构性质
private List<FilterBean.Bed> beds;//床位
private List<FilterBean.InstitutionPlace> places;//类型
private List<FilterBean.InstitutionFeature> features;//特色
//筛选器适配
private DropMenuAdapter dropMenuAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
dropDownMenu = findViewById(R.id.dropDownMenu);
layout_loaddata = findViewById(R.id.layout_loaddata);
initView();
initData();
initFilterDropDownView();
}
/**
* 显示
*/
/**
* 筛选框 初始化+获取列表数据+筛选条件监听
*/
private void initFilterDropDownView() {
//绑定数据源
dropMenuAdapter = new DropMenuAdapter(this, titleList, this);
dropMenuAdapter.setSortListData(sortListData);
dropMenuAdapter.setFilterBean(filterBean);
dropDownMenu.setMenuAdapter(dropMenuAdapter);
//01 省市区 回调参数
dropMenuAdapter.setOnPlaceCallbackListener(new DropMenuAdapter.OnPlaceCallbackListener() {
@Override
public void onPlaceCallbackListener(int provinceId, int cityId, int areaId) {
ToastUtil.ToastShort(MainActivity.this, "省的id=" + provinceId + "--" + cityId + "--" + areaId);
}
});
//02 多条件 回调参数
dropMenuAdapter.setOnMultiFilterCallbackListener(new DropMenuAdapter.OnMultiFilterCallbackListener() {
@Override
public void onMultiFilterCallbackListener(int objId, int propertyId, int bedId, int typeId, String serviceId) {
ToastUtil.ToastShort(MainActivity.this, "多选的i依次是=" + objId + "--" + propertyId + "--" + bedId + "--" + typeId + "--" + serviceId);
}
});
//03 dropMenuAdapter 价格范围回调
dropMenuAdapter.setOnPriceCallbackListener(new DropMenuAdapter.OnPriceCallbackListener() {
@Override
public void onPriceCallbackListener(InstitutionPriceBean item) {
ToastUtil.ToastShort(MainActivity.this, "价格=" + item.getName() + "--id=" + item.getId());
}
});
//04 dropMenuAdapter 排序回调 0 1 2
dropMenuAdapter.setOnSortCallbackListener(new DropMenuAdapter.OnSortCallbackListener() {
@Override
public void onSortCallbackListener(int item) {
ToastUtil.ToastShort(MainActivity.this, "排序id=" + item);
}
});
// //异步加载列表数据
// loadListData();
}
/**
* 初始化
*/
private void initView() {
filterBean = new FilterBean();
provinceBeans = new ArrayList<>();
cityBeans = new ArrayList<>();
areaBeans = new ArrayList<>();
priceBeans = new ArrayList<>();
objectbeans = new ArrayList<>();
propertyBeans = new ArrayList<>();
beds = new ArrayList<>();
places = new ArrayList<>();
features = new ArrayList<>();
}
/**
* 筛选器title的变化
* <p>
* 点击到选中的item,自动收回
*
* @param position
* @param positionTitle
* @param urlValue
*/
@Override
public void onFilterDone(int position, String positionTitle, String urlValue) {
//数据显示到筛选标题中
dropDownMenu.setPositionIndicatorText(position, positionTitle);
dropDownMenu.close();
}
//**************************************************************************************************************************
//*******************************以下 <SUF>
//**************************************************************************************************************************
/**
* 制作假数据
* 说明:FilterBean是公司项目接口返回的数据bean,现在用假数据实现,用注释+gif给大家解释
*/
private void initData() {
//筛选标题数据(固定数据)
titleList = new String[]{"区域", "筛选", "价格", "排序"};
//排序数据
sortListData = new ArrayList<>();
sortListData.add("综合排序");
sortListData.add("价格 从高到底");
sortListData.add("价格 从低到高");
//区数据
for (int i = 0; i < 33; i++) {
AreaBean bean = new AreaBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
areaBeans.add(bean);
} else {
bean.setId(i);
bean.setName("房间" + i);
bean.setPid("没用String");
areaBeans.add(bean);
}
}
MLog.d("区的数据:" + areaBeans.size());
//市数据
for (int i = 0; i < 26; i++) {
CityBean bean = new CityBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
} else {
bean.setId(i);
bean.setName("楼层" + i);
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
}
}
//省数据
for (int i = 0; i < 36; i++) {
ProvinceBean bean = new ProvinceBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
} else {
bean.setId(i);
bean.setName("单元号" + i);
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
}
}
//价格
for (int i = 0; i < 10; i++) {
InstitutionPriceBean bean = new InstitutionPriceBean();
if (i == 0) {
bean.setId(i);
bean.setName("2000元以下");
priceBeans.add(bean);
} else if (i == 9) {
bean.setId(i);
bean.setName("xxx元以上");
priceBeans.add(bean);
} else {
bean.setId(i);
bean.setName((2000 + i * 100) + "元");
priceBeans.add(bean);
}
}
//多选数据(5条)
//01收住对象
for (int i = 0; i < 7; i++) {
FilterBean.InstitutionObject bean = new FilterBean.InstitutionObject();
if (i == 0) {
bean.setId(i);
bean.setType("不限");
objectbeans.add(bean);
} else {
bean.setId(i);
bean.setType("对象" + i);
objectbeans.add(bean);
}
}
//02 机构性质
for (int i = 0; i < 3; i++) {
FilterBean.PlaceProperty bean = new FilterBean.PlaceProperty();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
propertyBeans.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setName("公办");
propertyBeans.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setName("民办");
propertyBeans.add(bean);
}
}
//03床位
for (int i = 0; i < 4; i++) {
FilterBean.Bed bean = new FilterBean.Bed();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
beds.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setName("100以下");
beds.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setName("100-500张");
beds.add(bean);
} else if (i == 3) {
bean.setId(i);
bean.setName("500张以上");
beds.add(bean);
}
}
//04机构类型
for (int i = 0; i < 7; i++) {
FilterBean.InstitutionPlace bean = new FilterBean.InstitutionPlace();
if (i == 0) {
bean.setId(i);
bean.setType("不限");
places.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setType("社区养老院");
places.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setType("敬老院");
places.add(bean);
} else if (i == 3) {
bean.setId(i);
bean.setType("疗养院");
places.add(bean);
} else {
bean.setId(i);
bean.setType("其他" + i);
places.add(bean);
}
}
//05特色
for (int i = 0; i < 7; i++) {
FilterBean.InstitutionFeature bean = new FilterBean.InstitutionFeature();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
features.add(bean);
} else if (i == 1) {
bean.setId(i);
bean.setName("医养结合");
features.add(bean);
} else if (i == 2) {
bean.setId(i);
bean.setName("免费试住");
features.add(bean);
} else if (i == 3) {
bean.setId(i);
bean.setName("合作医院");
features.add(bean);
} else {
bean.setId(i);
bean.setName("其他" + i);
features.add(bean);
}
}
//假数据整合,当成接口返回bean
filterBean.setType((ArrayList<FilterBean.InstitutionPlace>) places);
filterBean.setFeature((ArrayList<FilterBean.InstitutionFeature>) features);
filterBean.setBed((ArrayList<FilterBean.Bed>) beds);
filterBean.setObject((ArrayList<FilterBean.InstitutionObject>) objectbeans);
filterBean.setProperty((ArrayList<FilterBean.PlaceProperty>) propertyBeans);
filterBean.setPrice((ArrayList<InstitutionPriceBean>) priceBeans);
filterBean.setProvince((ArrayList<ProvinceBean>) provinceBeans);
}
/**
* 模拟数据更新
*
* @return
*/
private List<ProvinceBean> updateFilter01() {
List<ProvinceBean> provinceBeans = new ArrayList<>();
List<CityBean> cityBeans = new ArrayList<>();
List<AreaBean> areaBeans = new ArrayList<>();
//区数据
for (int i = 0; i < 10; i++) {
AreaBean bean = new AreaBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
areaBeans.add(bean);
} else {
bean.setId(i);
bean.setName("更新区" + i);
bean.setPid("没用String");
areaBeans.add(bean);
}
}
MLog.d("区的数据:" + areaBeans.size());
//市数据
for (int i = 0; i < 10; i++) {
CityBean bean = new CityBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
} else {
bean.setId(i);
bean.setName("更新市" + i);
bean.setPid("没用String");
cityBeans.add(bean);
//添加区数据
bean.setChild((ArrayList<AreaBean>) areaBeans);
}
}
//省数据
for (int i = 0; i < 10; i++) {
ProvinceBean bean = new ProvinceBean();
if (i == 0) {
bean.setId(i);
bean.setName("不限");
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
} else {
bean.setId(i);
bean.setName("更新省" + i);
bean.setPid("没用String");
provinceBeans.add(bean);
//省份添加市数据
bean.setChild((ArrayList<CityBean>) cityBeans);
}
}
return provinceBeans;
}
}
| 1 |
37144_2 | package com.xiaolin.adpter;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.xiaolin.R;
import com.xiaolin.bean.AttendDaysOFMonthBean;
import com.xiaolin.utils.DebugUtil;
import java.util.ArrayList;
import java.util.List;
/**
* AttendDayActivity中listView的适配
*/
public class AttendDayAdapter extends BaseAdapter {
private static final String TAG = "calendar";
List<AttendDaysOFMonthBean> list;
Context context;
public LayoutInflater inflater;
public AttendDayAdapter(Context context, ArrayList<AttendDaysOFMonthBean> list) {
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
public class WidgetHolder {
public TextView tv_moringTime;
public TextView tv_lateTime;
public TextView tv_moringType;
public TextView tv_lateType;
public TextView tv_moringState;
public TextView tv_lateState;
}
@Override
public int getCount() {
if (list != null) {
return list.size();
}
return 0;
}
@Override
public Object getItem(int i) {
return list.get(i
);
}
@Override
public long getItemId(int i) {
return i;
}
//listView赋值
public void setEntityList(ArrayList entityList) {
this.list.clear();
this.list.addAll(entityList);
notifyDataSetChanged();
}
WidgetHolder holder;
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
//该布局上的控件
holder = new WidgetHolder();
view = inflater.inflate(R.layout.item_attend_detail, new LinearLayout(context), false);
holder.tv_moringTime = (TextView) view.findViewById(R.id.tv_moringTime);
holder.tv_lateTime = (TextView) view.findViewById(R.id.tv_lateTime);
holder.tv_moringType = (TextView) view.findViewById(R.id.tv_morningType);
holder.tv_lateType = (TextView) view.findViewById(R.id.tv_lateType);
holder.tv_moringState = (TextView) view.findViewById(R.id.tv_morningState);
holder.tv_lateState = (TextView) view.findViewById(R.id.tv_lateState);
view.setTag(holder);
} else {
holder = (WidgetHolder) view.getTag();
}
AttendDaysOFMonthBean bean = list.get(i);
//签到
holder.tv_moringTime.setText(bean.getFirstAttendDateTime());
holder.tv_moringType.setText(bean.getFirstAttendType());
if (bean.getFirstState().contains("迟到")) {
DebugUtil.d(TAG, "签到--迟到");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getFirstState().contains("正常")) {
DebugUtil.d(TAG, "签到--正常");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签到--缺勤");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
//签退
holder.tv_lateTime.setText(bean.getLastAttendDateTime());
holder.tv_lateType.setText(bean.getLastAttendType());
if (bean.getLastState().contains("早退")) {
DebugUtil.d(TAG, "签退--早退");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getLastState().contains("正常")) {
DebugUtil.d(TAG, "签退--正常");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签退--缺勤");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
return view;
}
}
| 66668/IEMClient | app/src/main/java/com/xiaolin/adpter/AttendDayAdapter.java | 1,162 | //该布局上的控件 | line_comment | zh-cn | package com.xiaolin.adpter;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.xiaolin.R;
import com.xiaolin.bean.AttendDaysOFMonthBean;
import com.xiaolin.utils.DebugUtil;
import java.util.ArrayList;
import java.util.List;
/**
* AttendDayActivity中listView的适配
*/
public class AttendDayAdapter extends BaseAdapter {
private static final String TAG = "calendar";
List<AttendDaysOFMonthBean> list;
Context context;
public LayoutInflater inflater;
public AttendDayAdapter(Context context, ArrayList<AttendDaysOFMonthBean> list) {
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
public class WidgetHolder {
public TextView tv_moringTime;
public TextView tv_lateTime;
public TextView tv_moringType;
public TextView tv_lateType;
public TextView tv_moringState;
public TextView tv_lateState;
}
@Override
public int getCount() {
if (list != null) {
return list.size();
}
return 0;
}
@Override
public Object getItem(int i) {
return list.get(i
);
}
@Override
public long getItemId(int i) {
return i;
}
//listView赋值
public void setEntityList(ArrayList entityList) {
this.list.clear();
this.list.addAll(entityList);
notifyDataSetChanged();
}
WidgetHolder holder;
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
//该布 <SUF>
holder = new WidgetHolder();
view = inflater.inflate(R.layout.item_attend_detail, new LinearLayout(context), false);
holder.tv_moringTime = (TextView) view.findViewById(R.id.tv_moringTime);
holder.tv_lateTime = (TextView) view.findViewById(R.id.tv_lateTime);
holder.tv_moringType = (TextView) view.findViewById(R.id.tv_morningType);
holder.tv_lateType = (TextView) view.findViewById(R.id.tv_lateType);
holder.tv_moringState = (TextView) view.findViewById(R.id.tv_morningState);
holder.tv_lateState = (TextView) view.findViewById(R.id.tv_lateState);
view.setTag(holder);
} else {
holder = (WidgetHolder) view.getTag();
}
AttendDaysOFMonthBean bean = list.get(i);
//签到
holder.tv_moringTime.setText(bean.getFirstAttendDateTime());
holder.tv_moringType.setText(bean.getFirstAttendType());
if (bean.getFirstState().contains("迟到")) {
DebugUtil.d(TAG, "签到--迟到");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getFirstState().contains("正常")) {
DebugUtil.d(TAG, "签到--正常");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签到--缺勤");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
//签退
holder.tv_lateTime.setText(bean.getLastAttendDateTime());
holder.tv_lateType.setText(bean.getLastAttendType());
if (bean.getLastState().contains("早退")) {
DebugUtil.d(TAG, "签退--早退");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getLastState().contains("正常")) {
DebugUtil.d(TAG, "签退--正常");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签退--缺勤");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
return view;
}
}
| 0 |
28218_0 | package com.zhongou.common.calendarcommon;
public class CalendarTpyeArray {
public final static String[] sch_type = { "会议", "约会", "电话", "纪念日", "生日", "课程", "其他" }; // 日程类型
public final static String[] remind = {"提醒一次","隔10分钟","隔30分钟","隔一小时","每天重复","每周重复","每月重复","每年重复"};
}
| 66668/ZOERP | app/src/main/java/com/zhongou/common/calendarcommon/CalendarTpyeArray.java | 119 | // 日程类型 | line_comment | zh-cn | package com.zhongou.common.calendarcommon;
public class CalendarTpyeArray {
public final static String[] sch_type = { "会议", "约会", "电话", "纪念日", "生日", "课程", "其他" }; // 日程 <SUF>
public final static String[] remind = {"提醒一次","隔10分钟","隔30分钟","隔一小时","每天重复","每周重复","每月重复","每年重复"};
}
| 0 |