file_id
stringlengths 5
9
| content
stringlengths 128
32.8k
| repo
stringlengths 9
63
| path
stringlengths 8
120
| token_length
int64 52
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
⌀ | tmp
float64 5
1.83k
⌀ | test
float64 0
1
⌀ |
---|---|---|---|---|---|---|---|---|---|---|---|
29186_8 | /**
* Capability.java
*/
package artiano.core.structure;
import java.util.HashSet;
import java.util.Iterator;
/**
* 表示处理能力的类。
* <p>
* 这种“能力”表示仅限于对数据实例的处理。默认情况下,构造的本类实例 不具备任何实例处理能力,你可能需要手工添加。
* </p>
*
* @author Nano.Michael
* @version 1.0.0
* @date 2013-12-16
* @author (latest modification by Nano.Michael)
* @since 1.0.0
*/
public class Capability {
/** 属性处理能力 */
protected HashSet<Class<?>> attCapabilities = new HashSet<>();
/** 类属性处理能力 */
protected HashSet<Class<?>> classCapabilities = new HashSet<>();
/** 是否允许属性值有缺失 */
protected boolean allowAttMissing = false;
/** 是否允许类属性值有缺失 */
protected boolean allowClsMissing = false;
/** 最少实例数 ,未设定为负数 */
protected int minInstaces = -1;
/** 不能处理的原因 */
protected String failReason = null;
/**
* 构造一个不具备任何“能力”的实例
*/
public Capability() {
disableAll();
}
/**
* 使用给定的“能力”构造一个实例
*
* @param c
* 指定实例
*/
public Capability(Capability c) {
this();
or(c);
}
/**
* 设定是否允许属性值有缺失
*
* @param allowMissing
* 是否允许属性值缺失
*/
public void allowAttributeMissing(boolean allowMissing) {
this.allowAttMissing = allowMissing;
}
/**
* 设定是否允许类属性值有缺失
*
* @param allowMissing
* 是否允许类属性值缺失
*/
public void allowClassMissing(boolean allowMissing) {
this.allowClsMissing = allowMissing;
}
/**
* 设置最小能处理实例数
*
* @param min
* 最小实例数
*/
public void setMinimumInstances(int min) {
this.minInstaces = min;
}
/**
* 获取能处理的最小实例数
*
* @return 能处理的最小实例数
*/
public int minimumInstacnes() {
return this.minInstaces;
}
/**
* 当使用方法{@link #handles(Table)}对表数据集进行测试失败的原因,如果当前“能力”具备 处理待测试的表,则此方法返回
* {@code null}
*
* @return 测试失败原因
*/
public String failReason() {
return failReason;
}
/**
* 获取属性处理能力<br>
* <b><i>NOTICE:</b></i> 值得注意的是,如果当前“能力”具备类属性处理能力,则当前类属性 类型将被排除在属性“能力”集合中
*
* @return 属性处理能力
*/
public Iterator<Class<?>> attributeCapabilities() {
return attCapabilities.iterator();
}
/**
* 获取类属性处理能力集合
*
* @return 类属性处理能力
*/
public Iterator<Class<?>> classCapabilities() {
return classCapabilities.iterator();
}
/**
* 开启对某个属性的“能力”<br>
* <b><i>NOTICE:</b></i> 指定属性不包括类属性
*
* @param att
* 属性类型
*/
public void enableAttribute(Class<?> att) {
attCapabilities.add(att);
}
/**
* 禁用对某个属性的“能力”<br>
* <b><i>NOTICE:</b></i>如果本类实例中并不包含这个类的“能力”,将不做任何处理
*
* @param att
* 属性类型
*/
public void disableAttribute(Class<?> att) {
attCapabilities.remove(att);
}
/**
* 开启对指定类属性的“能力”
*
* @param att
* 属性类型
*/
public void enableClass(Class<?> att) {
classCapabilities.add(att);
}
/**
* 禁用对指定类属性的能力
*
* @param att
* 指定属性类型
*/
public void disableClass(Class<?> att) {
classCapabilities.remove(att);
}
/**
* 禁用所有能力
*/
public void disableAll() {
attCapabilities.clear();
classCapabilities.clear();
allowAttMissing = false;
allowClsMissing = false;
}
/**
* 判断当前能力是否支持指定能力
*
* @param cap
* 指定能力
* @return 若支持返回{@code true}
*/
public boolean supports(Capability cap) {
// attribute capabilities
for (Iterator<Class<?>> it = cap.attributeCapabilities(); it.hasNext();)
if (!handlesAttribute(it.next()))
return false;
// class capabilities
for (Iterator<Class<?>> it = cap.classCapabilities(); it.hasNext();)
if (!handlesClass(it.next()))
return false;
// allow attribute missing ?
if (!allowAttMissing && cap.allowAttMissing)
return false;
// allow class attribute missing ?
if (!allowClsMissing && cap.allowClsMissing)
return false;
// minimum instances
if (minInstaces < cap.minInstaces)
return false;
// pass all tests
return true;
}
/**
* 判断是否具有处理某个类的处理能力
*
* @param att
* 指定的类
* @return 若具备指定类的处理能力则返回{@code true}
*/
public boolean handlesAttribute(Class<?> att) {
return attCapabilities.contains(att);
}
/**
* 判断是否具有处理指定类属性的能力
*
* @param att
* 指定属性类型
* @return 若具备指定属性的能力则返回{@code true}
*/
public boolean handlesClass(Class<?> att) {
return classCapabilities.contains(att);
}
/**
* 判断是否具备处理某个表的能力
*
* @param t
* 待判断的表
* @return 如果能处理则返回{@code true}
*/
public boolean handles(Table t) {
// class is set ?
if (!classCapabilities.isEmpty() && !t.hasClass()) {
failReason = "Class is not set!";
return false;
}
// attributes capabilities
for (Iterator<Attribute> it = t.attributesIterator(); it.hasNext();) {
Attribute att = it.next();
// not the class attribute
if (!t.isClassAttribute(att)) {
// can handle ?
if (!handlesAttribute(att.getClass())) {
failReason = "Can't handle [" + att.getName() + ":" + att.getType()
+ "] attributes" + " in the table " + t.getName()
+ ".";
return false;
}
// allow missing ?
if (!allowAttMissing && att.hasMissing()) {
failReason = "Missing values in attributes "
+ att.getName() + " is not allowed.";
return false;
}
}
}
// class capabilities
if (!classCapabilities.isEmpty() && t.hasClass()) {
Attribute att = t.classAttribute();
// can handle the class attribute ?
if (!handlesClass(att.getClass())) {
failReason = "Can't handle [" + att.getType() + "] class.\n";
return false;
}
// allow class value missing ?
if (!allowClsMissing && att.hasMissing()) {
failReason = "Missing value in class attribute "
+ att.getName() + " is not allowed.";
return false;
}
}
// minimum instances
if (t.rows() < minInstaces) {
failReason = "Number of instances in the table " + t.getName()
+ " < minimum instances (=" + minInstaces + ") needed.\n";
return false;
}
// pass all tests
return true;
}
/**
* 与某个能力进行“或”运算
*
* @param c
* 指定的“能力”
*/
public void or(Capability c) {
// attribute capabilities
attCapabilities.addAll(c.attCapabilities);
// class attribute capabilities
classCapabilities.addAll(c.classCapabilities);
// can handle missing values in attributes ?
allowAttMissing = allowAttMissing || c.allowAttMissing;
// can handle missing values in class ?
allowClsMissing = allowClsMissing || c.allowClsMissing;
// minimum instances
minInstaces = minInstaces < c.minInstaces ? c.minInstaces : minInstaces;
}
/**
* 与某个能力进行“与”运算
*
* @param c
* 指定“能力”
*/
public void and(Capability c) {
// attribute capabilities
for (Class<?> cs : attCapabilities)
if (!(handlesAttribute(cs) && c.handlesAttribute(cs)))
attCapabilities.remove(cs);
// class attribute capabilities
for (Class<?> cs : classCapabilities)
if (!(handlesClass(cs) && c.handlesClass(cs)))
classCapabilities.remove(cs);
// can handle missing values in attributes ?
allowAttMissing = allowAttMissing && c.allowAttMissing;
// can handle missing values in class ?
allowClsMissing = allowClsMissing && c.allowClsMissing;
minInstaces = minInstaces < c.minInstaces ? minInstaces : c.minInstaces;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
// header
sb.append("Capabilities:\n");
// attribute capabilities
sb.append("#Attributes can handles:\n");
if (attCapabilities.isEmpty())
sb.append("\tNONE\n");
else {
for (Iterator<Class<?>> it = attributeCapabilities(); it.hasNext();) {
sb.append("\t<");
sb.append(it.next() + ">\n");
}
}
// class attribute capabilities
sb.append("\n#Class can handles:\n");
if (classCapabilities.isEmpty())
sb.append("\tNONE\n");
else {
for (Iterator<?> it = classCapabilities(); it.hasNext();) {
sb.append("\t<");
sb.append(it.next() + ">\n");
}
}
sb.append("\n#Addtional:\n");
// allow attribute value missing ?
sb.append("\tAllow missing values in attributes: " + allowAttMissing
+ "\n");
sb.append("\tAllow mssing values in class: " + allowClsMissing + "\n");
// minimum instances needed
sb.append("\tMinimum instances needed: "
+ (minInstaces < 0 ? "Unrestricted" : minInstaces));
return sb.toString();
}
public static void main(String[] args) {
Capability capability = new Capability();
capability.enableAttribute(NumericAttribute.class);
capability.enableAttribute(NominalAttribute.class);
capability.enableClass(NominalAttribute.class);
capability.allowAttributeMissing(true);
capability.allowClassMissing(true);
System.out.println(capability);
}
}
| Artiano/Artiano | src/artiano/core/structure/Capability.java | 2,796 | /**
* 构造一个不具备任何“能力”的实例
*/ | block_comment | zh-cn | /**
* Capability.java
*/
package artiano.core.structure;
import java.util.HashSet;
import java.util.Iterator;
/**
* 表示处理能力的类。
* <p>
* 这种“能力”表示仅限于对数据实例的处理。默认情况下,构造的本类实例 不具备任何实例处理能力,你可能需要手工添加。
* </p>
*
* @author Nano.Michael
* @version 1.0.0
* @date 2013-12-16
* @author (latest modification by Nano.Michael)
* @since 1.0.0
*/
public class Capability {
/** 属性处理能力 */
protected HashSet<Class<?>> attCapabilities = new HashSet<>();
/** 类属性处理能力 */
protected HashSet<Class<?>> classCapabilities = new HashSet<>();
/** 是否允许属性值有缺失 */
protected boolean allowAttMissing = false;
/** 是否允许类属性值有缺失 */
protected boolean allowClsMissing = false;
/** 最少实例数 ,未设定为负数 */
protected int minInstaces = -1;
/** 不能处理的原因 */
protected String failReason = null;
/**
* 构造一 <SUF>*/
public Capability() {
disableAll();
}
/**
* 使用给定的“能力”构造一个实例
*
* @param c
* 指定实例
*/
public Capability(Capability c) {
this();
or(c);
}
/**
* 设定是否允许属性值有缺失
*
* @param allowMissing
* 是否允许属性值缺失
*/
public void allowAttributeMissing(boolean allowMissing) {
this.allowAttMissing = allowMissing;
}
/**
* 设定是否允许类属性值有缺失
*
* @param allowMissing
* 是否允许类属性值缺失
*/
public void allowClassMissing(boolean allowMissing) {
this.allowClsMissing = allowMissing;
}
/**
* 设置最小能处理实例数
*
* @param min
* 最小实例数
*/
public void setMinimumInstances(int min) {
this.minInstaces = min;
}
/**
* 获取能处理的最小实例数
*
* @return 能处理的最小实例数
*/
public int minimumInstacnes() {
return this.minInstaces;
}
/**
* 当使用方法{@link #handles(Table)}对表数据集进行测试失败的原因,如果当前“能力”具备 处理待测试的表,则此方法返回
* {@code null}
*
* @return 测试失败原因
*/
public String failReason() {
return failReason;
}
/**
* 获取属性处理能力<br>
* <b><i>NOTICE:</b></i> 值得注意的是,如果当前“能力”具备类属性处理能力,则当前类属性 类型将被排除在属性“能力”集合中
*
* @return 属性处理能力
*/
public Iterator<Class<?>> attributeCapabilities() {
return attCapabilities.iterator();
}
/**
* 获取类属性处理能力集合
*
* @return 类属性处理能力
*/
public Iterator<Class<?>> classCapabilities() {
return classCapabilities.iterator();
}
/**
* 开启对某个属性的“能力”<br>
* <b><i>NOTICE:</b></i> 指定属性不包括类属性
*
* @param att
* 属性类型
*/
public void enableAttribute(Class<?> att) {
attCapabilities.add(att);
}
/**
* 禁用对某个属性的“能力”<br>
* <b><i>NOTICE:</b></i>如果本类实例中并不包含这个类的“能力”,将不做任何处理
*
* @param att
* 属性类型
*/
public void disableAttribute(Class<?> att) {
attCapabilities.remove(att);
}
/**
* 开启对指定类属性的“能力”
*
* @param att
* 属性类型
*/
public void enableClass(Class<?> att) {
classCapabilities.add(att);
}
/**
* 禁用对指定类属性的能力
*
* @param att
* 指定属性类型
*/
public void disableClass(Class<?> att) {
classCapabilities.remove(att);
}
/**
* 禁用所有能力
*/
public void disableAll() {
attCapabilities.clear();
classCapabilities.clear();
allowAttMissing = false;
allowClsMissing = false;
}
/**
* 判断当前能力是否支持指定能力
*
* @param cap
* 指定能力
* @return 若支持返回{@code true}
*/
public boolean supports(Capability cap) {
// attribute capabilities
for (Iterator<Class<?>> it = cap.attributeCapabilities(); it.hasNext();)
if (!handlesAttribute(it.next()))
return false;
// class capabilities
for (Iterator<Class<?>> it = cap.classCapabilities(); it.hasNext();)
if (!handlesClass(it.next()))
return false;
// allow attribute missing ?
if (!allowAttMissing && cap.allowAttMissing)
return false;
// allow class attribute missing ?
if (!allowClsMissing && cap.allowClsMissing)
return false;
// minimum instances
if (minInstaces < cap.minInstaces)
return false;
// pass all tests
return true;
}
/**
* 判断是否具有处理某个类的处理能力
*
* @param att
* 指定的类
* @return 若具备指定类的处理能力则返回{@code true}
*/
public boolean handlesAttribute(Class<?> att) {
return attCapabilities.contains(att);
}
/**
* 判断是否具有处理指定类属性的能力
*
* @param att
* 指定属性类型
* @return 若具备指定属性的能力则返回{@code true}
*/
public boolean handlesClass(Class<?> att) {
return classCapabilities.contains(att);
}
/**
* 判断是否具备处理某个表的能力
*
* @param t
* 待判断的表
* @return 如果能处理则返回{@code true}
*/
public boolean handles(Table t) {
// class is set ?
if (!classCapabilities.isEmpty() && !t.hasClass()) {
failReason = "Class is not set!";
return false;
}
// attributes capabilities
for (Iterator<Attribute> it = t.attributesIterator(); it.hasNext();) {
Attribute att = it.next();
// not the class attribute
if (!t.isClassAttribute(att)) {
// can handle ?
if (!handlesAttribute(att.getClass())) {
failReason = "Can't handle [" + att.getName() + ":" + att.getType()
+ "] attributes" + " in the table " + t.getName()
+ ".";
return false;
}
// allow missing ?
if (!allowAttMissing && att.hasMissing()) {
failReason = "Missing values in attributes "
+ att.getName() + " is not allowed.";
return false;
}
}
}
// class capabilities
if (!classCapabilities.isEmpty() && t.hasClass()) {
Attribute att = t.classAttribute();
// can handle the class attribute ?
if (!handlesClass(att.getClass())) {
failReason = "Can't handle [" + att.getType() + "] class.\n";
return false;
}
// allow class value missing ?
if (!allowClsMissing && att.hasMissing()) {
failReason = "Missing value in class attribute "
+ att.getName() + " is not allowed.";
return false;
}
}
// minimum instances
if (t.rows() < minInstaces) {
failReason = "Number of instances in the table " + t.getName()
+ " < minimum instances (=" + minInstaces + ") needed.\n";
return false;
}
// pass all tests
return true;
}
/**
* 与某个能力进行“或”运算
*
* @param c
* 指定的“能力”
*/
public void or(Capability c) {
// attribute capabilities
attCapabilities.addAll(c.attCapabilities);
// class attribute capabilities
classCapabilities.addAll(c.classCapabilities);
// can handle missing values in attributes ?
allowAttMissing = allowAttMissing || c.allowAttMissing;
// can handle missing values in class ?
allowClsMissing = allowClsMissing || c.allowClsMissing;
// minimum instances
minInstaces = minInstaces < c.minInstaces ? c.minInstaces : minInstaces;
}
/**
* 与某个能力进行“与”运算
*
* @param c
* 指定“能力”
*/
public void and(Capability c) {
// attribute capabilities
for (Class<?> cs : attCapabilities)
if (!(handlesAttribute(cs) && c.handlesAttribute(cs)))
attCapabilities.remove(cs);
// class attribute capabilities
for (Class<?> cs : classCapabilities)
if (!(handlesClass(cs) && c.handlesClass(cs)))
classCapabilities.remove(cs);
// can handle missing values in attributes ?
allowAttMissing = allowAttMissing && c.allowAttMissing;
// can handle missing values in class ?
allowClsMissing = allowClsMissing && c.allowClsMissing;
minInstaces = minInstaces < c.minInstaces ? minInstaces : c.minInstaces;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
// header
sb.append("Capabilities:\n");
// attribute capabilities
sb.append("#Attributes can handles:\n");
if (attCapabilities.isEmpty())
sb.append("\tNONE\n");
else {
for (Iterator<Class<?>> it = attributeCapabilities(); it.hasNext();) {
sb.append("\t<");
sb.append(it.next() + ">\n");
}
}
// class attribute capabilities
sb.append("\n#Class can handles:\n");
if (classCapabilities.isEmpty())
sb.append("\tNONE\n");
else {
for (Iterator<?> it = classCapabilities(); it.hasNext();) {
sb.append("\t<");
sb.append(it.next() + ">\n");
}
}
sb.append("\n#Addtional:\n");
// allow attribute value missing ?
sb.append("\tAllow missing values in attributes: " + allowAttMissing
+ "\n");
sb.append("\tAllow mssing values in class: " + allowClsMissing + "\n");
// minimum instances needed
sb.append("\tMinimum instances needed: "
+ (minInstaces < 0 ? "Unrestricted" : minInstaces));
return sb.toString();
}
public static void main(String[] args) {
Capability capability = new Capability();
capability.enableAttribute(NumericAttribute.class);
capability.enableAttribute(NominalAttribute.class);
capability.enableClass(NominalAttribute.class);
capability.allowAttributeMissing(true);
capability.allowClassMissing(true);
System.out.println(capability);
}
}
| 1 | 29 | 1 |
24191_4 | package Auth.token;
import Auth.api.ApiRequest;
import Auth.utils.SHAUtils;
/**
* @desc: token 有关,负责 token 的生成、解析
* @author: AruNi_Lu
* @date: 2023/3/21
*/
public class AuthToken {
private static final long DEFAULT_EXPIRED_TIME_INTERVAL = 1 * 5 * 1000;
private long createTime;
private String token;
private long expiredTimeInterval;
public AuthToken(long createTime, String token, long expiredTimeInterval) {
this.createTime = createTime;
this.token = token;
this.expiredTimeInterval = expiredTimeInterval;
}
public AuthToken(long createTime, String token) {
this(createTime, token, DEFAULT_EXPIRED_TIME_INTERVAL);
}
/**
* 使用默认的失效时间间隔 DEFAULT_EXPIRED_TIME_INTERVAL 生成 AuthToken
* @param baseUrl
* @param appId
* @param password
* @param timestamp 生成 token 时的时间戳
* @return
*/
public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp) {
String token = generateToken(baseUrl, appId, password, timestamp);
return new AuthToken(timestamp, token);
}
/**
* 使用自定义的失效时间间隔 expiredTimeInterval 生成 AuthToken
* @param baseUrl
* @param appId
* @param password
* @param timestamp 生成 token 时的时间戳
* @param expiredTimeInterval 自定义的失效时间间隔
* @return
*/
public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp, long expiredTimeInterval) {
String token = generateToken(baseUrl, appId, password, timestamp);
return new AuthToken(timestamp, token, expiredTimeInterval);
}
/**
* 加密生成 token
*/
public static String generateToken(String baseUrl, String appId, String password, long timestamp) {
StringBuilder sb = new StringBuilder();
sb.append(baseUrl)
.append("&").append("appId").append("=").append(appId)
.append("&").append("password").append("=").append(password)
.append("&").append("timestamp").append("=").append(timestamp);
return SHAUtils.SHA(sb.toString());
}
/**
* 判断是否超过失效时间间隔
*/
public boolean isExpired() {
return (System.currentTimeMillis() - this.createTime) > this.expiredTimeInterval;
}
/**
* 判断两个 token 是否是否匹配
*/
public boolean match(AuthToken authToken) {
return this.token.equals(authToken.token);
}
public long getCreateTime() {
return createTime;
}
public String getToken() {
return token;
}
public long getExpiredTimeInterval() {
return expiredTimeInterval;
}
}
| AruNi-01/DesignPattern | oop/src/Auth/token/AuthToken.java | 654 | /**
* 判断是否超过失效时间间隔
*/ | block_comment | zh-cn | package Auth.token;
import Auth.api.ApiRequest;
import Auth.utils.SHAUtils;
/**
* @desc: token 有关,负责 token 的生成、解析
* @author: AruNi_Lu
* @date: 2023/3/21
*/
public class AuthToken {
private static final long DEFAULT_EXPIRED_TIME_INTERVAL = 1 * 5 * 1000;
private long createTime;
private String token;
private long expiredTimeInterval;
public AuthToken(long createTime, String token, long expiredTimeInterval) {
this.createTime = createTime;
this.token = token;
this.expiredTimeInterval = expiredTimeInterval;
}
public AuthToken(long createTime, String token) {
this(createTime, token, DEFAULT_EXPIRED_TIME_INTERVAL);
}
/**
* 使用默认的失效时间间隔 DEFAULT_EXPIRED_TIME_INTERVAL 生成 AuthToken
* @param baseUrl
* @param appId
* @param password
* @param timestamp 生成 token 时的时间戳
* @return
*/
public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp) {
String token = generateToken(baseUrl, appId, password, timestamp);
return new AuthToken(timestamp, token);
}
/**
* 使用自定义的失效时间间隔 expiredTimeInterval 生成 AuthToken
* @param baseUrl
* @param appId
* @param password
* @param timestamp 生成 token 时的时间戳
* @param expiredTimeInterval 自定义的失效时间间隔
* @return
*/
public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp, long expiredTimeInterval) {
String token = generateToken(baseUrl, appId, password, timestamp);
return new AuthToken(timestamp, token, expiredTimeInterval);
}
/**
* 加密生成 token
*/
public static String generateToken(String baseUrl, String appId, String password, long timestamp) {
StringBuilder sb = new StringBuilder();
sb.append(baseUrl)
.append("&").append("appId").append("=").append(appId)
.append("&").append("password").append("=").append(password)
.append("&").append("timestamp").append("=").append(timestamp);
return SHAUtils.SHA(sb.toString());
}
/**
* 判断是 <SUF>*/
public boolean isExpired() {
return (System.currentTimeMillis() - this.createTime) > this.expiredTimeInterval;
}
/**
* 判断两个 token 是否是否匹配
*/
public boolean match(AuthToken authToken) {
return this.token.equals(authToken.token);
}
public long getCreateTime() {
return createTime;
}
public String getToken() {
return token;
}
public long getExpiredTimeInterval() {
return expiredTimeInterval;
}
}
| 1 | 31 | 1 |
5837_31 | package com.sf.request;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.sf.entity.ordertableEntity;
import com.sf.entity.userEntity;
import com.sf.service.impl.LoginServiceImpl;
import com.sf.service.impl.UserListServiceImpl;
import com.sf.tool.GetDataTime;
import com.sf.tool.GetUUID;
@Controller
public class LoginRequest {
@Autowired
LoginServiceImpl loginServiceImpl;
@Autowired
UserListServiceImpl userListServiceImpl;
@RequestMapping("loginservice.sf")
public String web3(String userName,String passWord,HttpServletRequest request){
boolean bl= loginServiceImpl.loginuser(userName, passWord);
if(bl){
//将用户的全部信息查询出来
userEntity list = userListServiceImpl.userlist(userName);
//request.setAttribute("userlist", list);
//成功
//将用户ID放到session里面
request.getSession().setAttribute("userID", list.getUserID());
request.getSession().setAttribute("userName", userName);
request.getSession().setAttribute("userHand", list.getUserHand());
String mamaipi = "logoone.sf";
if(request.getSession().getAttribute("jiequ")!=null){
//说明这个地址是用户想访问的地址 但是没用登录
String ceshidizhi=(String) request.getSession().getAttribute("jiequ");
//重置为空
String jiequ = "";
request.getSession().setAttribute("jiequ", jiequ);
//赋值
mamaipi = ceshidizhi;
}
return "redirect:/"+mamaipi;
}else{
//失败
request.setAttribute("PHO", "用户名或密码错误!");
}
return "loginnew";
}
//AJAX 提交
@RequestMapping(value="yanzhengpass.sf",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
public @ResponseBody void yanzhengpass(HttpServletRequest request,HttpServletResponse response
,String pass,String zong,String shangpingmingzi,String shangpingtupiao,String dizhi) throws IOException{
//System.out.println(pass);"shangpingmingzi":shangpingmingzi,"shangpingtupiao":shangpingtupiao,"dizhi":dizhi
//System.out.println(zong);//拿到物品的所有价格
String userName = (String) request.getSession().getAttribute("userName");
String list = "";
boolean bl = loginServiceImpl.paypassword(userName, pass);
if(bl){
//拿到数据库里面的全部金额
userEntity user=userListServiceImpl.userlist(userName);
//金额
String RMB=user.getUserRMB();
int shangpingjiage= 0;
shangpingjiage=Integer.valueOf(zong).intValue();//商品价格
int sqljiage= 0;
sqljiage=Integer.valueOf(RMB).intValue();//用户的钱
int yuer=sqljiage-shangpingjiage;
if(yuer<0){
list="对不起,您的余额不足";
}else{
//将yuer转换为字符串然后保存数据库
String userRMB="";
userRMB=String.valueOf(yuer);
//支付成功之后 将数据库里面的价格修改
boolean b = loginServiceImpl.updateRMB(userRMB, userName);
if(b){
//得到下单时间
String Time = GetDataTime.DQtime();
//将订单存到数据库
ordertableEntity ordertable = new ordertableEntity();
ordertable.setOrderID(GetUUID.getUUID());
ordertable.setOrderuserName(userName);
ordertable.setOrderIgridsName(shangpingmingzi);
ordertable.setOrdergridsImg(shangpingtupiao);
ordertable.setOrderzongRMB(zong);
ordertable.setOrderStat("1");
ordertable.setOrderTime(Time);
ordertable.setOrderAddr(dizhi);
boolean yes= loginServiceImpl.ordertable(ordertable);
if(yes){
list="下单成功";
}else{
list="服务器错误...请联系管理员!";
}
}else{
list="服务器错误...请联系管理员!";
}
}
}else{
list="对不起,您输入的支付密码有误!";
}
//设置编码
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
Gson gson=new Gson();
String sbb=gson.toJson(list);
out.write(sbb);
}
//这里是确认收货
@RequestMapping("querendingdan.sf")
public String querendingdan(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Confirmorder(orderID);
if(bl){
//收货成功
//System.out.println("成功");
}else{
//收货失败
//System.out.println("失败");
}
return "forward:/Order.sf";
}
//这里是待取消订单
@RequestMapping("Cancellationoforder.sf")
public String Cancellationoforder(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Cancellationoforder(orderID);
if(bl){
//收货成功
//System.out.println("待取消成功");
}else{
//收货失败
//System.out.println("待取消失败");
}
return "forward:/Order.sf";
}
//这里是用户删除的订单
@RequestMapping("delordertable.sf")
public String delordertable(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.delordertable(orderID);
if(bl){
//收货成功
//System.out.println("删除成功");
}else{
//收货失败
//System.out.println("删除失败");
}
return "forward:/Order.sf";
}
//这里是立即发货
@RequestMapping("Delivergoods.sf")
public String Delivergoods(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Delivergoods("2",orderID);
if(bl){
}else{
}
return "forward:/Shipmentpending";
}
//这里是立即退货
@RequestMapping("Returngoods.sf")
public String Returngoods(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Delivergoods("5",orderID);
if(bl){
}else{
}
return "forward:/Returngoods";
}
@RequestMapping("loginforum.sf")
public String loginforum(String username,String password,HttpServletRequest request){
boolean bl= loginServiceImpl.loginuser(username, password);
String sb = "";
if(bl){
//将用户的全部信息查询出来
userEntity list = userListServiceImpl.userlist(username);
request.setAttribute("登录成功", sb);
//成功
//将用户ID放到session里面
request.getSession().setAttribute("userID", list.getUserID());
request.getSession().setAttribute("userName", username);
request.getSession().setAttribute("userHand", list.getUserHand());
}else{
request.setAttribute("登录失败", sb);
return "forward:/forum.sf";
}
return "forward:/forum.sf";
}
}
| ArvinZhangX/ssm_bilibili | src/main/java/com/sf/request/LoginRequest.java | 1,962 | //这里是立即发货 | line_comment | zh-cn | package com.sf.request;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.sf.entity.ordertableEntity;
import com.sf.entity.userEntity;
import com.sf.service.impl.LoginServiceImpl;
import com.sf.service.impl.UserListServiceImpl;
import com.sf.tool.GetDataTime;
import com.sf.tool.GetUUID;
@Controller
public class LoginRequest {
@Autowired
LoginServiceImpl loginServiceImpl;
@Autowired
UserListServiceImpl userListServiceImpl;
@RequestMapping("loginservice.sf")
public String web3(String userName,String passWord,HttpServletRequest request){
boolean bl= loginServiceImpl.loginuser(userName, passWord);
if(bl){
//将用户的全部信息查询出来
userEntity list = userListServiceImpl.userlist(userName);
//request.setAttribute("userlist", list);
//成功
//将用户ID放到session里面
request.getSession().setAttribute("userID", list.getUserID());
request.getSession().setAttribute("userName", userName);
request.getSession().setAttribute("userHand", list.getUserHand());
String mamaipi = "logoone.sf";
if(request.getSession().getAttribute("jiequ")!=null){
//说明这个地址是用户想访问的地址 但是没用登录
String ceshidizhi=(String) request.getSession().getAttribute("jiequ");
//重置为空
String jiequ = "";
request.getSession().setAttribute("jiequ", jiequ);
//赋值
mamaipi = ceshidizhi;
}
return "redirect:/"+mamaipi;
}else{
//失败
request.setAttribute("PHO", "用户名或密码错误!");
}
return "loginnew";
}
//AJAX 提交
@RequestMapping(value="yanzhengpass.sf",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
public @ResponseBody void yanzhengpass(HttpServletRequest request,HttpServletResponse response
,String pass,String zong,String shangpingmingzi,String shangpingtupiao,String dizhi) throws IOException{
//System.out.println(pass);"shangpingmingzi":shangpingmingzi,"shangpingtupiao":shangpingtupiao,"dizhi":dizhi
//System.out.println(zong);//拿到物品的所有价格
String userName = (String) request.getSession().getAttribute("userName");
String list = "";
boolean bl = loginServiceImpl.paypassword(userName, pass);
if(bl){
//拿到数据库里面的全部金额
userEntity user=userListServiceImpl.userlist(userName);
//金额
String RMB=user.getUserRMB();
int shangpingjiage= 0;
shangpingjiage=Integer.valueOf(zong).intValue();//商品价格
int sqljiage= 0;
sqljiage=Integer.valueOf(RMB).intValue();//用户的钱
int yuer=sqljiage-shangpingjiage;
if(yuer<0){
list="对不起,您的余额不足";
}else{
//将yuer转换为字符串然后保存数据库
String userRMB="";
userRMB=String.valueOf(yuer);
//支付成功之后 将数据库里面的价格修改
boolean b = loginServiceImpl.updateRMB(userRMB, userName);
if(b){
//得到下单时间
String Time = GetDataTime.DQtime();
//将订单存到数据库
ordertableEntity ordertable = new ordertableEntity();
ordertable.setOrderID(GetUUID.getUUID());
ordertable.setOrderuserName(userName);
ordertable.setOrderIgridsName(shangpingmingzi);
ordertable.setOrdergridsImg(shangpingtupiao);
ordertable.setOrderzongRMB(zong);
ordertable.setOrderStat("1");
ordertable.setOrderTime(Time);
ordertable.setOrderAddr(dizhi);
boolean yes= loginServiceImpl.ordertable(ordertable);
if(yes){
list="下单成功";
}else{
list="服务器错误...请联系管理员!";
}
}else{
list="服务器错误...请联系管理员!";
}
}
}else{
list="对不起,您输入的支付密码有误!";
}
//设置编码
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
Gson gson=new Gson();
String sbb=gson.toJson(list);
out.write(sbb);
}
//这里是确认收货
@RequestMapping("querendingdan.sf")
public String querendingdan(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Confirmorder(orderID);
if(bl){
//收货成功
//System.out.println("成功");
}else{
//收货失败
//System.out.println("失败");
}
return "forward:/Order.sf";
}
//这里是待取消订单
@RequestMapping("Cancellationoforder.sf")
public String Cancellationoforder(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Cancellationoforder(orderID);
if(bl){
//收货成功
//System.out.println("待取消成功");
}else{
//收货失败
//System.out.println("待取消失败");
}
return "forward:/Order.sf";
}
//这里是用户删除的订单
@RequestMapping("delordertable.sf")
public String delordertable(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.delordertable(orderID);
if(bl){
//收货成功
//System.out.println("删除成功");
}else{
//收货失败
//System.out.println("删除失败");
}
return "forward:/Order.sf";
}
//这里 <SUF>
@RequestMapping("Delivergoods.sf")
public String Delivergoods(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Delivergoods("2",orderID);
if(bl){
}else{
}
return "forward:/Shipmentpending";
}
//这里是立即退货
@RequestMapping("Returngoods.sf")
public String Returngoods(HttpServletRequest request,String orderID) {
boolean bl = loginServiceImpl.Delivergoods("5",orderID);
if(bl){
}else{
}
return "forward:/Returngoods";
}
@RequestMapping("loginforum.sf")
public String loginforum(String username,String password,HttpServletRequest request){
boolean bl= loginServiceImpl.loginuser(username, password);
String sb = "";
if(bl){
//将用户的全部信息查询出来
userEntity list = userListServiceImpl.userlist(username);
request.setAttribute("登录成功", sb);
//成功
//将用户ID放到session里面
request.getSession().setAttribute("userID", list.getUserID());
request.getSession().setAttribute("userName", username);
request.getSession().setAttribute("userHand", list.getUserHand());
}else{
request.setAttribute("登录失败", sb);
return "forward:/forum.sf";
}
return "forward:/forum.sf";
}
}
| 1 | 9 | 1 |
34441_18 | package cn.whu.forum.analysis.views.panels;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import cn.whu.forum.analysis.entities.SwotActor;
import cn.whu.forum.analysis.entities.SwotActorProperty;
import cn.whu.forum.analysis.services.SwotPropertyDAO;
import cn.whu.forum.analysis.services.interfaces.SwotPropertyDAOInterface;
public class SwotActorPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1;
private SwotPropertyDAOInterface swotPropertyDAO;
private SwotActor swotActor;
private JPanel panelLabelAdvantageANDChance;
private JPanel panelTableAdvantageANDChance;
private JPanel panelLabelActorName;
private JPanel panelTableDisadvantageANDThreat;
private JPanel panelLabelDisadvantageANDThreat;
//显示标签
private JLabel labelAdvantage;
private JLabel labelChance;
private JLabel labelDisadvantage;
private JLabel labelThreat;
private JLabel labelActorName;
//四个属性table
private DefaultTableModel dtm;
private String propertyType; //属性名称标志
private int selectedTableRow;
private JTable tableAdvantage;
private JTable tableChance;
private JTable tableDisadvantage;
private JTable tableThreat;
private JScrollPane scrollpaneTableAdvantage;
private JScrollPane scrollpaneTableChance;
private JScrollPane scrollpaneTableDisadvantage;
private JScrollPane scrollpaneTableThreat;
//右键菜单
private JPopupMenu popupMenu;
private JMenuItem popmenuItemAddProperty;
private JMenuItem popmenuItemDeleteProperty;
private JMenuItem popmenuItemModifyProperty;
//表格双击修改属性内容面板
private JFrame frameModifyProperty;
private JPanel panelModifyProperty;
private JPanel panelLayLabelInModifyProperty;
private JPanel panelLaytextAreaContentInModifyProperty;
private JPanel panelLayButtonInModifyProperty;
private JLabel lablePropertyContentInModifyProperty;
private JTextArea textAreaPropertyContentInModifyProperty;
private JButton buttonConfirmInModifyProperty;
private JButton buttonCancelInModifyProperty;
//表格右键菜单添加属性内容面板
private JFrame frameAddProperty;
private JPanel panelAddProperty;
private JPanel panelLayLabelInAddProperty;
private JPanel panelLayTextareaInAddProperty;
private JPanel panelLayButtonInAddProperty;
private JLabel lableContentInAddProperty;
// private JLabel lableRemark1InAddProperty;
// private JLabel lableRemark2InPopmenuAddProperty;
private JTextArea textareaContentInAddProperty;
// private JTextArea textareaRemark1InAddProperty;
// private JTextArea textareaRemark2InAddProperty;
private JButton buttonConfirmInAddProperty;
private JButton buttonCancelInAddProperty;
public SwotActorPanel(SwotActor swotActor) { //参与者编号作为参数
swotPropertyDAO = new SwotPropertyDAO();
this.swotActor = swotActor;
initializeComponent();
layoutComponent();
}
public void initializeComponent() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
panelLabelAdvantageANDChance = new JPanel();
panelTableAdvantageANDChance = new JPanel();
panelLabelActorName = new JPanel();
panelTableDisadvantageANDThreat = new JPanel();
panelLabelDisadvantageANDThreat = new JPanel();
panelLabelAdvantageANDChance.setLayout(new BoxLayout(panelLabelAdvantageANDChance, BoxLayout.X_AXIS));
panelTableAdvantageANDChance.setLayout(new BoxLayout(panelTableAdvantageANDChance, BoxLayout.X_AXIS));
panelLabelActorName.setLayout(new BoxLayout(panelLabelActorName, BoxLayout.X_AXIS));
panelTableDisadvantageANDThreat.setLayout(new BoxLayout(panelTableDisadvantageANDThreat, BoxLayout.X_AXIS));
panelLabelDisadvantageANDThreat.setLayout(new BoxLayout(panelLabelDisadvantageANDThreat, BoxLayout.X_AXIS));
//显示标签
labelAdvantage = new JLabel("优势");
labelChance = new JLabel("机会");
labelDisadvantage = new JLabel("劣势");
labelThreat = new JLabel("威胁");
labelActorName = new JLabel(swotActor.getActorName());
tableAdvantage = initializeTable("advantage");
tableChance = initializeTable("chance");
tableDisadvantage = initializeTable("disadvantage");
tableThreat = initializeTable("threat");
//将table装入JSplitPane
scrollpaneTableAdvantage = new JScrollPane(tableAdvantage);
scrollpaneTableChance = new JScrollPane(tableChance);
scrollpaneTableDisadvantage = new JScrollPane(tableDisadvantage);
scrollpaneTableThreat = new JScrollPane(tableThreat);
//右键菜单
popupMenu = new JPopupMenu();
popmenuItemAddProperty = new JMenuItem("添加");
popmenuItemDeleteProperty = new JMenuItem("删除");
popmenuItemModifyProperty = new JMenuItem("修改");
popmenuItemAddProperty.addActionListener(this);
popmenuItemDeleteProperty.addActionListener(this);
popmenuItemModifyProperty.addActionListener(this);
}
public void layoutComponent() {
panelLabelAdvantageANDChance.add(labelAdvantage);
panelLabelAdvantageANDChance.add(Box.createHorizontalGlue());
panelLabelAdvantageANDChance.add(labelChance);
panelLabelAdvantageANDChance.add(Box.createHorizontalGlue());
panelTableAdvantageANDChance.add(scrollpaneTableAdvantage);
panelTableAdvantageANDChance.add(scrollpaneTableChance);
panelLabelActorName.add(labelActorName);
panelLabelDisadvantageANDThreat.add(labelDisadvantage);
panelLabelDisadvantageANDThreat.add(Box.createHorizontalGlue());
panelLabelDisadvantageANDThreat.add(labelThreat);
panelLabelDisadvantageANDThreat.add(Box.createHorizontalGlue());
panelTableDisadvantageANDThreat.add(scrollpaneTableDisadvantage);
panelTableDisadvantageANDThreat.add(scrollpaneTableThreat);
add(panelLabelAdvantageANDChance);
add(panelTableAdvantageANDChance);
add(panelLabelActorName);
add(panelLabelDisadvantageANDThreat);
add(panelTableDisadvantageANDThreat);
popupMenu.add(popmenuItemAddProperty);
popupMenu.add(popmenuItemDeleteProperty);
popupMenu.add(popmenuItemModifyProperty);
}
public JTable initializeTable(final String tableType) {
dtm = new DefaultTableModel() {
/**
*
*/
private static final long serialVersionUID = 1L;
public Class<String> getColumnClass(int columnIndex) {
return String.class;
}
public boolean isCellEditable(int row, int column) { //不可编辑,变成双击弹出修改框
return false;
}
};
dtm.setDataVector(
new Object[][]{
{"", "", -1}
},
new Object[] {"编号", "内容", "PropertyID"}
);
final JTable table = new JTable(dtm);
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setMaxWidth(40);
columnModel.getColumn(0).setPreferredWidth(40);
columnModel.removeColumn(columnModel.getColumn(2)); //第三列为隐藏列,存储属性ID,便于deleteProperty。获得remove掉的列的data必须使用TableModel
table.setDefaultRenderer(String.class, new MultiLineTableCellRender()); //渲染成可换行
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
selectedTableRow = table.rowAtPoint(e.getPoint()); //getSelectedRow()对于右键无效,值为-1
if(e.getButton() == MouseEvent.BUTTON3) { //监听右键菜单
popupMenu.show(e.getComponent(), e.getX(), e.getY()); //在鼠标点击位置弹出右键菜单
} else if(e.getClickCount() == 2) { //监听双击菜单
if(getSelectedTable().getValueAt(0, 0) != "")
modifyProperty();
else
JOptionPane.showMessageDialog(null, "当前表格无内容,无法做修改操作", "",JOptionPane.INFORMATION_MESSAGE);
}
table.changeSelection(table.getSelectedRow(), table.getSelectedColumn(), true, false);
table.requestFocus();
propertyType = tableType; //标记当前选中的属性表格
}
});
return table;
}
public void addProperty() {
/*-------------初始化Start--------------*/
frameAddProperty = new JFrame("添加属性");
frameAddProperty.setSize(500, 400);
frameAddProperty.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frameAddProperty.setLocationRelativeTo( null );
frameAddProperty.getContentPane().setLayout(new BorderLayout());
panelAddProperty = new JPanel();
panelLayLabelInAddProperty = new JPanel();
panelLayTextareaInAddProperty = new JPanel();
panelLayButtonInAddProperty = new JPanel();
panelAddProperty.setLayout(new BoxLayout(panelAddProperty, BoxLayout.Y_AXIS));
panelLayTextareaInAddProperty.setLayout(new BoxLayout(panelLayTextareaInAddProperty, BoxLayout.X_AXIS));
panelLayButtonInAddProperty.setLayout(new BoxLayout(panelLayButtonInAddProperty, BoxLayout.X_AXIS));
lableContentInAddProperty = new JLabel("内容");
// lableRemark1InAddProperty = new JLabel("备注1");
// lableRemark2InPopmenuAddProperty = new JLabel("备注2");
textareaContentInAddProperty = new JTextArea(5,5);
textareaContentInAddProperty.setLineWrap(true); //支持自动换行
textareaContentInAddProperty.setBorder(BorderFactory.createTitledBorder(""));
// textareaRemark1InAddProperty = new JTextArea();
// textareaRemark2InAddProperty = new JTextArea();
// textareaRemark1InAddProperty.setLineWrap(true); //支持自动换行
// textareaRemark2InAddProperty.setLineWrap(true); //支持自动换行
// textareaContentInAddProperty.setMinimumSize(new Dimension(200,200));
// textareaContentInAddProperty.setMaximumSize(new Dimension(900,900));
// textareaRemark1InAddProperty.setMinimumSize(new Dimension(100,250));
// textareaRemark1InAddProperty.setMaximumSize(new Dimension(200,200));
// textareaRemark2InAddProperty.setMinimumSize(new Dimension(100,250));
// textareaRemark2InAddProperty.setMaximumSize(new Dimension(200,200));
buttonConfirmInAddProperty = new JButton("确定");
buttonCancelInAddProperty = new JButton("取消");
buttonConfirmInAddProperty.addActionListener(this);
buttonCancelInAddProperty.addActionListener(this);
/*-------------初始化End--------------*/
/*-------------布局Start--------------*/
panelLayLabelInAddProperty.add(lableContentInAddProperty);
panelLayTextareaInAddProperty.add(Box.createHorizontalStrut(20));
panelLayTextareaInAddProperty.add(textareaContentInAddProperty);
panelLayTextareaInAddProperty.add(Box.createHorizontalStrut(20));
// panelLayTextareaInAddProperty.add(lableRemark1InAddProperty);
// panelLayTextareaInAddProperty.add(textareaRemark1InAddProperty);
// panelLayTextareaInAddProperty.add(lableRemark2InPopmenuAddProperty);
// panelLayTextareaInAddProperty.add(textareaRemark2InAddProperty);
panelLayButtonInAddProperty.add(buttonConfirmInAddProperty);
panelLayButtonInAddProperty.add(Box.createHorizontalStrut(10));
panelLayButtonInAddProperty.add(buttonCancelInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(20));
panelAddProperty.add(panelLayLabelInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(5));
panelAddProperty.add(panelLayTextareaInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(10));
panelAddProperty.add(panelLayButtonInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(20));
frameAddProperty.setContentPane(panelAddProperty);
frameAddProperty.setVisible(true);
/*-------------布局End--------------*/
}
public void deleteProperty() {
if(getSelectedTable().getValueAt(0, 0) != "") {
swotPropertyDAO.deletePropertyByID((int)(getSelectedTable().getModel().getValueAt(selectedTableRow, 2))); //获得remove掉的列的data必须使用TableModel
dtm = (DefaultTableModel)getSelectedTable().getModel();
dtm.removeRow(selectedTableRow);
if(getSelectedTable().getRowCount() == 0) {
dtm.addRow(new Object[]{"", "", -1});
}else {
for(int i = 0; i < dtm.getRowCount(); i++) {
dtm.setValueAt(i + 1, i, 0);
}
}
}else {
JOptionPane.showMessageDialog(null, "当前表格无内容,无法做删除内容操作", "",JOptionPane.INFORMATION_MESSAGE);
}
}
//修改属性内容面板START(双击单元格)
public void modifyProperty() {
/*-------------初始化Start--------------*/
frameModifyProperty = new JFrame("修改属性");
frameModifyProperty.setSize(500, 400);
frameModifyProperty.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frameModifyProperty.setLocationRelativeTo( null );
panelModifyProperty = new JPanel();
panelModifyProperty = new JPanel();
panelLayLabelInModifyProperty = new JPanel();
panelLaytextAreaContentInModifyProperty = new JPanel();
panelLayButtonInModifyProperty = new JPanel();
panelModifyProperty.setLayout(new BoxLayout(panelModifyProperty, BoxLayout.Y_AXIS));
panelLaytextAreaContentInModifyProperty.setLayout(new BoxLayout(panelLaytextAreaContentInModifyProperty, BoxLayout.X_AXIS));
panelLayButtonInModifyProperty.setLayout(new BoxLayout(panelLayButtonInModifyProperty, BoxLayout.X_AXIS));
lablePropertyContentInModifyProperty=new JLabel("内容");
textAreaPropertyContentInModifyProperty = new JTextArea(5,5);
textAreaPropertyContentInModifyProperty.setText((String) getSelectedTable().getValueAt(selectedTableRow, 1));
textAreaPropertyContentInModifyProperty.setLineWrap(true); //支持自动换行
textAreaPropertyContentInModifyProperty.setBorder(BorderFactory.createTitledBorder(""));
// textAreaPropertyContentInModifyProperty.setMinimumSize(new Dimension(100,80));
// textAreaPropertyContentInModifyProperty.setMaximumSize(new Dimension(150,130));
buttonConfirmInModifyProperty = new JButton("确定");
buttonCancelInModifyProperty = new JButton("取消");
buttonConfirmInModifyProperty.addActionListener(this);
buttonCancelInModifyProperty.addActionListener(this);
/*-------------初始化End--------------*/
/*-------------布局Start--------------*/
panelLayLabelInModifyProperty.add(lablePropertyContentInModifyProperty);
panelLaytextAreaContentInModifyProperty.add(Box.createHorizontalStrut(20));
panelLaytextAreaContentInModifyProperty.add(textAreaPropertyContentInModifyProperty);
panelLaytextAreaContentInModifyProperty.add(Box.createHorizontalStrut(20));
panelLayButtonInModifyProperty.add(buttonConfirmInModifyProperty);
panelLayButtonInModifyProperty.add(Box.createHorizontalStrut(10));
panelLayButtonInModifyProperty.add(buttonCancelInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(20));
panelModifyProperty.add(panelLayLabelInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(5));
panelModifyProperty.add(panelLaytextAreaContentInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(10));
panelModifyProperty.add(panelLayButtonInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(20));
frameModifyProperty.setContentPane(panelModifyProperty);
frameModifyProperty.setVisible(true);
/*-------------布局End--------------*/
}
//修改属性内容面板END
//返回当前选中的table
public JTable getSelectedTable() {
if(propertyType.equals("advantage")) {
return tableAdvantage;
}
else if(propertyType.equals("chance")) {
return tableChance;
}
else if(propertyType.equals("disadvantage")) {
return tableDisadvantage;
}
else if(propertyType.equals("threat")) {
return tableThreat;
}
return null;
}
//查询面板所用
public JTable getInsertTable(String PropertyType) {
if(PropertyType.equals("advantage")) {
return tableAdvantage;
}
else if(PropertyType.equals("chance")) {
return tableChance;
}
else if(PropertyType.equals("disadvantage")) {
return tableDisadvantage;
}
else if(PropertyType.equals("threat")) {
return tableThreat;
}
return null;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == popmenuItemAddProperty) { //右键菜单添加属性
addProperty();
}
else if(e.getSource() == popmenuItemDeleteProperty) {
deleteProperty();
}
else if(e.getSource() == popmenuItemModifyProperty) {
if(getSelectedTable().getValueAt(0, 0) != "")
modifyProperty();
else
JOptionPane.showMessageDialog(null, "当前表格无内容,无法做修改操作", "",JOptionPane.INFORMATION_MESSAGE);
}
else if(e.getSource() == buttonConfirmInModifyProperty) {
SwotActorProperty swotActorProperty = new SwotActorProperty();
swotActorProperty.setPropertyID((int)(getSelectedTable().getModel().getValueAt(selectedTableRow, 2))); //获得remove掉的列的data必须使用TableModel
swotActorProperty.setPropertyContent(textAreaPropertyContentInModifyProperty.getText());
// swotActorProperty.setPropertyMark1
// swotActorProperty.setPropertyMark2
swotPropertyDAO.updateProperty(swotActorProperty);
getSelectedTable().setValueAt(swotActorProperty.getPropertyContent(), selectedTableRow, 1);
}
else if(e.getSource() == buttonCancelInModifyProperty) {
frameModifyProperty.dispose();
}
else if(e.getSource() == buttonConfirmInAddProperty) {
SwotActorProperty swotActorProperty = new SwotActorProperty();
swotActorProperty.setPropertyType(propertyType);
swotActorProperty.setPropertyContent(textareaContentInAddProperty.getText());
swotPropertyDAO.addProperty(swotActor, swotActorProperty);
dtm = (DefaultTableModel)getSelectedTable().getModel();
if(dtm.getValueAt(0, 0) == "") {
dtm.setValueAt(1, 0, 0);
dtm.setValueAt(swotActorProperty.getPropertyContent(), 0, 1);
dtm.setValueAt(swotActorProperty.getPropertyID(), 0, 2);
} else{
dtm.addRow(new Object[]{dtm.getRowCount()+1, swotActorProperty.getPropertyContent(), swotActorProperty.getPropertyID()});
}
buttonConfirmInAddProperty.setText("继续添加");
textareaContentInAddProperty.setText("");
// textareaRemark1InAddProperty.setText("");
// textareaRemark2InAddProperty.setText("");
}
else if(e.getSource() == buttonCancelInAddProperty) {
frameAddProperty.dispose();
}
}
}
| AsasinCree/zlbyzc | src/cn/whu/forum/analysis/views/panels/SwotActorPanel.java | 5,109 | //监听右键菜单 | line_comment | zh-cn | package cn.whu.forum.analysis.views.panels;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import cn.whu.forum.analysis.entities.SwotActor;
import cn.whu.forum.analysis.entities.SwotActorProperty;
import cn.whu.forum.analysis.services.SwotPropertyDAO;
import cn.whu.forum.analysis.services.interfaces.SwotPropertyDAOInterface;
public class SwotActorPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1;
private SwotPropertyDAOInterface swotPropertyDAO;
private SwotActor swotActor;
private JPanel panelLabelAdvantageANDChance;
private JPanel panelTableAdvantageANDChance;
private JPanel panelLabelActorName;
private JPanel panelTableDisadvantageANDThreat;
private JPanel panelLabelDisadvantageANDThreat;
//显示标签
private JLabel labelAdvantage;
private JLabel labelChance;
private JLabel labelDisadvantage;
private JLabel labelThreat;
private JLabel labelActorName;
//四个属性table
private DefaultTableModel dtm;
private String propertyType; //属性名称标志
private int selectedTableRow;
private JTable tableAdvantage;
private JTable tableChance;
private JTable tableDisadvantage;
private JTable tableThreat;
private JScrollPane scrollpaneTableAdvantage;
private JScrollPane scrollpaneTableChance;
private JScrollPane scrollpaneTableDisadvantage;
private JScrollPane scrollpaneTableThreat;
//右键菜单
private JPopupMenu popupMenu;
private JMenuItem popmenuItemAddProperty;
private JMenuItem popmenuItemDeleteProperty;
private JMenuItem popmenuItemModifyProperty;
//表格双击修改属性内容面板
private JFrame frameModifyProperty;
private JPanel panelModifyProperty;
private JPanel panelLayLabelInModifyProperty;
private JPanel panelLaytextAreaContentInModifyProperty;
private JPanel panelLayButtonInModifyProperty;
private JLabel lablePropertyContentInModifyProperty;
private JTextArea textAreaPropertyContentInModifyProperty;
private JButton buttonConfirmInModifyProperty;
private JButton buttonCancelInModifyProperty;
//表格右键菜单添加属性内容面板
private JFrame frameAddProperty;
private JPanel panelAddProperty;
private JPanel panelLayLabelInAddProperty;
private JPanel panelLayTextareaInAddProperty;
private JPanel panelLayButtonInAddProperty;
private JLabel lableContentInAddProperty;
// private JLabel lableRemark1InAddProperty;
// private JLabel lableRemark2InPopmenuAddProperty;
private JTextArea textareaContentInAddProperty;
// private JTextArea textareaRemark1InAddProperty;
// private JTextArea textareaRemark2InAddProperty;
private JButton buttonConfirmInAddProperty;
private JButton buttonCancelInAddProperty;
public SwotActorPanel(SwotActor swotActor) { //参与者编号作为参数
swotPropertyDAO = new SwotPropertyDAO();
this.swotActor = swotActor;
initializeComponent();
layoutComponent();
}
public void initializeComponent() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
panelLabelAdvantageANDChance = new JPanel();
panelTableAdvantageANDChance = new JPanel();
panelLabelActorName = new JPanel();
panelTableDisadvantageANDThreat = new JPanel();
panelLabelDisadvantageANDThreat = new JPanel();
panelLabelAdvantageANDChance.setLayout(new BoxLayout(panelLabelAdvantageANDChance, BoxLayout.X_AXIS));
panelTableAdvantageANDChance.setLayout(new BoxLayout(panelTableAdvantageANDChance, BoxLayout.X_AXIS));
panelLabelActorName.setLayout(new BoxLayout(panelLabelActorName, BoxLayout.X_AXIS));
panelTableDisadvantageANDThreat.setLayout(new BoxLayout(panelTableDisadvantageANDThreat, BoxLayout.X_AXIS));
panelLabelDisadvantageANDThreat.setLayout(new BoxLayout(panelLabelDisadvantageANDThreat, BoxLayout.X_AXIS));
//显示标签
labelAdvantage = new JLabel("优势");
labelChance = new JLabel("机会");
labelDisadvantage = new JLabel("劣势");
labelThreat = new JLabel("威胁");
labelActorName = new JLabel(swotActor.getActorName());
tableAdvantage = initializeTable("advantage");
tableChance = initializeTable("chance");
tableDisadvantage = initializeTable("disadvantage");
tableThreat = initializeTable("threat");
//将table装入JSplitPane
scrollpaneTableAdvantage = new JScrollPane(tableAdvantage);
scrollpaneTableChance = new JScrollPane(tableChance);
scrollpaneTableDisadvantage = new JScrollPane(tableDisadvantage);
scrollpaneTableThreat = new JScrollPane(tableThreat);
//右键菜单
popupMenu = new JPopupMenu();
popmenuItemAddProperty = new JMenuItem("添加");
popmenuItemDeleteProperty = new JMenuItem("删除");
popmenuItemModifyProperty = new JMenuItem("修改");
popmenuItemAddProperty.addActionListener(this);
popmenuItemDeleteProperty.addActionListener(this);
popmenuItemModifyProperty.addActionListener(this);
}
public void layoutComponent() {
panelLabelAdvantageANDChance.add(labelAdvantage);
panelLabelAdvantageANDChance.add(Box.createHorizontalGlue());
panelLabelAdvantageANDChance.add(labelChance);
panelLabelAdvantageANDChance.add(Box.createHorizontalGlue());
panelTableAdvantageANDChance.add(scrollpaneTableAdvantage);
panelTableAdvantageANDChance.add(scrollpaneTableChance);
panelLabelActorName.add(labelActorName);
panelLabelDisadvantageANDThreat.add(labelDisadvantage);
panelLabelDisadvantageANDThreat.add(Box.createHorizontalGlue());
panelLabelDisadvantageANDThreat.add(labelThreat);
panelLabelDisadvantageANDThreat.add(Box.createHorizontalGlue());
panelTableDisadvantageANDThreat.add(scrollpaneTableDisadvantage);
panelTableDisadvantageANDThreat.add(scrollpaneTableThreat);
add(panelLabelAdvantageANDChance);
add(panelTableAdvantageANDChance);
add(panelLabelActorName);
add(panelLabelDisadvantageANDThreat);
add(panelTableDisadvantageANDThreat);
popupMenu.add(popmenuItemAddProperty);
popupMenu.add(popmenuItemDeleteProperty);
popupMenu.add(popmenuItemModifyProperty);
}
public JTable initializeTable(final String tableType) {
dtm = new DefaultTableModel() {
/**
*
*/
private static final long serialVersionUID = 1L;
public Class<String> getColumnClass(int columnIndex) {
return String.class;
}
public boolean isCellEditable(int row, int column) { //不可编辑,变成双击弹出修改框
return false;
}
};
dtm.setDataVector(
new Object[][]{
{"", "", -1}
},
new Object[] {"编号", "内容", "PropertyID"}
);
final JTable table = new JTable(dtm);
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setMaxWidth(40);
columnModel.getColumn(0).setPreferredWidth(40);
columnModel.removeColumn(columnModel.getColumn(2)); //第三列为隐藏列,存储属性ID,便于deleteProperty。获得remove掉的列的data必须使用TableModel
table.setDefaultRenderer(String.class, new MultiLineTableCellRender()); //渲染成可换行
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
selectedTableRow = table.rowAtPoint(e.getPoint()); //getSelectedRow()对于右键无效,值为-1
if(e.getButton() == MouseEvent.BUTTON3) { //监听 <SUF>
popupMenu.show(e.getComponent(), e.getX(), e.getY()); //在鼠标点击位置弹出右键菜单
} else if(e.getClickCount() == 2) { //监听双击菜单
if(getSelectedTable().getValueAt(0, 0) != "")
modifyProperty();
else
JOptionPane.showMessageDialog(null, "当前表格无内容,无法做修改操作", "",JOptionPane.INFORMATION_MESSAGE);
}
table.changeSelection(table.getSelectedRow(), table.getSelectedColumn(), true, false);
table.requestFocus();
propertyType = tableType; //标记当前选中的属性表格
}
});
return table;
}
public void addProperty() {
/*-------------初始化Start--------------*/
frameAddProperty = new JFrame("添加属性");
frameAddProperty.setSize(500, 400);
frameAddProperty.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frameAddProperty.setLocationRelativeTo( null );
frameAddProperty.getContentPane().setLayout(new BorderLayout());
panelAddProperty = new JPanel();
panelLayLabelInAddProperty = new JPanel();
panelLayTextareaInAddProperty = new JPanel();
panelLayButtonInAddProperty = new JPanel();
panelAddProperty.setLayout(new BoxLayout(panelAddProperty, BoxLayout.Y_AXIS));
panelLayTextareaInAddProperty.setLayout(new BoxLayout(panelLayTextareaInAddProperty, BoxLayout.X_AXIS));
panelLayButtonInAddProperty.setLayout(new BoxLayout(panelLayButtonInAddProperty, BoxLayout.X_AXIS));
lableContentInAddProperty = new JLabel("内容");
// lableRemark1InAddProperty = new JLabel("备注1");
// lableRemark2InPopmenuAddProperty = new JLabel("备注2");
textareaContentInAddProperty = new JTextArea(5,5);
textareaContentInAddProperty.setLineWrap(true); //支持自动换行
textareaContentInAddProperty.setBorder(BorderFactory.createTitledBorder(""));
// textareaRemark1InAddProperty = new JTextArea();
// textareaRemark2InAddProperty = new JTextArea();
// textareaRemark1InAddProperty.setLineWrap(true); //支持自动换行
// textareaRemark2InAddProperty.setLineWrap(true); //支持自动换行
// textareaContentInAddProperty.setMinimumSize(new Dimension(200,200));
// textareaContentInAddProperty.setMaximumSize(new Dimension(900,900));
// textareaRemark1InAddProperty.setMinimumSize(new Dimension(100,250));
// textareaRemark1InAddProperty.setMaximumSize(new Dimension(200,200));
// textareaRemark2InAddProperty.setMinimumSize(new Dimension(100,250));
// textareaRemark2InAddProperty.setMaximumSize(new Dimension(200,200));
buttonConfirmInAddProperty = new JButton("确定");
buttonCancelInAddProperty = new JButton("取消");
buttonConfirmInAddProperty.addActionListener(this);
buttonCancelInAddProperty.addActionListener(this);
/*-------------初始化End--------------*/
/*-------------布局Start--------------*/
panelLayLabelInAddProperty.add(lableContentInAddProperty);
panelLayTextareaInAddProperty.add(Box.createHorizontalStrut(20));
panelLayTextareaInAddProperty.add(textareaContentInAddProperty);
panelLayTextareaInAddProperty.add(Box.createHorizontalStrut(20));
// panelLayTextareaInAddProperty.add(lableRemark1InAddProperty);
// panelLayTextareaInAddProperty.add(textareaRemark1InAddProperty);
// panelLayTextareaInAddProperty.add(lableRemark2InPopmenuAddProperty);
// panelLayTextareaInAddProperty.add(textareaRemark2InAddProperty);
panelLayButtonInAddProperty.add(buttonConfirmInAddProperty);
panelLayButtonInAddProperty.add(Box.createHorizontalStrut(10));
panelLayButtonInAddProperty.add(buttonCancelInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(20));
panelAddProperty.add(panelLayLabelInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(5));
panelAddProperty.add(panelLayTextareaInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(10));
panelAddProperty.add(panelLayButtonInAddProperty);
panelAddProperty.add(Box.createVerticalStrut(20));
frameAddProperty.setContentPane(panelAddProperty);
frameAddProperty.setVisible(true);
/*-------------布局End--------------*/
}
public void deleteProperty() {
if(getSelectedTable().getValueAt(0, 0) != "") {
swotPropertyDAO.deletePropertyByID((int)(getSelectedTable().getModel().getValueAt(selectedTableRow, 2))); //获得remove掉的列的data必须使用TableModel
dtm = (DefaultTableModel)getSelectedTable().getModel();
dtm.removeRow(selectedTableRow);
if(getSelectedTable().getRowCount() == 0) {
dtm.addRow(new Object[]{"", "", -1});
}else {
for(int i = 0; i < dtm.getRowCount(); i++) {
dtm.setValueAt(i + 1, i, 0);
}
}
}else {
JOptionPane.showMessageDialog(null, "当前表格无内容,无法做删除内容操作", "",JOptionPane.INFORMATION_MESSAGE);
}
}
//修改属性内容面板START(双击单元格)
public void modifyProperty() {
/*-------------初始化Start--------------*/
frameModifyProperty = new JFrame("修改属性");
frameModifyProperty.setSize(500, 400);
frameModifyProperty.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frameModifyProperty.setLocationRelativeTo( null );
panelModifyProperty = new JPanel();
panelModifyProperty = new JPanel();
panelLayLabelInModifyProperty = new JPanel();
panelLaytextAreaContentInModifyProperty = new JPanel();
panelLayButtonInModifyProperty = new JPanel();
panelModifyProperty.setLayout(new BoxLayout(panelModifyProperty, BoxLayout.Y_AXIS));
panelLaytextAreaContentInModifyProperty.setLayout(new BoxLayout(panelLaytextAreaContentInModifyProperty, BoxLayout.X_AXIS));
panelLayButtonInModifyProperty.setLayout(new BoxLayout(panelLayButtonInModifyProperty, BoxLayout.X_AXIS));
lablePropertyContentInModifyProperty=new JLabel("内容");
textAreaPropertyContentInModifyProperty = new JTextArea(5,5);
textAreaPropertyContentInModifyProperty.setText((String) getSelectedTable().getValueAt(selectedTableRow, 1));
textAreaPropertyContentInModifyProperty.setLineWrap(true); //支持自动换行
textAreaPropertyContentInModifyProperty.setBorder(BorderFactory.createTitledBorder(""));
// textAreaPropertyContentInModifyProperty.setMinimumSize(new Dimension(100,80));
// textAreaPropertyContentInModifyProperty.setMaximumSize(new Dimension(150,130));
buttonConfirmInModifyProperty = new JButton("确定");
buttonCancelInModifyProperty = new JButton("取消");
buttonConfirmInModifyProperty.addActionListener(this);
buttonCancelInModifyProperty.addActionListener(this);
/*-------------初始化End--------------*/
/*-------------布局Start--------------*/
panelLayLabelInModifyProperty.add(lablePropertyContentInModifyProperty);
panelLaytextAreaContentInModifyProperty.add(Box.createHorizontalStrut(20));
panelLaytextAreaContentInModifyProperty.add(textAreaPropertyContentInModifyProperty);
panelLaytextAreaContentInModifyProperty.add(Box.createHorizontalStrut(20));
panelLayButtonInModifyProperty.add(buttonConfirmInModifyProperty);
panelLayButtonInModifyProperty.add(Box.createHorizontalStrut(10));
panelLayButtonInModifyProperty.add(buttonCancelInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(20));
panelModifyProperty.add(panelLayLabelInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(5));
panelModifyProperty.add(panelLaytextAreaContentInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(10));
panelModifyProperty.add(panelLayButtonInModifyProperty);
panelModifyProperty.add(Box.createVerticalStrut(20));
frameModifyProperty.setContentPane(panelModifyProperty);
frameModifyProperty.setVisible(true);
/*-------------布局End--------------*/
}
//修改属性内容面板END
//返回当前选中的table
public JTable getSelectedTable() {
if(propertyType.equals("advantage")) {
return tableAdvantage;
}
else if(propertyType.equals("chance")) {
return tableChance;
}
else if(propertyType.equals("disadvantage")) {
return tableDisadvantage;
}
else if(propertyType.equals("threat")) {
return tableThreat;
}
return null;
}
//查询面板所用
public JTable getInsertTable(String PropertyType) {
if(PropertyType.equals("advantage")) {
return tableAdvantage;
}
else if(PropertyType.equals("chance")) {
return tableChance;
}
else if(PropertyType.equals("disadvantage")) {
return tableDisadvantage;
}
else if(PropertyType.equals("threat")) {
return tableThreat;
}
return null;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == popmenuItemAddProperty) { //右键菜单添加属性
addProperty();
}
else if(e.getSource() == popmenuItemDeleteProperty) {
deleteProperty();
}
else if(e.getSource() == popmenuItemModifyProperty) {
if(getSelectedTable().getValueAt(0, 0) != "")
modifyProperty();
else
JOptionPane.showMessageDialog(null, "当前表格无内容,无法做修改操作", "",JOptionPane.INFORMATION_MESSAGE);
}
else if(e.getSource() == buttonConfirmInModifyProperty) {
SwotActorProperty swotActorProperty = new SwotActorProperty();
swotActorProperty.setPropertyID((int)(getSelectedTable().getModel().getValueAt(selectedTableRow, 2))); //获得remove掉的列的data必须使用TableModel
swotActorProperty.setPropertyContent(textAreaPropertyContentInModifyProperty.getText());
// swotActorProperty.setPropertyMark1
// swotActorProperty.setPropertyMark2
swotPropertyDAO.updateProperty(swotActorProperty);
getSelectedTable().setValueAt(swotActorProperty.getPropertyContent(), selectedTableRow, 1);
}
else if(e.getSource() == buttonCancelInModifyProperty) {
frameModifyProperty.dispose();
}
else if(e.getSource() == buttonConfirmInAddProperty) {
SwotActorProperty swotActorProperty = new SwotActorProperty();
swotActorProperty.setPropertyType(propertyType);
swotActorProperty.setPropertyContent(textareaContentInAddProperty.getText());
swotPropertyDAO.addProperty(swotActor, swotActorProperty);
dtm = (DefaultTableModel)getSelectedTable().getModel();
if(dtm.getValueAt(0, 0) == "") {
dtm.setValueAt(1, 0, 0);
dtm.setValueAt(swotActorProperty.getPropertyContent(), 0, 1);
dtm.setValueAt(swotActorProperty.getPropertyID(), 0, 2);
} else{
dtm.addRow(new Object[]{dtm.getRowCount()+1, swotActorProperty.getPropertyContent(), swotActorProperty.getPropertyID()});
}
buttonConfirmInAddProperty.setText("继续添加");
textareaContentInAddProperty.setText("");
// textareaRemark1InAddProperty.setText("");
// textareaRemark2InAddProperty.setText("");
}
else if(e.getSource() == buttonCancelInAddProperty) {
frameAddProperty.dispose();
}
}
}
| 1 | 8 | 1 |
24900_80 | package so.asch.sdk;
/**
* Asch UIA接口
* @author eagle
*/
public interface UIA extends AschInterface {
//获取全网所有发行商
//接口地址:/api/uia/issuers
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//issuers list 元素为字典,每个字典代表一个发行商,包含发行商名字、描述、id(Asch地址)
//count integer 发行商总个数
AschResult getIssuers(int limit, int offset);
//查询指定发行商的信息
//接口地址:/api/uia/issuers/name 请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 可以为发行商名称或Asch账户地址
//返回参数说明:
//success boole 是否成功
//issuers dict 包含发行商名字、描述、id(Asch地址)
AschResult getIssuer(String nameOrAddress);
//查看指定发行商的资产
//接口地址:/api/uia/issuers/name/assets
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 可以为发行商名称或Asch账户地址
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限(最大发行量=真实发行量*10**精度)、精度、
// 策略、当前发行量、发行高度、发行商id,acl模式(0:黑名单,1:白名单)、是否注销
//count interger 该发行商注册的资产总个数(包含已注销的)
AschResult queryIssuerAssets(String nameOrAddress, int limit, int offset);
//获取全网所有资产
//接口地址:/api/uia/assets
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销
//count integer 所有资产的个数
AschResult getAssets(int limit, int offset);
//获取指定资产信息
//接口地址:/api/uia/assets/name
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 资产名
//返回参数说明:
//success boole 是否成功
//assets dict 包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销
AschResult getAsset(String assertName);
//获取某个资产的访问控制列表(acl)
//接口地址:/api/uia/assets/name/acl/flag 请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 资产名
//flag boole Y 取值0和1,0表示黑名单,1表示白名单
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//list list 符合规则的账户列表
//count integer 符合规则账户总数
AschResult getAssetACL(String assertName, boolean whiteOrBlack, int limit, int offset);
//获取某个地址拥有的所有资产信息
//接口地址:/api/uia/balances/address 请求方式:get
//支持格式:urlencoded
//请求参数说明:
//address string Y 账户地址
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//balances list 拥有的资产详情列表,每个元素是一个资产,包含资产名、余额、上限、精度、当前发行量、是否注销(0:未注销,1:已注销)
//count integer 当前该地址拥有的资产个数
AschResult getAddressBalances(String address, int limit, int offset);
//获取资产交易记录
//接口地址:/api/uia/transactions
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//ownerPublicKey string N 公钥
//返回参数说明:
//success boole 是否成功
//transactions list 交易列表,每个元素是一个字典代表一次交易,包含交易id、区块高度、区块id、交易类型、时间戳、发送者公钥、发送者id、
// 接收者id(系统为空,如资产注册)、交易数量(资产交易都为0)、手续费0.1XAS、签名、多重签名、确认数、
// 资产信息(包含发行商id、发行商名字、描述)、交易id。
//count integer 资产交易总个数
AschResult getTransactions(String ownerPublicKey, int limit, int offset);
//注册资产发行商
//请求参数说明:
//name string Y 名称
//desc string Y 描述
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult createIssuer(String name, String desc, String secret, String secondSecret);
//注册资产
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//desc string Y 资产描述
//maximum integer Y 上限
//precision integer Y 精度(maximum = '1000000',精度为3,代表资产IssuerName.CNY的最大发行量为1000.000)
//strategy string Y 策略
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult createAsset(String currency, String desc, long maximum, byte precision, String strategy, String secret, String secondSecret);
//资产设置acl模式
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType)
//whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult setAssetACL(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret);
//资产发行
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult issue(String currency, long amount, String secret, String secondSecret);
//资产转账
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度
//recipientId string Y 接收人
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult transfer(String currency, String recipientId, long amount, String message, String secret, String secondSecret);
//资产注销
//资产设置acl模式
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType)
//whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult setAssetStatus(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret);
}
| AschPlatform/asch-java | src/so/asch/sdk/UIA.java | 2,422 | //请求参数说明: | line_comment | zh-cn | package so.asch.sdk;
/**
* Asch UIA接口
* @author eagle
*/
public interface UIA extends AschInterface {
//获取全网所有发行商
//接口地址:/api/uia/issuers
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//issuers list 元素为字典,每个字典代表一个发行商,包含发行商名字、描述、id(Asch地址)
//count integer 发行商总个数
AschResult getIssuers(int limit, int offset);
//查询指定发行商的信息
//接口地址:/api/uia/issuers/name 请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 可以为发行商名称或Asch账户地址
//返回参数说明:
//success boole 是否成功
//issuers dict 包含发行商名字、描述、id(Asch地址)
AschResult getIssuer(String nameOrAddress);
//查看指定发行商的资产
//接口地址:/api/uia/issuers/name/assets
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 可以为发行商名称或Asch账户地址
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限(最大发行量=真实发行量*10**精度)、精度、
// 策略、当前发行量、发行高度、发行商id,acl模式(0:黑名单,1:白名单)、是否注销
//count interger 该发行商注册的资产总个数(包含已注销的)
AschResult queryIssuerAssets(String nameOrAddress, int limit, int offset);
//获取全网所有资产
//接口地址:/api/uia/assets
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销
//count integer 所有资产的个数
AschResult getAssets(int limit, int offset);
//获取指定资产信息
//接口地址:/api/uia/assets/name
//请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 资产名
//返回参数说明:
//success boole 是否成功
//assets dict 包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销
AschResult getAsset(String assertName);
//获取某个资产的访问控制列表(acl)
//接口地址:/api/uia/assets/name/acl/flag 请求方式:get
//支持格式:urlencoded
//请求参数说明:
//name string Y 资产名
//flag boole Y 取值0和1,0表示黑名单,1表示白名单
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//list list 符合规则的账户列表
//count integer 符合规则账户总数
AschResult getAssetACL(String assertName, boolean whiteOrBlack, int limit, int offset);
//获取某个地址拥有的所有资产信息
//接口地址:/api/uia/balances/address 请求方式:get
//支持格式:urlencoded
//请求参数说明:
//address string Y 账户地址
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//返回参数说明:
//success boole 是否成功
//balances list 拥有的资产详情列表,每个元素是一个资产,包含资产名、余额、上限、精度、当前发行量、是否注销(0:未注销,1:已注销)
//count integer 当前该地址拥有的资产个数
AschResult getAddressBalances(String address, int limit, int offset);
//获取资产交易记录
//接口地址:/api/uia/transactions
//请求方式:get
//支持格式:urlencoded
//请求 <SUF>
//limit integer N 限制结果集个数,最小值:0,最大值:100
//offset integer N 偏移量,最小值0
//ownerPublicKey string N 公钥
//返回参数说明:
//success boole 是否成功
//transactions list 交易列表,每个元素是一个字典代表一次交易,包含交易id、区块高度、区块id、交易类型、时间戳、发送者公钥、发送者id、
// 接收者id(系统为空,如资产注册)、交易数量(资产交易都为0)、手续费0.1XAS、签名、多重签名、确认数、
// 资产信息(包含发行商id、发行商名字、描述)、交易id。
//count integer 资产交易总个数
AschResult getTransactions(String ownerPublicKey, int limit, int offset);
//注册资产发行商
//请求参数说明:
//name string Y 名称
//desc string Y 描述
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult createIssuer(String name, String desc, String secret, String secondSecret);
//注册资产
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//desc string Y 资产描述
//maximum integer Y 上限
//precision integer Y 精度(maximum = '1000000',精度为3,代表资产IssuerName.CNY的最大发行量为1000.000)
//strategy string Y 策略
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult createAsset(String currency, String desc, long maximum, byte precision, String strategy, String secret, String secondSecret);
//资产设置acl模式
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType)
//whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult setAssetACL(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret);
//资产发行
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult issue(String currency, long amount, String secret, String secondSecret);
//资产转账
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度
//recipientId string Y 接收人
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult transfer(String currency, String recipientId, long amount, String message, String secret, String secondSecret);
//资产注销
//资产设置acl模式
//请求参数说明:
//currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY
//assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType)
//whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式
//secret string Y 一级密码
//secondSecret string Y 二级密码
//返回参数说明:
//success boole 是否成功
AschResult setAssetStatus(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret);
}
| 1 | 9 | 1 |
44165_11 | package Game;
import Thing.Square;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;
public class Player {
private final double walkSpeed = 16 / (double) (World.FPS);//一秒16格
private final double jumpSpeed = 0.5;//初始跳跃速度
private double verticalSpeed = 0;//实时垂直速度
private int hp = 10;
private int vp = 10;
private int dp = 0;//防御力
private Toolbar toolbar = new Toolbar();
private int handSquareNO = 0;
private Square chosenSquare;
private int chosenNumber;
private Point.Double location;//玩家脚底中心坐标,决定从何处开始渲染
private boolean isLegSwing = true;
Color head = Color.WHITE;
Color body = Color.WHITE;
Color arm = Color.WHITE;
Color leg = Color.WHITE;
int legSwing = 0;//腿部摆动的角度
int walkLeft = 0;//玩家是否在向左侧移动
int walkRight = 0;//玩家是否在向右侧移动
boolean isJumping = false;//玩家是否在跳跃
boolean isOpenBag = false;//玩家是否在查看背包
boolean isShowBorder = false;//显示放置范围
public int getChosenNumber() {
return chosenNumber;
}
public void setChosenNumber(int chosenNumber) {
this.chosenNumber = chosenNumber;
}
public synchronized Square getChosenSquare() {
return chosenSquare;
}
public synchronized void setChosenSquare(Square chosenSquare) {
this.chosenSquare = chosenSquare;
}
public synchronized void throwOutSquare() {
if (toolbar.getNumber()[handSquareNO] > 1)
toolbar.getNumber()[handSquareNO] -= 1;
else {
toolbar.getSquares()[handSquareNO] = null;
toolbar.getNumber()[handSquareNO] = 0;
}
}
public synchronized int getHandSquareNO() {
return handSquareNO;
}
public synchronized Square getHandSquare() {
return toolbar.getSquares()[handSquareNO];
}
public synchronized void setHandSquare(int i) {
handSquareNO = i;
}
public synchronized Point.Double getLocation() {
return location;
}
public synchronized void setHp(int hp) {
this.hp = hp;
}
public synchronized int getHp() {
return hp;
}
public synchronized int getDp() {
return dp;
}
public synchronized int getLegSwing() {
return legSwing;
}
Toolbar getToolbar() {
return toolbar;
}
private synchronized void setLegSwing() {
if (isLegSwing) {
legSwing += 1;
if (legSwing == 6)
isLegSwing = false;
} else {
legSwing -= 1;
if (legSwing == 0)
isLegSwing = true;
}
}
public void setHeadColor(Color color) {
head = color;
}
public void setBodyColor(Color color) {
body = color;
}
public void setArmColor(Color color) {
arm = color;
}
public void setLegColor(Color color) {
leg = color;
}
public Player() {
location = World.startLocation;
}
public void updatePlayer(){
int walk = walkRight - walkLeft;
if (walk == -1) {
double targetX = location.x - walkSpeed;
Square square = World.worldSquare[(int) targetX][(int) location.y];
if (square == null)
location.x = targetX;
else {
if (!square.through)
location.x = Math.ceil(targetX);
else
location.x = targetX;
}
} else if (walk == 1) {
double targetX = location.x + walkSpeed;
Square square = World.worldSquare[(int) targetX][(int) location.y];
if (square == null)
location.x = targetX;
else {
if (!square.through)
location.x = (int) targetX - 0.01;//防止被卡在墙里
else
location.x = targetX;
}
}
if (walk != 0 || getLegSwing() != 0) {
setLegSwing();
}
if(getLegSwing()==1&&isLegSwing&&World.worldSquare[(int) location.x][(int) (location.y+0.02)]!=null){
MusicThreadExecutor.playWalkSong();
}
//jump
if (isJumping && verticalSpeed == 0) {//准备起跳
verticalSpeed = -jumpSpeed;
} else if (verticalSpeed != 0 || World.worldSquare[(int) location.x][(int) (location.y)] == null) {
double targetY = location.y + verticalSpeed;
Square square = World.worldSquare[(int) location.x][(int) (targetY)];
if (verticalSpeed < 0 && square != null && !square.through) {//磕脑袋
location.y = Math.ceil(targetY);
verticalSpeed = 0;
} else if (verticalSpeed > 0 && square != null && !square.through) {//落地
location.y = (int) targetY - 0.01;//防止陷到地里出不来了
verticalSpeed = 0;
} else {
location.y = targetY;
if (verticalSpeed <= 1)
verticalSpeed += World.gravity;
}
}
}
}
| Asterism12/mineminecraft | src/Game/Player.java | 1,295 | //防止被卡在墙里 | line_comment | zh-cn | package Game;
import Thing.Square;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;
public class Player {
private final double walkSpeed = 16 / (double) (World.FPS);//一秒16格
private final double jumpSpeed = 0.5;//初始跳跃速度
private double verticalSpeed = 0;//实时垂直速度
private int hp = 10;
private int vp = 10;
private int dp = 0;//防御力
private Toolbar toolbar = new Toolbar();
private int handSquareNO = 0;
private Square chosenSquare;
private int chosenNumber;
private Point.Double location;//玩家脚底中心坐标,决定从何处开始渲染
private boolean isLegSwing = true;
Color head = Color.WHITE;
Color body = Color.WHITE;
Color arm = Color.WHITE;
Color leg = Color.WHITE;
int legSwing = 0;//腿部摆动的角度
int walkLeft = 0;//玩家是否在向左侧移动
int walkRight = 0;//玩家是否在向右侧移动
boolean isJumping = false;//玩家是否在跳跃
boolean isOpenBag = false;//玩家是否在查看背包
boolean isShowBorder = false;//显示放置范围
public int getChosenNumber() {
return chosenNumber;
}
public void setChosenNumber(int chosenNumber) {
this.chosenNumber = chosenNumber;
}
public synchronized Square getChosenSquare() {
return chosenSquare;
}
public synchronized void setChosenSquare(Square chosenSquare) {
this.chosenSquare = chosenSquare;
}
public synchronized void throwOutSquare() {
if (toolbar.getNumber()[handSquareNO] > 1)
toolbar.getNumber()[handSquareNO] -= 1;
else {
toolbar.getSquares()[handSquareNO] = null;
toolbar.getNumber()[handSquareNO] = 0;
}
}
public synchronized int getHandSquareNO() {
return handSquareNO;
}
public synchronized Square getHandSquare() {
return toolbar.getSquares()[handSquareNO];
}
public synchronized void setHandSquare(int i) {
handSquareNO = i;
}
public synchronized Point.Double getLocation() {
return location;
}
public synchronized void setHp(int hp) {
this.hp = hp;
}
public synchronized int getHp() {
return hp;
}
public synchronized int getDp() {
return dp;
}
public synchronized int getLegSwing() {
return legSwing;
}
Toolbar getToolbar() {
return toolbar;
}
private synchronized void setLegSwing() {
if (isLegSwing) {
legSwing += 1;
if (legSwing == 6)
isLegSwing = false;
} else {
legSwing -= 1;
if (legSwing == 0)
isLegSwing = true;
}
}
public void setHeadColor(Color color) {
head = color;
}
public void setBodyColor(Color color) {
body = color;
}
public void setArmColor(Color color) {
arm = color;
}
public void setLegColor(Color color) {
leg = color;
}
public Player() {
location = World.startLocation;
}
public void updatePlayer(){
int walk = walkRight - walkLeft;
if (walk == -1) {
double targetX = location.x - walkSpeed;
Square square = World.worldSquare[(int) targetX][(int) location.y];
if (square == null)
location.x = targetX;
else {
if (!square.through)
location.x = Math.ceil(targetX);
else
location.x = targetX;
}
} else if (walk == 1) {
double targetX = location.x + walkSpeed;
Square square = World.worldSquare[(int) targetX][(int) location.y];
if (square == null)
location.x = targetX;
else {
if (!square.through)
location.x = (int) targetX - 0.01;//防止 <SUF>
else
location.x = targetX;
}
}
if (walk != 0 || getLegSwing() != 0) {
setLegSwing();
}
if(getLegSwing()==1&&isLegSwing&&World.worldSquare[(int) location.x][(int) (location.y+0.02)]!=null){
MusicThreadExecutor.playWalkSong();
}
//jump
if (isJumping && verticalSpeed == 0) {//准备起跳
verticalSpeed = -jumpSpeed;
} else if (verticalSpeed != 0 || World.worldSquare[(int) location.x][(int) (location.y)] == null) {
double targetY = location.y + verticalSpeed;
Square square = World.worldSquare[(int) location.x][(int) (targetY)];
if (verticalSpeed < 0 && square != null && !square.through) {//磕脑袋
location.y = Math.ceil(targetY);
verticalSpeed = 0;
} else if (verticalSpeed > 0 && square != null && !square.through) {//落地
location.y = (int) targetY - 0.01;//防止陷到地里出不来了
verticalSpeed = 0;
} else {
location.y = targetY;
if (verticalSpeed <= 1)
verticalSpeed += World.gravity;
}
}
}
}
| 1 | 9 | 1 |
56305_2 | package com.jvm;
/**
* 新生代配置
* -Xmn:可以设置新生代的大小,设值一个比较打的新生代会减少老年代的大小,
* 这个参数对系统性能以及GC行为有很大影响,新生代大小一般会设值整
* 个堆空间的 1/3 到 1/4 左右;
*
* -XX:SurvivorRatio:
* 用来设值新生代中 eden 空间和 from/to 空间的比例
* -XX:SurvivorRatio = eden / from = eden / to
*
* -XX:NewRatio:
* 设值新生代和老年代的比例
* -XX:NewRatio = 老年代 / 新生代
*
* 基本策略:尽可能将对象预留在新生代中,减少老年代的GC次数
*/
public class Jvm2 {
/**
* 第一次配置 eden 2 = from 1 + to 1
* -Xms20m -Xmx20m -Xmn1m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC
*
* 第二次配置 eden 2 = from 1 + to 1
* -Xms20m -Xmx20m -Xmn7m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC
*
* 第三次配置
* -XX:NewRatio = 老年代 / 新生代
* -Xms20m -Xmx20m -XX:NewRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC
*/
public static void main(String[] args) {
byte[] b = null;
//连续向系统申请10MB空间
for(int i = 0; i < 10; i ++){
b = new byte[1 * 1024 * 1024];
}
}
}
| Asura7969/JAVA8Demo | src/com/jvm/Jvm2.java | 488 | //连续向系统申请10MB空间 | line_comment | zh-cn | package com.jvm;
/**
* 新生代配置
* -Xmn:可以设置新生代的大小,设值一个比较打的新生代会减少老年代的大小,
* 这个参数对系统性能以及GC行为有很大影响,新生代大小一般会设值整
* 个堆空间的 1/3 到 1/4 左右;
*
* -XX:SurvivorRatio:
* 用来设值新生代中 eden 空间和 from/to 空间的比例
* -XX:SurvivorRatio = eden / from = eden / to
*
* -XX:NewRatio:
* 设值新生代和老年代的比例
* -XX:NewRatio = 老年代 / 新生代
*
* 基本策略:尽可能将对象预留在新生代中,减少老年代的GC次数
*/
public class Jvm2 {
/**
* 第一次配置 eden 2 = from 1 + to 1
* -Xms20m -Xmx20m -Xmn1m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC
*
* 第二次配置 eden 2 = from 1 + to 1
* -Xms20m -Xmx20m -Xmn7m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC
*
* 第三次配置
* -XX:NewRatio = 老年代 / 新生代
* -Xms20m -Xmx20m -XX:NewRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC
*/
public static void main(String[] args) {
byte[] b = null;
//连续 <SUF>
for(int i = 0; i < 10; i ++){
b = new byte[1 * 1024 * 1024];
}
}
}
| 1 | 15 | 1 |
24304_5 | /**
* @FileName: Main1.java
* @Package asura.framework.algorithm.sort
*
* @author zhangshaobin
* @created 2015年7月3日 上午9:54:18
*
* Copyright 2011-2015 asura
*/
package asura.framework.algorithm.sort;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.BitSet;
/**
* <p>
* NIO方式读取数据, 可以处理半行拼接
*
*
* 有N个500M以上的⼤大纯⽂文本⽂文件(N>10), 每个⽂文件中, 以换⾏行(\n)分隔, 每⾏行⼀一个数字(数字是
2^32⼤大⼩小以内 ⽆无符号正整数 乱序排列 有重复), 请找出位于数列中间的100个数字之和(去重后的)
* </p>
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author zhangshaobin
* @since 1.0
* @version 1.0
*/
public class Main1 {
/**
*
* 主程序
*
* args[0] = 文件夹路径 C:\\Users\\001\\Downloads\\sort
*
* @author zhangshaobin
* @created 2015年7月3日 上午10:28:57
*
* @param args
* @throws Exception
*/
public static void main(String []args) throws Exception {
long s = System.currentTimeMillis();
BitSet bs = new BitSet(Integer.MAX_VALUE);
String pathFile = "C:\\Users\\001\\Downloads\\sort"; // 文件路径
File dir = new File(pathFile);
if (dir.exists()) {
if (dir.isDirectory()) {
File [] files = dir.listFiles();
for (File f : files) {
System.out.println("---"+f.getAbsolutePath());
genBitSet(bs, f.getAbsolutePath());
}
} else {
genBitSet(bs, pathFile);
}
Jisuan.sum(bs);
} else {
System.out.println("老兄,文件夹路径错误!!!");
}
long e = System.currentTimeMillis();
System.out.println("耗时:"+(e-s));
}
/**
*
* 生成bitset对象
*
* @author zhangshaobin
* @created 2015年7月3日 上午10:01:44
*
* @return
*/
@SuppressWarnings("resource")
private static BitSet genBitSet(BitSet bs, String path){
try {
FileInputStream fin = new FileInputStream(path);
FileChannel fcin = fin.getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect(1024*1024*1); //10M 可以作为参数传过去
String last = "";
while (true) {
int flag = fcin.read(buffer);
if (flag == -1) {
break;
}
buffer.flip();
String bufferString = toString(buffer);
if (null != bufferString && bufferString.length() > 0) {
String [] lines = bufferString.split("\n");
int lines_length = lines.length;
if (null != lines && lines_length > 0) {
for (int i=0; i<lines_length-1; i++) {
if (i==0 && !"".equals(last)) {
bs.set(Integer.valueOf(last+lines[i]),true);
last = "";
} else {
bs.set(Integer.valueOf(lines[i]),true);
}
}
if (!bufferString.endsWith("\n")) {
last = lines[lines_length-1];
}
}
}
buffer.clear();
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bs;
}
/**
*
* 字节准换成字符
*
* @author zhangshaobin
* @created 2015年7月3日 上午9:59:41
*
* @param bb
* @return
*/
private static String toString(ByteBuffer bb) {
final byte[] bytes = new byte[bb.remaining()];
bb.duplicate().get(bytes);
return new String(bytes);
}
}
| AsuraTeam/asura | asura-algorithm/src/main/java/asura/framework/algorithm/sort/Main1.java | 1,237 | //10M 可以作为参数传过去 | line_comment | zh-cn | /**
* @FileName: Main1.java
* @Package asura.framework.algorithm.sort
*
* @author zhangshaobin
* @created 2015年7月3日 上午9:54:18
*
* Copyright 2011-2015 asura
*/
package asura.framework.algorithm.sort;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.BitSet;
/**
* <p>
* NIO方式读取数据, 可以处理半行拼接
*
*
* 有N个500M以上的⼤大纯⽂文本⽂文件(N>10), 每个⽂文件中, 以换⾏行(\n)分隔, 每⾏行⼀一个数字(数字是
2^32⼤大⼩小以内 ⽆无符号正整数 乱序排列 有重复), 请找出位于数列中间的100个数字之和(去重后的)
* </p>
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author zhangshaobin
* @since 1.0
* @version 1.0
*/
public class Main1 {
/**
*
* 主程序
*
* args[0] = 文件夹路径 C:\\Users\\001\\Downloads\\sort
*
* @author zhangshaobin
* @created 2015年7月3日 上午10:28:57
*
* @param args
* @throws Exception
*/
public static void main(String []args) throws Exception {
long s = System.currentTimeMillis();
BitSet bs = new BitSet(Integer.MAX_VALUE);
String pathFile = "C:\\Users\\001\\Downloads\\sort"; // 文件路径
File dir = new File(pathFile);
if (dir.exists()) {
if (dir.isDirectory()) {
File [] files = dir.listFiles();
for (File f : files) {
System.out.println("---"+f.getAbsolutePath());
genBitSet(bs, f.getAbsolutePath());
}
} else {
genBitSet(bs, pathFile);
}
Jisuan.sum(bs);
} else {
System.out.println("老兄,文件夹路径错误!!!");
}
long e = System.currentTimeMillis();
System.out.println("耗时:"+(e-s));
}
/**
*
* 生成bitset对象
*
* @author zhangshaobin
* @created 2015年7月3日 上午10:01:44
*
* @return
*/
@SuppressWarnings("resource")
private static BitSet genBitSet(BitSet bs, String path){
try {
FileInputStream fin = new FileInputStream(path);
FileChannel fcin = fin.getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect(1024*1024*1); //10 <SUF>
String last = "";
while (true) {
int flag = fcin.read(buffer);
if (flag == -1) {
break;
}
buffer.flip();
String bufferString = toString(buffer);
if (null != bufferString && bufferString.length() > 0) {
String [] lines = bufferString.split("\n");
int lines_length = lines.length;
if (null != lines && lines_length > 0) {
for (int i=0; i<lines_length-1; i++) {
if (i==0 && !"".equals(last)) {
bs.set(Integer.valueOf(last+lines[i]),true);
last = "";
} else {
bs.set(Integer.valueOf(lines[i]),true);
}
}
if (!bufferString.endsWith("\n")) {
last = lines[lines_length-1];
}
}
}
buffer.clear();
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bs;
}
/**
*
* 字节准换成字符
*
* @author zhangshaobin
* @created 2015年7月3日 上午9:59:41
*
* @param bb
* @return
*/
private static String toString(ByteBuffer bb) {
final byte[] bytes = new byte[bb.remaining()];
bb.duplicate().get(bytes);
return new String(bytes);
}
}
| 1 | 17 | 1 |
3274_6 | package com.asura.monitor.util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.asura.common.response.ResponseVo;
import com.asura.monitor.graph.entity.PushEntity;
import com.asura.monitor.graph.util.FileRender;
import com.asura.monitor.graph.util.FileWriter;
import com.asura.util.CheckUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.asura.monitor.graph.util.FileWriter.dataDir;
/**
* <p></p>
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author zhaozq
* @version 1.0
* @since 1.0
*/
public class MonitorUtil {
public static final String separator = System.getProperty("file.separator");
public static final Logger logger = LoggerFactory.getLogger(MonitorUtil.class);
/**
*
* @param lentity
* @return
*/
public static List<PushEntity> getPushEntity(String lentity){
if( null != lentity ) {
Type type = new TypeToken<ArrayList<PushEntity>>() {
}.getType();
List<PushEntity> list = new Gson().fromJson(lentity, type);
return list;
}
return new ArrayList<>();
}
/**
* @param lentity
*/
public static void writePush(String lentity, String writeType, String ip, Map<String, Long> map){
try {
List<PushEntity> list = getPushEntity(lentity);
if (null != map) {
if (!map.containsKey("indexCounter")) {
map.put("indexCounter", Long.valueOf(list.size()));
}else{
map.put("indexCounter", map.get("indexCounter")+ list.size());
}
}
for (PushEntity entity1 : list) {
if (null == entity1) {
continue;
}
pushMonitorData(entity1, writeType, ip);
}
}catch (Exception e){
logger.error("解析数据失败" + lentity, e);
}
}
/**
* 记录每个指标的服务器地址
* @param entity
*/
static void writeIndexHosts(PushEntity entity){
// 拼接文件目录
String dir = dataDir + separator + "graph" + separator +"index" +separator;
dir = dir + entity.getGroups()+"."+entity.getName()+separator;
dir = FileRender.replace(dir);
FileWriter.makeDirs(dir);
File file = new File(dir + "id");
if ( !file.exists() ) {
FileWriter.writeFile(dir + "id", entity.getScriptId(), false);
}
}
/**
*
* @param entity
* @param writeType
* @param ipAddr
*/
public static void pushMonitorData(PushEntity entity, String writeType, String ipAddr) {
String historyName = FileRender.replace(entity.getName());
String name = FileRender.replace(entity.getScriptId() +"_"
+ FileRender.replace(entity.getStatus())) + "_"
+ FileRender.replace(entity.getGroups())+ "_"+ FileRender.replace(entity.getName());
if ("2".equals(entity.getStatus())){
logger.info(name);
}
String groups = FileRender.replace(entity.getGroups());
String value = entity.getValue();
// 记录每个指标的服务器地址
writeIndexHosts(entity);
// 获取客户端IP
if (null != entity.getIp() && entity.getIp().length() > 7 ) {
ipAddr = FileRender.replace(entity.getIp());
}
// 只将数据写入到文件
if (CheckUtil.checkString(name) && CheckUtil.checkString(value)) {
// 画图数据生成
FileWriter.writeHistory(groups, ipAddr, historyName, value);
if(writeType.equals("success")) {
// 监控历史数据生成
if (CheckUtil.checkString(entity.getServer())) {
FileWriter.writeMonitorHistory(FileRender.replace(entity.getServer()), name, entity);
}
}
}
}
public static String getStopMonitorTime(long value){
if (value < 60 ) {
return "还有" + value + "秒恢复";
}
if (value > 60 && value < 3600 ) {
return "还有" + ( value / 60 ) +"分钟恢复";
}
if (value > 3600 && value < 86400 ) {
return "还有" + (value / 60 / 60) + "小时恢复";
}
if (value > 86400 && value < 604800 ) {
return "还有" +( value / 60 / 60 / 24) +"天恢复";
}
if (value > 604800 && value < 2419200 ){
return "还有" +( value / 60 / 60 / 24 / 7 ) +"周恢复";
}
return "监控正常报警中";
}
}
| AsuraTeam/monitor | server/src/main/java/com/asura/monitor/util/MonitorUtil.java | 1,319 | // 记录每个指标的服务器地址
| line_comment | zh-cn | package com.asura.monitor.util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.asura.common.response.ResponseVo;
import com.asura.monitor.graph.entity.PushEntity;
import com.asura.monitor.graph.util.FileRender;
import com.asura.monitor.graph.util.FileWriter;
import com.asura.util.CheckUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.asura.monitor.graph.util.FileWriter.dataDir;
/**
* <p></p>
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author zhaozq
* @version 1.0
* @since 1.0
*/
public class MonitorUtil {
public static final String separator = System.getProperty("file.separator");
public static final Logger logger = LoggerFactory.getLogger(MonitorUtil.class);
/**
*
* @param lentity
* @return
*/
public static List<PushEntity> getPushEntity(String lentity){
if( null != lentity ) {
Type type = new TypeToken<ArrayList<PushEntity>>() {
}.getType();
List<PushEntity> list = new Gson().fromJson(lentity, type);
return list;
}
return new ArrayList<>();
}
/**
* @param lentity
*/
public static void writePush(String lentity, String writeType, String ip, Map<String, Long> map){
try {
List<PushEntity> list = getPushEntity(lentity);
if (null != map) {
if (!map.containsKey("indexCounter")) {
map.put("indexCounter", Long.valueOf(list.size()));
}else{
map.put("indexCounter", map.get("indexCounter")+ list.size());
}
}
for (PushEntity entity1 : list) {
if (null == entity1) {
continue;
}
pushMonitorData(entity1, writeType, ip);
}
}catch (Exception e){
logger.error("解析数据失败" + lentity, e);
}
}
/**
* 记录每个指标的服务器地址
* @param entity
*/
static void writeIndexHosts(PushEntity entity){
// 拼接文件目录
String dir = dataDir + separator + "graph" + separator +"index" +separator;
dir = dir + entity.getGroups()+"."+entity.getName()+separator;
dir = FileRender.replace(dir);
FileWriter.makeDirs(dir);
File file = new File(dir + "id");
if ( !file.exists() ) {
FileWriter.writeFile(dir + "id", entity.getScriptId(), false);
}
}
/**
*
* @param entity
* @param writeType
* @param ipAddr
*/
public static void pushMonitorData(PushEntity entity, String writeType, String ipAddr) {
String historyName = FileRender.replace(entity.getName());
String name = FileRender.replace(entity.getScriptId() +"_"
+ FileRender.replace(entity.getStatus())) + "_"
+ FileRender.replace(entity.getGroups())+ "_"+ FileRender.replace(entity.getName());
if ("2".equals(entity.getStatus())){
logger.info(name);
}
String groups = FileRender.replace(entity.getGroups());
String value = entity.getValue();
// 记录 <SUF>
writeIndexHosts(entity);
// 获取客户端IP
if (null != entity.getIp() && entity.getIp().length() > 7 ) {
ipAddr = FileRender.replace(entity.getIp());
}
// 只将数据写入到文件
if (CheckUtil.checkString(name) && CheckUtil.checkString(value)) {
// 画图数据生成
FileWriter.writeHistory(groups, ipAddr, historyName, value);
if(writeType.equals("success")) {
// 监控历史数据生成
if (CheckUtil.checkString(entity.getServer())) {
FileWriter.writeMonitorHistory(FileRender.replace(entity.getServer()), name, entity);
}
}
}
}
public static String getStopMonitorTime(long value){
if (value < 60 ) {
return "还有" + value + "秒恢复";
}
if (value > 60 && value < 3600 ) {
return "还有" + ( value / 60 ) +"分钟恢复";
}
if (value > 3600 && value < 86400 ) {
return "还有" + (value / 60 / 60) + "小时恢复";
}
if (value > 86400 && value < 604800 ) {
return "还有" +( value / 60 / 60 / 24) +"天恢复";
}
if (value > 604800 && value < 2419200 ){
return "还有" +( value / 60 / 60 / 24 / 7 ) +"周恢复";
}
return "监控正常报警中";
}
}
| 1 | 16 | 1 |
26582_5 | package cn.utils;
import cn.domain.Admin;
import cn.domain.Users;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import io.jsonwebtoken.*;
import java.util.Date;
import java.util.UUID;
//需要导入java-jwt / jjwt 两个依赖
public class JwtUtil {
//秘钥, 随便
private static final String secretKey="[email protected]!Y#$%&()^><ioasf";
/**
* 生成 JWT TOKEN
* @param user 用户信息
* @return String token
*/
public static String createToken(Users user){
JwtBuilder jwtBuilder = Jwts.builder();
String token = jwtBuilder
//header 固定
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg", "HS256")
//payload 传输的数据
.claim("userId", user.getUserId())
.claim("userName", user.getUserEmail())
.setSubject("admin-test")
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) //过期时间为1h
.setId(UUID.randomUUID().toString())
//signature 签名 固定
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
return token;
}
/**
* 解析 JWT TOKEN
* @param token JWT TOKEN
* @return User user
*/
public static Users parse(String token){
JwtParser parser = Jwts.parser();
Jws<Claims> claimsJws = parser.setSigningKey(secretKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
System.out.println(claims.get("userId"));
System.out.println(claims.get("userName"));
System.out.println(claims.getId());
System.out.println(claims.getSubject());
System.out.println(claims.getExpiration());
Users user=new Users();
user.setUserId(Long.valueOf(claims.get("userId").toString()));
user.setUserEmail((String)claims.get("userName"));
return user;
}
}
| Ataraxia24/cat | src/main/java/cn/utils/JwtUtil.java | 513 | //过期时间为1h | line_comment | zh-cn | package cn.utils;
import cn.domain.Admin;
import cn.domain.Users;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import io.jsonwebtoken.*;
import java.util.Date;
import java.util.UUID;
//需要导入java-jwt / jjwt 两个依赖
public class JwtUtil {
//秘钥, 随便
private static final String secretKey="[email protected]!Y#$%&()^><ioasf";
/**
* 生成 JWT TOKEN
* @param user 用户信息
* @return String token
*/
public static String createToken(Users user){
JwtBuilder jwtBuilder = Jwts.builder();
String token = jwtBuilder
//header 固定
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg", "HS256")
//payload 传输的数据
.claim("userId", user.getUserId())
.claim("userName", user.getUserEmail())
.setSubject("admin-test")
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) //过期 <SUF>
.setId(UUID.randomUUID().toString())
//signature 签名 固定
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
return token;
}
/**
* 解析 JWT TOKEN
* @param token JWT TOKEN
* @return User user
*/
public static Users parse(String token){
JwtParser parser = Jwts.parser();
Jws<Claims> claimsJws = parser.setSigningKey(secretKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
System.out.println(claims.get("userId"));
System.out.println(claims.get("userName"));
System.out.println(claims.getId());
System.out.println(claims.getSubject());
System.out.println(claims.getExpiration());
Users user=new Users();
user.setUserId(Long.valueOf(claims.get("userId").toString()));
user.setUserEmail((String)claims.get("userName"));
return user;
}
}
| 1 | 9 | 1 |
20868_75 | package com.bixin.nft.bean.DO;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* @Class: NftKikoCatDo
* @Description: NFT Kiko猫信息表
* @author: 系统
* @created: 2021-12-30
*/
@Data
public class NftKikoCatDo implements Serializable {
/**
* 主键id
*/
private Long id;
/**
* nft_Info id
*/
private Long infoId;
/**
* 背景
*/
private String background;
/**
* 背景分
*/
private BigDecimal backgroundScore;
/**
* 皮毛
*/
private String fur;
/**
* 皮毛分
*/
private BigDecimal furScore;
/**
* 衣服
*/
private String clothes;
/**
* 衣服分
*/
private BigDecimal clothesScore;
/**
* 表情
*/
private String facialExpression;
/**
* 表情分
*/
private BigDecimal facialExpressionScore;
/**
* 头部
*/
private String head;
/**
* 头部分
*/
private BigDecimal headScore;
/**
* 配饰
*/
private String accessories;
/**
* 配饰分
*/
private BigDecimal accessoriesScore;
/**
* 眼部
*/
private String eyes;
/**
* 眼部分
*/
private BigDecimal eyesScore;
/**
* 帽子
*/
private String hat;
/**
* 帽子分
*/
private BigDecimal hatScore;
/**
* 服装
*/
private String costume;
/**
* 服装分
*/
private BigDecimal costumeScore;
/**
* 妆容
*/
private String makeup;
/**
* 妆容分
*/
private BigDecimal makeupScore;
/**
* 鞋子
*/
private String shoes;
/**
* 鞋子分
*/
private BigDecimal shoesScore;
/**
* 嘴
*/
private String mouth;
/**
* 嘴分
*/
private BigDecimal mouthScore;
/**
* 耳环
*/
private String earring;
/**
* 耳环分
*/
private BigDecimal earringScore;
/**
* 项链
*/
private String necklace;
/**
* 项链分
*/
private BigDecimal necklaceScore;
/**
* 颈部
*/
private String neck;
/**
* 颈部分
*/
private BigDecimal neckScore;
/**
* 头发
*/
private String hair;
/**
* 头发分
*/
private BigDecimal hairScore;
/**
* 角
*/
private String horn;
/**
* 角分
*/
private BigDecimal hornScore;
/**
* 手
*/
private String hands;
/**
* 手分
*/
private BigDecimal handsScore;
/**
* 身体
*/
private String body;
/**
* 身体分
*/
private BigDecimal bodyScore;
/**
* 皮肤
*/
private String skin;
/**
* 皮肤分
*/
private BigDecimal skinScore;
/**
* 纹身
*/
private String tattoo;
/**
* 纹身分
*/
private BigDecimal tattooScore;
/**
* 人物
*/
private String people;
/**
* 人物分
*/
private BigDecimal peopleScore;
/**
* 性格
*/
private String characteristic;
/**
* 性格分
*/
private BigDecimal characteristicScore;
/**
* 爱好
*/
private String hobby;
/**
* 爱好分
*/
private BigDecimal hobbyScore;
/**
* 星座
*/
private String zodiac;
/**
* 星座分
*/
private BigDecimal zodiacScore;
/**
* 动作
*/
private String action;
/**
* 动作分
*/
private BigDecimal actionScore;
/**
* 玩具
*/
private String toys;
/**
* 玩具分
*/
private BigDecimal toysScore;
/**
* 水果
*/
private String fruits;
/**
* 水果分
*/
private BigDecimal fruitsScore;
/**
* 蔬菜
*/
private String vegetables;
/**
* 蔬菜分
*/
private BigDecimal vegetablesScore;
/**
* 肉类
*/
private String meat;
/**
* 肉类分
*/
private BigDecimal meatScore;
/**
* 饮料
*/
private String beverages;
/**
* 饮料分
*/
private BigDecimal beveragesScore;
/**
* 食物
*/
private String food;
/**
* 食物分
*/
private BigDecimal foodScore;
/**
* 交通工具
*/
private String vehicle;
/**
* 交通工具分
*/
private BigDecimal vehicleScore;
/**
* 天气
*/
private String weather;
/**
* 天气分
*/
private BigDecimal weatherScore;
/**
* 月份
*/
private String month;
/**
* 月份分
*/
private BigDecimal monthScore;
/**
* 运动
*/
private String sports;
/**
* 运动分
*/
private BigDecimal sportsScore;
/**
* 音乐
*/
private String music;
/**
* 音乐分
*/
private BigDecimal musicScore;
/**
* 电影
*/
private String movies;
/**
* 电影分
*/
private BigDecimal moviesScore;
/**
* 季节
*/
private String season;
/**
* 季节分
*/
private BigDecimal seasonScore;
/**
* 搭配
*/
private String outfit;
/**
* 搭配分
*/
private BigDecimal outfitScore;
/**
* 五官
*/
private String face;
/**
* 五官分
*/
private BigDecimal faceScore;
/**
* 手臂
*/
private String arm;
/**
* 手臂分
*/
private BigDecimal armScore;
/**
* 腿部
*/
private String leg;
/**
* 腿部分
*/
private BigDecimal legScore;
/**
* 脚
*/
private String foot;
/**
* 脚分
*/
private BigDecimal footScore;
/**
* 武器
*/
private String weapon;
/**
* 武器分
*/
private BigDecimal weaponScore;
/**
* 头盔
*/
private String helmet;
/**
* 头盔分
*/
private BigDecimal helmetScore;
/**
* 盔甲
*/
private String armor;
/**
* 盔甲分
*/
private BigDecimal armorScore;
/**
* 机甲
*/
private String mecha;
/**
* 机甲分
*/
private BigDecimal mechaScore;
/**
* 裤子
*/
private String pants;
/**
* 裤子分
*/
private BigDecimal pantsScore;
/**
* 裙子
*/
private String skirt;
/**
* 裙子分
*/
private BigDecimal skirtScore;
/**
*
*/
private Long createTime;
/**
*
*/
private Long updateTime;
private static final long serialVersionUID = 1L;
} | Atlas-YX-Studio/ido-server | src/main/java/com/bixin/nft/bean/DO/NftKikoCatDo.java | 1,782 | /**
* 音乐
*/ | block_comment | zh-cn | package com.bixin.nft.bean.DO;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* @Class: NftKikoCatDo
* @Description: NFT Kiko猫信息表
* @author: 系统
* @created: 2021-12-30
*/
@Data
public class NftKikoCatDo implements Serializable {
/**
* 主键id
*/
private Long id;
/**
* nft_Info id
*/
private Long infoId;
/**
* 背景
*/
private String background;
/**
* 背景分
*/
private BigDecimal backgroundScore;
/**
* 皮毛
*/
private String fur;
/**
* 皮毛分
*/
private BigDecimal furScore;
/**
* 衣服
*/
private String clothes;
/**
* 衣服分
*/
private BigDecimal clothesScore;
/**
* 表情
*/
private String facialExpression;
/**
* 表情分
*/
private BigDecimal facialExpressionScore;
/**
* 头部
*/
private String head;
/**
* 头部分
*/
private BigDecimal headScore;
/**
* 配饰
*/
private String accessories;
/**
* 配饰分
*/
private BigDecimal accessoriesScore;
/**
* 眼部
*/
private String eyes;
/**
* 眼部分
*/
private BigDecimal eyesScore;
/**
* 帽子
*/
private String hat;
/**
* 帽子分
*/
private BigDecimal hatScore;
/**
* 服装
*/
private String costume;
/**
* 服装分
*/
private BigDecimal costumeScore;
/**
* 妆容
*/
private String makeup;
/**
* 妆容分
*/
private BigDecimal makeupScore;
/**
* 鞋子
*/
private String shoes;
/**
* 鞋子分
*/
private BigDecimal shoesScore;
/**
* 嘴
*/
private String mouth;
/**
* 嘴分
*/
private BigDecimal mouthScore;
/**
* 耳环
*/
private String earring;
/**
* 耳环分
*/
private BigDecimal earringScore;
/**
* 项链
*/
private String necklace;
/**
* 项链分
*/
private BigDecimal necklaceScore;
/**
* 颈部
*/
private String neck;
/**
* 颈部分
*/
private BigDecimal neckScore;
/**
* 头发
*/
private String hair;
/**
* 头发分
*/
private BigDecimal hairScore;
/**
* 角
*/
private String horn;
/**
* 角分
*/
private BigDecimal hornScore;
/**
* 手
*/
private String hands;
/**
* 手分
*/
private BigDecimal handsScore;
/**
* 身体
*/
private String body;
/**
* 身体分
*/
private BigDecimal bodyScore;
/**
* 皮肤
*/
private String skin;
/**
* 皮肤分
*/
private BigDecimal skinScore;
/**
* 纹身
*/
private String tattoo;
/**
* 纹身分
*/
private BigDecimal tattooScore;
/**
* 人物
*/
private String people;
/**
* 人物分
*/
private BigDecimal peopleScore;
/**
* 性格
*/
private String characteristic;
/**
* 性格分
*/
private BigDecimal characteristicScore;
/**
* 爱好
*/
private String hobby;
/**
* 爱好分
*/
private BigDecimal hobbyScore;
/**
* 星座
*/
private String zodiac;
/**
* 星座分
*/
private BigDecimal zodiacScore;
/**
* 动作
*/
private String action;
/**
* 动作分
*/
private BigDecimal actionScore;
/**
* 玩具
*/
private String toys;
/**
* 玩具分
*/
private BigDecimal toysScore;
/**
* 水果
*/
private String fruits;
/**
* 水果分
*/
private BigDecimal fruitsScore;
/**
* 蔬菜
*/
private String vegetables;
/**
* 蔬菜分
*/
private BigDecimal vegetablesScore;
/**
* 肉类
*/
private String meat;
/**
* 肉类分
*/
private BigDecimal meatScore;
/**
* 饮料
*/
private String beverages;
/**
* 饮料分
*/
private BigDecimal beveragesScore;
/**
* 食物
*/
private String food;
/**
* 食物分
*/
private BigDecimal foodScore;
/**
* 交通工具
*/
private String vehicle;
/**
* 交通工具分
*/
private BigDecimal vehicleScore;
/**
* 天气
*/
private String weather;
/**
* 天气分
*/
private BigDecimal weatherScore;
/**
* 月份
*/
private String month;
/**
* 月份分
*/
private BigDecimal monthScore;
/**
* 运动
*/
private String sports;
/**
* 运动分
*/
private BigDecimal sportsScore;
/**
* 音乐
<SUF>*/
private String music;
/**
* 音乐分
*/
private BigDecimal musicScore;
/**
* 电影
*/
private String movies;
/**
* 电影分
*/
private BigDecimal moviesScore;
/**
* 季节
*/
private String season;
/**
* 季节分
*/
private BigDecimal seasonScore;
/**
* 搭配
*/
private String outfit;
/**
* 搭配分
*/
private BigDecimal outfitScore;
/**
* 五官
*/
private String face;
/**
* 五官分
*/
private BigDecimal faceScore;
/**
* 手臂
*/
private String arm;
/**
* 手臂分
*/
private BigDecimal armScore;
/**
* 腿部
*/
private String leg;
/**
* 腿部分
*/
private BigDecimal legScore;
/**
* 脚
*/
private String foot;
/**
* 脚分
*/
private BigDecimal footScore;
/**
* 武器
*/
private String weapon;
/**
* 武器分
*/
private BigDecimal weaponScore;
/**
* 头盔
*/
private String helmet;
/**
* 头盔分
*/
private BigDecimal helmetScore;
/**
* 盔甲
*/
private String armor;
/**
* 盔甲分
*/
private BigDecimal armorScore;
/**
* 机甲
*/
private String mecha;
/**
* 机甲分
*/
private BigDecimal mechaScore;
/**
* 裤子
*/
private String pants;
/**
* 裤子分
*/
private BigDecimal pantsScore;
/**
* 裙子
*/
private String skirt;
/**
* 裙子分
*/
private BigDecimal skirtScore;
/**
*
*/
private Long createTime;
/**
*
*/
private Long updateTime;
private static final long serialVersionUID = 1L;
} | 0 | 21 | 0 |
8430_9 | package com.attilax.util;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
* Created on 17/6/7. 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过
* 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) 工程依赖了2个jar包(存放在工程的libs目录下)
* 1:aliyun-java-sdk-core.jar 2:aliyun-java-sdk-dysmsapi.jar
*
* 备注:Demo工程编码采用UTF-8 国际短信发送请勿参照此DEMO
*/
public class AliyunMessageUtil {
// 产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
// 产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static final String accessKeyId = "LTAIMaVxNlD5pgSk";
static final String accessKeySecret = "6xBXmGbFsr42sgURwrX1JWLVJWFu3L";
public static SendSmsResponse sendSms(Map<String, String> paramMap) throws ClientException {
// 可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
// 初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
// 组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
// 必填:待发送手机号
request.setPhoneNumbers(paramMap.get("phoneNumber"));
// 必填:短信签名-可在短信控制台中找到
request.setSignName(paramMap.get("msgSign"));
// 必填:短信模板-可在短信控制台中找到
request.setTemplateCode(paramMap.get("templateCode"));
// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam(paramMap.get("jsonContent"));
// 选填-上行短信扩展码(无特殊需求用户请忽略此字段)
// request.setSmsUpExtendCode("90997");
// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
// request.setOutId("yourOutId");
// hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
return sendSmsResponse;
}
/**
* 生成随机数
*
* @param num 位数
* @return
*/
public static String createRandomNum(int num) {
String randomNumStr = "";
for (int i = 0; i < num; i++) {
int randomNum = (int) (Math.random() * 10);
randomNumStr += randomNum;
}
return randomNumStr;
}
public static void main(String[] args) throws ClientException {
String phoneNumber = "18821766710";
String randomNum = createRandomNum(6);
String jsonContent = "{\"code\":\"" + randomNum + "\"}";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("phoneNumber", phoneNumber);
paramMap.put("msgSign", "唐唐云学堂");
// paramMap.put("templateCode", "SMS_150495957");
paramMap.put("templateCode", "SMS_150495959");
paramMap.put("jsonContent", jsonContent);
SendSmsResponse sendSmsResponse = AliyunMessageUtil.sendSms(paramMap);
System.out.println("已发送");
System.out.println(JSON.toJSON(sendSmsResponse));
// {"code":"OK","requestId":"27392149-150C-440B-802A-590C422AFB60","bizId":"422313255463283685^0","message":"OK"}
if (!(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))) {
if (sendSmsResponse.getCode() == null) {
System.out.println(sendSmsResponse.getCode());
}
if (!sendSmsResponse.getCode().equals("OK")) {
System.out.println(sendSmsResponse.getCode() + "");
}
}
}
}
| Atlks/bookmarksHtmlEverythingIndexPrj | src/com/attilax/util/AliyunMessageUtil.java | 1,397 | // 必填:短信模板-可在短信控制台中找到
| line_comment | zh-cn | package com.attilax.util;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
* Created on 17/6/7. 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过
* 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) 工程依赖了2个jar包(存放在工程的libs目录下)
* 1:aliyun-java-sdk-core.jar 2:aliyun-java-sdk-dysmsapi.jar
*
* 备注:Demo工程编码采用UTF-8 国际短信发送请勿参照此DEMO
*/
public class AliyunMessageUtil {
// 产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
// 产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static final String accessKeyId = "LTAIMaVxNlD5pgSk";
static final String accessKeySecret = "6xBXmGbFsr42sgURwrX1JWLVJWFu3L";
public static SendSmsResponse sendSms(Map<String, String> paramMap) throws ClientException {
// 可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
// 初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
// 组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
// 必填:待发送手机号
request.setPhoneNumbers(paramMap.get("phoneNumber"));
// 必填:短信签名-可在短信控制台中找到
request.setSignName(paramMap.get("msgSign"));
// 必填 <SUF>
request.setTemplateCode(paramMap.get("templateCode"));
// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam(paramMap.get("jsonContent"));
// 选填-上行短信扩展码(无特殊需求用户请忽略此字段)
// request.setSmsUpExtendCode("90997");
// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
// request.setOutId("yourOutId");
// hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
return sendSmsResponse;
}
/**
* 生成随机数
*
* @param num 位数
* @return
*/
public static String createRandomNum(int num) {
String randomNumStr = "";
for (int i = 0; i < num; i++) {
int randomNum = (int) (Math.random() * 10);
randomNumStr += randomNum;
}
return randomNumStr;
}
public static void main(String[] args) throws ClientException {
String phoneNumber = "18821766710";
String randomNum = createRandomNum(6);
String jsonContent = "{\"code\":\"" + randomNum + "\"}";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("phoneNumber", phoneNumber);
paramMap.put("msgSign", "唐唐云学堂");
// paramMap.put("templateCode", "SMS_150495957");
paramMap.put("templateCode", "SMS_150495959");
paramMap.put("jsonContent", jsonContent);
SendSmsResponse sendSmsResponse = AliyunMessageUtil.sendSms(paramMap);
System.out.println("已发送");
System.out.println(JSON.toJSON(sendSmsResponse));
// {"code":"OK","requestId":"27392149-150C-440B-802A-590C422AFB60","bizId":"422313255463283685^0","message":"OK"}
if (!(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))) {
if (sendSmsResponse.getCode() == null) {
System.out.println(sendSmsResponse.getCode());
}
if (!sendSmsResponse.getCode().equals("OK")) {
System.out.println(sendSmsResponse.getCode() + "");
}
}
}
}
| 1 | 22 | 1 |
37447_18 | package testkg;
import com.alibaba.fastjson.JSONObject;
import com.im.action.AbstractAction;
import com.im.action.login.LoginAction;
import com.im.action.sys.GetSmsCodeAction;
import com.im.action.sys.UpdateUserKeyPairAction;
import com.im.filter.SignitureValidFilter;
import com.webkit.web.ActionException;
import com.webkit.web.FilterDispatcher;
import redis.clients.jedis.Jedis;
import spark.Spark;
import static spark.Spark.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class spk {
public static void main(String[] args) {
Spark.exception(RuntimeException.class, (exception, request, response) -> {
//exception.printStackTrace();
throw exception;
});
port(8088);
System.out.println(org.eclipse.jetty.server.Handler.class);
System.out.println(org.slf4j.helpers.MessageFormatter.class);
// System.out.println( org.slf4j.impl.StaticLoggerBinder.class);
get("/h", (req, res) -> "Hel..");
get("/hh", (req, res) -> "Hel222.");
postx("/im-biz/sys/getSmsCode", new GetSmsCodeAction());
postx("/im-biz/login/login", new LoginAction());
postx("/im-biz/sys/updateUserKeyPair", new UpdateUserKeyPairAction());
// post("/im-biz/sys/getSmsCode", (req, res) -> {
//
//
// HttpServletResponse resps= res.raw();
// HttpServletRequest reqst=req.raw();
//
//
// addFltr( reqst,resps);
// AbstractAction act1= new GetSmsCodeAction();
// act1.execute( resps.getOutputStream() );
//
// resps.flushBuffer();
// resps.getOutputStream().close();
// return resps;
//
//
//
// });
// get("/hh", extracted());
get("/p",
(req, res) -> {
// HttpServletRequest req2 = (HttpServletRequest) req;
// spark.http.matching.RequestWrapper req2=req;
// System.out.println(req2.getSession().getServletContext().getRealPath("/"));
// ;
HttpServletRequest req2 = req.raw();
String path = req2.getServletContext().getContextPath();
System.out.println(path);
String realPath = req2.getServletContext().getRealPath("/uploadFile");
System.out.println(realPath);
return 1;
});
get("/m", (req, res) -> {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
// 如果 Redis 服务设置了密码,需要下面这行,没有就不需要
jedis.auth(" ");
System.out.println("连接成功");
//查看服务是否运行
System.out.println("服务正在运行: " + jedis.ping());
System.out.println(jedis.get("fgfkkk"));
//while(true){
Object msgx = jedis.brpoplpush("msgx", "msgxHstry", 10);
String msg = JSONObject.toJSONString(msgx);
System.out.println(msg);
return msg;
});
}
static void postx(String path, AbstractAction act1) {
post(path, (req, res) -> {
HttpServletResponse resps = res.raw();
HttpServletRequest reqst = req.raw();
addFltr(reqst, resps);
act1.execute(resps.getOutputStream());
resps.flushBuffer();
resps.getOutputStream().close();
return resps;
});
}
private static void addFltr(HttpServletRequest reqst, HttpServletResponse resps) throws IOException, ServletException, ActionException, ClassNotFoundException {
SignitureValidFilter signitureValidFilter = new SignitureValidFilter();
signitureValidFilter.exceptURI = "/index.jsp,/tool/scheduleEvent";
signitureValidFilter.doFilter(reqst, resps, new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
}
});
// FilterConfig fc = new FilterConfig() {
// @Override
// public String getFilterName() {
// return "fltnm";
// }
//
// @Override
// public ServletContext getServletContext() {
// return reqst.getServletContext();
// }
//
// @Override
// public String getInitParameter(String s) {
// if (s.equals("charset"))
// return "utf8";
// return "";
// }
//
// @Override
// public Enumeration<String> getInitParameterNames() {
// return null;
// }
// };
// FilterDispatcher filterDispatcher = new FilterDispatcher();
// filterDispatcher.init(fc);
//
//
// filterDispatcher.doFilter(reqst, resps, new FilterChain() {
// @Override
// public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
//
// }
// });
//add ActionContext.getActionContext()
// ActionContext.getActionContext()
System.out.println(com.webkit.web.ActionContextWrp.class);
com.webkit.web.ActionContextWrp.createActionContext(reqst.getServletContext(), reqst, resps);
// Dispatcher.getInstance(). serviceAction(,, );
// Dispatcher.getInstance().setActionContext(null);
// ActionContext
}
}
| Atlks/sdkprj | nodesrc/testkg/spk.java | 1,373 | //查看服务是否运行 | line_comment | zh-cn | package testkg;
import com.alibaba.fastjson.JSONObject;
import com.im.action.AbstractAction;
import com.im.action.login.LoginAction;
import com.im.action.sys.GetSmsCodeAction;
import com.im.action.sys.UpdateUserKeyPairAction;
import com.im.filter.SignitureValidFilter;
import com.webkit.web.ActionException;
import com.webkit.web.FilterDispatcher;
import redis.clients.jedis.Jedis;
import spark.Spark;
import static spark.Spark.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class spk {
public static void main(String[] args) {
Spark.exception(RuntimeException.class, (exception, request, response) -> {
//exception.printStackTrace();
throw exception;
});
port(8088);
System.out.println(org.eclipse.jetty.server.Handler.class);
System.out.println(org.slf4j.helpers.MessageFormatter.class);
// System.out.println( org.slf4j.impl.StaticLoggerBinder.class);
get("/h", (req, res) -> "Hel..");
get("/hh", (req, res) -> "Hel222.");
postx("/im-biz/sys/getSmsCode", new GetSmsCodeAction());
postx("/im-biz/login/login", new LoginAction());
postx("/im-biz/sys/updateUserKeyPair", new UpdateUserKeyPairAction());
// post("/im-biz/sys/getSmsCode", (req, res) -> {
//
//
// HttpServletResponse resps= res.raw();
// HttpServletRequest reqst=req.raw();
//
//
// addFltr( reqst,resps);
// AbstractAction act1= new GetSmsCodeAction();
// act1.execute( resps.getOutputStream() );
//
// resps.flushBuffer();
// resps.getOutputStream().close();
// return resps;
//
//
//
// });
// get("/hh", extracted());
get("/p",
(req, res) -> {
// HttpServletRequest req2 = (HttpServletRequest) req;
// spark.http.matching.RequestWrapper req2=req;
// System.out.println(req2.getSession().getServletContext().getRealPath("/"));
// ;
HttpServletRequest req2 = req.raw();
String path = req2.getServletContext().getContextPath();
System.out.println(path);
String realPath = req2.getServletContext().getRealPath("/uploadFile");
System.out.println(realPath);
return 1;
});
get("/m", (req, res) -> {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
// 如果 Redis 服务设置了密码,需要下面这行,没有就不需要
jedis.auth(" ");
System.out.println("连接成功");
//查看 <SUF>
System.out.println("服务正在运行: " + jedis.ping());
System.out.println(jedis.get("fgfkkk"));
//while(true){
Object msgx = jedis.brpoplpush("msgx", "msgxHstry", 10);
String msg = JSONObject.toJSONString(msgx);
System.out.println(msg);
return msg;
});
}
static void postx(String path, AbstractAction act1) {
post(path, (req, res) -> {
HttpServletResponse resps = res.raw();
HttpServletRequest reqst = req.raw();
addFltr(reqst, resps);
act1.execute(resps.getOutputStream());
resps.flushBuffer();
resps.getOutputStream().close();
return resps;
});
}
private static void addFltr(HttpServletRequest reqst, HttpServletResponse resps) throws IOException, ServletException, ActionException, ClassNotFoundException {
SignitureValidFilter signitureValidFilter = new SignitureValidFilter();
signitureValidFilter.exceptURI = "/index.jsp,/tool/scheduleEvent";
signitureValidFilter.doFilter(reqst, resps, new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
}
});
// FilterConfig fc = new FilterConfig() {
// @Override
// public String getFilterName() {
// return "fltnm";
// }
//
// @Override
// public ServletContext getServletContext() {
// return reqst.getServletContext();
// }
//
// @Override
// public String getInitParameter(String s) {
// if (s.equals("charset"))
// return "utf8";
// return "";
// }
//
// @Override
// public Enumeration<String> getInitParameterNames() {
// return null;
// }
// };
// FilterDispatcher filterDispatcher = new FilterDispatcher();
// filterDispatcher.init(fc);
//
//
// filterDispatcher.doFilter(reqst, resps, new FilterChain() {
// @Override
// public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
//
// }
// });
//add ActionContext.getActionContext()
// ActionContext.getActionContext()
System.out.println(com.webkit.web.ActionContextWrp.class);
com.webkit.web.ActionContextWrp.createActionContext(reqst.getServletContext(), reqst, resps);
// Dispatcher.getInstance(). serviceAction(,, );
// Dispatcher.getInstance().setActionContext(null);
// ActionContext
}
}
| 1 | 10 | 1 |
64153_38 | package testkg;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.input.ReversedLinesFileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.stream.Stream;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class IstTestFl {
public static void main(String[] args) throws Exception {
// rd_lastLine();
// wrt_zip_files(); def buff 20w/s,,if no zip comprs ,buf cache,then 30w/s
// wrt_many_files(); 2k /s
// rd();
// wrt(); // 200w/s longtime,,,, 1sec can 1kw
// wrt_many_files_buff();// 6k /s
}
public static void wrt_zip_files() throws IOException {
//5000 zipfile /secd....if bufferwarp 10w file one sec... 10ps so fast
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
//创建压缩包
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("zip_stored" + UUID.randomUUID() + ".zip")));
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("dt217_900w.txt", true)), 1024);
zipOutputStream.setLevel(Deflater.NO_COMPRESSION); ///no cmpare 30w ps ...fastr...if ziped dft..is 20w/s
logger.info("=============start.....");
for (int n = 0; n < 30 * 10000; n++) {
try {
//创建压缩包里的文件
ZipEntry zpe_ent_file = new ZipEntry(UUID.randomUUID() + ".json");
// zpe_ent_file.setMethod(ZipOutputStream.STORED);
zipOutputStream.putNextEntry(zpe_ent_file);
zipOutputStream.write(txt.getBytes()); //将数据写入到压缩包里的文件里面
zipOutputStream.closeEntry();
// FileUtils.writeStringToFile(new File("flds/dt2022"+ UUID.randomUUID() +".txt"),txt,true);
} catch (Throwable e) {
System.out.println(e);
}
}
zipOutputStream.flush();
zipOutputStream.close();
logger.info("===================end.....");
}
public static void wrt_many_files_buff() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
logger.info("=============start.....");
for (int n = 0; n < 3 * 10000; n++) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/fldss/"+UUID.randomUUID()+".txt", true)), 1024);
bw.write(n + txt);
bw.newLine();//输出换行,内部调用System.getProperty("line.separator")
//3.刷新缓存区
bw.flush();
//4.关闭流对象并释放有关的资源
bw.close();
} catch (Throwable e) {
System.out.println(e);
}
}
logger.info("===================end.....");
}
// 2k fils per sec only
public static void wrt_many_files() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
// 如果 Redis 服务设置了密码,需要下面这行,没有就不需要
jedis.auth(" ");
System.out.println("连接成功");
//查看服务是否运行
System.out.println("服务正在运行: " + jedis.ping());
System.out.println(jedis.get("fgfkkk"));
logger.info("=============start.....");
for (int n = 0; n < 1 * 10000; n++) {
try {
FileUtils.writeStringToFile(new File("flds/dt2022" + UUID.randomUUID() + ".txt"), txt, true);
} catch (Throwable e) {
System.out.println(e);
}
}
logger.info("===================end.....");
}
public static void rd_lastLine() throws IOException {
// very fast ,mayr use radnm seek ftuncthm,,only need 3ms
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
logger.info("=============start.....");
String line = "";
ReversedLinesFileReader reversedLinesReader = new ReversedLinesFileReader(new File("dt217_900w.txt"), Charset.defaultCharset());
System.out.println(reversedLinesReader.readLine());
logger.info("===================mid.....");
Stream<String> lines = Files.lines(Paths.get("dt217_900w.txt"));
line = lines.skip(899 * 10000).findFirst().get();
System.out.println(line);
logger.info("===================end.....");
}
public static void rd() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
logger.info("=============start.....");
String line = "";
RandomAccessFile raf = new RandomAccessFile("dt217_900w.txt", "r");
//获取RandomAccessFile对象文件指针的位置,初始位置是0
// System.out.println("RandomAccessFile文件指针的初始位置:"+raf.getFilePointer());
raf.seek(886 * 10000 * 92);//移动文件指针位置
System.out.println(raf.readLine());
System.out.println(raf.readLine());
logger.info("===================mid.....");
// int n = -1;
// LineIterator iterator = FileUtils.lineIterator(new File("dt217_900w.txt"), "UTf-8");
// while (iterator.hasNext()) {
// n++;
// if (n < 886 * 10000)
// {
// iterator.nextLine(); continue;
// }
//
// else {
// line = iterator.nextLine();
// System.out.println(line);
// break;
// }
// }
logger.info("===================mid.....");
Stream<String> lines = Files.lines(Paths.get("dt217_900w.txt"));
line = lines.skip(899 * 10000).findFirst().get();
System.out.println(line);
logger.info("===================end.....");
}
public static void wrt() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
//1.创建BufferedWriter类型的对象与c:/a.txt文件关联,true代表可以追加,
//写入流,设置缓存区大小为1024K
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("log"+UUID.randomUUID()+".txt", true)), 1024);
logger.info("=============start.....");
//if many w .... 200w /s wrting... spd ...if 1000kw,only 1s
// 200MB /s ??? 持续,峰值可以5被
for (int n = 0; n < 5*900 * 10000; n++) {
try {
// FileUtils.writeStringToFile(new File("dt2022.txt"),txt,true);
//2.将字符串数据"last demo!"写入文件中
bw.write(n + txt);
bw.newLine();//输出换行,内部调用System.getProperty("line.separator")
} catch (Throwable e) {
System.out.println(e);
}
}
//3.刷新缓存区
bw.flush();
//4.关闭流对象并释放有关的资源
bw.close();
logger.info("===================end.....");
}
}
| Atlks/sumdoc2023 | testkg/IstTestFl.java | 2,239 | // 200MB /s ??? 持续,峰值可以5被 | line_comment | zh-cn | package testkg;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.input.ReversedLinesFileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.stream.Stream;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class IstTestFl {
public static void main(String[] args) throws Exception {
// rd_lastLine();
// wrt_zip_files(); def buff 20w/s,,if no zip comprs ,buf cache,then 30w/s
// wrt_many_files(); 2k /s
// rd();
// wrt(); // 200w/s longtime,,,, 1sec can 1kw
// wrt_many_files_buff();// 6k /s
}
public static void wrt_zip_files() throws IOException {
//5000 zipfile /secd....if bufferwarp 10w file one sec... 10ps so fast
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
//创建压缩包
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("zip_stored" + UUID.randomUUID() + ".zip")));
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("dt217_900w.txt", true)), 1024);
zipOutputStream.setLevel(Deflater.NO_COMPRESSION); ///no cmpare 30w ps ...fastr...if ziped dft..is 20w/s
logger.info("=============start.....");
for (int n = 0; n < 30 * 10000; n++) {
try {
//创建压缩包里的文件
ZipEntry zpe_ent_file = new ZipEntry(UUID.randomUUID() + ".json");
// zpe_ent_file.setMethod(ZipOutputStream.STORED);
zipOutputStream.putNextEntry(zpe_ent_file);
zipOutputStream.write(txt.getBytes()); //将数据写入到压缩包里的文件里面
zipOutputStream.closeEntry();
// FileUtils.writeStringToFile(new File("flds/dt2022"+ UUID.randomUUID() +".txt"),txt,true);
} catch (Throwable e) {
System.out.println(e);
}
}
zipOutputStream.flush();
zipOutputStream.close();
logger.info("===================end.....");
}
public static void wrt_many_files_buff() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
logger.info("=============start.....");
for (int n = 0; n < 3 * 10000; n++) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/fldss/"+UUID.randomUUID()+".txt", true)), 1024);
bw.write(n + txt);
bw.newLine();//输出换行,内部调用System.getProperty("line.separator")
//3.刷新缓存区
bw.flush();
//4.关闭流对象并释放有关的资源
bw.close();
} catch (Throwable e) {
System.out.println(e);
}
}
logger.info("===================end.....");
}
// 2k fils per sec only
public static void wrt_many_files() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
// 如果 Redis 服务设置了密码,需要下面这行,没有就不需要
jedis.auth(" ");
System.out.println("连接成功");
//查看服务是否运行
System.out.println("服务正在运行: " + jedis.ping());
System.out.println(jedis.get("fgfkkk"));
logger.info("=============start.....");
for (int n = 0; n < 1 * 10000; n++) {
try {
FileUtils.writeStringToFile(new File("flds/dt2022" + UUID.randomUUID() + ".txt"), txt, true);
} catch (Throwable e) {
System.out.println(e);
}
}
logger.info("===================end.....");
}
public static void rd_lastLine() throws IOException {
// very fast ,mayr use radnm seek ftuncthm,,only need 3ms
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
logger.info("=============start.....");
String line = "";
ReversedLinesFileReader reversedLinesReader = new ReversedLinesFileReader(new File("dt217_900w.txt"), Charset.defaultCharset());
System.out.println(reversedLinesReader.readLine());
logger.info("===================mid.....");
Stream<String> lines = Files.lines(Paths.get("dt217_900w.txt"));
line = lines.skip(899 * 10000).findFirst().get();
System.out.println(line);
logger.info("===================end.....");
}
public static void rd() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
logger.info("=============start.....");
String line = "";
RandomAccessFile raf = new RandomAccessFile("dt217_900w.txt", "r");
//获取RandomAccessFile对象文件指针的位置,初始位置是0
// System.out.println("RandomAccessFile文件指针的初始位置:"+raf.getFilePointer());
raf.seek(886 * 10000 * 92);//移动文件指针位置
System.out.println(raf.readLine());
System.out.println(raf.readLine());
logger.info("===================mid.....");
// int n = -1;
// LineIterator iterator = FileUtils.lineIterator(new File("dt217_900w.txt"), "UTf-8");
// while (iterator.hasNext()) {
// n++;
// if (n < 886 * 10000)
// {
// iterator.nextLine(); continue;
// }
//
// else {
// line = iterator.nextLine();
// System.out.println(line);
// break;
// }
// }
logger.info("===================mid.....");
Stream<String> lines = Files.lines(Paths.get("dt217_900w.txt"));
line = lines.skip(899 * 10000).findFirst().get();
System.out.println(line);
logger.info("===================end.....");
}
public static void wrt() throws IOException {
Logger logger = LoggerFactory.getLogger(IstTestFl.class);
String txt = "aaaaaaaaaaaaaaaaaaaaaaaaadkjflkdsjfklasjfkld jfkdsajfkldsjfkldsjafklsdjafkljadkslfjdkl";
//1.创建BufferedWriter类型的对象与c:/a.txt文件关联,true代表可以追加,
//写入流,设置缓存区大小为1024K
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("log"+UUID.randomUUID()+".txt", true)), 1024);
logger.info("=============start.....");
//if many w .... 200w /s wrting... spd ...if 1000kw,only 1s
// 20 <SUF>
for (int n = 0; n < 5*900 * 10000; n++) {
try {
// FileUtils.writeStringToFile(new File("dt2022.txt"),txt,true);
//2.将字符串数据"last demo!"写入文件中
bw.write(n + txt);
bw.newLine();//输出换行,内部调用System.getProperty("line.separator")
} catch (Throwable e) {
System.out.println(e);
}
}
//3.刷新缓存区
bw.flush();
//4.关闭流对象并释放有关的资源
bw.close();
logger.info("===================end.....");
}
}
| 0 | 25 | 0 |
56775_1 | package com.attilax.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class terninal_linux {
/**
* 连接linux系统
* @param args
*/
public static void main(String[] args) {
try {
Connection conn = new Connection("192.168.81.129");
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword("root",
"123456");
if (isAuthenticated == false) {
throw new IOException("Authentication failed");
}
Session sess = conn.openSession();
sess.requestPTY("bash");
sess.startShell();
InputStream stdout = new StreamGobbler(sess.getStdout());
InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader stdoutReader = new BufferedReader(
new InputStreamReader(stdout));
BufferedReader stderrReader = new BufferedReader(
new InputStreamReader(stderr));
BufferedReader inputReader = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(sess.getStdin());
String temp = "";
while (!temp.equals("exit")) {
System.out.print("[root@vmone ~]#");
temp = inputReader.readLine();
out.println(temp);
out.flush();
String line = null;
while ((line = stdoutReader.readLine()) != null) {
if (line.length() == 0) {// line等于null从来不会发生,导致程序卡在这里
continue;
} else{
System.out.println(line);
}
}
System.out.println("Here is the output from stderr:");
while (true) {
line = stderrReader.readLine();
if (line == null)
break;
System.out.println(line);
}
}
System.out.println("ExitCode: " + sess.getExitStatus());
sess.close();
conn.close();
System.out.println("close connection");
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
}
}
| Atlks/sumdocIndexToolPrj | src/com/attilax/util/terninal_linux.java | 548 | // line等于null从来不会发生,导致程序卡在这里 | line_comment | zh-cn | package com.attilax.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class terninal_linux {
/**
* 连接linux系统
* @param args
*/
public static void main(String[] args) {
try {
Connection conn = new Connection("192.168.81.129");
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword("root",
"123456");
if (isAuthenticated == false) {
throw new IOException("Authentication failed");
}
Session sess = conn.openSession();
sess.requestPTY("bash");
sess.startShell();
InputStream stdout = new StreamGobbler(sess.getStdout());
InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader stdoutReader = new BufferedReader(
new InputStreamReader(stdout));
BufferedReader stderrReader = new BufferedReader(
new InputStreamReader(stderr));
BufferedReader inputReader = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(sess.getStdin());
String temp = "";
while (!temp.equals("exit")) {
System.out.print("[root@vmone ~]#");
temp = inputReader.readLine();
out.println(temp);
out.flush();
String line = null;
while ((line = stdoutReader.readLine()) != null) {
if (line.length() == 0) {// li <SUF>
continue;
} else{
System.out.println(line);
}
}
System.out.println("Here is the output from stderr:");
while (true) {
line = stderrReader.readLine();
if (line == null)
break;
System.out.println(line);
}
}
System.out.println("ExitCode: " + sess.getExitStatus());
sess.close();
conn.close();
System.out.println("close connection");
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
}
}
| 1 | 28 | 1 |
56610_7 | package com.ht.vo;
import java.io.Serializable;
import java.util.Date;
public class CarVo implements Serializable{
private long carId;
private String cardNo;//车牌
private String inTime;//入场时间
private String outTime;//入场时间
private String inPic;//入场图片
private String outPic;//出场图片
private float carFee;//停车费
private int status;//状态0:未收费,1已收费,2:免费
private String userName;//收费员
private String remark;//备注
private int financeType;//1:包月,2:临时停车
private int minutes;//停车时长(分钟)
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getFinanceType() {
return financeType;
}
public void setFinanceType(int financeType) {
this.financeType = financeType;
}
public long getCarId() {
return carId;
}
public void setCarId(long carId) {
this.carId = carId;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getInTime() {
return inTime;
}
public void setInTime(String inTime) {
this.inTime = inTime;
}
public String getOutTime() {
return outTime;
}
public void setOutTime(String outTime) {
this.outTime = outTime;
}
public String getInPic() {
return inPic;
}
public void setInPic(String inPic) {
this.inPic = inPic;
}
public String getOutPic() {
return outPic;
}
public void setOutPic(String outPic) {
this.outPic = outPic;
}
public float getCarFee() {
return carFee;
}
public void setCarFee(float carFee) {
this.carFee = carFee;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
| AuroraHan/Car | src/com/ht/vo/CarVo.java | 679 | //1:包月,2:临时停车 | line_comment | zh-cn | package com.ht.vo;
import java.io.Serializable;
import java.util.Date;
public class CarVo implements Serializable{
private long carId;
private String cardNo;//车牌
private String inTime;//入场时间
private String outTime;//入场时间
private String inPic;//入场图片
private String outPic;//出场图片
private float carFee;//停车费
private int status;//状态0:未收费,1已收费,2:免费
private String userName;//收费员
private String remark;//备注
private int financeType;//1: <SUF>
private int minutes;//停车时长(分钟)
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getFinanceType() {
return financeType;
}
public void setFinanceType(int financeType) {
this.financeType = financeType;
}
public long getCarId() {
return carId;
}
public void setCarId(long carId) {
this.carId = carId;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getInTime() {
return inTime;
}
public void setInTime(String inTime) {
this.inTime = inTime;
}
public String getOutTime() {
return outTime;
}
public void setOutTime(String outTime) {
this.outTime = outTime;
}
public String getInPic() {
return inPic;
}
public void setInPic(String inPic) {
this.inPic = inPic;
}
public String getOutPic() {
return outPic;
}
public void setOutPic(String outPic) {
this.outPic = outPic;
}
public float getCarFee() {
return carFee;
}
public void setCarFee(float carFee) {
this.carFee = carFee;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
| 0 | 13 | 0 |
7788_1 | package com.demo01;
/**
* @Author: LFJ
* @Date: 2023-02-02 14:22
*/
// 测试守护线程
// 上帝守护你
public class TestThread5 {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); // 设置成守护线程
thread.start();
new Thread(you).start();
}
}
// 上帝
class God implements Runnable {
public void run() {
while (true) {
System.out.println("上帝保佑你");
}
}
}
// 你
class You implements Runnable {
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你开心的活着");
}
}
} | Auroraol/BackFront | 2-后端/note01/多线程/code/lesson/src/com/demo01/TestThread5.java | 252 | // 测试守护线程 | line_comment | zh-cn | package com.demo01;
/**
* @Author: LFJ
* @Date: 2023-02-02 14:22
*/
// 测试 <SUF>
// 上帝守护你
public class TestThread5 {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); // 设置成守护线程
thread.start();
new Thread(you).start();
}
}
// 上帝
class God implements Runnable {
public void run() {
while (true) {
System.out.println("上帝保佑你");
}
}
}
// 你
class You implements Runnable {
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你开心的活着");
}
}
} | 1 | 9 | 1 |
55287_3 | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.sun.org.apache.bcel.internal.generic.RETURN;
public class Arithmetic_baoshu {
//题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
boolean[] arr = new boolean[len];
for (int i = 0; i < arr.length; i++) {
arr[i] = true; //初始化全部在圈内
}
int index = 0; //下标
int countNum = 0; //计数
int leftCount = len;
do {
if (arr[index]) { //是圈内的人时
countNum++; //报数
if (countNum==3) { //当这个人报数为三时
arr[index] = false; //这个人出圈
leftCount--; //剩余人数减一
countNum = 0; //报数重置为0
}
}
//数组下标和在不在圈内无关
index++; //下一个人的下标
if (index==len) { //当下标等于长度时
index = 0; //下标重置为零
}
} while (leftCount>1);
for (int i = 0; i < arr.length; i++) {
if (arr[i]) {
System.out.println("最后剩的人下标为"+i);
}
}
}
}
| AutKevin/JAVA | Arithmetic/Arithmetic_baoshu.java | 457 | //当这个人报数为三时 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.sun.org.apache.bcel.internal.generic.RETURN;
public class Arithmetic_baoshu {
//题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
boolean[] arr = new boolean[len];
for (int i = 0; i < arr.length; i++) {
arr[i] = true; //初始化全部在圈内
}
int index = 0; //下标
int countNum = 0; //计数
int leftCount = len;
do {
if (arr[index]) { //是圈内的人时
countNum++; //报数
if (countNum==3) { //当这 <SUF>
arr[index] = false; //这个人出圈
leftCount--; //剩余人数减一
countNum = 0; //报数重置为0
}
}
//数组下标和在不在圈内无关
index++; //下一个人的下标
if (index==len) { //当下标等于长度时
index = 0; //下标重置为零
}
} while (leftCount>1);
for (int i = 0; i < arr.length; i++) {
if (arr[i]) {
System.out.println("最后剩的人下标为"+i);
}
}
}
}
| 1 | 11 | 1 |
15102_12 | package cn.authing.sdk.java.dto;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TenantUserDto {
/**
* 邮箱,不区分大小写
*/
@JsonProperty("email")
private String email;
/**
* 手机号,不带区号。如果是国外手机号,请在 phoneCountryCode 参数中指定区号。
*/
@JsonProperty("phone")
private String phone;
/**
* 手机区号,中国大陆手机号可不填。Authing 短信服务暂不内置支持国际手机号,你需要在 Authing 控制台配置对应的国际短信服务。完整的手机区号列表可参阅 https://en.wikipedia.org/wiki/List_of_country_calling_codes。
*/
@JsonProperty("phoneCountryCode")
private String phoneCountryCode;
/**
* 用户名,用户池内唯一
*/
@JsonProperty("username")
private String username;
/**
* 用户真实名称,不具备唯一性
*/
@JsonProperty("name")
private String name;
/**
* 昵称
*/
@JsonProperty("nickname")
private String nickname;
/**
* 头像链接
*/
@JsonProperty("photo")
private String photo;
/**
* 历史总登录次数
*/
@JsonProperty("loginsCount")
private Integer loginsCount;
/**
* 上次登录 IP
*/
@JsonProperty("lastIp")
private String lastIp;
/**
* 性别:
* - `M`: 男性,`male`
* - `F`: 女性,`female`
* - `U`: 未知,`unknown`
*
*/
@JsonProperty("gender")
private Gender gender;
/**
* 出生日期
*/
@JsonProperty("birthdate")
private String birthdate;
/**
* 所在国家
*/
@JsonProperty("country")
private String country;
/**
* 所在省份
*/
@JsonProperty("province")
private String province;
/**
* 所在城市
*/
@JsonProperty("city")
private String city;
/**
* 所处地址
*/
@JsonProperty("address")
private String address;
/**
* 所处街道地址
*/
@JsonProperty("streetAddress")
private String streetAddress;
/**
* 邮政编码号
*/
@JsonProperty("postalCode")
private String postalCode;
/**
* 名
*/
@JsonProperty("givenName")
private String givenName;
/**
* 姓
*/
@JsonProperty("familyName")
private String familyName;
/**
* 中间名
*/
@JsonProperty("middleName")
private String middleName;
/**
* Preferred Username
*/
@JsonProperty("preferredUsername")
private String preferredUsername;
/**
* 用户上次登录的应用 ID
*/
@JsonProperty("lastLoginApp")
private String lastLoginApp;
/**
* 用户池 ID
*/
@JsonProperty("userPoolId")
private String userPoolId;
/**
* 租户 ID
*/
@JsonProperty("tenantId")
private String tenantId;
/**
* 租户成员 ID
*/
@JsonProperty("memberId")
private String memberId;
/**
* 关联的用户池级别的用户 ID
*/
@JsonProperty("linkUserId")
private String linkUserId;
/**
* 是否为租户管理员
*/
@JsonProperty("isTenantAdmin")
private Boolean isTenantAdmin;
/**
* 用户密码,默认为明文。我们使用 HTTPS 协议对密码进行安全传输,可以在一定程度上保证安全性。如果你还需要更高级别的安全性,我们还支持 RSA256 和国密 SM2 两种方式对密码进行加密。详情见 `passwordEncryptType` 参数。
*/
@JsonProperty("password")
private String password;
/**
* 加密用户密码的盐
*/
@JsonProperty("salt")
private String salt;
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 getPhoneCountryCode() {
return phoneCountryCode;
}
public void setPhoneCountryCode(String phoneCountryCode) {
this.phoneCountryCode = phoneCountryCode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Integer getLoginsCount() {
return loginsCount;
}
public void setLoginsCount(Integer loginsCount) {
this.loginsCount = loginsCount;
}
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getPreferredUsername() {
return preferredUsername;
}
public void setPreferredUsername(String preferredUsername) {
this.preferredUsername = preferredUsername;
}
public String getLastLoginApp() {
return lastLoginApp;
}
public void setLastLoginApp(String lastLoginApp) {
this.lastLoginApp = lastLoginApp;
}
public String getUserPoolId() {
return userPoolId;
}
public void setUserPoolId(String userPoolId) {
this.userPoolId = userPoolId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getLinkUserId() {
return linkUserId;
}
public void setLinkUserId(String linkUserId) {
this.linkUserId = linkUserId;
}
public Boolean getIsTenantAdmin() {
return isTenantAdmin;
}
public void setIsTenantAdmin(Boolean isTenantAdmin) {
this.isTenantAdmin = isTenantAdmin;
}
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;
}
/**
* 性别:
* - `M`: 男性,`male`
* - `F`: 女性,`female`
* - `U`: 未知,`unknown`
*
*/
public static enum Gender {
@JsonProperty("M")
M("M"),
@JsonProperty("F")
F("F"),
@JsonProperty("U")
U("U"),
@JsonProperty("W")
W("W")
;
private String value;
Gender(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
} | Authing/authing-java-sdk | src/main/java/cn/authing/sdk/java/dto/TenantUserDto.java | 2,092 | /**
* 所在省份
*/ | block_comment | zh-cn | package cn.authing.sdk.java.dto;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TenantUserDto {
/**
* 邮箱,不区分大小写
*/
@JsonProperty("email")
private String email;
/**
* 手机号,不带区号。如果是国外手机号,请在 phoneCountryCode 参数中指定区号。
*/
@JsonProperty("phone")
private String phone;
/**
* 手机区号,中国大陆手机号可不填。Authing 短信服务暂不内置支持国际手机号,你需要在 Authing 控制台配置对应的国际短信服务。完整的手机区号列表可参阅 https://en.wikipedia.org/wiki/List_of_country_calling_codes。
*/
@JsonProperty("phoneCountryCode")
private String phoneCountryCode;
/**
* 用户名,用户池内唯一
*/
@JsonProperty("username")
private String username;
/**
* 用户真实名称,不具备唯一性
*/
@JsonProperty("name")
private String name;
/**
* 昵称
*/
@JsonProperty("nickname")
private String nickname;
/**
* 头像链接
*/
@JsonProperty("photo")
private String photo;
/**
* 历史总登录次数
*/
@JsonProperty("loginsCount")
private Integer loginsCount;
/**
* 上次登录 IP
*/
@JsonProperty("lastIp")
private String lastIp;
/**
* 性别:
* - `M`: 男性,`male`
* - `F`: 女性,`female`
* - `U`: 未知,`unknown`
*
*/
@JsonProperty("gender")
private Gender gender;
/**
* 出生日期
*/
@JsonProperty("birthdate")
private String birthdate;
/**
* 所在国家
*/
@JsonProperty("country")
private String country;
/**
* 所在省 <SUF>*/
@JsonProperty("province")
private String province;
/**
* 所在城市
*/
@JsonProperty("city")
private String city;
/**
* 所处地址
*/
@JsonProperty("address")
private String address;
/**
* 所处街道地址
*/
@JsonProperty("streetAddress")
private String streetAddress;
/**
* 邮政编码号
*/
@JsonProperty("postalCode")
private String postalCode;
/**
* 名
*/
@JsonProperty("givenName")
private String givenName;
/**
* 姓
*/
@JsonProperty("familyName")
private String familyName;
/**
* 中间名
*/
@JsonProperty("middleName")
private String middleName;
/**
* Preferred Username
*/
@JsonProperty("preferredUsername")
private String preferredUsername;
/**
* 用户上次登录的应用 ID
*/
@JsonProperty("lastLoginApp")
private String lastLoginApp;
/**
* 用户池 ID
*/
@JsonProperty("userPoolId")
private String userPoolId;
/**
* 租户 ID
*/
@JsonProperty("tenantId")
private String tenantId;
/**
* 租户成员 ID
*/
@JsonProperty("memberId")
private String memberId;
/**
* 关联的用户池级别的用户 ID
*/
@JsonProperty("linkUserId")
private String linkUserId;
/**
* 是否为租户管理员
*/
@JsonProperty("isTenantAdmin")
private Boolean isTenantAdmin;
/**
* 用户密码,默认为明文。我们使用 HTTPS 协议对密码进行安全传输,可以在一定程度上保证安全性。如果你还需要更高级别的安全性,我们还支持 RSA256 和国密 SM2 两种方式对密码进行加密。详情见 `passwordEncryptType` 参数。
*/
@JsonProperty("password")
private String password;
/**
* 加密用户密码的盐
*/
@JsonProperty("salt")
private String salt;
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 getPhoneCountryCode() {
return phoneCountryCode;
}
public void setPhoneCountryCode(String phoneCountryCode) {
this.phoneCountryCode = phoneCountryCode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Integer getLoginsCount() {
return loginsCount;
}
public void setLoginsCount(Integer loginsCount) {
this.loginsCount = loginsCount;
}
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getPreferredUsername() {
return preferredUsername;
}
public void setPreferredUsername(String preferredUsername) {
this.preferredUsername = preferredUsername;
}
public String getLastLoginApp() {
return lastLoginApp;
}
public void setLastLoginApp(String lastLoginApp) {
this.lastLoginApp = lastLoginApp;
}
public String getUserPoolId() {
return userPoolId;
}
public void setUserPoolId(String userPoolId) {
this.userPoolId = userPoolId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getLinkUserId() {
return linkUserId;
}
public void setLinkUserId(String linkUserId) {
this.linkUserId = linkUserId;
}
public Boolean getIsTenantAdmin() {
return isTenantAdmin;
}
public void setIsTenantAdmin(Boolean isTenantAdmin) {
this.isTenantAdmin = isTenantAdmin;
}
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;
}
/**
* 性别:
* - `M`: 男性,`male`
* - `F`: 女性,`female`
* - `U`: 未知,`unknown`
*
*/
public static enum Gender {
@JsonProperty("M")
M("M"),
@JsonProperty("F")
F("F"),
@JsonProperty("U")
U("U"),
@JsonProperty("W")
W("W")
;
private String value;
Gender(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
} | 1 | 23 | 1 |
38538_6 | package com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.generate;
import com.autohome.frostmourne.monitor.model.enums.AlertType;
import com.autohome.frostmourne.monitor.model.enums.SendStatus;
import com.autohome.frostmourne.monitor.model.enums.SilenceStatus;
import java.io.Serializable;
import java.util.Date;
/**
* 报警日志
*
* @author mybatis-generator
*/
public class AlertLog implements Serializable {
/**
* 自增主键
*/
private Long id;
/**
* 监控ID
*/
private Long alarmId;
/**
* 监控执行ID
*/
private Long executeId;
/**
* 报警方式
*/
private String way;
/**
* 报警接收人
*/
private String recipient;
/**
* 是否在静默期(YES,NO)
*/
private SilenceStatus inSilence;
/**
* 发送状态(NONE,SUCCESS,FAIL,FORBID)
*/
private SendStatus sendStatus;
/**
* 消息类型(问题报警: PROBLEM; 恢复通知: RECOVER)
*/
private AlertType alertType;
/**
* 创建时间
*/
private Date createAt;
/**
* 报警内容
*/
private String content;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAlarmId() {
return alarmId;
}
public void setAlarmId(Long alarmId) {
this.alarmId = alarmId;
}
public Long getExecuteId() {
return executeId;
}
public void setExecuteId(Long executeId) {
this.executeId = executeId;
}
public String getWay() {
return way;
}
public void setWay(String way) {
this.way = way == null ? null : way.trim();
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient == null ? null : recipient.trim();
}
public SilenceStatus getInSilence() {
return inSilence;
}
public void setInSilence(SilenceStatus inSilence) {
this.inSilence = inSilence;
}
public SendStatus getSendStatus() {
return sendStatus;
}
public void setSendStatus(SendStatus sendStatus) {
this.sendStatus = sendStatus;
}
public AlertType getAlertType() {
return alertType;
}
public void setAlertType(AlertType alertType) {
this.alertType = alertType;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
AlertLog other = (AlertLog) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getAlarmId() == null ? other.getAlarmId() == null : this.getAlarmId().equals(other.getAlarmId()))
&& (this.getExecuteId() == null ? other.getExecuteId() == null : this.getExecuteId().equals(other.getExecuteId()))
&& (this.getWay() == null ? other.getWay() == null : this.getWay().equals(other.getWay()))
&& (this.getRecipient() == null ? other.getRecipient() == null : this.getRecipient().equals(other.getRecipient()))
&& (this.getInSilence() == null ? other.getInSilence() == null : this.getInSilence().equals(other.getInSilence()))
&& (this.getSendStatus() == null ? other.getSendStatus() == null : this.getSendStatus().equals(other.getSendStatus()))
&& (this.getAlertType() == null ? other.getAlertType() == null : this.getAlertType().equals(other.getAlertType()))
&& (this.getCreateAt() == null ? other.getCreateAt() == null : this.getCreateAt().equals(other.getCreateAt()))
&& (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getAlarmId() == null) ? 0 : getAlarmId().hashCode());
result = prime * result + ((getExecuteId() == null) ? 0 : getExecuteId().hashCode());
result = prime * result + ((getWay() == null) ? 0 : getWay().hashCode());
result = prime * result + ((getRecipient() == null) ? 0 : getRecipient().hashCode());
result = prime * result + ((getInSilence() == null) ? 0 : getInSilence().hashCode());
result = prime * result + ((getSendStatus() == null) ? 0 : getSendStatus().hashCode());
result = prime * result + ((getAlertType() == null) ? 0 : getAlertType().hashCode());
result = prime * result + ((getCreateAt() == null) ? 0 : getCreateAt().hashCode());
result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode());
return result;
}
} | AutohomeCorp/frostmourne | frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/dao/mybatis/frostmourne/domain/generate/AlertLog.java | 1,400 | /**
* 是否在静默期(YES,NO)
*/ | block_comment | zh-cn | package com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.generate;
import com.autohome.frostmourne.monitor.model.enums.AlertType;
import com.autohome.frostmourne.monitor.model.enums.SendStatus;
import com.autohome.frostmourne.monitor.model.enums.SilenceStatus;
import java.io.Serializable;
import java.util.Date;
/**
* 报警日志
*
* @author mybatis-generator
*/
public class AlertLog implements Serializable {
/**
* 自增主键
*/
private Long id;
/**
* 监控ID
*/
private Long alarmId;
/**
* 监控执行ID
*/
private Long executeId;
/**
* 报警方式
*/
private String way;
/**
* 报警接收人
*/
private String recipient;
/**
* 是否在 <SUF>*/
private SilenceStatus inSilence;
/**
* 发送状态(NONE,SUCCESS,FAIL,FORBID)
*/
private SendStatus sendStatus;
/**
* 消息类型(问题报警: PROBLEM; 恢复通知: RECOVER)
*/
private AlertType alertType;
/**
* 创建时间
*/
private Date createAt;
/**
* 报警内容
*/
private String content;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAlarmId() {
return alarmId;
}
public void setAlarmId(Long alarmId) {
this.alarmId = alarmId;
}
public Long getExecuteId() {
return executeId;
}
public void setExecuteId(Long executeId) {
this.executeId = executeId;
}
public String getWay() {
return way;
}
public void setWay(String way) {
this.way = way == null ? null : way.trim();
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient == null ? null : recipient.trim();
}
public SilenceStatus getInSilence() {
return inSilence;
}
public void setInSilence(SilenceStatus inSilence) {
this.inSilence = inSilence;
}
public SendStatus getSendStatus() {
return sendStatus;
}
public void setSendStatus(SendStatus sendStatus) {
this.sendStatus = sendStatus;
}
public AlertType getAlertType() {
return alertType;
}
public void setAlertType(AlertType alertType) {
this.alertType = alertType;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
AlertLog other = (AlertLog) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getAlarmId() == null ? other.getAlarmId() == null : this.getAlarmId().equals(other.getAlarmId()))
&& (this.getExecuteId() == null ? other.getExecuteId() == null : this.getExecuteId().equals(other.getExecuteId()))
&& (this.getWay() == null ? other.getWay() == null : this.getWay().equals(other.getWay()))
&& (this.getRecipient() == null ? other.getRecipient() == null : this.getRecipient().equals(other.getRecipient()))
&& (this.getInSilence() == null ? other.getInSilence() == null : this.getInSilence().equals(other.getInSilence()))
&& (this.getSendStatus() == null ? other.getSendStatus() == null : this.getSendStatus().equals(other.getSendStatus()))
&& (this.getAlertType() == null ? other.getAlertType() == null : this.getAlertType().equals(other.getAlertType()))
&& (this.getCreateAt() == null ? other.getCreateAt() == null : this.getCreateAt().equals(other.getCreateAt()))
&& (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getAlarmId() == null) ? 0 : getAlarmId().hashCode());
result = prime * result + ((getExecuteId() == null) ? 0 : getExecuteId().hashCode());
result = prime * result + ((getWay() == null) ? 0 : getWay().hashCode());
result = prime * result + ((getRecipient() == null) ? 0 : getRecipient().hashCode());
result = prime * result + ((getInSilence() == null) ? 0 : getInSilence().hashCode());
result = prime * result + ((getSendStatus() == null) ? 0 : getSendStatus().hashCode());
result = prime * result + ((getAlertType() == null) ? 0 : getAlertType().hashCode());
result = prime * result + ((getCreateAt() == null) ? 0 : getCreateAt().hashCode());
result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode());
return result;
}
} | 1 | 33 | 1 |
38334_49 | package JDB;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class TestSql
{
public static void main(String args[]) throws Exception
{
new Adm();
}
}
class Adm extends Frame
{
Panel p1,p2,p3,p4,p5,p6,p7,p8,p9; // 分行显示
Label s1,s2,s3,s4,s5,c1,c2,c3,c4,sc1,sc2,sc3,mes,mes1,mes2,mes3,mes4;
TextField st1,st2,st4,st5,ct1,ct2,ct3,ct4,sct1,sct2,sct3;
TextArea msg;
CheckboxGroup table,sex;
Checkbox student,course,sc;
Checkbox m,w; //分别代表 男 女
Button b1,b2,b3,b4; // 分别为 查询 插入 修改 删除
Connection cn; //与数据库连接
PreparedStatement cx,cr,xg,sg; // 分别为 查询 插入 修改 删除
String scx,scr,sxg,ssc,ssex; // 分别为 查询 插入 修改 删除
String ccx,ccr,cxg,csc;
String sccx,sccr,scxg,scsc;
Adm()
{
String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// SQL数据库引擎
try
{
Class.forName(JDriver);// 加载数据库引擎,返回给定字符串名的类
}
catch (ClassNotFoundException e)
{ // e.printStackTrace();
System.out.println("加载数据库引擎失败");
System.exit(0);
};
table=new CheckboxGroup();
student=new Checkbox("student 表",true,table); // 表的选择
course=new Checkbox("course 表",false,table);
sc=new Checkbox("sc 表",false,table);
s1=new Label("学号 ");
s2=new Label("姓名 ");
s3=new Label("年龄 ");
s4=new Label("系别 "); // student
s5=new Label("性别");
st1=new TextField(10);
st2=new TextField(10);
st4=new TextField(10);
st5=new TextField(10);
sex=new CheckboxGroup();
m=new Checkbox("男",true,sex);
w=new Checkbox("女",false,sex);
c1=new Label("课程号 ");
c2=new Label("课程名 ");
c3=new Label("先行课 "); // course 表
c4=new Label("学分 ");
ct1=new TextField(10);
ct2=new TextField(10);
ct3=new TextField(10);
ct4=new TextField(10);
sc1=new Label("学号 ");
sc2=new Label("课程号 "); // SC 表
sc3=new Label("成绩 ");
sct1=new TextField(10);
sct2=new TextField(10);
sct3=new TextField(10);
msg=new TextArea(10,80);
mes=new Label(" ");
mes1=new Label("说明: ");
mes2=new Label("1. 本数据库系统基于java语言编写,使用JDBC技术实现与SQL Server 连接 ,通过Eclispe构建开发平台。 ");
mes3=new Label("2.本系统暂时只能实现插入功能,可以对数据的有效性进行检验。关于其他的功能还有待开发。 操作过程中无需打开SQL Server");
mes4=new Label("3.该系统处处体现了人性化设计,具有一定的实用性和可移植性。") ;
msg.setText("欢迎进入学生信息管理系统,祝您愉快!O(∩_∩)O~"+"\n"+"\n"
+"本数据库管理系统 不支持 级联 删除 删除前请注意 数据的 唯一性 !!%>_<%"+"\n"+"\n"
+"student 支持由学号修改姓名,course 支持由课程号修改学分,sc 支持由学号和科目修改分数。"+"\n"+"\n"
+ "student 支持由学号删除其他项,course 支持由课程号删除其他项,sc 暂不支持删除功能。");
b1=new Button("查询");
b2=new Button("插入"); // 操作布局
b3=new Button("修改");
b4=new Button("删除");
p1=new Panel(); // 容器构造
p2=new Panel();
p3=new Panel();
p4=new Panel();
p5=new Panel();
p6=new Panel();
p7=new Panel();
p8=new Panel();
p9=new Panel();
p1.add(student);
p1.add(s1); p1.add(st1);
p1.add(s2); p1.add(st2);
p1.add(s3); p1.add(st4);
p1.add(s4); p1.add(st5);
p1.add(s5);
p1.add(m); // p1 容器
p1.add(w);
p2.add(course);
p2.add(c1); p2.add(ct1);
p2.add(c2); p2.add(ct2);
p2.add(c3); p2.add(ct3);
p2.add(c4); p2.add(ct4); // p2 容器
p3.add(sc);
p3.add(sc1); p3.add(sct1); // p3 容器
p3.add(sc2); p3.add(sct2);
p3.add(sc3); p3.add(sct3);
p3.add(mes);
p4.add(b1);
p4.add(b2); // p4 容器
p4.add(b3);
p4.add(b4);
p5.add(msg);
p6.add(mes1);
p7.add(mes2);
p8.add(mes3);
p9.add(mes4);
setLayout(new FlowLayout(0,8,8)); //布局构造
add(p1);
add(p2); // 添加容器到当前布局
add(p3);
add(p4);
add(p5);
add(p6);
add(p7);
add(p8);
add(p9);
b1.addActionListener(new B1());
b2.addActionListener(new B2()); // 为按钮创建事件
b3.addActionListener(new B3());
b4.addActionListener(new B4());
addWindowListener(new WinClose());
setSize(800,560);
setTitle("学生信息管理系统");
setVisible(true);
}
class B1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
Statement stmt;
ResultSet rs;
stmt=cn.createStatement();
rs=stmt.executeQuery("SELECT * FROM student ");
while(rs.next())
{
System.out.println(rs.getString("sno")+" "+rs.getString("sname")+
" "+rs.getString("ssex")+" "+rs.getInt("sage")+" "+rs.getString("sdept"));
msg.setText("数据查询成功,已经显示在 控制台窗口!");
};
}
catch (SQLException e1)
{
System.out.println("数据库连接错误"+"\n");
System.exit(0);
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
Statement stmt;
ResultSet rs;
stmt=cn.createStatement();
rs=stmt.executeQuery("SELECT * FROM course ");
while(rs.next())
{
System.out.println(rs.getString("cno")+" "+rs.getString("cname")+" "+
rs.getString("cpno")+" "+rs.getString("ccredit"));
msg.setText("数据查询成功,已经显示在 控制台窗口!");
};
}
catch (SQLException e1)
{
System.out.println("数据库连接错误"+"\n");
System.exit(0);
};
}
else
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
Statement stmt;
ResultSet rs;
stmt=cn.createStatement();
rs=stmt.executeQuery("SELECT * FROM sc ");
while(rs.next())
{
System.out.println(rs.getString("sno")+" "+rs.getString("cno")+" "
+rs.getString("grade"));
msg.setText("数据查询成功,已经显示在 控制台窗口!");
};
}
catch (SQLException e1)
{
System.out.println("数据库连接错误"+"\n");
System.exit(0);
};
}
}
}
class B2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
scr="INSERT INTO student VALUES(?,?,?,?,?)" ;
cr=cn.prepareStatement(scr);
msg.setText("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
System.out.print("数据库连接错误"+"\n");
System.exit(0);
};
try
{
cr.setString(1, st1.getText()); //为SQL语句参数赋值
cr.setString(2, st2.getText());
if(m.getState())
ssex="男";
else
ssex="女";
cr.setString(3, ssex);
cr.setInt(4, Integer.parseInt(st4.getText()));
cr.setString(5, st5.getText());
cr.executeUpdate();
msg.setText("插入数据成功");
st1.setText("");
st2.setText(""); //清空各输入框
st4.setText("");
st5.setText("");
st1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
st1.requestFocus();
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
ccr="INSERT INTO course VALUES(?,?,?,?)" ;
cr=cn.prepareStatement(ccr);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
cr.setInt(1, Integer.parseInt(ct1.getText())); //为SQL语句参数赋值
cr.setString(2, ct2.getText());
cr.setString(3, ct3.getText());
cr.setString(4, ct4.getText());
cr.executeUpdate();
msg.setText("插入数据成功");
ct1.setText("");
ct2.setText(""); //清空各输入框
ct3.setText("");
ct4.setText("");
ct1.requestFocus();
}
catch (Exception e2)
{
msg.setText("输入数据有误!");
ct1.requestFocus();
};
}
else
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
sccr="INSERT INTO sc VALUES(?,?,?)" ;
cr=cn.prepareStatement(sccr);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
cr.setString(1, sct1.getText()); //为SQL语句参数赋值
cr.setInt(2, Integer.parseInt(sct2.getText()));
cr.setInt(3, Integer.parseInt(sct3.getText()));
cr.executeUpdate();
msg.setText("插入数据成功");
sct1.setText("");
sct2.setText(""); //清空各输入框
sct3.setText("");
sct1.requestFocus();
}
catch (Exception e2)
{
msg.setText("输入数据有误!");
sct1.requestFocus();
};
}
}
}
class B3 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
sxg="UPDATE student SET sname=? WHERE sno=?" ;
xg=cn.prepareStatement(sxg);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
xg.setString(1, st2.getText()); //为SQL语句参数赋值
xg.setString(2, st1.getText());
xg.executeUpdate();
msg.setText("修改数据成功!");
st1.setText("");
st2.setText(""); //清空各输入框
st4.setText("");
st5.setText("");
st1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
st1.requestFocus();
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
cxg="UPDATE course SET ccredit=? WHERE cno=?" ;
xg=cn.prepareStatement(cxg);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
xg.setString(1, ct4.getText()); //为SQL语句参数赋值
xg.setString(2, ct1.getText());
xg.executeUpdate();
msg.setText("修改数据成功!");
ct1.setText("");
ct2.setText("");
ct3.setText("");
ct4.setText(""); //清空各输入框
ct1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
ct1.requestFocus();
};
}
else
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
scxg="UPDATE sc SET grade=? WHERE sno=? AND cno=?" ;
xg=cn.prepareStatement(scxg);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
xg.setString(1, sct3.getText()); //为SQL语句参数赋值
xg.setString(2, sct1.getText());
xg.setString(3, sct2.getText());
xg.executeUpdate();
msg.setText("修改数据成功!");
sct1.setText("");
sct2.setText("");
sct3.setText(""); //清空各输入框
sct1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
sct1.requestFocus();
};
}
}
}
class B4 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
ssc="DELETE FROM student WHERE sno=?" ;
sg=cn.prepareStatement(ssc);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
System.out.print("数据库连接错误"+"\n");
System.exit(0);
};
try
{
sg.setString(1, st1.getText()); //为SQL语句参数赋值
sg.executeUpdate();
msg.setText("删除数据成功!");
st1.setText("");
st2.setText(""); //清空各输入框
st1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
st1.requestFocus();
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
csc="DELETE FROM course WHERE cno=?" ;
sg=cn.prepareStatement(csc);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
System.out.print("数据库连接错误"+"\n");
System.exit(0);
};
try
{
sg.setInt(1, Integer.parseInt(ct1.getText())); //为SQL语句参数赋值
sg.executeUpdate();
msg.setText("删除数据成功!");
ct1.setText("");
ct2.setText("");
ct3.setText("");
ct4.setText("");//清空各输入框
ct1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
ct1.requestFocus();
};
}
else
{
msg.setText(" 对不起,暂不支持对 SC 表进行删除操作!");
}
}
}
class WinClose extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
(e.getWindow()).dispose();
System.exit(0);
}
}
}
| AutuanLiu/Student | TestSql.java | 5,246 | // 连接数据库对象 | line_comment | zh-cn | package JDB;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class TestSql
{
public static void main(String args[]) throws Exception
{
new Adm();
}
}
class Adm extends Frame
{
Panel p1,p2,p3,p4,p5,p6,p7,p8,p9; // 分行显示
Label s1,s2,s3,s4,s5,c1,c2,c3,c4,sc1,sc2,sc3,mes,mes1,mes2,mes3,mes4;
TextField st1,st2,st4,st5,ct1,ct2,ct3,ct4,sct1,sct2,sct3;
TextArea msg;
CheckboxGroup table,sex;
Checkbox student,course,sc;
Checkbox m,w; //分别代表 男 女
Button b1,b2,b3,b4; // 分别为 查询 插入 修改 删除
Connection cn; //与数据库连接
PreparedStatement cx,cr,xg,sg; // 分别为 查询 插入 修改 删除
String scx,scr,sxg,ssc,ssex; // 分别为 查询 插入 修改 删除
String ccx,ccr,cxg,csc;
String sccx,sccr,scxg,scsc;
Adm()
{
String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// SQL数据库引擎
try
{
Class.forName(JDriver);// 加载数据库引擎,返回给定字符串名的类
}
catch (ClassNotFoundException e)
{ // e.printStackTrace();
System.out.println("加载数据库引擎失败");
System.exit(0);
};
table=new CheckboxGroup();
student=new Checkbox("student 表",true,table); // 表的选择
course=new Checkbox("course 表",false,table);
sc=new Checkbox("sc 表",false,table);
s1=new Label("学号 ");
s2=new Label("姓名 ");
s3=new Label("年龄 ");
s4=new Label("系别 "); // student
s5=new Label("性别");
st1=new TextField(10);
st2=new TextField(10);
st4=new TextField(10);
st5=new TextField(10);
sex=new CheckboxGroup();
m=new Checkbox("男",true,sex);
w=new Checkbox("女",false,sex);
c1=new Label("课程号 ");
c2=new Label("课程名 ");
c3=new Label("先行课 "); // course 表
c4=new Label("学分 ");
ct1=new TextField(10);
ct2=new TextField(10);
ct3=new TextField(10);
ct4=new TextField(10);
sc1=new Label("学号 ");
sc2=new Label("课程号 "); // SC 表
sc3=new Label("成绩 ");
sct1=new TextField(10);
sct2=new TextField(10);
sct3=new TextField(10);
msg=new TextArea(10,80);
mes=new Label(" ");
mes1=new Label("说明: ");
mes2=new Label("1. 本数据库系统基于java语言编写,使用JDBC技术实现与SQL Server 连接 ,通过Eclispe构建开发平台。 ");
mes3=new Label("2.本系统暂时只能实现插入功能,可以对数据的有效性进行检验。关于其他的功能还有待开发。 操作过程中无需打开SQL Server");
mes4=new Label("3.该系统处处体现了人性化设计,具有一定的实用性和可移植性。") ;
msg.setText("欢迎进入学生信息管理系统,祝您愉快!O(∩_∩)O~"+"\n"+"\n"
+"本数据库管理系统 不支持 级联 删除 删除前请注意 数据的 唯一性 !!%>_<%"+"\n"+"\n"
+"student 支持由学号修改姓名,course 支持由课程号修改学分,sc 支持由学号和科目修改分数。"+"\n"+"\n"
+ "student 支持由学号删除其他项,course 支持由课程号删除其他项,sc 暂不支持删除功能。");
b1=new Button("查询");
b2=new Button("插入"); // 操作布局
b3=new Button("修改");
b4=new Button("删除");
p1=new Panel(); // 容器构造
p2=new Panel();
p3=new Panel();
p4=new Panel();
p5=new Panel();
p6=new Panel();
p7=new Panel();
p8=new Panel();
p9=new Panel();
p1.add(student);
p1.add(s1); p1.add(st1);
p1.add(s2); p1.add(st2);
p1.add(s3); p1.add(st4);
p1.add(s4); p1.add(st5);
p1.add(s5);
p1.add(m); // p1 容器
p1.add(w);
p2.add(course);
p2.add(c1); p2.add(ct1);
p2.add(c2); p2.add(ct2);
p2.add(c3); p2.add(ct3);
p2.add(c4); p2.add(ct4); // p2 容器
p3.add(sc);
p3.add(sc1); p3.add(sct1); // p3 容器
p3.add(sc2); p3.add(sct2);
p3.add(sc3); p3.add(sct3);
p3.add(mes);
p4.add(b1);
p4.add(b2); // p4 容器
p4.add(b3);
p4.add(b4);
p5.add(msg);
p6.add(mes1);
p7.add(mes2);
p8.add(mes3);
p9.add(mes4);
setLayout(new FlowLayout(0,8,8)); //布局构造
add(p1);
add(p2); // 添加容器到当前布局
add(p3);
add(p4);
add(p5);
add(p6);
add(p7);
add(p8);
add(p9);
b1.addActionListener(new B1());
b2.addActionListener(new B2()); // 为按钮创建事件
b3.addActionListener(new B3());
b4.addActionListener(new B4());
addWindowListener(new WinClose());
setSize(800,560);
setTitle("学生信息管理系统");
setVisible(true);
}
class B1 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
Statement stmt;
ResultSet rs;
stmt=cn.createStatement();
rs=stmt.executeQuery("SELECT * FROM student ");
while(rs.next())
{
System.out.println(rs.getString("sno")+" "+rs.getString("sname")+
" "+rs.getString("ssex")+" "+rs.getInt("sage")+" "+rs.getString("sdept"));
msg.setText("数据查询成功,已经显示在 控制台窗口!");
};
}
catch (SQLException e1)
{
System.out.println("数据库连接错误"+"\n");
System.exit(0);
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
Statement stmt;
ResultSet rs;
stmt=cn.createStatement();
rs=stmt.executeQuery("SELECT * FROM course ");
while(rs.next())
{
System.out.println(rs.getString("cno")+" "+rs.getString("cname")+" "+
rs.getString("cpno")+" "+rs.getString("ccredit"));
msg.setText("数据查询成功,已经显示在 控制台窗口!");
};
}
catch (SQLException e1)
{
System.out.println("数据库连接错误"+"\n");
System.exit(0);
};
}
else
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
Statement stmt;
ResultSet rs;
stmt=cn.createStatement();
rs=stmt.executeQuery("SELECT * FROM sc ");
while(rs.next())
{
System.out.println(rs.getString("sno")+" "+rs.getString("cno")+" "
+rs.getString("grade"));
msg.setText("数据查询成功,已经显示在 控制台窗口!");
};
}
catch (SQLException e1)
{
System.out.println("数据库连接错误"+"\n");
System.exit(0);
};
}
}
}
class B2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
scr="INSERT INTO student VALUES(?,?,?,?,?)" ;
cr=cn.prepareStatement(scr);
msg.setText("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
System.out.print("数据库连接错误"+"\n");
System.exit(0);
};
try
{
cr.setString(1, st1.getText()); //为SQL语句参数赋值
cr.setString(2, st2.getText());
if(m.getState())
ssex="男";
else
ssex="女";
cr.setString(3, ssex);
cr.setInt(4, Integer.parseInt(st4.getText()));
cr.setString(5, st5.getText());
cr.executeUpdate();
msg.setText("插入数据成功");
st1.setText("");
st2.setText(""); //清空各输入框
st4.setText("");
st5.setText("");
st1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
st1.requestFocus();
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
ccr="INSERT INTO course VALUES(?,?,?,?)" ;
cr=cn.prepareStatement(ccr);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
cr.setInt(1, Integer.parseInt(ct1.getText())); //为SQL语句参数赋值
cr.setString(2, ct2.getText());
cr.setString(3, ct3.getText());
cr.setString(4, ct4.getText());
cr.executeUpdate();
msg.setText("插入数据成功");
ct1.setText("");
ct2.setText(""); //清空各输入框
ct3.setText("");
ct4.setText("");
ct1.requestFocus();
}
catch (Exception e2)
{
msg.setText("输入数据有误!");
ct1.requestFocus();
};
}
else
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
sccr="INSERT INTO sc VALUES(?,?,?)" ;
cr=cn.prepareStatement(sccr);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
cr.setString(1, sct1.getText()); //为SQL语句参数赋值
cr.setInt(2, Integer.parseInt(sct2.getText()));
cr.setInt(3, Integer.parseInt(sct3.getText()));
cr.executeUpdate();
msg.setText("插入数据成功");
sct1.setText("");
sct2.setText(""); //清空各输入框
sct3.setText("");
sct1.requestFocus();
}
catch (Exception e2)
{
msg.setText("输入数据有误!");
sct1.requestFocus();
};
}
}
}
class B3 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
sxg="UPDATE student SET sname=? WHERE sno=?" ;
xg=cn.prepareStatement(sxg);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
xg.setString(1, st2.getText()); //为SQL语句参数赋值
xg.setString(2, st1.getText());
xg.executeUpdate();
msg.setText("修改数据成功!");
st1.setText("");
st2.setText(""); //清空各输入框
st4.setText("");
st5.setText("");
st1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
st1.requestFocus();
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
cxg="UPDATE course SET ccredit=? WHERE cno=?" ;
xg=cn.prepareStatement(cxg);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
xg.setString(1, ct4.getText()); //为SQL语句参数赋值
xg.setString(2, ct1.getText());
xg.executeUpdate();
msg.setText("修改数据成功!");
ct1.setText("");
ct2.setText("");
ct3.setText("");
ct4.setText(""); //清空各输入框
ct1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
ct1.requestFocus();
};
}
else
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接 <SUF>
scxg="UPDATE sc SET grade=? WHERE sno=? AND cno=?" ;
xg=cn.prepareStatement(scxg);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
msg.setText("数据库连接错误"+"\n");
System.exit(0);
};
try
{
xg.setString(1, sct3.getText()); //为SQL语句参数赋值
xg.setString(2, sct1.getText());
xg.setString(3, sct2.getText());
xg.executeUpdate();
msg.setText("修改数据成功!");
sct1.setText("");
sct2.setText("");
sct3.setText(""); //清空各输入框
sct1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
sct1.requestFocus();
};
}
}
}
class B4 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(student.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
ssc="DELETE FROM student WHERE sno=?" ;
sg=cn.prepareStatement(ssc);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
System.out.print("数据库连接错误"+"\n");
System.exit(0);
};
try
{
sg.setString(1, st1.getText()); //为SQL语句参数赋值
sg.executeUpdate();
msg.setText("删除数据成功!");
st1.setText("");
st2.setText(""); //清空各输入框
st1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
st1.requestFocus();
};
}
else if(course.getState())
{
try
{
String connectDB = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=学生课程管理";// 数据源
String user = "sa";
String password = "sa";
Connection cn = DriverManager.getConnection(connectDB, user, password);// 连接数据库对象
csc="DELETE FROM course WHERE cno=?" ;
sg=cn.prepareStatement(csc);
System.out.print("连接数据库成功"+"\n");
}
catch (SQLException e1)
{
System.out.print("数据库连接错误"+"\n");
System.exit(0);
};
try
{
sg.setInt(1, Integer.parseInt(ct1.getText())); //为SQL语句参数赋值
sg.executeUpdate();
msg.setText("删除数据成功!");
ct1.setText("");
ct2.setText("");
ct3.setText("");
ct4.setText("");//清空各输入框
ct1.requestFocus();
}
catch (Exception s2)
{
msg.setText("输入数据有误!");
ct1.requestFocus();
};
}
else
{
msg.setText(" 对不起,暂不支持对 SC 表进行删除操作!");
}
}
}
class WinClose extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
(e.getWindow()).dispose();
System.exit(0);
}
}
}
| 1 | 10 | 1 |
25043_3 | class Solution {
public int[] pondSizes(int[][] land) {
int m = land.length, n = land[0].length;
var ans = new ArrayList<Integer>();
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (land[i][j] == 0) // 从没有访问过的 0 出发
ans.add(dfs(land, i, j));
// 简洁写法,但是慢
// return ans.stream().sorted().mapToInt(i -> i).toArray();
// 更快的写法
var size = new int[ans.size()];
int i = 0;
for (int x : ans)
size[i++] = x;
Arrays.sort(size);
return size;
}
private int dfs(int[][] land, int x, int y) {
if (x < 0 || x >= land.length || y < 0 || y >= land[x].length || land[x][y] != 0)
return 0;
land[x][y] = 1; // 标记 (x,y) 被访问,避免重复访问
int cnt0 = 1;
// 访问八方向的 0
for (int i = x - 1; i <= x + 1; i++)
for (int j = y - 1; j <= y + 1; j++)
cnt0 += dfs(land, i, j);
return cnt0;
}
} | Autunomy/algothrim-study | leetcode/每日一题/2023/06/22/solution.java | 353 | // 更快的写法 | line_comment | zh-cn | class Solution {
public int[] pondSizes(int[][] land) {
int m = land.length, n = land[0].length;
var ans = new ArrayList<Integer>();
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (land[i][j] == 0) // 从没有访问过的 0 出发
ans.add(dfs(land, i, j));
// 简洁写法,但是慢
// return ans.stream().sorted().mapToInt(i -> i).toArray();
// 更快 <SUF>
var size = new int[ans.size()];
int i = 0;
for (int x : ans)
size[i++] = x;
Arrays.sort(size);
return size;
}
private int dfs(int[][] land, int x, int y) {
if (x < 0 || x >= land.length || y < 0 || y >= land[x].length || land[x][y] != 0)
return 0;
land[x][y] = 1; // 标记 (x,y) 被访问,避免重复访问
int cnt0 = 1;
// 访问八方向的 0
for (int i = x - 1; i <= x + 1; i++)
for (int j = y - 1; j <= y + 1; j++)
cnt0 += dfs(land, i, j);
return cnt0;
}
} | 1 | 8 | 1 |
48094_1 | package io.nio.chatroom2;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NioClient {
public static void main(String[] args) throws IOException {
// Nio的通用写法,保证不阻塞,注意clientSocketChannel这个名称,这个是客户端的socketChannel
SocketChannel clientSocketChannel = SocketChannel.open();
clientSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
// 连接客户端,可以理解成:客户端执行连接操作时,就会产生连接事件,此时这个事件还在socketChannel中。
clientSocketChannel.connect(new InetSocketAddress("47.92.149.10", 80));
// 将socketChannel注册到selector中,由selector来关联socketChannel的连接事件
clientSocketChannel.register(selector, SelectionKey.OP_CONNECT);
while (true) {
/**
* 在selector中寻找一次,看selector中是否有事件发生,如果没有时间发生,则会阻塞到这里。
* 但由于我们在初始化客户端的过程中已经执行了连接服务器的操作 ---> 这段代码:clientSocketChannel.configureBlocking(false)
* 因此此处不会阻塞,会往下执行
*
* 目前selector中只注册了一个clientSocketChannel,且这个clientSocketChannel对connect事件 “感兴趣”
* 因此,此次寻找,就是看是否有clientSocketChannel的connect事件发生,如果有发生,则会
* 将这个事件放入到一个set集合中,并且解阻塞。
*
* 注意:虽然注册只有socketChannel的connect事件,但只要socketChannel有事件发生了,这个地方
* 都会解除阻塞。
* 举个例子:
* 客户端拿到clientSocketChannel主动连接服务端,会产生connect事件,因此这个select方法会解除阻塞
* 客户端拿到clientSocketChannel向服务端写数据,会产生write事件,这个select也会解除阻塞
* 服务端拿到客户端的clientSocketChannel并往里面写数据,对于客户端而言:会产生read事件,这个select也会解除阻塞
* .....
*
* 因此,这个地方比较重要的点就是:
* 只要注册到selector中的channel有事件发生,则会解除阻塞,如果这个事件是channel感兴趣的事件,则会进入set集合中
*/
int select = selector.select();
/**
* 执行到这里,那肯定是上述的select方法解除阻塞了 ===> 这代表着有感兴趣的事件发生了,接下来需要处理感兴趣的事件了
* 而此时的事件就是连接事件。SelectionKey对象可以描述当前是什么事件。
*
* 这个set集合只会保存感兴趣的事件
*/
Set<SelectionKey> set = selector.selectedKeys();
System.out.println("产生的事件个数: ===> " + set.size());
// 遍历迭代器,开始处理事件
Iterator<SelectionKey> iterator = set.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
// 这个socketChannel与上述的clientSocketChannel一致
SocketChannel socketChannel = (SocketChannel) key.channel();
/**
* 验证key对应的通道是否已完成或未能完成其套接字连接操作 --> 这种情况都是返回true
* 若key对应的通道不支持链接时,才会返回false。
* 因此可以断定:只要是连接了客户端
*/
if (key.isConnectable()) {
/**
* 下面三行代码保证客户端能连接上服务器。
* 若连接失败,则会抛出异常,
* @see SocketChannel#finishConnect() 方法的签名
*/
if (socketChannel.isConnectionPending()) {
socketChannel.finishConnect();
}
// 连接服务器成功后,向服务器发送一段信息:I have been connected server
socketChannel.write(ByteBuffer.wrap("I have been connected server".getBytes()));
/**
* 还记得上面的select方法么。select方法是 只要有事件发生了就会解除阻塞。
* 而selectedKeys方法是 只筛选出感兴趣的事件。在此处注册一个read事件的原因就是
* 等会服务端会拿到客户端的clientSocketChannel并往里面写数据,
* 对客户端而言:这个操作就是一个读事件。因此这里注册一个读事件,为了就是能
* 在selectedKeys方法中把这个读事件找出来。不然的话select方法将会一直
* 解除阻塞,因为里面一直有一个读事件没有被处理,而且clientSocketChannel也
* 对读事件不感兴趣,最终会导致外层的while循环因select没有阻塞,会一直执行。
*
* 可以测试:将这段代码注释掉,看客户端是否一直在打印:产生的事件个数: ===> 0
*/
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
/**
* 这里就是处理服务端发来的消息,就是使用ByteBuffer操作channel中的数据。
* 这里模拟了传输大数据量的情况,设置的byteBuffer的数组长度只有5。
* 这里涉及到channel的read方法,当read方法返回值 > 0 时,表示读取到的数据。
* 可能为0 或者 -1. 具体情况可以查看read方法的注释
* @see ReadableByteChannel#read(java.nio.ByteBuffer)
*/
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
int len;
while ((len = socketChannel.read(byteBuffer)) > 0) {
System.out.print(new String(byteBuffer.array(), 0, len));
byteBuffer.flip();
}
}
// 感兴趣的事件处理完毕后,移除掉
iterator.remove();
}
}
}
}
| AvengerEug/javase | src/main/java/io/nio/chatroom2/NioClient.java | 1,430 | // 连接客户端,可以理解成:客户端执行连接操作时,就会产生连接事件,此时这个事件还在socketChannel中。 | line_comment | zh-cn | package io.nio.chatroom2;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NioClient {
public static void main(String[] args) throws IOException {
// Nio的通用写法,保证不阻塞,注意clientSocketChannel这个名称,这个是客户端的socketChannel
SocketChannel clientSocketChannel = SocketChannel.open();
clientSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
// 连接 <SUF>
clientSocketChannel.connect(new InetSocketAddress("47.92.149.10", 80));
// 将socketChannel注册到selector中,由selector来关联socketChannel的连接事件
clientSocketChannel.register(selector, SelectionKey.OP_CONNECT);
while (true) {
/**
* 在selector中寻找一次,看selector中是否有事件发生,如果没有时间发生,则会阻塞到这里。
* 但由于我们在初始化客户端的过程中已经执行了连接服务器的操作 ---> 这段代码:clientSocketChannel.configureBlocking(false)
* 因此此处不会阻塞,会往下执行
*
* 目前selector中只注册了一个clientSocketChannel,且这个clientSocketChannel对connect事件 “感兴趣”
* 因此,此次寻找,就是看是否有clientSocketChannel的connect事件发生,如果有发生,则会
* 将这个事件放入到一个set集合中,并且解阻塞。
*
* 注意:虽然注册只有socketChannel的connect事件,但只要socketChannel有事件发生了,这个地方
* 都会解除阻塞。
* 举个例子:
* 客户端拿到clientSocketChannel主动连接服务端,会产生connect事件,因此这个select方法会解除阻塞
* 客户端拿到clientSocketChannel向服务端写数据,会产生write事件,这个select也会解除阻塞
* 服务端拿到客户端的clientSocketChannel并往里面写数据,对于客户端而言:会产生read事件,这个select也会解除阻塞
* .....
*
* 因此,这个地方比较重要的点就是:
* 只要注册到selector中的channel有事件发生,则会解除阻塞,如果这个事件是channel感兴趣的事件,则会进入set集合中
*/
int select = selector.select();
/**
* 执行到这里,那肯定是上述的select方法解除阻塞了 ===> 这代表着有感兴趣的事件发生了,接下来需要处理感兴趣的事件了
* 而此时的事件就是连接事件。SelectionKey对象可以描述当前是什么事件。
*
* 这个set集合只会保存感兴趣的事件
*/
Set<SelectionKey> set = selector.selectedKeys();
System.out.println("产生的事件个数: ===> " + set.size());
// 遍历迭代器,开始处理事件
Iterator<SelectionKey> iterator = set.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
// 这个socketChannel与上述的clientSocketChannel一致
SocketChannel socketChannel = (SocketChannel) key.channel();
/**
* 验证key对应的通道是否已完成或未能完成其套接字连接操作 --> 这种情况都是返回true
* 若key对应的通道不支持链接时,才会返回false。
* 因此可以断定:只要是连接了客户端
*/
if (key.isConnectable()) {
/**
* 下面三行代码保证客户端能连接上服务器。
* 若连接失败,则会抛出异常,
* @see SocketChannel#finishConnect() 方法的签名
*/
if (socketChannel.isConnectionPending()) {
socketChannel.finishConnect();
}
// 连接服务器成功后,向服务器发送一段信息:I have been connected server
socketChannel.write(ByteBuffer.wrap("I have been connected server".getBytes()));
/**
* 还记得上面的select方法么。select方法是 只要有事件发生了就会解除阻塞。
* 而selectedKeys方法是 只筛选出感兴趣的事件。在此处注册一个read事件的原因就是
* 等会服务端会拿到客户端的clientSocketChannel并往里面写数据,
* 对客户端而言:这个操作就是一个读事件。因此这里注册一个读事件,为了就是能
* 在selectedKeys方法中把这个读事件找出来。不然的话select方法将会一直
* 解除阻塞,因为里面一直有一个读事件没有被处理,而且clientSocketChannel也
* 对读事件不感兴趣,最终会导致外层的while循环因select没有阻塞,会一直执行。
*
* 可以测试:将这段代码注释掉,看客户端是否一直在打印:产生的事件个数: ===> 0
*/
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
/**
* 这里就是处理服务端发来的消息,就是使用ByteBuffer操作channel中的数据。
* 这里模拟了传输大数据量的情况,设置的byteBuffer的数组长度只有5。
* 这里涉及到channel的read方法,当read方法返回值 > 0 时,表示读取到的数据。
* 可能为0 或者 -1. 具体情况可以查看read方法的注释
* @see ReadableByteChannel#read(java.nio.ByteBuffer)
*/
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
int len;
while ((len = socketChannel.read(byteBuffer)) > 0) {
System.out.print(new String(byteBuffer.array(), 0, len));
byteBuffer.flip();
}
}
// 感兴趣的事件处理完毕后,移除掉
iterator.remove();
}
}
}
}
| 1 | 58 | 1 |
12684_2 | package com.github.unclecatmyself.core.bean;
/**
* 用户层消息Bean封装
* Created by MySelf on 2018/12/19.
*/
public class InChatMessage {
/** 消息时间 */
private int time;
/** 消息类型 */
private String type;
/** 消息值 */
private String value;
/** 用户标识 */
private String token;
/** 群聊Id */
private String groupId;
/** 是否在线-个人 */
private String online;
/** 是否在线-群聊 */
private String onlineGroup;
/** 消息接收人标识 */
private String one;
public String getOnlineGroup() {
return onlineGroup;
}
public void setOnlineGroup(String onlineGroup) {
this.onlineGroup = onlineGroup;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getOnline() {
return online;
}
public void setOnline(String online) {
this.online = online;
}
public String getOne() {
return one;
}
public void setOne(String one) {
this.one = one;
}
@Override
public String toString() {
return "InChatMessage{" +
"time=" + time +
", type='" + type + '\'' +
", value='" + value + '\'' +
", token='" + token + '\'' +
", groupId='" + groupId + '\'' +
", online='" + online + '\'' +
", onlineGroup='" + onlineGroup + '\'' +
", one='" + one + '\'' +
'}';
}
}
| AwakenCN/InChat | src/main/java/com/github/unclecatmyself/core/bean/InChatMessage.java | 510 | /** 消息类型 */ | block_comment | zh-cn | package com.github.unclecatmyself.core.bean;
/**
* 用户层消息Bean封装
* Created by MySelf on 2018/12/19.
*/
public class InChatMessage {
/** 消息时间 */
private int time;
/** 消息类 <SUF>*/
private String type;
/** 消息值 */
private String value;
/** 用户标识 */
private String token;
/** 群聊Id */
private String groupId;
/** 是否在线-个人 */
private String online;
/** 是否在线-群聊 */
private String onlineGroup;
/** 消息接收人标识 */
private String one;
public String getOnlineGroup() {
return onlineGroup;
}
public void setOnlineGroup(String onlineGroup) {
this.onlineGroup = onlineGroup;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getOnline() {
return online;
}
public void setOnline(String online) {
this.online = online;
}
public String getOne() {
return one;
}
public void setOne(String one) {
this.one = one;
}
@Override
public String toString() {
return "InChatMessage{" +
"time=" + time +
", type='" + type + '\'' +
", value='" + value + '\'' +
", token='" + token + '\'' +
", groupId='" + groupId + '\'' +
", online='" + online + '\'' +
", onlineGroup='" + onlineGroup + '\'' +
", one='" + one + '\'' +
'}';
}
}
| 1 | 11 | 1 |
64213_4 | package com.awaken.leetcode.array;
/**
* @Auther: Noseparte
* @Date: 2020/5/7 7:40 下午
* @Description:
*
* <p>
* 1011. 在 D 天内送达包裹的能力
*
* 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
* 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
* 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
* </p>
*
*/
public class ShipWithinDays {
public int shipWithinDays(int[] weights, int D) {
int lo = 0, hi = Integer.MAX_VALUE;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (canShip(weights, D, mid)) {
hi = mid;
} else {
lo = mid+1;
}
}
return lo;
}
/**
* 定义函数canShip(D, K),来判断在最低承载力为K的情形下能否在DD天内送达所有包裹。我们所要做的就是按照传送带上货物的顺序,依次且尽可能多地往船上装载货物,当该艘船无法装下更多货物时,我们换一搜船,同时将天数加1。当运输完所有货物后,我们判断所用的天数是否小于等于D。
* 用二分查找的方式,来查找这个最低承载力,如果midmid可以完成任务,我们把查找范围缩减至[lo, mid][lo,mid](注意不是mid+1mid+1,因为mid可能是我们所求的解),否则我们去[mid+1, hi][mid+1,hi]区间中继续查找,详情见代码。
*
*/
private boolean canShip(int[] weights, int D, int K) {
int cur = K; // cur 表示当前船的可用承载量
for (int weight: weights) {
if (weight > K) return false;
if (cur < weight) {
cur = K;
D--;
}
cur -= weight;
}
return D > 0; // 能否在D天内运完
}
/**
* 示例 1:
*
* 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
* 输出:15
* 解释:
* 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
* 第 1 天:1, 2, 3, 4, 5
* 第 2 天:6, 7
* 第 3 天:8
* 第 4 天:9
* 第 5 天:10
*
* 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
*
*
* 示例 2:
* 输入:weights = [3,2,2,4,1,4], D = 3
* 输出:6
* 解释:
* 船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示:
* 第 1 天:3, 2
* 第 2 天:2, 4
* 第 3 天:1, 4
*
*
* 示例 3:
*
* 输入:weights = [1,2,3,1,1], D = 4
* 输出:3
* 解释:
* 第 1 天:1
* 第 2 天:2
* 第 3 天:3
* 第 4 天:1, 1
*
*
* 提示:
*
* 1 <= D <= weights.length <= 50000
* 1 <= weights[i] <= 500
*
*/
public static void main(String[] args) {
int ship = new ShipWithinDays().shipWithinDays(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5);
System.out.println(ship);
}
}
| AwakenCN/Nine-Chapters | src/main/java/com/awaken/leetcode/array/ShipWithinDays.java | 1,182 | /**
* 示例 1:
*
* 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
* 输出:15
* 解释:
* 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
* 第 1 天:1, 2, 3, 4, 5
* 第 2 天:6, 7
* 第 3 天:8
* 第 4 天:9
* 第 5 天:10
*
* 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
*
*
* 示例 2:
* 输入:weights = [3,2,2,4,1,4], D = 3
* 输出:6
* 解释:
* 船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示:
* 第 1 天:3, 2
* 第 2 天:2, 4
* 第 3 天:1, 4
*
*
* 示例 3:
*
* 输入:weights = [1,2,3,1,1], D = 4
* 输出:3
* 解释:
* 第 1 天:1
* 第 2 天:2
* 第 3 天:3
* 第 4 天:1, 1
*
*
* 提示:
*
* 1 <= D <= weights.length <= 50000
* 1 <= weights[i] <= 500
*
*/ | block_comment | zh-cn | package com.awaken.leetcode.array;
/**
* @Auther: Noseparte
* @Date: 2020/5/7 7:40 下午
* @Description:
*
* <p>
* 1011. 在 D 天内送达包裹的能力
*
* 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
* 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
* 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
* </p>
*
*/
public class ShipWithinDays {
public int shipWithinDays(int[] weights, int D) {
int lo = 0, hi = Integer.MAX_VALUE;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (canShip(weights, D, mid)) {
hi = mid;
} else {
lo = mid+1;
}
}
return lo;
}
/**
* 定义函数canShip(D, K),来判断在最低承载力为K的情形下能否在DD天内送达所有包裹。我们所要做的就是按照传送带上货物的顺序,依次且尽可能多地往船上装载货物,当该艘船无法装下更多货物时,我们换一搜船,同时将天数加1。当运输完所有货物后,我们判断所用的天数是否小于等于D。
* 用二分查找的方式,来查找这个最低承载力,如果midmid可以完成任务,我们把查找范围缩减至[lo, mid][lo,mid](注意不是mid+1mid+1,因为mid可能是我们所求的解),否则我们去[mid+1, hi][mid+1,hi]区间中继续查找,详情见代码。
*
*/
private boolean canShip(int[] weights, int D, int K) {
int cur = K; // cur 表示当前船的可用承载量
for (int weight: weights) {
if (weight > K) return false;
if (cur < weight) {
cur = K;
D--;
}
cur -= weight;
}
return D > 0; // 能否在D天内运完
}
/**
* 示例 <SUF>*/
public static void main(String[] args) {
int ship = new ShipWithinDays().shipWithinDays(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5);
System.out.println(ship);
}
}
| 1 | 791 | 0 |
60771_5 | public class Bag {
/*本代码实现了用回溯法实现01背包问题。亮点之一在于右子树的剪枝函数的设计非常之巧妙。
* 在回溯开始之前,首先对于背包中的物品按照单位重量价值进行排序,方便于后面右子树的剪枝操作。
* 在本代码中,省略了该排序过程,在初始化物品的重量和价值时,已经按照单位重量的价值排好了序。
* 该问题是一个典型的子集树问题,对于背包中的每一个物品,可以选择放入(左子树)或者不放入(右子树)。
* 依次对每个节点进行搜索,得到最优解。
*
* 剪枝函数:对于左子树,如果放入物品的重量已经超过了背包的容量,则直接进行剪枝。
* 对于右子树,是否可以直接跳过本层的物品,直接下一层的搜索操作呢?
* 这要取决于当前背包剩余的容量,依次取背包中剩余的物品中单位重量价值最大的物品(跳过本层物品),
* 最终能否超过此前找到的最优解,如果能够超过,则可以向右搜索,不能超过,则右节点变为死节点。
* 对于寻找剩余物品的最高价值上界,按照背包中剩余空间依次取剩下的物品,当空间不足以取下一个
* 物品时,则将下一个物品的单位重量价值折算到现在的剩余空间中去计算理想最高上界。
* */
int n = 3;
int capacity = 30;
int[] weight = {16, 15, 15};
double[] value = {45, 25, 25};
int maxValue = 0;
int tempValue;
int tempWeight;
int[] way = new int[n];
int[] bestWay = new int[n];
public void backTrack(int t) {
//当前轮结束,如果价值为最大,保存起来
if (t > n - 1) {
if (tempValue > maxValue) {
maxValue = tempValue;
for (int i = 0; i < n; i++)
bestWay[i] = way[i];
}
return;
}
//搜索左边节点
if (tempWeight + weight[t] <= capacity) {
tempWeight += weight[t];
tempValue += value[t];
way[t] = 1;
backTrack(t + 1);
tempWeight -= weight[t];
tempValue -= value[t];
way[t] = 0;
}
//不装入这个物品,直接搜索右边的节点
if (bound(t + 1) >= maxValue) {
backTrack(t + 1);
}
}
//用于计算剩余物品的最高价值上界
public double bound(int k) {
double maxLeft = tempValue;
int leftWeight = capacity - tempWeight;
//尽力依照单位重量价值次序装剩余的物品
while (k <= n - 1 && leftWeight > weight[k]) {
leftWeight -= weight[k];
maxLeft += value[k];
k++;
}
//不能装时,用下一个物品的单位重量价值折算到剩余空间。
if (k <= n - 1) {
maxLeft += value[k] / weight[k] * leftWeight;
}
return maxLeft;
}
public static void main(String[] args) {
Bag b = new Bag();
b.backTrack(0);
System.out.println("该背包能够取到的最大价值为:" + b.maxValue);
System.out.println("取出的方法为:");
for (int i : b.bestWay)
System.out.print(i + " ");
}
}
| AyoungYa/basic_study | src/Bag.java | 968 | //尽力依照单位重量价值次序装剩余的物品 | line_comment | zh-cn | public class Bag {
/*本代码实现了用回溯法实现01背包问题。亮点之一在于右子树的剪枝函数的设计非常之巧妙。
* 在回溯开始之前,首先对于背包中的物品按照单位重量价值进行排序,方便于后面右子树的剪枝操作。
* 在本代码中,省略了该排序过程,在初始化物品的重量和价值时,已经按照单位重量的价值排好了序。
* 该问题是一个典型的子集树问题,对于背包中的每一个物品,可以选择放入(左子树)或者不放入(右子树)。
* 依次对每个节点进行搜索,得到最优解。
*
* 剪枝函数:对于左子树,如果放入物品的重量已经超过了背包的容量,则直接进行剪枝。
* 对于右子树,是否可以直接跳过本层的物品,直接下一层的搜索操作呢?
* 这要取决于当前背包剩余的容量,依次取背包中剩余的物品中单位重量价值最大的物品(跳过本层物品),
* 最终能否超过此前找到的最优解,如果能够超过,则可以向右搜索,不能超过,则右节点变为死节点。
* 对于寻找剩余物品的最高价值上界,按照背包中剩余空间依次取剩下的物品,当空间不足以取下一个
* 物品时,则将下一个物品的单位重量价值折算到现在的剩余空间中去计算理想最高上界。
* */
int n = 3;
int capacity = 30;
int[] weight = {16, 15, 15};
double[] value = {45, 25, 25};
int maxValue = 0;
int tempValue;
int tempWeight;
int[] way = new int[n];
int[] bestWay = new int[n];
public void backTrack(int t) {
//当前轮结束,如果价值为最大,保存起来
if (t > n - 1) {
if (tempValue > maxValue) {
maxValue = tempValue;
for (int i = 0; i < n; i++)
bestWay[i] = way[i];
}
return;
}
//搜索左边节点
if (tempWeight + weight[t] <= capacity) {
tempWeight += weight[t];
tempValue += value[t];
way[t] = 1;
backTrack(t + 1);
tempWeight -= weight[t];
tempValue -= value[t];
way[t] = 0;
}
//不装入这个物品,直接搜索右边的节点
if (bound(t + 1) >= maxValue) {
backTrack(t + 1);
}
}
//用于计算剩余物品的最高价值上界
public double bound(int k) {
double maxLeft = tempValue;
int leftWeight = capacity - tempWeight;
//尽力 <SUF>
while (k <= n - 1 && leftWeight > weight[k]) {
leftWeight -= weight[k];
maxLeft += value[k];
k++;
}
//不能装时,用下一个物品的单位重量价值折算到剩余空间。
if (k <= n - 1) {
maxLeft += value[k] / weight[k] * leftWeight;
}
return maxLeft;
}
public static void main(String[] args) {
Bag b = new Bag();
b.backTrack(0);
System.out.println("该背包能够取到的最大价值为:" + b.maxValue);
System.out.println("取出的方法为:");
for (int i : b.bestWay)
System.out.print(i + " ");
}
}
| 1 | 20 | 1 |
59194_1 | package com.waibao.team.tuyou.model;
public class Category {
private String id;
private String type; //类型(国内,国外)
private String second_type; //刺激探险,休闲娱乐
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSecond_type() {
return second_type;
}
public void setSecond_type(String second_type) {
this.second_type = second_type;
}
}
| AzusaL/TuYou | app/src/main/java/com/waibao/team/tuyou/model/Category.java | 191 | //刺激探险,休闲娱乐 | line_comment | zh-cn | package com.waibao.team.tuyou.model;
public class Category {
private String id;
private String type; //类型(国内,国外)
private String second_type; //刺激 <SUF>
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSecond_type() {
return second_type;
}
public void setSecond_type(String second_type) {
this.second_type = second_type;
}
}
| 0 | 11 | 0 |
33850_0 | package atomic;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
/**
* 并行计算,不在乎执行顺序
*/
public class LongAccumulatorDemo {
public static void main(String[] args) {
LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0);
ExecutorService executorService = Executors.newFixedThreadPool(8);
IntStream.range(1, 10).forEach(i -> executorService.submit(() -> longAccumulator.accumulate(i)));
executorService.shutdown();
while(!executorService.isTerminated()) {
// Thread.sleep(10);
}
longAccumulator.accumulate(1);
System.out.println(longAccumulator.getThenReset());
}
}
| BBYYSS0917/juc-demo | src/main/java/atomic/LongAccumulatorDemo.java | 202 | /**
* 并行计算,不在乎执行顺序
*/ | block_comment | zh-cn | package atomic;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
/**
* 并行计 <SUF>*/
public class LongAccumulatorDemo {
public static void main(String[] args) {
LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0);
ExecutorService executorService = Executors.newFixedThreadPool(8);
IntStream.range(1, 10).forEach(i -> executorService.submit(() -> longAccumulator.accumulate(i)));
executorService.shutdown();
while(!executorService.isTerminated()) {
// Thread.sleep(10);
}
longAccumulator.accumulate(1);
System.out.println(longAccumulator.getThenReset());
}
}
| 1 | 23 | 1 |
37384_20 | package DDL;
import java.util.Arrays;
import java.util.Random;
//此程序用于调试测试Floyd算法
public class AlTest {
public static void main(String[] args) {
//定义矩阵大小,有多少个点
//超过26个时,建议使用字符串命名
int n=10;
//随机初始化一个n*n的矩阵
int[][] matrix = CreateData(n);
//创建Graph对象,此对象进行最短路径的计算
Graph graph=new Graph(n);
//各个节点的名称
String[] names=new String[n];
//这里测试使用字母
for (int i=0;i<n;i++){
//字母命名
// names[i]=Character.toString('A'+i);
//字符串命名
names[i]="A"+i;
}
graph.setNames(names);
graph.setMatrix(matrix);
//初始化矩阵
graph.initMatrix();
//测试结果是否相同
//调用Floyd算法
int[][] a1=new int[n][n];
int[][] floyd = graph.Floyd();
a1=floyd;
for (int[] ints : floyd) {
System.out.println(Arrays.toString(ints));
}
System.out.println();
//使用Dijkstra算法
int[][] a2=new int[n][n];
for (int i=0;i<n;i++){
graph.initStates();
//对每个节点进行一次Dijkstra算法,获得
a2[i]=graph.Dijkstra(i);
System.out.println(Arrays.toString(a2[i]));
}
System.out.println();
//使用Bellman_Ford算法
int[][] a3=new int[n][n];
for (int i=0;i<n;i++){
//对每个节点进行一次Bellman_Ford算法,获得
a3[i]=graph.Bellman_Ford(i);
System.out.println(Arrays.toString(a3[i]));
}
System.out.println();
//使用SPFA算法
int[][] a4=new int[n][n];
for (int i=0;i<n;i++){
graph.initStates();
//对每个节点进行一次SPFA算法,获得
a4[i]=graph.SPFA(i);
System.out.println(Arrays.toString(a4[i]));
}
System.out.println();
//使用SPFA算法
int[][] a5=new int[n][n];
for (int i=0;i<n;i++){
graph.initStates();
//对每个节点进行一次SPFA算法,获得
a5[i]=graph.DFS(i);
System.out.println(Arrays.toString(a5[i]));
}
check(a1,a2);
check(a2,a3);
check(a3,a4);
check(a2,a5);
}
//数据自生成
public static int[][] CreateData(int n){
int [][] data=new int[n][n];
Random random=new Random();
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i==j) data[i][j]=0;
else{
if (random.nextInt(10)>4){
data[i][j]=random.nextInt(10,100);
}else
data[i][j]=0;
}
}
}
return data;
}
//检测两个二维矩阵是否相同
public static void check(int[][] a,int[][] b){
if (a.length!= b.length||a[0].length!=b[0].length){
System.out.println("不同");
return;
}
int n=a.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j]!=b[i][j]){
System.out.println("两矩阵不同");
return;
}
}
}
System.out.println("两矩阵相同");
}
}
| BDacy/myexercise | src/DDL/AlTest.java | 981 | //对每个节点进行一次SPFA算法,获得 | line_comment | zh-cn | package DDL;
import java.util.Arrays;
import java.util.Random;
//此程序用于调试测试Floyd算法
public class AlTest {
public static void main(String[] args) {
//定义矩阵大小,有多少个点
//超过26个时,建议使用字符串命名
int n=10;
//随机初始化一个n*n的矩阵
int[][] matrix = CreateData(n);
//创建Graph对象,此对象进行最短路径的计算
Graph graph=new Graph(n);
//各个节点的名称
String[] names=new String[n];
//这里测试使用字母
for (int i=0;i<n;i++){
//字母命名
// names[i]=Character.toString('A'+i);
//字符串命名
names[i]="A"+i;
}
graph.setNames(names);
graph.setMatrix(matrix);
//初始化矩阵
graph.initMatrix();
//测试结果是否相同
//调用Floyd算法
int[][] a1=new int[n][n];
int[][] floyd = graph.Floyd();
a1=floyd;
for (int[] ints : floyd) {
System.out.println(Arrays.toString(ints));
}
System.out.println();
//使用Dijkstra算法
int[][] a2=new int[n][n];
for (int i=0;i<n;i++){
graph.initStates();
//对每个节点进行一次Dijkstra算法,获得
a2[i]=graph.Dijkstra(i);
System.out.println(Arrays.toString(a2[i]));
}
System.out.println();
//使用Bellman_Ford算法
int[][] a3=new int[n][n];
for (int i=0;i<n;i++){
//对每个节点进行一次Bellman_Ford算法,获得
a3[i]=graph.Bellman_Ford(i);
System.out.println(Arrays.toString(a3[i]));
}
System.out.println();
//使用SPFA算法
int[][] a4=new int[n][n];
for (int i=0;i<n;i++){
graph.initStates();
//对每个节点进行一次SPFA算法,获得
a4[i]=graph.SPFA(i);
System.out.println(Arrays.toString(a4[i]));
}
System.out.println();
//使用SPFA算法
int[][] a5=new int[n][n];
for (int i=0;i<n;i++){
graph.initStates();
//对每 <SUF>
a5[i]=graph.DFS(i);
System.out.println(Arrays.toString(a5[i]));
}
check(a1,a2);
check(a2,a3);
check(a3,a4);
check(a2,a5);
}
//数据自生成
public static int[][] CreateData(int n){
int [][] data=new int[n][n];
Random random=new Random();
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i==j) data[i][j]=0;
else{
if (random.nextInt(10)>4){
data[i][j]=random.nextInt(10,100);
}else
data[i][j]=0;
}
}
}
return data;
}
//检测两个二维矩阵是否相同
public static void check(int[][] a,int[][] b){
if (a.length!= b.length||a[0].length!=b[0].length){
System.out.println("不同");
return;
}
int n=a.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j]!=b[i][j]){
System.out.println("两矩阵不同");
return;
}
}
}
System.out.println("两矩阵相同");
}
}
| 0 | 20 | 0 |
20809_2 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.abel533.echarts.samples.force;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.code.*;
import com.github.abel533.echarts.series.Force;
import com.github.abel533.echarts.series.force.Link;
import com.github.abel533.echarts.series.force.Node;
import com.github.abel533.echarts.style.LinkStyle;
import com.github.abel533.echarts.style.NodeStyle;
import com.github.abel533.echarts.style.TextStyle;
import com.github.abel533.echarts.util.EnhancedOption;
import org.junit.Test;
/**
* @author liuzh
*/
public class ForceTest1 {
@Test
public void test() {
//地址:http://echarts.baidu.com/doc/example/force1.html
EnhancedOption option = new EnhancedOption();
option.title().text("人物关系:乔布斯").subtext("数据来自人立方").x(X.right).y(Y.bottom);
option.tooltip().trigger(Trigger.item).formatter("{a} : {b}");
option.toolbox().show(true).feature(Tool.restore, Tool.saveAsImage);
option.legend("家人", "朋友").legend().x(X.left);
//数据
Force force = new Force("人物关系");
force.categories("人物", "家人", "朋友");
force.itemStyle().normal()
.label(new Label().show(true).textStyle(new TextStyle().color("#333")))
.nodeStyle().brushType(BrushType.both).color("rgba(255,215,0,0.4)").borderWidth(1);
force.itemStyle().emphasis()
.linkStyle(new LinkStyle())
.nodeStyle(new NodeStyle())
.label().show(true);
force.useWorker(false).minRadius(15).maxRadius(25).gravity(1.1).scaling(1.1).linkSymbol(Symbol.arrow);
force.nodes(new Node(0, "乔布斯", 10),
new Node(1, "丽萨-乔布斯", 2),
new Node(1, "保罗-乔布斯", 3),
new Node(1, "克拉拉-乔布斯", 3),
new Node(1, "劳伦-鲍威尔", 7),
new Node(2, "史蒂夫-沃兹尼艾克", 5),
new Node(2, "奥巴马", 8),
new Node(2, "比尔-盖茨", 9),
new Node(2, "乔纳森-艾夫", 4),
new Node(2, "蒂姆-库克", 4),
new Node(2, "龙-韦恩", 1));
force.links(new Link("丽萨-乔布斯", "乔布斯", 1),
new Link("保罗-乔布斯", "乔布斯", 2),
new Link("克拉拉-乔布斯", "乔布斯", 1),
new Link("劳伦-鲍威尔", "乔布斯", 2),
new Link("史蒂夫-沃兹尼艾克", "乔布斯", 3),
new Link("奥巴马", "乔布斯", 6),
new Link("比尔-盖茨", "乔布斯", 6),
new Link("乔纳森-艾夫", "乔布斯", 1),
new Link("蒂姆-库克", "乔布斯", 1),
new Link("龙-韦恩", "乔布斯", 1),
new Link("克拉拉-乔布斯", "保罗-乔布斯", 1),
new Link("奥巴马", "保罗-乔布斯", 1),
new Link("奥巴马", "克拉拉-乔布斯", 1),
new Link("奥巴马", "劳伦-鲍威尔", 1),
new Link("奥巴马", "史蒂夫-沃兹尼艾克", 1),
new Link("比尔-盖茨", "奥巴马", 6),
new Link("比尔-盖茨", "克拉拉-乔布斯", 1),
new Link("蒂姆-库克", "奥巴马", 1)
);
option.series(force);
option.exportToHtml("force1.html");
option.view();
}
}
| BIT-SYS/BIT-DEC | src/com/github/abel533/echarts/samples/force/ForceTest1.java | 1,438 | //地址:http://echarts.baidu.com/doc/example/force1.html | line_comment | zh-cn | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.abel533.echarts.samples.force;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.code.*;
import com.github.abel533.echarts.series.Force;
import com.github.abel533.echarts.series.force.Link;
import com.github.abel533.echarts.series.force.Node;
import com.github.abel533.echarts.style.LinkStyle;
import com.github.abel533.echarts.style.NodeStyle;
import com.github.abel533.echarts.style.TextStyle;
import com.github.abel533.echarts.util.EnhancedOption;
import org.junit.Test;
/**
* @author liuzh
*/
public class ForceTest1 {
@Test
public void test() {
//地址 <SUF>
EnhancedOption option = new EnhancedOption();
option.title().text("人物关系:乔布斯").subtext("数据来自人立方").x(X.right).y(Y.bottom);
option.tooltip().trigger(Trigger.item).formatter("{a} : {b}");
option.toolbox().show(true).feature(Tool.restore, Tool.saveAsImage);
option.legend("家人", "朋友").legend().x(X.left);
//数据
Force force = new Force("人物关系");
force.categories("人物", "家人", "朋友");
force.itemStyle().normal()
.label(new Label().show(true).textStyle(new TextStyle().color("#333")))
.nodeStyle().brushType(BrushType.both).color("rgba(255,215,0,0.4)").borderWidth(1);
force.itemStyle().emphasis()
.linkStyle(new LinkStyle())
.nodeStyle(new NodeStyle())
.label().show(true);
force.useWorker(false).minRadius(15).maxRadius(25).gravity(1.1).scaling(1.1).linkSymbol(Symbol.arrow);
force.nodes(new Node(0, "乔布斯", 10),
new Node(1, "丽萨-乔布斯", 2),
new Node(1, "保罗-乔布斯", 3),
new Node(1, "克拉拉-乔布斯", 3),
new Node(1, "劳伦-鲍威尔", 7),
new Node(2, "史蒂夫-沃兹尼艾克", 5),
new Node(2, "奥巴马", 8),
new Node(2, "比尔-盖茨", 9),
new Node(2, "乔纳森-艾夫", 4),
new Node(2, "蒂姆-库克", 4),
new Node(2, "龙-韦恩", 1));
force.links(new Link("丽萨-乔布斯", "乔布斯", 1),
new Link("保罗-乔布斯", "乔布斯", 2),
new Link("克拉拉-乔布斯", "乔布斯", 1),
new Link("劳伦-鲍威尔", "乔布斯", 2),
new Link("史蒂夫-沃兹尼艾克", "乔布斯", 3),
new Link("奥巴马", "乔布斯", 6),
new Link("比尔-盖茨", "乔布斯", 6),
new Link("乔纳森-艾夫", "乔布斯", 1),
new Link("蒂姆-库克", "乔布斯", 1),
new Link("龙-韦恩", "乔布斯", 1),
new Link("克拉拉-乔布斯", "保罗-乔布斯", 1),
new Link("奥巴马", "保罗-乔布斯", 1),
new Link("奥巴马", "克拉拉-乔布斯", 1),
new Link("奥巴马", "劳伦-鲍威尔", 1),
new Link("奥巴马", "史蒂夫-沃兹尼艾克", 1),
new Link("比尔-盖茨", "奥巴马", 6),
new Link("比尔-盖茨", "克拉拉-乔布斯", 1),
new Link("蒂姆-库克", "奥巴马", 1)
);
option.series(force);
option.exportToHtml("force1.html");
option.view();
}
}
| 0 | 53 | 0 |
24214_3 | package run;
import domains.*;
//import domains.Pos;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
/**
* Created by Hugh on 2014/12/29 0029.
*/
public class Run {
public static void main(String[] args) throws Exception {
Run run = new Run();
ShoppingChart shoppingChart = run.saxIndex();
ShoppingListChart shoppingListChart = new ShoppingListChart(shoppingChart);
Pos pos = new Pos();
String result = pos.getShoppingList(shoppingListChart);
System.out.println(result);
}
/*
功能:根据索引表导出购物清单,该函数依赖于saxListing
参数:无
返回值:购物车清单ShoppingChart,若读取时出错,则跳过该清单并提示出错的编码barCode
*/
public ShoppingChart saxIndex() throws Exception
{
ShoppingChart shoppingChart=new ShoppingChart();
SAXReader saxReader = new SAXReader();
Document document;
document = saxReader.read("index.xml");
Element root = document.getRootElement();
Element goods=root.element("goods");
Iterator<Element> iterator = goods.elementIterator();
while (iterator.hasNext()) {
Element element=iterator.next();
String barCode=element.getText();
Item item=saxListing(barCode);
if(!item.isRecommended())
{
System.out.println("Discount and promotion can't exist both, barCode: "+item.getBarCode());
}
if(!item.isNull()){
shoppingChart.add(item);
}else {
System.out.println("Read error,item barcode: " + barCode);
}
}
return shoppingChart;
}
/*
功能:根据产品编码从产品列表中寻找相应的产品,返回该商品属性Item
参数:String bacCord 产品的编码
返回值:Item 若成功,则返回该产品属性,否则,返回空Item
*/
public Item saxListing(String bacCode) throws DocumentException{
SAXReader saxReader = new SAXReader();
Document document;
document = saxReader.read("listing.xml");
Element root = document.getRootElement();
Iterator<Element> iterator = root.elementIterator();
while (iterator.hasNext()) {
Element element = iterator.next();
if(element.attributeValue("type").equals(bacCode)){
String name=element.elementText("name");
String unit=element.elementText("unit");
double price=Double.parseDouble(element.elementText("price"));
double discount=Double.parseDouble(element.elementText("discount"));
boolean promotion = Boolean.parseBoolean(element.elementText("promotion"));
double vipDiscount=Double.parseDouble(element.elementText("vipDiscount"));
return new Item(bacCode,name,unit,price,discount,promotion,vipDiscount);
}
}
return new Item();
}
}
| BJUT-Agile-Group/Pos-Team3 | src/run/Run.java | 749 | /*
功能:根据产品编码从产品列表中寻找相应的产品,返回该商品属性Item
参数:String bacCord 产品的编码
返回值:Item 若成功,则返回该产品属性,否则,返回空Item
*/ | block_comment | zh-cn | package run;
import domains.*;
//import domains.Pos;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
/**
* Created by Hugh on 2014/12/29 0029.
*/
public class Run {
public static void main(String[] args) throws Exception {
Run run = new Run();
ShoppingChart shoppingChart = run.saxIndex();
ShoppingListChart shoppingListChart = new ShoppingListChart(shoppingChart);
Pos pos = new Pos();
String result = pos.getShoppingList(shoppingListChart);
System.out.println(result);
}
/*
功能:根据索引表导出购物清单,该函数依赖于saxListing
参数:无
返回值:购物车清单ShoppingChart,若读取时出错,则跳过该清单并提示出错的编码barCode
*/
public ShoppingChart saxIndex() throws Exception
{
ShoppingChart shoppingChart=new ShoppingChart();
SAXReader saxReader = new SAXReader();
Document document;
document = saxReader.read("index.xml");
Element root = document.getRootElement();
Element goods=root.element("goods");
Iterator<Element> iterator = goods.elementIterator();
while (iterator.hasNext()) {
Element element=iterator.next();
String barCode=element.getText();
Item item=saxListing(barCode);
if(!item.isRecommended())
{
System.out.println("Discount and promotion can't exist both, barCode: "+item.getBarCode());
}
if(!item.isNull()){
shoppingChart.add(item);
}else {
System.out.println("Read error,item barcode: " + barCode);
}
}
return shoppingChart;
}
/*
功能: <SUF>*/
public Item saxListing(String bacCode) throws DocumentException{
SAXReader saxReader = new SAXReader();
Document document;
document = saxReader.read("listing.xml");
Element root = document.getRootElement();
Iterator<Element> iterator = root.elementIterator();
while (iterator.hasNext()) {
Element element = iterator.next();
if(element.attributeValue("type").equals(bacCode)){
String name=element.elementText("name");
String unit=element.elementText("unit");
double price=Double.parseDouble(element.elementText("price"));
double discount=Double.parseDouble(element.elementText("discount"));
boolean promotion = Boolean.parseBoolean(element.elementText("promotion"));
double vipDiscount=Double.parseDouble(element.elementText("vipDiscount"));
return new Item(bacCode,name,unit,price,discount,promotion,vipDiscount);
}
}
return new Item();
}
}
| 1 | 115 | 1 |
61398_10 | //你的面前有一堵矩形的、由 n 行砖块组成的砖墙。这些砖块高度相同(也就是一个单位高)但是宽度不同。每一行砖块的宽度之和相等。
//
// 你现在要画一条 自顶向下 的、穿过 最少 砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你不能沿着墙的两个垂直边缘之一画线,这样显然是没
//有穿过一块砖的。
//
// 给你一个二维数组 wall ,该数组包含这堵墙的相关信息。其中,wall[i] 是一个代表从左至右每块砖的宽度的数组。你需要找出怎样画才能使这条线 穿过的
//砖块数量最少 ,并且返回 穿过的砖块数量 。
//
//
//
// 示例 1:
//
//
//输入:wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
//输出:2
//
//
// 示例 2:
//
//
//输入:wall = [[1],[1],[1]]
//输出:3
//
//
//
// 提示:
//
//
// n == wall.length
// 1 <= n <= 104
// 1 <= wall[i].length <= 104
// 1 <= sum(wall[i].length) <= 2 * 104
// 对于每一行 i ,sum(wall[i]) 是相同的
// 1 <= wall[i][j] <= 231 - 1
//
// Related Topics 数组 哈希表
// 👍 245 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int leastBricks(List<List<Integer>> wall) {
int n = wall.size();
Map<Integer, Integer> map = new HashMap<>();
// 前缀和 + map记录缝隙出现次数
for (int i = 0; i < n; i++) {
int sum = 0;
for (int cur : wall.get(i)) {
sum += cur;
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
// 移除最后一个缝隙
map.remove(sum);
}
int ans = n;
for (int key : map.keySet()) {
int count = map.get(key);
ans = Math.min(ans, n - count);
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| BLUEONE-art/LeetCodeAlgorithm | bytedancer/leetcode/editor/cn/[554]砖墙.java | 704 | //输出:3 | line_comment | zh-cn | //你的面前有一堵矩形的、由 n 行砖块组成的砖墙。这些砖块高度相同(也就是一个单位高)但是宽度不同。每一行砖块的宽度之和相等。
//
// 你现在要画一条 自顶向下 的、穿过 最少 砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你不能沿着墙的两个垂直边缘之一画线,这样显然是没
//有穿过一块砖的。
//
// 给你一个二维数组 wall ,该数组包含这堵墙的相关信息。其中,wall[i] 是一个代表从左至右每块砖的宽度的数组。你需要找出怎样画才能使这条线 穿过的
//砖块数量最少 ,并且返回 穿过的砖块数量 。
//
//
//
// 示例 1:
//
//
//输入:wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
//输出:2
//
//
// 示例 2:
//
//
//输入:wall = [[1],[1],[1]]
//输出 <SUF>
//
//
//
// 提示:
//
//
// n == wall.length
// 1 <= n <= 104
// 1 <= wall[i].length <= 104
// 1 <= sum(wall[i].length) <= 2 * 104
// 对于每一行 i ,sum(wall[i]) 是相同的
// 1 <= wall[i][j] <= 231 - 1
//
// Related Topics 数组 哈希表
// 👍 245 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int leastBricks(List<List<Integer>> wall) {
int n = wall.size();
Map<Integer, Integer> map = new HashMap<>();
// 前缀和 + map记录缝隙出现次数
for (int i = 0; i < n; i++) {
int sum = 0;
for (int cur : wall.get(i)) {
sum += cur;
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
// 移除最后一个缝隙
map.remove(sum);
}
int ans = n;
for (int key : map.keySet()) {
int count = map.get(key);
ans = Math.min(ans, n - count);
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | 6 | 0 |
37953_14 | package BOBO.web;
import BOBO.pojo.Page;
import BOBO.pojo.Sct;
import BOBO.pojo.Student;
import BOBO.service.Impl.SctServiceImpl;
import BOBO.service.Impl.StudentServiceImpl;
import BOBO.service.SctService;
import BOBO.service.StudentService;
import BOBO.utils.WebUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class StudentServlet extends BaseServlet {
//调用对应的service层函数
private StudentService studentService = new StudentServiceImpl();
private SctService sctService = new SctServiceImpl();
//添加学生信息
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*获取当前页码*/
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
/*保证添加信息后跳到最后一页,+100*/
pageNo += 100;
/*把获取到的对象注入映射Map中*/
Student student = WebUtils.WebUtils(req.getParameterMap(), new Student());
/*调用service方法添加*/
studentService.addStudent(student);
/*重定向地址到信息展示,加上属性pageNo*/
resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + pageNo);
}
//删除学生信息
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*获取点击删除的ID*/
int id = WebUtils.parseInt(req.getParameter("id"), 0);
/*新建一个Sct选课对象,并通过学号ID查找是否存在*/
Sct sct = sctService.querySctbySno(id);
/*不存在,则直接删*/
if (sct == null) {
studentService.deleteStudent(id);
}
/*存在,先删选课信息,再删学生信息,防止产生依赖,报错*/
else {
sctService.deleteSct(sct.getSct_no());
studentService.deleteStudent(id);
}
/*重定向地址到信息展示,加上属性pageNo*/
resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo"));
}
//修改学生信息
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*把获取到的对象注入映射Map中*/
Student student = WebUtils.WebUtils(req.getParameterMap(), new Student());
studentService.updateStudent(student);
resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo"));
}
//获取学生信息,获取后跳到学生编辑界面
protected void getStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = WebUtils.parseInt(req.getParameter("id"), 0);
Student student = studentService.queryStudentbyId(id);
/*把student存到resquest域中*/
req.setAttribute("studnet", student);
/*进行编辑页面跳转*/
req.getRequestDispatcher("/page/edit_page/Student_edit.jsp").forward(req, resp);
}
//处理分页服务
protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
/*新建一个page对象*/
Page<Student> page = studentService.page(pageNo, pageSize);
/*设置Url,用于分页处理*/
page.setUrl("studentServlet?action=page");
req.setAttribute("page", page);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
//通过学号查找学生信息
protected void findByNo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int sno = WebUtils.parseInt(req.getParameter("sno"), 1);
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
Page<Student> page = studentService.findOneByNo(pageNo, pageSize, sno);
page.setUrl("studentServlet?action=findByNo&sno=" + sno);
req.setAttribute("page", page);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
protected void findByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int sno = WebUtils.parseInt(req.getParameter("sno"), 1);
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
// String sname = new String(req.getParameter("sname").getBytes("ISO-8859-1"),"utf-8");
String sname = req.getParameter("sname");
Page<Student> page = studentService.findOneByName(pageNo, pageSize, sname);
page.setUrl("studentServlet?action=findByName&sname=" + sname);
req.setAttribute("page", page);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
//列出所有学生信息(没用)
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Student> students = studentService.queryStudents();
req.setAttribute("students", students);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
}
| BOBO-ZzB/Student_select_class- | src/BOBO/web/StudentServlet.java | 1,346 | /*把获取到的对象注入映射Map中*/ | block_comment | zh-cn | package BOBO.web;
import BOBO.pojo.Page;
import BOBO.pojo.Sct;
import BOBO.pojo.Student;
import BOBO.service.Impl.SctServiceImpl;
import BOBO.service.Impl.StudentServiceImpl;
import BOBO.service.SctService;
import BOBO.service.StudentService;
import BOBO.utils.WebUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class StudentServlet extends BaseServlet {
//调用对应的service层函数
private StudentService studentService = new StudentServiceImpl();
private SctService sctService = new SctServiceImpl();
//添加学生信息
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*获取当前页码*/
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
/*保证添加信息后跳到最后一页,+100*/
pageNo += 100;
/*把获取到的对象注入映射Map中*/
Student student = WebUtils.WebUtils(req.getParameterMap(), new Student());
/*调用service方法添加*/
studentService.addStudent(student);
/*重定向地址到信息展示,加上属性pageNo*/
resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + pageNo);
}
//删除学生信息
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*获取点击删除的ID*/
int id = WebUtils.parseInt(req.getParameter("id"), 0);
/*新建一个Sct选课对象,并通过学号ID查找是否存在*/
Sct sct = sctService.querySctbySno(id);
/*不存在,则直接删*/
if (sct == null) {
studentService.deleteStudent(id);
}
/*存在,先删选课信息,再删学生信息,防止产生依赖,报错*/
else {
sctService.deleteSct(sct.getSct_no());
studentService.deleteStudent(id);
}
/*重定向地址到信息展示,加上属性pageNo*/
resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo"));
}
//修改学生信息
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*把获取 <SUF>*/
Student student = WebUtils.WebUtils(req.getParameterMap(), new Student());
studentService.updateStudent(student);
resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo"));
}
//获取学生信息,获取后跳到学生编辑界面
protected void getStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = WebUtils.parseInt(req.getParameter("id"), 0);
Student student = studentService.queryStudentbyId(id);
/*把student存到resquest域中*/
req.setAttribute("studnet", student);
/*进行编辑页面跳转*/
req.getRequestDispatcher("/page/edit_page/Student_edit.jsp").forward(req, resp);
}
//处理分页服务
protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
/*新建一个page对象*/
Page<Student> page = studentService.page(pageNo, pageSize);
/*设置Url,用于分页处理*/
page.setUrl("studentServlet?action=page");
req.setAttribute("page", page);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
//通过学号查找学生信息
protected void findByNo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int sno = WebUtils.parseInt(req.getParameter("sno"), 1);
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
Page<Student> page = studentService.findOneByNo(pageNo, pageSize, sno);
page.setUrl("studentServlet?action=findByNo&sno=" + sno);
req.setAttribute("page", page);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
protected void findByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int sno = WebUtils.parseInt(req.getParameter("sno"), 1);
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
// String sname = new String(req.getParameter("sname").getBytes("ISO-8859-1"),"utf-8");
String sname = req.getParameter("sname");
Page<Student> page = studentService.findOneByName(pageNo, pageSize, sname);
page.setUrl("studentServlet?action=findByName&sname=" + sname);
req.setAttribute("page", page);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
//列出所有学生信息(没用)
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Student> students = studentService.queryStudents();
req.setAttribute("students", students);
req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp);
}
}
| 1 | 19 | 1 |
48068_51 | package com.tmall.judge.grade;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Grade {
//从Traffic_Light_Table.txt读取所有路口红绿灯位置关系信息
static Map<String, String[]> trafficLightTable = new ConcurrentHashMap<String, String[]>();
//所有路口某个小时的静态流量表和动态流量表(数组长度为120)
static Map<String, Integer[]> staticFlowTable = new ConcurrentHashMap<String,Integer[]>();
static Map<String, Integer[]> dynamicFlowTable = new ConcurrentHashMap<String,Integer[]>();
//传出给选手参数:某个小时某个时段T(i)所有路口的车流量
static Map<String, Integer> currentFlows = new ConcurrentHashMap<String,Integer>();
//传出给选手参数:某个时段T(i)所有路口车辆的 转向概率:[左转,右转,直行]
static Map<String, Double[]> turnRate = new ConcurrentHashMap<String,Double[]>();
//传出给选手参数:某个时段T(i)所有路口车辆的 通过率:[左转,右转,直行]
static Map<String, Integer[]> throughRate = new ConcurrentHashMap<String,Integer[]>();
//选手传入参数:某个时段T(i)所有路口红 绿灯的状态:[左转,右转,直行] (红灯为0,绿等为1,缺失-1)
static Map<String, Integer[]> currentStatus = new ConcurrentHashMap<String,Integer[]>();
//某个小时内红绿灯的历史信息
static Map<String, ArrayList<Integer[]>> statusHistory = new ConcurrentHashMap<String,ArrayList<Integer[]>>();
//14个小时的penalty
//所有taskId对应的penalty
public static Map<String, Double[]> penaltyMap = new ConcurrentHashMap<String, Double[]>();
public static boolean inited = false;
//初始化每个选手对应的penalty数组
public static void initPenalty(String taskId) {
Double[] penalty = {0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0};
penaltyMap.put(taskId, penalty);
}
//从trafficLightTable读取红绿灯位置信息
public static void setLightInfo(String taskId, Map<String, String[]> trafficLightMap){
for (String aKey : trafficLightMap.keySet()) {
String[] keyStrings = aKey.split("-");
String taks_key = keyStrings[0] + "-" + keyStrings[1] + "-" + taskId;
trafficLightTable.put(taks_key,trafficLightMap.get(aKey));
}
}
// 第i个小时状态初始化
public static void hourInit(String taskId, Map<String, Integer[]> trafficFlowMap,int i) throws NumberFormatException, IOException {
for (String aKey : trafficFlowMap.keySet()) {
String[] keyStrings = aKey.split("-");
String taks_key = keyStrings[0] + "-" + keyStrings[1] + "-" + taskId;
Integer[] values = new Integer[120];
for (int i1 = 0; i1 < values.length; i1++) {
values[i1] = trafficFlowMap.get(aKey)[i*120 + i1];
}
staticFlowTable.put(taks_key,values);
dynamicFlowTable.put(taks_key,values.clone());
}
//初始化turnRate:[0.1,0.1,0.8]、throughRate:[2,2,16]、statusHistory
for(String key : trafficLightTable.keySet()){
if(!taskId.equals(key.split("-")[2])){
continue;
}
//十字路口转向概率
Double[] initTurnRate = {0.1,0.1,0.8};
//丁字路口,无左转方向
if (trafficLightTable.get(key)[0].equals("#")) {
initTurnRate[1] += initTurnRate[0];
initTurnRate[0] -= initTurnRate[0];
}else if (trafficLightTable.get(key)[1].equals("#")) {
//丁字路口,无右转方向
initTurnRate[0] += initTurnRate[1];
initTurnRate[1] -= initTurnRate[1];
}else if (trafficLightTable.get(key)[2].equals("#")) {
//丁字路口,无直行方向
initTurnRate[0] += initTurnRate[2]*0.5;
initTurnRate[1] += initTurnRate[2]*0.5;
initTurnRate[2] -= initTurnRate[2];
}
Integer[] initThroughRate = {2,2,16};
ArrayList<Integer[]> initStatusHistory = new ArrayList<Integer[]>();
for (int j = 0; j < 120; j++) {
Integer[] aStatus = {0,0,0};
if ("#".equals(trafficLightTable.get(key)[0])) {
aStatus[0] = -1;
}else if ("#".equals(trafficLightTable.get(key)[1])) {
aStatus[1] = -1;
}else if ("#".equals(trafficLightTable.get(key)[2])) {
aStatus[2] = -1;
}
initStatusHistory.add(aStatus);
}
turnRate.put(key, initTurnRate);
throughRate.put(key, initThroughRate);
statusHistory.put(key, initStatusHistory);
}
}
//根据最近一段时间红绿历史状态表计算转向概率[ALPHA,BETA,GAMMA],初赛为固定值不更新
public static void updateTurnRate() {
/**for (String key : statusHistory.keySet()) {
Double[] rate = {0.1,0.1,0.8};
turnRate.put(key, rate);
}*/
}
//根据路口车流量计算车辆通过率[TH1,TH2,TH3],初赛通过率固定值为不更新
public static void updateThroughRate() {
/**
for(String key : currentFlows.keySet()){
Integer[] rate = {5,5,20};
throughRate.put(key, rate);
}*/
}
//选手传入参数:第i时刻currentStatus,更新到statusHistory
public static void setCurrentStatus(Map<String, Integer[]> aStatus,int i) {
//currentStatus = aStatus;
for(String key :aStatus.keySet()){
if (statusHistory.containsKey(key)) {
for (int j = 0; j < 3; j++) {
if ("#".equals(trafficLightTable.get(key)[j])) {
//如果路口不通,强制将灯设置为-1
statusHistory.get(key).get(i)[j] = -1;
} else {
//如果路口是通的,不允许选手将灯设置为-1
statusHistory.get(key).get(i)[j] = Math.max(0, aStatus.get(key)[j]);
}
}
}
}
}
//根据statusHistory(i)、dynamicFlowTable(i)计算T(i)时刻某路口滞留车辆数
public static int computeStay(String key, int i) {
//左转右转直行实际能够通过的车辆数
int leftThrough,rightThrough,straightThrough;
leftThrough=rightThrough=straightThrough = 0;
//绿灯时通过率才有效
if (statusHistory.get(key).get(i)[0]==1) {
leftThrough = throughRate.get(key)[0];
}
if (statusHistory.get(key).get(i)[1]==1) {
rightThrough = throughRate.get(key)[1];
}
if (statusHistory.get(key).get(i)[2]==1) {
straightThrough = throughRate.get(key)[2];
}
//dynamicFlow(i)
int iFlow = dynamicFlowTable.get(key)[i];
//左转右转直行的滞留车辆
int leftStay,rightStay,straightStay;
leftStay = rightStay = straightStay = 0;
double leftRate = turnRate.get(key)[0];
double rihgtRate = turnRate.get(key)[1];
double straightRate = turnRate.get(key)[2];
//上取整可能会导致流量增大一点
leftStay = Math.max(0, (int)Math.ceil(iFlow*leftRate) - leftThrough);
rightStay = Math.max(0, (int)Math.ceil(iFlow*rihgtRate) - rightThrough);
straightStay = Math.max(0,(int)Math.ceil(iFlow*straightRate)-straightThrough);
//LOGGER.error("key="+key+",i="+i+",leftStay="+leftStay+",rightStay="+rightStay+",straightStay="+straightStay);
//返回T(i)时刻滞留车辆数
//System.out.println("allStay===" +(leftStay + rightStay + straightStay));
return (leftStay + rightStay + straightStay);
}
/*根据红绿灯位置信息表、T(i-1)时段的:车流量、所有红绿灯状态、车辆转向概率、车辆通过率
*计算T(i)时刻车流量
*dynamicFlowTable(i)=LAMADA*staticFlowTable(i) + G(trafficLightTable,statusHistory(i-1),dynamicFlowTable(i-1),turnRate(i-1),throughRate(i-1))
*/
public static void updateDynamicFlowTable(String taskId, int i) {
for(String key :dynamicFlowTable.keySet()){
String tId = key.split("-")[2];
if (tId.equals(taskId)) {
if (i==0) {
dynamicFlowTable.get(key)[i] = staticFlowTable.get(key)[i];
} else {
//观察值系数LAMADA
double LAMADA = 0.5;
//更新flow,加上系数LAMADA*staticFlow(i)
dynamicFlowTable.get(key)[i] = (int)(Math.floor(LAMADA*staticFlowTable.get(key)[i]));
//结合statusHistory(i-1)加上 dynamicFlow(i-1)的 左转滞留+右转滞留+直行滞留
int allStay = 0;
//优化代码用函数实现
allStay = computeStay(key, i-1);
//更新,加上滞留车辆
dynamicFlowTable.get(key)[i] += allStay;
//加上FromID从其他路口流入的车辆
int flowIn1,flowIn2,flowIn3;
flowIn1 = flowIn2 = flowIn3 = 0;
//反向路径ID
String[] keyStrings = key.split("-");
String antiKey = keyStrings[1] + "-" + keyStrings[0] + "-" + taskId;
//反向路径存在于trafficLightTable中才有意义
if (trafficLightTable.containsKey(antiKey)) {
//流入车辆的来源ID
String antiLeftID = trafficLightTable.get(antiKey)[0];
String antiRightID = trafficLightTable.get(antiKey)[1];
String antiStraightID = trafficLightTable.get(antiKey)[2];
String antiLeftKey = keyStrings[1] + "-" + antiLeftID + "-" + keyStrings[2];
String antiRightKey = keyStrings[1] + "-" + antiRightID + "-" + keyStrings[2];
String antiStraightKey = keyStrings[1] + "-" + antiStraightID + "-" + keyStrings[2];
//从 antiLeftID 右转流入
if (!(trafficLightTable.get(antiLeftKey)==null)&&(statusHistory.get(antiLeftKey).get(i-1)[1]==1)) {
flowIn1 = Math.min(throughRate.get(antiLeftKey)[1], (int)Math.ceil(dynamicFlowTable.get(antiLeftKey)[i-1]*turnRate.get(antiLeftKey)[1]));
}
//从 antiRightID 左转流入
if (!(trafficLightTable.get(antiRightKey)==null)&&(statusHistory.get(antiRightKey).get(i-1)[0]==1)) {
flowIn2 = Math.min(throughRate.get(antiRightKey)[0], (int)Math.ceil(dynamicFlowTable.get(antiRightKey)[i-1]*turnRate.get(antiRightKey)[0]));
}
//从 antiStraightKey 直行流入
if(!(trafficLightTable.get(antiStraightKey)==null)&&(statusHistory.get(antiStraightKey).get(i-1)[2]==1)){
flowIn3 = Math.min(throughRate.get(antiStraightKey)[2], (int)Math.ceil(dynamicFlowTable.get(antiStraightKey)[i-1]*turnRate.get(antiStraightKey)[2]));
}
}
//更新,加上流入车辆
dynamicFlowTable.get(key)[i] += flowIn1 + flowIn2 + flowIn3;
//System.out.println(" " + key +"-" + i + " flow:" +dynamicFlowTable.get(key)[i] );
}
}
}
}
//用 dynamicFlowTable 设置 currentFlow 传出给选手
public static Map<String, Integer> getCurrentFlow(String taskId, int i){
for(String key : dynamicFlowTable.keySet()){
if (taskId.equals(key.split("-")[2])) {
currentFlows.put(key, dynamicFlowTable.get(key)[i]);
}
}
return currentFlows;
}
//根据currentStatus(i)更新第k个小时penalty
public static void updatePenalty(String taskId,int i,int k){
//每个路口T(i)时刻penalty: 左转滞留+右转滞留+直行滞留;违反交通规则扣分;违反公平性原则扣分
for(String key : dynamicFlowTable.keySet()){
String[] lights = key.split("-");
if (taskId.equals(lights[2])) {
//更新,车辆滞留部分
penaltyMap.get(taskId)[k] += computeStay(key, i);
//更新,加上红绿灯违反交通规则的惩罚 a:直行垂直直行惩罚 b:直行垂直左转惩罚
double a,b;
a=b=0.0;
//交通违规的惩罚倍数
double zeta =0.5;
String leftKey = lights[0] + "-" + trafficLightTable.get(key)[0] + "-" + lights[2];
String rightKey = lights[0] + "-" + trafficLightTable.get(key)[1] + "-" + lights[2];
//垂直方向不能同时直行
if (statusHistory.get(key).get(i)[2]==1 &&
((statusHistory.containsKey(leftKey) && statusHistory.get(leftKey).get(i)[2]==1)
|| (statusHistory.containsKey(rightKey) && statusHistory.get(rightKey).get(i)[2]==1))) {
a += zeta*dynamicFlowTable.get(key)[i];
if (dynamicFlowTable.containsKey(leftKey)) {
a += zeta*dynamicFlowTable.get(leftKey)[i];
}
if (dynamicFlowTable.containsKey(rightKey)) {
a += zeta*dynamicFlowTable.get(rightKey)[i];
}
}
//直行时垂直方向右侧不能左转
if (statusHistory.get(key).get(i)[2]==1 && statusHistory.containsKey(rightKey) && statusHistory.get(rightKey).get(i)[0]==1) {
b += zeta*(dynamicFlowTable.get(rightKey)[i] + dynamicFlowTable.get(key)[i]);
}
//违规扣分
penaltyMap.get(taskId)[k] += 0.5*a + b;
//更新,加上违反公平原则扣分 v*sqrt(r-4)
if (i>3) {
for (int j = 0; j < 3; j++) {
if (statusHistory.get(key).get(i)[j]==0) {
int waitTime = 1;
int waitStart = i;
//修改bug
while ((waitStart>0) && statusHistory.get(key).get(waitStart-1)[j]==0) {
waitTime += 1;
waitStart -=1;
}
penaltyMap.get(taskId)[k] += (int)Math.ceil(dynamicFlowTable.get(key)[i]*Math.sqrt(Math.max(waitTime-4, 0)));
}
}
}
}
}
//System.out.println(k + "th hour" + i + "th Penalty======" + penaltyMap.get(taskId)[k]);
}
//清除某个用户的缓存数据
public static void cleanCache(String taskId) {
List<String> list = Lists.newArrayList(trafficLightTable.keySet());
for(String key : list){
String[] keyStrings = key.split("-");
if (keyStrings[2].equals(taskId)) {
trafficLightTable.remove(key);
staticFlowTable.remove(key);
dynamicFlowTable.remove(key);
turnRate.remove(key);
throughRate.remove(key);
statusHistory.remove(key);
}
}
penaltyMap.remove(taskId);
}
//输出选手最终得分
public static int getGrade(String taskId) {
if (penaltyMap.containsKey(taskId)) {
int score = 0;
for (int i = 0; i < penaltyMap.get(taskId).length; i++) {
score += penaltyMap.get(taskId)[i];
}
//清缓存数据
cleanCache(taskId);
System.out.println("returnSumScore====" + score);
return score;
} else {
//出异常的选手得分为-1
return -1;
}
}
}
| BSBandme/Traffic-light-Optimization | Grading code/Grade.java | 4,771 | //每个路口T(i)时刻penalty: 左转滞留+右转滞留+直行滞留;违反交通规则扣分;违反公平性原则扣分 | line_comment | zh-cn | package com.tmall.judge.grade;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Grade {
//从Traffic_Light_Table.txt读取所有路口红绿灯位置关系信息
static Map<String, String[]> trafficLightTable = new ConcurrentHashMap<String, String[]>();
//所有路口某个小时的静态流量表和动态流量表(数组长度为120)
static Map<String, Integer[]> staticFlowTable = new ConcurrentHashMap<String,Integer[]>();
static Map<String, Integer[]> dynamicFlowTable = new ConcurrentHashMap<String,Integer[]>();
//传出给选手参数:某个小时某个时段T(i)所有路口的车流量
static Map<String, Integer> currentFlows = new ConcurrentHashMap<String,Integer>();
//传出给选手参数:某个时段T(i)所有路口车辆的 转向概率:[左转,右转,直行]
static Map<String, Double[]> turnRate = new ConcurrentHashMap<String,Double[]>();
//传出给选手参数:某个时段T(i)所有路口车辆的 通过率:[左转,右转,直行]
static Map<String, Integer[]> throughRate = new ConcurrentHashMap<String,Integer[]>();
//选手传入参数:某个时段T(i)所有路口红 绿灯的状态:[左转,右转,直行] (红灯为0,绿等为1,缺失-1)
static Map<String, Integer[]> currentStatus = new ConcurrentHashMap<String,Integer[]>();
//某个小时内红绿灯的历史信息
static Map<String, ArrayList<Integer[]>> statusHistory = new ConcurrentHashMap<String,ArrayList<Integer[]>>();
//14个小时的penalty
//所有taskId对应的penalty
public static Map<String, Double[]> penaltyMap = new ConcurrentHashMap<String, Double[]>();
public static boolean inited = false;
//初始化每个选手对应的penalty数组
public static void initPenalty(String taskId) {
Double[] penalty = {0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0};
penaltyMap.put(taskId, penalty);
}
//从trafficLightTable读取红绿灯位置信息
public static void setLightInfo(String taskId, Map<String, String[]> trafficLightMap){
for (String aKey : trafficLightMap.keySet()) {
String[] keyStrings = aKey.split("-");
String taks_key = keyStrings[0] + "-" + keyStrings[1] + "-" + taskId;
trafficLightTable.put(taks_key,trafficLightMap.get(aKey));
}
}
// 第i个小时状态初始化
public static void hourInit(String taskId, Map<String, Integer[]> trafficFlowMap,int i) throws NumberFormatException, IOException {
for (String aKey : trafficFlowMap.keySet()) {
String[] keyStrings = aKey.split("-");
String taks_key = keyStrings[0] + "-" + keyStrings[1] + "-" + taskId;
Integer[] values = new Integer[120];
for (int i1 = 0; i1 < values.length; i1++) {
values[i1] = trafficFlowMap.get(aKey)[i*120 + i1];
}
staticFlowTable.put(taks_key,values);
dynamicFlowTable.put(taks_key,values.clone());
}
//初始化turnRate:[0.1,0.1,0.8]、throughRate:[2,2,16]、statusHistory
for(String key : trafficLightTable.keySet()){
if(!taskId.equals(key.split("-")[2])){
continue;
}
//十字路口转向概率
Double[] initTurnRate = {0.1,0.1,0.8};
//丁字路口,无左转方向
if (trafficLightTable.get(key)[0].equals("#")) {
initTurnRate[1] += initTurnRate[0];
initTurnRate[0] -= initTurnRate[0];
}else if (trafficLightTable.get(key)[1].equals("#")) {
//丁字路口,无右转方向
initTurnRate[0] += initTurnRate[1];
initTurnRate[1] -= initTurnRate[1];
}else if (trafficLightTable.get(key)[2].equals("#")) {
//丁字路口,无直行方向
initTurnRate[0] += initTurnRate[2]*0.5;
initTurnRate[1] += initTurnRate[2]*0.5;
initTurnRate[2] -= initTurnRate[2];
}
Integer[] initThroughRate = {2,2,16};
ArrayList<Integer[]> initStatusHistory = new ArrayList<Integer[]>();
for (int j = 0; j < 120; j++) {
Integer[] aStatus = {0,0,0};
if ("#".equals(trafficLightTable.get(key)[0])) {
aStatus[0] = -1;
}else if ("#".equals(trafficLightTable.get(key)[1])) {
aStatus[1] = -1;
}else if ("#".equals(trafficLightTable.get(key)[2])) {
aStatus[2] = -1;
}
initStatusHistory.add(aStatus);
}
turnRate.put(key, initTurnRate);
throughRate.put(key, initThroughRate);
statusHistory.put(key, initStatusHistory);
}
}
//根据最近一段时间红绿历史状态表计算转向概率[ALPHA,BETA,GAMMA],初赛为固定值不更新
public static void updateTurnRate() {
/**for (String key : statusHistory.keySet()) {
Double[] rate = {0.1,0.1,0.8};
turnRate.put(key, rate);
}*/
}
//根据路口车流量计算车辆通过率[TH1,TH2,TH3],初赛通过率固定值为不更新
public static void updateThroughRate() {
/**
for(String key : currentFlows.keySet()){
Integer[] rate = {5,5,20};
throughRate.put(key, rate);
}*/
}
//选手传入参数:第i时刻currentStatus,更新到statusHistory
public static void setCurrentStatus(Map<String, Integer[]> aStatus,int i) {
//currentStatus = aStatus;
for(String key :aStatus.keySet()){
if (statusHistory.containsKey(key)) {
for (int j = 0; j < 3; j++) {
if ("#".equals(trafficLightTable.get(key)[j])) {
//如果路口不通,强制将灯设置为-1
statusHistory.get(key).get(i)[j] = -1;
} else {
//如果路口是通的,不允许选手将灯设置为-1
statusHistory.get(key).get(i)[j] = Math.max(0, aStatus.get(key)[j]);
}
}
}
}
}
//根据statusHistory(i)、dynamicFlowTable(i)计算T(i)时刻某路口滞留车辆数
public static int computeStay(String key, int i) {
//左转右转直行实际能够通过的车辆数
int leftThrough,rightThrough,straightThrough;
leftThrough=rightThrough=straightThrough = 0;
//绿灯时通过率才有效
if (statusHistory.get(key).get(i)[0]==1) {
leftThrough = throughRate.get(key)[0];
}
if (statusHistory.get(key).get(i)[1]==1) {
rightThrough = throughRate.get(key)[1];
}
if (statusHistory.get(key).get(i)[2]==1) {
straightThrough = throughRate.get(key)[2];
}
//dynamicFlow(i)
int iFlow = dynamicFlowTable.get(key)[i];
//左转右转直行的滞留车辆
int leftStay,rightStay,straightStay;
leftStay = rightStay = straightStay = 0;
double leftRate = turnRate.get(key)[0];
double rihgtRate = turnRate.get(key)[1];
double straightRate = turnRate.get(key)[2];
//上取整可能会导致流量增大一点
leftStay = Math.max(0, (int)Math.ceil(iFlow*leftRate) - leftThrough);
rightStay = Math.max(0, (int)Math.ceil(iFlow*rihgtRate) - rightThrough);
straightStay = Math.max(0,(int)Math.ceil(iFlow*straightRate)-straightThrough);
//LOGGER.error("key="+key+",i="+i+",leftStay="+leftStay+",rightStay="+rightStay+",straightStay="+straightStay);
//返回T(i)时刻滞留车辆数
//System.out.println("allStay===" +(leftStay + rightStay + straightStay));
return (leftStay + rightStay + straightStay);
}
/*根据红绿灯位置信息表、T(i-1)时段的:车流量、所有红绿灯状态、车辆转向概率、车辆通过率
*计算T(i)时刻车流量
*dynamicFlowTable(i)=LAMADA*staticFlowTable(i) + G(trafficLightTable,statusHistory(i-1),dynamicFlowTable(i-1),turnRate(i-1),throughRate(i-1))
*/
public static void updateDynamicFlowTable(String taskId, int i) {
for(String key :dynamicFlowTable.keySet()){
String tId = key.split("-")[2];
if (tId.equals(taskId)) {
if (i==0) {
dynamicFlowTable.get(key)[i] = staticFlowTable.get(key)[i];
} else {
//观察值系数LAMADA
double LAMADA = 0.5;
//更新flow,加上系数LAMADA*staticFlow(i)
dynamicFlowTable.get(key)[i] = (int)(Math.floor(LAMADA*staticFlowTable.get(key)[i]));
//结合statusHistory(i-1)加上 dynamicFlow(i-1)的 左转滞留+右转滞留+直行滞留
int allStay = 0;
//优化代码用函数实现
allStay = computeStay(key, i-1);
//更新,加上滞留车辆
dynamicFlowTable.get(key)[i] += allStay;
//加上FromID从其他路口流入的车辆
int flowIn1,flowIn2,flowIn3;
flowIn1 = flowIn2 = flowIn3 = 0;
//反向路径ID
String[] keyStrings = key.split("-");
String antiKey = keyStrings[1] + "-" + keyStrings[0] + "-" + taskId;
//反向路径存在于trafficLightTable中才有意义
if (trafficLightTable.containsKey(antiKey)) {
//流入车辆的来源ID
String antiLeftID = trafficLightTable.get(antiKey)[0];
String antiRightID = trafficLightTable.get(antiKey)[1];
String antiStraightID = trafficLightTable.get(antiKey)[2];
String antiLeftKey = keyStrings[1] + "-" + antiLeftID + "-" + keyStrings[2];
String antiRightKey = keyStrings[1] + "-" + antiRightID + "-" + keyStrings[2];
String antiStraightKey = keyStrings[1] + "-" + antiStraightID + "-" + keyStrings[2];
//从 antiLeftID 右转流入
if (!(trafficLightTable.get(antiLeftKey)==null)&&(statusHistory.get(antiLeftKey).get(i-1)[1]==1)) {
flowIn1 = Math.min(throughRate.get(antiLeftKey)[1], (int)Math.ceil(dynamicFlowTable.get(antiLeftKey)[i-1]*turnRate.get(antiLeftKey)[1]));
}
//从 antiRightID 左转流入
if (!(trafficLightTable.get(antiRightKey)==null)&&(statusHistory.get(antiRightKey).get(i-1)[0]==1)) {
flowIn2 = Math.min(throughRate.get(antiRightKey)[0], (int)Math.ceil(dynamicFlowTable.get(antiRightKey)[i-1]*turnRate.get(antiRightKey)[0]));
}
//从 antiStraightKey 直行流入
if(!(trafficLightTable.get(antiStraightKey)==null)&&(statusHistory.get(antiStraightKey).get(i-1)[2]==1)){
flowIn3 = Math.min(throughRate.get(antiStraightKey)[2], (int)Math.ceil(dynamicFlowTable.get(antiStraightKey)[i-1]*turnRate.get(antiStraightKey)[2]));
}
}
//更新,加上流入车辆
dynamicFlowTable.get(key)[i] += flowIn1 + flowIn2 + flowIn3;
//System.out.println(" " + key +"-" + i + " flow:" +dynamicFlowTable.get(key)[i] );
}
}
}
}
//用 dynamicFlowTable 设置 currentFlow 传出给选手
public static Map<String, Integer> getCurrentFlow(String taskId, int i){
for(String key : dynamicFlowTable.keySet()){
if (taskId.equals(key.split("-")[2])) {
currentFlows.put(key, dynamicFlowTable.get(key)[i]);
}
}
return currentFlows;
}
//根据currentStatus(i)更新第k个小时penalty
public static void updatePenalty(String taskId,int i,int k){
//每个 <SUF>
for(String key : dynamicFlowTable.keySet()){
String[] lights = key.split("-");
if (taskId.equals(lights[2])) {
//更新,车辆滞留部分
penaltyMap.get(taskId)[k] += computeStay(key, i);
//更新,加上红绿灯违反交通规则的惩罚 a:直行垂直直行惩罚 b:直行垂直左转惩罚
double a,b;
a=b=0.0;
//交通违规的惩罚倍数
double zeta =0.5;
String leftKey = lights[0] + "-" + trafficLightTable.get(key)[0] + "-" + lights[2];
String rightKey = lights[0] + "-" + trafficLightTable.get(key)[1] + "-" + lights[2];
//垂直方向不能同时直行
if (statusHistory.get(key).get(i)[2]==1 &&
((statusHistory.containsKey(leftKey) && statusHistory.get(leftKey).get(i)[2]==1)
|| (statusHistory.containsKey(rightKey) && statusHistory.get(rightKey).get(i)[2]==1))) {
a += zeta*dynamicFlowTable.get(key)[i];
if (dynamicFlowTable.containsKey(leftKey)) {
a += zeta*dynamicFlowTable.get(leftKey)[i];
}
if (dynamicFlowTable.containsKey(rightKey)) {
a += zeta*dynamicFlowTable.get(rightKey)[i];
}
}
//直行时垂直方向右侧不能左转
if (statusHistory.get(key).get(i)[2]==1 && statusHistory.containsKey(rightKey) && statusHistory.get(rightKey).get(i)[0]==1) {
b += zeta*(dynamicFlowTable.get(rightKey)[i] + dynamicFlowTable.get(key)[i]);
}
//违规扣分
penaltyMap.get(taskId)[k] += 0.5*a + b;
//更新,加上违反公平原则扣分 v*sqrt(r-4)
if (i>3) {
for (int j = 0; j < 3; j++) {
if (statusHistory.get(key).get(i)[j]==0) {
int waitTime = 1;
int waitStart = i;
//修改bug
while ((waitStart>0) && statusHistory.get(key).get(waitStart-1)[j]==0) {
waitTime += 1;
waitStart -=1;
}
penaltyMap.get(taskId)[k] += (int)Math.ceil(dynamicFlowTable.get(key)[i]*Math.sqrt(Math.max(waitTime-4, 0)));
}
}
}
}
}
//System.out.println(k + "th hour" + i + "th Penalty======" + penaltyMap.get(taskId)[k]);
}
//清除某个用户的缓存数据
public static void cleanCache(String taskId) {
List<String> list = Lists.newArrayList(trafficLightTable.keySet());
for(String key : list){
String[] keyStrings = key.split("-");
if (keyStrings[2].equals(taskId)) {
trafficLightTable.remove(key);
staticFlowTable.remove(key);
dynamicFlowTable.remove(key);
turnRate.remove(key);
throughRate.remove(key);
statusHistory.remove(key);
}
}
penaltyMap.remove(taskId);
}
//输出选手最终得分
public static int getGrade(String taskId) {
if (penaltyMap.containsKey(taskId)) {
int score = 0;
for (int i = 0; i < penaltyMap.get(taskId).length; i++) {
score += penaltyMap.get(taskId)[i];
}
//清缓存数据
cleanCache(taskId);
System.out.println("returnSumScore====" + score);
return score;
} else {
//出异常的选手得分为-1
return -1;
}
}
}
| 1 | 54 | 1 |
28273_2 | package ir;
import ir.type.Type;
import ir.User.Use;
import java.util.LinkedList;
/*
* LLVM 中 Value Use User 的关系介绍
* https://buaa-se-compiling.github.io/miniSysY-tutorial/pre/design_hints.html
*/
/*
* Value 类,几乎所有实体都是Value的子类
*
*/
public class Value {
public Value(Type type) {
this.type = type;
uses = new LinkedList<>();
}
public Type type;
public String name = "";
protected LinkedList<Use> uses;
public boolean needName = true;
//将所有对 this 的使用换为对v的使用
public void replaceAllUseWith(Value v) {
for (Use use : uses) {
use.setV(v);
v.uses.add(use);
}
}
}
| BUAA-SE-Compiling/miniSysY_example_compiler | src/ir/Value.java | 209 | //将所有对 this 的使用换为对v的使用 | line_comment | zh-cn | package ir;
import ir.type.Type;
import ir.User.Use;
import java.util.LinkedList;
/*
* LLVM 中 Value Use User 的关系介绍
* https://buaa-se-compiling.github.io/miniSysY-tutorial/pre/design_hints.html
*/
/*
* Value 类,几乎所有实体都是Value的子类
*
*/
public class Value {
public Value(Type type) {
this.type = type;
uses = new LinkedList<>();
}
public Type type;
public String name = "";
protected LinkedList<Use> uses;
public boolean needName = true;
//将所 <SUF>
public void replaceAllUseWith(Value v) {
for (Use use : uses) {
use.setV(v);
v.uses.add(use);
}
}
}
| 1 | 22 | 1 |
39934_1 | import java.util.ArrayList;
import java.util.Scanner;
public class ClearUp {
private static int[][] arr = new int[9][9];
public static void main(String[] args) {
newGame();
displayRound();
checkAll();
return;
}
private static void checkAll() {
ArrayList<Integer> boomList = new ArrayList<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (isBoom(arr[i][j], i, j, Directions.TOP) || isBoom(arr[i][j], i, j, Directions.BOTTOM)
|| isBoom(arr[i][j], i, j, Directions.LEFT) || isBoom(arr[i][j], i, j, Directions.RIGHT)) {
System.out.println("point ---- i " + i + " j " + j + " will boom");
if (!boomList.contains(i * 10 + j)) {
boomList.add(i * 10 + j); // save
}
}
}
}
System.out.println("check over~~~~~~~~~~~~~~~~~~");
}
private static boolean isBoom(int type, int x, int y, Directions d) {
if (d == Directions.TOP) {
if (x + 2 <= 8) {
if (type == arr[x + 1][y] && type == arr[x + 2][y]) {
return true;
}
} else { // 超过索引
return false;
}
} else if (d == Directions.BOTTOM) {
if (x - 2 >= 0) {
if (type == arr[x - 1][y] && type == arr[x - 2][y]) {
return true;
}
} else {
return false;
}
} else if (d == Directions.LEFT) {
if (y - 2 >= 0) {
if (type == arr[x][y - 1] && type == arr[x][y - 2]) {
return true;
}
} else {
return false;
}
} else if (d == Directions.RIGHT) {
if (y + 2 <= 8) {
if (type == arr[x][y + 1] && type == arr[x][y + 2]) {
return true;
}
} else {
return false;
}
}
return false;
}
/**
*/
private static void displayRound() {
System.out.println("--------------------------------");
for (int i = 0; i < 9; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 9; j++) {
String s = "" + arr[i][j];
sb.append("" + s);
}
System.out.println(sb.toString());
}
System.out.println("--------------------------------");
}
/**
*/
private static void newGame() {
System.out.println("new game ------------");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
arr[i][j] = (int) (Math.random() * 8) + 1;
}
}
}
/**
* 枚举四个方向
*/
enum Directions {
TOP, BOTTOM, LEFT, RIGHT
}
}
| BUGyyc/myMd | #.code/ClearUp.java | 813 | // 超过索引 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.Scanner;
public class ClearUp {
private static int[][] arr = new int[9][9];
public static void main(String[] args) {
newGame();
displayRound();
checkAll();
return;
}
private static void checkAll() {
ArrayList<Integer> boomList = new ArrayList<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (isBoom(arr[i][j], i, j, Directions.TOP) || isBoom(arr[i][j], i, j, Directions.BOTTOM)
|| isBoom(arr[i][j], i, j, Directions.LEFT) || isBoom(arr[i][j], i, j, Directions.RIGHT)) {
System.out.println("point ---- i " + i + " j " + j + " will boom");
if (!boomList.contains(i * 10 + j)) {
boomList.add(i * 10 + j); // save
}
}
}
}
System.out.println("check over~~~~~~~~~~~~~~~~~~");
}
private static boolean isBoom(int type, int x, int y, Directions d) {
if (d == Directions.TOP) {
if (x + 2 <= 8) {
if (type == arr[x + 1][y] && type == arr[x + 2][y]) {
return true;
}
} else { // 超过 <SUF>
return false;
}
} else if (d == Directions.BOTTOM) {
if (x - 2 >= 0) {
if (type == arr[x - 1][y] && type == arr[x - 2][y]) {
return true;
}
} else {
return false;
}
} else if (d == Directions.LEFT) {
if (y - 2 >= 0) {
if (type == arr[x][y - 1] && type == arr[x][y - 2]) {
return true;
}
} else {
return false;
}
} else if (d == Directions.RIGHT) {
if (y + 2 <= 8) {
if (type == arr[x][y + 1] && type == arr[x][y + 2]) {
return true;
}
} else {
return false;
}
}
return false;
}
/**
*/
private static void displayRound() {
System.out.println("--------------------------------");
for (int i = 0; i < 9; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 9; j++) {
String s = "" + arr[i][j];
sb.append("" + s);
}
System.out.println(sb.toString());
}
System.out.println("--------------------------------");
}
/**
*/
private static void newGame() {
System.out.println("new game ------------");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
arr[i][j] = (int) (Math.random() * 8) + 1;
}
}
}
/**
* 枚举四个方向
*/
enum Directions {
TOP, BOTTOM, LEFT, RIGHT
}
}
| 1 | 7 | 1 |
17335_1 | package com.match.springmvc.entities;
import org.springframework.stereotype.Component;
/**
* 教师-比赛-队伍
* @author lenovo
*
*/
@Component
public class TrTeam {
private Integer TrCTid;
private Teacher teacher;
private String Tname;
private String Tdepartment;
private Competition competition;
private String Coname;
private Team team;
private Integer Workload; // 教师工作量(个人)
public Integer getTrCTid() {
return TrCTid;
}
public void setTrCTid(Integer trCTid) {
TrCTid = trCTid;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public String getTname() {
return Tname;
}
public String getTdepartment() {
return Tdepartment;
}
public void setTdepartment(String tdepartment) {
Tdepartment = tdepartment;
}
public void setTname(String tname) {
Tname = tname;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public Competition getCompetition() {
return competition;
}
public void setCompetition(Competition competition) {
this.competition = competition;
}
public String getConame() {
return Coname;
}
public void setConame(String coname) {
Coname = coname;
}
public Integer getWorkload() {
return Workload;
}
public void setWorkload(Integer workload) {
Workload = workload;
}
}
| BYFOR/competition-system-of-hbfu | src/com/match/springmvc/entities/TrTeam.java | 457 | // 教师工作量(个人)
| line_comment | zh-cn | package com.match.springmvc.entities;
import org.springframework.stereotype.Component;
/**
* 教师-比赛-队伍
* @author lenovo
*
*/
@Component
public class TrTeam {
private Integer TrCTid;
private Teacher teacher;
private String Tname;
private String Tdepartment;
private Competition competition;
private String Coname;
private Team team;
private Integer Workload; // 教师 <SUF>
public Integer getTrCTid() {
return TrCTid;
}
public void setTrCTid(Integer trCTid) {
TrCTid = trCTid;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public String getTname() {
return Tname;
}
public String getTdepartment() {
return Tdepartment;
}
public void setTdepartment(String tdepartment) {
Tdepartment = tdepartment;
}
public void setTname(String tname) {
Tname = tname;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public Competition getCompetition() {
return competition;
}
public void setCompetition(Competition competition) {
this.competition = competition;
}
public String getConame() {
return Coname;
}
public void setConame(String coname) {
Coname = coname;
}
public Integer getWorkload() {
return Workload;
}
public void setWorkload(Integer workload) {
Workload = workload;
}
}
| 1 | 13 | 1 |
40637_36 | public class MiGong {
//编写一个main方法
public static void main(String[] args) {
//思路
//1. 先创建迷宫,用二维数组表示 int[][] map = new int[8][7];
//2. 先规定 map 数组的元素值: 0 表示可以走 1 表示障碍物
int[][] map = new int[8][7];
//3. 将最上面的一行和最下面的一行,全部设置为1
for(int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1;
}
//4.将最右面的一列和最左面的一列,全部设置为1
for(int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}
map[3][1] = 1;
map[3][2] = 1;
map[2][2] = 1; //测试回溯
// map[2][1] = 1;
// map[2][2] = 1;
// map[1][2] = 1;
//输出当前的地图
System.out.println("=====当前地图情况======");
for(int i = 0; i < map.length; i++) {
for(int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");//输出一行
}
System.out.println();
}
//使用findWay给老鼠找路
C c1 = new C();
//下右上左
c1.findWay(map, 1, 1);
System.out.println("\n====找路的情况如下=====");
for(int i = 0; i < map.length; i++) {
for(int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");//输出一行
}
System.out.println();
}
}
}
class C {
//使用递归回溯的思想来解决老鼠出迷宫
//老韩解读
//1. findWay方法就是专门来找出迷宫的路径
//2. 如果找到,就返回 true ,否则返回false
//3. map 就是二维数组,即表示迷宫
//4. i,j 就是老鼠的位置,初始化的位置为(1,1)
//5. 因为我们是递归的找路,所以我先规定 map数组的各个值的含义
// 0 表示可以走 1 表示障碍物 2 表示可以走 3 表示走过,但是走不通是死路
//6. 当map[6][5] =2 就说明找到通路,就可以结束,否则就继续找.
//7. 先确定老鼠找路策略 下->右->上->左
public boolean findWay(int[][] map , int i, int j) {
if(map[6][5] == 2) {//说明已经找到
return true;
} else {
if(map[i][j] == 0) {//当前这个位置0,说明表示可以走
//我们假定可以走通
map[i][j] = 2;
//使用找路策略,来确定该位置是否真的可以走通
//下->右->上->左
if(findWay(map, i + 1, j)) {//先走下
return true;
} else if(findWay(map, i, j + 1)){//右
return true;
} else if(findWay(map, i-1, j)) {//上
return true;
} else if(findWay(map, i, j-1)){//左
return true;
} else {
map[i][j] = 3;
return false;
}
} else { //map[i][j] = 1 , 2, 3
return false;
}
}
}
//修改找路策略,看看路径是否有变化
//下->右->上->左 ==> 上->右->下->左
public boolean findWay2(int[][] map , int i, int j) {
if(map[6][5] == 2) {//说明已经找到
return true;
} else {
if(map[i][j] == 0) {//当前这个位置0,说明表示可以走
//我们假定可以走通
map[i][j] = 2;
//使用找路策略,来确定该位置是否真的可以走通
//上->右->下->左
if(findWay2(map, i - 1, j)) {//先走上
return true;
} else if(findWay2(map, i, j + 1)){//右
return true;
} else if(findWay2(map, i+1, j)) {//下
return true;
} else if(findWay2(map, i, j-1)){//左
return true;
} else {
map[i][j] = 3;
return false;
}
} else { //map[i][j] = 1 , 2, 3
return false;
}
}
}
}
| BabysBreath017/HelloWorld | MiGong.java | 1,372 | //使用找路策略,来确定该位置是否真的可以走通 | line_comment | zh-cn | public class MiGong {
//编写一个main方法
public static void main(String[] args) {
//思路
//1. 先创建迷宫,用二维数组表示 int[][] map = new int[8][7];
//2. 先规定 map 数组的元素值: 0 表示可以走 1 表示障碍物
int[][] map = new int[8][7];
//3. 将最上面的一行和最下面的一行,全部设置为1
for(int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1;
}
//4.将最右面的一列和最左面的一列,全部设置为1
for(int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}
map[3][1] = 1;
map[3][2] = 1;
map[2][2] = 1; //测试回溯
// map[2][1] = 1;
// map[2][2] = 1;
// map[1][2] = 1;
//输出当前的地图
System.out.println("=====当前地图情况======");
for(int i = 0; i < map.length; i++) {
for(int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");//输出一行
}
System.out.println();
}
//使用findWay给老鼠找路
C c1 = new C();
//下右上左
c1.findWay(map, 1, 1);
System.out.println("\n====找路的情况如下=====");
for(int i = 0; i < map.length; i++) {
for(int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");//输出一行
}
System.out.println();
}
}
}
class C {
//使用递归回溯的思想来解决老鼠出迷宫
//老韩解读
//1. findWay方法就是专门来找出迷宫的路径
//2. 如果找到,就返回 true ,否则返回false
//3. map 就是二维数组,即表示迷宫
//4. i,j 就是老鼠的位置,初始化的位置为(1,1)
//5. 因为我们是递归的找路,所以我先规定 map数组的各个值的含义
// 0 表示可以走 1 表示障碍物 2 表示可以走 3 表示走过,但是走不通是死路
//6. 当map[6][5] =2 就说明找到通路,就可以结束,否则就继续找.
//7. 先确定老鼠找路策略 下->右->上->左
public boolean findWay(int[][] map , int i, int j) {
if(map[6][5] == 2) {//说明已经找到
return true;
} else {
if(map[i][j] == 0) {//当前这个位置0,说明表示可以走
//我们假定可以走通
map[i][j] = 2;
//使用找路策略,来确定该位置是否真的可以走通
//下->右->上->左
if(findWay(map, i + 1, j)) {//先走下
return true;
} else if(findWay(map, i, j + 1)){//右
return true;
} else if(findWay(map, i-1, j)) {//上
return true;
} else if(findWay(map, i, j-1)){//左
return true;
} else {
map[i][j] = 3;
return false;
}
} else { //map[i][j] = 1 , 2, 3
return false;
}
}
}
//修改找路策略,看看路径是否有变化
//下->右->上->左 ==> 上->右->下->左
public boolean findWay2(int[][] map , int i, int j) {
if(map[6][5] == 2) {//说明已经找到
return true;
} else {
if(map[i][j] == 0) {//当前这个位置0,说明表示可以走
//我们假定可以走通
map[i][j] = 2;
//使用 <SUF>
//上->右->下->左
if(findWay2(map, i - 1, j)) {//先走上
return true;
} else if(findWay2(map, i, j + 1)){//右
return true;
} else if(findWay2(map, i+1, j)) {//下
return true;
} else if(findWay2(map, i, j-1)){//左
return true;
} else {
map[i][j] = 3;
return false;
}
} else { //map[i][j] = 1 , 2, 3
return false;
}
}
}
}
| 1 | 23 | 1 |
43924_0 | import java.util.Stack;
/**
* #617. 合并二叉树
* 给定两个二叉树,想像当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点
* 便会重叠。
* 你需要将它们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将它们的
* 值相加作为节点合并后的新值,否则不为NULL的节点将直接作为新二叉树的节点。*/
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
// 递归求解:
// if (t1 == null) return t2;
// if (t2 == null) return t1;
//
// t1.val += t2.val;
//
// t1.left = mergeTrees(t1.left, t2.left);
// t1.right = mergeTrees(t1.right, t2.right);
//
// return t1;
// 迭代求解:
if (t1 == null) return t2;
Stack<TreeNode[]> stack = new Stack<>();
stack.push(new TreeNode[] {t1, t2});
while (!stack.isEmpty()) {
TreeNode[] t = stack.pop();
if (t[0] == null || t[1] == null) continue;
t[0].val += t[1].val;
if (t[0].left == null) {
t[0].left = t[1].left;
} else {
stack.push(new TreeNode[] {t[0].left, t[1].left});
}
if (t[0].right == null) {
t[0].right = t[1].right;
} else {
stack.push(new TreeNode[] {t[0].right, t[1].right});
}
}
return t1;
}
}
public class Main {
public static void main(String[] args) {
TreeNode root_1 = new TreeNode(1);
TreeNode node1_1 = new TreeNode(3);
TreeNode node2_1 = new TreeNode(2);
TreeNode node3_1 = new TreeNode(5);
TreeNode root_2 = new TreeNode(2);
TreeNode node1_2 = new TreeNode(1);
TreeNode node2_2 = new TreeNode(3);
TreeNode node3_2 = new TreeNode(4);
TreeNode node4_4 = new TreeNode(7);
root_1.left = node1_1;
root_1.right = node2_1;
node1_1.left = node3_1;
root_2.left = node1_2;
root_2.right = node2_2;
node1_2.right = node3_2;
node2_2.right = node4_4;
Solution solution = new Solution();
TreeNode node = solution.mergeTrees(root_1, root_2);
System.out.println(node.left.val);
}
}
| BaiWenchao/Algorithm-LeetCode | HOT-100/#617_merge-two-binary-tree/src/Main.java | 747 | /**
* #617. 合并二叉树
* 给定两个二叉树,想像当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点
* 便会重叠。
* 你需要将它们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将它们的
* 值相加作为节点合并后的新值,否则不为NULL的节点将直接作为新二叉树的节点。*/ | block_comment | zh-cn | import java.util.Stack;
/**
* #61 <SUF>*/
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
// 递归求解:
// if (t1 == null) return t2;
// if (t2 == null) return t1;
//
// t1.val += t2.val;
//
// t1.left = mergeTrees(t1.left, t2.left);
// t1.right = mergeTrees(t1.right, t2.right);
//
// return t1;
// 迭代求解:
if (t1 == null) return t2;
Stack<TreeNode[]> stack = new Stack<>();
stack.push(new TreeNode[] {t1, t2});
while (!stack.isEmpty()) {
TreeNode[] t = stack.pop();
if (t[0] == null || t[1] == null) continue;
t[0].val += t[1].val;
if (t[0].left == null) {
t[0].left = t[1].left;
} else {
stack.push(new TreeNode[] {t[0].left, t[1].left});
}
if (t[0].right == null) {
t[0].right = t[1].right;
} else {
stack.push(new TreeNode[] {t[0].right, t[1].right});
}
}
return t1;
}
}
public class Main {
public static void main(String[] args) {
TreeNode root_1 = new TreeNode(1);
TreeNode node1_1 = new TreeNode(3);
TreeNode node2_1 = new TreeNode(2);
TreeNode node3_1 = new TreeNode(5);
TreeNode root_2 = new TreeNode(2);
TreeNode node1_2 = new TreeNode(1);
TreeNode node2_2 = new TreeNode(3);
TreeNode node3_2 = new TreeNode(4);
TreeNode node4_4 = new TreeNode(7);
root_1.left = node1_1;
root_1.right = node2_1;
node1_1.left = node3_1;
root_2.left = node1_2;
root_2.right = node2_2;
node1_2.right = node3_2;
node2_2.right = node4_4;
Solution solution = new Solution();
TreeNode node = solution.mergeTrees(root_1, root_2);
System.out.println(node.left.val);
}
}
| 0 | 155 | 0 |
20733_1 | package userInterface;
import entity.Department;
import entity.Hospital;
import entity.Patient;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import logic.DataStructure.Algorithms;
import logic.Util;
import java.util.ArrayList;
import java.util.List;
public class PatientSearch {
// 创建Util单例
Util util = Util.getInstance();
// 创建医院单例
Hospital hospital = Hospital.getInstance();
// 创建算法类单例
Algorithms algorithms = Algorithms.getInstance();
ObservableList<Patient> patientObservableList = FXCollections.observableArrayList();
@FXML
private TableColumn<Patient, String> numColumn;
@FXML
private TableColumn<Patient, String> timeColumn;
@FXML
private Button search;
@FXML
private ChoiceBox<String> departmentBox;
@FXML
private TableColumn<Patient, String> nameColumn;
@FXML
private TableView<Patient> infoTable;
@FXML
private Button idSort;
@FXML
private Button nameSort;
@FXML
private void initialize(){
infoTable.setItems(patientObservableList);
timeColumn.setCellValueFactory(cellData -> cellData.getValue().currentInsertTimeProperty());
numColumn.setCellValueFactory(cellData -> cellData.getValue().hosRecordNumProperty());
nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
}
@FXML
private void initDepartment(){
ObservableList<String> choices = FXCollections.observableArrayList("内科","外科","医院");
departmentBox.setItems(choices);
}
@FXML
private void setSearch(){
String range = departmentBox.getValue();
if(range == null){
util.errorInformationAlert("请选择查询范围!");
return;
}
if(range.equals("内科")){
for(Department d : hospital.getDepartmentList()){
if(d.getName().equals("内科")){
patientObservableList.clear();
patientObservableList.addAll(d.getPatientList());
}
}
}else if(range.equals("外科")){
for(Department d : hospital.getDepartmentList()){
if(d.getName().equals("外科")){
patientObservableList.clear();
patientObservableList.addAll(d.getPatientList());
}
}
}else if(range.equals("医院")){
patientObservableList.clear();
for(Department d : hospital.getDepartmentList()){
patientObservableList.addAll(d.getPatientList());
}
}
}
@FXML
private void setIdSort(){
List<Patient> patientList = new ArrayList<>();
for(Patient p : patientObservableList){
patientList.add(p);
}
algorithms.mergeSort(patientList, true);
patientObservableList.clear();
patientObservableList.addAll(patientList);
}
@FXML
private void setNameSort(){
List<Patient> patientList = new ArrayList<>();
for(Patient p : patientObservableList){
patientList.add(p);
}
algorithms.mergeSort(patientList, false);
patientObservableList.clear();
patientObservableList.addAll(patientList);
}
}
| BaiWenchao/HISProject2.0 | src/userInterface/PatientSearch.java | 766 | // 创建医院单例 | line_comment | zh-cn | package userInterface;
import entity.Department;
import entity.Hospital;
import entity.Patient;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import logic.DataStructure.Algorithms;
import logic.Util;
import java.util.ArrayList;
import java.util.List;
public class PatientSearch {
// 创建Util单例
Util util = Util.getInstance();
// 创建 <SUF>
Hospital hospital = Hospital.getInstance();
// 创建算法类单例
Algorithms algorithms = Algorithms.getInstance();
ObservableList<Patient> patientObservableList = FXCollections.observableArrayList();
@FXML
private TableColumn<Patient, String> numColumn;
@FXML
private TableColumn<Patient, String> timeColumn;
@FXML
private Button search;
@FXML
private ChoiceBox<String> departmentBox;
@FXML
private TableColumn<Patient, String> nameColumn;
@FXML
private TableView<Patient> infoTable;
@FXML
private Button idSort;
@FXML
private Button nameSort;
@FXML
private void initialize(){
infoTable.setItems(patientObservableList);
timeColumn.setCellValueFactory(cellData -> cellData.getValue().currentInsertTimeProperty());
numColumn.setCellValueFactory(cellData -> cellData.getValue().hosRecordNumProperty());
nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
}
@FXML
private void initDepartment(){
ObservableList<String> choices = FXCollections.observableArrayList("内科","外科","医院");
departmentBox.setItems(choices);
}
@FXML
private void setSearch(){
String range = departmentBox.getValue();
if(range == null){
util.errorInformationAlert("请选择查询范围!");
return;
}
if(range.equals("内科")){
for(Department d : hospital.getDepartmentList()){
if(d.getName().equals("内科")){
patientObservableList.clear();
patientObservableList.addAll(d.getPatientList());
}
}
}else if(range.equals("外科")){
for(Department d : hospital.getDepartmentList()){
if(d.getName().equals("外科")){
patientObservableList.clear();
patientObservableList.addAll(d.getPatientList());
}
}
}else if(range.equals("医院")){
patientObservableList.clear();
for(Department d : hospital.getDepartmentList()){
patientObservableList.addAll(d.getPatientList());
}
}
}
@FXML
private void setIdSort(){
List<Patient> patientList = new ArrayList<>();
for(Patient p : patientObservableList){
patientList.add(p);
}
algorithms.mergeSort(patientList, true);
patientObservableList.clear();
patientObservableList.addAll(patientList);
}
@FXML
private void setNameSort(){
List<Patient> patientList = new ArrayList<>();
for(Patient p : patientObservableList){
patientList.add(p);
}
algorithms.mergeSort(patientList, false);
patientObservableList.clear();
patientObservableList.addAll(patientList);
}
}
| 1 | 9 | 1 |
43821_13 | /*
* Copyright 2017 Baidu, Inc.
*
* 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 com.baidu.aip.bodyanalysis;
import com.baidu.aip.client.BaseClient;
import com.baidu.aip.error.AipError;
import com.baidu.aip.http.AipRequest;
import com.baidu.aip.util.Base64Util;
import com.baidu.aip.util.Util;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class AipBodyAnalysis extends BaseClient {
public AipBodyAnalysis(String appId, String apiKey, String secretKey) {
super(appId, apiKey, secretKey);
}
/**
* 人体关键点识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图片中的所有人体,输出每个人体的21个主要关键点,包含头顶、五官、脖颈、四肢等部位,同时输出人体的坐标信息和数量**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject bodyAnalysis(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_ANALYSIS);
postOperation(request);
return requestServer(request);
}
/**
* 人体关键点识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图片中的所有人体,输出每个人体的21个主要关键点,包含头顶、五官、脖颈、四肢等部位,同时输出人体的坐标信息和数量**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject bodyAnalysis(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyAnalysis(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人体检测与属性识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图像中的所有人体并返回每个人体的矩形框位置,识别人体的静态属性和行为,共支持20余种属性,包括:性别、年龄阶段、衣着(含类别/颜色)、是否戴帽子、是否戴眼镜、是否背包、是否使用手机、身体朝向等**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type gender,<br>age,<br>lower_wear,<br>upper_wear,<br>headwear,<br>glasses,<br>upper_color,<br>lower_color,<br>cellphone,<br>upper_wear_fg,<br>upper_wear_texture,<br>lower_wear_texture,<br>orientation,<br>umbrella,<br>bag,<br>smoke,<br>vehicle,<br>carrying_item,<br>upper_cut,<br>lower_cut,<br>occlusion,<br>is_human | 1)可选值说明:<br>gender-性别,<br>age-年龄阶段,<br>lower_wear-下身服饰,<br>upper_wear-上身服饰,<br>headwear-是否戴帽子,<br>glasses-是否戴眼镜,<br>upper_color-上身服饰颜色,<br>lower_color-下身服饰颜色,<br>cellphone-是否使用手机,<br>upper_wear_fg-上身服饰细分类,<br>upper_wear_texture-上身服饰纹理,<br>orientation-身体朝向,<br>umbrella-是否撑伞;<br>bag-背包,<br>smoke-是否吸烟,<br>vehicle-交通工具,<br>carrying_item-是否有手提物,<br>upper_cut-上方截断,<br>lower_cut-下方截断,<br>occlusion-遮挡,<br>is_human-是否是正常人体<br>2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部21个属性**
* @return JSONObject
*/
public JSONObject bodyAttr(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_ATTR);
postOperation(request);
return requestServer(request);
}
/**
* 人体检测与属性识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图像中的所有人体并返回每个人体的矩形框位置,识别人体的静态属性和行为,共支持20余种属性,包括:性别、年龄阶段、衣着(含类别/颜色)、是否戴帽子、是否戴眼镜、是否背包、是否使用手机、身体朝向等**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type gender,<br>age,<br>lower_wear,<br>upper_wear,<br>headwear,<br>glasses,<br>upper_color,<br>lower_color,<br>cellphone,<br>upper_wear_fg,<br>upper_wear_texture,<br>lower_wear_texture,<br>orientation,<br>umbrella,<br>bag,<br>smoke,<br>vehicle,<br>carrying_item,<br>upper_cut,<br>lower_cut,<br>occlusion,<br>is_human | 1)可选值说明:<br>gender-性别,<br>age-年龄阶段,<br>lower_wear-下身服饰,<br>upper_wear-上身服饰,<br>headwear-是否戴帽子,<br>glasses-是否戴眼镜,<br>upper_color-上身服饰颜色,<br>lower_color-下身服饰颜色,<br>cellphone-是否使用手机,<br>upper_wear_fg-上身服饰细分类,<br>upper_wear_texture-上身服饰纹理,<br>orientation-身体朝向,<br>umbrella-是否撑伞;<br>bag-背包,<br>smoke-是否吸烟,<br>vehicle-交通工具,<br>carrying_item-是否有手提物,<br>upper_cut-上方截断,<br>lower_cut-下方截断,<br>occlusion-遮挡,<br>is_human-是否是正常人体<br>2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部21个属性**
* @return JSONObject
*/
public JSONObject bodyAttr(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyAttr(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人流量统计接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像当中的人体个数(静态统计,暂不支持追踪和去重)**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* area 特定框选区域坐标,支持多个多边形区域,最多支持10个区域,如输入超过10个区域,截取前10个区域进行识别。<br>**此参数为空或无此参数、或area参数设置错误时,默认识别整个图片的人数** 。<br>area参数设置错误的示例:某个坐标超过原图大小,x、y坐标未成对出现等;注意:**设置了多个区域时,任意一个坐标设置错误,则认为area参数错误、失效**。<br>**area参数设置格式**:<br>1)多个区域用英文分号“;”分隔;<br>2)同一个区域内的坐标用英文逗号“,”分隔,默认尾点和首点相连做闭合。<br>示例:<br>1)单个多边形区域:x1,y1,x2,y2,x3,y3...xn,yn<br>2)多个多边形区域:xa1,ya1,xa2,ya2,xa3,ya3...xan,yan;xb1,yb1,xb2,yb2,xb3,yb3...xbn,ybn;..
* show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
* @return JSONObject
*/
public JSONObject bodyNum(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_NUM);
postOperation(request);
return requestServer(request);
}
/**
* 人流量统计接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像当中的人体个数(静态统计,暂不支持追踪和去重)**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* area 特定框选区域坐标,支持多个多边形区域,最多支持10个区域,如输入超过10个区域,截取前10个区域进行识别。<br>**此参数为空或无此参数、或area参数设置错误时,默认识别整个图片的人数** 。<br>area参数设置错误的示例:某个坐标超过原图大小,x、y坐标未成对出现等;注意:**设置了多个区域时,任意一个坐标设置错误,则认为area参数错误、失效**。<br>**area参数设置格式**:<br>1)多个区域用英文分号“;”分隔;<br>2)同一个区域内的坐标用英文逗号“,”分隔,默认尾点和首点相连做闭合。<br>示例:<br>1)单个多边形区域:x1,y1,x2,y2,x3,y3...xn,yn<br>2)多个多边形区域:xa1,ya1,xa2,ya2,xa3,ya3...xan,yan;xb1,yb1,xb2,yb2,xb3,yb3...xbn,ybn;..
* show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
* @return JSONObject
*/
public JSONObject bodyNum(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyNum(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 手势识别接口
* 识别图片中的手势类型,返回手势名称、手势矩形框、概率分数,可识别24种常见手势,适用于手势特效、智能家居手势交互等场景**。支持的24类手势列表:拳头、OK、祈祷、作揖、作别、单手比心、点赞、Diss、我爱你、掌心向上、双手比心(3种)、数字(9种)、Rock、竖中指。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject gesture(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.GESTURE);
postOperation(request);
return requestServer(request);
}
/**
* 手势识别接口
* 识别图片中的手势类型,返回手势名称、手势矩形框、概率分数,可识别24种常见手势,适用于手势特效、智能家居手势交互等场景**。支持的24类手势列表:拳头、OK、祈祷、作揖、作别、单手比心、点赞、Diss、我爱你、掌心向上、双手比心(3种)、数字(9种)、Rock、竖中指。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject gesture(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return gesture(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人像分割接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别人体的轮廓范围,与背景进行分离,适用于拍照背景替换、照片合成、身体特效等场景。输入正常人像图片,返回分割后的二值结果图和分割类型(目前仅支持person)**
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type 可以通过设置type参数,自主设置返回哪些结果图,避免造成带宽的浪费<br>1)可选值说明:<br>labelmap - 二值图像,需二次处理方能查看分割效果<br>scoremap - 人像前景灰度图<br>foreground - 人像前景抠图,透明背景<br>2)type 参数值可以是可选值的组合,用逗号分隔;如果无此参数默认输出全部3类结果图
* @return JSONObject
*/
public JSONObject bodySeg(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_SEG);
postOperation(request);
return requestServer(request);
}
/**
* 人像分割接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别人体的轮廓范围,与背景进行分离,适用于拍照背景替换、照片合成、身体特效等场景。输入正常人像图片,返回分割后的二值结果图和分割类型(目前仅支持person)**
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type 可以通过设置type参数,自主设置返回哪些结果图,避免造成带宽的浪费<br>1)可选值说明:<br>labelmap - 二值图像,需二次处理方能查看分割效果<br>scoremap - 人像前景灰度图<br>foreground - 人像前景抠图,透明背景<br>2)type 参数值可以是可选值的组合,用逗号分隔;如果无此参数默认输出全部3类结果图
* @return JSONObject
*/
public JSONObject bodySeg(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodySeg(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 驾驶行为分析接口
* 对于输入的一张车载监控图片(可正常解码,且长宽比适宜),**识别图像中是否有人体(驾驶员),若检测到至少1个人体,则进一步识别属性行为,可识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type smoke,cellphone,<br>not_buckling_up,<br>both_hands_leaving_wheel,<br>not_facing_front |识别的属性行为类别,英文逗号分隔,默认所有属性都识别;<br>smoke //吸烟,<br>cellphone //打手机 ,<br>not_buckling_up // 未系安全带,<br>both_hands_leaving_wheel // 双手离开方向盘,<br>not_facing_front // 视角未看前方
* @return JSONObject
*/
public JSONObject driverBehavior(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.DRIVER_BEHAVIOR);
postOperation(request);
return requestServer(request);
}
/**
* 驾驶行为分析接口
* 对于输入的一张车载监控图片(可正常解码,且长宽比适宜),**识别图像中是否有人体(驾驶员),若检测到至少1个人体,则进一步识别属性行为,可识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type smoke,cellphone,<br>not_buckling_up,<br>both_hands_leaving_wheel,<br>not_facing_front |识别的属性行为类别,英文逗号分隔,默认所有属性都识别;<br>smoke //吸烟,<br>cellphone //打手机 ,<br>not_buckling_up // 未系安全带,<br>both_hands_leaving_wheel // 双手离开方向盘,<br>not_facing_front // 视角未看前方
* @return JSONObject
*/
public JSONObject driverBehavior(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return driverBehavior(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人流量统计-动态版接口
* 统计图像中的人体个数和流动趋势,主要适用于**低空俯拍、出入口场景,以人体头肩为主要识别目标**
*
* @param image - 二进制图像数据
* @param dynamic - true:动态人流量统计,返回总人数、跟踪ID、区域进出人数;<br>false:静态人数统计,返回总人数
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* case_id 当dynamic为True时,必填;任务ID(通过case_id区分不同视频流,自拟,不同序列间不可重复即可)
* case_init 当dynamic为True时,必填;每个case的初始化信号,为true时对该case下的跟踪算法进行初始化,为false时重载该case的跟踪状态。当为false且读取不到相应case的信息时,直接重新初始化
* show 否返回结果图(含统计值和跟踪框渲染),默认不返回,选true时返回渲染后的图片(base64),其它无效值或为空则默认false
* area 当dynamic为True时,必填;静态人数统计时,只统计区域内的人,缺省时为全图统计。<br>动态人流量统计时,进出区域的人流会被统计。<br>逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',按顺序依次给出每个顶点的xy坐标(默认尾点和首点相连),形成闭合多边形区域。<br>服务会做范围(顶点左边需在图像范围内)及个数校验(数组长度必须为偶数,且大于3个顶点)。只支持单个多边形区域,建议设置矩形框,即4个顶点。**坐标取值不能超过图像宽度和高度,比如1280的宽度,坐标值最小建议从1开始,最大到1279**。
* @return JSONObject
*/
public JSONObject bodyTracking(byte[] image, String dynamic, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
request.addBody("dynamic", dynamic);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_TRACKING);
postOperation(request);
return requestServer(request);
}
/**
* 人流量统计-动态版接口
* 统计图像中的人体个数和流动趋势,主要适用于**低空俯拍、出入口场景,以人体头肩为主要识别目标**
*
* @param image - 本地图片路径
* @param dynamic - true:动态人流量统计,返回总人数、跟踪ID、区域进出人数;<br>false:静态人数统计,返回总人数
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* case_id 当dynamic为True时,必填;任务ID(通过case_id区分不同视频流,自拟,不同序列间不可重复即可)
* case_init 当dynamic为True时,必填;每个case的初始化信号,为true时对该case下的跟踪算法进行初始化,为false时重载该case的跟踪状态。当为false且读取不到相应case的信息时,直接重新初始化
* show 否返回结果图(含统计值和跟踪框渲染),默认不返回,选true时返回渲染后的图片(base64),其它无效值或为空则默认false
* area 当dynamic为True时,必填;静态人数统计时,只统计区域内的人,缺省时为全图统计。<br>动态人流量统计时,进出区域的人流会被统计。<br>逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',按顺序依次给出每个顶点的xy坐标(默认尾点和首点相连),形成闭合多边形区域。<br>服务会做范围(顶点左边需在图像范围内)及个数校验(数组长度必须为偶数,且大于3个顶点)。只支持单个多边形区域,建议设置矩形框,即4个顶点。**坐标取值不能超过图像宽度和高度,比如1280的宽度,坐标值最小建议从1开始,最大到1279**。
* @return JSONObject
*/
public JSONObject bodyTracking(String image, String dynamic, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyTracking(data, dynamic, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
/**
* 针对人像分割接口,将返回的二值图转化为灰度图,存储为jpg格式
* @param labelmapBase64 人像分割接口返回的二值图base64
* @param realWidth 图片原始宽度
* @param realHeight 图片原始高度
* @param outPath 灰度图输出路径
*/
public static void convert(String labelmapBase64, int realWidth, int realHeight, String outPath) {
try {
byte[] bytes = Base64Util.decode(labelmapBase64);
InputStream is = new ByteArrayInputStream(bytes);
BufferedImage image = ImageIO.read(is);
BufferedImage newImage = resize(image, realWidth, realHeight);
BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_GRAY);
for (int i = 0 ; i < realWidth ; i++) {
for (int j = 0 ; j < realHeight; j++) {
int rgb = newImage.getRGB(i, j);
grayImage.setRGB(i, j, rgb * 255); // 将像素存入缓冲区
}
}
File newFile = new File(outPath);
ImageIO.write(grayImage, "jpg", newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
} | Baidu-AIP/java-sdk | src/main/java/com/baidu/aip/bodyanalysis/AipBodyAnalysis.java | 6,787 | /**
* 人流量统计-动态版接口
* 统计图像中的人体个数和流动趋势,主要适用于**低空俯拍、出入口场景,以人体头肩为主要识别目标**
*
* @param image - 二进制图像数据
* @param dynamic - true:动态人流量统计,返回总人数、跟踪ID、区域进出人数;<br>false:静态人数统计,返回总人数
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* case_id 当dynamic为True时,必填;任务ID(通过case_id区分不同视频流,自拟,不同序列间不可重复即可)
* case_init 当dynamic为True时,必填;每个case的初始化信号,为true时对该case下的跟踪算法进行初始化,为false时重载该case的跟踪状态。当为false且读取不到相应case的信息时,直接重新初始化
* show 否返回结果图(含统计值和跟踪框渲染),默认不返回,选true时返回渲染后的图片(base64),其它无效值或为空则默认false
* area 当dynamic为True时,必填;静态人数统计时,只统计区域内的人,缺省时为全图统计。<br>动态人流量统计时,进出区域的人流会被统计。<br>逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',按顺序依次给出每个顶点的xy坐标(默认尾点和首点相连),形成闭合多边形区域。<br>服务会做范围(顶点左边需在图像范围内)及个数校验(数组长度必须为偶数,且大于3个顶点)。只支持单个多边形区域,建议设置矩形框,即4个顶点。**坐标取值不能超过图像宽度和高度,比如1280的宽度,坐标值最小建议从1开始,最大到1279**。
* @return JSONObject
*/ | block_comment | zh-cn | /*
* Copyright 2017 Baidu, Inc.
*
* 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 com.baidu.aip.bodyanalysis;
import com.baidu.aip.client.BaseClient;
import com.baidu.aip.error.AipError;
import com.baidu.aip.http.AipRequest;
import com.baidu.aip.util.Base64Util;
import com.baidu.aip.util.Util;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class AipBodyAnalysis extends BaseClient {
public AipBodyAnalysis(String appId, String apiKey, String secretKey) {
super(appId, apiKey, secretKey);
}
/**
* 人体关键点识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图片中的所有人体,输出每个人体的21个主要关键点,包含头顶、五官、脖颈、四肢等部位,同时输出人体的坐标信息和数量**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject bodyAnalysis(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_ANALYSIS);
postOperation(request);
return requestServer(request);
}
/**
* 人体关键点识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图片中的所有人体,输出每个人体的21个主要关键点,包含头顶、五官、脖颈、四肢等部位,同时输出人体的坐标信息和数量**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject bodyAnalysis(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyAnalysis(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人体检测与属性识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图像中的所有人体并返回每个人体的矩形框位置,识别人体的静态属性和行为,共支持20余种属性,包括:性别、年龄阶段、衣着(含类别/颜色)、是否戴帽子、是否戴眼镜、是否背包、是否使用手机、身体朝向等**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type gender,<br>age,<br>lower_wear,<br>upper_wear,<br>headwear,<br>glasses,<br>upper_color,<br>lower_color,<br>cellphone,<br>upper_wear_fg,<br>upper_wear_texture,<br>lower_wear_texture,<br>orientation,<br>umbrella,<br>bag,<br>smoke,<br>vehicle,<br>carrying_item,<br>upper_cut,<br>lower_cut,<br>occlusion,<br>is_human | 1)可选值说明:<br>gender-性别,<br>age-年龄阶段,<br>lower_wear-下身服饰,<br>upper_wear-上身服饰,<br>headwear-是否戴帽子,<br>glasses-是否戴眼镜,<br>upper_color-上身服饰颜色,<br>lower_color-下身服饰颜色,<br>cellphone-是否使用手机,<br>upper_wear_fg-上身服饰细分类,<br>upper_wear_texture-上身服饰纹理,<br>orientation-身体朝向,<br>umbrella-是否撑伞;<br>bag-背包,<br>smoke-是否吸烟,<br>vehicle-交通工具,<br>carrying_item-是否有手提物,<br>upper_cut-上方截断,<br>lower_cut-下方截断,<br>occlusion-遮挡,<br>is_human-是否是正常人体<br>2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部21个属性**
* @return JSONObject
*/
public JSONObject bodyAttr(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_ATTR);
postOperation(request);
return requestServer(request);
}
/**
* 人体检测与属性识别接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图像中的所有人体并返回每个人体的矩形框位置,识别人体的静态属性和行为,共支持20余种属性,包括:性别、年龄阶段、衣着(含类别/颜色)、是否戴帽子、是否戴眼镜、是否背包、是否使用手机、身体朝向等**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type gender,<br>age,<br>lower_wear,<br>upper_wear,<br>headwear,<br>glasses,<br>upper_color,<br>lower_color,<br>cellphone,<br>upper_wear_fg,<br>upper_wear_texture,<br>lower_wear_texture,<br>orientation,<br>umbrella,<br>bag,<br>smoke,<br>vehicle,<br>carrying_item,<br>upper_cut,<br>lower_cut,<br>occlusion,<br>is_human | 1)可选值说明:<br>gender-性别,<br>age-年龄阶段,<br>lower_wear-下身服饰,<br>upper_wear-上身服饰,<br>headwear-是否戴帽子,<br>glasses-是否戴眼镜,<br>upper_color-上身服饰颜色,<br>lower_color-下身服饰颜色,<br>cellphone-是否使用手机,<br>upper_wear_fg-上身服饰细分类,<br>upper_wear_texture-上身服饰纹理,<br>orientation-身体朝向,<br>umbrella-是否撑伞;<br>bag-背包,<br>smoke-是否吸烟,<br>vehicle-交通工具,<br>carrying_item-是否有手提物,<br>upper_cut-上方截断,<br>lower_cut-下方截断,<br>occlusion-遮挡,<br>is_human-是否是正常人体<br>2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部21个属性**
* @return JSONObject
*/
public JSONObject bodyAttr(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyAttr(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人流量统计接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像当中的人体个数(静态统计,暂不支持追踪和去重)**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* area 特定框选区域坐标,支持多个多边形区域,最多支持10个区域,如输入超过10个区域,截取前10个区域进行识别。<br>**此参数为空或无此参数、或area参数设置错误时,默认识别整个图片的人数** 。<br>area参数设置错误的示例:某个坐标超过原图大小,x、y坐标未成对出现等;注意:**设置了多个区域时,任意一个坐标设置错误,则认为area参数错误、失效**。<br>**area参数设置格式**:<br>1)多个区域用英文分号“;”分隔;<br>2)同一个区域内的坐标用英文逗号“,”分隔,默认尾点和首点相连做闭合。<br>示例:<br>1)单个多边形区域:x1,y1,x2,y2,x3,y3...xn,yn<br>2)多个多边形区域:xa1,ya1,xa2,ya2,xa3,ya3...xan,yan;xb1,yb1,xb2,yb2,xb3,yb3...xbn,ybn;..
* show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
* @return JSONObject
*/
public JSONObject bodyNum(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_NUM);
postOperation(request);
return requestServer(request);
}
/**
* 人流量统计接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像当中的人体个数(静态统计,暂不支持追踪和去重)**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* area 特定框选区域坐标,支持多个多边形区域,最多支持10个区域,如输入超过10个区域,截取前10个区域进行识别。<br>**此参数为空或无此参数、或area参数设置错误时,默认识别整个图片的人数** 。<br>area参数设置错误的示例:某个坐标超过原图大小,x、y坐标未成对出现等;注意:**设置了多个区域时,任意一个坐标设置错误,则认为area参数错误、失效**。<br>**area参数设置格式**:<br>1)多个区域用英文分号“;”分隔;<br>2)同一个区域内的坐标用英文逗号“,”分隔,默认尾点和首点相连做闭合。<br>示例:<br>1)单个多边形区域:x1,y1,x2,y2,x3,y3...xn,yn<br>2)多个多边形区域:xa1,ya1,xa2,ya2,xa3,ya3...xan,yan;xb1,yb1,xb2,yb2,xb3,yb3...xbn,ybn;..
* show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
* @return JSONObject
*/
public JSONObject bodyNum(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyNum(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 手势识别接口
* 识别图片中的手势类型,返回手势名称、手势矩形框、概率分数,可识别24种常见手势,适用于手势特效、智能家居手势交互等场景**。支持的24类手势列表:拳头、OK、祈祷、作揖、作别、单手比心、点赞、Diss、我爱你、掌心向上、双手比心(3种)、数字(9种)、Rock、竖中指。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject gesture(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.GESTURE);
postOperation(request);
return requestServer(request);
}
/**
* 手势识别接口
* 识别图片中的手势类型,返回手势名称、手势矩形框、概率分数,可识别24种常见手势,适用于手势特效、智能家居手势交互等场景**。支持的24类手势列表:拳头、OK、祈祷、作揖、作别、单手比心、点赞、Diss、我爱你、掌心向上、双手比心(3种)、数字(9种)、Rock、竖中指。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject gesture(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return gesture(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人像分割接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别人体的轮廓范围,与背景进行分离,适用于拍照背景替换、照片合成、身体特效等场景。输入正常人像图片,返回分割后的二值结果图和分割类型(目前仅支持person)**
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type 可以通过设置type参数,自主设置返回哪些结果图,避免造成带宽的浪费<br>1)可选值说明:<br>labelmap - 二值图像,需二次处理方能查看分割效果<br>scoremap - 人像前景灰度图<br>foreground - 人像前景抠图,透明背景<br>2)type 参数值可以是可选值的组合,用逗号分隔;如果无此参数默认输出全部3类结果图
* @return JSONObject
*/
public JSONObject bodySeg(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_SEG);
postOperation(request);
return requestServer(request);
}
/**
* 人像分割接口
* 对于输入的一张图片(可正常解码,且长宽比适宜),**识别人体的轮廓范围,与背景进行分离,适用于拍照背景替换、照片合成、身体特效等场景。输入正常人像图片,返回分割后的二值结果图和分割类型(目前仅支持person)**
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type 可以通过设置type参数,自主设置返回哪些结果图,避免造成带宽的浪费<br>1)可选值说明:<br>labelmap - 二值图像,需二次处理方能查看分割效果<br>scoremap - 人像前景灰度图<br>foreground - 人像前景抠图,透明背景<br>2)type 参数值可以是可选值的组合,用逗号分隔;如果无此参数默认输出全部3类结果图
* @return JSONObject
*/
public JSONObject bodySeg(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodySeg(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 驾驶行为分析接口
* 对于输入的一张车载监控图片(可正常解码,且长宽比适宜),**识别图像中是否有人体(驾驶员),若检测到至少1个人体,则进一步识别属性行为,可识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态**。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type smoke,cellphone,<br>not_buckling_up,<br>both_hands_leaving_wheel,<br>not_facing_front |识别的属性行为类别,英文逗号分隔,默认所有属性都识别;<br>smoke //吸烟,<br>cellphone //打手机 ,<br>not_buckling_up // 未系安全带,<br>both_hands_leaving_wheel // 双手离开方向盘,<br>not_facing_front // 视角未看前方
* @return JSONObject
*/
public JSONObject driverBehavior(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.DRIVER_BEHAVIOR);
postOperation(request);
return requestServer(request);
}
/**
* 驾驶行为分析接口
* 对于输入的一张车载监控图片(可正常解码,且长宽比适宜),**识别图像中是否有人体(驾驶员),若检测到至少1个人体,则进一步识别属性行为,可识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态**。
*
* @param image - 本地图片路径
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* type smoke,cellphone,<br>not_buckling_up,<br>both_hands_leaving_wheel,<br>not_facing_front |识别的属性行为类别,英文逗号分隔,默认所有属性都识别;<br>smoke //吸烟,<br>cellphone //打手机 ,<br>not_buckling_up // 未系安全带,<br>both_hands_leaving_wheel // 双手离开方向盘,<br>not_facing_front // 视角未看前方
* @return JSONObject
*/
public JSONObject driverBehavior(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return driverBehavior(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
/**
* 人流量 <SUF>*/
public JSONObject bodyTracking(byte[] image, String dynamic, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
request.addBody("dynamic", dynamic);
if (options != null) {
request.addBody(options);
}
request.setUri(BodyAnalysisConsts.BODY_TRACKING);
postOperation(request);
return requestServer(request);
}
/**
* 人流量统计-动态版接口
* 统计图像中的人体个数和流动趋势,主要适用于**低空俯拍、出入口场景,以人体头肩为主要识别目标**
*
* @param image - 本地图片路径
* @param dynamic - true:动态人流量统计,返回总人数、跟踪ID、区域进出人数;<br>false:静态人数统计,返回总人数
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* case_id 当dynamic为True时,必填;任务ID(通过case_id区分不同视频流,自拟,不同序列间不可重复即可)
* case_init 当dynamic为True时,必填;每个case的初始化信号,为true时对该case下的跟踪算法进行初始化,为false时重载该case的跟踪状态。当为false且读取不到相应case的信息时,直接重新初始化
* show 否返回结果图(含统计值和跟踪框渲染),默认不返回,选true时返回渲染后的图片(base64),其它无效值或为空则默认false
* area 当dynamic为True时,必填;静态人数统计时,只统计区域内的人,缺省时为全图统计。<br>动态人流量统计时,进出区域的人流会被统计。<br>逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',按顺序依次给出每个顶点的xy坐标(默认尾点和首点相连),形成闭合多边形区域。<br>服务会做范围(顶点左边需在图像范围内)及个数校验(数组长度必须为偶数,且大于3个顶点)。只支持单个多边形区域,建议设置矩形框,即4个顶点。**坐标取值不能超过图像宽度和高度,比如1280的宽度,坐标值最小建议从1开始,最大到1279**。
* @return JSONObject
*/
public JSONObject bodyTracking(String image, String dynamic, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return bodyTracking(data, dynamic, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
/**
* 针对人像分割接口,将返回的二值图转化为灰度图,存储为jpg格式
* @param labelmapBase64 人像分割接口返回的二值图base64
* @param realWidth 图片原始宽度
* @param realHeight 图片原始高度
* @param outPath 灰度图输出路径
*/
public static void convert(String labelmapBase64, int realWidth, int realHeight, String outPath) {
try {
byte[] bytes = Base64Util.decode(labelmapBase64);
InputStream is = new ByteArrayInputStream(bytes);
BufferedImage image = ImageIO.read(is);
BufferedImage newImage = resize(image, realWidth, realHeight);
BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_GRAY);
for (int i = 0 ; i < realWidth ; i++) {
for (int j = 0 ; j < realHeight; j++) {
int rgb = newImage.getRGB(i, j);
grayImage.setRGB(i, j, rgb * 255); // 将像素存入缓冲区
}
}
File newFile = new File(outPath);
ImageIO.write(grayImage, "jpg", newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
} | 0 | 870 | 0 |
10771_9 | package com.baidu.speech.restapi.asrdemo;
import com.baidu.speech.restapi.common.ConnUtil;
import com.baidu.speech.restapi.common.DemoException;
import com.baidu.speech.restapi.common.TokenHolder;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class AsrMain {
private final boolean METHOD_RAW = false; // 默认以json方式上传音频文件
// 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx"
private final String APP_KEY = "kVcnfD9iW2XVZSMaLXXXXXXX";
// 填写网页上申请的APP SECRET 如 $SECRET_KEY="94dc99566550d87f8fa8ece112xxxxx"
private final String SECRET_KEY = "O9o1O213UgG5LFn0bDGNtoRNXXXXXX";
// 需要识别的文件
private final String FILENAME = "16k.pcm";
// 文件格式, 支持pcm/wav/amr 格式,极速版额外支持m4a 格式
private final String FORMAT = FILENAME.substring(FILENAME.length() - 3);
private String CUID = "1234567JAVA";
// 采样率固定值
private final int RATE = 16000;
private String URL;
private int DEV_PID;
//private int LM_ID;//测试自训练平台需要打开此注释
private String SCOPE;
// 普通版 参数
{
URL = "http://vop.baidu.com/server_api"; // 可以改为https
// 1537 表示识别普通话,使用输入法模型。 其它语种参见文档
DEV_PID = 1537;
SCOPE = "audio_voice_assistant_get";
}
// 自训练平台 参数
/*{
//自训练平台模型上线后,您会看见 第二步:“”获取专属模型参数pid:8001,modelid:1234”,按照这个信息获取 dev_pid=8001,lm_id=1234
DEV_PID = 8001;
LM_ID = 1234;
}*/
/* 极速版 参数
{
URL = "http://vop.baidu.com/pro_api"; // 可以改为https
DEV_PID = 80001;
SCOPE = "brain_enhanced_asr";
}
*/
/* 忽略scope检查,非常旧的应用可能没有
{
SCOPE = null;
}
*/
public static void main(String[] args) throws IOException, DemoException {
AsrMain demo = new AsrMain();
// 填写下面信息
String result = demo.run();
System.out.println("识别结束:结果是:");
System.out.println(result);
// 如果显示乱码,请打开result.txt查看
File file = new File("result.txt");
FileWriter fo = new FileWriter(file);
fo.write(result);
fo.close();
System.out.println("Result also wrote into " + file.getAbsolutePath());
}
public String run() throws IOException, DemoException {
TokenHolder holder = new TokenHolder(APP_KEY, SECRET_KEY, SCOPE);
holder.resfresh();
String token = holder.getToken();
String result = null;
if (METHOD_RAW) {
result = runRawPostMethod(token);
} else {
result = runJsonPostMethod(token);
}
return result;
}
private String runRawPostMethod(String token) throws IOException, DemoException {
String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&token=" + token;
//测试自训练平台需要打开以下信息
//String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&lm_id="+ LM_ID + "&token=" + token;
String contentTypeStr = "audio/" + FORMAT + "; rate=" + RATE;
//System.out.println(url2);
byte[] content = getFileContent(FILENAME);
HttpURLConnection conn = (HttpURLConnection) new URL(url2).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", contentTypeStr);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(content);
conn.getOutputStream().close();
System.out.println("url is " + url2);
System.out.println("header is " + "Content-Type :" + contentTypeStr);
String result = ConnUtil.getResponseString(conn);
return result;
}
public String runJsonPostMethod(String token) throws DemoException, IOException {
byte[] content = getFileContent(FILENAME);
String speech = base64Encode(content);
JSONObject params = new JSONObject();
params.put("dev_pid", DEV_PID);
//params.put("lm_id",LM_ID);//测试自训练平台需要打开注释
params.put("format", FORMAT);
params.put("rate", RATE);
params.put("token", token);
params.put("cuid", CUID);
params.put("channel", "1");
params.put("len", content.length);
params.put("speech", speech);
// System.out.println(params.toString());
HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setDoOutput(true);
conn.getOutputStream().write(params.toString().getBytes());
conn.getOutputStream().close();
String result = ConnUtil.getResponseString(conn);
params.put("speech", "base64Encode(getFileContent(FILENAME))");
System.out.println("url is : " + URL);
System.out.println("params is :" + params.toString());
return result;
}
private byte[] getFileContent(String filename) throws DemoException, IOException {
File file = new File(filename);
if (!file.canRead()) {
System.err.println("文件不存在或者不可读: " + file.getAbsolutePath());
throw new DemoException("file cannot read: " + file.getAbsolutePath());
}
FileInputStream is = null;
try {
is = new FileInputStream(file);
return ConnUtil.getInputStreamContent(is);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String base64Encode(byte[] content) {
/**
Base64.Encoder encoder = Base64.getEncoder(); // JDK 1.8 推荐方法
String str = encoder.encodeToString(content);
**/
char[] chars = Base64Util.encode(content); // 1.7 及以下,不推荐,请自行跟换相关库
String str = new String(chars);
return str;
}
}
| Baidu-AIP/speech-demo | rest-api-asr/java/src/main/java/com/baidu/speech/restapi/asrdemo/AsrMain.java | 1,754 | // 1537 表示识别普通话,使用输入法模型。 其它语种参见文档
| line_comment | zh-cn | package com.baidu.speech.restapi.asrdemo;
import com.baidu.speech.restapi.common.ConnUtil;
import com.baidu.speech.restapi.common.DemoException;
import com.baidu.speech.restapi.common.TokenHolder;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class AsrMain {
private final boolean METHOD_RAW = false; // 默认以json方式上传音频文件
// 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx"
private final String APP_KEY = "kVcnfD9iW2XVZSMaLXXXXXXX";
// 填写网页上申请的APP SECRET 如 $SECRET_KEY="94dc99566550d87f8fa8ece112xxxxx"
private final String SECRET_KEY = "O9o1O213UgG5LFn0bDGNtoRNXXXXXX";
// 需要识别的文件
private final String FILENAME = "16k.pcm";
// 文件格式, 支持pcm/wav/amr 格式,极速版额外支持m4a 格式
private final String FORMAT = FILENAME.substring(FILENAME.length() - 3);
private String CUID = "1234567JAVA";
// 采样率固定值
private final int RATE = 16000;
private String URL;
private int DEV_PID;
//private int LM_ID;//测试自训练平台需要打开此注释
private String SCOPE;
// 普通版 参数
{
URL = "http://vop.baidu.com/server_api"; // 可以改为https
// 15 <SUF>
DEV_PID = 1537;
SCOPE = "audio_voice_assistant_get";
}
// 自训练平台 参数
/*{
//自训练平台模型上线后,您会看见 第二步:“”获取专属模型参数pid:8001,modelid:1234”,按照这个信息获取 dev_pid=8001,lm_id=1234
DEV_PID = 8001;
LM_ID = 1234;
}*/
/* 极速版 参数
{
URL = "http://vop.baidu.com/pro_api"; // 可以改为https
DEV_PID = 80001;
SCOPE = "brain_enhanced_asr";
}
*/
/* 忽略scope检查,非常旧的应用可能没有
{
SCOPE = null;
}
*/
public static void main(String[] args) throws IOException, DemoException {
AsrMain demo = new AsrMain();
// 填写下面信息
String result = demo.run();
System.out.println("识别结束:结果是:");
System.out.println(result);
// 如果显示乱码,请打开result.txt查看
File file = new File("result.txt");
FileWriter fo = new FileWriter(file);
fo.write(result);
fo.close();
System.out.println("Result also wrote into " + file.getAbsolutePath());
}
public String run() throws IOException, DemoException {
TokenHolder holder = new TokenHolder(APP_KEY, SECRET_KEY, SCOPE);
holder.resfresh();
String token = holder.getToken();
String result = null;
if (METHOD_RAW) {
result = runRawPostMethod(token);
} else {
result = runJsonPostMethod(token);
}
return result;
}
private String runRawPostMethod(String token) throws IOException, DemoException {
String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&token=" + token;
//测试自训练平台需要打开以下信息
//String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&lm_id="+ LM_ID + "&token=" + token;
String contentTypeStr = "audio/" + FORMAT + "; rate=" + RATE;
//System.out.println(url2);
byte[] content = getFileContent(FILENAME);
HttpURLConnection conn = (HttpURLConnection) new URL(url2).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", contentTypeStr);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(content);
conn.getOutputStream().close();
System.out.println("url is " + url2);
System.out.println("header is " + "Content-Type :" + contentTypeStr);
String result = ConnUtil.getResponseString(conn);
return result;
}
public String runJsonPostMethod(String token) throws DemoException, IOException {
byte[] content = getFileContent(FILENAME);
String speech = base64Encode(content);
JSONObject params = new JSONObject();
params.put("dev_pid", DEV_PID);
//params.put("lm_id",LM_ID);//测试自训练平台需要打开注释
params.put("format", FORMAT);
params.put("rate", RATE);
params.put("token", token);
params.put("cuid", CUID);
params.put("channel", "1");
params.put("len", content.length);
params.put("speech", speech);
// System.out.println(params.toString());
HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setDoOutput(true);
conn.getOutputStream().write(params.toString().getBytes());
conn.getOutputStream().close();
String result = ConnUtil.getResponseString(conn);
params.put("speech", "base64Encode(getFileContent(FILENAME))");
System.out.println("url is : " + URL);
System.out.println("params is :" + params.toString());
return result;
}
private byte[] getFileContent(String filename) throws DemoException, IOException {
File file = new File(filename);
if (!file.canRead()) {
System.err.println("文件不存在或者不可读: " + file.getAbsolutePath());
throw new DemoException("file cannot read: " + file.getAbsolutePath());
}
FileInputStream is = null;
try {
is = new FileInputStream(file);
return ConnUtil.getInputStreamContent(is);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String base64Encode(byte[] content) {
/**
Base64.Encoder encoder = Base64.getEncoder(); // JDK 1.8 推荐方法
String str = encoder.encodeToString(content);
**/
char[] chars = Base64Util.encode(content); // 1.7 及以下,不推荐,请自行跟换相关库
String str = new String(chars);
return str;
}
}
| 1 | 35 | 1 |
61164_6 | package com.ricemarch.cms.pms.entity;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* <p>
*
* </p>
*
* @author ricemarch
* @since 2021-03-05
*/
@Data
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private String id;
/**
* 微信小程序openId
*/
private String openId;
/**
* 微信unionId
*/
private String unionId;
/**
* 名称
*/
private String username;
/**
* 头像链接
*/
private String headImage;
/**
* 密码
*/
private String password;
/**
* 人事状态 on 在职,off 离职
*/
private String state;
/**
* 账号状态 默认未启用
*/
private Boolean accountState;
/**
* 薪水
*/
private Double salary;
private String gender;
private Boolean active;
/**
* 年纪
*/
private Integer age;
/**
* 手机号码
*/
private String phone;
/**
* 身份证号码
*/
private String idcardNumber;
/**
* 生日
*/
private LocalDate birthday;
/**
* 入职时间
*/
private LocalDate entryDay;
/**
* 地址信息
*/
private String address;
/**
* store 门店用户 company 公司用户 tenant 租户用户
*/
private String userType;
private Long storeId;
private Long companyId;
private Long tenantId;
/**
* 组织机构账号ID
*/
private Long sysUserId;
/**
* 密码是否手动设置
*/
private Boolean resetFlag;
/**
* 备注
*/
private String mark;
/**
* 是否删除
*/
private Boolean isDelete;
/**
* 存id
*/
private String updateUser;
/**
* 存id
*/
private String createUser;
private LocalDateTime createTime;
private LocalDateTime updateTime;
/**
* 店员编码
*/
private String userNo;
/**
* 岗位code
*/
private String positionCode;
/**
* 工种code
*/
private String professionCode;
}
| BakaRice/ricemarch-dfmc-cms-pms | src/main/java/com/ricemarch/cms/pms/entity/User.java | 593 | /**
* 密码
*/ | block_comment | zh-cn | package com.ricemarch.cms.pms.entity;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* <p>
*
* </p>
*
* @author ricemarch
* @since 2021-03-05
*/
@Data
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private String id;
/**
* 微信小程序openId
*/
private String openId;
/**
* 微信unionId
*/
private String unionId;
/**
* 名称
*/
private String username;
/**
* 头像链接
*/
private String headImage;
/**
* 密码
<SUF>*/
private String password;
/**
* 人事状态 on 在职,off 离职
*/
private String state;
/**
* 账号状态 默认未启用
*/
private Boolean accountState;
/**
* 薪水
*/
private Double salary;
private String gender;
private Boolean active;
/**
* 年纪
*/
private Integer age;
/**
* 手机号码
*/
private String phone;
/**
* 身份证号码
*/
private String idcardNumber;
/**
* 生日
*/
private LocalDate birthday;
/**
* 入职时间
*/
private LocalDate entryDay;
/**
* 地址信息
*/
private String address;
/**
* store 门店用户 company 公司用户 tenant 租户用户
*/
private String userType;
private Long storeId;
private Long companyId;
private Long tenantId;
/**
* 组织机构账号ID
*/
private Long sysUserId;
/**
* 密码是否手动设置
*/
private Boolean resetFlag;
/**
* 备注
*/
private String mark;
/**
* 是否删除
*/
private Boolean isDelete;
/**
* 存id
*/
private String updateUser;
/**
* 存id
*/
private String createUser;
private LocalDateTime createTime;
private LocalDateTime updateTime;
/**
* 店员编码
*/
private String userNo;
/**
* 岗位code
*/
private String positionCode;
/**
* 工种code
*/
private String professionCode;
}
| 0 | 21 | 0 |
41255_8 | package me.bakumon.library;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
/**
* 日食加载动画
*
* @author Bakumon https://bakumon.me
* @date 2018/01/03
*/
public class EclipseLoadingView extends View {
/**
* 左右日食过程
*/
private static final int STATE_ECLIPSE = 0;
/**
* 转圈过程
*/
private static final int STATE_ROTATE = 1;
/**
* 恢复过程
*/
private static final int STATE_RECOVER = 2;
/**
* view 默认宽高
*/
private int defaultSize;
/**
* 中心点坐标,xy
*/
private int center;
/**
* 太阳半径
*/
private int radius;
/**
* 圈圈线条的宽度
*/
private int arcWidth;
/**
* 太阳颜色
*/
private int mSunColor;
/**
* @see EclipseLoadingView#STATE_ECLIPSE
* @see EclipseLoadingView#STATE_ROTATE
* @see EclipseLoadingView#STATE_RECOVER
* 为了在 onDraw 中不绘制看不到的部分
*/
private int status;
private Paint paint;
/**
* 裁剪绘画区域
*/
private Path canvasClipPath;
/**
* 日食过程移动的 path
*/
private Path eclipseClipPath;
/**
* 恢复过程移动的 path
*/
private Path recoverClipPath;
/**
* 圈圈过程圆弧相关
*/
private RectF rectF;
/**
* 日食和恢复过程 path 移动的 offset
*/
private float eclipseOffsetX;
/**
* 圈圈过程圆弧显示的角度
*/
private float eclipseSweepAngle;
private AnimatorSet animatorSet;
public EclipseLoadingView(Context context) {
this(context, null);
}
public EclipseLoadingView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EclipseLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EclipseLoadingView);
mSunColor = a.getColor(R.styleable.EclipseLoadingView_sunColor, Color.parseColor("#FDAC2A"));
a.recycle();
init();
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
defaultSize = dp2px(60);
arcWidth = dp2px(2);
paint.setStrokeWidth(arcWidth);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 取宽高的最小值做整个 view 的边长
int size = Math.min(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec));
setMeasuredDimension(size, size);
}
private int measureSize(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = defaultSize;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// 宽和高相等
center = w / 2;
int bottom = getPaddingBottom();
int top = getPaddingTop();
int right = getPaddingRight();
int left = getPaddingLeft();
// 最大内边距
int maxPadding = Math.max(Math.max(Math.max(bottom, top), right), left);
radius = w / 2 - maxPadding;
int rectFLeftTop = maxPadding + arcWidth;
int rectFRightBottom = w - maxPadding - arcWidth;
rectF = new RectF(rectFLeftTop, rectFLeftTop, rectFRightBottom, rectFRightBottom);
canvasClipPath = new Path();
canvasClipPath.addCircle(center, center, center, Path.Direction.CW);
eclipseClipPath = new Path();
eclipseClipPath.setFillType(Path.FillType.INVERSE_WINDING);
eclipseClipPath.addCircle(center + radius * 2, center, radius, Path.Direction.CW);
recoverClipPath = new Path();
recoverClipPath.setFillType(Path.FillType.INVERSE_WINDING);
recoverClipPath.addCircle(center, center, radius, Path.Direction.CW);
initAnimator();
}
private void initAnimator() {
// animator1 日食过程
ValueAnimator animator1 = ValueAnimator.ofFloat(0, -((radius) * 2));
animator1.setDuration(2000);
animator1.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
status = STATE_ECLIPSE;
}
});
animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseOffsetX((Float) animation.getAnimatedValue());
}
});
// animator2 animator3 转圈过程
ValueAnimator animator2 = ValueAnimator.ofFloat(0, -360);
animator2.setDuration(400);
animator2.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
status = STATE_ROTATE;
}
});
animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseSweepAngle((Float) animation.getAnimatedValue());
}
});
ValueAnimator animator3 = ValueAnimator.ofFloat(360, 0);
animator3.setDuration(400);
animator3.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseSweepAngle((Float) animation.getAnimatedValue());
}
});
// animator4 恢复过程
ValueAnimator animator4 = ValueAnimator.ofFloat(0, -((radius) * 2));
animator4.setDuration(2000);
animator4.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
status = STATE_RECOVER;
}
});
animator4.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseOffsetX((Float) animation.getAnimatedValue());
}
});
animatorSet = new AnimatorSet();
animatorSet.playSequentially(animator1, animator2, animator3, animator4);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
animatorSet.start();
}
});
animatorSet.start();
}
private void setEclipseOffsetX(float eclipseOffsetX) {
this.eclipseOffsetX = eclipseOffsetX;
invalidate();
}
private void setEclipseSweepAngle(float eclipseSweepAngle) {
this.eclipseSweepAngle = eclipseSweepAngle;
invalidate();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
animatorSet.cancel();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.clipPath(canvasClipPath);
if (status == STATE_ROTATE) {
// 圈圈
drawRotate(canvas);
} else {
if (status == STATE_ECLIPSE) {
// 日食过程
drawEclipse(canvas, eclipseClipPath);
} else {
// 恢复过程
drawEclipse(canvas, recoverClipPath);
}
}
}
/**
* 画圈圈
*/
private void drawRotate(Canvas canvas) {
paint.setStyle(Paint.Style.STROKE);
paint.setColor(mSunColor);
canvas.drawArc(rectF, -90, eclipseSweepAngle, false, paint);
}
/**
* 日食或恢复过程
*
* @param eclipsePath eclipseClipPath:日食过程 recoverClipPath:恢复过程
*/
private void drawEclipse(Canvas canvas, Path eclipsePath) {
canvas.save();
eclipsePath.offset(eclipseOffsetX, 0);
canvas.clipPath(eclipsePath);
eclipsePath.offset(-eclipseOffsetX, 0);
// 太阳
paint.setStyle(Paint.Style.FILL);
paint.setColor(mSunColor);
canvas.drawCircle(center, center, radius, paint);
canvas.restore();
}
public int getSunColor() {
return mSunColor;
}
public void setSunColor(int sunColor) {
this.mSunColor = sunColor;
}
private int dp2px(float dipValue) {
float density = getContext().getResources().getDisplayMetrics().density;
return (int) (dipValue * density + 0.5f);
}
}
| Bakumon/EclipseLoading | library/src/main/java/me/bakumon/library/EclipseLoadingView.java | 2,353 | /**
* 太阳颜色
*/ | block_comment | zh-cn | package me.bakumon.library;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
/**
* 日食加载动画
*
* @author Bakumon https://bakumon.me
* @date 2018/01/03
*/
public class EclipseLoadingView extends View {
/**
* 左右日食过程
*/
private static final int STATE_ECLIPSE = 0;
/**
* 转圈过程
*/
private static final int STATE_ROTATE = 1;
/**
* 恢复过程
*/
private static final int STATE_RECOVER = 2;
/**
* view 默认宽高
*/
private int defaultSize;
/**
* 中心点坐标,xy
*/
private int center;
/**
* 太阳半径
*/
private int radius;
/**
* 圈圈线条的宽度
*/
private int arcWidth;
/**
* 太阳颜 <SUF>*/
private int mSunColor;
/**
* @see EclipseLoadingView#STATE_ECLIPSE
* @see EclipseLoadingView#STATE_ROTATE
* @see EclipseLoadingView#STATE_RECOVER
* 为了在 onDraw 中不绘制看不到的部分
*/
private int status;
private Paint paint;
/**
* 裁剪绘画区域
*/
private Path canvasClipPath;
/**
* 日食过程移动的 path
*/
private Path eclipseClipPath;
/**
* 恢复过程移动的 path
*/
private Path recoverClipPath;
/**
* 圈圈过程圆弧相关
*/
private RectF rectF;
/**
* 日食和恢复过程 path 移动的 offset
*/
private float eclipseOffsetX;
/**
* 圈圈过程圆弧显示的角度
*/
private float eclipseSweepAngle;
private AnimatorSet animatorSet;
public EclipseLoadingView(Context context) {
this(context, null);
}
public EclipseLoadingView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EclipseLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EclipseLoadingView);
mSunColor = a.getColor(R.styleable.EclipseLoadingView_sunColor, Color.parseColor("#FDAC2A"));
a.recycle();
init();
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
defaultSize = dp2px(60);
arcWidth = dp2px(2);
paint.setStrokeWidth(arcWidth);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 取宽高的最小值做整个 view 的边长
int size = Math.min(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec));
setMeasuredDimension(size, size);
}
private int measureSize(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = defaultSize;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// 宽和高相等
center = w / 2;
int bottom = getPaddingBottom();
int top = getPaddingTop();
int right = getPaddingRight();
int left = getPaddingLeft();
// 最大内边距
int maxPadding = Math.max(Math.max(Math.max(bottom, top), right), left);
radius = w / 2 - maxPadding;
int rectFLeftTop = maxPadding + arcWidth;
int rectFRightBottom = w - maxPadding - arcWidth;
rectF = new RectF(rectFLeftTop, rectFLeftTop, rectFRightBottom, rectFRightBottom);
canvasClipPath = new Path();
canvasClipPath.addCircle(center, center, center, Path.Direction.CW);
eclipseClipPath = new Path();
eclipseClipPath.setFillType(Path.FillType.INVERSE_WINDING);
eclipseClipPath.addCircle(center + radius * 2, center, radius, Path.Direction.CW);
recoverClipPath = new Path();
recoverClipPath.setFillType(Path.FillType.INVERSE_WINDING);
recoverClipPath.addCircle(center, center, radius, Path.Direction.CW);
initAnimator();
}
private void initAnimator() {
// animator1 日食过程
ValueAnimator animator1 = ValueAnimator.ofFloat(0, -((radius) * 2));
animator1.setDuration(2000);
animator1.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
status = STATE_ECLIPSE;
}
});
animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseOffsetX((Float) animation.getAnimatedValue());
}
});
// animator2 animator3 转圈过程
ValueAnimator animator2 = ValueAnimator.ofFloat(0, -360);
animator2.setDuration(400);
animator2.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
status = STATE_ROTATE;
}
});
animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseSweepAngle((Float) animation.getAnimatedValue());
}
});
ValueAnimator animator3 = ValueAnimator.ofFloat(360, 0);
animator3.setDuration(400);
animator3.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseSweepAngle((Float) animation.getAnimatedValue());
}
});
// animator4 恢复过程
ValueAnimator animator4 = ValueAnimator.ofFloat(0, -((radius) * 2));
animator4.setDuration(2000);
animator4.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
status = STATE_RECOVER;
}
});
animator4.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setEclipseOffsetX((Float) animation.getAnimatedValue());
}
});
animatorSet = new AnimatorSet();
animatorSet.playSequentially(animator1, animator2, animator3, animator4);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
animatorSet.start();
}
});
animatorSet.start();
}
private void setEclipseOffsetX(float eclipseOffsetX) {
this.eclipseOffsetX = eclipseOffsetX;
invalidate();
}
private void setEclipseSweepAngle(float eclipseSweepAngle) {
this.eclipseSweepAngle = eclipseSweepAngle;
invalidate();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
animatorSet.cancel();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.clipPath(canvasClipPath);
if (status == STATE_ROTATE) {
// 圈圈
drawRotate(canvas);
} else {
if (status == STATE_ECLIPSE) {
// 日食过程
drawEclipse(canvas, eclipseClipPath);
} else {
// 恢复过程
drawEclipse(canvas, recoverClipPath);
}
}
}
/**
* 画圈圈
*/
private void drawRotate(Canvas canvas) {
paint.setStyle(Paint.Style.STROKE);
paint.setColor(mSunColor);
canvas.drawArc(rectF, -90, eclipseSweepAngle, false, paint);
}
/**
* 日食或恢复过程
*
* @param eclipsePath eclipseClipPath:日食过程 recoverClipPath:恢复过程
*/
private void drawEclipse(Canvas canvas, Path eclipsePath) {
canvas.save();
eclipsePath.offset(eclipseOffsetX, 0);
canvas.clipPath(eclipsePath);
eclipsePath.offset(-eclipseOffsetX, 0);
// 太阳
paint.setStyle(Paint.Style.FILL);
paint.setColor(mSunColor);
canvas.drawCircle(center, center, radius, paint);
canvas.restore();
}
public int getSunColor() {
return mSunColor;
}
public void setSunColor(int sunColor) {
this.mSunColor = sunColor;
}
private int dp2px(float dipValue) {
float density = getContext().getResources().getDisplayMetrics().density;
return (int) (dipValue * density + 0.5f);
}
}
| 1 | 23 | 1 |
37098_10 | package leetcode.algorithms;
import java.util.*;
import java.util.stream.Collectors;
/**
* Description: 2115. Find All Possible Recipes from Given Supplies
*
* @author Baltan
* @date 2021/12/26 14:45
*/
public class FindAllRecipes {
public static void main(String[] args) {
String[] recipes1 = {"bread"};
List<List<String>> ingredients1 = Arrays.asList(
Arrays.asList("yeast", "flour")
);
String[] supplies1 = {"yeast", "flour", "corn"};
System.out.println(findAllRecipes(recipes1, ingredients1, supplies1));
String[] recipes2 = {"bread", "sandwich"};
List<List<String>> ingredients2 = Arrays.asList(
Arrays.asList("yeast", "flour"),
Arrays.asList("bread", "meat")
);
String[] supplies2 = {"yeast", "flour", "meat"};
System.out.println(findAllRecipes(recipes2, ingredients2, supplies2));
String[] recipes3 = {"bread", "sandwich", "burger"};
List<List<String>> ingredients3 = Arrays.asList(
Arrays.asList("yeast", "flour"),
Arrays.asList("bread", "meat"),
Arrays.asList("sandwich", "meat", "bread")
);
String[] supplies3 = {"yeast", "flour", "meat"};
System.out.println(findAllRecipes(recipes3, ingredients3, supplies3));
String[] recipes4 = {"bread"};
List<List<String>> ingredients4 = Arrays.asList(
Arrays.asList("yeast", "flour")
);
String[] supplies4 = {"yeast"};
System.out.println(findAllRecipes(recipes4, ingredients4, supplies4));
}
public static List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients,
String[] supplies) {
List<String> result = new ArrayList<>();
/**
* 已拥有的原材料集合
*/
Set<String> supplySet = Arrays.stream(supplies).collect(Collectors.toSet());
/**
* 每道菜需要的原材料集合
*/
List<Set<String>> ingredientSetList = ingredients.stream()
.map(ingredient -> ingredient.stream().collect(Collectors.toSet()))
.collect(Collectors.toList());
/**
* 剩余还未做出的菜
*/
int leftCount = recipes.length;
/**
* isCreated[i]表示第i道菜是否已被做出
*/
boolean[] isCreated = new boolean[leftCount];
/**
* 标记每一轮判断是否有新的菜被做出,如果有新的菜被做出,可能会使得其他菜也能被做出,需要继续判断
*/
boolean changed = true;
while (changed && leftCount > 0) {
/**
* 当前这轮判断还没有新的菜被做出
*/
changed = false;
for (int i = 0; i < ingredientSetList.size(); i++) {
/**
* 已被做出的菜不需要重复判断
*/
if (isCreated[i]) {
continue;
}
/**
* 如果需要完成当前这道菜还需要的原材料
*/
Set<String> ingredientSet = ingredientSetList.get(i);
Iterator<String> it = ingredientSet.iterator();
/**
* 如果需要的原材料我们已经拥有了,就删除
*/
while (it.hasNext()) {
String str = it.next();
if (supplySet.contains(str)) {
it.remove();
}
}
/**
* 如果当前这道菜所需要的所有原材料我们都拥有了,就可以做出这道菜了,同时这道菜也被加入我们拥有的原材料中,用于
* 判断是否能做出其他的才
*/
if (ingredientSet.isEmpty()) {
supplySet.add(recipes[i]);
result.add(recipes[i]);
isCreated[i] = true;
changed = true;
}
}
}
return result;
}
}
| Baltan/leetcode | src/leetcode/algorithms/FindAllRecipes.java | 976 | /**
* 如果当前这道菜所需要的所有原材料我们都拥有了,就可以做出这道菜了,同时这道菜也被加入我们拥有的原材料中,用于
* 判断是否能做出其他的才
*/ | block_comment | zh-cn | package leetcode.algorithms;
import java.util.*;
import java.util.stream.Collectors;
/**
* Description: 2115. Find All Possible Recipes from Given Supplies
*
* @author Baltan
* @date 2021/12/26 14:45
*/
public class FindAllRecipes {
public static void main(String[] args) {
String[] recipes1 = {"bread"};
List<List<String>> ingredients1 = Arrays.asList(
Arrays.asList("yeast", "flour")
);
String[] supplies1 = {"yeast", "flour", "corn"};
System.out.println(findAllRecipes(recipes1, ingredients1, supplies1));
String[] recipes2 = {"bread", "sandwich"};
List<List<String>> ingredients2 = Arrays.asList(
Arrays.asList("yeast", "flour"),
Arrays.asList("bread", "meat")
);
String[] supplies2 = {"yeast", "flour", "meat"};
System.out.println(findAllRecipes(recipes2, ingredients2, supplies2));
String[] recipes3 = {"bread", "sandwich", "burger"};
List<List<String>> ingredients3 = Arrays.asList(
Arrays.asList("yeast", "flour"),
Arrays.asList("bread", "meat"),
Arrays.asList("sandwich", "meat", "bread")
);
String[] supplies3 = {"yeast", "flour", "meat"};
System.out.println(findAllRecipes(recipes3, ingredients3, supplies3));
String[] recipes4 = {"bread"};
List<List<String>> ingredients4 = Arrays.asList(
Arrays.asList("yeast", "flour")
);
String[] supplies4 = {"yeast"};
System.out.println(findAllRecipes(recipes4, ingredients4, supplies4));
}
public static List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients,
String[] supplies) {
List<String> result = new ArrayList<>();
/**
* 已拥有的原材料集合
*/
Set<String> supplySet = Arrays.stream(supplies).collect(Collectors.toSet());
/**
* 每道菜需要的原材料集合
*/
List<Set<String>> ingredientSetList = ingredients.stream()
.map(ingredient -> ingredient.stream().collect(Collectors.toSet()))
.collect(Collectors.toList());
/**
* 剩余还未做出的菜
*/
int leftCount = recipes.length;
/**
* isCreated[i]表示第i道菜是否已被做出
*/
boolean[] isCreated = new boolean[leftCount];
/**
* 标记每一轮判断是否有新的菜被做出,如果有新的菜被做出,可能会使得其他菜也能被做出,需要继续判断
*/
boolean changed = true;
while (changed && leftCount > 0) {
/**
* 当前这轮判断还没有新的菜被做出
*/
changed = false;
for (int i = 0; i < ingredientSetList.size(); i++) {
/**
* 已被做出的菜不需要重复判断
*/
if (isCreated[i]) {
continue;
}
/**
* 如果需要完成当前这道菜还需要的原材料
*/
Set<String> ingredientSet = ingredientSetList.get(i);
Iterator<String> it = ingredientSet.iterator();
/**
* 如果需要的原材料我们已经拥有了,就删除
*/
while (it.hasNext()) {
String str = it.next();
if (supplySet.contains(str)) {
it.remove();
}
}
/**
* 如果当 <SUF>*/
if (ingredientSet.isEmpty()) {
supplySet.add(recipes[i]);
result.add(recipes[i]);
isCreated[i] = true;
changed = true;
}
}
}
return result;
}
}
| 1 | 128 | 1 |
11950_4 | package org.spring.springboot;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* 小混蛋
*/
public class CodeGenerator {
public static final String DB_URL = "jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true";
public static final String USER_NAME = "root";
public static final String PASSWORD = "root";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String AUTHOR = "作者bamboo";
//生成的文件输出到哪个目录
public static final String OUTPUT_FILE = "D:\\codeGen";
//包名,会按照com/example/demo这种形式生成类
public static final String PACKAGE = "com.example.demo";
//TODO 更多配置请参考http://mp.baomidou.com/#/generate-code
public void generateByTables(boolean serviceNameStartWithI, String... tableNames) {
GlobalConfig config = new GlobalConfig();
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(DB_URL)
.setUsername(USER_NAME)
.setPassword(PASSWORD)
.setDriverName(DRIVER);
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setDbColumnUnderline(true)
.setNaming(NamingStrategy.underline_to_camel)
.setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
config.setActiveRecord(false)
.setAuthor(AUTHOR)
.setOutputDir(OUTPUT_FILE)
.setFileOverride(true);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent(PACKAGE)
.setController("controller")
.setEntity("entity")
).execute();
}
public static void main(String[] args) {
CodeGenerator gse = new CodeGenerator();
//要给那些表生成
gse.generateByTables(false,"t_red_packet_activity");
}
}
| BambooZhang/springboot-study | springboot-mybatis-plus/src/main/java/org/spring/springboot/CodeGenerator.java | 624 | //TODO 更多配置请参考http://mp.baomidou.com/#/generate-code | line_comment | zh-cn | package org.spring.springboot;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* 小混蛋
*/
public class CodeGenerator {
public static final String DB_URL = "jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true";
public static final String USER_NAME = "root";
public static final String PASSWORD = "root";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String AUTHOR = "作者bamboo";
//生成的文件输出到哪个目录
public static final String OUTPUT_FILE = "D:\\codeGen";
//包名,会按照com/example/demo这种形式生成类
public static final String PACKAGE = "com.example.demo";
//TO <SUF>
public void generateByTables(boolean serviceNameStartWithI, String... tableNames) {
GlobalConfig config = new GlobalConfig();
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(DB_URL)
.setUsername(USER_NAME)
.setPassword(PASSWORD)
.setDriverName(DRIVER);
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setDbColumnUnderline(true)
.setNaming(NamingStrategy.underline_to_camel)
.setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
config.setActiveRecord(false)
.setAuthor(AUTHOR)
.setOutputDir(OUTPUT_FILE)
.setFileOverride(true);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent(PACKAGE)
.setController("controller")
.setEntity("entity")
).execute();
}
public static void main(String[] args) {
CodeGenerator gse = new CodeGenerator();
//要给那些表生成
gse.generateByTables(false,"t_red_packet_activity");
}
}
| 0 | 52 | 0 |
9838_8 | package com.bamboy.bamboycollected.page.freedom;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.bamboy.bamboycollected.R;
import com.bamboy.bamboycollected.base.actiivty.BamActivity;
import com.bamboy.bamboycollected.base.freedom.FreedomAdapter;
import com.bamboy.bamboycollected.base.freedom.FreedomBean;
import com.bamboy.bamboycollected.base.freedom.FreedomCallback;
import com.bamboy.bamboycollected.base.freedom.ViewHolderManager;
import com.bamboy.bamboycollected.page.bean.FourIconBean;
import com.bamboy.bamboycollected.page.bean.SingleBtnBean;
import com.bamboy.bamboycollected.page.bean.SingleImageBean;
import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueLeft;
import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueRight;
import com.bamboy.bamboycollected.page.freedom.bean.BeanMusic;
import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsImg;
import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsText;
import com.bamboy.bamboycollected.page.toast.bamtoast.BamToast;
import java.util.ArrayList;
import java.util.List;
/**
* 非约束列表Demo
* <p>
* Created by Bamboy on 2017/4/17.
*/
public class FreedomListActivity extends BamActivity implements FreedomCallback {
private RecyclerView recycler;
/**
* 数据源
*/
private List<FreedomBean> mList;
/**
* 适配器
*/
private FreedomAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_freedom);
}
@Override
protected void findView() {
recycler = findViewById(R.id.recycler);
}
@Override
protected void setListener() {
}
@Override
protected void init() {
// 初始化RecyclerView
initRecycler();
}
@Override
public void onClickCallback(View view, int position, ViewHolderManager.ViewHolder holder) {
switch (view.getId()) {
case R.id.rl_single:
BamToast.showText(this, "点击了条目样式 1");
break;
case R.id.rl_fresh:
BamToast.showText(this, "点击了最新上架");
break;
case R.id.rl_hot:
BamToast.showText(this, "点击了热门精选");
break;
case R.id.rl_classic:
BamToast.showText(this, "点击了重温经典");
break;
case R.id.rl_sleep:
BamToast.showText(this, "点击了睡前小酌");
break;
case R.id.iv_single:
BamToast.showText(this, "点击了单个图片");
break;
}
}
/**
* 初始化列表数据
*/
private void initRecycler() {
// 初始化数据
initData();
// 实例化RecyclerView
// 把每行平分成2份
GridLayoutManager manager = new GridLayoutManager(this, 2);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
FreedomBean bean = mList.get(position);
// 获取当前这个条目占几份
return bean.getSpanSize(2);
}
});
recycler.setLayoutManager(manager);
recycler.setItemAnimator(null);
mAdapter = new FreedomAdapter(this, mList);
recycler.setAdapter(mAdapter);
}
/**
* 初始化数据
*/
private void initData() {
// 实例化List
mList = new ArrayList();
// 模拟加载数据,往mList里放一些乱七八糟的条目
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanMusic("成都", "赵雷 - 成都"));
mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集"));
mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲"));
mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手"));
mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己"));
mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……"));
mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮"));
mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮"));
mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。"));
mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……"));
mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者"));
mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱"));
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了"));
mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!"));
mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?"));
mList.add(new BeanDialogueRight("六六", "我要吃肉肉…"));
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanMusic("成都", "赵雷 - 成都"));
mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集"));
mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲"));
mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手"));
mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己"));
mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……"));
mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮"));
mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮"));
mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。"));
mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……"));
mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者"));
mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱"));
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了"));
mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!"));
mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?"));
mList.add(new BeanDialogueRight("六六", "我要吃肉肉…"));
}
}
| Bamboy120315/bamboy | app/src/main/java/com/bamboy/bamboycollected/page/freedom/FreedomListActivity.java | 2,514 | // 获取当前这个条目占几份 | line_comment | zh-cn | package com.bamboy.bamboycollected.page.freedom;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.bamboy.bamboycollected.R;
import com.bamboy.bamboycollected.base.actiivty.BamActivity;
import com.bamboy.bamboycollected.base.freedom.FreedomAdapter;
import com.bamboy.bamboycollected.base.freedom.FreedomBean;
import com.bamboy.bamboycollected.base.freedom.FreedomCallback;
import com.bamboy.bamboycollected.base.freedom.ViewHolderManager;
import com.bamboy.bamboycollected.page.bean.FourIconBean;
import com.bamboy.bamboycollected.page.bean.SingleBtnBean;
import com.bamboy.bamboycollected.page.bean.SingleImageBean;
import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueLeft;
import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueRight;
import com.bamboy.bamboycollected.page.freedom.bean.BeanMusic;
import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsImg;
import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsText;
import com.bamboy.bamboycollected.page.toast.bamtoast.BamToast;
import java.util.ArrayList;
import java.util.List;
/**
* 非约束列表Demo
* <p>
* Created by Bamboy on 2017/4/17.
*/
public class FreedomListActivity extends BamActivity implements FreedomCallback {
private RecyclerView recycler;
/**
* 数据源
*/
private List<FreedomBean> mList;
/**
* 适配器
*/
private FreedomAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_freedom);
}
@Override
protected void findView() {
recycler = findViewById(R.id.recycler);
}
@Override
protected void setListener() {
}
@Override
protected void init() {
// 初始化RecyclerView
initRecycler();
}
@Override
public void onClickCallback(View view, int position, ViewHolderManager.ViewHolder holder) {
switch (view.getId()) {
case R.id.rl_single:
BamToast.showText(this, "点击了条目样式 1");
break;
case R.id.rl_fresh:
BamToast.showText(this, "点击了最新上架");
break;
case R.id.rl_hot:
BamToast.showText(this, "点击了热门精选");
break;
case R.id.rl_classic:
BamToast.showText(this, "点击了重温经典");
break;
case R.id.rl_sleep:
BamToast.showText(this, "点击了睡前小酌");
break;
case R.id.iv_single:
BamToast.showText(this, "点击了单个图片");
break;
}
}
/**
* 初始化列表数据
*/
private void initRecycler() {
// 初始化数据
initData();
// 实例化RecyclerView
// 把每行平分成2份
GridLayoutManager manager = new GridLayoutManager(this, 2);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
FreedomBean bean = mList.get(position);
// 获取 <SUF>
return bean.getSpanSize(2);
}
});
recycler.setLayoutManager(manager);
recycler.setItemAnimator(null);
mAdapter = new FreedomAdapter(this, mList);
recycler.setAdapter(mAdapter);
}
/**
* 初始化数据
*/
private void initData() {
// 实例化List
mList = new ArrayList();
// 模拟加载数据,往mList里放一些乱七八糟的条目
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanMusic("成都", "赵雷 - 成都"));
mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集"));
mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲"));
mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手"));
mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己"));
mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……"));
mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮"));
mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮"));
mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。"));
mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……"));
mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者"));
mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱"));
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了"));
mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!"));
mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?"));
mList.add(new BeanDialogueRight("六六", "我要吃肉肉…"));
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanMusic("成都", "赵雷 - 成都"));
mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集"));
mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲"));
mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手"));
mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己"));
mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……"));
mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮"));
mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮"));
mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。"));
mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……"));
mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者"));
mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱"));
mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?"));
mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了"));
mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!"));
mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?"));
mList.add(new BeanDialogueRight("六六", "我要吃肉肉…"));
}
}
| 1 | 14 | 1 |
19065_3 | package com.bantanger.im.domain.group.service;
import com.bantanger.im.common.model.SyncReq;
import com.bantanger.im.domain.group.model.req.*;
import com.bantanger.im.common.ResponseVO;
import com.bantanger.im.domain.group.dao.ImGroupEntity;
/**
* @author BanTanger 半糖
* @Date 2023/3/25 15:16
*/
public interface ImGroupService {
/**
* 批量导入群组信息
* 如果 req 没有群组 ID,会通过 uuid 自动生成一个
* @param req
* @return
*/
ResponseVO importGroup(ImportGroupReq req);
/**
* 创建群组
* @param req
* @return
*/
ResponseVO createGroup(CreateGroupReq req);
/**
* 修改群基础信息
* 如果是后台管理员调用,则不检查权限,如果不是则检查权限,
* 如果是私有群(微信群)任何人都可以修改资料,公开群只有管理员可以修改
* 如果是群主或者管理员可以修改其他信息。
* @param req
* @return com.lld.im.common.ResponseVO
*/
ResponseVO updateBaseGroupInfo(UpdateGroupReq req);
/**
* 获取用户加入所有群组列表
* @param req
* @return com.lld.im.common.ResponseVO
*/
ResponseVO getJoinedGroup(GetJoinedGroupReq req);
/**
* 解散群组,只支持后台管理员和群主解散, 私有群只能通过 app 管理员解散
* @param req
* @return com.lld.im.common.ResponseVO
*/
ResponseVO destroyGroup(DestroyGroupReq req);
/**
* 转让群组
* @param req
* @return
*/
ResponseVO transferGroup(TransferGroupReq req);
/**
* 获取指定群组信息
* @param groupId
* @param appId
* @return 200 代表存在,4000 代表不存在
*/
ResponseVO<ImGroupEntity> getGroup(String groupId, Integer appId);
/**
* 获取指定群组信息以及群内所有成员信息
* @param req
* @return
*/
ResponseVO getGroup(GetGroupReq req);
ResponseVO muteGroup(MuteGroupReq req);
ResponseVO syncJoinedGroupList(SyncReq req);
Long getUserGroupMaxSeq(String userId, Integer appId);
}
| BanTanger/im-whale-shark | im-domain/src/main/java/com/bantanger/im/domain/group/service/ImGroupService.java | 582 | /**
* 修改群基础信息
* 如果是后台管理员调用,则不检查权限,如果不是则检查权限,
* 如果是私有群(微信群)任何人都可以修改资料,公开群只有管理员可以修改
* 如果是群主或者管理员可以修改其他信息。
* @param req
* @return com.lld.im.common.ResponseVO
*/ | block_comment | zh-cn | package com.bantanger.im.domain.group.service;
import com.bantanger.im.common.model.SyncReq;
import com.bantanger.im.domain.group.model.req.*;
import com.bantanger.im.common.ResponseVO;
import com.bantanger.im.domain.group.dao.ImGroupEntity;
/**
* @author BanTanger 半糖
* @Date 2023/3/25 15:16
*/
public interface ImGroupService {
/**
* 批量导入群组信息
* 如果 req 没有群组 ID,会通过 uuid 自动生成一个
* @param req
* @return
*/
ResponseVO importGroup(ImportGroupReq req);
/**
* 创建群组
* @param req
* @return
*/
ResponseVO createGroup(CreateGroupReq req);
/**
* 修改群 <SUF>*/
ResponseVO updateBaseGroupInfo(UpdateGroupReq req);
/**
* 获取用户加入所有群组列表
* @param req
* @return com.lld.im.common.ResponseVO
*/
ResponseVO getJoinedGroup(GetJoinedGroupReq req);
/**
* 解散群组,只支持后台管理员和群主解散, 私有群只能通过 app 管理员解散
* @param req
* @return com.lld.im.common.ResponseVO
*/
ResponseVO destroyGroup(DestroyGroupReq req);
/**
* 转让群组
* @param req
* @return
*/
ResponseVO transferGroup(TransferGroupReq req);
/**
* 获取指定群组信息
* @param groupId
* @param appId
* @return 200 代表存在,4000 代表不存在
*/
ResponseVO<ImGroupEntity> getGroup(String groupId, Integer appId);
/**
* 获取指定群组信息以及群内所有成员信息
* @param req
* @return
*/
ResponseVO getGroup(GetGroupReq req);
ResponseVO muteGroup(MuteGroupReq req);
ResponseVO syncJoinedGroupList(SyncReq req);
Long getUserGroupMaxSeq(String userId, Integer appId);
}
| 0 | 193 | 0 |
14960_17 | package xyz.acproject.danmuji.conf.set;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import xyz.acproject.danmuji.conf.PublicDataConf;
import xyz.acproject.danmuji.conf.base.ThankLiveSetConf;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
/**
* @ClassName ThankGiftSetConf
* @Description TODO
* @author BanqiJane
* @date 2020年8月10日 下午12:21:24
*
* @Copyright:2020 blogs.acproject.xyz Inc. All rights reserved.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ThankGiftSetConf extends ThankLiveSetConf implements Serializable{
/**
*
*/
private static final long serialVersionUID = -418947096472064467L;
//是否开启本人
@JSONField(name = "is_open_self")
private boolean is_open_self = false;
//礼物屏蔽模式 0 自定义 1 免费 2 低价 3 规则
private short shield_status =0;
//礼物名单限制模式 0黑名单 1白名单 默认黑
@JSONField(name = "list_gift_shield_status")
private short list_gift_shield_status = 0;
//人员感谢过滤 0全部 1仅勋章 2仅舰长
@JSONField(name = "list_people_shield_status")
private short list_people_shield_status = 0;
//自定义礼物屏蔽 0
private HashSet<String> giftStrings;
//自定义感谢屏蔽规则 3
private HashSet<ThankGiftRuleSet> thankGiftRuleSets;
//感谢模式 0 单人单种 1 单人多种 2 多人多种
private short thank_status = 0;
//感谢语 默认感谢模式0下的
private String thank ="感谢%uName%大佬%Type%的%GiftName% x%Num%~";
//是否舰长私信
@JSONField(name = "is_guard_report")
private boolean is_guard_report =false;
//是否开启本地存储舰长
@JSONField(name = "is_guard_local")
private boolean is_guard_local=false;
//是否开启礼物码模式
@JSONField(name = "is_gift_code")
private boolean is_gift_code = false;
//舰长私信语
private String report;
//舰长私信成功后发送弹幕
private String report_barrage;
//礼物码HashSet
private HashSet<String> codeStrings;
//是否开启感谢数量显示
@JSONField(name = "is_num")
private boolean is_num=true;
public ThankGiftSetConf(boolean is_open) {
super();
super.set_open(is_open);
}
//方法区
public boolean is_giftThank(){
if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){
return false;
}
if(is_live_open()) {
//没在直播
if(PublicDataConf.lIVE_STATUS !=1){
return false;
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}
public boolean is_giftThank(short live_status){
if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){
return false;
}
if(is_live_open()) {
//没在直播
if(live_status!=1){
return false;
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}
public HashSet<ThankGiftRuleSet> getThankGiftRuleSets() {
if(thankGiftRuleSets!=null) {
return thankGiftRuleSets.stream().sorted(Comparator.comparing(ThankGiftRuleSet::getGift_name)).collect(Collectors.toCollection(LinkedHashSet::new));
}
return new HashSet<>();
}
public HashSet<String> getCodeStrings() {
if(codeStrings!=null) {
return codeStrings.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new));
}
return new HashSet<>();
}
}
| BanqiJane/Bilibili_Danmuji | src/main/java/xyz/acproject/danmuji/conf/set/ThankGiftSetConf.java | 1,247 | //没在直播 | line_comment | zh-cn | package xyz.acproject.danmuji.conf.set;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import xyz.acproject.danmuji.conf.PublicDataConf;
import xyz.acproject.danmuji.conf.base.ThankLiveSetConf;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
/**
* @ClassName ThankGiftSetConf
* @Description TODO
* @author BanqiJane
* @date 2020年8月10日 下午12:21:24
*
* @Copyright:2020 blogs.acproject.xyz Inc. All rights reserved.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ThankGiftSetConf extends ThankLiveSetConf implements Serializable{
/**
*
*/
private static final long serialVersionUID = -418947096472064467L;
//是否开启本人
@JSONField(name = "is_open_self")
private boolean is_open_self = false;
//礼物屏蔽模式 0 自定义 1 免费 2 低价 3 规则
private short shield_status =0;
//礼物名单限制模式 0黑名单 1白名单 默认黑
@JSONField(name = "list_gift_shield_status")
private short list_gift_shield_status = 0;
//人员感谢过滤 0全部 1仅勋章 2仅舰长
@JSONField(name = "list_people_shield_status")
private short list_people_shield_status = 0;
//自定义礼物屏蔽 0
private HashSet<String> giftStrings;
//自定义感谢屏蔽规则 3
private HashSet<ThankGiftRuleSet> thankGiftRuleSets;
//感谢模式 0 单人单种 1 单人多种 2 多人多种
private short thank_status = 0;
//感谢语 默认感谢模式0下的
private String thank ="感谢%uName%大佬%Type%的%GiftName% x%Num%~";
//是否舰长私信
@JSONField(name = "is_guard_report")
private boolean is_guard_report =false;
//是否开启本地存储舰长
@JSONField(name = "is_guard_local")
private boolean is_guard_local=false;
//是否开启礼物码模式
@JSONField(name = "is_gift_code")
private boolean is_gift_code = false;
//舰长私信语
private String report;
//舰长私信成功后发送弹幕
private String report_barrage;
//礼物码HashSet
private HashSet<String> codeStrings;
//是否开启感谢数量显示
@JSONField(name = "is_num")
private boolean is_num=true;
public ThankGiftSetConf(boolean is_open) {
super();
super.set_open(is_open);
}
//方法区
public boolean is_giftThank(){
if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){
return false;
}
if(is_live_open()) {
//没在 <SUF>
if(PublicDataConf.lIVE_STATUS !=1){
return false;
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}
public boolean is_giftThank(short live_status){
if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){
return false;
}
if(is_live_open()) {
//没在直播
if(live_status!=1){
return false;
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}else{
if(is_open()) {
return true;
}else{
return false;
}
}
}
public HashSet<ThankGiftRuleSet> getThankGiftRuleSets() {
if(thankGiftRuleSets!=null) {
return thankGiftRuleSets.stream().sorted(Comparator.comparing(ThankGiftRuleSet::getGift_name)).collect(Collectors.toCollection(LinkedHashSet::new));
}
return new HashSet<>();
}
public HashSet<String> getCodeStrings() {
if(codeStrings!=null) {
return codeStrings.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new));
}
return new HashSet<>();
}
}
| 1 | 6 | 1 |
42988_7 | package com.example.jianqiang.testlistview.imageloader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
/**
* Created by struggle_liping on 2017/7/16.
*/
public class OkHttpClientUtils {
public static OkHttpClient getClient(){
if(false){
return getAllPassClient();
}else {
return getNormalClient();
}
}
/**
* 不校验证书
* @return
*/
private static OkHttpClient getAllPassClient() {
X509TrustManager xtm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[]{};
return x509Certificates;
// return null;
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// sslSocketFactory和hostnameVerifier代码与httpsUtil中一模一样,只有这里不一样,但下面能行,这里就不行,见鬼了
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory())
.hostnameVerifier(DO_NOT_VERIFY)
.readTimeout(0, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置超时
.build();
return client;
}
private static OkHttpClient getNormalClient(){
OkHttpClient client = new OkHttpClient.Builder()
//.sslSocketFactory(sslContext.getSocketFactory())
//.hostnameVerifier(DO_NOT_VERIFY)
.readTimeout(0, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置超时
.build();
return client;
}
}
| BaoBaoJianqiang/CustomListView | TestListView/app/src/main/java/com/example/jianqiang/testlistview/imageloader/OkHttpClientUtils.java | 677 | //设置超时 | line_comment | zh-cn | package com.example.jianqiang.testlistview.imageloader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
/**
* Created by struggle_liping on 2017/7/16.
*/
public class OkHttpClientUtils {
public static OkHttpClient getClient(){
if(false){
return getAllPassClient();
}else {
return getNormalClient();
}
}
/**
* 不校验证书
* @return
*/
private static OkHttpClient getAllPassClient() {
X509TrustManager xtm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[]{};
return x509Certificates;
// return null;
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// sslSocketFactory和hostnameVerifier代码与httpsUtil中一模一样,只有这里不一样,但下面能行,这里就不行,见鬼了
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory())
.hostnameVerifier(DO_NOT_VERIFY)
.readTimeout(0, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置超时
.build();
return client;
}
private static OkHttpClient getNormalClient(){
OkHttpClient client = new OkHttpClient.Builder()
//.sslSocketFactory(sslContext.getSocketFactory())
//.hostnameVerifier(DO_NOT_VERIFY)
.readTimeout(0, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置 <SUF>
.build();
return client;
}
}
| 1 | 6 | 1 |
15927_3 | package com.baron.patterns.state.state;
/**
* 状态之木有钱
*
* @author Baron Zhang (baron[dot]zhanglei[at]gmail[dot]com)
* @version 1.0
* @since 1.0
*/
public class NoQuarterState implements State {
GumballMachine gumballMachine;
public NoQuarterState(GumballMachine gumballMachine) {
this.gumballMachine = gumballMachine;
}
@Override
public void insertQuarter() {
//这里加入投币代码
System.out.println("客官您投入了25分硬币");
gumballMachine.setState(gumballMachine.getHasQuarterState());
}
@Override
public void ejectQuarter() {
//这里加入退币代码
System.out.println("小子!你特么都没投钱,还要求退币?!!!");
}
@Override
public void turnCrank() {
//这里加入转动曲柄代码
System.out.println("没给钱拨你妹的曲柄开关啊");
}
@Override
public void dispense() {
//这里加入发糖果代码
System.out.println("哥哥,咱先给钱好不好");
}
}
| BaronZ88/DesignPatterns | src/com/baron/patterns/state/state/NoQuarterState.java | 317 | //这里加入转动曲柄代码 | line_comment | zh-cn | package com.baron.patterns.state.state;
/**
* 状态之木有钱
*
* @author Baron Zhang (baron[dot]zhanglei[at]gmail[dot]com)
* @version 1.0
* @since 1.0
*/
public class NoQuarterState implements State {
GumballMachine gumballMachine;
public NoQuarterState(GumballMachine gumballMachine) {
this.gumballMachine = gumballMachine;
}
@Override
public void insertQuarter() {
//这里加入投币代码
System.out.println("客官您投入了25分硬币");
gumballMachine.setState(gumballMachine.getHasQuarterState());
}
@Override
public void ejectQuarter() {
//这里加入退币代码
System.out.println("小子!你特么都没投钱,还要求退币?!!!");
}
@Override
public void turnCrank() {
//这里 <SUF>
System.out.println("没给钱拨你妹的曲柄开关啊");
}
@Override
public void dispense() {
//这里加入发糖果代码
System.out.println("哥哥,咱先给钱好不好");
}
}
| 1 | 12 | 1 |
13571_28 | package com.baronzhang.android.weather.data.http.entity.envicloud;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.List;
/**
* @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com)
* 2017/2/16
*/
public class EnvironmentCloudForecast {
/**
* citycode : 101020100
* rdesc : Success
* suggestion : {"uv":{"txt":"属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。","brf":"最弱"},"cw":{"txt":"不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。","brf":"不宜"},"drs":{"txt":"建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。","brf":"较冷"},"trav":{"txt":"温度适宜,又有较弱降水和微风作伴,会给您的旅行带来意想不到的景象,适宜旅游,可不要错过机会呦!","brf":"适宜"},"air":{"txt":"气象条件对空气污染物稀释、扩散和清除无明显影响,易感人群应适当减少室外活动时间。","brf":"中"},"comf":{"txt":"白天会有降雨,这种天气条件下,人们会感到有些凉意,但大部分人完全可以接受。","brf":"较舒适"},"sport":{"txt":"有降水,推荐您在室内进行各种健身休闲运动,若坚持户外运动,须注意保暖并携带雨具。","brf":"较不宜"},"flu":{"txt":"天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。","brf":"较易发"}}
* cityname : 上海
* rcode : 200
* forecast : [{"pop":"0","date":"2017-02-16","uv":"5","vis":"10","hum":"74","astro":{"ss":"17:42","mr":"22:42","ms":"09:41","sr":"06:34"},"pres":"1020","pcpn":"0.0","tmp":{"min":"10","max":"19"},"cond":{"cond_d":"小雨","cond_n":"阴"},"wind":{"sc":"微风","spd":"4","deg":"204","dir":"南风"}},{"pop":"70","date":"2017-02-17","uv":"6","vis":"10","hum":"77","astro":{"ss":"17:43","mr":"23:35","ms":"10:15","sr":"06:33"},"pres":"1025","pcpn":"0.3","tmp":{"min":"6","max":"15"},"cond":{"cond_d":"小雨","cond_n":"小雨"},"wind":{"sc":"3-4","spd":"10","deg":"28","dir":"东北风"}},{"pop":"33","date":"2017-02-18","uv":"6","vis":"10","hum":"72","astro":{"ss":"17:43","mr":"null","ms":"10:52","sr":"06:32"},"pres":"1029","pcpn":"0.0","tmp":{"min":"6","max":"10"},"cond":{"cond_d":"多云","cond_n":"晴"},"wind":{"sc":"微风","spd":"6","deg":"75","dir":"东南风"}},{"pop":"0","date":"2017-02-19","uv":"5","vis":"10","hum":"78","astro":{"ss":"17:44","mr":"00:27","ms":"11:31","sr":"06:31"},"pres":"1019","pcpn":"0.0","tmp":{"min":"10","max":"16"},"cond":{"cond_d":"多云","cond_n":"多云"},"wind":{"sc":"微风","spd":"1","deg":"174","dir":"东南风"}},{"pop":"0","date":"2017-02-20","uv":"N/A","vis":"10","hum":"81","astro":{"ss":"17:45","mr":"01:19","ms":"12:12","sr":"06:30"},"pres":"1013","pcpn":"0.0","tmp":{"min":"10","max":"19"},"cond":{"cond_d":"多云","cond_n":"小雨"},"wind":{"sc":"3-4","spd":"14","deg":"168","dir":"东北风"}},{"pop":"71","date":"2017-02-21","uv":"N/A","vis":"9","hum":"83","astro":{"ss":"17:46","mr":"02:10","ms":"12:57","sr":"06:29"},"pres":"1012","pcpn":"4.9","tmp":{"min":"7","max":"14"},"cond":{"cond_d":"小雨","cond_n":"小雨"},"wind":{"sc":"微风","spd":"0","deg":"94","dir":"东南风"}},{"pop":"100","date":"2017-02-22","uv":"N/A","vis":"2","hum":"91","astro":{"ss":"17:47","mr":"03:00","ms":"13:46","sr":"06:28"},"pres":"1016","pcpn":"9.7","tmp":{"min":"2","max":"11"},"cond":{"cond_d":"小雨","cond_n":"中雨"},"wind":{"sc":"4-5","spd":"23","deg":"340","dir":"西北风"}}]
*/
@JSONField(name = "rcode")
private int requestCode;//结果吗
@JSONField(name = "rdesc")
private String requestDesc;//结果描述
private SuggestionEntity suggestion;//生活指数
@JSONField(name = "citycode")
private String cityId;//城市ID
@JSONField(name = "cityname")
private String cityName;//城市名
private List<ForecastEntity> forecast;//天气预报
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public String getRequestDesc() {
return requestDesc;
}
public void setRequestDesc(String requestDesc) {
this.requestDesc = requestDesc;
}
public SuggestionEntity getSuggestion() {
return suggestion;
}
public void setSuggestion(SuggestionEntity suggestion) {
this.suggestion = suggestion;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public List<ForecastEntity> getForecast() {
return forecast;
}
public void setForecast(List<ForecastEntity> forecast) {
this.forecast = forecast;
}
public static class SuggestionEntity {
/**
* uv : {"txt":"属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。","brf":"最弱"}
* cw : {"txt":"不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。","brf":"不宜"}
* drs : {"txt":"建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。","brf":"较冷"}
* trav : {"txt":"温度适宜,又有较弱降水和微风作伴,会给您的旅行带来意想不到的景象,适宜旅游,可不要错过机会呦!","brf":"适宜"}
* air : {"txt":"气象条件对空气污染物稀释、扩散和清除无明显影响,易感人群应适当减少室外活动时间。","brf":"中"}
* comf : {"txt":"白天会有降雨,这种天气条件下,人们会感到有些凉意,但大部分人完全可以接受。","brf":"较舒适"}
* sport : {"txt":"有降水,推荐您在室内进行各种健身休闲运动,若坚持户外运动,须注意保暖并携带雨具。","brf":"较不宜"}
* flu : {"txt":"天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。","brf":"较易发"}
*/
private UvEntity uv;//紫外线
private CwEntity cw;//洗车指数
private DrsEntity drs;//穿衣指数
private TravEntity trav;//旅游指数
private AirEntity air;//空气质量指数
private ComfEntity comf;//s舒适度指数
private SportEntity sport;//运动指数
private FluEntity flu;//感冒指数
public UvEntity getUv() {
return uv;
}
public void setUv(UvEntity uv) {
this.uv = uv;
}
public CwEntity getCw() {
return cw;
}
public void setCw(CwEntity cw) {
this.cw = cw;
}
public DrsEntity getDrs() {
return drs;
}
public void setDrs(DrsEntity drs) {
this.drs = drs;
}
public TravEntity getTrav() {
return trav;
}
public void setTrav(TravEntity trav) {
this.trav = trav;
}
public AirEntity getAir() {
return air;
}
public void setAir(AirEntity air) {
this.air = air;
}
public ComfEntity getComf() {
return comf;
}
public void setComf(ComfEntity comf) {
this.comf = comf;
}
public SportEntity getSport() {
return sport;
}
public void setSport(SportEntity sport) {
this.sport = sport;
}
public FluEntity getFlu() {
return flu;
}
public void setFlu(FluEntity flu) {
this.flu = flu;
}
public static class UvEntity {
/**
* txt : 属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。
* brf : 最弱
*/
private String txt;//生活指数详情
private String brf;//生活指数简介
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class CwEntity {
/**
* txt : 不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。
* brf : 不宜
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class DrsEntity {
/**
* txt : 建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。
* brf : 较冷
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class TravEntity {
/**
* txt : 温度适宜,又有较弱降水和微风作伴,会给您的旅行带来意想不到的景象,适宜旅游,可不要错过机会呦!
* brf : 适宜
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class AirEntity {
/**
* txt : 气象条件对空气污染物稀释、扩散和清除无明显影响,易感人群应适当减少室外活动时间。
* brf : 中
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class ComfEntity {
/**
* txt : 白天会有降雨,这种天气条件下,人们会感到有些凉意,但大部分人完全可以接受。
* brf : 较舒适
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class SportEntity {
/**
* txt : 有降水,推荐您在室内进行各种健身休闲运动,若坚持户外运动,须注意保暖并携带雨具。
* brf : 较不宜
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class FluEntity {
/**
* txt : 天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。
* brf : 较易发
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
}
public static class ForecastEntity {
/**
* pop : 0
* date : 2017-02-16
* uv : 5
* vis : 10
* hum : 74
* astro : {"ss":"17:42","mr":"22:42","ms":"09:41","sr":"06:34"}
* pres : 1020
* pcpn : 0.0
* tmp : {"min":"10","max":"19"}
* cond : {"cond_d":"小雨","cond_n":"阴"}
* wind : {"sc":"微风","spd":"4","deg":"204","dir":"南风"}
*/
private String pop;//降水概率(%)
private String date;//预报日期
private String uv;//紫外线级别
private String vis;//能见度(km)
private String hum;//相对湿度(%)
private AstroEntity astro;//天文数据
private String pres;//气压(hPa)
private String pcpn;//降水量(mm)
private TmpEntity tmp;//气温
private CondEntity cond;//天气现象
private WindEntity wind;//风力风向数据
public String getPop() {
return pop;
}
public void setPop(String pop) {
this.pop = pop;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUv() {
return uv;
}
public void setUv(String uv) {
this.uv = uv;
}
public String getVis() {
return vis;
}
public void setVis(String vis) {
this.vis = vis;
}
public String getHum() {
return hum;
}
public void setHum(String hum) {
this.hum = hum;
}
public AstroEntity getAstro() {
return astro;
}
public void setAstro(AstroEntity astro) {
this.astro = astro;
}
public String getPres() {
return pres;
}
public void setPres(String pres) {
this.pres = pres;
}
public String getPcpn() {
return pcpn;
}
public void setPcpn(String pcpn) {
this.pcpn = pcpn;
}
public TmpEntity getTmp() {
return tmp;
}
public void setTmp(TmpEntity tmp) {
this.tmp = tmp;
}
public CondEntity getCond() {
return cond;
}
public void setCond(CondEntity cond) {
this.cond = cond;
}
public WindEntity getWind() {
return wind;
}
public void setWind(WindEntity wind) {
this.wind = wind;
}
public static class AstroEntity {
/**
* ss : 17:42
* mr : 22:42
* ms : 09:41
* sr : 06:34
*/
private String ss;//日落时间
private String mr;//月升
private String ms;//月落
private String sr;//日出时间
public String getSs() {
return ss;
}
public void setSs(String ss) {
this.ss = ss;
}
public String getMr() {
return mr;
}
public void setMr(String mr) {
this.mr = mr;
}
public String getMs() {
return ms;
}
public void setMs(String ms) {
this.ms = ms;
}
public String getSr() {
return sr;
}
public void setSr(String sr) {
this.sr = sr;
}
}
public static class TmpEntity {
/**
* min : 10
* max : 19
*/
private String min;//最低气温(℃)
private String max;//最高气温(℃)
public String getMin() {
return min;
}
public void setMin(String min) {
this.min = min;
}
public String getMax() {
return max;
}
public void setMax(String max) {
this.max = max;
}
}
public static class CondEntity {
/**
* cond_d : 小雨
* cond_n : 阴
*/
private String cond_d;//白天天气现象
private String cond_n;//夜间天气现象
public String getCond_d() {
return cond_d;
}
public void setCond_d(String cond_d) {
this.cond_d = cond_d;
}
public String getCond_n() {
return cond_n;
}
public void setCond_n(String cond_n) {
this.cond_n = cond_n;
}
}
public static class WindEntity {
/**
* sc : 微风
* spd : 4
* deg : 204
* dir : 南风
*/
private String sc;//风力
private String spd;//风速(m/s)
private String deg;//风向(360°)
private String dir;//风向
public String getSc() {
return sc;
}
public void setSc(String sc) {
this.sc = sc;
}
public String getSpd() {
return spd;
}
public void setSpd(String spd) {
this.spd = spd;
}
public String getDeg() {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
}
}
}
| BaronZ88/MinimalistWeather | app/src/main/java/com/baronzhang/android/weather/data/http/entity/envicloud/EnvironmentCloudForecast.java | 5,286 | //降水概率(%) | line_comment | zh-cn | package com.baronzhang.android.weather.data.http.entity.envicloud;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.List;
/**
* @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com)
* 2017/2/16
*/
public class EnvironmentCloudForecast {
/**
* citycode : 101020100
* rdesc : Success
* suggestion : {"uv":{"txt":"属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。","brf":"最弱"},"cw":{"txt":"不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。","brf":"不宜"},"drs":{"txt":"建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。","brf":"较冷"},"trav":{"txt":"温度适宜,又有较弱降水和微风作伴,会给您的旅行带来意想不到的景象,适宜旅游,可不要错过机会呦!","brf":"适宜"},"air":{"txt":"气象条件对空气污染物稀释、扩散和清除无明显影响,易感人群应适当减少室外活动时间。","brf":"中"},"comf":{"txt":"白天会有降雨,这种天气条件下,人们会感到有些凉意,但大部分人完全可以接受。","brf":"较舒适"},"sport":{"txt":"有降水,推荐您在室内进行各种健身休闲运动,若坚持户外运动,须注意保暖并携带雨具。","brf":"较不宜"},"flu":{"txt":"天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。","brf":"较易发"}}
* cityname : 上海
* rcode : 200
* forecast : [{"pop":"0","date":"2017-02-16","uv":"5","vis":"10","hum":"74","astro":{"ss":"17:42","mr":"22:42","ms":"09:41","sr":"06:34"},"pres":"1020","pcpn":"0.0","tmp":{"min":"10","max":"19"},"cond":{"cond_d":"小雨","cond_n":"阴"},"wind":{"sc":"微风","spd":"4","deg":"204","dir":"南风"}},{"pop":"70","date":"2017-02-17","uv":"6","vis":"10","hum":"77","astro":{"ss":"17:43","mr":"23:35","ms":"10:15","sr":"06:33"},"pres":"1025","pcpn":"0.3","tmp":{"min":"6","max":"15"},"cond":{"cond_d":"小雨","cond_n":"小雨"},"wind":{"sc":"3-4","spd":"10","deg":"28","dir":"东北风"}},{"pop":"33","date":"2017-02-18","uv":"6","vis":"10","hum":"72","astro":{"ss":"17:43","mr":"null","ms":"10:52","sr":"06:32"},"pres":"1029","pcpn":"0.0","tmp":{"min":"6","max":"10"},"cond":{"cond_d":"多云","cond_n":"晴"},"wind":{"sc":"微风","spd":"6","deg":"75","dir":"东南风"}},{"pop":"0","date":"2017-02-19","uv":"5","vis":"10","hum":"78","astro":{"ss":"17:44","mr":"00:27","ms":"11:31","sr":"06:31"},"pres":"1019","pcpn":"0.0","tmp":{"min":"10","max":"16"},"cond":{"cond_d":"多云","cond_n":"多云"},"wind":{"sc":"微风","spd":"1","deg":"174","dir":"东南风"}},{"pop":"0","date":"2017-02-20","uv":"N/A","vis":"10","hum":"81","astro":{"ss":"17:45","mr":"01:19","ms":"12:12","sr":"06:30"},"pres":"1013","pcpn":"0.0","tmp":{"min":"10","max":"19"},"cond":{"cond_d":"多云","cond_n":"小雨"},"wind":{"sc":"3-4","spd":"14","deg":"168","dir":"东北风"}},{"pop":"71","date":"2017-02-21","uv":"N/A","vis":"9","hum":"83","astro":{"ss":"17:46","mr":"02:10","ms":"12:57","sr":"06:29"},"pres":"1012","pcpn":"4.9","tmp":{"min":"7","max":"14"},"cond":{"cond_d":"小雨","cond_n":"小雨"},"wind":{"sc":"微风","spd":"0","deg":"94","dir":"东南风"}},{"pop":"100","date":"2017-02-22","uv":"N/A","vis":"2","hum":"91","astro":{"ss":"17:47","mr":"03:00","ms":"13:46","sr":"06:28"},"pres":"1016","pcpn":"9.7","tmp":{"min":"2","max":"11"},"cond":{"cond_d":"小雨","cond_n":"中雨"},"wind":{"sc":"4-5","spd":"23","deg":"340","dir":"西北风"}}]
*/
@JSONField(name = "rcode")
private int requestCode;//结果吗
@JSONField(name = "rdesc")
private String requestDesc;//结果描述
private SuggestionEntity suggestion;//生活指数
@JSONField(name = "citycode")
private String cityId;//城市ID
@JSONField(name = "cityname")
private String cityName;//城市名
private List<ForecastEntity> forecast;//天气预报
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public String getRequestDesc() {
return requestDesc;
}
public void setRequestDesc(String requestDesc) {
this.requestDesc = requestDesc;
}
public SuggestionEntity getSuggestion() {
return suggestion;
}
public void setSuggestion(SuggestionEntity suggestion) {
this.suggestion = suggestion;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public List<ForecastEntity> getForecast() {
return forecast;
}
public void setForecast(List<ForecastEntity> forecast) {
this.forecast = forecast;
}
public static class SuggestionEntity {
/**
* uv : {"txt":"属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。","brf":"最弱"}
* cw : {"txt":"不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。","brf":"不宜"}
* drs : {"txt":"建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。","brf":"较冷"}
* trav : {"txt":"温度适宜,又有较弱降水和微风作伴,会给您的旅行带来意想不到的景象,适宜旅游,可不要错过机会呦!","brf":"适宜"}
* air : {"txt":"气象条件对空气污染物稀释、扩散和清除无明显影响,易感人群应适当减少室外活动时间。","brf":"中"}
* comf : {"txt":"白天会有降雨,这种天气条件下,人们会感到有些凉意,但大部分人完全可以接受。","brf":"较舒适"}
* sport : {"txt":"有降水,推荐您在室内进行各种健身休闲运动,若坚持户外运动,须注意保暖并携带雨具。","brf":"较不宜"}
* flu : {"txt":"天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。","brf":"较易发"}
*/
private UvEntity uv;//紫外线
private CwEntity cw;//洗车指数
private DrsEntity drs;//穿衣指数
private TravEntity trav;//旅游指数
private AirEntity air;//空气质量指数
private ComfEntity comf;//s舒适度指数
private SportEntity sport;//运动指数
private FluEntity flu;//感冒指数
public UvEntity getUv() {
return uv;
}
public void setUv(UvEntity uv) {
this.uv = uv;
}
public CwEntity getCw() {
return cw;
}
public void setCw(CwEntity cw) {
this.cw = cw;
}
public DrsEntity getDrs() {
return drs;
}
public void setDrs(DrsEntity drs) {
this.drs = drs;
}
public TravEntity getTrav() {
return trav;
}
public void setTrav(TravEntity trav) {
this.trav = trav;
}
public AirEntity getAir() {
return air;
}
public void setAir(AirEntity air) {
this.air = air;
}
public ComfEntity getComf() {
return comf;
}
public void setComf(ComfEntity comf) {
this.comf = comf;
}
public SportEntity getSport() {
return sport;
}
public void setSport(SportEntity sport) {
this.sport = sport;
}
public FluEntity getFlu() {
return flu;
}
public void setFlu(FluEntity flu) {
this.flu = flu;
}
public static class UvEntity {
/**
* txt : 属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。
* brf : 最弱
*/
private String txt;//生活指数详情
private String brf;//生活指数简介
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class CwEntity {
/**
* txt : 不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。
* brf : 不宜
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class DrsEntity {
/**
* txt : 建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。
* brf : 较冷
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class TravEntity {
/**
* txt : 温度适宜,又有较弱降水和微风作伴,会给您的旅行带来意想不到的景象,适宜旅游,可不要错过机会呦!
* brf : 适宜
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class AirEntity {
/**
* txt : 气象条件对空气污染物稀释、扩散和清除无明显影响,易感人群应适当减少室外活动时间。
* brf : 中
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class ComfEntity {
/**
* txt : 白天会有降雨,这种天气条件下,人们会感到有些凉意,但大部分人完全可以接受。
* brf : 较舒适
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class SportEntity {
/**
* txt : 有降水,推荐您在室内进行各种健身休闲运动,若坚持户外运动,须注意保暖并携带雨具。
* brf : 较不宜
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
public static class FluEntity {
/**
* txt : 天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。
* brf : 较易发
*/
private String txt;
private String brf;
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
}
}
public static class ForecastEntity {
/**
* pop : 0
* date : 2017-02-16
* uv : 5
* vis : 10
* hum : 74
* astro : {"ss":"17:42","mr":"22:42","ms":"09:41","sr":"06:34"}
* pres : 1020
* pcpn : 0.0
* tmp : {"min":"10","max":"19"}
* cond : {"cond_d":"小雨","cond_n":"阴"}
* wind : {"sc":"微风","spd":"4","deg":"204","dir":"南风"}
*/
private String pop;//降水 <SUF>
private String date;//预报日期
private String uv;//紫外线级别
private String vis;//能见度(km)
private String hum;//相对湿度(%)
private AstroEntity astro;//天文数据
private String pres;//气压(hPa)
private String pcpn;//降水量(mm)
private TmpEntity tmp;//气温
private CondEntity cond;//天气现象
private WindEntity wind;//风力风向数据
public String getPop() {
return pop;
}
public void setPop(String pop) {
this.pop = pop;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUv() {
return uv;
}
public void setUv(String uv) {
this.uv = uv;
}
public String getVis() {
return vis;
}
public void setVis(String vis) {
this.vis = vis;
}
public String getHum() {
return hum;
}
public void setHum(String hum) {
this.hum = hum;
}
public AstroEntity getAstro() {
return astro;
}
public void setAstro(AstroEntity astro) {
this.astro = astro;
}
public String getPres() {
return pres;
}
public void setPres(String pres) {
this.pres = pres;
}
public String getPcpn() {
return pcpn;
}
public void setPcpn(String pcpn) {
this.pcpn = pcpn;
}
public TmpEntity getTmp() {
return tmp;
}
public void setTmp(TmpEntity tmp) {
this.tmp = tmp;
}
public CondEntity getCond() {
return cond;
}
public void setCond(CondEntity cond) {
this.cond = cond;
}
public WindEntity getWind() {
return wind;
}
public void setWind(WindEntity wind) {
this.wind = wind;
}
public static class AstroEntity {
/**
* ss : 17:42
* mr : 22:42
* ms : 09:41
* sr : 06:34
*/
private String ss;//日落时间
private String mr;//月升
private String ms;//月落
private String sr;//日出时间
public String getSs() {
return ss;
}
public void setSs(String ss) {
this.ss = ss;
}
public String getMr() {
return mr;
}
public void setMr(String mr) {
this.mr = mr;
}
public String getMs() {
return ms;
}
public void setMs(String ms) {
this.ms = ms;
}
public String getSr() {
return sr;
}
public void setSr(String sr) {
this.sr = sr;
}
}
public static class TmpEntity {
/**
* min : 10
* max : 19
*/
private String min;//最低气温(℃)
private String max;//最高气温(℃)
public String getMin() {
return min;
}
public void setMin(String min) {
this.min = min;
}
public String getMax() {
return max;
}
public void setMax(String max) {
this.max = max;
}
}
public static class CondEntity {
/**
* cond_d : 小雨
* cond_n : 阴
*/
private String cond_d;//白天天气现象
private String cond_n;//夜间天气现象
public String getCond_d() {
return cond_d;
}
public void setCond_d(String cond_d) {
this.cond_d = cond_d;
}
public String getCond_n() {
return cond_n;
}
public void setCond_n(String cond_n) {
this.cond_n = cond_n;
}
}
public static class WindEntity {
/**
* sc : 微风
* spd : 4
* deg : 204
* dir : 南风
*/
private String sc;//风力
private String spd;//风速(m/s)
private String deg;//风向(360°)
private String dir;//风向
public String getSc() {
return sc;
}
public void setSc(String sc) {
this.sc = sc;
}
public String getSpd() {
return spd;
}
public void setSpd(String spd) {
this.spd = spd;
}
public String getDeg() {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
}
}
}
| 1 | 9 | 1 |
9767_10 | package wow.service;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import wow.entity.BackJSON;
import wow.entity.Doctor;
import wow.entity.Patient;
import wow.entity.UserInfo;
import wow.mapper.DoctorMapper;
import wow.mapper.PatientMapper;
import wow.mapper.UserMapper;
import wow.util.Value;
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper um;
@Autowired
private PatientMapper pm;
@Autowired
private DoctorMapper dm;
@Override
@Transactional
public BackJSON userRegister(UserInfo userInfo) {
BackJSON json = new BackJSON(200);
Map<String, String> data = new HashMap<>();
int userType = userInfo.getUserType();
int userID = um.getUserCount();
userInfo.setUserID(userID);
int insertResult = 0;
// 密码经过 MD5 hash
userInfo.setPassword(Value.MD5Hash(userInfo.getPassword()));
if(1 == userType) {
// 患者
if (pm.ifPhone(userInfo.getUserPhone()) > 0) {
// 手机号注册过
data.put("result", "1");
} else {
insertResult = pm.newPatient(userInfo);
if (insertResult != 1) {
data.put("result", "2");
}
}
} else if(2 == userType) {
// 医生
if(dm.ifPhone(userInfo.getUserPhone()) > 0) {
// 手机号注册过
data.put("result", "1");
} else {
insertResult = dm.newDoctor(userInfo);
if(insertResult != 1 ) {
data.put("result", "2");
}
}
} else {
json.setData(201);
return json;
}
if(1 == insertResult) {
data.put("result", "0");
um.updateUserCount();
// 注册成功,生成密钥对
Map<String, String> keyMap = Value.generateRSAKeyPair();
String publicKey = keyMap.get("publicKey");
String privateKey = keyMap.get("privateKey");
if(um.newUserPublicKey(userID, publicKey)==1) {
data.put("privateKey", privateKey);
} else {
data.put("result", "2");
}
}
json.setData(data);
return json;
}
@Override
@Transactional(readOnly = true)
public BackJSON getHospitalID(String hospitalName) {
BackJSON json = new BackJSON(200);
Map<String, Object> data = new HashMap<>();
Integer hospitalID = um.getHospitalID(hospitalName);
if(hospitalID!=null) {
data.put("hospitalID", hospitalID);
} else {
// 不存在,返回 0
data.put("hospitalID", 0);
}
json.setData(data);
return json;
}
@Override
@Transactional(readOnly = true)
public BackJSON userLogin(UserInfo userInfo) {
BackJSON json = new BackJSON(200);
Map<String, Object> data = new HashMap<>();
int userType = userInfo.getUserType();
String phone = userInfo.getUserPhone();
String password = userInfo.getPassword();
if(1==userType) {
// 患者
Patient patient = pm.patientLogin(phone);
if(null==patient) {
// 手机号不存在
data.put("result", 2);
} else {
if(patient.getPatientState()!=0) {
// 患者处于非法状态
data.put("result", 3);
} else {
if(!Value.MD5Verify(password, patient.getPatientPassword())) {
// 用户名或密码错误
data.put("result", 1);
} else {
data.put("result", 0);
data.put("userID", patient.getPatientID());
}
}
}
} else if(2==userType) {
// 医生
Doctor doctor = dm.doctorLogin(phone);
if(null==doctor) {
// 手机号不存在
data.put("result", 2);
} else {
if(doctor.getDoctorState()!=0) {
// 患者处于非法状态
data.put("result", 3);
} else {
if(!Value.MD5Verify(password, doctor.getDoctorPassword())) {
// 用户名或密码错误
data.put("result", 1);
} else {
data.put("result", 0);
data.put("userID", doctor.getDoctorID());
}
}
}
} else {
data.put("result", 4);
}
json.setData(data);
return json;
}
}
| BattleCall3/graduatework | code/medical/src/main/java/wow/service/UserServiceImpl.java | 1,331 | // 用户名或密码错误
| line_comment | zh-cn | package wow.service;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import wow.entity.BackJSON;
import wow.entity.Doctor;
import wow.entity.Patient;
import wow.entity.UserInfo;
import wow.mapper.DoctorMapper;
import wow.mapper.PatientMapper;
import wow.mapper.UserMapper;
import wow.util.Value;
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper um;
@Autowired
private PatientMapper pm;
@Autowired
private DoctorMapper dm;
@Override
@Transactional
public BackJSON userRegister(UserInfo userInfo) {
BackJSON json = new BackJSON(200);
Map<String, String> data = new HashMap<>();
int userType = userInfo.getUserType();
int userID = um.getUserCount();
userInfo.setUserID(userID);
int insertResult = 0;
// 密码经过 MD5 hash
userInfo.setPassword(Value.MD5Hash(userInfo.getPassword()));
if(1 == userType) {
// 患者
if (pm.ifPhone(userInfo.getUserPhone()) > 0) {
// 手机号注册过
data.put("result", "1");
} else {
insertResult = pm.newPatient(userInfo);
if (insertResult != 1) {
data.put("result", "2");
}
}
} else if(2 == userType) {
// 医生
if(dm.ifPhone(userInfo.getUserPhone()) > 0) {
// 手机号注册过
data.put("result", "1");
} else {
insertResult = dm.newDoctor(userInfo);
if(insertResult != 1 ) {
data.put("result", "2");
}
}
} else {
json.setData(201);
return json;
}
if(1 == insertResult) {
data.put("result", "0");
um.updateUserCount();
// 注册成功,生成密钥对
Map<String, String> keyMap = Value.generateRSAKeyPair();
String publicKey = keyMap.get("publicKey");
String privateKey = keyMap.get("privateKey");
if(um.newUserPublicKey(userID, publicKey)==1) {
data.put("privateKey", privateKey);
} else {
data.put("result", "2");
}
}
json.setData(data);
return json;
}
@Override
@Transactional(readOnly = true)
public BackJSON getHospitalID(String hospitalName) {
BackJSON json = new BackJSON(200);
Map<String, Object> data = new HashMap<>();
Integer hospitalID = um.getHospitalID(hospitalName);
if(hospitalID!=null) {
data.put("hospitalID", hospitalID);
} else {
// 不存在,返回 0
data.put("hospitalID", 0);
}
json.setData(data);
return json;
}
@Override
@Transactional(readOnly = true)
public BackJSON userLogin(UserInfo userInfo) {
BackJSON json = new BackJSON(200);
Map<String, Object> data = new HashMap<>();
int userType = userInfo.getUserType();
String phone = userInfo.getUserPhone();
String password = userInfo.getPassword();
if(1==userType) {
// 患者
Patient patient = pm.patientLogin(phone);
if(null==patient) {
// 手机号不存在
data.put("result", 2);
} else {
if(patient.getPatientState()!=0) {
// 患者处于非法状态
data.put("result", 3);
} else {
if(!Value.MD5Verify(password, patient.getPatientPassword())) {
// 用户 <SUF>
data.put("result", 1);
} else {
data.put("result", 0);
data.put("userID", patient.getPatientID());
}
}
}
} else if(2==userType) {
// 医生
Doctor doctor = dm.doctorLogin(phone);
if(null==doctor) {
// 手机号不存在
data.put("result", 2);
} else {
if(doctor.getDoctorState()!=0) {
// 患者处于非法状态
data.put("result", 3);
} else {
if(!Value.MD5Verify(password, doctor.getDoctorPassword())) {
// 用户名或密码错误
data.put("result", 1);
} else {
data.put("result", 0);
data.put("userID", doctor.getDoctorID());
}
}
}
} else {
data.put("result", 4);
}
json.setData(data);
return json;
}
}
| 1 | 12 | 1 |
63900_2 | package org.laopopo.monitor;
import static org.laopopo.common.protocal.LaopopoProtocol.MANAGER_SERVICE;
import static org.laopopo.common.protocal.LaopopoProtocol.MERTRICS_SERVICE;
import static org.laopopo.common.serialization.SerializerHolder.serializerImpl;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.ConcurrentSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.laopopo.common.metrics.ServiceMetrics;
import org.laopopo.common.metrics.ServiceMetrics.ProviderInfo;
import org.laopopo.common.protocal.LaopopoProtocol;
import org.laopopo.common.rpc.ManagerServiceRequestType;
import org.laopopo.common.rpc.MetricsReporter;
import org.laopopo.common.rpc.RegisterMeta;
import org.laopopo.common.rpc.RegisterMeta.Address;
import org.laopopo.common.transport.body.ManagerServiceCustomBody;
import org.laopopo.common.transport.body.MetricsCustomBody;
import org.laopopo.common.transport.body.ProviderMetricsCustomBody;
import org.laopopo.remoting.ConnectionUtils;
import org.laopopo.remoting.model.NettyRequestProcessor;
import org.laopopo.remoting.model.RemotingTransporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author BazingaLyn
* @description monitor的处理器
* @time 2016年8月17日
* @modifytime
*/
public class DefaultMonitorProcessor implements NettyRequestProcessor {
private static final Logger logger = LoggerFactory.getLogger(DefaultMonitorProcessor.class);
private DefaultMonitor defaultMonitor;
public DefaultMonitorProcessor(DefaultMonitor defaultMonitor) {
this.defaultMonitor = defaultMonitor;
}
@Override
public RemotingTransporter processRequest(ChannelHandlerContext ctx, RemotingTransporter request) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("receive request, {} {} {}",//
request.getCode(), //
ConnectionUtils.parseChannelRemoteAddr(ctx.channel()), //
request);
}
switch (request.getCode()) {
case MERTRICS_SERVICE: //因为服务提供者端是定时发送统计信息的,如果没有收到或者消费失败了,则丢弃,不做强制消费的ack判断要求provider重发
return handlerMetricsService(request,ctx.channel());
case MANAGER_SERVICE:
return handlerManagerService(request,ctx.channel());
}
return null;
}
private RemotingTransporter handlerManagerService(RemotingTransporter request, Channel channel) {
MetricsCustomBody metricsCustomBody = new MetricsCustomBody();
RemotingTransporter remotingTransporter = RemotingTransporter.createResponseTransporter(LaopopoProtocol.MERTRICS_SERVICE, metricsCustomBody, request.getOpaque());
ManagerServiceCustomBody body = serializerImpl().readObject(request.bytes(), ManagerServiceCustomBody.class);
if(body.getManagerServiceRequestType() == ManagerServiceRequestType.METRICS){
String serviceName = body.getSerivceName();
ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName);
ConcurrentMap<Address, MetricsReporter> historyMaps = defaultMonitor.getHistoryGlobalMetricsReporter().get(serviceName);
//返回给管理页面的对象
ServiceMetrics metrics = new ServiceMetrics();
metrics.setServiceName(serviceName);
//从当前的统计信息中,构建返回体
buildMetrics(maps,metrics);
//从持久化信息中返回
buildMetrics(historyMaps,metrics);
List<ServiceMetrics> serviceMetricses = new ArrayList<ServiceMetrics>();
serviceMetricses.add(metrics);
metricsCustomBody.setServiceMetricses(serviceMetricses);
}
return remotingTransporter;
}
private void buildMetrics(ConcurrentMap<Address, MetricsReporter> maps, ServiceMetrics metrics) {
if (null != maps) {
Long totalCallCount = 0l;
Long totalFailCount = 0l;
Long totalTime = 0l;
Long totalRequestSize = 0l;
for (Address address : maps.keySet()) {
MetricsReporter metricsReporter = maps.get(address);
Long callCount = metricsReporter.getCallCount();
Long failCount = metricsReporter.getFailCount();
Long requestSize = metricsReporter.getRequestSize();
Long handlerTime = metricsReporter.getTotalReuqestTime();
totalCallCount += callCount;
totalFailCount += failCount;
totalRequestSize += requestSize;
totalTime += handlerTime;
ConcurrentMap<Address, ProviderInfo> providerConcurrentMap = metrics.getProviderMaps();
ProviderInfo info = providerConcurrentMap.get(address);
if (info == null) {
info = new ProviderInfo();
info.setHost(address.getHost());
info.setPort(address.getPort());
providerConcurrentMap.put(address, info);
}
Long eachHandlerAvgTime = 0l;
if ((info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount()) != 0) {
eachHandlerAvgTime = ((info.getCallCount() - info.getFailCount()) * info.getHandlerAvgTime() + metricsReporter.getTotalReuqestTime())
/ (info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount());
}
info.setHandlerAvgTime(eachHandlerAvgTime);
info.setCallCount(info.getCallCount() + callCount);
info.setFailCount(info.getFailCount() + failCount);
info.setRequestSize(info.getRequestSize() + requestSize);
}
metrics.setTotalCallCount(metrics.getTotalCallCount() + totalCallCount);
metrics.setTotalFailCount(metrics.getTotalFailCount() + totalFailCount);
Long existTotalTime = (metrics.getTotalCallCount() - metrics.getTotalFailCount()) * metrics.getHandlerAvgTime();
if (metrics.getTotalCallCount() - metrics.getTotalFailCount() != 0) {
metrics.setHandlerAvgTime((existTotalTime + totalTime) / (metrics.getTotalCallCount() - metrics.getTotalFailCount()));
} else {
metrics.setHandlerAvgTime(0L);
}
metrics.setRequestSize(metrics.getRequestSize() + totalRequestSize);
}
}
/**
* 处理服务提供者发送过来的统计信息
* 这边需要注意的是,因为服务提供端不是按照时间段去统计的,而是从服务启动的时候就开始统计,也就说服务提供端发送过来的信息是全量信息,不是增量信息
* 所以我们这边要做的是将provider发送过来最新的信息替换monitor本地的信息,而不是将本地的信息与provider发送的信息做累加操作
*
* @param request
* @param channel
* @return
*/
private RemotingTransporter handlerMetricsService(RemotingTransporter request, Channel channel) {
//反序列化内容
ProviderMetricsCustomBody body = serializerImpl().readObject(request.bytes(),ProviderMetricsCustomBody.class);
if(body.getMetricsReporter() != null && !body.getMetricsReporter().isEmpty()){
for(MetricsReporter metricsReporter : body.getMetricsReporter()){
String host = ConnectionUtils.parseChannelRemoteAddress(channel).getHost();
Address address = new Address(host, metricsReporter.getPort());
metricsReporter.setHost(host);
ConcurrentSet<Address> addresses = defaultMonitor.getGlobalProviderReporter().get(channel);
if(addresses == null){
addresses = new ConcurrentSet<Address>();
defaultMonitor.getGlobalProviderReporter().put(channel, addresses);
}
addresses.add(address);
String serviceName = metricsReporter.getServiceName();
ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName);
//第一次发送统计信息的时候,map为null,需要赋值
if(maps == null){
maps = new ConcurrentHashMap<RegisterMeta.Address, MetricsReporter>();
defaultMonitor.getGlobalMetricsReporter().put(serviceName, maps);
}
maps.put(address, metricsReporter);
}
}
return null;
}
}
| BazingaLyn/laopopo-rpc | laopopo-monitor/src/main/java/org/laopopo/monitor/DefaultMonitorProcessor.java | 2,067 | //返回给管理页面的对象 | line_comment | zh-cn | package org.laopopo.monitor;
import static org.laopopo.common.protocal.LaopopoProtocol.MANAGER_SERVICE;
import static org.laopopo.common.protocal.LaopopoProtocol.MERTRICS_SERVICE;
import static org.laopopo.common.serialization.SerializerHolder.serializerImpl;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.ConcurrentSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.laopopo.common.metrics.ServiceMetrics;
import org.laopopo.common.metrics.ServiceMetrics.ProviderInfo;
import org.laopopo.common.protocal.LaopopoProtocol;
import org.laopopo.common.rpc.ManagerServiceRequestType;
import org.laopopo.common.rpc.MetricsReporter;
import org.laopopo.common.rpc.RegisterMeta;
import org.laopopo.common.rpc.RegisterMeta.Address;
import org.laopopo.common.transport.body.ManagerServiceCustomBody;
import org.laopopo.common.transport.body.MetricsCustomBody;
import org.laopopo.common.transport.body.ProviderMetricsCustomBody;
import org.laopopo.remoting.ConnectionUtils;
import org.laopopo.remoting.model.NettyRequestProcessor;
import org.laopopo.remoting.model.RemotingTransporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author BazingaLyn
* @description monitor的处理器
* @time 2016年8月17日
* @modifytime
*/
public class DefaultMonitorProcessor implements NettyRequestProcessor {
private static final Logger logger = LoggerFactory.getLogger(DefaultMonitorProcessor.class);
private DefaultMonitor defaultMonitor;
public DefaultMonitorProcessor(DefaultMonitor defaultMonitor) {
this.defaultMonitor = defaultMonitor;
}
@Override
public RemotingTransporter processRequest(ChannelHandlerContext ctx, RemotingTransporter request) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("receive request, {} {} {}",//
request.getCode(), //
ConnectionUtils.parseChannelRemoteAddr(ctx.channel()), //
request);
}
switch (request.getCode()) {
case MERTRICS_SERVICE: //因为服务提供者端是定时发送统计信息的,如果没有收到或者消费失败了,则丢弃,不做强制消费的ack判断要求provider重发
return handlerMetricsService(request,ctx.channel());
case MANAGER_SERVICE:
return handlerManagerService(request,ctx.channel());
}
return null;
}
private RemotingTransporter handlerManagerService(RemotingTransporter request, Channel channel) {
MetricsCustomBody metricsCustomBody = new MetricsCustomBody();
RemotingTransporter remotingTransporter = RemotingTransporter.createResponseTransporter(LaopopoProtocol.MERTRICS_SERVICE, metricsCustomBody, request.getOpaque());
ManagerServiceCustomBody body = serializerImpl().readObject(request.bytes(), ManagerServiceCustomBody.class);
if(body.getManagerServiceRequestType() == ManagerServiceRequestType.METRICS){
String serviceName = body.getSerivceName();
ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName);
ConcurrentMap<Address, MetricsReporter> historyMaps = defaultMonitor.getHistoryGlobalMetricsReporter().get(serviceName);
//返回 <SUF>
ServiceMetrics metrics = new ServiceMetrics();
metrics.setServiceName(serviceName);
//从当前的统计信息中,构建返回体
buildMetrics(maps,metrics);
//从持久化信息中返回
buildMetrics(historyMaps,metrics);
List<ServiceMetrics> serviceMetricses = new ArrayList<ServiceMetrics>();
serviceMetricses.add(metrics);
metricsCustomBody.setServiceMetricses(serviceMetricses);
}
return remotingTransporter;
}
private void buildMetrics(ConcurrentMap<Address, MetricsReporter> maps, ServiceMetrics metrics) {
if (null != maps) {
Long totalCallCount = 0l;
Long totalFailCount = 0l;
Long totalTime = 0l;
Long totalRequestSize = 0l;
for (Address address : maps.keySet()) {
MetricsReporter metricsReporter = maps.get(address);
Long callCount = metricsReporter.getCallCount();
Long failCount = metricsReporter.getFailCount();
Long requestSize = metricsReporter.getRequestSize();
Long handlerTime = metricsReporter.getTotalReuqestTime();
totalCallCount += callCount;
totalFailCount += failCount;
totalRequestSize += requestSize;
totalTime += handlerTime;
ConcurrentMap<Address, ProviderInfo> providerConcurrentMap = metrics.getProviderMaps();
ProviderInfo info = providerConcurrentMap.get(address);
if (info == null) {
info = new ProviderInfo();
info.setHost(address.getHost());
info.setPort(address.getPort());
providerConcurrentMap.put(address, info);
}
Long eachHandlerAvgTime = 0l;
if ((info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount()) != 0) {
eachHandlerAvgTime = ((info.getCallCount() - info.getFailCount()) * info.getHandlerAvgTime() + metricsReporter.getTotalReuqestTime())
/ (info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount());
}
info.setHandlerAvgTime(eachHandlerAvgTime);
info.setCallCount(info.getCallCount() + callCount);
info.setFailCount(info.getFailCount() + failCount);
info.setRequestSize(info.getRequestSize() + requestSize);
}
metrics.setTotalCallCount(metrics.getTotalCallCount() + totalCallCount);
metrics.setTotalFailCount(metrics.getTotalFailCount() + totalFailCount);
Long existTotalTime = (metrics.getTotalCallCount() - metrics.getTotalFailCount()) * metrics.getHandlerAvgTime();
if (metrics.getTotalCallCount() - metrics.getTotalFailCount() != 0) {
metrics.setHandlerAvgTime((existTotalTime + totalTime) / (metrics.getTotalCallCount() - metrics.getTotalFailCount()));
} else {
metrics.setHandlerAvgTime(0L);
}
metrics.setRequestSize(metrics.getRequestSize() + totalRequestSize);
}
}
/**
* 处理服务提供者发送过来的统计信息
* 这边需要注意的是,因为服务提供端不是按照时间段去统计的,而是从服务启动的时候就开始统计,也就说服务提供端发送过来的信息是全量信息,不是增量信息
* 所以我们这边要做的是将provider发送过来最新的信息替换monitor本地的信息,而不是将本地的信息与provider发送的信息做累加操作
*
* @param request
* @param channel
* @return
*/
private RemotingTransporter handlerMetricsService(RemotingTransporter request, Channel channel) {
//反序列化内容
ProviderMetricsCustomBody body = serializerImpl().readObject(request.bytes(),ProviderMetricsCustomBody.class);
if(body.getMetricsReporter() != null && !body.getMetricsReporter().isEmpty()){
for(MetricsReporter metricsReporter : body.getMetricsReporter()){
String host = ConnectionUtils.parseChannelRemoteAddress(channel).getHost();
Address address = new Address(host, metricsReporter.getPort());
metricsReporter.setHost(host);
ConcurrentSet<Address> addresses = defaultMonitor.getGlobalProviderReporter().get(channel);
if(addresses == null){
addresses = new ConcurrentSet<Address>();
defaultMonitor.getGlobalProviderReporter().put(channel, addresses);
}
addresses.add(address);
String serviceName = metricsReporter.getServiceName();
ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName);
//第一次发送统计信息的时候,map为null,需要赋值
if(maps == null){
maps = new ConcurrentHashMap<RegisterMeta.Address, MetricsReporter>();
defaultMonitor.getGlobalMetricsReporter().put(serviceName, maps);
}
maps.put(address, metricsReporter);
}
}
return null;
}
}
| 1 | 12 | 1 |
53371_1 | package com.DI.dao.Impl;
import com.DI.dao.UserDao;
//创建一个业务逻辑接口
public class UserDaoImpl implements UserDao {
public boolean login(String name, String password) {
//如果名字是比尔和密码是123456就返回true
if(name.equals("比尔")&&password.equals("12345")){
return true;
}
return false;
}
}
| BeAlrightc/java_pro_note | spring家族/spring/project/ioc/DlLearning/src/main/java/com/DI/dao/Impl/UserDaoImpl.java | 105 | //如果名字是比尔和密码是123456就返回true | line_comment | zh-cn | package com.DI.dao.Impl;
import com.DI.dao.UserDao;
//创建一个业务逻辑接口
public class UserDaoImpl implements UserDao {
public boolean login(String name, String password) {
//如果 <SUF>
if(name.equals("比尔")&&password.equals("12345")){
return true;
}
return false;
}
}
| 1 | 26 | 1 |
46262_0 | package zhao.algorithmMagic.operands.vector;
/**
* 算法之星的向量抽象类,其中提供了两个针对性能设计的方法
* 1 在原有向量数据的基础上进行向量计算的三个函数
* 2 使用行指针锁来进行矩阵计算的三个函数(注意 矩阵中的数据是不可变的,所以这里在矩阵中,下面三个函数提升计算的安全性)
*
* @author zhao
*/
public abstract class ASVector<ImplementationType, ElementType, ArrayType> extends Vector<ImplementationType, ElementType, ArrayType> {
/**
* 刷新操作数对象的所有字段
*/
protected abstract void reFresh();
/**
* @return 将本对象中存储的向量序列的数组直接返回,注意,这里返回的是一个正在被维护的数组,因此建议保证返回值作为只读变量使用。
* <p>
* Return the array of vector sequences stored in this object directly. Note that the returned value is an array being maintained. Therefore, it is recommended to ensure that the returned value is used as a read-only variable.
*/
public abstract ArrayType toArray();
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了按维度求和计算之后,被修改的向量对象
*/
public abstract ImplementationType add(ImplementationType value, boolean ModifyCaller);
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了按维度的减法计算之后,被修改的向量对象
*/
public abstract ImplementationType diff(ImplementationType value, boolean ModifyCaller);
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了按维度的减法计算之后,被修改的向量对象
*/
public abstract ImplementationType diffAbs(ImplementationType value, boolean ModifyCaller);
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了外积计算之后,被修改的向量对象
*/
public abstract ImplementationType multiply(ImplementationType value, boolean ModifyCaller);
/**
* 将数据所维护的数组左移n个位置,并获取到结果数值
* <p>
* Move the array maintained by the data to the left n positions and get the result value
*
* @param n 被左移的次数,该数值应取值于 [0, getNumberOfDimensions]
* <p>
* The number of times it is moved to the left. The value should be [0, getNumberOfDimensions]
* @param copy 本次左移的作用参数,如果设置为true,代表本次位移会创建出一个新的数组,于当前数组毫无关联。
* <p>
* If the action parameter of this left shift is set to true, it means that this shift will create a new array, which has no association with the current array.
* @return 位移之后的AS操作数对象,其类型与调用者数据类型一致。
* <p>
* The AS operand object after displacement has the same type as the caller data type.
*/
public abstract ImplementationType leftShift(int n, boolean copy);
/**
* 将数据所维护的数组右移n个位置,并获取到结果数值
* <p>
* Move the array maintained by the data to the right n positions and get the result value
*
* @param n 被右移的次数,该数值应取值于 [0, getNumberOfDimensions]
* <p>
* The number of times it is moved to the right. The value should be [0, getNumberOfDimensions]
* @param copy 本次右移的作用参数,如果设置为true,代表本次位移会创建出一个新的数组,于当前数组毫无关联。
* <p>
* If the action parameter of this right shift is set to true, it means that this shift will create a new array, which has no association with the current array.
* @return 位移之后的AS操作数对象,其类型与调用者数据类型一致。
* <p>
* The AS operand object after displacement has the same type as the caller data type.
*/
public abstract ImplementationType rightShift(int n, boolean copy);
/**
* 将当前对象中的元素从左向右的方向进行元素索引为宗旨的反转,实现更多的效果。
* <p>
* Invert the element index of the current object from left to right to achieve more results.
*
* @param isCopy 如果设置为true 代表反转操作会作用到一个新数组中,并不会更改源数组中的元素位置。反之则是直接更改源数组。
* <p>
* If set to true, the inversion operation will be applied to a new array, and the position of the elements in the source array will not be changed. On the contrary, you can directly change the source array.
* @return 被反转之后的对象,该对象的数据类型与函数调用者是一致的。
* <p>
* The data type of the reversed object is the same as that of the function caller.
*/
public abstract ImplementationType reverseLR(boolean isCopy);
}
| BeardedManZhao/algorithmStar | src_code/src/main/java/zhao/algorithmMagic/operands/vector/ASVector.java | 2,115 | /**
* 算法之星的向量抽象类,其中提供了两个针对性能设计的方法
* 1 在原有向量数据的基础上进行向量计算的三个函数
* 2 使用行指针锁来进行矩阵计算的三个函数(注意 矩阵中的数据是不可变的,所以这里在矩阵中,下面三个函数提升计算的安全性)
*
* @author zhao
*/ | block_comment | zh-cn | package zhao.algorithmMagic.operands.vector;
/**
* 算法之 <SUF>*/
public abstract class ASVector<ImplementationType, ElementType, ArrayType> extends Vector<ImplementationType, ElementType, ArrayType> {
/**
* 刷新操作数对象的所有字段
*/
protected abstract void reFresh();
/**
* @return 将本对象中存储的向量序列的数组直接返回,注意,这里返回的是一个正在被维护的数组,因此建议保证返回值作为只读变量使用。
* <p>
* Return the array of vector sequences stored in this object directly. Note that the returned value is an array being maintained. Therefore, it is recommended to ensure that the returned value is used as a read-only variable.
*/
public abstract ArrayType toArray();
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了按维度求和计算之后,被修改的向量对象
*/
public abstract ImplementationType add(ImplementationType value, boolean ModifyCaller);
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了按维度的减法计算之后,被修改的向量对象
*/
public abstract ImplementationType diff(ImplementationType value, boolean ModifyCaller);
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了按维度的减法计算之后,被修改的向量对象
*/
public abstract ImplementationType diffAbs(ImplementationType value, boolean ModifyCaller);
/**
* 在两个向量对象之间进行计算的函数,自从1.13版本开始支持该函数的调用,该函数中的计算并不会产生一个新的向量,而是将计算操作作用于原操作数中
* <p>
* The function that calculates between two vector objects supports the call of this function since version 1.13. The calculation in this function will not generate a new vector, but will apply the calculation operation to the original operand
*
* @param value 与当前向量一起进行计算的另一个向量对象。
* <p>
* Another vector object that is evaluated with the current vector.
* @param ModifyCaller 计算操作作用对象的设置,该参数如果为true,那么计算时针对向量序列的修改操作将会直接作用到调用函数的向量中,反之将会作用到被操作数中。
* <p>
* The setting of the calculation operation action object. If this parameter is true, the modification of the vector sequence during calculation will directly affect the vector of the calling function, and vice versa.
* @return 两个向量经过了外积计算之后,被修改的向量对象
*/
public abstract ImplementationType multiply(ImplementationType value, boolean ModifyCaller);
/**
* 将数据所维护的数组左移n个位置,并获取到结果数值
* <p>
* Move the array maintained by the data to the left n positions and get the result value
*
* @param n 被左移的次数,该数值应取值于 [0, getNumberOfDimensions]
* <p>
* The number of times it is moved to the left. The value should be [0, getNumberOfDimensions]
* @param copy 本次左移的作用参数,如果设置为true,代表本次位移会创建出一个新的数组,于当前数组毫无关联。
* <p>
* If the action parameter of this left shift is set to true, it means that this shift will create a new array, which has no association with the current array.
* @return 位移之后的AS操作数对象,其类型与调用者数据类型一致。
* <p>
* The AS operand object after displacement has the same type as the caller data type.
*/
public abstract ImplementationType leftShift(int n, boolean copy);
/**
* 将数据所维护的数组右移n个位置,并获取到结果数值
* <p>
* Move the array maintained by the data to the right n positions and get the result value
*
* @param n 被右移的次数,该数值应取值于 [0, getNumberOfDimensions]
* <p>
* The number of times it is moved to the right. The value should be [0, getNumberOfDimensions]
* @param copy 本次右移的作用参数,如果设置为true,代表本次位移会创建出一个新的数组,于当前数组毫无关联。
* <p>
* If the action parameter of this right shift is set to true, it means that this shift will create a new array, which has no association with the current array.
* @return 位移之后的AS操作数对象,其类型与调用者数据类型一致。
* <p>
* The AS operand object after displacement has the same type as the caller data type.
*/
public abstract ImplementationType rightShift(int n, boolean copy);
/**
* 将当前对象中的元素从左向右的方向进行元素索引为宗旨的反转,实现更多的效果。
* <p>
* Invert the element index of the current object from left to right to achieve more results.
*
* @param isCopy 如果设置为true 代表反转操作会作用到一个新数组中,并不会更改源数组中的元素位置。反之则是直接更改源数组。
* <p>
* If set to true, the inversion operation will be applied to a new array, and the position of the elements in the source array will not be changed. On the contrary, you can directly change the source array.
* @return 被反转之后的对象,该对象的数据类型与函数调用者是一致的。
* <p>
* The data type of the reversed object is the same as that of the function caller.
*/
public abstract ImplementationType reverseLR(boolean isCopy);
}
| 0 | 149 | 0 |
27127_2 | package greedy;
import java.math.BigInteger;
/**
* 剑指 Offer 14- II. 剪绳子 II
* <p>
* https://leetcode.cn/problems/jian-sheng-zi-ii-lcof/
*/
public class CuttingRopeDemo {
public static void main(String[] args) {
}
/**
* dp 写法。
* 记住,不能在dp过程 取模,只能最终结果取模。
* <p>
* 尝试在动态规划的基础上取余,就算把数据类型都换成long也是无解的,对每次的dp[i]取余确实可以避免溢出的问题,但是由于过程中修改了值,会导致最终结果和预期不同。比如
* 这一步:
* dp[i] = Math.max(dp[i],x * y);
* x * y = 1000000005 ,若dp[i] 本该等于 1000000008 ,但是经过上次取余后变成了1,本来的结果应该是1000000008 ,现在却变成了1000000005,所以在动态规划过程中是不能取余的,那么就只能使用BigInter存储中间结果了
* <p>
* https://leetcode.cn/problems/jian-sheng-zi-ii-lcof/solution/di-zi-fen-xi-shi-yong-dong-tai-gui-hua-q-jlr7/
*/
public int cuttingRope(int n) {
BigInteger[] dp = new BigInteger[n + 1];
dp[1] = BigInteger.valueOf(0L);
dp[2] = BigInteger.valueOf(1L);
for (int i = 3; i <= n; i++) {
dp[i] = BigInteger.valueOf(0);
for (int j = 1; j < i; j++) {
dp[i] = dp[i].max(dp[i - j].multiply(BigInteger.valueOf(j))).max(BigInteger.valueOf(i - j).multiply(BigInteger.valueOf(j)));
}
}
return dp[n].mod(BigInteger.valueOf(1000000007)).intValue();
}
/**
* 贪心 + 循环取模。
* <p>
* 本题的特点是将绳子全部按照长度为3进行切割乘积结果是最大的(证明过程略过,其实贪心本来也可以不需要证明,找不出反例即可)
* 不过有几种情况需要注意:
* (1) 在剩余长度等于4的时候,要取2 * 2,而不是3
* (2) 在至少分出1段3的情况下,
* 剩余n = 2的时候要取2;剩余n = 1的时候要取1
* <p>
* 循环取余
* 所谓循环取余就是每乘一次3就取次余数,为什么这种方法不会像动态规划那样影响最终结果呢,因为本题的动态规划涉及到数的比较,会出现取余后的数和取余前的数相比较的情况,自然会影响后面的结果,
* 而贪心算法的求解过程就是简单的乘法,(100000009 % 1000000007) * 3 和 (100000009 * 3)% 1000000007的结果是一样的
*/
public int cuttingRopeV2(int n) {
if (n < 3) {
return 1;
}
if (n == 3) {
return 2;
}
long res = 1;
while (n > 4) {
res *= 3;
res %= 1000000007;
n -= 3;
}
return (int) (n * res % 1000000007);
}
}
| BeauteousJade/LeetCodeDemo | src/greedy/CuttingRopeDemo.java | 975 | /**
* 贪心 + 循环取模。
* <p>
* 本题的特点是将绳子全部按照长度为3进行切割乘积结果是最大的(证明过程略过,其实贪心本来也可以不需要证明,找不出反例即可)
* 不过有几种情况需要注意:
* (1) 在剩余长度等于4的时候,要取2 * 2,而不是3
* (2) 在至少分出1段3的情况下,
* 剩余n = 2的时候要取2;剩余n = 1的时候要取1
* <p>
* 循环取余
* 所谓循环取余就是每乘一次3就取次余数,为什么这种方法不会像动态规划那样影响最终结果呢,因为本题的动态规划涉及到数的比较,会出现取余后的数和取余前的数相比较的情况,自然会影响后面的结果,
* 而贪心算法的求解过程就是简单的乘法,(100000009 % 1000000007) * 3 和 (100000009 * 3)% 1000000007的结果是一样的
*/ | block_comment | zh-cn | package greedy;
import java.math.BigInteger;
/**
* 剑指 Offer 14- II. 剪绳子 II
* <p>
* https://leetcode.cn/problems/jian-sheng-zi-ii-lcof/
*/
public class CuttingRopeDemo {
public static void main(String[] args) {
}
/**
* dp 写法。
* 记住,不能在dp过程 取模,只能最终结果取模。
* <p>
* 尝试在动态规划的基础上取余,就算把数据类型都换成long也是无解的,对每次的dp[i]取余确实可以避免溢出的问题,但是由于过程中修改了值,会导致最终结果和预期不同。比如
* 这一步:
* dp[i] = Math.max(dp[i],x * y);
* x * y = 1000000005 ,若dp[i] 本该等于 1000000008 ,但是经过上次取余后变成了1,本来的结果应该是1000000008 ,现在却变成了1000000005,所以在动态规划过程中是不能取余的,那么就只能使用BigInter存储中间结果了
* <p>
* https://leetcode.cn/problems/jian-sheng-zi-ii-lcof/solution/di-zi-fen-xi-shi-yong-dong-tai-gui-hua-q-jlr7/
*/
public int cuttingRope(int n) {
BigInteger[] dp = new BigInteger[n + 1];
dp[1] = BigInteger.valueOf(0L);
dp[2] = BigInteger.valueOf(1L);
for (int i = 3; i <= n; i++) {
dp[i] = BigInteger.valueOf(0);
for (int j = 1; j < i; j++) {
dp[i] = dp[i].max(dp[i - j].multiply(BigInteger.valueOf(j))).max(BigInteger.valueOf(i - j).multiply(BigInteger.valueOf(j)));
}
}
return dp[n].mod(BigInteger.valueOf(1000000007)).intValue();
}
/**
* 贪心 <SUF>*/
public int cuttingRopeV2(int n) {
if (n < 3) {
return 1;
}
if (n == 3) {
return 2;
}
long res = 1;
while (n > 4) {
res *= 3;
res %= 1000000007;
n -= 3;
}
return (int) (n * res % 1000000007);
}
}
| 0 | 438 | 0 |
61057_4 | package io;
import java.io.*;
public class BRDemo {
/**
* BufferedReader 缓冲字符输入流
* 特点:块读文本数据,可以按行读取字符串
*/
public static void main(String[] args) throws IOException {
//将当前源代码输出到控制台
/*
文件输入流(字节流,低级流)
作用:从文件中读取字节
*/
FileInputStream fis = new FileInputStream(
"./src/main/java/io/BRDemo.java"
);
/*
转换流(字符流,高级流)
1:衔接字节与字符流
2:将读取的字节转换为字符
*/
InputStreamReader isr = new InputStreamReader(fis);
/*
缓冲字符输入流(字符流,高级流)
1:块读字符数据(内部默认8192长的char数组)
2:按行读取字符串
*/
BufferedReader br = new BufferedReader(isr);
/*
String readLine()
读取一行字符串。遇到换行符停止,将换行符之前的一行内容返回,并且返回的
字符串中不含有最后的换行符.
如果返回值为null则表达流读取到了末尾。
如果读取到了空行(这一行只有一个换行符)此时方法返回一个空字符串
需要注意:
当我们第一次调用readLine()方法时,缓冲流会一次性读取8192个字符到其内部
的char数组中(一次块读操作),然后从数组最开始连续扫描字符,直到遇到换行符
停止,并将之前的所有字符以一个字符串形式返回
*/
// String line = br.readLine();
// System.out.println(line);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
| Beeeee-really/jsd2306se | src/main/java/io/BRDemo.java | 434 | /*
缓冲字符输入流(字符流,高级流)
1:块读字符数据(内部默认8192长的char数组)
2:按行读取字符串
*/ | block_comment | zh-cn | package io;
import java.io.*;
public class BRDemo {
/**
* BufferedReader 缓冲字符输入流
* 特点:块读文本数据,可以按行读取字符串
*/
public static void main(String[] args) throws IOException {
//将当前源代码输出到控制台
/*
文件输入流(字节流,低级流)
作用:从文件中读取字节
*/
FileInputStream fis = new FileInputStream(
"./src/main/java/io/BRDemo.java"
);
/*
转换流(字符流,高级流)
1:衔接字节与字符流
2:将读取的字节转换为字符
*/
InputStreamReader isr = new InputStreamReader(fis);
/*
缓冲字 <SUF>*/
BufferedReader br = new BufferedReader(isr);
/*
String readLine()
读取一行字符串。遇到换行符停止,将换行符之前的一行内容返回,并且返回的
字符串中不含有最后的换行符.
如果返回值为null则表达流读取到了末尾。
如果读取到了空行(这一行只有一个换行符)此时方法返回一个空字符串
需要注意:
当我们第一次调用readLine()方法时,缓冲流会一次性读取8192个字符到其内部
的char数组中(一次块读操作),然后从数组最开始连续扫描字符,直到遇到换行符
停止,并将之前的所有字符以一个字符串形式返回
*/
// String line = br.readLine();
// System.out.println(line);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
| 0 | 104 | 0 |
37242_3 | public class Operator {
/*
/输入:Student 对象
/输出:无
/功能:往学生数组中添加一个新学生
*/
public static void addStudent(Student stu) {
for (Student s : Students) {
if (s.getName() == NULL) {
s.initStudent(stu.getName(), stu.getAddress(),
stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(),
stu.getQQ(), stu.getPersonalLanguage());
}
}
}
/*
/输入:学生姓名,类型为 String
/输出:无
/功能:将学生数组中该名字的学生姓名置空,达到删除目的
*/
public static void removeStudent(String stuName) {
for (Student s : Students) {
if (s.getName() == stuName) {
s.setName(NULL);
}
}
}
/*
/输入:Student 对象
/输出:无
/功能:按传入的对象更新学生数组中该名字的学生
*/
public static void changeStudent(Student stu) {
String stuName = stu.getName();
for (Student s : Students) {
if (s.getName() == stuName) {
s.initStudent(stuName, stu.getAddress(),
stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(),
stu.getQQ(), stu.getPersonalLanguage());
}
}
}
/*
/输入:学生姓名,类型为 String
/输出:Student 对象
/功能:查找该名字的学生的信息
*/
public static Student searchStudent(String stuName) {
Student theStudent;
for (Student s : Students) {
if (s.getName() == stuName) {
theStudent.initStudent(stuName, s.getAddress(),
s.getPhoneNumber(), s.getWeChat(), s.getMail(),
s.getQQ(), s.getPersonalLanguage());
}
}
return theStudent;
}
} | BeiDouQiXing/Classmate-book | Operate.java | 468 | /*
/输入:学生姓名,类型为 String
/输出:Student 对象
/功能:查找该名字的学生的信息
*/ | block_comment | zh-cn | public class Operator {
/*
/输入:Student 对象
/输出:无
/功能:往学生数组中添加一个新学生
*/
public static void addStudent(Student stu) {
for (Student s : Students) {
if (s.getName() == NULL) {
s.initStudent(stu.getName(), stu.getAddress(),
stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(),
stu.getQQ(), stu.getPersonalLanguage());
}
}
}
/*
/输入:学生姓名,类型为 String
/输出:无
/功能:将学生数组中该名字的学生姓名置空,达到删除目的
*/
public static void removeStudent(String stuName) {
for (Student s : Students) {
if (s.getName() == stuName) {
s.setName(NULL);
}
}
}
/*
/输入:Student 对象
/输出:无
/功能:按传入的对象更新学生数组中该名字的学生
*/
public static void changeStudent(Student stu) {
String stuName = stu.getName();
for (Student s : Students) {
if (s.getName() == stuName) {
s.initStudent(stuName, stu.getAddress(),
stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(),
stu.getQQ(), stu.getPersonalLanguage());
}
}
}
/*
/输入: <SUF>*/
public static Student searchStudent(String stuName) {
Student theStudent;
for (Student s : Students) {
if (s.getName() == stuName) {
theStudent.initStudent(stuName, s.getAddress(),
s.getPhoneNumber(), s.getWeChat(), s.getMail(),
s.getQQ(), s.getPersonalLanguage());
}
}
return theStudent;
}
} | 1 | 72 | 1 |
18364_5 | package com.yiliao.util;
import java.io.UnsupportedEncodingException;
import java.util.Random;
public class CharUtil {
public static void main(String[] args) {
System.out.println(adjective.length);
System.out.println(noun.length);
for (int i = 0; i < 100; i++) {
System.out.println(generateName());
// System.out.println(getRandomName());
}
}
private static String adjective[] = {"快乐的","冷静的","醉熏的","潇洒的","糊涂的","积极的","冷酷的","深情的","粗暴的","温柔的","可爱的","愉快的","义气的","认真的","威武的","帅气的","传统的","潇洒的","漂亮的","自然的","专一的","听话的","昏睡的","狂野的","等待的","搞怪的","幽默的","魁梧的","活泼的","开心的","高兴的","超帅的","留胡子的","坦率的","直率的","轻松的","痴情的","完美的","精明的","无聊的","有魅力的","丰富的","繁荣的","饱满的","炙热的","暴躁的","碧蓝的","俊逸的","英勇的","健忘的","故意的","无心的","土豪的","朴实的","兴奋的","幸福的","淡定的","不安的","阔达的","孤独的","独特的","疯狂的","时尚的","落后的","风趣的","忧伤的","大胆的","爱笑的","矮小的","健康的","合适的","玩命的","沉默的","斯文的","香蕉","苹果","鲤鱼","鳗鱼","任性的","细心的","粗心的","大意的","甜甜的","酷酷的","健壮的","英俊的","霸气的","阳光的","默默的","大力的","孝顺的","忧虑的","着急的","紧张的","善良的","凶狠的","害怕的","重要的","危机的","欢喜的","欣慰的","满意的","跳跃的","诚心的","称心的","如意的","怡然的","娇气的","无奈的","无语的","激动的","愤怒的","美好的","感动的","激情的","激昂的","震动的","虚拟的","超级的","寒冷的","精明的","明理的","犹豫的","忧郁的","寂寞的","奋斗的","勤奋的","现代的","过时的","稳重的","热情的","含蓄的","开放的","无辜的","多情的","纯真的","拉长的","热心的","从容的","体贴的","风中的","曾经的","追寻的","儒雅的","优雅的","开朗的","外向的","内向的","清爽的","文艺的","长情的","平常的","单身的","伶俐的","高大的","懦弱的","柔弱的","爱笑的","乐观的","耍酷的","酷炫的","神勇的","年轻的","唠叨的","瘦瘦的","无情的","包容的","顺心的","畅快的","舒适的","靓丽的","负责的","背后的","简单的","谦让的","彩色的","缥缈的","欢呼的","生动的","复杂的","慈祥的","仁爱的","魔幻的","虚幻的","淡然的","受伤的","雪白的","高高的","糟糕的","顺利的","闪闪的","羞涩的","缓慢的","迅速的","优秀的","聪明的","含糊的","俏皮的","淡淡的","坚强的","平淡的","欣喜的","能干的","灵巧的","友好的","机智的","机灵的","正直的","谨慎的","俭朴的","殷勤的","虚心的","辛勤的","自觉的","无私的","无限的","踏实的","老实的","现实的","可靠的","务实的","拼搏的","个性的","粗犷的","活力的","成就的","勤劳的","单纯的","落寞的","朴素的","悲凉的","忧心的","洁净的","清秀的","自由的","小巧的","单薄的","贪玩的","刻苦的","干净的","壮观的","和谐的","文静的","调皮的","害羞的","安详的","自信的","端庄的","坚定的","美满的","舒心的","温暖的","专注的","勤恳的","美丽的","腼腆的","优美的","甜美的","甜蜜的","整齐的","动人的","典雅的","尊敬的","舒服的","妩媚的","秀丽的","喜悦的","甜美的","彪壮的","强健的","大方的","俊秀的","聪慧的","迷人的","陶醉的","悦耳的","动听的","明亮的","结实的","魁梧的","标致的","清脆的","敏感的","光亮的","大气的","老迟到的","知性的","冷傲的","呆萌的","野性的","隐形的","笑点低的","微笑的","笨笨的","难过的","沉静的","火星上的","失眠的","安静的","纯情的","要减肥的","迷路的","烂漫的","哭泣的","贤惠的","苗条的","温婉的","发嗲的","会撒娇的","贪玩的","执着的","眯眯眼的","花痴的","想人陪的","眼睛大的","高贵的","傲娇的","心灵美的","爱撒娇的","细腻的","天真的","怕黑的","感性的","飘逸的","怕孤独的","忐忑的","高挑的","傻傻的","冷艳的","爱听歌的","还单身的","怕孤单的","懵懂的"
,"一样的", "喜欢的", "美丽的", "一定的", "原来的", "美好的", "开心的", "可能的", "可爱的",
"明白的", "所有的", "后来的", "重要的", "经常的", "自然的", "真正的", "害怕的", "空中的",
"红色的", "痛苦的", "干净的", "辛苦的", "精彩的", "欢乐的", "进步的", "影响的", "黄色的",
"亲爱的", "根本的", "完美的", "金黄的", "聪明的", "清新的", "迷人的", "光明的", "共同的",
"直接的", "真实的", "听说的", "用心的", "飞快的", "雪白的", "着急的", "乐观的", "主要的",
"鲜艳的", "冰冷的", "细心的", "奇妙的", "水平的", "动人的", "大量的", "无知的", "礼貌的",
"暖和的", "深情的", "正常的", "平淡的", "光亮的", "落后的", "大方的", "老大的", "刻苦的",
"晴朗的", "专业的", "永久的", "大气的", "知己的", "刚好的", "相对的", "平和的", "友好的",
"广大的", "秀丽的", "日常的", "高级的", "相同的", "笔直的", "安定的", "知足的", "结实的",
"许久的", "听话的", "知名的", "闷热的", "众多的", "拥挤的", "天生的", "迷你的", "老实的",
"友爱的", "原始的", "可笑的", "合格的", "公共的", "大红的", "得力的", "洁净的", "暗淡的",
"鲜红的", "桃红的", "吓人的", "多余的", "秀美的", "繁忙的", "冰凉的", "热心的", "空旷的",
"冷清的", "公开的", "冷淡的", "齐全的", "草绿的", "能干的", "发火的", "可心的", "业余的",
"空心的", "凉快的", "长远的", "土黄的", "和好的", "合法的", "明净的", "过时的", "低下的",
"不快的", "低级的", "中用的", "不定的", "公办的", "用功的", "少许的", "忙乱的", "日用的",
"要紧的", "少见的", "非分的", "怕人的", "大忙的", "幸福的", "特别的", "未来的", "伟大的",
"困难的", "伤心的", "实在的", "现实的", "丰富的", "同样的", "巨大的", "耐心的", "优秀的",
"亲切的", "讨厌的", "严厉的", "积极的", "整齐的", "环保的"};
private static String[] noun = {
"嚓茶","凉面","便当","毛豆","花生","可乐","灯泡","哈密瓜","野狼","背包","眼神","缘分","雪碧","人生","牛排","蚂蚁","飞鸟","灰狼","斑马","汉堡","悟空","巨人","绿茶","自行车","保温杯","大碗","墨镜","魔镜","煎饼","月饼","月亮","星星","芝麻","啤酒","玫瑰","大叔","小伙","哈密瓜,数据线","太阳","树叶","芹菜","黄蜂","蜜粉","蜜蜂","信封","西装","外套","裙子","大象","猫咪","母鸡","路灯","蓝天","白云","星月","彩虹","微笑","摩托","板栗","高山","大地","大树","电灯胆","砖头","楼房","水池","鸡翅","蜻蜓","红牛","咖啡","机器猫","枕头","大船","诺言","钢笔","刺猬","天空","飞机","大炮","冬天","洋葱","春天","夏天","秋天","冬日","航空","毛衣","豌豆","黑米","玉米","眼睛","老鼠","白羊","帅哥","美女","季节","鲜花","服饰","裙子","白开水","秀发","大山","火车","汽车","歌曲","舞蹈","老师","导师","方盒","大米","麦片","水杯","水壶","手套","鞋子","自行车","鼠标","手机","电脑","书本","奇迹","身影","香烟","夕阳","台灯","宝贝","未来","皮带","钥匙","心锁","故事","花瓣","滑板","画笔","画板","学姐","店员","电源","饼干","宝马","过客","大白","时光","石头","钻石","河马","犀牛","西牛","绿草","抽屉","柜子","往事","寒风","路人","橘子","耳机","鸵鸟","朋友","苗条","铅笔","钢笔","硬币","热狗","大侠","御姐","萝莉","毛巾","期待","盼望","白昼","黑夜","大门","黑裤","钢铁侠","哑铃","板凳","枫叶","荷花","乌龟","仙人掌","衬衫","大神","草丛","早晨","心情","茉莉","流沙","蜗牛","战斗机","冥王星","猎豹","棒球","篮球","乐曲","电话","网络","世界","中心","鱼","鸡","狗","老虎","鸭子","雨","羽毛","翅膀","外套","火","丝袜","书包","钢笔","冷风","八宝粥","烤鸡","大雁","音响","招牌","胡萝卜","冰棍","帽子","菠萝","蛋挞","香水","泥猴桃","吐司","溪流","黄豆","樱桃","小鸽子","小蝴蝶","爆米花","花卷","小鸭子","小海豚","日记本","小熊猫","小懒猪","小懒虫","荔枝","镜子","曲奇","金针菇","小松鼠","小虾米","酒窝","紫菜","金鱼","柚子","果汁","百褶裙","项链","帆布鞋","火龙果","奇异果","煎蛋","唇彩","小土豆","高跟鞋","戒指","雪糕","睫毛","铃铛","手链","香氛","红酒","月光","酸奶","银耳汤","咖啡豆","小蜜蜂","小蚂蚁","蜡烛","棉花糖","向日葵","水蜜桃","小蝴蝶","小刺猬","小丸子","指甲油","康乃馨","糖豆","薯片","口红","超短裙","乌冬面","冰淇淋","棒棒糖","长颈鹿","豆芽","发箍","发卡","发夹","发带","铃铛","小馒头","小笼包","小甜瓜","冬瓜","香菇","小兔子","含羞草","短靴","睫毛膏","小蘑菇","跳跳糖","小白菜","草莓","柠檬","月饼","百合","纸鹤","小天鹅","云朵","芒果","面包","海燕","小猫咪","龙猫","唇膏","鞋垫","羊","黑猫","白猫","万宝路","金毛","山水","音响",
"生活", "一起", "不是", "人们", "今天", "孩子", "心里", "奶奶", "眼睛",
"学校", "原来", "爷爷", "地方", "过去", "事情", "以后", "可能", "晚上",
"里面", "才能", "知识", "故事", "多少", "比赛", "冬天", "所有", "样子",
"成绩", "后来", "以前", "童年", "问题", "日子", "活动", "公园", "作文",
"旁边", "下午", "自然", "房间", "空气", "笑容", "明天", "风景", "音乐",
"岁月", "文化", "生气", "机会", "身影", "天气", "空中", "红色", "书包",
"今年", "汽车", "早晨", "道路", "认识", "办法", "精彩",
"中午", "礼物", "星星", "习惯", "树木", "女儿", "友谊", "夜晚", "意义",
"家长", "耳朵", "家人", "门口", "班级", "人间", "厨房", "风雨", "影响",
"过年", "电话", "黄色", "种子", "广场", "清晨", "根本", "故乡", "笑脸",
"水面", "思想", "伙伴", "美景", "照片", "水果", "彩虹", "刚才", "月光",
"先生", "鲜花", "灯光", "感情", "亲人", "语言", "爱心", "光明", "左右",
"新年", "角落", "青蛙", "电影", "行为", "阳台", "用心", "题目", "天地",
"动力", "花园", "诗人", "树林", "雨伞", "去年", "少女", "乡村", "对手",
"上午", "分别", "活力", "作用", "古代", "公主", "力气", "从前", "作品",
"空间", "黑夜", "说明", "青年", "面包", "往事", "大小", "司机",
"中心", "对面", "心头", "嘴角", "家门", "书本", "雪人", "笑话",
"云朵", "早饭", "右手", "水平", "行人", "乐园", "花草", "人才", "左手",
"目的", "课文", "优点", "灰尘", "年代", "沙子", "小说", "儿女", "明星",
"难题", "本子", "水珠", "彩色", "路灯", "把握", "房屋", "心愿", "左边",
"新闻", "早点", "市场", "雨点", "细雨", "书房", "毛巾", "画家", "元旦",
"绿豆", "本领", "起点", "青菜", "土豆", "总结", "礼貌", "右边", "窗帘",
"萝卜", "深情", "楼房", "对话", "面条", "北方", "木头", "商店", "疑问",
"后果", "现场", "诗词", "光亮", "白菜", "男子", "风格", "大道", "梦乡",
"姐妹", "毛衣", "园丁", "两边", "大风", "乡下", "广播", "规定", "围巾",
"意见", "大方", "头脑", "老大", "成语", "专业", "背景", "大衣", "黄豆",
"高手", "叶片", "过往", "选手", "奶油", "时空", "大气", "借口", "抹布",
"画笔", "山羊", "晚会", "拖鞋", "手心", "手工", "明年", "手术", "火苗",
"知己", "价格", "树苗", "主意", "摇篮", "对比", "胖子", "专家", "年级",
"落日", "东风", "屋子", "创意", "报道", "下巴", "面子", "迷宫", "雪山",
"友好", "烟雾", "西方", "姨妈", "问号", "年轮", "居民", "选手", "奶油",
"时空", "大气", "借口", "抹布", "画笔", "山羊", "晚会", "拖鞋", "手心",
"手工", "明年", "手术", "火苗", "知己", "价格", "树苗", "主意", "摇篮",
"对比", "胖子", "专家", "年级", "落日", "东风", "屋子", "创意", "报道",
"下巴", "面子", "迷宫", "雪山", "友好", "烟雾", "西方", "姨妈", "问号",
"年轮", "居民", "选手", "奶油", "时空", "大气", "借口", "抹布", "画笔",
"山羊", "晚会", "拖鞋", "手心", "手工", "明年", "手术", "火苗", "知己",
"价格", "树苗", "主意", "摇篮", "对比", "胖子", "专家", "年级", "落日",
"东风", "屋子", "创意", "报道", "下巴", "面子", "迷宫", "雪山", "友好",
"烟雾", "西方", "姨妈", "问号", "年轮", "居民"};
/**
* 生成随机昵称
*
* @return
*/
public static String generateName() {
return "vip user";
/* int adjLen= adjective.length;
int nLen= noun.length;
StringBuffer sb = new StringBuffer();
Random random = new Random();
sb.append(adjective[random.nextInt(adjLen)]);
sb.append(noun[random.nextInt(nLen)]);
return sb.toString();*/
}
/**
* 将字符串转换成相应的字符编码
* @param s
* @return
*/
public static String bytes2HexString(String s) {
byte[] b = s.getBytes();
s = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = "0" + hex;
}
s = s + hex.toUpperCase();
}
return s;
}
/**
* 随机生成汉字
* @return
*/
public static String getRandomChar() {
String str = "";
int highCode;
int lowCode;
Random random = new Random();
highCode = (176 + Math.abs(random.nextInt(39))); //B0 + 0~39(16~55) 一级汉字所占区
lowCode = (161 + Math.abs(random.nextInt(93))); //A1 + 0~93 每区有94个汉字
byte[] b = new byte[2];
b[0] = (Integer.valueOf(highCode)).byteValue();
b[1] = (Integer.valueOf(lowCode)).byteValue();
try {
str = new String(b, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
/**
* 随机生成2-4个字的名字
* @return
*/
public static String getRandomName() {
Random random = new Random();
//名字的个数
int charNum = random.nextInt(4) % 3 + 2;
String resultName = "";
for (int i= 0 ; i<charNum; i++) {
String nameWord = getRandomChar();
resultName += nameWord;
}
return resultName;
}
}
| BenThougHou/chap_app | src/com/yiliao/util/CharUtil.java | 6,209 | //B0 + 0~39(16~55) 一级汉字所占区 | line_comment | zh-cn | package com.yiliao.util;
import java.io.UnsupportedEncodingException;
import java.util.Random;
public class CharUtil {
public static void main(String[] args) {
System.out.println(adjective.length);
System.out.println(noun.length);
for (int i = 0; i < 100; i++) {
System.out.println(generateName());
// System.out.println(getRandomName());
}
}
private static String adjective[] = {"快乐的","冷静的","醉熏的","潇洒的","糊涂的","积极的","冷酷的","深情的","粗暴的","温柔的","可爱的","愉快的","义气的","认真的","威武的","帅气的","传统的","潇洒的","漂亮的","自然的","专一的","听话的","昏睡的","狂野的","等待的","搞怪的","幽默的","魁梧的","活泼的","开心的","高兴的","超帅的","留胡子的","坦率的","直率的","轻松的","痴情的","完美的","精明的","无聊的","有魅力的","丰富的","繁荣的","饱满的","炙热的","暴躁的","碧蓝的","俊逸的","英勇的","健忘的","故意的","无心的","土豪的","朴实的","兴奋的","幸福的","淡定的","不安的","阔达的","孤独的","独特的","疯狂的","时尚的","落后的","风趣的","忧伤的","大胆的","爱笑的","矮小的","健康的","合适的","玩命的","沉默的","斯文的","香蕉","苹果","鲤鱼","鳗鱼","任性的","细心的","粗心的","大意的","甜甜的","酷酷的","健壮的","英俊的","霸气的","阳光的","默默的","大力的","孝顺的","忧虑的","着急的","紧张的","善良的","凶狠的","害怕的","重要的","危机的","欢喜的","欣慰的","满意的","跳跃的","诚心的","称心的","如意的","怡然的","娇气的","无奈的","无语的","激动的","愤怒的","美好的","感动的","激情的","激昂的","震动的","虚拟的","超级的","寒冷的","精明的","明理的","犹豫的","忧郁的","寂寞的","奋斗的","勤奋的","现代的","过时的","稳重的","热情的","含蓄的","开放的","无辜的","多情的","纯真的","拉长的","热心的","从容的","体贴的","风中的","曾经的","追寻的","儒雅的","优雅的","开朗的","外向的","内向的","清爽的","文艺的","长情的","平常的","单身的","伶俐的","高大的","懦弱的","柔弱的","爱笑的","乐观的","耍酷的","酷炫的","神勇的","年轻的","唠叨的","瘦瘦的","无情的","包容的","顺心的","畅快的","舒适的","靓丽的","负责的","背后的","简单的","谦让的","彩色的","缥缈的","欢呼的","生动的","复杂的","慈祥的","仁爱的","魔幻的","虚幻的","淡然的","受伤的","雪白的","高高的","糟糕的","顺利的","闪闪的","羞涩的","缓慢的","迅速的","优秀的","聪明的","含糊的","俏皮的","淡淡的","坚强的","平淡的","欣喜的","能干的","灵巧的","友好的","机智的","机灵的","正直的","谨慎的","俭朴的","殷勤的","虚心的","辛勤的","自觉的","无私的","无限的","踏实的","老实的","现实的","可靠的","务实的","拼搏的","个性的","粗犷的","活力的","成就的","勤劳的","单纯的","落寞的","朴素的","悲凉的","忧心的","洁净的","清秀的","自由的","小巧的","单薄的","贪玩的","刻苦的","干净的","壮观的","和谐的","文静的","调皮的","害羞的","安详的","自信的","端庄的","坚定的","美满的","舒心的","温暖的","专注的","勤恳的","美丽的","腼腆的","优美的","甜美的","甜蜜的","整齐的","动人的","典雅的","尊敬的","舒服的","妩媚的","秀丽的","喜悦的","甜美的","彪壮的","强健的","大方的","俊秀的","聪慧的","迷人的","陶醉的","悦耳的","动听的","明亮的","结实的","魁梧的","标致的","清脆的","敏感的","光亮的","大气的","老迟到的","知性的","冷傲的","呆萌的","野性的","隐形的","笑点低的","微笑的","笨笨的","难过的","沉静的","火星上的","失眠的","安静的","纯情的","要减肥的","迷路的","烂漫的","哭泣的","贤惠的","苗条的","温婉的","发嗲的","会撒娇的","贪玩的","执着的","眯眯眼的","花痴的","想人陪的","眼睛大的","高贵的","傲娇的","心灵美的","爱撒娇的","细腻的","天真的","怕黑的","感性的","飘逸的","怕孤独的","忐忑的","高挑的","傻傻的","冷艳的","爱听歌的","还单身的","怕孤单的","懵懂的"
,"一样的", "喜欢的", "美丽的", "一定的", "原来的", "美好的", "开心的", "可能的", "可爱的",
"明白的", "所有的", "后来的", "重要的", "经常的", "自然的", "真正的", "害怕的", "空中的",
"红色的", "痛苦的", "干净的", "辛苦的", "精彩的", "欢乐的", "进步的", "影响的", "黄色的",
"亲爱的", "根本的", "完美的", "金黄的", "聪明的", "清新的", "迷人的", "光明的", "共同的",
"直接的", "真实的", "听说的", "用心的", "飞快的", "雪白的", "着急的", "乐观的", "主要的",
"鲜艳的", "冰冷的", "细心的", "奇妙的", "水平的", "动人的", "大量的", "无知的", "礼貌的",
"暖和的", "深情的", "正常的", "平淡的", "光亮的", "落后的", "大方的", "老大的", "刻苦的",
"晴朗的", "专业的", "永久的", "大气的", "知己的", "刚好的", "相对的", "平和的", "友好的",
"广大的", "秀丽的", "日常的", "高级的", "相同的", "笔直的", "安定的", "知足的", "结实的",
"许久的", "听话的", "知名的", "闷热的", "众多的", "拥挤的", "天生的", "迷你的", "老实的",
"友爱的", "原始的", "可笑的", "合格的", "公共的", "大红的", "得力的", "洁净的", "暗淡的",
"鲜红的", "桃红的", "吓人的", "多余的", "秀美的", "繁忙的", "冰凉的", "热心的", "空旷的",
"冷清的", "公开的", "冷淡的", "齐全的", "草绿的", "能干的", "发火的", "可心的", "业余的",
"空心的", "凉快的", "长远的", "土黄的", "和好的", "合法的", "明净的", "过时的", "低下的",
"不快的", "低级的", "中用的", "不定的", "公办的", "用功的", "少许的", "忙乱的", "日用的",
"要紧的", "少见的", "非分的", "怕人的", "大忙的", "幸福的", "特别的", "未来的", "伟大的",
"困难的", "伤心的", "实在的", "现实的", "丰富的", "同样的", "巨大的", "耐心的", "优秀的",
"亲切的", "讨厌的", "严厉的", "积极的", "整齐的", "环保的"};
private static String[] noun = {
"嚓茶","凉面","便当","毛豆","花生","可乐","灯泡","哈密瓜","野狼","背包","眼神","缘分","雪碧","人生","牛排","蚂蚁","飞鸟","灰狼","斑马","汉堡","悟空","巨人","绿茶","自行车","保温杯","大碗","墨镜","魔镜","煎饼","月饼","月亮","星星","芝麻","啤酒","玫瑰","大叔","小伙","哈密瓜,数据线","太阳","树叶","芹菜","黄蜂","蜜粉","蜜蜂","信封","西装","外套","裙子","大象","猫咪","母鸡","路灯","蓝天","白云","星月","彩虹","微笑","摩托","板栗","高山","大地","大树","电灯胆","砖头","楼房","水池","鸡翅","蜻蜓","红牛","咖啡","机器猫","枕头","大船","诺言","钢笔","刺猬","天空","飞机","大炮","冬天","洋葱","春天","夏天","秋天","冬日","航空","毛衣","豌豆","黑米","玉米","眼睛","老鼠","白羊","帅哥","美女","季节","鲜花","服饰","裙子","白开水","秀发","大山","火车","汽车","歌曲","舞蹈","老师","导师","方盒","大米","麦片","水杯","水壶","手套","鞋子","自行车","鼠标","手机","电脑","书本","奇迹","身影","香烟","夕阳","台灯","宝贝","未来","皮带","钥匙","心锁","故事","花瓣","滑板","画笔","画板","学姐","店员","电源","饼干","宝马","过客","大白","时光","石头","钻石","河马","犀牛","西牛","绿草","抽屉","柜子","往事","寒风","路人","橘子","耳机","鸵鸟","朋友","苗条","铅笔","钢笔","硬币","热狗","大侠","御姐","萝莉","毛巾","期待","盼望","白昼","黑夜","大门","黑裤","钢铁侠","哑铃","板凳","枫叶","荷花","乌龟","仙人掌","衬衫","大神","草丛","早晨","心情","茉莉","流沙","蜗牛","战斗机","冥王星","猎豹","棒球","篮球","乐曲","电话","网络","世界","中心","鱼","鸡","狗","老虎","鸭子","雨","羽毛","翅膀","外套","火","丝袜","书包","钢笔","冷风","八宝粥","烤鸡","大雁","音响","招牌","胡萝卜","冰棍","帽子","菠萝","蛋挞","香水","泥猴桃","吐司","溪流","黄豆","樱桃","小鸽子","小蝴蝶","爆米花","花卷","小鸭子","小海豚","日记本","小熊猫","小懒猪","小懒虫","荔枝","镜子","曲奇","金针菇","小松鼠","小虾米","酒窝","紫菜","金鱼","柚子","果汁","百褶裙","项链","帆布鞋","火龙果","奇异果","煎蛋","唇彩","小土豆","高跟鞋","戒指","雪糕","睫毛","铃铛","手链","香氛","红酒","月光","酸奶","银耳汤","咖啡豆","小蜜蜂","小蚂蚁","蜡烛","棉花糖","向日葵","水蜜桃","小蝴蝶","小刺猬","小丸子","指甲油","康乃馨","糖豆","薯片","口红","超短裙","乌冬面","冰淇淋","棒棒糖","长颈鹿","豆芽","发箍","发卡","发夹","发带","铃铛","小馒头","小笼包","小甜瓜","冬瓜","香菇","小兔子","含羞草","短靴","睫毛膏","小蘑菇","跳跳糖","小白菜","草莓","柠檬","月饼","百合","纸鹤","小天鹅","云朵","芒果","面包","海燕","小猫咪","龙猫","唇膏","鞋垫","羊","黑猫","白猫","万宝路","金毛","山水","音响",
"生活", "一起", "不是", "人们", "今天", "孩子", "心里", "奶奶", "眼睛",
"学校", "原来", "爷爷", "地方", "过去", "事情", "以后", "可能", "晚上",
"里面", "才能", "知识", "故事", "多少", "比赛", "冬天", "所有", "样子",
"成绩", "后来", "以前", "童年", "问题", "日子", "活动", "公园", "作文",
"旁边", "下午", "自然", "房间", "空气", "笑容", "明天", "风景", "音乐",
"岁月", "文化", "生气", "机会", "身影", "天气", "空中", "红色", "书包",
"今年", "汽车", "早晨", "道路", "认识", "办法", "精彩",
"中午", "礼物", "星星", "习惯", "树木", "女儿", "友谊", "夜晚", "意义",
"家长", "耳朵", "家人", "门口", "班级", "人间", "厨房", "风雨", "影响",
"过年", "电话", "黄色", "种子", "广场", "清晨", "根本", "故乡", "笑脸",
"水面", "思想", "伙伴", "美景", "照片", "水果", "彩虹", "刚才", "月光",
"先生", "鲜花", "灯光", "感情", "亲人", "语言", "爱心", "光明", "左右",
"新年", "角落", "青蛙", "电影", "行为", "阳台", "用心", "题目", "天地",
"动力", "花园", "诗人", "树林", "雨伞", "去年", "少女", "乡村", "对手",
"上午", "分别", "活力", "作用", "古代", "公主", "力气", "从前", "作品",
"空间", "黑夜", "说明", "青年", "面包", "往事", "大小", "司机",
"中心", "对面", "心头", "嘴角", "家门", "书本", "雪人", "笑话",
"云朵", "早饭", "右手", "水平", "行人", "乐园", "花草", "人才", "左手",
"目的", "课文", "优点", "灰尘", "年代", "沙子", "小说", "儿女", "明星",
"难题", "本子", "水珠", "彩色", "路灯", "把握", "房屋", "心愿", "左边",
"新闻", "早点", "市场", "雨点", "细雨", "书房", "毛巾", "画家", "元旦",
"绿豆", "本领", "起点", "青菜", "土豆", "总结", "礼貌", "右边", "窗帘",
"萝卜", "深情", "楼房", "对话", "面条", "北方", "木头", "商店", "疑问",
"后果", "现场", "诗词", "光亮", "白菜", "男子", "风格", "大道", "梦乡",
"姐妹", "毛衣", "园丁", "两边", "大风", "乡下", "广播", "规定", "围巾",
"意见", "大方", "头脑", "老大", "成语", "专业", "背景", "大衣", "黄豆",
"高手", "叶片", "过往", "选手", "奶油", "时空", "大气", "借口", "抹布",
"画笔", "山羊", "晚会", "拖鞋", "手心", "手工", "明年", "手术", "火苗",
"知己", "价格", "树苗", "主意", "摇篮", "对比", "胖子", "专家", "年级",
"落日", "东风", "屋子", "创意", "报道", "下巴", "面子", "迷宫", "雪山",
"友好", "烟雾", "西方", "姨妈", "问号", "年轮", "居民", "选手", "奶油",
"时空", "大气", "借口", "抹布", "画笔", "山羊", "晚会", "拖鞋", "手心",
"手工", "明年", "手术", "火苗", "知己", "价格", "树苗", "主意", "摇篮",
"对比", "胖子", "专家", "年级", "落日", "东风", "屋子", "创意", "报道",
"下巴", "面子", "迷宫", "雪山", "友好", "烟雾", "西方", "姨妈", "问号",
"年轮", "居民", "选手", "奶油", "时空", "大气", "借口", "抹布", "画笔",
"山羊", "晚会", "拖鞋", "手心", "手工", "明年", "手术", "火苗", "知己",
"价格", "树苗", "主意", "摇篮", "对比", "胖子", "专家", "年级", "落日",
"东风", "屋子", "创意", "报道", "下巴", "面子", "迷宫", "雪山", "友好",
"烟雾", "西方", "姨妈", "问号", "年轮", "居民"};
/**
* 生成随机昵称
*
* @return
*/
public static String generateName() {
return "vip user";
/* int adjLen= adjective.length;
int nLen= noun.length;
StringBuffer sb = new StringBuffer();
Random random = new Random();
sb.append(adjective[random.nextInt(adjLen)]);
sb.append(noun[random.nextInt(nLen)]);
return sb.toString();*/
}
/**
* 将字符串转换成相应的字符编码
* @param s
* @return
*/
public static String bytes2HexString(String s) {
byte[] b = s.getBytes();
s = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = "0" + hex;
}
s = s + hex.toUpperCase();
}
return s;
}
/**
* 随机生成汉字
* @return
*/
public static String getRandomChar() {
String str = "";
int highCode;
int lowCode;
Random random = new Random();
highCode = (176 + Math.abs(random.nextInt(39))); //B0 <SUF>
lowCode = (161 + Math.abs(random.nextInt(93))); //A1 + 0~93 每区有94个汉字
byte[] b = new byte[2];
b[0] = (Integer.valueOf(highCode)).byteValue();
b[1] = (Integer.valueOf(lowCode)).byteValue();
try {
str = new String(b, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
/**
* 随机生成2-4个字的名字
* @return
*/
public static String getRandomName() {
Random random = new Random();
//名字的个数
int charNum = random.nextInt(4) % 3 + 2;
String resultName = "";
for (int i= 0 ; i<charNum; i++) {
String nameWord = getRandomChar();
resultName += nameWord;
}
return resultName;
}
}
| 1 | 26 | 1 |
27847_4 | package bus.service;
import bus.Vo.CustomerVo;
import bus.domian.Customer;
import sys.utils.DataGridView;
import java.util.List;
public interface CustomerService {
/*查询所有客户*/
DataGridView queryAllCustomer(CustomerVo customerVo);
/*添加客户*/
void addCustomer(CustomerVo customerVo);
/*修改客户*/
void updateCustomer(CustomerVo customerVo);
/*根据id删除客户*/
void deleteCustomer(String identity);
/*批量删除客户*/
void deleteBatchCustomer(String[] identitys);
/*根据客户身份证号查询信息,用在判断这个客户是否存在,在出售表哪里*/
Customer queryCustomerByIdentity(String identity);
/*到处客户数据*/
List<Customer> queryCustomerAllList(CustomerVo customerVo);
}
| Berlin12034/ssm_gift | src/main/java/bus/service/CustomerService.java | 188 | /*批量删除客户*/ | block_comment | zh-cn | package bus.service;
import bus.Vo.CustomerVo;
import bus.domian.Customer;
import sys.utils.DataGridView;
import java.util.List;
public interface CustomerService {
/*查询所有客户*/
DataGridView queryAllCustomer(CustomerVo customerVo);
/*添加客户*/
void addCustomer(CustomerVo customerVo);
/*修改客户*/
void updateCustomer(CustomerVo customerVo);
/*根据id删除客户*/
void deleteCustomer(String identity);
/*批量删 <SUF>*/
void deleteBatchCustomer(String[] identitys);
/*根据客户身份证号查询信息,用在判断这个客户是否存在,在出售表哪里*/
Customer queryCustomerByIdentity(String identity);
/*到处客户数据*/
List<Customer> queryCustomerAllList(CustomerVo customerVo);
}
| 1 | 10 | 1 |
50430_14 | package ValuePicker;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.Scroller;
import java.text.DecimalFormat;
public class ValuePickerC extends View {
public enum Gravity {
START, END, TOP, BOTTOM, CENTRE
}
private int h10 = 60, h5 = 50, h1 = 30;
private int w10 = 4, w5 = 4, w1 = 2;
private int c10, c5;
private Gravity mGravity = Gravity.START;
private Scroller mScroller;
private VelocityTracker mVelocityTracker;
private Paint mPaintLine;
/**
* 控件的X轴的中心点
*/
private int mCentreY;
/**
* 控件的X轴的中心点
*/
private int mCentreX;
/**
* 控件的高
*/
private int mRadius;
private int mWidth, mHeight;
/**
* 滑动的偏移量
*/
private float mOffset;
/**
* 刻度的宽度
*/
private int mItemDegree = 3;
/**
* 起始值
*/
private float mValueStart;
/**
* 刻度的差值
*/
private float mValuePer;
/**
* 总共刻度
*/
private int mTotalCounts;
private OnValuePickedListener mOnValuePickedListener;
public ValuePickerC(Context context) {
this(context, null);
}
public ValuePickerC(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ValuePickerC(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mScroller = new Scroller(context);
mPaintLine = new Paint();
mPaintLine.setDither(true);
mPaintLine.setAntiAlias(true);
mPaintLine.setTextSize(40);
c10 = Color.parseColor("#FF4081");
c5 = Color.parseColor("#999999");
}
RectF mRange;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
switch (mGravity) {
case START:
mCentreX = 0;
mCentreY = mHeight / 2;
mRadius = mCentreY;
mRange = new RectF(-mRadius, 0, mRadius, mHeight);
break;
case END:
mCentreX = mWidth;
mCentreY = mHeight / 2;
mRadius = mCentreY;
mRange = new RectF(mWidth - mRadius, 0, mWidth + mRadius, mHeight);
break;
case TOP:
mCentreX = mWidth / 2;
mCentreY = 0;
mRadius = mCentreX;
mRange = new RectF(0, -mRadius, mWidth, mRadius);
break;
case BOTTOM:
mCentreX = mWidth / 2;
mRadius = mWidth / 2;
mCentreY = mHeight;
mRange = new RectF(0, mHeight - mRadius, mWidth, mHeight + mRadius);
break;
case CENTRE:
mCentreX = mWidth / 2;
mCentreY = mHeight / 2;
mRadius = mHeight < mWidth ? mHeight / 2 : mWidth / 2;
break;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// if (mGravity == Gravity.BOTTOM) {
// mPaintLine.setColor(c5);
// mPaintLine.setStrokeWidth(w5);
// mPaintLine.setStyle(Paint.Style.STROKE);
// canvas.drawCircle(mWidth / 2, mHeight, mRadius, mPaintLine);
// }
int startX = 0, endX = 0, startY = 0, endY = 0;
float offset;
for (int i = 0; i <= mTotalCounts; i++) {
switch (mGravity) {
case START:
offset = mOffset - mItemDegree * i;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mRadius * Math.cos(offset * Math.PI / 180));
startY = (int) (mRadius - mRadius * Math.sin(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) ((mRadius - h10) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h10) * Math.sin(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, -30 - offset, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) ((mRadius - h5) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h5) * Math.sin(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) ((mRadius - h1) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h1) * Math.sin(offset * Math.PI / 180));
}
break;
case END:
offset = mOffset - mItemDegree * i;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mWidth - mRadius * Math.cos(offset * Math.PI / 180));
startY = (int) (mRadius - mRadius * Math.sin(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) (mWidth - (mRadius - h10) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h10) * Math.sin(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, offset + 150, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) (mWidth - (mRadius - h5) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h5) * Math.sin(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) (mWidth - (mRadius - h1) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h1) * Math.sin(offset * Math.PI / 180));
}
break;
case TOP:
offset = mItemDegree * i - mOffset;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mRadius * Math.sin(offset * Math.PI / 180) + mWidth / 2);
startY = (int) (mRadius * Math.cos(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) ((mRadius - h10) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) ((mRadius - h10) * Math.cos(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, 60 - offset, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) ((mRadius - h5) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) ((mRadius - h5) * Math.cos(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) ((mRadius - h1) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) ((mRadius - h1) * Math.cos(offset * Math.PI / 180));
}
break;
case BOTTOM:
offset = mItemDegree * i - mOffset;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mRadius * Math.sin(offset * Math.PI / 180) + mWidth / 2);
startY = (int) (mHeight - mRadius * Math.cos(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) ((mRadius - h10) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) (mHeight - (mRadius - h10) * Math.cos(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, offset - 120, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) ((mRadius - h5) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) (mHeight - (mRadius - h5) * Math.cos(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) ((mRadius - h1) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) (mHeight - (mRadius - h1) * Math.cos(offset * Math.PI / 180));
}
break;
case CENTRE:
break;
}
canvas.drawLine(startX, startY, endX, endY, mPaintLine);
}
}
public void setParams(Gravity gravity, float start, float end, float per, float selectedValue) {
this.mGravity = gravity;
this.mValueStart = start;
this.mValuePer = per;
this.mTotalCounts = (int) (Math.abs(start - end) / per);
this.mOffset = mItemDegree * (selectedValue - start) / per;
invalidate();
}
public void setOnValuePickedListener(OnValuePickedListener l) {
this.mOnValuePickedListener = l;
}
private float mLastX;
private float mLastY;
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
float x = event.getX();
float y = event.getY();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_DOWN:
mScrollerOffset = 0;
if (mVa != null) {
mVa.cancel();
}
mScroller.forceFinished(true);
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_MOVE:
if (mGravity == Gravity.START || mGravity == Gravity.END) {
float dy = mLastY - y;
float offset = (float) (180 * dy / Math.PI / mRadius);
mOffset += offset;
if (mOffset < 0) {
mOffset = 0;
}
if (mOffset > mTotalCounts * mItemDegree) {
mOffset = mTotalCounts * mItemDegree;
}
} else if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) {
float dx = mLastX - x;
float offset = (float) (180 * dx / Math.PI / mRadius);
mOffset += offset;
if (mOffset < 0) {
mOffset = 0;
}
if (mOffset > mTotalCounts * mItemDegree) {
mOffset = mTotalCounts * mItemDegree;
}
}
returnValue();
invalidate();
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mVelocityTracker.computeCurrentVelocity(1000);
if (mGravity == Gravity.START || mGravity == Gravity.END) {
mVelocityTracker.computeCurrentVelocity(500);
float yVelocity = mVelocityTracker.getYVelocity();//大约为几千,往右为负,往左为正
if (Math.abs(yVelocity) > 50) {
mScroller.fling(0, 0, 0, (int) (yVelocity / 2), 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
postInvalidate();
} else {
end();
}
} else if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) {
mVelocityTracker.computeCurrentVelocity(500);
float xVelocity = mVelocityTracker.getXVelocity();//大约为几千,往右为负,往左为正
if (Math.abs(xVelocity) > 50) {
mScroller.fling(0, 0, (int) (xVelocity / 2), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
postInvalidate();
} else {
end();
}
}
break;
}
return true;
}
private ValueAnimator mVa;
private void end() {
int end;
if (mOffset % mItemDegree > (mItemDegree / 2)) {
end = ((int) (mOffset / mItemDegree) + 1) * mItemDegree;
} else {
end = (int) (mOffset / mItemDegree) * mItemDegree;
}
if (end < 0) {
end = 0;
}
if (end > mItemDegree * mTotalCounts) {
end = mItemDegree * mTotalCounts;
}
if (mVa != null) {
mVa.cancel();
}
mVa = ValueAnimator.ofFloat(mOffset, end);
mVa.setDuration(400);
mVa.start();
mVa.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mOffset = (float) animation.getAnimatedValue();
postInvalidate();
}
});
mVa.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
returnValue();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
private int mScrollerOffset;
@Override
public void computeScroll() {
switch (mGravity) {
case START:
case END:
if (mScroller.computeScrollOffset()) {
int y = mScroller.getCurrY();
int dy = y - mScrollerOffset;
mOffset -= dy;
if (mOffset < 0) {
mOffset = 0;
mScroller.forceFinished(true);
}
if (mOffset > mItemDegree * mTotalCounts) {
mOffset = mItemDegree * mTotalCounts;
mScroller.forceFinished(true);
}
returnValue();
postInvalidate();
mScrollerOffset = y;
if (mScroller.getCurrY() == mScroller.getFinalY()) {
if (mOffset > 0 && mOffset < mItemDegree * mTotalCounts) {
end();
}
}
}
break;
case TOP:
case BOTTOM:
if (mScroller.computeScrollOffset()) {
int x = mScroller.getCurrX();
int dx = x - mScrollerOffset;
mOffset -= dx;
if (mOffset < 0) {
mOffset = 0;
mScroller.forceFinished(true);
}
if (mOffset > mItemDegree * mTotalCounts) {
mOffset = mItemDegree * mTotalCounts;
mScroller.forceFinished(true);
}
returnValue();
postInvalidate();
mScrollerOffset = x;
if (mScroller.getCurrX() == mScroller.getFinalX()) {
if (mOffset > 0 && mOffset < mItemDegree * mTotalCounts) {
end();
}
}
}
break;
}
}
private void returnValue() {
if (mOnValuePickedListener != null) {
mOnValuePickedListener.onValueSelected(getValue());
}
}
private DecimalFormat mDecimalFormat = new DecimalFormat("####0.0");
private float getValue() {
return Float.parseFloat(mDecimalFormat.format(mValueStart + mValuePer * (mOffset / mItemDegree)));
}
} | BestMafen/ValuePicker | app/src/main/java/ValuePicker/ValuePickerC.java | 4,984 | //大约为几千,往右为负,往左为正 | line_comment | zh-cn | package ValuePicker;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.Scroller;
import java.text.DecimalFormat;
public class ValuePickerC extends View {
public enum Gravity {
START, END, TOP, BOTTOM, CENTRE
}
private int h10 = 60, h5 = 50, h1 = 30;
private int w10 = 4, w5 = 4, w1 = 2;
private int c10, c5;
private Gravity mGravity = Gravity.START;
private Scroller mScroller;
private VelocityTracker mVelocityTracker;
private Paint mPaintLine;
/**
* 控件的X轴的中心点
*/
private int mCentreY;
/**
* 控件的X轴的中心点
*/
private int mCentreX;
/**
* 控件的高
*/
private int mRadius;
private int mWidth, mHeight;
/**
* 滑动的偏移量
*/
private float mOffset;
/**
* 刻度的宽度
*/
private int mItemDegree = 3;
/**
* 起始值
*/
private float mValueStart;
/**
* 刻度的差值
*/
private float mValuePer;
/**
* 总共刻度
*/
private int mTotalCounts;
private OnValuePickedListener mOnValuePickedListener;
public ValuePickerC(Context context) {
this(context, null);
}
public ValuePickerC(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ValuePickerC(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mScroller = new Scroller(context);
mPaintLine = new Paint();
mPaintLine.setDither(true);
mPaintLine.setAntiAlias(true);
mPaintLine.setTextSize(40);
c10 = Color.parseColor("#FF4081");
c5 = Color.parseColor("#999999");
}
RectF mRange;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
switch (mGravity) {
case START:
mCentreX = 0;
mCentreY = mHeight / 2;
mRadius = mCentreY;
mRange = new RectF(-mRadius, 0, mRadius, mHeight);
break;
case END:
mCentreX = mWidth;
mCentreY = mHeight / 2;
mRadius = mCentreY;
mRange = new RectF(mWidth - mRadius, 0, mWidth + mRadius, mHeight);
break;
case TOP:
mCentreX = mWidth / 2;
mCentreY = 0;
mRadius = mCentreX;
mRange = new RectF(0, -mRadius, mWidth, mRadius);
break;
case BOTTOM:
mCentreX = mWidth / 2;
mRadius = mWidth / 2;
mCentreY = mHeight;
mRange = new RectF(0, mHeight - mRadius, mWidth, mHeight + mRadius);
break;
case CENTRE:
mCentreX = mWidth / 2;
mCentreY = mHeight / 2;
mRadius = mHeight < mWidth ? mHeight / 2 : mWidth / 2;
break;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// if (mGravity == Gravity.BOTTOM) {
// mPaintLine.setColor(c5);
// mPaintLine.setStrokeWidth(w5);
// mPaintLine.setStyle(Paint.Style.STROKE);
// canvas.drawCircle(mWidth / 2, mHeight, mRadius, mPaintLine);
// }
int startX = 0, endX = 0, startY = 0, endY = 0;
float offset;
for (int i = 0; i <= mTotalCounts; i++) {
switch (mGravity) {
case START:
offset = mOffset - mItemDegree * i;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mRadius * Math.cos(offset * Math.PI / 180));
startY = (int) (mRadius - mRadius * Math.sin(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) ((mRadius - h10) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h10) * Math.sin(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, -30 - offset, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) ((mRadius - h5) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h5) * Math.sin(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) ((mRadius - h1) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h1) * Math.sin(offset * Math.PI / 180));
}
break;
case END:
offset = mOffset - mItemDegree * i;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mWidth - mRadius * Math.cos(offset * Math.PI / 180));
startY = (int) (mRadius - mRadius * Math.sin(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) (mWidth - (mRadius - h10) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h10) * Math.sin(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, offset + 150, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) (mWidth - (mRadius - h5) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h5) * Math.sin(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) (mWidth - (mRadius - h1) * Math.cos(offset * Math.PI / 180));
endY = (int) (mRadius - (mRadius - h1) * Math.sin(offset * Math.PI / 180));
}
break;
case TOP:
offset = mItemDegree * i - mOffset;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mRadius * Math.sin(offset * Math.PI / 180) + mWidth / 2);
startY = (int) (mRadius * Math.cos(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) ((mRadius - h10) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) ((mRadius - h10) * Math.cos(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, 60 - offset, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) ((mRadius - h5) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) ((mRadius - h5) * Math.cos(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) ((mRadius - h1) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) ((mRadius - h1) * Math.cos(offset * Math.PI / 180));
}
break;
case BOTTOM:
offset = mItemDegree * i - mOffset;
if (offset < -90 || offset > 90) {
continue;
}
startX = (int) (mRadius * Math.sin(offset * Math.PI / 180) + mWidth / 2);
startY = (int) (mHeight - mRadius * Math.cos(offset * Math.PI / 180));
if (i % 10 == 0) {
endX = (int) ((mRadius - h10) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) (mHeight - (mRadius - h10) * Math.cos(offset * Math.PI / 180));
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
mPaintLine.setStyle(Paint.Style.FILL);
String text = String.valueOf(mValueStart + i * mValuePer);
Path path = new Path();
path.addArc(mRange, offset - 120, 60);
float textWidth = mPaintLine.measureText(text);
float hOffset = (float) (Math.PI * mRadius / 6 - textWidth / 2);
float vOffset = h10 + 40;
canvas.drawTextOnPath(text, path, hOffset, vOffset, mPaintLine);
mPaintLine.setColor(c10);
mPaintLine.setStrokeWidth(w10);
} else if (i % 5 == 0) {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w5);
endX = (int) ((mRadius - h5) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) (mHeight - (mRadius - h5) * Math.cos(offset * Math.PI / 180));
} else {
mPaintLine.setColor(c5);
mPaintLine.setStrokeWidth(w1);
endX = (int) ((mRadius - h1) * Math.sin(offset * Math.PI / 180) + mWidth / 2);
endY = (int) (mHeight - (mRadius - h1) * Math.cos(offset * Math.PI / 180));
}
break;
case CENTRE:
break;
}
canvas.drawLine(startX, startY, endX, endY, mPaintLine);
}
}
public void setParams(Gravity gravity, float start, float end, float per, float selectedValue) {
this.mGravity = gravity;
this.mValueStart = start;
this.mValuePer = per;
this.mTotalCounts = (int) (Math.abs(start - end) / per);
this.mOffset = mItemDegree * (selectedValue - start) / per;
invalidate();
}
public void setOnValuePickedListener(OnValuePickedListener l) {
this.mOnValuePickedListener = l;
}
private float mLastX;
private float mLastY;
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
float x = event.getX();
float y = event.getY();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_DOWN:
mScrollerOffset = 0;
if (mVa != null) {
mVa.cancel();
}
mScroller.forceFinished(true);
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_MOVE:
if (mGravity == Gravity.START || mGravity == Gravity.END) {
float dy = mLastY - y;
float offset = (float) (180 * dy / Math.PI / mRadius);
mOffset += offset;
if (mOffset < 0) {
mOffset = 0;
}
if (mOffset > mTotalCounts * mItemDegree) {
mOffset = mTotalCounts * mItemDegree;
}
} else if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) {
float dx = mLastX - x;
float offset = (float) (180 * dx / Math.PI / mRadius);
mOffset += offset;
if (mOffset < 0) {
mOffset = 0;
}
if (mOffset > mTotalCounts * mItemDegree) {
mOffset = mTotalCounts * mItemDegree;
}
}
returnValue();
invalidate();
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mVelocityTracker.computeCurrentVelocity(1000);
if (mGravity == Gravity.START || mGravity == Gravity.END) {
mVelocityTracker.computeCurrentVelocity(500);
float yVelocity = mVelocityTracker.getYVelocity();//大约为几千,往右为负,往左为正
if (Math.abs(yVelocity) > 50) {
mScroller.fling(0, 0, 0, (int) (yVelocity / 2), 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
postInvalidate();
} else {
end();
}
} else if (mGravity == Gravity.TOP || mGravity == Gravity.BOTTOM) {
mVelocityTracker.computeCurrentVelocity(500);
float xVelocity = mVelocityTracker.getXVelocity();//大约 <SUF>
if (Math.abs(xVelocity) > 50) {
mScroller.fling(0, 0, (int) (xVelocity / 2), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
postInvalidate();
} else {
end();
}
}
break;
}
return true;
}
private ValueAnimator mVa;
private void end() {
int end;
if (mOffset % mItemDegree > (mItemDegree / 2)) {
end = ((int) (mOffset / mItemDegree) + 1) * mItemDegree;
} else {
end = (int) (mOffset / mItemDegree) * mItemDegree;
}
if (end < 0) {
end = 0;
}
if (end > mItemDegree * mTotalCounts) {
end = mItemDegree * mTotalCounts;
}
if (mVa != null) {
mVa.cancel();
}
mVa = ValueAnimator.ofFloat(mOffset, end);
mVa.setDuration(400);
mVa.start();
mVa.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mOffset = (float) animation.getAnimatedValue();
postInvalidate();
}
});
mVa.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
returnValue();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
private int mScrollerOffset;
@Override
public void computeScroll() {
switch (mGravity) {
case START:
case END:
if (mScroller.computeScrollOffset()) {
int y = mScroller.getCurrY();
int dy = y - mScrollerOffset;
mOffset -= dy;
if (mOffset < 0) {
mOffset = 0;
mScroller.forceFinished(true);
}
if (mOffset > mItemDegree * mTotalCounts) {
mOffset = mItemDegree * mTotalCounts;
mScroller.forceFinished(true);
}
returnValue();
postInvalidate();
mScrollerOffset = y;
if (mScroller.getCurrY() == mScroller.getFinalY()) {
if (mOffset > 0 && mOffset < mItemDegree * mTotalCounts) {
end();
}
}
}
break;
case TOP:
case BOTTOM:
if (mScroller.computeScrollOffset()) {
int x = mScroller.getCurrX();
int dx = x - mScrollerOffset;
mOffset -= dx;
if (mOffset < 0) {
mOffset = 0;
mScroller.forceFinished(true);
}
if (mOffset > mItemDegree * mTotalCounts) {
mOffset = mItemDegree * mTotalCounts;
mScroller.forceFinished(true);
}
returnValue();
postInvalidate();
mScrollerOffset = x;
if (mScroller.getCurrX() == mScroller.getFinalX()) {
if (mOffset > 0 && mOffset < mItemDegree * mTotalCounts) {
end();
}
}
}
break;
}
}
private void returnValue() {
if (mOnValuePickedListener != null) {
mOnValuePickedListener.onValueSelected(getValue());
}
}
private DecimalFormat mDecimalFormat = new DecimalFormat("####0.0");
private float getValue() {
return Float.parseFloat(mDecimalFormat.format(mValueStart + mValuePer * (mOffset / mItemDegree)));
}
} | 1 | 17 | 1 |
56050_7 | package com.chenyanwu.erp.erpframework.config;
import com.chenyanwu.erp.erpframework.common.util.DateConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;
/**
* @Auther: chenyanwu
* @Date: 2019/2/27 22:56
* @Description:
* @Version 1.0
*/
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
/**
* 增加字符串转日期的功能
*/
@PostConstruct
public void initEditableValidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer
.getConversionService();
genericConversionService.addConverter(new DateConverter());
}
}
// 注册连接器
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/static/**", "/assets/**", "/css/**", "/images/**", "/layui_ext/**",
"/login", "/login/main", "/genCaptcha");
super.addInterceptors(registry);
}
/**
* 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。
* 需要重新指定静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
// 处理继承了WebMvcConfigurationSupport后,字符编码在application.properties文件中无效的问题
// 参考网址:https://blog.csdn.net/qq_15071263/article/details/80248805
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(responseBodyConverter());
// 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案
// 百度,谷歌,各大论坛等。你可以试试去掉。
addDefaultHttpMessageConverters(converters);
}
}
| BetterZhaoyuan/erp-framework-master | src/main/java/com/chenyanwu/erp/erpframework/config/WebConfig.java | 818 | // 百度,谷歌,各大论坛等。你可以试试去掉。 | line_comment | zh-cn | package com.chenyanwu.erp.erpframework.config;
import com.chenyanwu.erp.erpframework.common.util.DateConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;
/**
* @Auther: chenyanwu
* @Date: 2019/2/27 22:56
* @Description:
* @Version 1.0
*/
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
/**
* 增加字符串转日期的功能
*/
@PostConstruct
public void initEditableValidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer
.getConversionService();
genericConversionService.addConverter(new DateConverter());
}
}
// 注册连接器
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/static/**", "/assets/**", "/css/**", "/images/**", "/layui_ext/**",
"/login", "/login/main", "/genCaptcha");
super.addInterceptors(registry);
}
/**
* 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。
* 需要重新指定静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
// 处理继承了WebMvcConfigurationSupport后,字符编码在application.properties文件中无效的问题
// 参考网址:https://blog.csdn.net/qq_15071263/article/details/80248805
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(responseBodyConverter());
// 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案
// 百度 <SUF>
addDefaultHttpMessageConverters(converters);
}
}
| 0 | 23 | 0 |
28085_0 | package DP;
public class LC70_ClimbingStairs {
public static int climb (int n) {
if (n < 2) return 1;
int ans = 0;
// 状态转移方程
// dp[i] 只与 dp[i - 1] 与 dp[i - 2] 有关
// f(x) = f(x - 1) + f(x - 2)
// 特别的, 有 f(0) = 1, f(1) = 1
int p1 = 1, p2 = 1;
for (int i = 2; i <= n; ++i) {
ans = p1 + p2;
p2 = p1;
p1 = ans;
}
return ans;
}
// 1 1 2 3 5 8
public static void main(String[] args) {
int n = 5;
System.out.println(climb(n));
}
}
| Bi1ack/LeetCode | src/DP/LC70_ClimbingStairs.java | 236 | // 状态转移方程 | line_comment | zh-cn | package DP;
public class LC70_ClimbingStairs {
public static int climb (int n) {
if (n < 2) return 1;
int ans = 0;
// 状态 <SUF>
// dp[i] 只与 dp[i - 1] 与 dp[i - 2] 有关
// f(x) = f(x - 1) + f(x - 2)
// 特别的, 有 f(0) = 1, f(1) = 1
int p1 = 1, p2 = 1;
for (int i = 2; i <= n; ++i) {
ans = p1 + p2;
p2 = p1;
p1 = ans;
}
return ans;
}
// 1 1 2 3 5 8
public static void main(String[] args) {
int n = 5;
System.out.println(climb(n));
}
}
| 1 | 9 | 1 |
16472_11 | package models;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import play.db.jpa.GenericModel;
import play.libs.Codec;
import utils.PageBean;
import utils.StringUtils;
/*
* 租房信息表
* @author john
*/
@Entity
@Table(name = "house")
public class House extends GenericModel{
@Id
public String id;
//出租方
@ManyToOne
public User author;
//1为隐藏,2为显示
@Column(name="status",columnDefinition="int default 1")
public int status;
//1代表待审核,2为审核不通过,3为审核通过,管理员添加的默认为3
@Column(name="audit",columnDefinition="int default 1")
public int audit;
//出租方式
@Column(name = "way")
public String way;
//您的身份
public String indentity;
//联系人
public String contacts;
//联系电话
public String phone;
//小区
@Column(name="community")
public String community;
//地址
@Column(name = "address")
public String address;
//户型
@Column(name = "bed_room")
public int bedRoom;
@Column(name = "living_rom")
public int livingRoom;
@Column(name = "bath_room")
public int bathRoom;
public double square;
//楼层
@Column(name = "current_floor")
public int currentFloor;
@Column(name = "count_floor")
public int countFloor;
//房屋情况
@Column(name = "decoration_situation")
public String decorationSituation;
@Column(name = "class_situation")
public String classSituation;
//家电配备
public String equipment;
//租金
@Column(name = "price")
public double price;
//描述
@Column(name = "details")
public String details;
//照片
@Column(name = "photo_url")
public String photoUrl;
//初始化构造方法
public House(){
this.id = Codec.UUID();
this.status=1;
this.audit=1;
}
//查询房子信息
//关键字 当前页
public static List<House> findHouses(String searchKey, int curPage) {
if (StringUtils.isEmpty(searchKey)) {
return House.all().fetch(curPage, 5);
} else {
return House.find("address like ?", "%" + searchKey + "%").fetch(
curPage, 5);
}
}
//pagebean
public static PageBean getPageBean(String searchKey, int curPage) {
long total = 0;
if (StringUtils.isEmpty(searchKey))
total = House.count();
else
total = House.find("address like ?", "%" + searchKey + "%").fetch()
.size();
return PageBean.getInstance(curPage, total, 5);
}
//是否显示
public boolean isShow(){
return status==2;
}
}
| BiaoPro/community | app/models/House.java | 858 | //楼层
| line_comment | zh-cn | package models;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import play.db.jpa.GenericModel;
import play.libs.Codec;
import utils.PageBean;
import utils.StringUtils;
/*
* 租房信息表
* @author john
*/
@Entity
@Table(name = "house")
public class House extends GenericModel{
@Id
public String id;
//出租方
@ManyToOne
public User author;
//1为隐藏,2为显示
@Column(name="status",columnDefinition="int default 1")
public int status;
//1代表待审核,2为审核不通过,3为审核通过,管理员添加的默认为3
@Column(name="audit",columnDefinition="int default 1")
public int audit;
//出租方式
@Column(name = "way")
public String way;
//您的身份
public String indentity;
//联系人
public String contacts;
//联系电话
public String phone;
//小区
@Column(name="community")
public String community;
//地址
@Column(name = "address")
public String address;
//户型
@Column(name = "bed_room")
public int bedRoom;
@Column(name = "living_rom")
public int livingRoom;
@Column(name = "bath_room")
public int bathRoom;
public double square;
//楼层 <SUF>
@Column(name = "current_floor")
public int currentFloor;
@Column(name = "count_floor")
public int countFloor;
//房屋情况
@Column(name = "decoration_situation")
public String decorationSituation;
@Column(name = "class_situation")
public String classSituation;
//家电配备
public String equipment;
//租金
@Column(name = "price")
public double price;
//描述
@Column(name = "details")
public String details;
//照片
@Column(name = "photo_url")
public String photoUrl;
//初始化构造方法
public House(){
this.id = Codec.UUID();
this.status=1;
this.audit=1;
}
//查询房子信息
//关键字 当前页
public static List<House> findHouses(String searchKey, int curPage) {
if (StringUtils.isEmpty(searchKey)) {
return House.all().fetch(curPage, 5);
} else {
return House.find("address like ?", "%" + searchKey + "%").fetch(
curPage, 5);
}
}
//pagebean
public static PageBean getPageBean(String searchKey, int curPage) {
long total = 0;
if (StringUtils.isEmpty(searchKey))
total = House.count();
else
total = House.find("address like ?", "%" + searchKey + "%").fetch()
.size();
return PageBean.getInstance(curPage, total, 5);
}
//是否显示
public boolean isShow(){
return status==2;
}
}
| 1 | 5 | 1 |
59646_59 | package Mips;
import MidCode.LLVMIR.*;
import MidCode.LLVMIR.Instruction.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class MipsGenerator {
private final IrModule module;
private final BufferedWriter writer;
private Value[] registerUsed = new Value[4];
private LinkedHashMap<Value, Integer> registerUseMap = new LinkedHashMap<>();
// 栈指针虚拟位置,初始时为0,仅用于计算偏移
private int sp = 0;
private Function currentFunction;
public MipsGenerator(IrModule module, BufferedWriter writer) {
this.module = module;
this.writer = writer;
}
public void generate() throws IOException {
generateMipsFromModule();
}
public void generateMipsFromModule() throws IOException {
// 生成全局数据段
writer.write(".data");
writer.newLine();
for (GlobalVariable var : module.getGlobalVariables()) {
writer.write(var.getMips());
writer.newLine();
var.setAddr(var.getRawName());
}
for (ConstString str: module.getConstStrings()) {
writer.write(str.getMips());
writer.newLine();
str.setAddr(str.getRawName());
}
// 添加宏
generateMipsForLibFunction();
writer.write(".text");
writer.newLine();
writer.write("jal main");
writer.newLine();
writer.write("move $a0, $v0");
writer.newLine();
writer.write("li $v0, 10");
writer.newLine();
writer.write("syscall");
writer.newLine();
for (Function func : module.getFunctions()) {
generateMipsFromFunction(func);
}
}
public void generateMipsForLibFunction() throws IOException {
// getint
writer.write(".macro getint");
writer.newLine();
writer.write("li $v0, 5");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
// putint
writer.write(".macro putint");
writer.newLine();
writer.write("li $v0, 1");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
// putch
writer.write(".macro putch");
writer.newLine();
writer.write("li $v0, 11");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
// putstr
writer.write(".macro putstr");
writer.newLine();
writer.write("li $v0, 4");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
}
public void generateMipsFromFunction(Function function) throws IOException {
currentFunction = function;
// 记录初始$sp位置
function.setPrimarySp(sp);
writer.write(function.getRawName() + ":");
writer.newLine();
// 计算函数参数地址
for (int i = function.getParams().size() - 1, offset = 0; i >=0 ; i--) {
function.getParams().get(i).setAddr(offset + sp + "");
offset += 4; // 参数大小均为4字节
}
// 保存$ra等
sp -= 4;
function.setRaAddr(sp);
allocStack(4);
saveToStack("$ra", 0);
// 为所有的中间变量分配空间
int primary = sp;
for (BasicBlock b : currentFunction.getBasicBlocks()) {
for (Value v : b.getInstructions()) {
if (v instanceof Alloca) {
sp -= ((Alloca) v).getSize();
v.setAddr("" + sp);
} else if (!(v instanceof Br ||
v instanceof Putint ||
v instanceof Putstr ||
v instanceof Ret ||
v instanceof Store
)){
sp -= 4;
v.setAddr("" + sp);
}
}
}
allocStack(primary - sp);
for (BasicBlock block : function.getBasicBlocks()) {
generateMipsFromBasicBlock(block);
}
// 恢复$ra等、释放栈空间在生成jr $ra的函数中进行
sp = function.getPrimarySp();
// 翻译完一个函数后,将registerUsed、registerUseMap清空
registerUsed = new Value[4];
registerUseMap = new LinkedHashMap<>();
}
public void generateMipsFromBasicBlock(BasicBlock block) throws IOException {
// 输出标签
if (!block.getUseList().isEmpty()) {
writer.write(block.getMipsLabel(currentFunction.getRawName()) + ": ");
writer.newLine();
}
ArrayList<Instruction> instructions = block.getInstructions();
for (Instruction instruction : instructions) {
if (instruction instanceof Alloca) {
continue;
} else if (instruction instanceof Store) {
generateMipsFromStore((Store) instruction);
} else if (instruction instanceof Load) {
generateMipsFromLoad((Load) instruction);
} else if (instruction instanceof Getelementptr) {
generateMipsFromGetelementptr((Getelementptr) instruction);
} else if (instruction instanceof Add) {
generateMipsFromAdd((Add) instruction);
} else if (instruction instanceof Sub) {
generateMipsFromSub((Sub) instruction);
} else if (instruction instanceof Mul) {
generateMipsFromMul((Mul) instruction);
} else if (instruction instanceof Sdiv) {
generateMipsFromSdiv((Sdiv) instruction);
} else if (instruction instanceof Srem) {
generateMipsFromSrem((Srem) instruction);
} else if (instruction instanceof Gt) {
generateMipsFromGt((Gt) instruction);
} else if (instruction instanceof Ge) {
generateMipsFromGe((Ge) instruction);
} else if (instruction instanceof Lt) {
generateMipsFromLt((Lt) instruction);
} else if (instruction instanceof Le) {
generateMipsFromLe((Le) instruction);
} else if (instruction instanceof Eq) {
generateMipsFromEq((Eq) instruction);
} else if (instruction instanceof Ne) {
generateMipsFromNe((Ne) instruction);
} else if (instruction instanceof Zext) {
generateMipsFromZext((Zext) instruction);
} else if (instruction instanceof Call) {
generateMipsFromCall((Call) instruction);
} else if (instruction instanceof GetInt) {
generateMipsFromGetInt((GetInt) instruction);
} else if (instruction instanceof Putint) {
generateMipsFromPutint((Putint) instruction);
} else if (instruction instanceof Putstr) {
generateMipsFromPutstr((Putstr) instruction);
} else if (instruction instanceof Ret) {
generateMipsFromRet((Ret) instruction);
} else if (instruction instanceof Br) {
generateMipsFromBr((Br) instruction);
}
}
}
private void generateMipsFromStore(Store store) throws IOException {
// 获取操作数的寄存器
Value value = store.getOperands().get(0);
int reg1 = getRegister(value);
Value address = store.getOperands().get(1);
if (address instanceof GlobalVariable) {
String label = address.getRawName();
writer.write(String.format("sw $a%d, %s", reg1, label));
writer.newLine();
} else if (address instanceof Getelementptr) {
// 地址由getelementptr计算出
int reg2 = getRegister(address);
writer.write(String.format("sw $a%d, ($a%d)", reg1, reg2));
writer.newLine();
} else if (address instanceof Alloca) {
// 必然是普通变量,地址为数值形式
int addr = Integer.parseInt(address.getAddr());
int offset = addr - sp;
writer.write(String.format("sw $a%d, %d($sp)", reg1, offset));
writer.newLine();
}
}
private void generateMipsFromLoad(Load load) throws IOException {
Value address = load.getOperands().get(0);
if (address instanceof GlobalVariable) {
String label = address.getRawName();
// 为结果分配寄存器
int reg1 = allocRegister(load);
writer.write(String.format("lw $a%d, %s", reg1, label));
writer.newLine();
} else if (address instanceof Getelementptr) {
// 地址由getelementptr计算出
int reg2 = getRegister(address);
// 为结果分配寄存器
int reg1 = allocRegister(load);
writer.write(String.format("lw $a%d, ($a%d)", reg1, reg2));
writer.newLine();
} else if (address instanceof Instruction) {
int addr = Integer.parseInt(address.getAddr());
int offset = addr - sp;
// 为结果分配寄存器
int reg1 = allocRegister(load);
writer.write(String.format("lw $a%d, %d($sp)", reg1, offset));
writer.newLine();
}
}
private void generateMipsFromGetelementptr(Getelementptr g) throws IOException {
ArrayList<Value> operands = g.getOperands();
Value address = operands.get(0);
if (address instanceof GlobalVariable) {
int reg0 = allocRegister(g);
// 全局数组,初始地址为label
writer.write(String.format("la $a%d, %s", reg0, address.getRawName()));
writer.newLine();
} else if (address instanceof Alloca) {
// 局部数组或指针,起始地址为$sp+offset
int addr = Integer.parseInt(address.getAddr());
int reg0 = allocRegister(g);
writer.write(String.format("addiu $a%d, $sp, %d", reg0, addr - sp));
writer.newLine();
} else {
// getelementptr
int reg1 = getRegister(address);
int reg0 = allocRegister(g);
writer.write(String.format("move $a%d, $a%d", reg0, reg1));
writer.newLine();
}
for (int i = 1; i < operands.size(); i++) {
int layerSize = g.getSize(i - 1);
if (operands.get(i) instanceof ConstInt) {
int offset = layerSize * ((ConstInt) operands.get(i)).getValue();
int reg0 = getRegister(g);
writer.write(String.format("addiu $a%d, $a%d, %d", reg0, reg0, offset));
writer.newLine();
} else {
int reg1 = getRegister(operands.get(i));
int reg2 = allocRegister(new Value(""));
int reg0 = getRegister(g);
writer.write(String.format("mul $a%d, $a%d, %d", reg2, reg1, layerSize));
writer.newLine();
writer.write(String.format("addu $a%d, $a%d, $a%d", reg0, reg0, reg2));
writer.newLine();
}
}
}
private void generateMipsFromAdd(Add a) throws IOException {
calculate(a, "addu");
}
private void generateMipsFromSub(Sub s) throws IOException {
calculate(s, "subu");
}
private void generateMipsFromMul(Mul m) throws IOException {
calculate(m, "mul");
}
private void generateMipsFromSdiv(Sdiv s) throws IOException {
calculate(s, "div");
}
private void generateMipsFromSrem(Srem s) throws IOException {
calculate(s, "rem");
}
private void generateMipsFromGt(Gt g) throws IOException {
calculate(g, "sgt");
}
private void generateMipsFromGe(Ge g) throws IOException {
calculate(g, "sge");
}
private void generateMipsFromLt(Lt l) throws IOException {
calculate(l, "slt");
}
private void generateMipsFromLe(Le l) throws IOException {
calculate(l, "sle");
}
private void generateMipsFromEq(Eq e) throws IOException {
calculate(e, "seq");
}
private void generateMipsFromNe(Ne n) throws IOException {
calculate(n, "sne");
}
private void calculate(Instruction instruction, String op) throws IOException {
// 命令右操作数可以为数字的命令
ArrayList<String> numberAvailable= new ArrayList<String>(){{
add("addu"); add("subu"); add("mul"); add("div"); add("rem");
}};
// 左操作数必须获取寄存器
Value left = instruction.getOperands().get(0);
int reg1 = getRegister(left);
Value right = instruction.getOperands().get(1);
if (right instanceof ConstInt && numberAvailable.contains(op)) {
// 右操作数为常量,无需获取寄存器
int val = ((ConstInt) right).getValue();
int reg0 = allocRegister(instruction);
writer.write(String.format(op + " $a%d, $a%d, %d", reg0, reg1, val));
writer.newLine();
} else {
// 其他情况,需要获取寄存器
int reg2 = getRegister(right);
int reg0 = allocRegister(instruction);
writer.write(String.format(op + " $a%d, $a%d, $a%d", reg0, reg1, reg2));
writer.newLine();
}
}
private void generateMipsFromZext(Zext zext) throws IOException {
// 由于只涉及i1到i32的转换,实际无需进行,
// 但涉及寄存器的分配,需要进行一次move
Value operand = zext.getOperands().get(0);
int reg1 = getRegister(operand);
int reg0 = allocRegister(zext);
writer.write(String.format("move $a%d, $a%d", reg0, reg1));
writer.newLine();
}
private void generateMipsFromCall(Call call) throws IOException {
// 函数调用
ArrayList<Value> operands = call.getOperands();
Function function = (Function) operands.get(0);
int primary = sp;
// 参数压栈
ArrayList<Integer> paramAddr = new ArrayList<>();
for (int i = 1; i < operands.size(); i++) {
// 参数分配栈空间
sp -= 4; // 参数大小均为4
paramAddr.add(sp);
}
// 生成分配栈空间的指令
allocStack(primary - sp);
for (int i = 1; i < operands.size(); i++) {
Value value = operands.get(i);
int addr = paramAddr.get(i - 1);
// 获取参数值所在寄存器
int reg = getRegister(value);
// 存入栈
saveToStack("$a" + reg, addr - sp);
}
// 保存现场 $a0-$a3
freeAllReg();
// 跳转
writer.write(String.format("jal %s", function.getRawName()));
writer.newLine();
// 生成释放栈空间的指令
freeStack(primary - sp);
sp = primary;
// 有返回值时,保存返回值至寄存器
if (((SymbolTable.Function)function.getSymbol()).hasReturn()) {
int reg = allocRegister(call);
writer.write("move $a" + reg + ", $v0");
writer.newLine();
}
}
private void generateMipsFromGetInt(GetInt getInt) throws IOException {
// 无需保存寄存器
// 调用宏
writer.write("getint");
writer.newLine();
// 保存$v0的值至寄存器
int reg = allocRegister(getInt);
writer.write(String.format("move $a%d, $v0", reg));
writer.newLine();
}
private void generateMipsFromPutint(Putint putint) throws IOException {
// 释放$a0
if (registerUsed[0] != null) {
freeRegister(registerUsed[0]);
}
// 传递参数
Value operand = putint.getOperands().get(0);
int reg = getRegister(operand);
if (reg != 0) {
writer.write(String.format("move $a0, $a%d", reg));
writer.newLine();
}
// 调用宏
writer.write("putint");
writer.newLine();
}
private void generateMipsFromPutstr(Putstr putstr) throws IOException {
// 释放$a0
if (registerUsed[0] != null) {
freeRegister(registerUsed[0]);
}
// 传递参数
Value operand = putstr.getOperands().get(0);
writer.write(String.format("la $a0, %s", operand.getAddr()));
writer.newLine();
// 调用宏
writer.write("putstr");
writer.newLine();
}
private void generateMipsFromRet(Ret r) throws IOException {
if (!r.getOperands().isEmpty()) {
// 返回值存入$v0
Value value = r.getOperands().get(0);
if (value instanceof ConstInt){
writer.write(String.format("li $v0, %d", ((ConstInt) value).getValue()));
writer.newLine();
} else {
int reg = getRegister(value);
writer.write(String.format("move $v0, $a%d", reg));
writer.newLine();
}
}
// 恢复$ra等
loadFromStack("$ra", currentFunction.getRaAddr() - sp);
// 释放栈空间
freeStack(currentFunction.getPrimarySp() - sp);
// 函数返回时,需释放$a0-$a3,但不需存回栈空间
freeAllRegWithoutStore();
// 返回
writer.write("jr $ra");
writer.newLine();
}
private void generateMipsFromBr(Br b) throws IOException {
ArrayList<Value> operands = b.getOperands();
if (operands.size() == 1) {
// 离开基本块前,释放寄存器
freeAllRegWithoutStore();
BasicBlock block = (BasicBlock) operands.get(0);
writer.write("j " + block.getMipsLabel(currentFunction.getRawName()));
writer.newLine();
} else {
Value cond = operands.get(0);
BasicBlock trueBlock = (BasicBlock) operands.get(1);
BasicBlock falseBlock = (BasicBlock) operands.get(2);
int reg = getRegister(cond);
// 离开基本块前,释放寄存器
freeAllRegWithoutStore();
writer.write(String.format("beqz $a%d, %s", reg, falseBlock.getMipsLabel(currentFunction.getRawName())));
writer.newLine();
writer.write(String.format("j %s", trueBlock.getMipsLabel(currentFunction.getRawName())));
writer.newLine();
}
}
private void allocStack(int size) throws IOException {
if (size == 0) {
return;
}
// 分配栈空间
writer.write("addiu $sp, $sp, " + (-size));
writer.newLine();
}
private void freeStack(int size) throws IOException {
if (size == 0) {
return;
}
// 释放栈空间
writer.write("addiu $sp, $sp, " + size);
writer.newLine();
}
private void saveToStack(String reg, int offset) throws IOException {
writer.write(String.format("sw %s, %d($sp)", reg, offset));
writer.newLine();
}
private void loadFromStack(String reg, int offset) throws IOException {
writer.write(String.format("lw %s, %d($sp)", reg, offset));
writer.newLine();
}
private int allocRegister(Value value) throws IOException {
for (int i = 0; i < 4; i++) {
if (registerUsed[i] == null) {
// 记录分配情况
registerUsed[i] = value;
registerUseMap.put(value, i);
return i;
}
}
// 无空闲寄存器,需要释放
// 释放未访问时间最长的
Value v = registerUseMap.keySet().iterator().next();
int reg = registerUseMap.get(v);
freeRegister(v);
// 记录分配情况
registerUsed[reg] = value;
registerUseMap.put(value, reg);
return reg;
}
// 用于获取操作数(中间变量)所在的寄存器
private int getRegister(Value value) throws IOException {
if (registerUseMap.containsKey(value)) {
// 获取后更新访问时间
int reg = registerUseMap.get(value);
registerUseMap.remove(value);
registerUseMap.put(value, reg);
return reg;
}
if (value instanceof ConstInt) {
// 对于常量,分配一个寄存器,并通过li赋值
int reg = allocRegister(value);
writer.write(String.format("li $a%d, %d", reg, ((ConstInt) value).getValue()));
writer.newLine();
return reg;
}
// 中间变量不在内存,需要分配寄存器并读入内存
int reg = allocRegister(value);
loadFromStack("$a" + reg, Integer.parseInt(value.getAddr()) - sp);
return reg;
}
private void freeRegister(Value value) throws IOException {
int reg = registerUseMap.get(value);
if (value instanceof Instruction) {
// 保存至栈
saveToStack("$a" + reg, Integer.parseInt(value.getAddr()) - sp);
}
registerUsed[reg] = null;
registerUseMap.remove(value);
}
// 释放$a0-$a3,将值存回栈空间
private void freeAllReg() throws IOException {
for (Value value : registerUseMap.keySet()) {
int reg = registerUseMap.get(value);
if (registerUsed[reg] instanceof Instruction){
// 保存至栈
saveToStack("$a" + reg, Integer.parseInt(registerUsed[reg].getAddr()) - sp);
}
registerUsed[reg] = null;
}
registerUseMap.clear();
}
// 释放$a0-$a3,值不存回栈空间
private void freeAllRegWithoutStore() {
registerUsed = new Value[4];
registerUseMap.clear();
}
}
| BienBoy/BUAA-Compiler-2023 | src/Mips/MipsGenerator.java | 5,908 | // 无空闲寄存器,需要释放 | line_comment | zh-cn | package Mips;
import MidCode.LLVMIR.*;
import MidCode.LLVMIR.Instruction.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class MipsGenerator {
private final IrModule module;
private final BufferedWriter writer;
private Value[] registerUsed = new Value[4];
private LinkedHashMap<Value, Integer> registerUseMap = new LinkedHashMap<>();
// 栈指针虚拟位置,初始时为0,仅用于计算偏移
private int sp = 0;
private Function currentFunction;
public MipsGenerator(IrModule module, BufferedWriter writer) {
this.module = module;
this.writer = writer;
}
public void generate() throws IOException {
generateMipsFromModule();
}
public void generateMipsFromModule() throws IOException {
// 生成全局数据段
writer.write(".data");
writer.newLine();
for (GlobalVariable var : module.getGlobalVariables()) {
writer.write(var.getMips());
writer.newLine();
var.setAddr(var.getRawName());
}
for (ConstString str: module.getConstStrings()) {
writer.write(str.getMips());
writer.newLine();
str.setAddr(str.getRawName());
}
// 添加宏
generateMipsForLibFunction();
writer.write(".text");
writer.newLine();
writer.write("jal main");
writer.newLine();
writer.write("move $a0, $v0");
writer.newLine();
writer.write("li $v0, 10");
writer.newLine();
writer.write("syscall");
writer.newLine();
for (Function func : module.getFunctions()) {
generateMipsFromFunction(func);
}
}
public void generateMipsForLibFunction() throws IOException {
// getint
writer.write(".macro getint");
writer.newLine();
writer.write("li $v0, 5");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
// putint
writer.write(".macro putint");
writer.newLine();
writer.write("li $v0, 1");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
// putch
writer.write(".macro putch");
writer.newLine();
writer.write("li $v0, 11");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
// putstr
writer.write(".macro putstr");
writer.newLine();
writer.write("li $v0, 4");
writer.newLine();
writer.write("syscall");
writer.newLine();
writer.write(".end_macro");
writer.newLine();
}
public void generateMipsFromFunction(Function function) throws IOException {
currentFunction = function;
// 记录初始$sp位置
function.setPrimarySp(sp);
writer.write(function.getRawName() + ":");
writer.newLine();
// 计算函数参数地址
for (int i = function.getParams().size() - 1, offset = 0; i >=0 ; i--) {
function.getParams().get(i).setAddr(offset + sp + "");
offset += 4; // 参数大小均为4字节
}
// 保存$ra等
sp -= 4;
function.setRaAddr(sp);
allocStack(4);
saveToStack("$ra", 0);
// 为所有的中间变量分配空间
int primary = sp;
for (BasicBlock b : currentFunction.getBasicBlocks()) {
for (Value v : b.getInstructions()) {
if (v instanceof Alloca) {
sp -= ((Alloca) v).getSize();
v.setAddr("" + sp);
} else if (!(v instanceof Br ||
v instanceof Putint ||
v instanceof Putstr ||
v instanceof Ret ||
v instanceof Store
)){
sp -= 4;
v.setAddr("" + sp);
}
}
}
allocStack(primary - sp);
for (BasicBlock block : function.getBasicBlocks()) {
generateMipsFromBasicBlock(block);
}
// 恢复$ra等、释放栈空间在生成jr $ra的函数中进行
sp = function.getPrimarySp();
// 翻译完一个函数后,将registerUsed、registerUseMap清空
registerUsed = new Value[4];
registerUseMap = new LinkedHashMap<>();
}
public void generateMipsFromBasicBlock(BasicBlock block) throws IOException {
// 输出标签
if (!block.getUseList().isEmpty()) {
writer.write(block.getMipsLabel(currentFunction.getRawName()) + ": ");
writer.newLine();
}
ArrayList<Instruction> instructions = block.getInstructions();
for (Instruction instruction : instructions) {
if (instruction instanceof Alloca) {
continue;
} else if (instruction instanceof Store) {
generateMipsFromStore((Store) instruction);
} else if (instruction instanceof Load) {
generateMipsFromLoad((Load) instruction);
} else if (instruction instanceof Getelementptr) {
generateMipsFromGetelementptr((Getelementptr) instruction);
} else if (instruction instanceof Add) {
generateMipsFromAdd((Add) instruction);
} else if (instruction instanceof Sub) {
generateMipsFromSub((Sub) instruction);
} else if (instruction instanceof Mul) {
generateMipsFromMul((Mul) instruction);
} else if (instruction instanceof Sdiv) {
generateMipsFromSdiv((Sdiv) instruction);
} else if (instruction instanceof Srem) {
generateMipsFromSrem((Srem) instruction);
} else if (instruction instanceof Gt) {
generateMipsFromGt((Gt) instruction);
} else if (instruction instanceof Ge) {
generateMipsFromGe((Ge) instruction);
} else if (instruction instanceof Lt) {
generateMipsFromLt((Lt) instruction);
} else if (instruction instanceof Le) {
generateMipsFromLe((Le) instruction);
} else if (instruction instanceof Eq) {
generateMipsFromEq((Eq) instruction);
} else if (instruction instanceof Ne) {
generateMipsFromNe((Ne) instruction);
} else if (instruction instanceof Zext) {
generateMipsFromZext((Zext) instruction);
} else if (instruction instanceof Call) {
generateMipsFromCall((Call) instruction);
} else if (instruction instanceof GetInt) {
generateMipsFromGetInt((GetInt) instruction);
} else if (instruction instanceof Putint) {
generateMipsFromPutint((Putint) instruction);
} else if (instruction instanceof Putstr) {
generateMipsFromPutstr((Putstr) instruction);
} else if (instruction instanceof Ret) {
generateMipsFromRet((Ret) instruction);
} else if (instruction instanceof Br) {
generateMipsFromBr((Br) instruction);
}
}
}
private void generateMipsFromStore(Store store) throws IOException {
// 获取操作数的寄存器
Value value = store.getOperands().get(0);
int reg1 = getRegister(value);
Value address = store.getOperands().get(1);
if (address instanceof GlobalVariable) {
String label = address.getRawName();
writer.write(String.format("sw $a%d, %s", reg1, label));
writer.newLine();
} else if (address instanceof Getelementptr) {
// 地址由getelementptr计算出
int reg2 = getRegister(address);
writer.write(String.format("sw $a%d, ($a%d)", reg1, reg2));
writer.newLine();
} else if (address instanceof Alloca) {
// 必然是普通变量,地址为数值形式
int addr = Integer.parseInt(address.getAddr());
int offset = addr - sp;
writer.write(String.format("sw $a%d, %d($sp)", reg1, offset));
writer.newLine();
}
}
private void generateMipsFromLoad(Load load) throws IOException {
Value address = load.getOperands().get(0);
if (address instanceof GlobalVariable) {
String label = address.getRawName();
// 为结果分配寄存器
int reg1 = allocRegister(load);
writer.write(String.format("lw $a%d, %s", reg1, label));
writer.newLine();
} else if (address instanceof Getelementptr) {
// 地址由getelementptr计算出
int reg2 = getRegister(address);
// 为结果分配寄存器
int reg1 = allocRegister(load);
writer.write(String.format("lw $a%d, ($a%d)", reg1, reg2));
writer.newLine();
} else if (address instanceof Instruction) {
int addr = Integer.parseInt(address.getAddr());
int offset = addr - sp;
// 为结果分配寄存器
int reg1 = allocRegister(load);
writer.write(String.format("lw $a%d, %d($sp)", reg1, offset));
writer.newLine();
}
}
private void generateMipsFromGetelementptr(Getelementptr g) throws IOException {
ArrayList<Value> operands = g.getOperands();
Value address = operands.get(0);
if (address instanceof GlobalVariable) {
int reg0 = allocRegister(g);
// 全局数组,初始地址为label
writer.write(String.format("la $a%d, %s", reg0, address.getRawName()));
writer.newLine();
} else if (address instanceof Alloca) {
// 局部数组或指针,起始地址为$sp+offset
int addr = Integer.parseInt(address.getAddr());
int reg0 = allocRegister(g);
writer.write(String.format("addiu $a%d, $sp, %d", reg0, addr - sp));
writer.newLine();
} else {
// getelementptr
int reg1 = getRegister(address);
int reg0 = allocRegister(g);
writer.write(String.format("move $a%d, $a%d", reg0, reg1));
writer.newLine();
}
for (int i = 1; i < operands.size(); i++) {
int layerSize = g.getSize(i - 1);
if (operands.get(i) instanceof ConstInt) {
int offset = layerSize * ((ConstInt) operands.get(i)).getValue();
int reg0 = getRegister(g);
writer.write(String.format("addiu $a%d, $a%d, %d", reg0, reg0, offset));
writer.newLine();
} else {
int reg1 = getRegister(operands.get(i));
int reg2 = allocRegister(new Value(""));
int reg0 = getRegister(g);
writer.write(String.format("mul $a%d, $a%d, %d", reg2, reg1, layerSize));
writer.newLine();
writer.write(String.format("addu $a%d, $a%d, $a%d", reg0, reg0, reg2));
writer.newLine();
}
}
}
private void generateMipsFromAdd(Add a) throws IOException {
calculate(a, "addu");
}
private void generateMipsFromSub(Sub s) throws IOException {
calculate(s, "subu");
}
private void generateMipsFromMul(Mul m) throws IOException {
calculate(m, "mul");
}
private void generateMipsFromSdiv(Sdiv s) throws IOException {
calculate(s, "div");
}
private void generateMipsFromSrem(Srem s) throws IOException {
calculate(s, "rem");
}
private void generateMipsFromGt(Gt g) throws IOException {
calculate(g, "sgt");
}
private void generateMipsFromGe(Ge g) throws IOException {
calculate(g, "sge");
}
private void generateMipsFromLt(Lt l) throws IOException {
calculate(l, "slt");
}
private void generateMipsFromLe(Le l) throws IOException {
calculate(l, "sle");
}
private void generateMipsFromEq(Eq e) throws IOException {
calculate(e, "seq");
}
private void generateMipsFromNe(Ne n) throws IOException {
calculate(n, "sne");
}
private void calculate(Instruction instruction, String op) throws IOException {
// 命令右操作数可以为数字的命令
ArrayList<String> numberAvailable= new ArrayList<String>(){{
add("addu"); add("subu"); add("mul"); add("div"); add("rem");
}};
// 左操作数必须获取寄存器
Value left = instruction.getOperands().get(0);
int reg1 = getRegister(left);
Value right = instruction.getOperands().get(1);
if (right instanceof ConstInt && numberAvailable.contains(op)) {
// 右操作数为常量,无需获取寄存器
int val = ((ConstInt) right).getValue();
int reg0 = allocRegister(instruction);
writer.write(String.format(op + " $a%d, $a%d, %d", reg0, reg1, val));
writer.newLine();
} else {
// 其他情况,需要获取寄存器
int reg2 = getRegister(right);
int reg0 = allocRegister(instruction);
writer.write(String.format(op + " $a%d, $a%d, $a%d", reg0, reg1, reg2));
writer.newLine();
}
}
private void generateMipsFromZext(Zext zext) throws IOException {
// 由于只涉及i1到i32的转换,实际无需进行,
// 但涉及寄存器的分配,需要进行一次move
Value operand = zext.getOperands().get(0);
int reg1 = getRegister(operand);
int reg0 = allocRegister(zext);
writer.write(String.format("move $a%d, $a%d", reg0, reg1));
writer.newLine();
}
private void generateMipsFromCall(Call call) throws IOException {
// 函数调用
ArrayList<Value> operands = call.getOperands();
Function function = (Function) operands.get(0);
int primary = sp;
// 参数压栈
ArrayList<Integer> paramAddr = new ArrayList<>();
for (int i = 1; i < operands.size(); i++) {
// 参数分配栈空间
sp -= 4; // 参数大小均为4
paramAddr.add(sp);
}
// 生成分配栈空间的指令
allocStack(primary - sp);
for (int i = 1; i < operands.size(); i++) {
Value value = operands.get(i);
int addr = paramAddr.get(i - 1);
// 获取参数值所在寄存器
int reg = getRegister(value);
// 存入栈
saveToStack("$a" + reg, addr - sp);
}
// 保存现场 $a0-$a3
freeAllReg();
// 跳转
writer.write(String.format("jal %s", function.getRawName()));
writer.newLine();
// 生成释放栈空间的指令
freeStack(primary - sp);
sp = primary;
// 有返回值时,保存返回值至寄存器
if (((SymbolTable.Function)function.getSymbol()).hasReturn()) {
int reg = allocRegister(call);
writer.write("move $a" + reg + ", $v0");
writer.newLine();
}
}
private void generateMipsFromGetInt(GetInt getInt) throws IOException {
// 无需保存寄存器
// 调用宏
writer.write("getint");
writer.newLine();
// 保存$v0的值至寄存器
int reg = allocRegister(getInt);
writer.write(String.format("move $a%d, $v0", reg));
writer.newLine();
}
private void generateMipsFromPutint(Putint putint) throws IOException {
// 释放$a0
if (registerUsed[0] != null) {
freeRegister(registerUsed[0]);
}
// 传递参数
Value operand = putint.getOperands().get(0);
int reg = getRegister(operand);
if (reg != 0) {
writer.write(String.format("move $a0, $a%d", reg));
writer.newLine();
}
// 调用宏
writer.write("putint");
writer.newLine();
}
private void generateMipsFromPutstr(Putstr putstr) throws IOException {
// 释放$a0
if (registerUsed[0] != null) {
freeRegister(registerUsed[0]);
}
// 传递参数
Value operand = putstr.getOperands().get(0);
writer.write(String.format("la $a0, %s", operand.getAddr()));
writer.newLine();
// 调用宏
writer.write("putstr");
writer.newLine();
}
private void generateMipsFromRet(Ret r) throws IOException {
if (!r.getOperands().isEmpty()) {
// 返回值存入$v0
Value value = r.getOperands().get(0);
if (value instanceof ConstInt){
writer.write(String.format("li $v0, %d", ((ConstInt) value).getValue()));
writer.newLine();
} else {
int reg = getRegister(value);
writer.write(String.format("move $v0, $a%d", reg));
writer.newLine();
}
}
// 恢复$ra等
loadFromStack("$ra", currentFunction.getRaAddr() - sp);
// 释放栈空间
freeStack(currentFunction.getPrimarySp() - sp);
// 函数返回时,需释放$a0-$a3,但不需存回栈空间
freeAllRegWithoutStore();
// 返回
writer.write("jr $ra");
writer.newLine();
}
private void generateMipsFromBr(Br b) throws IOException {
ArrayList<Value> operands = b.getOperands();
if (operands.size() == 1) {
// 离开基本块前,释放寄存器
freeAllRegWithoutStore();
BasicBlock block = (BasicBlock) operands.get(0);
writer.write("j " + block.getMipsLabel(currentFunction.getRawName()));
writer.newLine();
} else {
Value cond = operands.get(0);
BasicBlock trueBlock = (BasicBlock) operands.get(1);
BasicBlock falseBlock = (BasicBlock) operands.get(2);
int reg = getRegister(cond);
// 离开基本块前,释放寄存器
freeAllRegWithoutStore();
writer.write(String.format("beqz $a%d, %s", reg, falseBlock.getMipsLabel(currentFunction.getRawName())));
writer.newLine();
writer.write(String.format("j %s", trueBlock.getMipsLabel(currentFunction.getRawName())));
writer.newLine();
}
}
private void allocStack(int size) throws IOException {
if (size == 0) {
return;
}
// 分配栈空间
writer.write("addiu $sp, $sp, " + (-size));
writer.newLine();
}
private void freeStack(int size) throws IOException {
if (size == 0) {
return;
}
// 释放栈空间
writer.write("addiu $sp, $sp, " + size);
writer.newLine();
}
private void saveToStack(String reg, int offset) throws IOException {
writer.write(String.format("sw %s, %d($sp)", reg, offset));
writer.newLine();
}
private void loadFromStack(String reg, int offset) throws IOException {
writer.write(String.format("lw %s, %d($sp)", reg, offset));
writer.newLine();
}
private int allocRegister(Value value) throws IOException {
for (int i = 0; i < 4; i++) {
if (registerUsed[i] == null) {
// 记录分配情况
registerUsed[i] = value;
registerUseMap.put(value, i);
return i;
}
}
// 无空 <SUF>
// 释放未访问时间最长的
Value v = registerUseMap.keySet().iterator().next();
int reg = registerUseMap.get(v);
freeRegister(v);
// 记录分配情况
registerUsed[reg] = value;
registerUseMap.put(value, reg);
return reg;
}
// 用于获取操作数(中间变量)所在的寄存器
private int getRegister(Value value) throws IOException {
if (registerUseMap.containsKey(value)) {
// 获取后更新访问时间
int reg = registerUseMap.get(value);
registerUseMap.remove(value);
registerUseMap.put(value, reg);
return reg;
}
if (value instanceof ConstInt) {
// 对于常量,分配一个寄存器,并通过li赋值
int reg = allocRegister(value);
writer.write(String.format("li $a%d, %d", reg, ((ConstInt) value).getValue()));
writer.newLine();
return reg;
}
// 中间变量不在内存,需要分配寄存器并读入内存
int reg = allocRegister(value);
loadFromStack("$a" + reg, Integer.parseInt(value.getAddr()) - sp);
return reg;
}
private void freeRegister(Value value) throws IOException {
int reg = registerUseMap.get(value);
if (value instanceof Instruction) {
// 保存至栈
saveToStack("$a" + reg, Integer.parseInt(value.getAddr()) - sp);
}
registerUsed[reg] = null;
registerUseMap.remove(value);
}
// 释放$a0-$a3,将值存回栈空间
private void freeAllReg() throws IOException {
for (Value value : registerUseMap.keySet()) {
int reg = registerUseMap.get(value);
if (registerUsed[reg] instanceof Instruction){
// 保存至栈
saveToStack("$a" + reg, Integer.parseInt(registerUsed[reg].getAddr()) - sp);
}
registerUsed[reg] = null;
}
registerUseMap.clear();
}
// 释放$a0-$a3,值不存回栈空间
private void freeAllRegWithoutStore() {
registerUsed = new Value[4];
registerUseMap.clear();
}
}
| 1 | 14 | 1 |
3583_11 | package com.kit.widget.scrollview;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;
/**
* 自定义ScrollView 实现弹性回弹功能
*/
public class ReboundScrollView2 extends ScrollView {
private View inner;// 孩子
private float y;// 坐标
private Rect normal = new Rect();// 矩形空白
public ReboundScrollView2(Context context, AttributeSet attrs) {
super(context, attrs);
}
/***
* 根据 XML 生成视图工作完成.该函数在生成视图的最后调用,在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate
* 方法,也应该调用父类的方法,使该方法得以执行.
*/
@Override
protected void onFinishInflate() {
if (getChildCount() > 0) {
inner = getChildAt(0);// 获取其孩子
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (inner != null) {
commOnTouchEvent(ev);
}
return super.onTouchEvent(ev);
}
/***
* 触摸事件
*
* @param ev
*/
public void commOnTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
y = ev.getY();// 获取点击y坐标
break;
case MotionEvent.ACTION_UP:
if (isNeedAnimation()) {
animation();
}
break;
case MotionEvent.ACTION_MOVE:
final float preY = y;
float nowY = ev.getY();
int deltaY = (int) (preY - nowY);// 获取滑动距离
y = nowY;
// 当滚动到最上或者最下时就不会再滚动,这时移动布局
if (isNeedMove()) {
if (normal.isEmpty()) {
// 填充矩形,目的:就是告诉this:我现在已经有了,你松开的时候记得要执行回归动画.
normal.set(inner.getLeft(), inner.getTop(),
inner.getRight(), inner.getBottom());
}
// 移动布局
inner.layout(inner.getLeft(), inner.getTop() - deltaY / 4,
inner.getRight(), inner.getBottom() - deltaY / 4);
}
break;
default:
break;
}
}
/***
* 开启动画移动
*/
public void animation() {
// 开启移动动画
TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(),
normal.top);
ta.setDuration(300);
inner.startAnimation(ta);
// 设置回到正常的布局位置
inner.layout(normal.left, normal.top, normal.right, normal.bottom);
normal.setEmpty();// 清空矩形
}
/***
* 是否需要开启动画
*
* 如果矩形不为空,返回true,否则返回false.
*
*
* @return
*/
public boolean isNeedAnimation() {
return !normal.isEmpty();
}
/***
* 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的高度
* getHeight():获取的是当前控件在屏幕中显示的高度
*
* @return
*/
public boolean isNeedMove() {
int offset = inner.getMeasuredHeight() - getHeight();
int scrollY = getScrollY();
// 0是顶部,后面那个是底部
if (scrollY == 0 || scrollY == offset) {
return true;
}
return false;
}
}
| BigAppOS/BigApp_Discuz_Android | libs/ZUtilsExtWidget/src/com/kit/widget/scrollview/ReboundScrollView2.java | 959 | // 开启移动动画 | line_comment | zh-cn | package com.kit.widget.scrollview;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;
/**
* 自定义ScrollView 实现弹性回弹功能
*/
public class ReboundScrollView2 extends ScrollView {
private View inner;// 孩子
private float y;// 坐标
private Rect normal = new Rect();// 矩形空白
public ReboundScrollView2(Context context, AttributeSet attrs) {
super(context, attrs);
}
/***
* 根据 XML 生成视图工作完成.该函数在生成视图的最后调用,在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate
* 方法,也应该调用父类的方法,使该方法得以执行.
*/
@Override
protected void onFinishInflate() {
if (getChildCount() > 0) {
inner = getChildAt(0);// 获取其孩子
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (inner != null) {
commOnTouchEvent(ev);
}
return super.onTouchEvent(ev);
}
/***
* 触摸事件
*
* @param ev
*/
public void commOnTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
y = ev.getY();// 获取点击y坐标
break;
case MotionEvent.ACTION_UP:
if (isNeedAnimation()) {
animation();
}
break;
case MotionEvent.ACTION_MOVE:
final float preY = y;
float nowY = ev.getY();
int deltaY = (int) (preY - nowY);// 获取滑动距离
y = nowY;
// 当滚动到最上或者最下时就不会再滚动,这时移动布局
if (isNeedMove()) {
if (normal.isEmpty()) {
// 填充矩形,目的:就是告诉this:我现在已经有了,你松开的时候记得要执行回归动画.
normal.set(inner.getLeft(), inner.getTop(),
inner.getRight(), inner.getBottom());
}
// 移动布局
inner.layout(inner.getLeft(), inner.getTop() - deltaY / 4,
inner.getRight(), inner.getBottom() - deltaY / 4);
}
break;
default:
break;
}
}
/***
* 开启动画移动
*/
public void animation() {
// 开启 <SUF>
TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(),
normal.top);
ta.setDuration(300);
inner.startAnimation(ta);
// 设置回到正常的布局位置
inner.layout(normal.left, normal.top, normal.right, normal.bottom);
normal.setEmpty();// 清空矩形
}
/***
* 是否需要开启动画
*
* 如果矩形不为空,返回true,否则返回false.
*
*
* @return
*/
public boolean isNeedAnimation() {
return !normal.isEmpty();
}
/***
* 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的高度
* getHeight():获取的是当前控件在屏幕中显示的高度
*
* @return
*/
public boolean isNeedMove() {
int offset = inner.getMeasuredHeight() - getHeight();
int scrollY = getScrollY();
// 0是顶部,后面那个是底部
if (scrollY == 0 || scrollY == offset) {
return true;
}
return false;
}
}
| 1 | 9 | 1 |
47338_13 | package com.bigModel.backend.utils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class chatGPT {
public static HashMap<String, String> getAnswer(String content) {
final String apiKey = "sk-BXsVgXDpYvWRQLBM1b6d88Ac70Cc4eB094289a6f5411A692";
final String baseUrl = "https://aihubmix.com/v1";
final String model = "gpt-3.5-turbo";
System.out.println("进入chatGPT分析");
HashMap<String, String> answerHash = new HashMap<>();
answerHash.put("content", content);
// try {
// // Replace "sk-xxx" with your actual API key
// String apiKey = "sk-LvLWgzMybUVMovfA0355Ec8599Fb42A7A9D163D4041fD94c";
//
// // Replace "https://orisound.cn//v1" with the actual base URL
// String baseUrl = "https://aihubmix.com";
//
// URL url = new URL(baseUrl + "/chat/completions");
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Authorization", "Bearer " + apiKey);
// connection.setDoOutput(true);
//
// // Replace "Say this is a test" with your actual message
// String userMessage = "请记住,你是一位语句分析师,能够对句子按照类别库进行分类。类别库包括:枪支、毒品、诈骗、洗钱、赌博、网安威胁、反共反体制、民运、组党结社、维权抗议、民族分裂、宗教极端、非法宗教、恐怖暴力、海外利益等。句子如下 " + content + " 如果你发现句子包含上述类别或者可能即将进行或者正在进行的游行示威活动,如果包含,只需返回是,如果不包含,只需返回否。";
//
// String payload = "{\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"" + userMessage + "\"\n }\n ],\n \"model\": \"gpt-3.5-turbo\"\n}";
//
//
// try (OutputStream os = connection.getOutputStream()) {
// byte[] input = payload.getBytes("utf-8");
// os.write(input, 0, input.length);
// }
//
// try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
// StringBuilder response = new StringBuilder();
// String responseLine;
// while ((responseLine = br.readLine()) != null) {
// response.append(responseLine.trim());
// }
// System.out.println("原始" + response);
// String res = response.substring(response.indexOf("\"content\""));
// String[] tmp = res.split("\"");
// System.out.println(tmp[3]);
// answerHash.put("answer", tmp[3]);
// }
// connection.disconnect();
// } catch (Exception e) {
// e.printStackTrace();
// }
RestTemplate restTemplate = new RestTemplate();
String userMessage = "请记住,你是一位语句分析师,能够对句子按照类别库进行分类。类别库包括:枪支、毒品、诈骗、洗钱、赌博、网安威胁、反共反体制、民运、组党结社、维权抗议、民族分裂、宗教极端、非法宗教、恐怖暴力、海外利益等。句子如下 " + content + " 如果你发现句子包含上述类别或者可能即将进行或者正在进行的游行示威活动,只需返回是,反之只需返回否。无需返回任何其他答案。";
// Create a JSON request payload
String jsonPayload = "{ \"messages\": [ { \"role\": \"user\", \"content\": \"" + userMessage + "\" } ], \"model\": \"" + model + "\" }";
String endpoint = baseUrl + "/chat/completions";
// Set headers
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
headers.set("Authorization", "Bearer " + apiKey);
// Create the request
HttpEntity<String> entity = new HttpEntity<>(jsonPayload, headers);
// Make the request
ResponseEntity<String> response = restTemplate.exchange(endpoint, HttpMethod.POST, entity, String.class);
String strResponse = response.toString();
String res = strResponse.substring(strResponse.indexOf("\"content\""));
String[] tmp = res.split("\"");
answerHash.put("answer", tmp[3]);
return answerHash;
}
}
| BigModelCQUPT/WebSite | backend/src/main/java/com/bigModel/backend/utils/chatGPT.java | 1,314 | // String userMessage = "请记住,你是一位语句分析师,能够对句子按照类别库进行分类。类别库包括:枪支、毒品、诈骗、洗钱、赌博、网安威胁、反共反体制、民运、组党结社、维权抗议、民族分裂、宗教极端、非法宗教、恐怖暴力、海外利益等。句子如下 " + content + " 如果你发现句子包含上述类别或者可能即将进行或者正在进行的游行示威活动,如果包含,只需返回是,如果不包含,只需返回否。"; | line_comment | zh-cn | package com.bigModel.backend.utils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class chatGPT {
public static HashMap<String, String> getAnswer(String content) {
final String apiKey = "sk-BXsVgXDpYvWRQLBM1b6d88Ac70Cc4eB094289a6f5411A692";
final String baseUrl = "https://aihubmix.com/v1";
final String model = "gpt-3.5-turbo";
System.out.println("进入chatGPT分析");
HashMap<String, String> answerHash = new HashMap<>();
answerHash.put("content", content);
// try {
// // Replace "sk-xxx" with your actual API key
// String apiKey = "sk-LvLWgzMybUVMovfA0355Ec8599Fb42A7A9D163D4041fD94c";
//
// // Replace "https://orisound.cn//v1" with the actual base URL
// String baseUrl = "https://aihubmix.com";
//
// URL url = new URL(baseUrl + "/chat/completions");
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Authorization", "Bearer " + apiKey);
// connection.setDoOutput(true);
//
// // Replace "Say this is a test" with your actual message
// St <SUF>
//
// String payload = "{\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"" + userMessage + "\"\n }\n ],\n \"model\": \"gpt-3.5-turbo\"\n}";
//
//
// try (OutputStream os = connection.getOutputStream()) {
// byte[] input = payload.getBytes("utf-8");
// os.write(input, 0, input.length);
// }
//
// try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
// StringBuilder response = new StringBuilder();
// String responseLine;
// while ((responseLine = br.readLine()) != null) {
// response.append(responseLine.trim());
// }
// System.out.println("原始" + response);
// String res = response.substring(response.indexOf("\"content\""));
// String[] tmp = res.split("\"");
// System.out.println(tmp[3]);
// answerHash.put("answer", tmp[3]);
// }
// connection.disconnect();
// } catch (Exception e) {
// e.printStackTrace();
// }
RestTemplate restTemplate = new RestTemplate();
String userMessage = "请记住,你是一位语句分析师,能够对句子按照类别库进行分类。类别库包括:枪支、毒品、诈骗、洗钱、赌博、网安威胁、反共反体制、民运、组党结社、维权抗议、民族分裂、宗教极端、非法宗教、恐怖暴力、海外利益等。句子如下 " + content + " 如果你发现句子包含上述类别或者可能即将进行或者正在进行的游行示威活动,只需返回是,反之只需返回否。无需返回任何其他答案。";
// Create a JSON request payload
String jsonPayload = "{ \"messages\": [ { \"role\": \"user\", \"content\": \"" + userMessage + "\" } ], \"model\": \"" + model + "\" }";
String endpoint = baseUrl + "/chat/completions";
// Set headers
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
headers.set("Authorization", "Bearer " + apiKey);
// Create the request
HttpEntity<String> entity = new HttpEntity<>(jsonPayload, headers);
// Make the request
ResponseEntity<String> response = restTemplate.exchange(endpoint, HttpMethod.POST, entity, String.class);
String strResponse = response.toString();
String res = strResponse.substring(strResponse.indexOf("\"content\""));
String[] tmp = res.split("\"");
answerHash.put("answer", tmp[3]);
return answerHash;
}
}
| 0 | 217 | 0 |
10611_35 | package com.bigkoo.pickerviewdemo;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bigkoo.pickerviewdemo.bean.CardBean;
import com.bigkoo.pickerviewdemo.bean.ProvinceBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayList<ProvinceBean> options1Items = new ArrayList<>();
private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
private Button btn_Options;
private Button btn_CustomOptions;
private Button btn_CustomTime;
private TimePickerView pvTime, pvCustomTime, pvCustomLunar;
private OptionsPickerView pvOptions, pvCustomOptions, pvNoLinkOptions;
private ArrayList<CardBean> cardItem = new ArrayList<>();
private ArrayList<String> food = new ArrayList<>();
private ArrayList<String> clothes = new ArrayList<>();
private ArrayList<String> computer = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//等数据加载完毕再初始化并显示Picker,以免还未加载完数据就显示,造成APP崩溃。
getOptionData();
initTimePicker();
initCustomTimePicker();
initLunarPicker();
initOptionPicker();
initCustomOptionPicker();
initNoLinkOptionsPicker();
Button btn_Time = (Button) findViewById(R.id.btn_Time);
btn_Options = (Button) findViewById(R.id.btn_Options);
btn_CustomOptions = (Button) findViewById(R.id.btn_CustomOptions);
btn_CustomTime = (Button) findViewById(R.id.btn_CustomTime);
Button btn_no_linkage = (Button) findViewById(R.id.btn_no_linkage);
Button btn_to_Fragment = (Button) findViewById(R.id.btn_fragment);
Button btn_circle = (Button) findViewById(R.id.btn_circle);
btn_Time.setOnClickListener(this);
btn_Options.setOnClickListener(this);
btn_CustomOptions.setOnClickListener(this);
btn_CustomTime.setOnClickListener(this);
btn_no_linkage.setOnClickListener(this);
btn_to_Fragment.setOnClickListener(this);
btn_circle.setOnClickListener(this);
findViewById(R.id.btn_GotoJsonData).setOnClickListener(this);
findViewById(R.id.btn_lunar).setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_Time && pvTime != null) {
// pvTime.setDate(Calendar.getInstance());
/* pvTime.show(); //show timePicker*/
pvTime.show(v);//弹出时间选择器,传递参数过去,回调的时候则可以绑定此view
} else if (v.getId() == R.id.btn_Options && pvOptions != null) {
pvOptions.show(); //弹出条件选择器
} else if (v.getId() == R.id.btn_CustomOptions && pvCustomOptions != null) {
pvCustomOptions.show(); //弹出自定义条件选择器
} else if (v.getId() == R.id.btn_CustomTime && pvCustomTime != null) {
pvCustomTime.show(); //弹出自定义时间选择器
} else if (v.getId() == R.id.btn_no_linkage && pvNoLinkOptions != null) {//不联动数据选择器
pvNoLinkOptions.show();
} else if (v.getId() == R.id.btn_GotoJsonData) {//跳转到 省市区解析示例页面
startActivity(new Intent(MainActivity.this, JsonDataActivity.class));
} else if (v.getId() == R.id.btn_fragment) {//跳转到 fragment
startActivity(new Intent(MainActivity.this, FragmentTestActivity.class));
} else if (v.getId() == R.id.btn_lunar) {
pvCustomLunar.show();
} else if (v.getId() == R.id.btn_circle) {
startActivity(new Intent(MainActivity.this, TestCircleWheelViewActivity.class));
}
}
/**
* 农历时间已扩展至 : 1900 - 2100年
*/
private void initLunarPicker() {
Calendar selectedDate = Calendar.getInstance();//系统当前时间
Calendar startDate = Calendar.getInstance();
startDate.set(2014, 1, 23);
Calendar endDate = Calendar.getInstance();
endDate.set(2069, 2, 28);
//时间选择器 ,自定义布局
pvCustomLunar = new TimePickerBuilder(this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {//选中事件回调
Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
}
})
.setDate(selectedDate)
.setRangDate(startDate, endDate)
.setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {
@Override
public void customLayout(final View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomLunar.returnData();
pvCustomLunar.dismiss();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomLunar.dismiss();
}
});
//公农历切换
CheckBox cb_lunar = (CheckBox) v.findViewById(R.id.cb_lunar);
cb_lunar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
pvCustomLunar.setLunarCalendar(!pvCustomLunar.isLunarCalendar());
//自适应宽
setTimePickerChildWeight(v, isChecked ? 0.8f : 1f, isChecked ? 1f : 1.1f);
}
});
}
/**
* 公农历切换后调整宽
* @param v
* @param yearWeight
* @param weight
*/
private void setTimePickerChildWeight(View v, float yearWeight, float weight) {
ViewGroup timePicker = (ViewGroup) v.findViewById(R.id.timepicker);
View year = timePicker.getChildAt(0);
LinearLayout.LayoutParams lp = ((LinearLayout.LayoutParams) year.getLayoutParams());
lp.weight = yearWeight;
year.setLayoutParams(lp);
for (int i = 1; i < timePicker.getChildCount(); i++) {
View childAt = timePicker.getChildAt(i);
LinearLayout.LayoutParams childLp = ((LinearLayout.LayoutParams) childAt.getLayoutParams());
childLp.weight = weight;
childAt.setLayoutParams(childLp);
}
}
})
.setType(new boolean[]{true, true, true, false, false, false})
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.setDividerColor(Color.RED)
.build();
}
private void initTimePicker() {//Dialog 模式下,在底部弹出
pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {
Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
Log.i("pvTime", "onTimeSelect");
}
})
.setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
@Override
public void onTimeSelectChanged(Date date) {
Log.i("pvTime", "onTimeSelectChanged");
}
})
.setType(new boolean[]{true, true, true, true, true, true})
.isDialog(true) //默认设置false ,内部实现将DecorView 作为它的父控件。
.addOnCancelClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("pvTime", "onCancelClickListener");
}
})
.setItemVisibleCount(5) //若设置偶数,实际值会加1(比如设置6,则最大可见条目为7)
.setLineSpacingMultiplier(2.0f)
.isAlphaGradient(true)
.build();
Dialog mDialog = pvTime.getDialog();
if (mDialog != null) {
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM);
params.leftMargin = 0;
params.rightMargin = 0;
pvTime.getDialogContainerLayout().setLayoutParams(params);
Window dialogWindow = mDialog.getWindow();
if (dialogWindow != null) {
dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
dialogWindow.setDimAmount(0.3f);
}
}
}
private void initCustomTimePicker() {
/**
* @description
*
* 注意事项:
* 1.自定义布局中,id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有,否则会报空指针.
* 具体可参考demo 里面的两个自定义layout布局。
* 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
* setRangDate方法控制起始终止时间(如果不设置范围,则使用默认时间1900-2100年,此段代码可注释)
*/
Calendar selectedDate = Calendar.getInstance();//系统当前时间
Calendar startDate = Calendar.getInstance();
startDate.set(2014, 1, 23);
Calendar endDate = Calendar.getInstance();
endDate.set(2027, 2, 28);
//时间选择器 ,自定义布局
pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {//选中事件回调
btn_CustomTime.setText(getTime(date));
}
})
/*.setType(TimePickerView.Type.ALL)//default is all
.setCancelText("Cancel")
.setSubmitText("Sure")
.setContentTextSize(18)
.setTitleSize(20)
.setTitleText("Title")
.setTitleColor(Color.BLACK)
/*.setDividerColor(Color.WHITE)//设置分割线的颜色
.setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
.setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
.setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
.setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
.setSubmitColor(Color.WHITE)
.setCancelColor(Color.WHITE)*/
/*.animGravity(Gravity.RIGHT)// default is center*/
.setDate(selectedDate)
.setRangDate(startDate, endDate)
.setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {
@Override
public void customLayout(View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomTime.returnData();
pvCustomTime.dismiss();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomTime.dismiss();
}
});
}
})
.setContentTextSize(18)
.setType(new boolean[]{false, false, false, true, true, true})
.setLabel("年", "月", "日", "时", "分", "秒")
.setLineSpacingMultiplier(1.2f)
.setTextXOffset(0, 0, 0, 40, 0, -40)
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.setDividerColor(0xFF24AD9D)
.build();
}
private void initOptionPicker() {//条件选择器初始化
/**
* 注意 :如果是三级联动的数据(省市区等),请参照 JsonDataActivity 类里面的写法。
*/
pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int options2, int options3, View v) {
//返回的分别是三个级别的选中位置
String tx = options1Items.get(options1).getPickerViewText()
+ options2Items.get(options1).get(options2)
/* + options3Items.get(options1).get(options2).get(options3).getPickerViewText()*/;
btn_Options.setText(tx);
}
})
.setTitleText("城市选择")
.setContentTextSize(20)//设置滚轮文字大小
.setDividerColor(Color.LTGRAY)//设置分割线的颜色
.setSelectOptions(0, 1)//默认选中项
.setBgColor(Color.BLACK)
.setTitleBgColor(Color.DKGRAY)
.setTitleColor(Color.LTGRAY)
.setCancelColor(Color.YELLOW)
.setSubmitColor(Color.YELLOW)
.setTextColorCenter(Color.LTGRAY)
.isRestoreItem(true)//切换时是否还原,设置默认选中第一项。
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.setLabels("省", "市", "区")
.setOutSideColor(0x00000000) //设置外部遮罩颜色
.setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
@Override
public void onOptionsSelectChanged(int options1, int options2, int options3) {
String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
})
.build();
// pvOptions.setSelectOptions(1,1);
/*pvOptions.setPicker(options1Items);//一级选择器*/
pvOptions.setPicker(options1Items, options2Items);//二级选择器
/*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
}
private void initCustomOptionPicker() {//条件选择器初始化,自定义布局
/**
* @description
*
* 注意事项:
* 自定义布局中,id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有,否则会报空指针。
* 具体可参考demo 里面的两个自定义layout布局。
*/
pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int option2, int options3, View v) {
//返回的分别是三个级别的选中位置
String tx = cardItem.get(options1).getPickerViewText();
btn_CustomOptions.setText(tx);
}
})
.setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
@Override
public void customLayout(View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
final TextView tvAdd = (TextView) v.findViewById(R.id.tv_add);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomOptions.returnData();
pvCustomOptions.dismiss();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomOptions.dismiss();
}
});
tvAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCardData();
pvCustomOptions.setPicker(cardItem);
}
});
}
})
.isDialog(true)
.setOutSideCancelable(false)
.build();
pvCustomOptions.setPicker(cardItem);//添加数据
}
private void initNoLinkOptionsPicker() {// 不联动的多级选项
pvNoLinkOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int options2, int options3, View v) {
String str = "food:" + food.get(options1)
+ "\nclothes:" + clothes.get(options2)
+ "\ncomputer:" + computer.get(options3);
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
})
.setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
@Override
public void onOptionsSelectChanged(int options1, int options2, int options3) {
String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
})
.setItemVisibleCount(5)
// .setSelectOptions(0, 1, 1)
.build();
pvNoLinkOptions.setNPicker(food, clothes, computer);
pvNoLinkOptions.setSelectOptions(0, 1, 1);
}
private String getTime(Date date) {//可根据需要自行截取数据显示
Log.d("getTime()", "choice date millis: " + date.getTime());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(date);
}
private void getOptionData() {
/*
* 注意:如果是添加JavaBean实体数据,则实体类需要实现 IPickerViewData 接口,
* PickerView会通过getPickerViewText方法获取字符串显示出来。
*/
getCardData();
getNoLinkData();
//选项1
options1Items.add(new ProvinceBean(0, "广东", "描述部分", "其他数据"));
options1Items.add(new ProvinceBean(1, "湖南", "描述部分", "其他数据"));
options1Items.add(new ProvinceBean(2, "广西", "描述部分", "其他数据"));
//选项2
ArrayList<String> options2Items_01 = new ArrayList<>();
options2Items_01.add("广州");
options2Items_01.add("佛山");
options2Items_01.add("东莞");
options2Items_01.add("珠海");
ArrayList<String> options2Items_02 = new ArrayList<>();
options2Items_02.add("长沙");
options2Items_02.add("岳阳");
options2Items_02.add("株洲");
options2Items_02.add("衡阳");
ArrayList<String> options2Items_03 = new ArrayList<>();
options2Items_03.add("桂林");
options2Items_03.add("玉林");
options2Items.add(options2Items_01);
options2Items.add(options2Items_02);
options2Items.add(options2Items_03);
/*--------数据源添加完毕---------*/
}
private void getCardData() {
for (int i = 0; i < 5; i++) {
cardItem.add(new CardBean(i, "No.ABC12345 " + i));
}
for (int i = 0; i < cardItem.size(); i++) {
if (cardItem.get(i).getCardNo().length() > 6) {
String str_item = cardItem.get(i).getCardNo().substring(0, 6) + "...";
cardItem.get(i).setCardNo(str_item);
}
}
}
private void getNoLinkData() {
food.add("KFC");
food.add("MacDonald");
food.add("Pizza hut");
clothes.add("Nike");
clothes.add("Adidas");
clothes.add("Armani");
computer.add("ASUS");
computer.add("Lenovo");
computer.add("Apple");
computer.add("HP");
}
}
| Bigkoo/Android-PickerView | app/src/main/java/com/bigkoo/pickerviewdemo/MainActivity.java | 5,240 | //设置分割线的颜色 | line_comment | zh-cn | package com.bigkoo.pickerviewdemo;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bigkoo.pickerviewdemo.bean.CardBean;
import com.bigkoo.pickerviewdemo.bean.ProvinceBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayList<ProvinceBean> options1Items = new ArrayList<>();
private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
private Button btn_Options;
private Button btn_CustomOptions;
private Button btn_CustomTime;
private TimePickerView pvTime, pvCustomTime, pvCustomLunar;
private OptionsPickerView pvOptions, pvCustomOptions, pvNoLinkOptions;
private ArrayList<CardBean> cardItem = new ArrayList<>();
private ArrayList<String> food = new ArrayList<>();
private ArrayList<String> clothes = new ArrayList<>();
private ArrayList<String> computer = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//等数据加载完毕再初始化并显示Picker,以免还未加载完数据就显示,造成APP崩溃。
getOptionData();
initTimePicker();
initCustomTimePicker();
initLunarPicker();
initOptionPicker();
initCustomOptionPicker();
initNoLinkOptionsPicker();
Button btn_Time = (Button) findViewById(R.id.btn_Time);
btn_Options = (Button) findViewById(R.id.btn_Options);
btn_CustomOptions = (Button) findViewById(R.id.btn_CustomOptions);
btn_CustomTime = (Button) findViewById(R.id.btn_CustomTime);
Button btn_no_linkage = (Button) findViewById(R.id.btn_no_linkage);
Button btn_to_Fragment = (Button) findViewById(R.id.btn_fragment);
Button btn_circle = (Button) findViewById(R.id.btn_circle);
btn_Time.setOnClickListener(this);
btn_Options.setOnClickListener(this);
btn_CustomOptions.setOnClickListener(this);
btn_CustomTime.setOnClickListener(this);
btn_no_linkage.setOnClickListener(this);
btn_to_Fragment.setOnClickListener(this);
btn_circle.setOnClickListener(this);
findViewById(R.id.btn_GotoJsonData).setOnClickListener(this);
findViewById(R.id.btn_lunar).setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_Time && pvTime != null) {
// pvTime.setDate(Calendar.getInstance());
/* pvTime.show(); //show timePicker*/
pvTime.show(v);//弹出时间选择器,传递参数过去,回调的时候则可以绑定此view
} else if (v.getId() == R.id.btn_Options && pvOptions != null) {
pvOptions.show(); //弹出条件选择器
} else if (v.getId() == R.id.btn_CustomOptions && pvCustomOptions != null) {
pvCustomOptions.show(); //弹出自定义条件选择器
} else if (v.getId() == R.id.btn_CustomTime && pvCustomTime != null) {
pvCustomTime.show(); //弹出自定义时间选择器
} else if (v.getId() == R.id.btn_no_linkage && pvNoLinkOptions != null) {//不联动数据选择器
pvNoLinkOptions.show();
} else if (v.getId() == R.id.btn_GotoJsonData) {//跳转到 省市区解析示例页面
startActivity(new Intent(MainActivity.this, JsonDataActivity.class));
} else if (v.getId() == R.id.btn_fragment) {//跳转到 fragment
startActivity(new Intent(MainActivity.this, FragmentTestActivity.class));
} else if (v.getId() == R.id.btn_lunar) {
pvCustomLunar.show();
} else if (v.getId() == R.id.btn_circle) {
startActivity(new Intent(MainActivity.this, TestCircleWheelViewActivity.class));
}
}
/**
* 农历时间已扩展至 : 1900 - 2100年
*/
private void initLunarPicker() {
Calendar selectedDate = Calendar.getInstance();//系统当前时间
Calendar startDate = Calendar.getInstance();
startDate.set(2014, 1, 23);
Calendar endDate = Calendar.getInstance();
endDate.set(2069, 2, 28);
//时间选择器 ,自定义布局
pvCustomLunar = new TimePickerBuilder(this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {//选中事件回调
Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
}
})
.setDate(selectedDate)
.setRangDate(startDate, endDate)
.setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {
@Override
public void customLayout(final View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomLunar.returnData();
pvCustomLunar.dismiss();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomLunar.dismiss();
}
});
//公农历切换
CheckBox cb_lunar = (CheckBox) v.findViewById(R.id.cb_lunar);
cb_lunar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
pvCustomLunar.setLunarCalendar(!pvCustomLunar.isLunarCalendar());
//自适应宽
setTimePickerChildWeight(v, isChecked ? 0.8f : 1f, isChecked ? 1f : 1.1f);
}
});
}
/**
* 公农历切换后调整宽
* @param v
* @param yearWeight
* @param weight
*/
private void setTimePickerChildWeight(View v, float yearWeight, float weight) {
ViewGroup timePicker = (ViewGroup) v.findViewById(R.id.timepicker);
View year = timePicker.getChildAt(0);
LinearLayout.LayoutParams lp = ((LinearLayout.LayoutParams) year.getLayoutParams());
lp.weight = yearWeight;
year.setLayoutParams(lp);
for (int i = 1; i < timePicker.getChildCount(); i++) {
View childAt = timePicker.getChildAt(i);
LinearLayout.LayoutParams childLp = ((LinearLayout.LayoutParams) childAt.getLayoutParams());
childLp.weight = weight;
childAt.setLayoutParams(childLp);
}
}
})
.setType(new boolean[]{true, true, true, false, false, false})
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.setDividerColor(Color.RED)
.build();
}
private void initTimePicker() {//Dialog 模式下,在底部弹出
pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {
Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
Log.i("pvTime", "onTimeSelect");
}
})
.setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
@Override
public void onTimeSelectChanged(Date date) {
Log.i("pvTime", "onTimeSelectChanged");
}
})
.setType(new boolean[]{true, true, true, true, true, true})
.isDialog(true) //默认设置false ,内部实现将DecorView 作为它的父控件。
.addOnCancelClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("pvTime", "onCancelClickListener");
}
})
.setItemVisibleCount(5) //若设置偶数,实际值会加1(比如设置6,则最大可见条目为7)
.setLineSpacingMultiplier(2.0f)
.isAlphaGradient(true)
.build();
Dialog mDialog = pvTime.getDialog();
if (mDialog != null) {
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM);
params.leftMargin = 0;
params.rightMargin = 0;
pvTime.getDialogContainerLayout().setLayoutParams(params);
Window dialogWindow = mDialog.getWindow();
if (dialogWindow != null) {
dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
dialogWindow.setDimAmount(0.3f);
}
}
}
private void initCustomTimePicker() {
/**
* @description
*
* 注意事项:
* 1.自定义布局中,id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有,否则会报空指针.
* 具体可参考demo 里面的两个自定义layout布局。
* 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
* setRangDate方法控制起始终止时间(如果不设置范围,则使用默认时间1900-2100年,此段代码可注释)
*/
Calendar selectedDate = Calendar.getInstance();//系统当前时间
Calendar startDate = Calendar.getInstance();
startDate.set(2014, 1, 23);
Calendar endDate = Calendar.getInstance();
endDate.set(2027, 2, 28);
//时间选择器 ,自定义布局
pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {//选中事件回调
btn_CustomTime.setText(getTime(date));
}
})
/*.setType(TimePickerView.Type.ALL)//default is all
.setCancelText("Cancel")
.setSubmitText("Sure")
.setContentTextSize(18)
.setTitleSize(20)
.setTitleText("Title")
.setTitleColor(Color.BLACK)
/*.setDividerColor(Color.WHITE)//设置分割线的颜色
.setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
.setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
.setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
.setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
.setSubmitColor(Color.WHITE)
.setCancelColor(Color.WHITE)*/
/*.animGravity(Gravity.RIGHT)// default is center*/
.setDate(selectedDate)
.setRangDate(startDate, endDate)
.setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {
@Override
public void customLayout(View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomTime.returnData();
pvCustomTime.dismiss();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomTime.dismiss();
}
});
}
})
.setContentTextSize(18)
.setType(new boolean[]{false, false, false, true, true, true})
.setLabel("年", "月", "日", "时", "分", "秒")
.setLineSpacingMultiplier(1.2f)
.setTextXOffset(0, 0, 0, 40, 0, -40)
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.setDividerColor(0xFF24AD9D)
.build();
}
private void initOptionPicker() {//条件选择器初始化
/**
* 注意 :如果是三级联动的数据(省市区等),请参照 JsonDataActivity 类里面的写法。
*/
pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int options2, int options3, View v) {
//返回的分别是三个级别的选中位置
String tx = options1Items.get(options1).getPickerViewText()
+ options2Items.get(options1).get(options2)
/* + options3Items.get(options1).get(options2).get(options3).getPickerViewText()*/;
btn_Options.setText(tx);
}
})
.setTitleText("城市选择")
.setContentTextSize(20)//设置滚轮文字大小
.setDividerColor(Color.LTGRAY)//设置 <SUF>
.setSelectOptions(0, 1)//默认选中项
.setBgColor(Color.BLACK)
.setTitleBgColor(Color.DKGRAY)
.setTitleColor(Color.LTGRAY)
.setCancelColor(Color.YELLOW)
.setSubmitColor(Color.YELLOW)
.setTextColorCenter(Color.LTGRAY)
.isRestoreItem(true)//切换时是否还原,设置默认选中第一项。
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.setLabels("省", "市", "区")
.setOutSideColor(0x00000000) //设置外部遮罩颜色
.setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
@Override
public void onOptionsSelectChanged(int options1, int options2, int options3) {
String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
})
.build();
// pvOptions.setSelectOptions(1,1);
/*pvOptions.setPicker(options1Items);//一级选择器*/
pvOptions.setPicker(options1Items, options2Items);//二级选择器
/*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
}
private void initCustomOptionPicker() {//条件选择器初始化,自定义布局
/**
* @description
*
* 注意事项:
* 自定义布局中,id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有,否则会报空指针。
* 具体可参考demo 里面的两个自定义layout布局。
*/
pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int option2, int options3, View v) {
//返回的分别是三个级别的选中位置
String tx = cardItem.get(options1).getPickerViewText();
btn_CustomOptions.setText(tx);
}
})
.setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
@Override
public void customLayout(View v) {
final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
final TextView tvAdd = (TextView) v.findViewById(R.id.tv_add);
ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
tvSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomOptions.returnData();
pvCustomOptions.dismiss();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvCustomOptions.dismiss();
}
});
tvAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCardData();
pvCustomOptions.setPicker(cardItem);
}
});
}
})
.isDialog(true)
.setOutSideCancelable(false)
.build();
pvCustomOptions.setPicker(cardItem);//添加数据
}
private void initNoLinkOptionsPicker() {// 不联动的多级选项
pvNoLinkOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int options2, int options3, View v) {
String str = "food:" + food.get(options1)
+ "\nclothes:" + clothes.get(options2)
+ "\ncomputer:" + computer.get(options3);
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
})
.setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
@Override
public void onOptionsSelectChanged(int options1, int options2, int options3) {
String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
})
.setItemVisibleCount(5)
// .setSelectOptions(0, 1, 1)
.build();
pvNoLinkOptions.setNPicker(food, clothes, computer);
pvNoLinkOptions.setSelectOptions(0, 1, 1);
}
private String getTime(Date date) {//可根据需要自行截取数据显示
Log.d("getTime()", "choice date millis: " + date.getTime());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(date);
}
private void getOptionData() {
/*
* 注意:如果是添加JavaBean实体数据,则实体类需要实现 IPickerViewData 接口,
* PickerView会通过getPickerViewText方法获取字符串显示出来。
*/
getCardData();
getNoLinkData();
//选项1
options1Items.add(new ProvinceBean(0, "广东", "描述部分", "其他数据"));
options1Items.add(new ProvinceBean(1, "湖南", "描述部分", "其他数据"));
options1Items.add(new ProvinceBean(2, "广西", "描述部分", "其他数据"));
//选项2
ArrayList<String> options2Items_01 = new ArrayList<>();
options2Items_01.add("广州");
options2Items_01.add("佛山");
options2Items_01.add("东莞");
options2Items_01.add("珠海");
ArrayList<String> options2Items_02 = new ArrayList<>();
options2Items_02.add("长沙");
options2Items_02.add("岳阳");
options2Items_02.add("株洲");
options2Items_02.add("衡阳");
ArrayList<String> options2Items_03 = new ArrayList<>();
options2Items_03.add("桂林");
options2Items_03.add("玉林");
options2Items.add(options2Items_01);
options2Items.add(options2Items_02);
options2Items.add(options2Items_03);
/*--------数据源添加完毕---------*/
}
private void getCardData() {
for (int i = 0; i < 5; i++) {
cardItem.add(new CardBean(i, "No.ABC12345 " + i));
}
for (int i = 0; i < cardItem.size(); i++) {
if (cardItem.get(i).getCardNo().length() > 6) {
String str_item = cardItem.get(i).getCardNo().substring(0, 6) + "...";
cardItem.get(i).setCardNo(str_item);
}
}
}
private void getNoLinkData() {
food.add("KFC");
food.add("MacDonald");
food.add("Pizza hut");
clothes.add("Nike");
clothes.add("Adidas");
clothes.add("Armani");
computer.add("ASUS");
computer.add("Lenovo");
computer.add("Apple");
computer.add("HP");
}
}
| 1 | 10 | 1 |
53860_11 | package net.mcxk.minehunt.game;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import me.MrGraycat.eGlow.API.Enum.EGlowColor;
import net.mcxk.minehunt.MineHunt;
import net.mcxk.minehunt.util.GameEndingData;
import net.mcxk.minehunt.util.MusicPlayer;
import net.mcxk.minehunt.util.StatisticsBaker;
import net.mcxk.minehunt.util.Util;
import net.mcxk.minehunt.watcher.PlayerMoveWatcher;
import net.mcxk.minehunt.watcher.RadarWatcher;
import net.mcxk.minehunt.watcher.ReconnectWatcher;
import org.apache.commons.lang.StringUtils;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class Game {
@Getter
final Map<Player, Double> teamDamageData = new HashMap<>();
private final MineHunt plugin = MineHunt.getInstance();
@Getter
private final Set<Player> inGamePlayers = Sets.newCopyOnWriteArraySet(); //线程安全
@Getter
private final int countdown = 60;
@Getter
private final Map<Player, Long> reconnectTimer = new HashMap<>();
@Getter
private final GameProgressManager progressManager = new GameProgressManager();
@Getter
private final GameEndingData gameEndingData = new GameEndingData();
private final Map<World, Difficulty> difficultyMap = new HashMap<>();
@Getter
@Setter
private GameStatus status = GameStatus.WAITING_PLAYERS;
@Getter
private Map<Player, PlayerRole> roleMapping; //线程安全
@Getter
private final int maxPlayers = plugin.getConfig().getInt("max-players");
@Getter
private final int minPlayers = plugin.getConfig().getInt("min-players");
private final int runnerMax = plugin.getConfig().getInt("runner-max");
@Getter
private boolean compassUnlocked = false;
@Getter
private boolean compassRemoved = false;
public Game() {
fixConfig();
}
public void switchCompass(boolean unlocked) {
if (this.compassUnlocked == unlocked) {
return;
}
this.compassUnlocked = unlocked;
if (unlocked) {
getPlayersAsRole(PlayerRole.HUNTER).forEach(p -> p.getInventory().addItem(new ItemStack(Material.COMPASS, 1)));
Bukkit.broadcastMessage(ChatColor.YELLOW + "猎人已解锁追踪指南针!逃亡者的位置已经暴露!");
} else if(!compassRemoved) {
getPlayersAsRole(PlayerRole.HUNTER).forEach(p -> p.getInventory().remove(Material.COMPASS));
Bukkit.broadcastMessage(ChatColor.YELLOW + "猎人的追踪指南针被破坏失效,需要重新解锁!");
compassRemoved = true;
}
getPlayersAsRole(PlayerRole.RUNNER).forEach(p -> p.getInventory().remove(Material.COMPASS)); //清除合成的指南针
}
/**
* 获取玩家角色
*
* @param player 玩家
* @return 可能是Empty(玩家不属于游戏中的玩家)否则返回玩家角色
*/
public Optional<PlayerRole> getPlayerRole(Player player) {
if (!this.roleMapping.containsKey(player)) {
return Optional.empty();
}
return Optional.of(this.roleMapping.get(player));
}
public boolean playerJoining(Player player) {
reconnectTimer.remove(player);
if (inGamePlayers.size() < maxPlayers) {
inGamePlayers.add(player);
return true;
}
return false;
}
public void fixConfig() {
// if(runnerMax >minPlayers){
// runnerAmount = minPlayers -1;
// }
// if(runnerAmount < 1){
// runnerAmount = 1;
// minPlayers = runnerAmount + 1;
// }
// if(maxPlayers < minPlayers){
// maxPlayers = minPlayers + 1;
// }
}
public void playerLeaving(Player player) {
if (status == GameStatus.WAITING_PLAYERS) {
this.inGamePlayers.remove(player);
} else {
this.reconnectTimer.put(player, System.currentTimeMillis());
}
}
public void playerLeft(Player player) {
this.roleMapping.remove(player);
this.inGamePlayers.remove(player);
if (getPlayersAsRole(PlayerRole.RUNNER).isEmpty() || getPlayersAsRole(PlayerRole.HUNTER).isEmpty()) {
Bukkit.broadcastMessage("由于比赛的一方所有人因为长时间未能重新连接而被从列表中剔除,游戏被迫终止。");
Bukkit.broadcastMessage("服务器将会在 10 秒钟后重新启动。");
new BukkitRunnable() {
@Override
public void run() {
Bukkit.shutdown();
}
}.runTaskLater(plugin, 200);
return;
}
Bukkit.broadcastMessage("玩家:" + player.getName() + " 因长时间未能重新连接回对战而被从列表中剔除");
Bukkit.broadcastMessage(ChatColor.RED + "猎人: " + Util.list2String(getPlayersAsRole(PlayerRole.HUNTER).stream().map(Player::getName).collect(Collectors.toList())));
Bukkit.broadcastMessage(ChatColor.GREEN + "逃亡者: " + Util.list2String(getPlayersAsRole(PlayerRole.RUNNER).stream().map(Player::getName).collect(Collectors.toList())));
setupGlow();
}
public void setupGlow(){
if(plugin.getEGlowAPI() == null) return;
setupGlowForce();
}
public void setupGlowForce(){
plugin.getLogger().info("Rendering players glowing...");
getPlayersAsRole(PlayerRole.RUNNER).forEach(player->{
if(player == null || !player.isOnline()) return;
plugin.getEGlowAPI().enableGlow(player, EGlowColor.DARK_GREEN);
plugin.getEGlowAPI().setCustomGlowReceivers(player,getPlayersAsRole(PlayerRole.RUNNER));
});
getPlayersAsRole(PlayerRole.HUNTER).forEach(player->{
if(player == null || !player.isOnline()) return;
plugin.getEGlowAPI().enableGlow(player, EGlowColor.DARK_RED);
plugin.getEGlowAPI().setCustomGlowReceivers(player,getPlayersAsRole(PlayerRole.HUNTER));
});
}
public void start() {
if (status != GameStatus.WAITING_PLAYERS) {
return;
}
Bukkit.broadcastMessage("请稍后,系统正在随机分配玩家身份...");
Random random = new Random();
List<Player> noRolesPlayers = new ArrayList<>(inGamePlayers);
Map<Player, PlayerRole> roleMapTemp = new HashMap<>();
int runners = 1;
if (inGamePlayers.size() == maxPlayers) {
runners = runnerMax;
}
if (noRolesPlayers.size() == 0){
Bukkit.shutdown(); //出错,重启服务器
}
for (int i = 0; i < runners; i++) {
Player selected = noRolesPlayers.get(random.nextInt(noRolesPlayers.size()));
roleMapTemp.put(selected, PlayerRole.RUNNER);
noRolesPlayers.remove(selected);
}
noRolesPlayers.forEach(p -> roleMapTemp.put(p, PlayerRole.HUNTER));
this.roleMapping = new ConcurrentHashMap<>(roleMapTemp);
if(plugin.getConfig().getBoolean("runner-airdrop",true)) {
Bukkit.broadcastMessage("正在将逃亡者随机传送到远离猎人的位置...");
Location airDropLoc = airDrop(getPlayersAsRole(PlayerRole.RUNNER).get(0).getWorld().getSpawnLocation());
getPlayersAsRole(PlayerRole.RUNNER).forEach(runner -> runner.teleport(airDropLoc));
getPlayersAsRole(PlayerRole.HUNTER).forEach(p -> p.teleport(p.getWorld().getSpawnLocation()));
}else{
getInGamePlayers().forEach(p->p.teleport(p.getWorld().getSpawnLocation()));
}
if(getPlayersAsRole(PlayerRole.RUNNER).size() != 2 && getInGamePlayers().size() > 2){
getPlayersAsRole(PlayerRole.RUNNER).forEach(runner->{
runner.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(40.0d);
runner.setHealth(40.0d);
});
}
Bukkit.broadcastMessage("设置游戏规则...");
inGamePlayers.forEach(p -> {
p.setGameMode(GameMode.SURVIVAL);
p.setFoodLevel(40);
p.setHealth(p.getMaxHealth());
p.setExp(0.0f);
p.setCompassTarget(p.getWorld().getSpawnLocation());
p.getInventory().clear();
});
switchWorldRuleForReady(true);
Bukkit.broadcastMessage("游戏开始!");
Bukkit.broadcastMessage(ChatColor.AQUA + "欢迎来到 " + ChatColor.GREEN + "MineHunt " + ChatColor.AQUA + "!");
Bukkit.broadcastMessage(ChatColor.AQUA + "在本游戏中,将会有 " + ChatColor.YELLOW + runners + ChatColor.AQUA + " 名玩家扮演逃亡者,其余玩家扮演猎人");
Bukkit.broadcastMessage(ChatColor.RED + "猎人需要阻止逃亡者击杀末影龙或击杀逃亡者以取得胜利。");
Bukkit.broadcastMessage(ChatColor.GREEN + "逃亡者需要在猎人的追杀下击败末影龙以取得胜利。逃亡者无法复活且由于任何原因死亡均会导致猎人胜利。");
Bukkit.broadcastMessage(ChatColor.AQUA + "在游戏过程中,当你解锁特定的游戏阶段时,全体玩家将会获得阶段奖励,可能是特定物品也可能是增益效果。");
Bukkit.broadcastMessage(ChatColor.AQUA + "猎人可以通过合成指南针来定位逃亡者的方向。");
Bukkit.broadcastMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "祝君好运,末地见!");
Bukkit.broadcastMessage(ChatColor.RED + "猎人: " + Util.list2String(getPlayersAsRole(PlayerRole.HUNTER).stream().map(Player::getName).collect(Collectors.toList())));
Bukkit.broadcastMessage(ChatColor.GREEN + "逃亡者: " + Util.list2String(getPlayersAsRole(PlayerRole.RUNNER).stream().map(Player::getName).collect(Collectors.toList())));
status = GameStatus.GAME_STARTED;
this.registerWatchers();
plugin.getGame().getProgressManager().unlockProgress(GameProgress.GAME_STARTING);
inGamePlayers.forEach(player -> player.sendTitle(ChatColor.GREEN+"游戏开始","GO GO GO", 0,80,0));
setupGlow();
}
public void switchWorldRuleForReady(boolean ready) {
if (!ready) {
Bukkit.getWorlds().forEach(world -> {
world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false);
world.setGameRule(GameRule.DO_MOB_SPAWNING, false);
world.setGameRule(GameRule.DO_FIRE_TICK, false);
world.setGameRule(GameRule.MOB_GRIEFING, false);
difficultyMap.put(world, world.getDifficulty());
world.setDifficulty(Difficulty.PEACEFUL);
});
} else {
Bukkit.getWorlds().forEach(world -> {
world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, true);
world.setGameRule(GameRule.DO_MOB_SPAWNING, true);
world.setGameRule(GameRule.DO_FIRE_TICK, true);
world.setGameRule(GameRule.MOB_GRIEFING, true);
world.setDifficulty(difficultyMap.getOrDefault(world, Difficulty.NORMAL));
});
}
}
public void stop(PlayerRole winner, Location location) {
this.inGamePlayers.stream().filter(Player::isOnline).forEach(player -> {
player.setGameMode(GameMode.SPECTATOR);
player.teleport(location.clone().add(0, 3, 0));
player.teleport(Util.lookAt(player.getEyeLocation(), location));
});
this.status = GameStatus.ENDED;
Bukkit.broadcastMessage(ChatColor.YELLOW + "游戏结束! 服务器将在30秒后重新启动!");
String runnerNames = Util.list2String(getPlayersAsRole(PlayerRole.RUNNER).stream().map(Player::getName).collect(Collectors.toList()));
String hunterNames = Util.list2String(getPlayersAsRole(PlayerRole.HUNTER).stream().map(Player::getName).collect(Collectors.toList()));
if (winner == PlayerRole.HUNTER) {
Bukkit.broadcastMessage(ChatColor.GOLD + "胜利者:猎人");
Bukkit.broadcastMessage(ChatColor.LIGHT_PURPLE + "恭喜:" + hunterNames);
getPlayersAsRole(PlayerRole.HUNTER).forEach(player -> player.sendTitle(ChatColor.GOLD + "胜利", "成功击败了逃亡者", 0, 2000, 0));
getPlayersAsRole(PlayerRole.RUNNER).forEach(player -> player.sendTitle(ChatColor.RED + "游戏结束", "不幸阵亡", 0, 2000, 0));
} else {
Bukkit.broadcastMessage(ChatColor.GOLD + "胜利者:逃亡者");
Bukkit.broadcastMessage(ChatColor.LIGHT_PURPLE + "恭喜:" + runnerNames);
getPlayersAsRole(PlayerRole.RUNNER).forEach(player -> player.sendTitle(ChatColor.GOLD + "胜利", "成功战胜了末影龙", 0, 2000, 0));
getPlayersAsRole(PlayerRole.HUNTER).forEach(player -> player.sendTitle(ChatColor.RED + "游戏结束", "未能阻止末影龙死亡", 0, 2000, 0));
}
new MusicPlayer().playEnding();
Bukkit.getOnlinePlayers().stream().filter(p -> !inGamePlayers.contains(p)).forEach(p -> p.sendTitle(ChatColor.RED + "游戏结束", "The End", 0, 2000, 0));
new BukkitRunnable() {
@Override
public void run() {
//开始结算阶段
StatisticsBaker baker = new StatisticsBaker();
//计算输出最多的玩家
getGameEndingData().setDamageOutput(baker.getDamageMaster());
getGameEndingData().setDamageReceive(baker.getDamageTakenMaster());
getGameEndingData().setWalkMaster(baker.getWalkingMaster());
getGameEndingData().setJumpMaster(baker.getJumpMaster());
getGameEndingData().setTeamKiller(baker.getTeamBadGuy());
new BukkitRunnable() {
@Override
public void run() {
sendEndingAnimation();
}
}.runTaskLaterAsynchronously(plugin, 20 * 10);
}
}.runTaskLater(MineHunt.getInstance(), 20 * 10);
}
@SneakyThrows
private void sendEndingAnimation() {
double maxCanCost = 20000d;
int needShows = 0;
if (StringUtils.isNotBlank(gameEndingData.getDamageOutput())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getDragonKiller())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getDamageReceive())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getStoneAgePassed())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getRunnerKiller())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getWalkMaster())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getJumpMaster())) {
needShows++;
}
maxCanCost /= needShows;
int sleep = (int) maxCanCost;
if (StringUtils.isNotBlank(gameEndingData.getDragonKiller())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GOLD + "屠龙勇士", gameEndingData.getDragonKiller(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getRunnerKiller())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.RED + "逃亡者的噩梦", gameEndingData.getRunnerKiller(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getDamageOutput())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.AQUA + "最佳伤害输出", gameEndingData.getDamageOutput(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getDamageReceive())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.LIGHT_PURPLE + "最惨怪物标靶", gameEndingData.getDamageReceive(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getTeamKiller())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.DARK_RED + "队友杀手", gameEndingData.getTeamKiller(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getWalkMaster())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.YELLOW + "大探险家", gameEndingData.getWalkMaster(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getJumpMaster())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GRAY + "CS:GO玩家", gameEndingData.getJumpMaster(), 0, 20000, 0));
Thread.sleep(sleep);
}
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GREEN + "感谢游玩", "Thanks for playing!", 0, 20000, 0));
Thread.sleep(sleep);
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GREEN + plugin.getConfig().getString("server-name"), "友尽大逃杀-MineHunt", 0, 20000, 0));
Thread.sleep(sleep);
Bukkit.getOnlinePlayers().forEach(Player::resetTitle);
Bukkit.shutdown();
}
private void registerWatchers() {
new RadarWatcher();
new ReconnectWatcher();
new PlayerMoveWatcher();
}
public List<Player> getPlayersAsRole(PlayerRole role) {
return this.roleMapping.entrySet().stream().filter(playerPlayerRoleEntry -> playerPlayerRoleEntry.getValue() == role).map(Map.Entry::getKey).collect(Collectors.toList());
}
//Code from ManHunt
private Location airDrop(Location spawnpoint) {
Location loc = spawnpoint.clone();
loc = new Location(loc.getWorld(), loc.getBlockX(), 0, loc.getBlockZ());
Random random = new Random();
loc.add(random.nextInt(200) + 100, 0, random.nextInt(200) + 100);
loc = loc.getWorld().getHighestBlockAt(loc).getLocation();
loc.getBlock().setType(Material.GLASS);
loc.setY(loc.getY() + 1);
return loc;
}
}
| Bilicraft-Community/MineHunt | src/main/java/net/mcxk/minehunt/game/Game.java | 4,945 | //出错,重启服务器 | line_comment | zh-cn | package net.mcxk.minehunt.game;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import me.MrGraycat.eGlow.API.Enum.EGlowColor;
import net.mcxk.minehunt.MineHunt;
import net.mcxk.minehunt.util.GameEndingData;
import net.mcxk.minehunt.util.MusicPlayer;
import net.mcxk.minehunt.util.StatisticsBaker;
import net.mcxk.minehunt.util.Util;
import net.mcxk.minehunt.watcher.PlayerMoveWatcher;
import net.mcxk.minehunt.watcher.RadarWatcher;
import net.mcxk.minehunt.watcher.ReconnectWatcher;
import org.apache.commons.lang.StringUtils;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class Game {
@Getter
final Map<Player, Double> teamDamageData = new HashMap<>();
private final MineHunt plugin = MineHunt.getInstance();
@Getter
private final Set<Player> inGamePlayers = Sets.newCopyOnWriteArraySet(); //线程安全
@Getter
private final int countdown = 60;
@Getter
private final Map<Player, Long> reconnectTimer = new HashMap<>();
@Getter
private final GameProgressManager progressManager = new GameProgressManager();
@Getter
private final GameEndingData gameEndingData = new GameEndingData();
private final Map<World, Difficulty> difficultyMap = new HashMap<>();
@Getter
@Setter
private GameStatus status = GameStatus.WAITING_PLAYERS;
@Getter
private Map<Player, PlayerRole> roleMapping; //线程安全
@Getter
private final int maxPlayers = plugin.getConfig().getInt("max-players");
@Getter
private final int minPlayers = plugin.getConfig().getInt("min-players");
private final int runnerMax = plugin.getConfig().getInt("runner-max");
@Getter
private boolean compassUnlocked = false;
@Getter
private boolean compassRemoved = false;
public Game() {
fixConfig();
}
public void switchCompass(boolean unlocked) {
if (this.compassUnlocked == unlocked) {
return;
}
this.compassUnlocked = unlocked;
if (unlocked) {
getPlayersAsRole(PlayerRole.HUNTER).forEach(p -> p.getInventory().addItem(new ItemStack(Material.COMPASS, 1)));
Bukkit.broadcastMessage(ChatColor.YELLOW + "猎人已解锁追踪指南针!逃亡者的位置已经暴露!");
} else if(!compassRemoved) {
getPlayersAsRole(PlayerRole.HUNTER).forEach(p -> p.getInventory().remove(Material.COMPASS));
Bukkit.broadcastMessage(ChatColor.YELLOW + "猎人的追踪指南针被破坏失效,需要重新解锁!");
compassRemoved = true;
}
getPlayersAsRole(PlayerRole.RUNNER).forEach(p -> p.getInventory().remove(Material.COMPASS)); //清除合成的指南针
}
/**
* 获取玩家角色
*
* @param player 玩家
* @return 可能是Empty(玩家不属于游戏中的玩家)否则返回玩家角色
*/
public Optional<PlayerRole> getPlayerRole(Player player) {
if (!this.roleMapping.containsKey(player)) {
return Optional.empty();
}
return Optional.of(this.roleMapping.get(player));
}
public boolean playerJoining(Player player) {
reconnectTimer.remove(player);
if (inGamePlayers.size() < maxPlayers) {
inGamePlayers.add(player);
return true;
}
return false;
}
public void fixConfig() {
// if(runnerMax >minPlayers){
// runnerAmount = minPlayers -1;
// }
// if(runnerAmount < 1){
// runnerAmount = 1;
// minPlayers = runnerAmount + 1;
// }
// if(maxPlayers < minPlayers){
// maxPlayers = minPlayers + 1;
// }
}
public void playerLeaving(Player player) {
if (status == GameStatus.WAITING_PLAYERS) {
this.inGamePlayers.remove(player);
} else {
this.reconnectTimer.put(player, System.currentTimeMillis());
}
}
public void playerLeft(Player player) {
this.roleMapping.remove(player);
this.inGamePlayers.remove(player);
if (getPlayersAsRole(PlayerRole.RUNNER).isEmpty() || getPlayersAsRole(PlayerRole.HUNTER).isEmpty()) {
Bukkit.broadcastMessage("由于比赛的一方所有人因为长时间未能重新连接而被从列表中剔除,游戏被迫终止。");
Bukkit.broadcastMessage("服务器将会在 10 秒钟后重新启动。");
new BukkitRunnable() {
@Override
public void run() {
Bukkit.shutdown();
}
}.runTaskLater(plugin, 200);
return;
}
Bukkit.broadcastMessage("玩家:" + player.getName() + " 因长时间未能重新连接回对战而被从列表中剔除");
Bukkit.broadcastMessage(ChatColor.RED + "猎人: " + Util.list2String(getPlayersAsRole(PlayerRole.HUNTER).stream().map(Player::getName).collect(Collectors.toList())));
Bukkit.broadcastMessage(ChatColor.GREEN + "逃亡者: " + Util.list2String(getPlayersAsRole(PlayerRole.RUNNER).stream().map(Player::getName).collect(Collectors.toList())));
setupGlow();
}
public void setupGlow(){
if(plugin.getEGlowAPI() == null) return;
setupGlowForce();
}
public void setupGlowForce(){
plugin.getLogger().info("Rendering players glowing...");
getPlayersAsRole(PlayerRole.RUNNER).forEach(player->{
if(player == null || !player.isOnline()) return;
plugin.getEGlowAPI().enableGlow(player, EGlowColor.DARK_GREEN);
plugin.getEGlowAPI().setCustomGlowReceivers(player,getPlayersAsRole(PlayerRole.RUNNER));
});
getPlayersAsRole(PlayerRole.HUNTER).forEach(player->{
if(player == null || !player.isOnline()) return;
plugin.getEGlowAPI().enableGlow(player, EGlowColor.DARK_RED);
plugin.getEGlowAPI().setCustomGlowReceivers(player,getPlayersAsRole(PlayerRole.HUNTER));
});
}
public void start() {
if (status != GameStatus.WAITING_PLAYERS) {
return;
}
Bukkit.broadcastMessage("请稍后,系统正在随机分配玩家身份...");
Random random = new Random();
List<Player> noRolesPlayers = new ArrayList<>(inGamePlayers);
Map<Player, PlayerRole> roleMapTemp = new HashMap<>();
int runners = 1;
if (inGamePlayers.size() == maxPlayers) {
runners = runnerMax;
}
if (noRolesPlayers.size() == 0){
Bukkit.shutdown(); //出错 <SUF>
}
for (int i = 0; i < runners; i++) {
Player selected = noRolesPlayers.get(random.nextInt(noRolesPlayers.size()));
roleMapTemp.put(selected, PlayerRole.RUNNER);
noRolesPlayers.remove(selected);
}
noRolesPlayers.forEach(p -> roleMapTemp.put(p, PlayerRole.HUNTER));
this.roleMapping = new ConcurrentHashMap<>(roleMapTemp);
if(plugin.getConfig().getBoolean("runner-airdrop",true)) {
Bukkit.broadcastMessage("正在将逃亡者随机传送到远离猎人的位置...");
Location airDropLoc = airDrop(getPlayersAsRole(PlayerRole.RUNNER).get(0).getWorld().getSpawnLocation());
getPlayersAsRole(PlayerRole.RUNNER).forEach(runner -> runner.teleport(airDropLoc));
getPlayersAsRole(PlayerRole.HUNTER).forEach(p -> p.teleport(p.getWorld().getSpawnLocation()));
}else{
getInGamePlayers().forEach(p->p.teleport(p.getWorld().getSpawnLocation()));
}
if(getPlayersAsRole(PlayerRole.RUNNER).size() != 2 && getInGamePlayers().size() > 2){
getPlayersAsRole(PlayerRole.RUNNER).forEach(runner->{
runner.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(40.0d);
runner.setHealth(40.0d);
});
}
Bukkit.broadcastMessage("设置游戏规则...");
inGamePlayers.forEach(p -> {
p.setGameMode(GameMode.SURVIVAL);
p.setFoodLevel(40);
p.setHealth(p.getMaxHealth());
p.setExp(0.0f);
p.setCompassTarget(p.getWorld().getSpawnLocation());
p.getInventory().clear();
});
switchWorldRuleForReady(true);
Bukkit.broadcastMessage("游戏开始!");
Bukkit.broadcastMessage(ChatColor.AQUA + "欢迎来到 " + ChatColor.GREEN + "MineHunt " + ChatColor.AQUA + "!");
Bukkit.broadcastMessage(ChatColor.AQUA + "在本游戏中,将会有 " + ChatColor.YELLOW + runners + ChatColor.AQUA + " 名玩家扮演逃亡者,其余玩家扮演猎人");
Bukkit.broadcastMessage(ChatColor.RED + "猎人需要阻止逃亡者击杀末影龙或击杀逃亡者以取得胜利。");
Bukkit.broadcastMessage(ChatColor.GREEN + "逃亡者需要在猎人的追杀下击败末影龙以取得胜利。逃亡者无法复活且由于任何原因死亡均会导致猎人胜利。");
Bukkit.broadcastMessage(ChatColor.AQUA + "在游戏过程中,当你解锁特定的游戏阶段时,全体玩家将会获得阶段奖励,可能是特定物品也可能是增益效果。");
Bukkit.broadcastMessage(ChatColor.AQUA + "猎人可以通过合成指南针来定位逃亡者的方向。");
Bukkit.broadcastMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "祝君好运,末地见!");
Bukkit.broadcastMessage(ChatColor.RED + "猎人: " + Util.list2String(getPlayersAsRole(PlayerRole.HUNTER).stream().map(Player::getName).collect(Collectors.toList())));
Bukkit.broadcastMessage(ChatColor.GREEN + "逃亡者: " + Util.list2String(getPlayersAsRole(PlayerRole.RUNNER).stream().map(Player::getName).collect(Collectors.toList())));
status = GameStatus.GAME_STARTED;
this.registerWatchers();
plugin.getGame().getProgressManager().unlockProgress(GameProgress.GAME_STARTING);
inGamePlayers.forEach(player -> player.sendTitle(ChatColor.GREEN+"游戏开始","GO GO GO", 0,80,0));
setupGlow();
}
public void switchWorldRuleForReady(boolean ready) {
if (!ready) {
Bukkit.getWorlds().forEach(world -> {
world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false);
world.setGameRule(GameRule.DO_MOB_SPAWNING, false);
world.setGameRule(GameRule.DO_FIRE_TICK, false);
world.setGameRule(GameRule.MOB_GRIEFING, false);
difficultyMap.put(world, world.getDifficulty());
world.setDifficulty(Difficulty.PEACEFUL);
});
} else {
Bukkit.getWorlds().forEach(world -> {
world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, true);
world.setGameRule(GameRule.DO_MOB_SPAWNING, true);
world.setGameRule(GameRule.DO_FIRE_TICK, true);
world.setGameRule(GameRule.MOB_GRIEFING, true);
world.setDifficulty(difficultyMap.getOrDefault(world, Difficulty.NORMAL));
});
}
}
public void stop(PlayerRole winner, Location location) {
this.inGamePlayers.stream().filter(Player::isOnline).forEach(player -> {
player.setGameMode(GameMode.SPECTATOR);
player.teleport(location.clone().add(0, 3, 0));
player.teleport(Util.lookAt(player.getEyeLocation(), location));
});
this.status = GameStatus.ENDED;
Bukkit.broadcastMessage(ChatColor.YELLOW + "游戏结束! 服务器将在30秒后重新启动!");
String runnerNames = Util.list2String(getPlayersAsRole(PlayerRole.RUNNER).stream().map(Player::getName).collect(Collectors.toList()));
String hunterNames = Util.list2String(getPlayersAsRole(PlayerRole.HUNTER).stream().map(Player::getName).collect(Collectors.toList()));
if (winner == PlayerRole.HUNTER) {
Bukkit.broadcastMessage(ChatColor.GOLD + "胜利者:猎人");
Bukkit.broadcastMessage(ChatColor.LIGHT_PURPLE + "恭喜:" + hunterNames);
getPlayersAsRole(PlayerRole.HUNTER).forEach(player -> player.sendTitle(ChatColor.GOLD + "胜利", "成功击败了逃亡者", 0, 2000, 0));
getPlayersAsRole(PlayerRole.RUNNER).forEach(player -> player.sendTitle(ChatColor.RED + "游戏结束", "不幸阵亡", 0, 2000, 0));
} else {
Bukkit.broadcastMessage(ChatColor.GOLD + "胜利者:逃亡者");
Bukkit.broadcastMessage(ChatColor.LIGHT_PURPLE + "恭喜:" + runnerNames);
getPlayersAsRole(PlayerRole.RUNNER).forEach(player -> player.sendTitle(ChatColor.GOLD + "胜利", "成功战胜了末影龙", 0, 2000, 0));
getPlayersAsRole(PlayerRole.HUNTER).forEach(player -> player.sendTitle(ChatColor.RED + "游戏结束", "未能阻止末影龙死亡", 0, 2000, 0));
}
new MusicPlayer().playEnding();
Bukkit.getOnlinePlayers().stream().filter(p -> !inGamePlayers.contains(p)).forEach(p -> p.sendTitle(ChatColor.RED + "游戏结束", "The End", 0, 2000, 0));
new BukkitRunnable() {
@Override
public void run() {
//开始结算阶段
StatisticsBaker baker = new StatisticsBaker();
//计算输出最多的玩家
getGameEndingData().setDamageOutput(baker.getDamageMaster());
getGameEndingData().setDamageReceive(baker.getDamageTakenMaster());
getGameEndingData().setWalkMaster(baker.getWalkingMaster());
getGameEndingData().setJumpMaster(baker.getJumpMaster());
getGameEndingData().setTeamKiller(baker.getTeamBadGuy());
new BukkitRunnable() {
@Override
public void run() {
sendEndingAnimation();
}
}.runTaskLaterAsynchronously(plugin, 20 * 10);
}
}.runTaskLater(MineHunt.getInstance(), 20 * 10);
}
@SneakyThrows
private void sendEndingAnimation() {
double maxCanCost = 20000d;
int needShows = 0;
if (StringUtils.isNotBlank(gameEndingData.getDamageOutput())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getDragonKiller())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getDamageReceive())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getStoneAgePassed())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getRunnerKiller())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getWalkMaster())) {
needShows++;
}
if (StringUtils.isNotBlank(gameEndingData.getJumpMaster())) {
needShows++;
}
maxCanCost /= needShows;
int sleep = (int) maxCanCost;
if (StringUtils.isNotBlank(gameEndingData.getDragonKiller())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GOLD + "屠龙勇士", gameEndingData.getDragonKiller(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getRunnerKiller())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.RED + "逃亡者的噩梦", gameEndingData.getRunnerKiller(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getDamageOutput())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.AQUA + "最佳伤害输出", gameEndingData.getDamageOutput(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getDamageReceive())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.LIGHT_PURPLE + "最惨怪物标靶", gameEndingData.getDamageReceive(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getTeamKiller())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.DARK_RED + "队友杀手", gameEndingData.getTeamKiller(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getWalkMaster())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.YELLOW + "大探险家", gameEndingData.getWalkMaster(), 0, 20000, 0));
Thread.sleep(sleep);
}
if (StringUtils.isNotBlank(gameEndingData.getJumpMaster())) {
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GRAY + "CS:GO玩家", gameEndingData.getJumpMaster(), 0, 20000, 0));
Thread.sleep(sleep);
}
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GREEN + "感谢游玩", "Thanks for playing!", 0, 20000, 0));
Thread.sleep(sleep);
Bukkit.getOnlinePlayers().forEach(p -> p.sendTitle(ChatColor.GREEN + plugin.getConfig().getString("server-name"), "友尽大逃杀-MineHunt", 0, 20000, 0));
Thread.sleep(sleep);
Bukkit.getOnlinePlayers().forEach(Player::resetTitle);
Bukkit.shutdown();
}
private void registerWatchers() {
new RadarWatcher();
new ReconnectWatcher();
new PlayerMoveWatcher();
}
public List<Player> getPlayersAsRole(PlayerRole role) {
return this.roleMapping.entrySet().stream().filter(playerPlayerRoleEntry -> playerPlayerRoleEntry.getValue() == role).map(Map.Entry::getKey).collect(Collectors.toList());
}
//Code from ManHunt
private Location airDrop(Location spawnpoint) {
Location loc = spawnpoint.clone();
loc = new Location(loc.getWorld(), loc.getBlockX(), 0, loc.getBlockZ());
Random random = new Random();
loc.add(random.nextInt(200) + 100, 0, random.nextInt(200) + 100);
loc = loc.getWorld().getHighestBlockAt(loc).getLocation();
loc.getBlock().setType(Material.GLASS);
loc.setY(loc.getY() + 1);
return loc;
}
}
| 1 | 10 | 1 |
54057_3 | package com.bill56.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bill56.carlife.R;
import com.bill56.entity.UserCar;
import java.util.List;
/**
* Created by Bill56 on 2016/5/23.
*/
public class CarInfoAdapter extends BaseAdapter {
// 上下文环境
private Context mContext;
// 数据
private List<UserCar> mData;
// 布局服务加载器
private LayoutInflater layoutInflater;
public CarInfoAdapter(Context context, List<UserCar> data) {
this.mContext = context;
mData = data;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
// 加载模板,创建视图项——将布局创建成一个View对象
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.item_car_info, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
UserCar userCar = mData.get(position);
viewHolder.bindData(userCar);
return convertView;
}
/**
* 保存布局控件实例的类
*/
private class ViewHolder {
// 字段
ImageView imgCarLogo;
TextView textCarBrandVersion;
TextView textTotalOil;
TextView textCarLicence;
TextView textTransState;
TextView textEngineState;
TextView textLightState;
TextView textEngineNo;
/**
* 构造方法,获得布局中的控件绑定对象
* @param v 布局参数
*/
public ViewHolder(View v) {
imgCarLogo = (ImageView) v.findViewById(R.id.image_car_logo);
textCarBrandVersion = (TextView) v.findViewById(R.id.text_car_brand_version);
textTotalOil = (TextView) v.findViewById(R.id.text_total_oil);
textCarLicence = (TextView) v.findViewById(R.id.text_car_licence);
textTransState = (TextView) v.findViewById(R.id.text_trans_state);
textEngineState = (TextView) v.findViewById(R.id.text_engine_state);
textLightState = (TextView) v.findViewById(R.id.text_light_state);
textEngineNo = (TextView) v.findViewById(R.id.text_engine_no);
}
/**
* 绑定数据
* @param userCar 用户车辆对象
*/
public void bindData(UserCar userCar) {
// 设置图标
setCarLogo(userCar.getCarBrand());
// 设置其他参数
textCarBrandVersion.setText(userCar.getCarBrand()+userCar.getCarVersion());
textTotalOil.setText(userCar.getCarOilTotal() + "L");
textCarLicence.setText(userCar.getCarLicence());
textEngineState.setText(userCar.getCarEngineState());
textTransState.setText(userCar.getCarTransState());
textLightState.setText(userCar.getCarLightState());
textEngineNo.setText(userCar.getCarEngineNo());
}
private void setCarLogo(String carBrand) {
// 根据车品牌设置图标
switch (carBrand) {
case "奥迪":
imgCarLogo.setImageResource(R.drawable.auto_audi);
break;
case "本田":
imgCarLogo.setImageResource(R.drawable.auto_honda);
break;
case "福特":
imgCarLogo.setImageResource(R.drawable.auto_ford);
break;
case "玛莎拉蒂":
imgCarLogo.setImageResource(R.drawable.auto_maserati);
break;
case "马自达":
imgCarLogo.setImageResource(R.drawable.auto_mazda);
break;
case "现代":
imgCarLogo.setImageResource(R.drawable.auto_hyundai);
break;
case "大众":
imgCarLogo.setImageResource(R.drawable.auto_volkswagen);
break;
case "日产":
imgCarLogo.setImageResource(R.drawable.auto_nissan);
break;
case "斯柯达":
imgCarLogo.setImageResource(R.drawable.auto_skoda);
break;
case "雪弗兰":
imgCarLogo.setImageResource(R.drawable.auto_chevrolet);
break;
case "三菱":
imgCarLogo.setImageResource(R.drawable.auto_mitsubishi);
break;
default:
imgCarLogo.setImageResource(R.drawable.auto_abarth);
break;
}
}
}
}
| Bill56/CarLife | app/src/main/java/com/bill56/adapter/CarInfoAdapter.java | 1,247 | // 加载模板,创建视图项——将布局创建成一个View对象 | line_comment | zh-cn | package com.bill56.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bill56.carlife.R;
import com.bill56.entity.UserCar;
import java.util.List;
/**
* Created by Bill56 on 2016/5/23.
*/
public class CarInfoAdapter extends BaseAdapter {
// 上下文环境
private Context mContext;
// 数据
private List<UserCar> mData;
// 布局服务加载器
private LayoutInflater layoutInflater;
public CarInfoAdapter(Context context, List<UserCar> data) {
this.mContext = context;
mData = data;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
// 加载 <SUF>
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.item_car_info, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
UserCar userCar = mData.get(position);
viewHolder.bindData(userCar);
return convertView;
}
/**
* 保存布局控件实例的类
*/
private class ViewHolder {
// 字段
ImageView imgCarLogo;
TextView textCarBrandVersion;
TextView textTotalOil;
TextView textCarLicence;
TextView textTransState;
TextView textEngineState;
TextView textLightState;
TextView textEngineNo;
/**
* 构造方法,获得布局中的控件绑定对象
* @param v 布局参数
*/
public ViewHolder(View v) {
imgCarLogo = (ImageView) v.findViewById(R.id.image_car_logo);
textCarBrandVersion = (TextView) v.findViewById(R.id.text_car_brand_version);
textTotalOil = (TextView) v.findViewById(R.id.text_total_oil);
textCarLicence = (TextView) v.findViewById(R.id.text_car_licence);
textTransState = (TextView) v.findViewById(R.id.text_trans_state);
textEngineState = (TextView) v.findViewById(R.id.text_engine_state);
textLightState = (TextView) v.findViewById(R.id.text_light_state);
textEngineNo = (TextView) v.findViewById(R.id.text_engine_no);
}
/**
* 绑定数据
* @param userCar 用户车辆对象
*/
public void bindData(UserCar userCar) {
// 设置图标
setCarLogo(userCar.getCarBrand());
// 设置其他参数
textCarBrandVersion.setText(userCar.getCarBrand()+userCar.getCarVersion());
textTotalOil.setText(userCar.getCarOilTotal() + "L");
textCarLicence.setText(userCar.getCarLicence());
textEngineState.setText(userCar.getCarEngineState());
textTransState.setText(userCar.getCarTransState());
textLightState.setText(userCar.getCarLightState());
textEngineNo.setText(userCar.getCarEngineNo());
}
private void setCarLogo(String carBrand) {
// 根据车品牌设置图标
switch (carBrand) {
case "奥迪":
imgCarLogo.setImageResource(R.drawable.auto_audi);
break;
case "本田":
imgCarLogo.setImageResource(R.drawable.auto_honda);
break;
case "福特":
imgCarLogo.setImageResource(R.drawable.auto_ford);
break;
case "玛莎拉蒂":
imgCarLogo.setImageResource(R.drawable.auto_maserati);
break;
case "马自达":
imgCarLogo.setImageResource(R.drawable.auto_mazda);
break;
case "现代":
imgCarLogo.setImageResource(R.drawable.auto_hyundai);
break;
case "大众":
imgCarLogo.setImageResource(R.drawable.auto_volkswagen);
break;
case "日产":
imgCarLogo.setImageResource(R.drawable.auto_nissan);
break;
case "斯柯达":
imgCarLogo.setImageResource(R.drawable.auto_skoda);
break;
case "雪弗兰":
imgCarLogo.setImageResource(R.drawable.auto_chevrolet);
break;
case "三菱":
imgCarLogo.setImageResource(R.drawable.auto_mitsubishi);
break;
default:
imgCarLogo.setImageResource(R.drawable.auto_abarth);
break;
}
}
}
}
| 1 | 29 | 1 |
51833_2 | import java.util.Random;
public class Main {
private static void testEncodeLong64() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
long y = LongEncoder.encode64(x);
long z = LongEncoder.decode64(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testEncodeLong64 success");
} else {
System.out.println("testEncodeLong64 failed");
}
}
private static void testEncodeLong48() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong() >>> 16;
long y = LongEncoder.encode48(x);
long z = LongEncoder.decode48(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testEncodeLong48 success");
} else {
System.out.println("testEncodeLong48 failed");
}
}
private static void testBase62() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
String y = Base62.encode(LongEncoder.encode64(x));
long z = LongEncoder.decode64(Base62.decode(y));
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testBase62 success");
} else {
System.out.println("testBase62 failed");
}
}
private static void testBase62ForShortLink(){
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong() >>> 16;
// 48bit的x, y的长度在1~9之间,长度为8居多
// 如果需要恒定8字节,则可以用Base64, Base64时6bit一个字节,正好8字节
// 如果又不想引入特殊字符('-','_'), 则x需要需要小于等于47bit,构造一个47bit的x(比较复杂)
String y = Base62.encodePositive(LongEncoder.encode48(x));
long z = LongEncoder.decode48(Base62.decodePositive(y));
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testBase62ForShortLink success");
} else {
System.out.println("testBase62ForShortLink failed");
}
}
private static void testLong48ToHex() {
Random r = new Random();
long x = r.nextLong() >>> 16;
String y = HexUtil.long48ToHex(LongEncoder.encode48(x));
long z = LongEncoder.decode48(HexUtil.hexToLong48(y));
if (x == z) {
System.out.println("testLong48ToHex success");
} else {
System.out.println("testLong48ToHex failed");
}
System.out.println("y = " + y);
}
private static void testNumberCipher() {
byte[] key = new byte[24];
Random r = new Random();
r.nextBytes(key);
NumberCipher cipher = new NumberCipher(key);
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
long y = cipher.encryptLong(x);
long z = cipher.decryptLong(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("Test encode long success");
} else {
System.out.println("Test encode long failed");
}
if(!success){
return;
}
for (int i = 0; i < 100; i++) {
int x = r.nextInt();
int y = cipher.encryptInt(x);
int z = cipher.decryptInt(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("Test encode int success");
} else {
System.out.println("Test encode int failed");
}
}
public static void main(String[] args) {
testEncodeLong64();
testEncodeLong48();
testNumberCipher();
// testBase62();
// testBase62ForShortLink();
// testLong48ToHex();
}
}
| BillyWei01/LongEncrypt | src/Main.java | 1,176 | // 如果又不想引入特殊字符('-','_'), 则x需要需要小于等于47bit,构造一个47bit的x(比较复杂) | line_comment | zh-cn | import java.util.Random;
public class Main {
private static void testEncodeLong64() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
long y = LongEncoder.encode64(x);
long z = LongEncoder.decode64(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testEncodeLong64 success");
} else {
System.out.println("testEncodeLong64 failed");
}
}
private static void testEncodeLong48() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong() >>> 16;
long y = LongEncoder.encode48(x);
long z = LongEncoder.decode48(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testEncodeLong48 success");
} else {
System.out.println("testEncodeLong48 failed");
}
}
private static void testBase62() {
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
String y = Base62.encode(LongEncoder.encode64(x));
long z = LongEncoder.decode64(Base62.decode(y));
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testBase62 success");
} else {
System.out.println("testBase62 failed");
}
}
private static void testBase62ForShortLink(){
Random r = new Random();
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong() >>> 16;
// 48bit的x, y的长度在1~9之间,长度为8居多
// 如果需要恒定8字节,则可以用Base64, Base64时6bit一个字节,正好8字节
// 如果 <SUF>
String y = Base62.encodePositive(LongEncoder.encode48(x));
long z = LongEncoder.decode48(Base62.decodePositive(y));
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("testBase62ForShortLink success");
} else {
System.out.println("testBase62ForShortLink failed");
}
}
private static void testLong48ToHex() {
Random r = new Random();
long x = r.nextLong() >>> 16;
String y = HexUtil.long48ToHex(LongEncoder.encode48(x));
long z = LongEncoder.decode48(HexUtil.hexToLong48(y));
if (x == z) {
System.out.println("testLong48ToHex success");
} else {
System.out.println("testLong48ToHex failed");
}
System.out.println("y = " + y);
}
private static void testNumberCipher() {
byte[] key = new byte[24];
Random r = new Random();
r.nextBytes(key);
NumberCipher cipher = new NumberCipher(key);
boolean success = true;
for (int i = 0; i < 100; i++) {
long x = r.nextLong();
long y = cipher.encryptLong(x);
long z = cipher.decryptLong(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("Test encode long success");
} else {
System.out.println("Test encode long failed");
}
if(!success){
return;
}
for (int i = 0; i < 100; i++) {
int x = r.nextInt();
int y = cipher.encryptInt(x);
int z = cipher.decryptInt(y);
if (x != z) {
success = false;
break;
}
}
if (success) {
System.out.println("Test encode int success");
} else {
System.out.println("Test encode int failed");
}
}
public static void main(String[] args) {
testEncodeLong64();
testEncodeLong48();
testNumberCipher();
// testBase62();
// testBase62ForShortLink();
// testLong48ToHex();
}
}
| 1 | 58 | 1 |
57071_8 | package cn.com.xiaoyaoji.entity;
/**
* 导入类型
* @author: zhoujingjie
* @Date: 17/4/16
*/
public class ImportType {
//pdf
public static final String IMPORT_PDF = "import.pdf";
//postman
public static final String IMPORT_POSTMAN = "import.postman";
//word
public static final String IMPORT_WORD = "import.word";
//excel
public static final String IMPORT_EXCEL = "import.excel";
//chm
public static final String IMPORT_CHM = "import.chm";
//markdown
public static final String IMPORT_MARKDOWN = "import.markdown";
//epub
public static final String IMPORT_EPUB = "import.epub";
//印象笔记
public static final String IMPORT_YXNOTE = "import.yxnote";
//有道笔记
public static final String IMPORT_YDNOTE = "import.ydnote";
}
| Bin-mario/xiaoyaoji | xiaoyaoji-web/src/main/java/cn/com/xiaoyaoji/entity/ImportType.java | 228 | //印象笔记 | line_comment | zh-cn | package cn.com.xiaoyaoji.entity;
/**
* 导入类型
* @author: zhoujingjie
* @Date: 17/4/16
*/
public class ImportType {
//pdf
public static final String IMPORT_PDF = "import.pdf";
//postman
public static final String IMPORT_POSTMAN = "import.postman";
//word
public static final String IMPORT_WORD = "import.word";
//excel
public static final String IMPORT_EXCEL = "import.excel";
//chm
public static final String IMPORT_CHM = "import.chm";
//markdown
public static final String IMPORT_MARKDOWN = "import.markdown";
//epub
public static final String IMPORT_EPUB = "import.epub";
//印象 <SUF>
public static final String IMPORT_YXNOTE = "import.yxnote";
//有道笔记
public static final String IMPORT_YDNOTE = "import.ydnote";
}
| 1 | 6 | 1 |
18339_18 | import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
/*
日期类(Date,Calendar)
>前面两代日期类的不足分析
JDK1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK1.1引入Calendar类之后被弃用了。
而Calendar也存在如下问题∶
1)可变性∶像日期和时间这样的类应该是不可变的。
2)偏移性∶Date中的年份是从1900开始的,而月份都从0开始。
3)格式化格式化只对Date有用,Calendar则不行。
4)此外,它们也不是线程安全的;不能处理闰秒等(每隔2天,多出1s)。
>LocalDate(日期/年月日)、LocalTime(时间/时分秒)、LocalDateTime(日期时间/年月日时分秒)JDK8加入
LocalDate只包含日期,可以获取日期字段LocalTime只包含时间,可以获取时间字段
LocalDateTime包含日期+时间,可以获取日期和时间字段
第三代日期类常用方法
·使用DateTimeFormatter来格式化日期
·LocalDateTime类
·MonthDay类∶检查重复事件
·是否是闰年
·增加日期的某个部分
·使用plus方法测试增加时间的某个部分
·使用minus方法测试查看一年前和一年后的日期
* */
public class Date01 {
public static void main(String[] args) {
//1. 获取当前系统时间
//2. 这里的 Date 类是在 java.util 包
//3. 默认输出的日期格式是国外的方式, 因此通常需要对格式进行转换
Date d1 = new Date(); //获取当前系统时间
System.out.println("当前日期=" + d1);
Date d2 = new Date(9234567); //通过指定毫秒数得到时间
System.out.println("d2=" + d2); //获取某个时间对应的毫秒数
//1. 创建 SimpleDateFormat 对象,可以指定相应的格式
//2. 这里的格式使用的字母是规定好,不能乱写
SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日 hh:mm:ss E");
String format = sdf.format(d1); // format:将日期转换成指定格式的字符串
System.out.println("当前日期=" + format);
//1. 可以把一个格式化的 String 转成对应的 Date
//2. 得到 Date 仍然在输出时,还是按照国外的形式,如果希望指定格式输出,需要转换
//3. 在把 String -> Date , 使用的 sdf 格式需要和你给的 String 的格式一样,否则会抛出转换异常
String s = "1996 年 01 月 01 日 10:20:30 星期一";
Date parse = null;
try {
parse = sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("parse=" + sdf.format(parse));
//1. Calendar 是一个抽象类, 并且构造器是 private
//2. 可以通过 getInstance() 来获取实例
//3. 提供大量的方法和字段提供给程序员
//4. Calendar 没有提供对应的格式化的类,因此需要程序员自己组合来输出(灵活)
//5. 如果我们需要按照 24 小时进制来获取时间, Calendar.HOUR ==改成=> Calendar.HOUR_OF_DAY
Calendar c = Calendar.getInstance(); //创建日历类对象//比较简单,自由
System.out.println("c=" + c);
//2.获取日历对象的某个日历字段
System.out.println("年:" + c.get(Calendar.YEAR));
// 这里为什么要 + 1, 因为 Calendar 返回月时候,是按照 0 开始编号
System.out.println("月:" + (c.get(Calendar.MONTH) + 1));
System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));
System.out.println("小时:" + c.get(Calendar.HOUR));
System.out.println("分钟:" + c.get(Calendar.MINUTE));
System.out.println("秒:" + c.get(Calendar.SECOND));
//Calender 没有专门的格式化方法,所以使用时需要自己来组合显示
System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" +
c.get(Calendar.DAY_OF_MONTH) +
" " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND));
//第三代日期
//1. 使用 now() 返回表示当前日期时间的 对象
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
System.out.println(ldt);
//2. 使用 DateTimeFormatter 对象来进行格式化
// 创建 DateTimeFormatter 对象
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format1 = dateTimeFormatter.format(ldt);
System.out.println("格式化的日期=" + format1);
System.out.println("年=" + ldt.getYear());
System.out.println("月=" + ldt.getMonth());
System.out.println("月=" + ldt.getMonthValue());
System.out.println("日=" + ldt.getDayOfMonth());
System.out.println("时=" + ldt.getHour());
System.out.println("分=" + ldt.getMinute());
System.out.println("秒=" + ldt.getSecond());
LocalDate now = LocalDate.now(); //可以获取年月日
LocalTime now2 = LocalTime.now();//获取到时分秒
//提供 plus 和 minus 方法可以对当前时间进行加或者减
//看看 890 天后,是什么时候 把 年月日-时分秒
LocalDateTime localDateTime = ldt.plusDays(890);
System.out.println("890 天后=" + dateTimeFormatter.format(localDateTime));
//看看在 3456 分钟前是什么时候,把 年月日-时分秒输出
LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
System.out.println("3456 分钟前 日期=" + dateTimeFormatter.format(localDateTime2));
}
}
| BinGBanG21/JavaBing | JavaSE/Date01/src/Date01.java | 1,576 | //创建日历类对象//比较简单,自由 | line_comment | zh-cn | import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
/*
日期类(Date,Calendar)
>前面两代日期类的不足分析
JDK1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK1.1引入Calendar类之后被弃用了。
而Calendar也存在如下问题∶
1)可变性∶像日期和时间这样的类应该是不可变的。
2)偏移性∶Date中的年份是从1900开始的,而月份都从0开始。
3)格式化格式化只对Date有用,Calendar则不行。
4)此外,它们也不是线程安全的;不能处理闰秒等(每隔2天,多出1s)。
>LocalDate(日期/年月日)、LocalTime(时间/时分秒)、LocalDateTime(日期时间/年月日时分秒)JDK8加入
LocalDate只包含日期,可以获取日期字段LocalTime只包含时间,可以获取时间字段
LocalDateTime包含日期+时间,可以获取日期和时间字段
第三代日期类常用方法
·使用DateTimeFormatter来格式化日期
·LocalDateTime类
·MonthDay类∶检查重复事件
·是否是闰年
·增加日期的某个部分
·使用plus方法测试增加时间的某个部分
·使用minus方法测试查看一年前和一年后的日期
* */
public class Date01 {
public static void main(String[] args) {
//1. 获取当前系统时间
//2. 这里的 Date 类是在 java.util 包
//3. 默认输出的日期格式是国外的方式, 因此通常需要对格式进行转换
Date d1 = new Date(); //获取当前系统时间
System.out.println("当前日期=" + d1);
Date d2 = new Date(9234567); //通过指定毫秒数得到时间
System.out.println("d2=" + d2); //获取某个时间对应的毫秒数
//1. 创建 SimpleDateFormat 对象,可以指定相应的格式
//2. 这里的格式使用的字母是规定好,不能乱写
SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日 hh:mm:ss E");
String format = sdf.format(d1); // format:将日期转换成指定格式的字符串
System.out.println("当前日期=" + format);
//1. 可以把一个格式化的 String 转成对应的 Date
//2. 得到 Date 仍然在输出时,还是按照国外的形式,如果希望指定格式输出,需要转换
//3. 在把 String -> Date , 使用的 sdf 格式需要和你给的 String 的格式一样,否则会抛出转换异常
String s = "1996 年 01 月 01 日 10:20:30 星期一";
Date parse = null;
try {
parse = sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("parse=" + sdf.format(parse));
//1. Calendar 是一个抽象类, 并且构造器是 private
//2. 可以通过 getInstance() 来获取实例
//3. 提供大量的方法和字段提供给程序员
//4. Calendar 没有提供对应的格式化的类,因此需要程序员自己组合来输出(灵活)
//5. 如果我们需要按照 24 小时进制来获取时间, Calendar.HOUR ==改成=> Calendar.HOUR_OF_DAY
Calendar c = Calendar.getInstance(); //创建 <SUF>
System.out.println("c=" + c);
//2.获取日历对象的某个日历字段
System.out.println("年:" + c.get(Calendar.YEAR));
// 这里为什么要 + 1, 因为 Calendar 返回月时候,是按照 0 开始编号
System.out.println("月:" + (c.get(Calendar.MONTH) + 1));
System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));
System.out.println("小时:" + c.get(Calendar.HOUR));
System.out.println("分钟:" + c.get(Calendar.MINUTE));
System.out.println("秒:" + c.get(Calendar.SECOND));
//Calender 没有专门的格式化方法,所以使用时需要自己来组合显示
System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" +
c.get(Calendar.DAY_OF_MONTH) +
" " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND));
//第三代日期
//1. 使用 now() 返回表示当前日期时间的 对象
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
System.out.println(ldt);
//2. 使用 DateTimeFormatter 对象来进行格式化
// 创建 DateTimeFormatter 对象
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format1 = dateTimeFormatter.format(ldt);
System.out.println("格式化的日期=" + format1);
System.out.println("年=" + ldt.getYear());
System.out.println("月=" + ldt.getMonth());
System.out.println("月=" + ldt.getMonthValue());
System.out.println("日=" + ldt.getDayOfMonth());
System.out.println("时=" + ldt.getHour());
System.out.println("分=" + ldt.getMinute());
System.out.println("秒=" + ldt.getSecond());
LocalDate now = LocalDate.now(); //可以获取年月日
LocalTime now2 = LocalTime.now();//获取到时分秒
//提供 plus 和 minus 方法可以对当前时间进行加或者减
//看看 890 天后,是什么时候 把 年月日-时分秒
LocalDateTime localDateTime = ldt.plusDays(890);
System.out.println("890 天后=" + dateTimeFormatter.format(localDateTime));
//看看在 3456 分钟前是什么时候,把 年月日-时分秒输出
LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
System.out.println("3456 分钟前 日期=" + dateTimeFormatter.format(localDateTime2));
}
}
| 1 | 18 | 1 |
23523_1 | package keyWords;
public class Volatile {
// 防止字分裂
// 字分裂就是:比如long、double都是64位,在32位计算机上,就要分两次更新一个值,可能在中途由于上下文的切换,就导致读值错误
// 可见性
// 阻止变量被编译器优化,也就是不会被缓存。变量值发生改变,就会直接写入主存,读的时候也只从主存里面拿
// 阻止 happens before
// java会对指令进行重排序来优化性能,这种重排序就叫 happens before ,先行发生保证
// volatile操作,也叫 内存栅栏 memory barrier,该操作之前的读写等操作不会被重排序到volatile操作之后,对应其后面的操作也不会排到前面
// 先行发生保证,会把一些其他非volatile变量也刷新到主存,隐式把这些非volatile变量变成了volatile变量
// 不建议使用volatile,使用Atomic变量
public volatile long val;
public Volatile(long val) {
this.val = val;
}
public void sumsum() {
for (int i = 0; i < 5; i++) {
// 自增操作不是一个原子操作
System.out.println(val++);
}
}
public static void main(String[] args) {
Volatile aVolatile = new Volatile(0);
aVolatile.sumsum();
}
}
| BinchaoPeng/JavaLearn | src/main/java/keyWords/Volatile.java | 339 | // 字分裂就是:比如long、double都是64位,在32位计算机上,就要分两次更新一个值,可能在中途由于上下文的切换,就导致读值错误 | line_comment | zh-cn | package keyWords;
public class Volatile {
// 防止字分裂
// 字分 <SUF>
// 可见性
// 阻止变量被编译器优化,也就是不会被缓存。变量值发生改变,就会直接写入主存,读的时候也只从主存里面拿
// 阻止 happens before
// java会对指令进行重排序来优化性能,这种重排序就叫 happens before ,先行发生保证
// volatile操作,也叫 内存栅栏 memory barrier,该操作之前的读写等操作不会被重排序到volatile操作之后,对应其后面的操作也不会排到前面
// 先行发生保证,会把一些其他非volatile变量也刷新到主存,隐式把这些非volatile变量变成了volatile变量
// 不建议使用volatile,使用Atomic变量
public volatile long val;
public Volatile(long val) {
this.val = val;
}
public void sumsum() {
for (int i = 0; i < 5; i++) {
// 自增操作不是一个原子操作
System.out.println(val++);
}
}
public static void main(String[] args) {
Volatile aVolatile = new Volatile(0);
aVolatile.sumsum();
}
}
| 1 | 74 | 1 |
45849_5 | package com.hu.dao.impl;
import com.hu.dao.ExpenseDao;
import com.hu.entity.Employee;
import com.hu.entity.ExpImage;
import com.hu.entity.Expense;
import com.hu.entity.ExpenseItem;
import com.hu.util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @author 胡冰
* @version 1.0
* @create 2020-06-11 22:55
* @decription
**/
public class ExpenseDaoImpl implements ExpenseDao {
@Override
public void save(Expense expense) {
String sql = "insert into expense values(?,?,?,?,?,?,?,?)";
Object[] params = {expense.getExpId(), expense.getEmpId(), expense.getTotalAmount(),
new java.sql.Date(expense.getExpTime().getTime()), expense.getExpDesc(), expense.getNextAuditorId(),
expense.getLastResult(), expense.getStatus()};
JdbcUtil.executeUpdate(sql, params);
}
/**
* 此处简写了,仅仅为审核功能而写
* 如果具体点儿。可以结合 findExp() 方法
*/
@Override
public List<Expense> findByAuditorId(String auditorId) {
String sql = " select exp.* ,emp.realName " +
" from expense exp , employee emp " +
" where exp.empid = emp.empid " +
" and nextauditor = ? ";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Expense> list = new ArrayList<Expense>();
try {
conn = JdbcUtil.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, auditorId);
rs = pstmt.executeQuery();
while (rs.next()) {
int expId = rs.getInt("expId");
String empId = rs.getString("empId");
double totalAmount = rs.getDouble("totalAmount");
Date expTime = rs.getDate("expTime");
String expDesc = rs.getString("expDesc");
String nextAuditorId = auditorId;
String lastResult = rs.getString("lastResult");
String status = rs.getString("status");
String realName = rs.getString("realName");
Employee emp = new Employee();
emp.setEmpId(empId);
emp.setRealName(realName);
Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status, emp, null);
list.add(exp);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeAll(conn, pstmt, rs);
}
return list;
}
@Override
public void update(Expense expense) {
String sql = "update expense set nextauditor = ?,lastresult=?,status =? where expid=?";
Object params[] = {expense.getNextAuditorId(), expense.getLastResult(), expense.getStatus(), expense.getExpId()};
JdbcUtil.executeUpdate(sql, params);
}
@Override
public Expense findById(int expId) {
String sql = "select * from expense where expId = ?";
Object[] params = {expId};
List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, params);
if (maps.size() == 0) {
return null;
}
Map<String, Object> map = maps.get(0);
Expense exp = new Expense();
exp.setExpId(expId);
map.forEach((key, value) -> {
if ("empId".equalsIgnoreCase(key)) {
exp.setEmpId((String) value);
}
if ("totalAmount".equalsIgnoreCase(key)) {
exp.setTotalAmount((Double)value);
}
if ("expTime".equalsIgnoreCase(key)) {
exp.setExpTime((Date) value);
}
if ("expDesc".equalsIgnoreCase(key)) {
exp.setExpDesc((String) value);
}
if ("nextAuditor".equalsIgnoreCase(key)) {
exp.setNextAuditorId((String) value);
}
if ("lastResult".equalsIgnoreCase(key)) {
exp.setLastResult((String) value);
}
if ("status".equalsIgnoreCase(key)) {
exp.setStatus((String) value);
}
});
return exp;
}
@Override
public int findExpId() {
String sql = " select max(expid) next from expense";
List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, null);
Map<String, Object> map = maps.get(0);
int value=0;
for (String key : map.keySet()) {
value = (Integer) map.get(key);
}
int next = value + 1;
return next;
}
@Override
public List<Expense> findExp(String empId2, String status2, java.sql.Date expTime2) {
StringBuilder sql = new StringBuilder("select exp.* ,item.type,item.amount,item.itemdesc,image.realname,image.filename,image.filetype " +
" from expense exp " +
" JOIN expenseitem item on exp.expid = item.expid " +
" join expimage image on exp.expid = image.expid " +
" where 1=1");
if (empId2 != null & !"".equals(empId2)) {
sql.append(" and exp.empid = '" + empId2 + "' ");
}
if (status2 != null & !"".equals(status2)) {
sql.append(" and exp.`status`= '" + status2 + "' ");
}
if (expTime2 != null) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sdtDate = sdf.format(expTime2);
sql.append(" and exp.exptime >='" + expTime2 + "'");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Expense> expenseList = new ArrayList<Expense>();
List<ExpenseItem> expenseItemList = new ArrayList<ExpenseItem>();
List<ExpImage> imageList = new ArrayList<ExpImage>();
try {
conn = JdbcUtil.getConnection();
pstmt = conn.prepareStatement(sql.toString());
rs = pstmt.executeQuery();
while (rs.next()) {
//expense 各个字段
int expId = rs.getInt("expId");
String empId = rs.getString("empId");
double totalAmount = rs.getDouble("totalAmount");
Date expTime = rs.getDate("expTime");
String expDesc = rs.getString("expDesc");
String nextAuditorId = rs.getString("nextAuditor");
String lastResult = rs.getString("lastResult");
String status = rs.getString("status");
//expenseitem 各个字段
String type = rs.getString("type");
double amount = rs.getDouble("amount");
String itemDesc = rs.getString("itemDesc");
//expimage 各个字段
String realName = rs.getString("realName");
String filename = rs.getString("filename");
String filetype = rs.getString("filetype");
//
ExpImage expImage = new ExpImage(realName, filename, filetype);
expImage.setExpId(expId);
ExpenseItem expenseItem = new ExpenseItem(type, amount, itemDesc);
expenseItem.setExpId(expId);
Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status);
expenseList.add(exp);
expenseItemList.add(expenseItem);
imageList.add(expImage);
}
//去除重复
for ( int i = 0 ; i < expenseList.size() - 1 ; i ++ ) {
for ( int j = expenseList.size() - 1 ; j > i; j -- ) {
if (expenseList.get(j).equals(expenseList.get(i))) {
expenseList.remove(j);
}
}
}
//
/* for (ExpenseItem item: expenseItemList){
System.out.println(item);
}*/
for (int i=0;i<expenseList.size();i++){
List<ExpenseItem> itemList = new ArrayList<ExpenseItem>();
for (int j=0;j<expenseItemList.size();j++){
if(expenseList.get(i).getExpId()==expenseItemList.get(j).getExpId()){
itemList.add(expenseItemList.get(j));
}
}
expenseList.get(i).setItemList(itemList);
for (int k=0;k<imageList.size();k++){
if(expenseList.get(i).getExpId()==imageList.get(k).getExpId()){
expenseList.get(i).setExpImage(imageList.get(k));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeAll(conn, pstmt, rs);
}
return expenseList;
}
}
| BingBuLiang/PersonnelManagement_OA | src/com/hu/dao/impl/ExpenseDaoImpl.java | 2,220 | //去除重复 | line_comment | zh-cn | package com.hu.dao.impl;
import com.hu.dao.ExpenseDao;
import com.hu.entity.Employee;
import com.hu.entity.ExpImage;
import com.hu.entity.Expense;
import com.hu.entity.ExpenseItem;
import com.hu.util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @author 胡冰
* @version 1.0
* @create 2020-06-11 22:55
* @decription
**/
public class ExpenseDaoImpl implements ExpenseDao {
@Override
public void save(Expense expense) {
String sql = "insert into expense values(?,?,?,?,?,?,?,?)";
Object[] params = {expense.getExpId(), expense.getEmpId(), expense.getTotalAmount(),
new java.sql.Date(expense.getExpTime().getTime()), expense.getExpDesc(), expense.getNextAuditorId(),
expense.getLastResult(), expense.getStatus()};
JdbcUtil.executeUpdate(sql, params);
}
/**
* 此处简写了,仅仅为审核功能而写
* 如果具体点儿。可以结合 findExp() 方法
*/
@Override
public List<Expense> findByAuditorId(String auditorId) {
String sql = " select exp.* ,emp.realName " +
" from expense exp , employee emp " +
" where exp.empid = emp.empid " +
" and nextauditor = ? ";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Expense> list = new ArrayList<Expense>();
try {
conn = JdbcUtil.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, auditorId);
rs = pstmt.executeQuery();
while (rs.next()) {
int expId = rs.getInt("expId");
String empId = rs.getString("empId");
double totalAmount = rs.getDouble("totalAmount");
Date expTime = rs.getDate("expTime");
String expDesc = rs.getString("expDesc");
String nextAuditorId = auditorId;
String lastResult = rs.getString("lastResult");
String status = rs.getString("status");
String realName = rs.getString("realName");
Employee emp = new Employee();
emp.setEmpId(empId);
emp.setRealName(realName);
Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status, emp, null);
list.add(exp);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeAll(conn, pstmt, rs);
}
return list;
}
@Override
public void update(Expense expense) {
String sql = "update expense set nextauditor = ?,lastresult=?,status =? where expid=?";
Object params[] = {expense.getNextAuditorId(), expense.getLastResult(), expense.getStatus(), expense.getExpId()};
JdbcUtil.executeUpdate(sql, params);
}
@Override
public Expense findById(int expId) {
String sql = "select * from expense where expId = ?";
Object[] params = {expId};
List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, params);
if (maps.size() == 0) {
return null;
}
Map<String, Object> map = maps.get(0);
Expense exp = new Expense();
exp.setExpId(expId);
map.forEach((key, value) -> {
if ("empId".equalsIgnoreCase(key)) {
exp.setEmpId((String) value);
}
if ("totalAmount".equalsIgnoreCase(key)) {
exp.setTotalAmount((Double)value);
}
if ("expTime".equalsIgnoreCase(key)) {
exp.setExpTime((Date) value);
}
if ("expDesc".equalsIgnoreCase(key)) {
exp.setExpDesc((String) value);
}
if ("nextAuditor".equalsIgnoreCase(key)) {
exp.setNextAuditorId((String) value);
}
if ("lastResult".equalsIgnoreCase(key)) {
exp.setLastResult((String) value);
}
if ("status".equalsIgnoreCase(key)) {
exp.setStatus((String) value);
}
});
return exp;
}
@Override
public int findExpId() {
String sql = " select max(expid) next from expense";
List<Map<String, Object>> maps = JdbcUtil.executeQuery(sql, null);
Map<String, Object> map = maps.get(0);
int value=0;
for (String key : map.keySet()) {
value = (Integer) map.get(key);
}
int next = value + 1;
return next;
}
@Override
public List<Expense> findExp(String empId2, String status2, java.sql.Date expTime2) {
StringBuilder sql = new StringBuilder("select exp.* ,item.type,item.amount,item.itemdesc,image.realname,image.filename,image.filetype " +
" from expense exp " +
" JOIN expenseitem item on exp.expid = item.expid " +
" join expimage image on exp.expid = image.expid " +
" where 1=1");
if (empId2 != null & !"".equals(empId2)) {
sql.append(" and exp.empid = '" + empId2 + "' ");
}
if (status2 != null & !"".equals(status2)) {
sql.append(" and exp.`status`= '" + status2 + "' ");
}
if (expTime2 != null) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sdtDate = sdf.format(expTime2);
sql.append(" and exp.exptime >='" + expTime2 + "'");
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Expense> expenseList = new ArrayList<Expense>();
List<ExpenseItem> expenseItemList = new ArrayList<ExpenseItem>();
List<ExpImage> imageList = new ArrayList<ExpImage>();
try {
conn = JdbcUtil.getConnection();
pstmt = conn.prepareStatement(sql.toString());
rs = pstmt.executeQuery();
while (rs.next()) {
//expense 各个字段
int expId = rs.getInt("expId");
String empId = rs.getString("empId");
double totalAmount = rs.getDouble("totalAmount");
Date expTime = rs.getDate("expTime");
String expDesc = rs.getString("expDesc");
String nextAuditorId = rs.getString("nextAuditor");
String lastResult = rs.getString("lastResult");
String status = rs.getString("status");
//expenseitem 各个字段
String type = rs.getString("type");
double amount = rs.getDouble("amount");
String itemDesc = rs.getString("itemDesc");
//expimage 各个字段
String realName = rs.getString("realName");
String filename = rs.getString("filename");
String filetype = rs.getString("filetype");
//
ExpImage expImage = new ExpImage(realName, filename, filetype);
expImage.setExpId(expId);
ExpenseItem expenseItem = new ExpenseItem(type, amount, itemDesc);
expenseItem.setExpId(expId);
Expense exp = new Expense(expId, empId, totalAmount, expTime, expDesc, nextAuditorId, lastResult, status);
expenseList.add(exp);
expenseItemList.add(expenseItem);
imageList.add(expImage);
}
//去除 <SUF>
for ( int i = 0 ; i < expenseList.size() - 1 ; i ++ ) {
for ( int j = expenseList.size() - 1 ; j > i; j -- ) {
if (expenseList.get(j).equals(expenseList.get(i))) {
expenseList.remove(j);
}
}
}
//
/* for (ExpenseItem item: expenseItemList){
System.out.println(item);
}*/
for (int i=0;i<expenseList.size();i++){
List<ExpenseItem> itemList = new ArrayList<ExpenseItem>();
for (int j=0;j<expenseItemList.size();j++){
if(expenseList.get(i).getExpId()==expenseItemList.get(j).getExpId()){
itemList.add(expenseItemList.get(j));
}
}
expenseList.get(i).setItemList(itemList);
for (int k=0;k<imageList.size();k++){
if(expenseList.get(i).getExpId()==imageList.get(k).getExpId()){
expenseList.get(i).setExpImage(imageList.get(k));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.closeAll(conn, pstmt, rs);
}
return expenseList;
}
}
| 1 | 6 | 1 |
47254_36 | package enumerated;
import java.util.*;
import net.mindview.util.*;
import static enumerated.Input.*;
import static net.mindview.util.Print.*;
enum Category { //使用Category枚举对贩卖机的状态进行了分类
MONEY(NICKEL/*5美分*/, DIME/*10美分*/, QUARTER/*25美分*/, DOLLAR/*100美分,即1美元*/){}, //金额
ITEM_SELECTION(TOOTHPASTE/*牙膏*/, CHIPS/*薯片*/, SODA/*苏打*/, SOAP/*香皂*/){}, //商品选项
QUIT_TRANSACTION(ABORT_TRANSACTION){}, //退出交易
SHUT_DOWN(STOP){}; //关闭
private Input[] values;
Category(Input... types) { values = types; }
private static EnumMap<Input,Category> categories = new EnumMap<Input,Category>(Input.class);
static {
for(Category c : Category.class.getEnumConstants()) { //获取Category枚举类的所有实例,c是Category枚举类的一个实例
for(Input type : c.values) { //type是c实例中成员变量values中的Input枚举类的一个实例
categories.put(type, c); //以Input贩卖机输入指令为key,类目为value
}
}
}
public static Category categorize(Input input) {
return categories.get(input);
}
}
/**
* @version 1.0
* @Description:
* @author: bingyu
* @date: 2021/6/25
*/
public class VendingMachine { //贩卖机
private static State state = State.RESTING; //贩卖机的状态,默认是休眠的
private static int amount = 0; //金额
private static Input selection = null; //选项
enum StateDuration { TRANSIENT } // enum1:状态持续时间枚举
enum State { // enum2:贩卖机的状态枚举
RESTING { //休眠
void next(Input input) {
switch(Category.categorize(input)) { //根据输入指令取出对应的类目
case MONEY: //如果输入的是金额选项,则增加金额,
amount += input.amount();
state = ADDING_MONEY; //贩卖机状态变为"投币状态"
break;
case SHUT_DOWN: //如果输入的是停止命令,则贩卖机状态变为"终止状态"
state = TERMINAL;
default:
}
}
},
ADDING_MONEY { //投币状态
void next(Input input) {
switch(Category.categorize(input)) {
case MONEY: //输入金额
amount += input.amount();
break;
case ITEM_SELECTION: //输入选择商品指令
selection = input;
if(amount < selection.amount()) { //判断付出的金额和商品的金额
print("Insufficient money for " + selection); //付出的金额<商品金额 金额不足
} else {
state = DISPENSING; //付出的金额 > 商品金额 状态变更为"可取出商品状态"
}
break;
case QUIT_TRANSACTION: //如果是输入的"退出交易指令"
state = GIVING_CHANGE; //状态变更为"找钱,即将原来投进去的钱退出来"
break;
case SHUT_DOWN: //输入的关闭指定
state = TERMINAL; //状态变更为"终止状态"
default:
}
}
},
DISPENSING(StateDuration.TRANSIENT) { //可取出商品状态
void next() {
print("here is your " + selection); //这是你的商品选项
amount -= selection.amount(); //扣除商品等价金额
state = GIVING_CHANGE; //状态变更为"找零钱"
}
},
GIVING_CHANGE(StateDuration.TRANSIENT) { //"找零钱状态"(注意因为这个枚举实例是用的带参构造器,所有它的isTransient=true)
void next() {
if(amount > 0) {
print("Your change: " + amount); //找零
amount = 0; //将机器里的金额置0
}
state = RESTING; //上面工作完成,状态变更为"休眠状态"
}
},
TERMINAL { void output() { print("Halted"); } }; //终止状态
private boolean isTransient = false; //枚举State用来判断是否是瞬时状态
State() {}
State(StateDuration trans) { isTransient = true; }
void next(Input input) { //只允许非瞬时状态的输入指定调用该方法(因为只有非瞬时状态枚举实例会重写该方法),否则就会抛异常
throw new RuntimeException("Only call " + "next(Input input) for non-transient states");
}
void next() { //只允许瞬时状态的输入指令调用该方法(因为只有瞬时状态枚举实例会重写该方法),否则就会抛异常
throw new RuntimeException("Only call next() for " + "StateDuration.TRANSIENT states");
}
void output() { print(amount); }
} //State枚举结束
/**
* 该方法永远不会停止,因为gen.next()不会返回stop命令
* @param gen
*/
static void run(Generator<Input> gen) {
while(state != State.TERMINAL) { //状态不是终止,就一直进行
Input input = gen.next();
state.next(input); //执行下一步命令
while(state.isTransient) { //如果枚举状态是瞬时的就执行下一步
state.next();
}
state.output(); //状态输出
}
}
public static void main(String[] args) {
Generator<Input> gen = new RandomInputGenerator();
if(args.length == 1) {
gen = new FileInputGenerator(args[0]);
}
run(gen);
}
} //VendingMachine结束
class RandomInputGenerator implements Generator<Input> {
public Input next() {
return Input.randomSelection(); //随机生成一个输入指令(但是不包括Stop)返回
}
}
// Create Inputs from a file of ‘;’-separated strings:
class FileInputGenerator implements Generator<Input> {
private Iterator<String> input;
public FileInputGenerator(String fileName) {
input = new TextFile(fileName, ";").iterator();
}
public Input next() {
if(!input.hasNext()) {
return null;
}
return Enum.valueOf(Input.class, input.next().trim());
}
}
| BingYu-track/Thinking-In-Java-Learning | src/enumerated/VendingMachine.java | 1,556 | //状态变更为"找零钱" | line_comment | zh-cn | package enumerated;
import java.util.*;
import net.mindview.util.*;
import static enumerated.Input.*;
import static net.mindview.util.Print.*;
enum Category { //使用Category枚举对贩卖机的状态进行了分类
MONEY(NICKEL/*5美分*/, DIME/*10美分*/, QUARTER/*25美分*/, DOLLAR/*100美分,即1美元*/){}, //金额
ITEM_SELECTION(TOOTHPASTE/*牙膏*/, CHIPS/*薯片*/, SODA/*苏打*/, SOAP/*香皂*/){}, //商品选项
QUIT_TRANSACTION(ABORT_TRANSACTION){}, //退出交易
SHUT_DOWN(STOP){}; //关闭
private Input[] values;
Category(Input... types) { values = types; }
private static EnumMap<Input,Category> categories = new EnumMap<Input,Category>(Input.class);
static {
for(Category c : Category.class.getEnumConstants()) { //获取Category枚举类的所有实例,c是Category枚举类的一个实例
for(Input type : c.values) { //type是c实例中成员变量values中的Input枚举类的一个实例
categories.put(type, c); //以Input贩卖机输入指令为key,类目为value
}
}
}
public static Category categorize(Input input) {
return categories.get(input);
}
}
/**
* @version 1.0
* @Description:
* @author: bingyu
* @date: 2021/6/25
*/
public class VendingMachine { //贩卖机
private static State state = State.RESTING; //贩卖机的状态,默认是休眠的
private static int amount = 0; //金额
private static Input selection = null; //选项
enum StateDuration { TRANSIENT } // enum1:状态持续时间枚举
enum State { // enum2:贩卖机的状态枚举
RESTING { //休眠
void next(Input input) {
switch(Category.categorize(input)) { //根据输入指令取出对应的类目
case MONEY: //如果输入的是金额选项,则增加金额,
amount += input.amount();
state = ADDING_MONEY; //贩卖机状态变为"投币状态"
break;
case SHUT_DOWN: //如果输入的是停止命令,则贩卖机状态变为"终止状态"
state = TERMINAL;
default:
}
}
},
ADDING_MONEY { //投币状态
void next(Input input) {
switch(Category.categorize(input)) {
case MONEY: //输入金额
amount += input.amount();
break;
case ITEM_SELECTION: //输入选择商品指令
selection = input;
if(amount < selection.amount()) { //判断付出的金额和商品的金额
print("Insufficient money for " + selection); //付出的金额<商品金额 金额不足
} else {
state = DISPENSING; //付出的金额 > 商品金额 状态变更为"可取出商品状态"
}
break;
case QUIT_TRANSACTION: //如果是输入的"退出交易指令"
state = GIVING_CHANGE; //状态变更为"找钱,即将原来投进去的钱退出来"
break;
case SHUT_DOWN: //输入的关闭指定
state = TERMINAL; //状态变更为"终止状态"
default:
}
}
},
DISPENSING(StateDuration.TRANSIENT) { //可取出商品状态
void next() {
print("here is your " + selection); //这是你的商品选项
amount -= selection.amount(); //扣除商品等价金额
state = GIVING_CHANGE; //状态 <SUF>
}
},
GIVING_CHANGE(StateDuration.TRANSIENT) { //"找零钱状态"(注意因为这个枚举实例是用的带参构造器,所有它的isTransient=true)
void next() {
if(amount > 0) {
print("Your change: " + amount); //找零
amount = 0; //将机器里的金额置0
}
state = RESTING; //上面工作完成,状态变更为"休眠状态"
}
},
TERMINAL { void output() { print("Halted"); } }; //终止状态
private boolean isTransient = false; //枚举State用来判断是否是瞬时状态
State() {}
State(StateDuration trans) { isTransient = true; }
void next(Input input) { //只允许非瞬时状态的输入指定调用该方法(因为只有非瞬时状态枚举实例会重写该方法),否则就会抛异常
throw new RuntimeException("Only call " + "next(Input input) for non-transient states");
}
void next() { //只允许瞬时状态的输入指令调用该方法(因为只有瞬时状态枚举实例会重写该方法),否则就会抛异常
throw new RuntimeException("Only call next() for " + "StateDuration.TRANSIENT states");
}
void output() { print(amount); }
} //State枚举结束
/**
* 该方法永远不会停止,因为gen.next()不会返回stop命令
* @param gen
*/
static void run(Generator<Input> gen) {
while(state != State.TERMINAL) { //状态不是终止,就一直进行
Input input = gen.next();
state.next(input); //执行下一步命令
while(state.isTransient) { //如果枚举状态是瞬时的就执行下一步
state.next();
}
state.output(); //状态输出
}
}
public static void main(String[] args) {
Generator<Input> gen = new RandomInputGenerator();
if(args.length == 1) {
gen = new FileInputGenerator(args[0]);
}
run(gen);
}
} //VendingMachine结束
class RandomInputGenerator implements Generator<Input> {
public Input next() {
return Input.randomSelection(); //随机生成一个输入指令(但是不包括Stop)返回
}
}
// Create Inputs from a file of ‘;’-separated strings:
class FileInputGenerator implements Generator<Input> {
private Iterator<String> input;
public FileInputGenerator(String fileName) {
input = new TextFile(fileName, ";").iterator();
}
public Input next() {
if(!input.hasNext()) {
return null;
}
return Enum.valueOf(Input.class, input.next().trim());
}
}
| 1 | 12 | 1 |
58841_4 | package com.hbh.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.hbh.entity.Type;
import com.hbh.entity.TypeExample;
/**
* @Author Binvor
* @Date 2019年3月25日下午2:24:36
* @Des 类别管理
*/
public interface ITypeService {
// 删除
int delete(String protypeid);
//插入
int insert(Type record);
//查询所有
List<Type> getall();
//根据主键查询
Type selectByid(String protypeid);
//更新
boolean update(Type record);
// 按条件查询
List<Type> getbyparams(String protypeid,String typename);
}
| BinvorWin/market | market/src/main/java/com/hbh/service/ITypeService.java | 201 | //根据主键查询
| line_comment | zh-cn | package com.hbh.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.hbh.entity.Type;
import com.hbh.entity.TypeExample;
/**
* @Author Binvor
* @Date 2019年3月25日下午2:24:36
* @Des 类别管理
*/
public interface ITypeService {
// 删除
int delete(String protypeid);
//插入
int insert(Type record);
//查询所有
List<Type> getall();
//根据 <SUF>
Type selectByid(String protypeid);
//更新
boolean update(Type record);
// 按条件查询
List<Type> getbyparams(String protypeid,String typename);
}
| 1 | 9 | 1 |
32006_7 | package glorydark.lockershop.items;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.form.element.ElementButtonImageData;
import cn.nukkit.math.Vector3f;
import cn.nukkit.network.protocol.SpawnParticleEffectPacket;
import cn.nukkit.utils.Config;
import glorydark.lockershop.MainClass;
import lombok.Data;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@Data
public class particleItem implements purchaseItem{
String name;
String displayName;
String description;
String identifier;
String category;
ElementButtonImageData iconData;
double needMoney;
boolean isAllowToUse; //可使用
boolean isPurchasable; //可购买
long duration;
public particleItem(String name, String displayName, String description, String category, ElementButtonImageData iconData, String identifier, double needMoney, boolean isAllowToUse, boolean isPurchasable, long duration){
this.name = name;
this.description = description;
this.displayName = displayName.replace("\\n", "\n");
this.identifier = identifier;
this.needMoney = needMoney;
this.isAllowToUse = isAllowToUse;
this.isPurchasable = isPurchasable;
this.duration = duration;
this.iconData = iconData;
this.category = category;
}
public void equip(Player player){
equip(player, true);
}
public void equip(Player player, boolean save){
if(isAllowToUse) {
if (save) {
MainClass.setDisplayParticle(player.getName(), this.getName());
}
MainClass.players.put(player, System.currentTimeMillis()+5000);
MainClass.particlesCache.put(player, MainClass.getDisplayParticle(player));
player.sendMessage("§a已装备粒子:" + this.getDisplayName());
}else{
player.sendMessage("§c§l[提示] 该粒子暂时不可用!");
}
}
public void remove(Player player){
//移除
MainClass.particlesCache.remove(player);
MainClass.setDisplayParticle(player.getName(), "");
player.sendMessage("§a已卸载粒子:"+this.getDisplayName());
}
public boolean claim(String player, String claimer, boolean purchase, Object... params){
if(MainClass.getUnlockedCapes(player).contains(this.getName())){
Player p = Server.getInstance().getPlayer(player);
if(p != null){
p.sendMessage("§c§l[提示] 您已拥有此粒子!");
}
return false;
}
if(purchase){
if(!isPurchasable) {
Player p = Server.getInstance().getPlayer(player);
if (p != null) {
p.sendMessage("§c§l[提示] 该粒子暂时不可购买!");
}
return false;
}
if(MainClass.economyAPI.myMoney(player) >= needMoney) {
MainClass.economyAPI.reduceMoney(player, needMoney);
}else{
Player p = Server.getInstance().getPlayer(player);
if(p != null){
p.sendMessage("§a§l[提示] 您的货币不足");
}
return false;
}
}
Config config = new Config(MainClass.path+"/players/"+player+".yml", Config.YAML);
Map<String, Object> map = new HashMap<>();
map.put("reducedMoney", needMoney);
map.put("date", getDate());
map.put("claimer", claimer);
if (duration == 0) {
map.put("due", 0);
} else {
long end;
if(params.length != 1) {
end = System.currentTimeMillis() + duration;
}else{
if(params[0].toString().equals("0")) {
end = 0;
}else{
end = System.currentTimeMillis() + Long.parseLong(params[0].toString());
}
}
map.put("due", end);
map.put("dueString", getDate(end));
}
config.set("particles."+name, map);
config.save();
Player p = Server.getInstance().getPlayer(player);
if(p != null){
p.sendMessage("§a§l[提示] 您获得了粒子:§e"+getDisplayName()+"§a,快去使用吧!");
}
return true;
}
public static String getDate(){
Calendar c1=Calendar.getInstance();
return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+
"月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+
":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND);
}
public static String getDate(Long time){
if(time == 0){
return "永久";
}
Calendar c1=new Calendar.Builder().build();
c1.setTimeInMillis(time);
return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+
"月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+
":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND);
}
// @author: wode490390
public void addCustomParticle(Player p){
if(isAllowToUse) {
SpawnParticleEffectPacket pk = new SpawnParticleEffectPacket(); // 此数据包用于调用客户端的颗粒效果
pk.position = new Vector3f((float) p.getX(), (float) p.getY(), (float) p.getZ()); // 生成颗粒效果的位置
pk.identifier = this.getIdentifier(); // 颗粒效果定义符, 必须和材质包内设定的一样, 否则不会显示
pk.dimensionId = 0; // 维度ID, 填玩家所在世界维度的即可, 默认为 0 (0: 主世界, 1: 地狱, 2: 末地)
pk.uniqueEntityId = -1; // 某实体的UUID, 目前无需理会, 默认为 -1
p.dataPacket(pk);
}
}
}
| BirdsStudio/LockerShop | src/main/java/glorydark/lockershop/items/particleItem.java | 1,517 | // 某实体的UUID, 目前无需理会, 默认为 -1 | line_comment | zh-cn | package glorydark.lockershop.items;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.form.element.ElementButtonImageData;
import cn.nukkit.math.Vector3f;
import cn.nukkit.network.protocol.SpawnParticleEffectPacket;
import cn.nukkit.utils.Config;
import glorydark.lockershop.MainClass;
import lombok.Data;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@Data
public class particleItem implements purchaseItem{
String name;
String displayName;
String description;
String identifier;
String category;
ElementButtonImageData iconData;
double needMoney;
boolean isAllowToUse; //可使用
boolean isPurchasable; //可购买
long duration;
public particleItem(String name, String displayName, String description, String category, ElementButtonImageData iconData, String identifier, double needMoney, boolean isAllowToUse, boolean isPurchasable, long duration){
this.name = name;
this.description = description;
this.displayName = displayName.replace("\\n", "\n");
this.identifier = identifier;
this.needMoney = needMoney;
this.isAllowToUse = isAllowToUse;
this.isPurchasable = isPurchasable;
this.duration = duration;
this.iconData = iconData;
this.category = category;
}
public void equip(Player player){
equip(player, true);
}
public void equip(Player player, boolean save){
if(isAllowToUse) {
if (save) {
MainClass.setDisplayParticle(player.getName(), this.getName());
}
MainClass.players.put(player, System.currentTimeMillis()+5000);
MainClass.particlesCache.put(player, MainClass.getDisplayParticle(player));
player.sendMessage("§a已装备粒子:" + this.getDisplayName());
}else{
player.sendMessage("§c§l[提示] 该粒子暂时不可用!");
}
}
public void remove(Player player){
//移除
MainClass.particlesCache.remove(player);
MainClass.setDisplayParticle(player.getName(), "");
player.sendMessage("§a已卸载粒子:"+this.getDisplayName());
}
public boolean claim(String player, String claimer, boolean purchase, Object... params){
if(MainClass.getUnlockedCapes(player).contains(this.getName())){
Player p = Server.getInstance().getPlayer(player);
if(p != null){
p.sendMessage("§c§l[提示] 您已拥有此粒子!");
}
return false;
}
if(purchase){
if(!isPurchasable) {
Player p = Server.getInstance().getPlayer(player);
if (p != null) {
p.sendMessage("§c§l[提示] 该粒子暂时不可购买!");
}
return false;
}
if(MainClass.economyAPI.myMoney(player) >= needMoney) {
MainClass.economyAPI.reduceMoney(player, needMoney);
}else{
Player p = Server.getInstance().getPlayer(player);
if(p != null){
p.sendMessage("§a§l[提示] 您的货币不足");
}
return false;
}
}
Config config = new Config(MainClass.path+"/players/"+player+".yml", Config.YAML);
Map<String, Object> map = new HashMap<>();
map.put("reducedMoney", needMoney);
map.put("date", getDate());
map.put("claimer", claimer);
if (duration == 0) {
map.put("due", 0);
} else {
long end;
if(params.length != 1) {
end = System.currentTimeMillis() + duration;
}else{
if(params[0].toString().equals("0")) {
end = 0;
}else{
end = System.currentTimeMillis() + Long.parseLong(params[0].toString());
}
}
map.put("due", end);
map.put("dueString", getDate(end));
}
config.set("particles."+name, map);
config.save();
Player p = Server.getInstance().getPlayer(player);
if(p != null){
p.sendMessage("§a§l[提示] 您获得了粒子:§e"+getDisplayName()+"§a,快去使用吧!");
}
return true;
}
public static String getDate(){
Calendar c1=Calendar.getInstance();
return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+
"月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+
":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND);
}
public static String getDate(Long time){
if(time == 0){
return "永久";
}
Calendar c1=new Calendar.Builder().build();
c1.setTimeInMillis(time);
return c1.get(Calendar.YEAR)+"年"+(c1.get(Calendar.MONTH)+1)+
"月"+c1.get(Calendar.DAY_OF_MONTH)+"日 "+c1.get(Calendar.HOUR_OF_DAY)+
":"+c1.get(Calendar.MINUTE)+":"+c1.get(Calendar.SECOND);
}
// @author: wode490390
public void addCustomParticle(Player p){
if(isAllowToUse) {
SpawnParticleEffectPacket pk = new SpawnParticleEffectPacket(); // 此数据包用于调用客户端的颗粒效果
pk.position = new Vector3f((float) p.getX(), (float) p.getY(), (float) p.getZ()); // 生成颗粒效果的位置
pk.identifier = this.getIdentifier(); // 颗粒效果定义符, 必须和材质包内设定的一样, 否则不会显示
pk.dimensionId = 0; // 维度ID, 填玩家所在世界维度的即可, 默认为 0 (0: 主世界, 1: 地狱, 2: 末地)
pk.uniqueEntityId = -1; // 某实 <SUF>
p.dataPacket(pk);
}
}
}
| 1 | 27 | 1 |
61341_7 | import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicSessionCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferManagerConfiguration;
import java.io.File;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
public class Put2Cos {
// 创建 COSClient 实例,这个实例用来后续调用请求
COSClient cosClient;
COSClient createCOSClient() {
// 这里需要已经获取到临时密钥的结果。
// 临时密钥的生成参见 https://cloud.tencent.com/document/product/436/14048#cos-sts-sdk
String tmpSecretId = "AKIDxtlXksCATQt8ke03yxktIRS9RkIO9w7XaoMI6EdniPH5lANEppIvZr7nPfVFa2QL";
String tmpSecretKey = "WJbz2PJGINWWAPgTKI6PgZPe+wqJLHoeGucagngmQUo=";
String sessionToken = "0mPmSkvHd48ByFqnLDh7qC0ADEEw66maac0fee1bbc1f2e60e2d8858bd0e478c5xtDJSGkwqe_uA-YxRxhBY2AHUzIibPpBKnWHMtCgvs9PuAXGmJHp3vK-_GLztko9GsX_FwY3QFoxaxlXQhLFNsE15q-IgL7-_jUV-RnojPDQB1dFBWgSSm0cU7d7W69CnrpB3VT-AimIEH1oZORmf7HnooYLlgWvMYvJjOPfY2lgoXmYFHi-FzldGsOmLul1CtTQpmfxfGnX-ZY0rFE2oQo5M0acTIIiAI5hMDfR2GYyh5RDApwS-W4PC8rWaP9Rw-zyLBuaBIZn-9salEx6tHWq5zFb4CByJ5XU9VAHuA0_vudfcSC1nR4rZA_FRjOlVnLIu2jWKAqZQoTSUdJKoTxua890ZbMNLbeyIDudMMVV0gO90aN0gxduW_qsL9RFMzia15LiUb4QOO0x7_pn4v-qNhx6cXCN2xak8AhsZREbA54EY73RiEoh37EKkO8VGVC5_13BjVCsZVtrdQR9TWAsMDMyK2Crf7oL-Dd_lGaRFV6HrglvsfHl8hvOchiPLeNsiGnB8iHOvp4h606owpbypGonEsJf8DPVwLPZMjVn8Gfzlt7qUXSscdDtl4UN6_hjso6hVYRhaW-475kzoR4J7nSHZUnbwjkdY36uMJNXbOFfrRwvyvVADTriAG1SO51IRJQqlyVU-zTnmfhJGiAfjrnG8ksLZQp0rk6_62GYhMcoo__K9iIe5NoJ5rGqn3I3ex6_RSrASnckpEeN-LED-1pHS14Ks5F2KIeanXISKV71DaShwurUZSUA6-mkBIbopklKwepypBWHy483Vg";
BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);
// ClientConfig 中包含了后续请求 COS 的客户端设置:
ClientConfig clientConfig = new ClientConfig();
// 设置 bucket 的地域
// COS_REGION 请参见 https://cloud.tencent.com/document/product/436/6224
clientConfig.setRegion(new Region("ap-beijing"));
// 设置请求协议, http 或者 https
// 5.6.53 及更低的版本,建议设置使用 https 协议
// 5.6.54 及更高版本,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 以下的设置,是可选的:
// 设置 socket 读取超时,默认 30s
clientConfig.setSocketTimeout(30*1000);
// 设置建立连接超时,默认 30s
clientConfig.setConnectionTimeout(30*1000);
// 如果需要的话,设置 http 代理,ip 以及 port
// clientConfig.setHttpProxyIp("httpProxyIp");
// clientConfig.setHttpProxyPort(80);
// 生成 cos 客户端。
return new COSClient(cred, clientConfig);
}
public String putObject(String FileName) throws InterruptedException {
Instant timeStamp = Instant.now();
String localFilePath = "uploaded/"+FileName+"_"+timeStamp.toString()+".pptx";
COSClient cosClient = createCOSClient();
File localFile = new File(localFilePath);
// 指定文件将要存放的存储桶
String bucketName = "ppt-helper-1300870583";
// 指定文件上传到 COS 上的路径,即对象键。例如对象键为 folder/picture.jpg,则表示将文件 picture.jpg 上传到 folder 路径下
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, FileName, localFile);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
System.out.println(putObjectResult);
return putObjectResult.toString();
}
public Put2Cos() {
cosClient = createCOSClient();
}
public static void main(String[] args) {
Put2Cos cos = new Put2Cos();
try {
System.out.println(cos.putObject("my12-3.pptx"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
| Bistu-OSSDT-2023/20-PPT-Helper | src/main/java/Put2Cos.java | 1,500 | // 5.6.53 及更低的版本,建议设置使用 https 协议 | line_comment | zh-cn | import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicSessionCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferManagerConfiguration;
import java.io.File;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
public class Put2Cos {
// 创建 COSClient 实例,这个实例用来后续调用请求
COSClient cosClient;
COSClient createCOSClient() {
// 这里需要已经获取到临时密钥的结果。
// 临时密钥的生成参见 https://cloud.tencent.com/document/product/436/14048#cos-sts-sdk
String tmpSecretId = "AKIDxtlXksCATQt8ke03yxktIRS9RkIO9w7XaoMI6EdniPH5lANEppIvZr7nPfVFa2QL";
String tmpSecretKey = "WJbz2PJGINWWAPgTKI6PgZPe+wqJLHoeGucagngmQUo=";
String sessionToken = "0mPmSkvHd48ByFqnLDh7qC0ADEEw66maac0fee1bbc1f2e60e2d8858bd0e478c5xtDJSGkwqe_uA-YxRxhBY2AHUzIibPpBKnWHMtCgvs9PuAXGmJHp3vK-_GLztko9GsX_FwY3QFoxaxlXQhLFNsE15q-IgL7-_jUV-RnojPDQB1dFBWgSSm0cU7d7W69CnrpB3VT-AimIEH1oZORmf7HnooYLlgWvMYvJjOPfY2lgoXmYFHi-FzldGsOmLul1CtTQpmfxfGnX-ZY0rFE2oQo5M0acTIIiAI5hMDfR2GYyh5RDApwS-W4PC8rWaP9Rw-zyLBuaBIZn-9salEx6tHWq5zFb4CByJ5XU9VAHuA0_vudfcSC1nR4rZA_FRjOlVnLIu2jWKAqZQoTSUdJKoTxua890ZbMNLbeyIDudMMVV0gO90aN0gxduW_qsL9RFMzia15LiUb4QOO0x7_pn4v-qNhx6cXCN2xak8AhsZREbA54EY73RiEoh37EKkO8VGVC5_13BjVCsZVtrdQR9TWAsMDMyK2Crf7oL-Dd_lGaRFV6HrglvsfHl8hvOchiPLeNsiGnB8iHOvp4h606owpbypGonEsJf8DPVwLPZMjVn8Gfzlt7qUXSscdDtl4UN6_hjso6hVYRhaW-475kzoR4J7nSHZUnbwjkdY36uMJNXbOFfrRwvyvVADTriAG1SO51IRJQqlyVU-zTnmfhJGiAfjrnG8ksLZQp0rk6_62GYhMcoo__K9iIe5NoJ5rGqn3I3ex6_RSrASnckpEeN-LED-1pHS14Ks5F2KIeanXISKV71DaShwurUZSUA6-mkBIbopklKwepypBWHy483Vg";
BasicSessionCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);
// ClientConfig 中包含了后续请求 COS 的客户端设置:
ClientConfig clientConfig = new ClientConfig();
// 设置 bucket 的地域
// COS_REGION 请参见 https://cloud.tencent.com/document/product/436/6224
clientConfig.setRegion(new Region("ap-beijing"));
// 设置请求协议, http 或者 https
// 5. <SUF>
// 5.6.54 及更高版本,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 以下的设置,是可选的:
// 设置 socket 读取超时,默认 30s
clientConfig.setSocketTimeout(30*1000);
// 设置建立连接超时,默认 30s
clientConfig.setConnectionTimeout(30*1000);
// 如果需要的话,设置 http 代理,ip 以及 port
// clientConfig.setHttpProxyIp("httpProxyIp");
// clientConfig.setHttpProxyPort(80);
// 生成 cos 客户端。
return new COSClient(cred, clientConfig);
}
public String putObject(String FileName) throws InterruptedException {
Instant timeStamp = Instant.now();
String localFilePath = "uploaded/"+FileName+"_"+timeStamp.toString()+".pptx";
COSClient cosClient = createCOSClient();
File localFile = new File(localFilePath);
// 指定文件将要存放的存储桶
String bucketName = "ppt-helper-1300870583";
// 指定文件上传到 COS 上的路径,即对象键。例如对象键为 folder/picture.jpg,则表示将文件 picture.jpg 上传到 folder 路径下
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, FileName, localFile);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
System.out.println(putObjectResult);
return putObjectResult.toString();
}
public Put2Cos() {
cosClient = createCOSClient();
}
public static void main(String[] args) {
Put2Cos cos = new Put2Cos();
try {
System.out.println(cos.putObject("my12-3.pptx"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
| 0 | 32 | 0 |
20080_4 | package Link;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.io.File;
public class Main extends Application {
TextArea News = new TextArea();
int fig_num = 33;
File file = new File("music/bgm1.mp3");
String url = file.toURI().toString();
Media media = new Media(url);
MediaPlayer mplayer = new MediaPlayer(media);
public void start(Stage stage){
//-------------------------------定义面板------------------------------------
VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
BorderPane bp = new BorderPane();
BorderPane Note = new BorderPane();
News.setMinHeight(190);
News.setMaxWidth(150);
Note.setTop(News);
//播放bgm
mplayer.setCycleCount(MediaPlayer.INDEFINITE);
mplayer.play();
//------------------------------------开始界面,设置中心面板和背景图----------------------------------
bp.setCenter(vBox);
bp.setStyle("-fx-background-image: url(" + "file:pic/bg3.jpeg" + "); " +
"-fx-background-position: center center; " +
"-fx-background-repeat: stretch;" +
"-fx-background-color: transparent;");
//------------------------------进入连连看面板--------------------------
Board bo = new Board(4,6,fig_num);//默认界面
vBox.getChildren().add(bo.getVbox());//获取连连看面板
bp.setCenter(vBox);
//------------------------------------上方菜单----------------------------------
MenuBar menuBar = new MenuBar();
Menu menu = new Menu("正常模式难度");
Menu menu1 = new Menu("记忆模式难度");
Menu menu2 = new Menu("图片数量");
Menu menu3 = new Menu("其他");
MenuItem bt_ease = new MenuItem("简单(4*4)");
MenuItem bt_mid = new MenuItem("中等(6*6)");
MenuItem bt_high = new MenuItem("困难(8*8)");
MenuItem bt_ghost = new MenuItem("炼狱(10*10)");
MenuItem bt_free = new MenuItem("自定义");
MenuItem bt_one = new MenuItem("简单(4*4)");
MenuItem bt_two = new MenuItem("中等(6*6)");
MenuItem bt_free1 = new MenuItem("自定义");
MenuItem bt_other1 = new MenuItem("NOTE");
//-----------------------------正常模式的按钮设置--------------------------
bt_ease.setOnAction(e->{
Board bo_ease = new Board(4,4,fig_num);
reset(bp,vBox,bo_ease);
});
bt_mid.setOnAction(e->{
Board bo_mid = new Board(6,6,fig_num);
reset(bp,vBox,bo_mid);
});
bt_high.setOnAction(e->{
Board bo_high = new Board(8,8,fig_num);
reset(bp,vBox,bo_high);
});
bt_ghost.setOnAction(e->{
Board bo_ghost = new Board(10,10,fig_num);
reset(bp,vBox,bo_ghost);
});
bt_free.setOnAction(e->{
Stage stage1 = new Stage();
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 380, 180, Color.WHITE);
GridPane in_put = new GridPane();
in_put.setPadding(new Insets(5));
in_put.setHgap(5);
in_put.setVgap(5);
ColumnConstraints column1 = new ColumnConstraints(100);
ColumnConstraints column2 = new ColumnConstraints(50, 150, 300);
column2.setHgrow(Priority.ALWAYS);
in_put.getColumnConstraints().addAll(column1, column2);
Label in_row = new Label("行");
Label in_column = new Label("列");
TextField in_row_num = new TextField();
TextField in_column_num = new TextField();
Button be_Sure = new Button("确认");
GridPane.setHalignment(in_row, HPos.RIGHT);
GridPane.setHalignment(in_column, HPos.RIGHT);
GridPane.setHalignment(in_row_num, HPos.LEFT);
GridPane.setHalignment(in_column_num, HPos.LEFT);
GridPane.setHalignment(be_Sure, HPos.RIGHT);
in_put.add(in_row, 0, 0);
in_put.add(in_column, 0, 1);
in_put.add(in_row_num, 1, 0);
in_put.add(in_column_num, 1, 1);
in_put.add(be_Sure, 1, 2);
be_Sure.setOnMouseClicked(e1->{
int real_r = Integer.parseInt(in_row_num.getText());
int real_c = Integer.parseInt(in_column_num.getText());
if(real_c % 2 == 0 || real_r % 2 ==0){
Board free_bo = new Board(real_r,real_c,fig_num);
reset(bp,vBox,free_bo);
stage1.close();
}
});
root.setCenter(in_put);
stage1.setScene(scene);
stage1.show();
});
//-----------------------------记忆模式的按钮设置----------------------------------
bt_one.setOnAction(e->{
Board_Remember br = new Board_Remember(4,4,fig_num);
reset(bp,vBox,br);
});
bt_two.setOnAction(e->{
Board_Remember br = new Board_Remember(6,6,fig_num);
reset(bp,vBox,br);
});
bt_free1.setOnAction(e->{
Stage stage1 = new Stage();
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 380, 150, Color.WHITE);
GridPane in_put = new GridPane();
in_put.setPadding(new Insets(5));
in_put.setHgap(5);
in_put.setVgap(5);
ColumnConstraints column1 = new ColumnConstraints(100);
ColumnConstraints column2 = new ColumnConstraints(50, 150, 300);
column2.setHgrow(Priority.ALWAYS);
in_put.getColumnConstraints().addAll(column1, column2);
Label in_row = new Label("行");
Label in_column = new Label("列");
TextField in_row_num = new TextField();
TextField in_column_num = new TextField();
Button be_Sure = new Button("确认");
GridPane.setHalignment(in_row, HPos.RIGHT);
GridPane.setHalignment(in_column, HPos.RIGHT);
GridPane.setHalignment(in_row_num, HPos.LEFT);
GridPane.setHalignment(in_column_num, HPos.LEFT);
GridPane.setHalignment(be_Sure, HPos.RIGHT);
in_put.add(in_row, 0, 0);
in_put.add(in_column, 0, 1);
in_put.add(in_row_num, 1, 0);
in_put.add(in_column_num, 1, 1);
in_put.add(be_Sure, 1, 2);
be_Sure.setOnMouseClicked(e1->{
int real_r = Integer.parseInt(in_row_num.getText());
int real_c = Integer.parseInt(in_column_num.getText());
if(real_c % 2 == 0 || real_r % 2 ==0){
Board_Remember free_bo = new Board_Remember(real_r,real_c,fig_num);
reset(bp,vBox,free_bo);
stage1.close();
}
});
root.setCenter(in_put);
stage1.setScene(scene);
stage1.show();
});
bt_other1.setOnAction(e->{
Stage stage1 = new Stage();
Pane pane = new Pane();
pane.getChildren().addAll(News);
Scene scene = new Scene(pane,400,200);
stage1.setScene(scene);
stage1.show();
});
//----------------------------------菜单布局-----------------------------
menu.getItems().addAll(bt_ease,bt_mid,bt_high,bt_ghost,bt_free);
menu1.getItems().addAll(bt_one,bt_two,bt_free1);
//改变全局变量的图片数量,要重新设置。
for(int i = 10 ; i <= 33; i++){
MenuItem bts = new MenuItem(""+i);
int k = i;
bts.setOnAction(e->fig_num=k);
menu2.getItems().add(bts);
}
menu3.getItems().addAll(bt_other1);
menuBar.getMenus().addAll(menu,menu1,menu2,menu3);
//------------------------------------布置场景--------------------------------
bp.setTop(menuBar);
final Scene scene = new Scene(bp,1000, 600);
stage.setScene(scene);
stage.setTitle("LiNK_LiNK");
stage.getIcons().add(new Image("file:pic/"+(int)(1+Math.random()*33)+".jpg"));
stage.show();
}
//-----------------------------------------刷新游戏界面---------------------------
public void reset(BorderPane bp,VBox vBox,Board bo){
vBox.getChildren().clear();
vBox.getChildren().add(bo.getVbox());
bp.setCenter(vBox);
}
}
| BitComing/Java_Homework_miniGame | src/Link/Main.java | 2,403 | //默认界面 | line_comment | zh-cn | package Link;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.io.File;
public class Main extends Application {
TextArea News = new TextArea();
int fig_num = 33;
File file = new File("music/bgm1.mp3");
String url = file.toURI().toString();
Media media = new Media(url);
MediaPlayer mplayer = new MediaPlayer(media);
public void start(Stage stage){
//-------------------------------定义面板------------------------------------
VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
BorderPane bp = new BorderPane();
BorderPane Note = new BorderPane();
News.setMinHeight(190);
News.setMaxWidth(150);
Note.setTop(News);
//播放bgm
mplayer.setCycleCount(MediaPlayer.INDEFINITE);
mplayer.play();
//------------------------------------开始界面,设置中心面板和背景图----------------------------------
bp.setCenter(vBox);
bp.setStyle("-fx-background-image: url(" + "file:pic/bg3.jpeg" + "); " +
"-fx-background-position: center center; " +
"-fx-background-repeat: stretch;" +
"-fx-background-color: transparent;");
//------------------------------进入连连看面板--------------------------
Board bo = new Board(4,6,fig_num);//默认 <SUF>
vBox.getChildren().add(bo.getVbox());//获取连连看面板
bp.setCenter(vBox);
//------------------------------------上方菜单----------------------------------
MenuBar menuBar = new MenuBar();
Menu menu = new Menu("正常模式难度");
Menu menu1 = new Menu("记忆模式难度");
Menu menu2 = new Menu("图片数量");
Menu menu3 = new Menu("其他");
MenuItem bt_ease = new MenuItem("简单(4*4)");
MenuItem bt_mid = new MenuItem("中等(6*6)");
MenuItem bt_high = new MenuItem("困难(8*8)");
MenuItem bt_ghost = new MenuItem("炼狱(10*10)");
MenuItem bt_free = new MenuItem("自定义");
MenuItem bt_one = new MenuItem("简单(4*4)");
MenuItem bt_two = new MenuItem("中等(6*6)");
MenuItem bt_free1 = new MenuItem("自定义");
MenuItem bt_other1 = new MenuItem("NOTE");
//-----------------------------正常模式的按钮设置--------------------------
bt_ease.setOnAction(e->{
Board bo_ease = new Board(4,4,fig_num);
reset(bp,vBox,bo_ease);
});
bt_mid.setOnAction(e->{
Board bo_mid = new Board(6,6,fig_num);
reset(bp,vBox,bo_mid);
});
bt_high.setOnAction(e->{
Board bo_high = new Board(8,8,fig_num);
reset(bp,vBox,bo_high);
});
bt_ghost.setOnAction(e->{
Board bo_ghost = new Board(10,10,fig_num);
reset(bp,vBox,bo_ghost);
});
bt_free.setOnAction(e->{
Stage stage1 = new Stage();
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 380, 180, Color.WHITE);
GridPane in_put = new GridPane();
in_put.setPadding(new Insets(5));
in_put.setHgap(5);
in_put.setVgap(5);
ColumnConstraints column1 = new ColumnConstraints(100);
ColumnConstraints column2 = new ColumnConstraints(50, 150, 300);
column2.setHgrow(Priority.ALWAYS);
in_put.getColumnConstraints().addAll(column1, column2);
Label in_row = new Label("行");
Label in_column = new Label("列");
TextField in_row_num = new TextField();
TextField in_column_num = new TextField();
Button be_Sure = new Button("确认");
GridPane.setHalignment(in_row, HPos.RIGHT);
GridPane.setHalignment(in_column, HPos.RIGHT);
GridPane.setHalignment(in_row_num, HPos.LEFT);
GridPane.setHalignment(in_column_num, HPos.LEFT);
GridPane.setHalignment(be_Sure, HPos.RIGHT);
in_put.add(in_row, 0, 0);
in_put.add(in_column, 0, 1);
in_put.add(in_row_num, 1, 0);
in_put.add(in_column_num, 1, 1);
in_put.add(be_Sure, 1, 2);
be_Sure.setOnMouseClicked(e1->{
int real_r = Integer.parseInt(in_row_num.getText());
int real_c = Integer.parseInt(in_column_num.getText());
if(real_c % 2 == 0 || real_r % 2 ==0){
Board free_bo = new Board(real_r,real_c,fig_num);
reset(bp,vBox,free_bo);
stage1.close();
}
});
root.setCenter(in_put);
stage1.setScene(scene);
stage1.show();
});
//-----------------------------记忆模式的按钮设置----------------------------------
bt_one.setOnAction(e->{
Board_Remember br = new Board_Remember(4,4,fig_num);
reset(bp,vBox,br);
});
bt_two.setOnAction(e->{
Board_Remember br = new Board_Remember(6,6,fig_num);
reset(bp,vBox,br);
});
bt_free1.setOnAction(e->{
Stage stage1 = new Stage();
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 380, 150, Color.WHITE);
GridPane in_put = new GridPane();
in_put.setPadding(new Insets(5));
in_put.setHgap(5);
in_put.setVgap(5);
ColumnConstraints column1 = new ColumnConstraints(100);
ColumnConstraints column2 = new ColumnConstraints(50, 150, 300);
column2.setHgrow(Priority.ALWAYS);
in_put.getColumnConstraints().addAll(column1, column2);
Label in_row = new Label("行");
Label in_column = new Label("列");
TextField in_row_num = new TextField();
TextField in_column_num = new TextField();
Button be_Sure = new Button("确认");
GridPane.setHalignment(in_row, HPos.RIGHT);
GridPane.setHalignment(in_column, HPos.RIGHT);
GridPane.setHalignment(in_row_num, HPos.LEFT);
GridPane.setHalignment(in_column_num, HPos.LEFT);
GridPane.setHalignment(be_Sure, HPos.RIGHT);
in_put.add(in_row, 0, 0);
in_put.add(in_column, 0, 1);
in_put.add(in_row_num, 1, 0);
in_put.add(in_column_num, 1, 1);
in_put.add(be_Sure, 1, 2);
be_Sure.setOnMouseClicked(e1->{
int real_r = Integer.parseInt(in_row_num.getText());
int real_c = Integer.parseInt(in_column_num.getText());
if(real_c % 2 == 0 || real_r % 2 ==0){
Board_Remember free_bo = new Board_Remember(real_r,real_c,fig_num);
reset(bp,vBox,free_bo);
stage1.close();
}
});
root.setCenter(in_put);
stage1.setScene(scene);
stage1.show();
});
bt_other1.setOnAction(e->{
Stage stage1 = new Stage();
Pane pane = new Pane();
pane.getChildren().addAll(News);
Scene scene = new Scene(pane,400,200);
stage1.setScene(scene);
stage1.show();
});
//----------------------------------菜单布局-----------------------------
menu.getItems().addAll(bt_ease,bt_mid,bt_high,bt_ghost,bt_free);
menu1.getItems().addAll(bt_one,bt_two,bt_free1);
//改变全局变量的图片数量,要重新设置。
for(int i = 10 ; i <= 33; i++){
MenuItem bts = new MenuItem(""+i);
int k = i;
bts.setOnAction(e->fig_num=k);
menu2.getItems().add(bts);
}
menu3.getItems().addAll(bt_other1);
menuBar.getMenus().addAll(menu,menu1,menu2,menu3);
//------------------------------------布置场景--------------------------------
bp.setTop(menuBar);
final Scene scene = new Scene(bp,1000, 600);
stage.setScene(scene);
stage.setTitle("LiNK_LiNK");
stage.getIcons().add(new Image("file:pic/"+(int)(1+Math.random()*33)+".jpg"));
stage.show();
}
//-----------------------------------------刷新游戏界面---------------------------
public void reset(BorderPane bp,VBox vBox,Board bo){
vBox.getChildren().clear();
vBox.getChildren().add(bo.getVbox());
bp.setCenter(vBox);
}
}
| 1 | 6 | 1 |
23743_4 | package cn.bixin.sona.demo.web.controller;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import cn.bixin.sona.api.im.RouterRoomMessageService;
import cn.bixin.sona.api.im.enums.PriorityEnum;
import cn.bixin.sona.api.im.request.RoomMessageRequest;
import cn.bixin.sona.api.room.SonaRoomQueryRemoteService;
import cn.bixin.sona.common.dto.PageResult;
import cn.bixin.sona.common.dto.Response;
import cn.bixin.sona.demo.web.message.MessgeInfo;
import cn.bixin.sona.demo.web.message.MicMessage;
import cn.bixin.sona.demo.web.message.RewardMessage;
import cn.bixin.sona.demo.web.message.RewardMessage2;
import cn.bixin.sona.demo.web.request.MicRequest;
import cn.bixin.sona.demo.web.request.RewardRequest;
import cn.bixin.sona.demo.web.response.GiftInfoVO;
import cn.bixin.sona.demo.web.response.RoomInfoVO;
import cn.bixin.sona.demo.web.response.SeatInfoVO;
import cn.bixin.sona.dto.RoomDTO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* demo
*/
@Slf4j
@RestController
@RequestMapping("/sona/demo")
public class SonaDemoController {
@DubboReference
private SonaRoomQueryRemoteService sonaRoomQueryRemoteService;
@DubboReference
private RouterRoomMessageService routerRoomMessageService;
private Map<String, List<SeatInfoVO>> roomSeatMap = Maps.newHashMap();
private static Map<Integer, String> giftMap = Maps.newHashMap();
static {
giftMap.put(1, "海豚恋人");
giftMap.put(2, "萌兔兔");
giftMap.put(3, "原谅帽");
giftMap.put(4, "海上城堡");
}
/**
* 获取房间列表
*/
@GetMapping(path = {"/room/list"})
public Response<List<RoomDTO>> getOnlineRoomList() {
Response<PageResult<RoomDTO>> response = sonaRoomQueryRemoteService.getOnlineRoomList("0", 100);
if (!response.isSuccess()) {
return Response.success(Collections.emptyList());
}
return Response.success(response.getResult().getList());
}
/**
* 获取房间列表
*/
@GetMapping(path = {"/room/info"})
public Response<RoomInfoVO> getRoomInfo(@RequestParam String roomId) {
Response<RoomDTO> response = sonaRoomQueryRemoteService.getRoom(Long.valueOf(roomId));
if (!response.isSuccess() || response.getResult() == null) {
return Response.success(null);
}
RoomDTO roomDTO = response.getResult();
RoomInfoVO vo = new RoomInfoVO();
vo.setName(roomDTO.getName());
vo.setRoomId(roomDTO.getRoomId() + "");
List<SeatInfoVO> seatInfoVOS = roomSeatMap.get(roomDTO.getRoomId() + "");
if (CollectionUtils.isEmpty(seatInfoVOS)) {
seatInfoVOS = Lists.newArrayList();
initSeatList(seatInfoVOS);
roomSeatMap.put(roomId, seatInfoVOS);
}
vo.setSeatList(seatInfoVOS);
return Response.success(vo);
}
private void initSeatList(List<SeatInfoVO> seatInfoVOS) {
SeatInfoVO s1 = new SeatInfoVO();
s1.setUid("");
s1.setIndex(0);
seatInfoVOS.add(s1);
SeatInfoVO s2 = new SeatInfoVO();
s2.setIndex(1);
s2.setUid("");
seatInfoVOS.add(s2);
SeatInfoVO s3 = new SeatInfoVO();
s3.setIndex(2);
s3.setUid("");
seatInfoVOS.add(s3);
SeatInfoVO s4 = new SeatInfoVO();
s4.setUid("");
s4.setIndex(3);
seatInfoVOS.add(s4);
SeatInfoVO s5 = new SeatInfoVO();
s5.setUid("");
s5.setIndex(4);
seatInfoVOS.add(s5);
SeatInfoVO s6 = new SeatInfoVO();
s6.setUid("");
s6.setIndex(5);
seatInfoVOS.add(s6);
}
/**
* 获取礼物列表
*/
@GetMapping(path = {"/gift/list"})
public Response<List<GiftInfoVO>> getGiftList() {
List<GiftInfoVO> list = Lists.newArrayList();
GiftInfoVO gift1 = new GiftInfoVO();
gift1.setGiftId(1);
gift1.setGiftName("海豚恋人");
gift1.setPrice(5200);
list.add(gift1);
GiftInfoVO gift2 = new GiftInfoVO();
gift2.setGiftId(2);
gift2.setGiftName("萌兔兔");
gift2.setPrice(100);
list.add(gift2);
GiftInfoVO gift3 = new GiftInfoVO();
gift3.setGiftId(3);
gift3.setGiftName("原谅帽");
gift3.setPrice(200);
list.add(gift3);
GiftInfoVO gift4 = new GiftInfoVO();
gift4.setGiftId(4);
gift4.setGiftName("海上城堡");
gift4.setPrice(400);
list.add(gift4);
return Response.success(list);
}
/**
* 礼物打赏
*/
@PostMapping(path = {"/gift/reward"})
public Response<Boolean> reward(@RequestBody RewardRequest rewardRequest) {
RoomMessageRequest request = new RoomMessageRequest();
request.setRoomId(Long.valueOf(rewardRequest.getRoomId()));
request.setPriority(PriorityEnum.HIGH);
request.setProductCode("CHATROOM");
request.setMsgType("REWARD");
RewardMessage rewardMessage = new RewardMessage();
rewardMessage.setGiftId(rewardRequest.getGiftId());
rewardMessage.setRoomId(rewardRequest.getRoomId());
rewardMessage.setUid(rewardRequest.getToUid());
RewardMessage2 rewardMessage2 = new RewardMessage2();
rewardMessage2.setGiftId(rewardRequest.getGiftId());
rewardMessage2.setFromUid(rewardRequest.getFromUid());
rewardMessage2.setToUid(rewardRequest.getToUid());
rewardMessage2.setRoomId(rewardRequest.getRoomId());
rewardMessage2.setGiftName(giftMap.get(rewardRequest.getGiftId()));
MessgeInfo messageInfo = new MessgeInfo();
messageInfo.setData(JSON.toJSONString(rewardMessage));
messageInfo.setMsgType(303);
request.setContent(JSON.toJSONString(messageInfo));
routerRoomMessageService.sendChatRoomMessage(request);
MessgeInfo messageInfo2 = new MessgeInfo();
messageInfo2.setData(JSON.toJSONString(rewardMessage2));
messageInfo2.setMsgType(304);
request.setContent(JSON.toJSONString(messageInfo2));
routerRoomMessageService.sendChatRoomMessage(request);
return Response.success(true);
}
/**
* 上下麦
*/
@PostMapping(path = {"/room/mic"})
public Response<Boolean> doMic(@RequestBody MicRequest micRequest) {
RoomMessageRequest request = new RoomMessageRequest();
request.setRoomId(Long.valueOf(micRequest.getRoomId()));
request.setPriority(PriorityEnum.HIGH);
request.setProductCode("CHATROOM");
request.setMsgType("MIC");
MicMessage micMessage = new MicMessage();
micMessage.setUid(micRequest.getUid());
micMessage.setRoomId(micRequest.getRoomId());
micMessage.setOperate(micRequest.getOperate());
micMessage.setIndex(micRequest.getIndex());
MessgeInfo messgeInfo = new MessgeInfo();
messgeInfo.setData(JSON.toJSONString(micMessage));
messgeInfo.setMsgType(203);
request.setContent(JSON.toJSONString(messgeInfo));
routerRoomMessageService.sendChatRoomMessage(request);
String roomId = micRequest.getRoomId();
if (micMessage.getOperate() == 1) {
List<SeatInfoVO> seatList = roomSeatMap.get(roomId);
if (CollectionUtils.isEmpty(seatList)) {
seatList = Lists.newArrayList();
}
SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null);
if (seatInfo == null) {
seatInfo = new SeatInfoVO();
seatInfo.setIndex(micMessage.getIndex());
seatInfo.setUid(micRequest.getUid());
seatList.add(seatInfo);
} else {
seatInfo.setUid(micRequest.getUid());
}
roomSeatMap.put(roomId, seatList);
} else {
List<SeatInfoVO> seatList = roomSeatMap.get(roomId);
if (!CollectionUtils.isEmpty(seatList)) {
SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null);
if (seatInfo != null) {
seatInfo.setUid("");
}
}
roomSeatMap.put(roomId, seatList);
}
return Response.success(true);
}
}
| BixinTech/sona | sona-demo-web/src/main/java/cn/bixin/sona/demo/web/controller/SonaDemoController.java | 2,513 | /**
* 礼物打赏
*/ | block_comment | zh-cn | package cn.bixin.sona.demo.web.controller;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import cn.bixin.sona.api.im.RouterRoomMessageService;
import cn.bixin.sona.api.im.enums.PriorityEnum;
import cn.bixin.sona.api.im.request.RoomMessageRequest;
import cn.bixin.sona.api.room.SonaRoomQueryRemoteService;
import cn.bixin.sona.common.dto.PageResult;
import cn.bixin.sona.common.dto.Response;
import cn.bixin.sona.demo.web.message.MessgeInfo;
import cn.bixin.sona.demo.web.message.MicMessage;
import cn.bixin.sona.demo.web.message.RewardMessage;
import cn.bixin.sona.demo.web.message.RewardMessage2;
import cn.bixin.sona.demo.web.request.MicRequest;
import cn.bixin.sona.demo.web.request.RewardRequest;
import cn.bixin.sona.demo.web.response.GiftInfoVO;
import cn.bixin.sona.demo.web.response.RoomInfoVO;
import cn.bixin.sona.demo.web.response.SeatInfoVO;
import cn.bixin.sona.dto.RoomDTO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* demo
*/
@Slf4j
@RestController
@RequestMapping("/sona/demo")
public class SonaDemoController {
@DubboReference
private SonaRoomQueryRemoteService sonaRoomQueryRemoteService;
@DubboReference
private RouterRoomMessageService routerRoomMessageService;
private Map<String, List<SeatInfoVO>> roomSeatMap = Maps.newHashMap();
private static Map<Integer, String> giftMap = Maps.newHashMap();
static {
giftMap.put(1, "海豚恋人");
giftMap.put(2, "萌兔兔");
giftMap.put(3, "原谅帽");
giftMap.put(4, "海上城堡");
}
/**
* 获取房间列表
*/
@GetMapping(path = {"/room/list"})
public Response<List<RoomDTO>> getOnlineRoomList() {
Response<PageResult<RoomDTO>> response = sonaRoomQueryRemoteService.getOnlineRoomList("0", 100);
if (!response.isSuccess()) {
return Response.success(Collections.emptyList());
}
return Response.success(response.getResult().getList());
}
/**
* 获取房间列表
*/
@GetMapping(path = {"/room/info"})
public Response<RoomInfoVO> getRoomInfo(@RequestParam String roomId) {
Response<RoomDTO> response = sonaRoomQueryRemoteService.getRoom(Long.valueOf(roomId));
if (!response.isSuccess() || response.getResult() == null) {
return Response.success(null);
}
RoomDTO roomDTO = response.getResult();
RoomInfoVO vo = new RoomInfoVO();
vo.setName(roomDTO.getName());
vo.setRoomId(roomDTO.getRoomId() + "");
List<SeatInfoVO> seatInfoVOS = roomSeatMap.get(roomDTO.getRoomId() + "");
if (CollectionUtils.isEmpty(seatInfoVOS)) {
seatInfoVOS = Lists.newArrayList();
initSeatList(seatInfoVOS);
roomSeatMap.put(roomId, seatInfoVOS);
}
vo.setSeatList(seatInfoVOS);
return Response.success(vo);
}
private void initSeatList(List<SeatInfoVO> seatInfoVOS) {
SeatInfoVO s1 = new SeatInfoVO();
s1.setUid("");
s1.setIndex(0);
seatInfoVOS.add(s1);
SeatInfoVO s2 = new SeatInfoVO();
s2.setIndex(1);
s2.setUid("");
seatInfoVOS.add(s2);
SeatInfoVO s3 = new SeatInfoVO();
s3.setIndex(2);
s3.setUid("");
seatInfoVOS.add(s3);
SeatInfoVO s4 = new SeatInfoVO();
s4.setUid("");
s4.setIndex(3);
seatInfoVOS.add(s4);
SeatInfoVO s5 = new SeatInfoVO();
s5.setUid("");
s5.setIndex(4);
seatInfoVOS.add(s5);
SeatInfoVO s6 = new SeatInfoVO();
s6.setUid("");
s6.setIndex(5);
seatInfoVOS.add(s6);
}
/**
* 获取礼物列表
*/
@GetMapping(path = {"/gift/list"})
public Response<List<GiftInfoVO>> getGiftList() {
List<GiftInfoVO> list = Lists.newArrayList();
GiftInfoVO gift1 = new GiftInfoVO();
gift1.setGiftId(1);
gift1.setGiftName("海豚恋人");
gift1.setPrice(5200);
list.add(gift1);
GiftInfoVO gift2 = new GiftInfoVO();
gift2.setGiftId(2);
gift2.setGiftName("萌兔兔");
gift2.setPrice(100);
list.add(gift2);
GiftInfoVO gift3 = new GiftInfoVO();
gift3.setGiftId(3);
gift3.setGiftName("原谅帽");
gift3.setPrice(200);
list.add(gift3);
GiftInfoVO gift4 = new GiftInfoVO();
gift4.setGiftId(4);
gift4.setGiftName("海上城堡");
gift4.setPrice(400);
list.add(gift4);
return Response.success(list);
}
/**
* 礼物打 <SUF>*/
@PostMapping(path = {"/gift/reward"})
public Response<Boolean> reward(@RequestBody RewardRequest rewardRequest) {
RoomMessageRequest request = new RoomMessageRequest();
request.setRoomId(Long.valueOf(rewardRequest.getRoomId()));
request.setPriority(PriorityEnum.HIGH);
request.setProductCode("CHATROOM");
request.setMsgType("REWARD");
RewardMessage rewardMessage = new RewardMessage();
rewardMessage.setGiftId(rewardRequest.getGiftId());
rewardMessage.setRoomId(rewardRequest.getRoomId());
rewardMessage.setUid(rewardRequest.getToUid());
RewardMessage2 rewardMessage2 = new RewardMessage2();
rewardMessage2.setGiftId(rewardRequest.getGiftId());
rewardMessage2.setFromUid(rewardRequest.getFromUid());
rewardMessage2.setToUid(rewardRequest.getToUid());
rewardMessage2.setRoomId(rewardRequest.getRoomId());
rewardMessage2.setGiftName(giftMap.get(rewardRequest.getGiftId()));
MessgeInfo messageInfo = new MessgeInfo();
messageInfo.setData(JSON.toJSONString(rewardMessage));
messageInfo.setMsgType(303);
request.setContent(JSON.toJSONString(messageInfo));
routerRoomMessageService.sendChatRoomMessage(request);
MessgeInfo messageInfo2 = new MessgeInfo();
messageInfo2.setData(JSON.toJSONString(rewardMessage2));
messageInfo2.setMsgType(304);
request.setContent(JSON.toJSONString(messageInfo2));
routerRoomMessageService.sendChatRoomMessage(request);
return Response.success(true);
}
/**
* 上下麦
*/
@PostMapping(path = {"/room/mic"})
public Response<Boolean> doMic(@RequestBody MicRequest micRequest) {
RoomMessageRequest request = new RoomMessageRequest();
request.setRoomId(Long.valueOf(micRequest.getRoomId()));
request.setPriority(PriorityEnum.HIGH);
request.setProductCode("CHATROOM");
request.setMsgType("MIC");
MicMessage micMessage = new MicMessage();
micMessage.setUid(micRequest.getUid());
micMessage.setRoomId(micRequest.getRoomId());
micMessage.setOperate(micRequest.getOperate());
micMessage.setIndex(micRequest.getIndex());
MessgeInfo messgeInfo = new MessgeInfo();
messgeInfo.setData(JSON.toJSONString(micMessage));
messgeInfo.setMsgType(203);
request.setContent(JSON.toJSONString(messgeInfo));
routerRoomMessageService.sendChatRoomMessage(request);
String roomId = micRequest.getRoomId();
if (micMessage.getOperate() == 1) {
List<SeatInfoVO> seatList = roomSeatMap.get(roomId);
if (CollectionUtils.isEmpty(seatList)) {
seatList = Lists.newArrayList();
}
SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null);
if (seatInfo == null) {
seatInfo = new SeatInfoVO();
seatInfo.setIndex(micMessage.getIndex());
seatInfo.setUid(micRequest.getUid());
seatList.add(seatInfo);
} else {
seatInfo.setUid(micRequest.getUid());
}
roomSeatMap.put(roomId, seatList);
} else {
List<SeatInfoVO> seatList = roomSeatMap.get(roomId);
if (!CollectionUtils.isEmpty(seatList)) {
SeatInfoVO seatInfo = seatList.stream().filter(each -> each.getIndex() == micRequest.getIndex()).findFirst().orElse(null);
if (seatInfo != null) {
seatInfo.setUid("");
}
}
roomSeatMap.put(roomId, seatList);
}
return Response.success(true);
}
}
| 1 | 23 | 1 |
37940_6 | package github.saukiya.pvpaswantedmanager.event;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import github.saukiya.pvpaswantedmanager.JailManager;
import github.saukiya.pvpaswantedmanager.util.Config;
import github.saukiya.pvpaswantedmanager.util.Data;
import github.saukiya.pvpaswantedmanager.util.PlayerData;
import github.saukiya.pvpaswantedmanager.util.Message;
import github.saukiya.pvpaswantedmanager.util.Money;
/*本类由 Saukiya 在 2018年2月14日 上午12:31:13 时创建
*TIM:[email protected]
*GitHub:https://github.com/Saukiya
**/
public class PlayerDeath implements Listener {
@EventHandler
public void onPlayerDeathEvent(PlayerDeathEvent event){
Player player = event.getEntity();
if(!Data.isOn(player.getWorld().getName()))return;
Player killer = player.getKiller();
Location loc = player.getLocation();
System.out.println(" ");
System.out.println(player +" "+ killer);
System.out.println(loc);
PlayerData playerData = Data.getPlayerData(player.getName());
int playerWantedPoints = playerData.getW_Points();
int playerJailCumulativeNumber = playerData.getJ_CumulativeNumber();
//玩家与玩家之间
if(killer !=null){
PlayerData killerData = Data.getPlayerData(killer.getName());
if(Data.isAsWanted(player.getName(), killerData)){//通缉状态
//处理通缉犯
int jailTime = Integer.valueOf(Config.getConfig(Config.TIMETICK_JAIL_PLAYER_TIMES).replaceAll("[^0-9]", ""));
playerData.setJ_Times(playerData.getW_Points()*jailTime);
playerData.setW_Points(0);
playerData.addJ_CumulativeNumber();
playerData.setA_loc(loc);
player.spigot().respawn();
//TODO 传送到指定位置
JailManager.tpJailLocation(player);
Data.removeWantedList(player.getName());
Double taskRewardMoney = Double.valueOf(Config.getConfig(Config.TASKREWARD_MONEY));
if(Config.getConfig(Config.ARREST_PUNISH_ENABLED).equalsIgnoreCase("true")){
if(Money.has(player.getName(), playerWantedPoints*taskRewardMoney)){
Money.take(player.getName(), playerWantedPoints*taskRewardMoney);
player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH, String.valueOf(playerWantedPoints*taskRewardMoney)));
}else{
playerData.setJ_Times(playerData.getJ_Times()+(playerWantedPoints*10));
player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH_FAIL, String.valueOf(playerWantedPoints*10)));
}
}
//处理逮捕人员
}else{//击杀状态
}
}
if(playerData.getW_Points()>0)Data.takePlayerLevel(player, playerData.getW_Points());
}
}
| Bkm016/PAWM-Reloaded | src/github/saukiya/pvpaswantedmanager/event/PlayerDeath.java | 860 | //击杀状态 | line_comment | zh-cn | package github.saukiya.pvpaswantedmanager.event;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import github.saukiya.pvpaswantedmanager.JailManager;
import github.saukiya.pvpaswantedmanager.util.Config;
import github.saukiya.pvpaswantedmanager.util.Data;
import github.saukiya.pvpaswantedmanager.util.PlayerData;
import github.saukiya.pvpaswantedmanager.util.Message;
import github.saukiya.pvpaswantedmanager.util.Money;
/*本类由 Saukiya 在 2018年2月14日 上午12:31:13 时创建
*TIM:[email protected]
*GitHub:https://github.com/Saukiya
**/
public class PlayerDeath implements Listener {
@EventHandler
public void onPlayerDeathEvent(PlayerDeathEvent event){
Player player = event.getEntity();
if(!Data.isOn(player.getWorld().getName()))return;
Player killer = player.getKiller();
Location loc = player.getLocation();
System.out.println(" ");
System.out.println(player +" "+ killer);
System.out.println(loc);
PlayerData playerData = Data.getPlayerData(player.getName());
int playerWantedPoints = playerData.getW_Points();
int playerJailCumulativeNumber = playerData.getJ_CumulativeNumber();
//玩家与玩家之间
if(killer !=null){
PlayerData killerData = Data.getPlayerData(killer.getName());
if(Data.isAsWanted(player.getName(), killerData)){//通缉状态
//处理通缉犯
int jailTime = Integer.valueOf(Config.getConfig(Config.TIMETICK_JAIL_PLAYER_TIMES).replaceAll("[^0-9]", ""));
playerData.setJ_Times(playerData.getW_Points()*jailTime);
playerData.setW_Points(0);
playerData.addJ_CumulativeNumber();
playerData.setA_loc(loc);
player.spigot().respawn();
//TODO 传送到指定位置
JailManager.tpJailLocation(player);
Data.removeWantedList(player.getName());
Double taskRewardMoney = Double.valueOf(Config.getConfig(Config.TASKREWARD_MONEY));
if(Config.getConfig(Config.ARREST_PUNISH_ENABLED).equalsIgnoreCase("true")){
if(Money.has(player.getName(), playerWantedPoints*taskRewardMoney)){
Money.take(player.getName(), playerWantedPoints*taskRewardMoney);
player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH, String.valueOf(playerWantedPoints*taskRewardMoney)));
}else{
playerData.setJ_Times(playerData.getJ_Times()+(playerWantedPoints*10));
player.sendMessage(Message.getMsg(Message.PLAYER_ARREST_PUNISH_FAIL, String.valueOf(playerWantedPoints*10)));
}
}
//处理逮捕人员
}else{//击杀 <SUF>
}
}
if(playerData.getW_Points()>0)Data.takePlayerLevel(player, playerData.getW_Points());
}
}
| 1 | 6 | 1 |
36934_2 | package icu.cattery.lixworth.blackbe;
import cn.nukkit.Player;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.event.EventHandler;
import cn.nukkit.event.Listener;
import cn.nukkit.event.player.PlayerJoinEvent;
import cn.nukkit.plugin.PluginBase;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* BlackBE Nukkit Plugin
*
* BlackBE云黑致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心
* https://minewiki.net/%E4%BA%91%E9%BB%91:BlackBE%E4%BA%91%E9%BB%91
*
* @author LixWorth <[email protected]>
* @website https://github.com/lixworth/BlackBE-NKPlugin
*/
public class BlackBE extends PluginBase implements Listener {
public static String api_version = "3.2[NE]";
public static String api_domain = "http://api.blackbe.work/openapi";
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
this.getLogger().info("BlackBE云黑插件加载完成,API版本" + api_version);
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent playerJoinEvent) {
Player player = playerJoinEvent.getPlayer();
this.getServer().getScheduler().scheduleAsyncTask(this,new QueryTask(this,player));
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("blackbe")) {
String message = "本服务器使用BlackBE云黑限制违禁玩家 API版本:" + api_version + "。 BlackBE云黑(https://blackbe.xyz)致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心。";
if (sender.isPlayer()) {
this.getServer().getPlayer(sender.getName()).sendMessage(message);
} else {
this.getLogger().info(message);
}
}
return true;
}
} | BlackBEDevelopment/BlackBE-NKPlugin | src/main/java/icu/cattery/lixworth/blackbe/BlackBE.java | 590 | //blackbe.xyz)致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心。"; | line_comment | zh-cn | package icu.cattery.lixworth.blackbe;
import cn.nukkit.Player;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.event.EventHandler;
import cn.nukkit.event.Listener;
import cn.nukkit.event.player.PlayerJoinEvent;
import cn.nukkit.plugin.PluginBase;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* BlackBE Nukkit Plugin
*
* BlackBE云黑致力于维护MCBE的服务器环境,用最简单粗暴的方式,让广大服主开服省心、放心
* https://minewiki.net/%E4%BA%91%E9%BB%91:BlackBE%E4%BA%91%E9%BB%91
*
* @author LixWorth <[email protected]>
* @website https://github.com/lixworth/BlackBE-NKPlugin
*/
public class BlackBE extends PluginBase implements Listener {
public static String api_version = "3.2[NE]";
public static String api_domain = "http://api.blackbe.work/openapi";
@Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
this.getLogger().info("BlackBE云黑插件加载完成,API版本" + api_version);
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent playerJoinEvent) {
Player player = playerJoinEvent.getPlayer();
this.getServer().getScheduler().scheduleAsyncTask(this,new QueryTask(this,player));
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("blackbe")) {
String message = "本服务器使用BlackBE云黑限制违禁玩家 API版本:" + api_version + "。 BlackBE云黑(https://bl <SUF>
if (sender.isPlayer()) {
this.getServer().getPlayer(sender.getName()).sendMessage(message);
} else {
this.getLogger().info(message);
}
}
return true;
}
} | 1 | 55 | 1 |
39454_4 | package com.peony.lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 显示锁和内置锁问题
* 显示锁:Lock接口的实现类,最常用的就是ReentrantLock,ReentrantReadWriteLock
* 内置锁:synchronized
*/
public class ShowLockAndInnerLockQuestion {
public static void main(String[] args) {
executeUseInnerLock();
System.out.println("======================");
executeUseShowLock();
}
/**
* 使用显示锁
* 公平/非公平
* 可重入
*/
public static void executeUseShowLock() {
// 非公平锁,也是默认的锁,性能更高
// 考虑为什么更高(省去了唤醒线程的时间)
Lock nonFairLock = new ReentrantLock(false);
nonFairLock.lock();
System.out.println("lock");
try {
action("使用显示锁实现线程安全");
} catch (Exception e) {
System.out.printf("遇到异常[%s]\n", e.getCause());
} finally {
// 显示锁的定时炸弹,如果不关闭锁,则这个锁将一直存在,如果一旦出现问题,这个炸弹爆炸,则很难发现发生
// 错误的地方,因为没有记录当时应当释放锁的位置
// 这也是ReentranLock不能完全替代synchronized的主要原因
System.out.println("unlock");
nonFairLock.unlock();
}
}
/**
* 使用内置锁
* 非公平锁
* 可重入
*/
public static void executeUseInnerLock() {
synchronized (ShowLockAndInnerLockQuestion.class) {
action("使用内置锁实现线程安全");
}
}
public static void action(String s) throws RuntimeException {
System.out.println(s);
}
}
| BlackHe/akoibj | src/main/java/com/peony/lock/ShowLockAndInnerLockQuestion.java | 457 | // 显示锁的定时炸弹,如果不关闭锁,则这个锁将一直存在,如果一旦出现问题,这个炸弹爆炸,则很难发现发生 | line_comment | zh-cn | package com.peony.lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 显示锁和内置锁问题
* 显示锁:Lock接口的实现类,最常用的就是ReentrantLock,ReentrantReadWriteLock
* 内置锁:synchronized
*/
public class ShowLockAndInnerLockQuestion {
public static void main(String[] args) {
executeUseInnerLock();
System.out.println("======================");
executeUseShowLock();
}
/**
* 使用显示锁
* 公平/非公平
* 可重入
*/
public static void executeUseShowLock() {
// 非公平锁,也是默认的锁,性能更高
// 考虑为什么更高(省去了唤醒线程的时间)
Lock nonFairLock = new ReentrantLock(false);
nonFairLock.lock();
System.out.println("lock");
try {
action("使用显示锁实现线程安全");
} catch (Exception e) {
System.out.printf("遇到异常[%s]\n", e.getCause());
} finally {
// 显示 <SUF>
// 错误的地方,因为没有记录当时应当释放锁的位置
// 这也是ReentranLock不能完全替代synchronized的主要原因
System.out.println("unlock");
nonFairLock.unlock();
}
}
/**
* 使用内置锁
* 非公平锁
* 可重入
*/
public static void executeUseInnerLock() {
synchronized (ShowLockAndInnerLockQuestion.class) {
action("使用内置锁实现线程安全");
}
}
public static void action(String s) throws RuntimeException {
System.out.println(s);
}
}
| 1 | 52 | 1 |
48855_4 | package com.service;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.dao.AssignDao;
import com.dao.AuthorDao;
import com.dao.MemberDao;
import com.dao.PaperDao;
import com.dao.PersonDao;
import com.dao.ReportDao;
import com.service.JspToHtml;
import com.vo.Author;
import com.vo.Paper;
import com.vo.Person;
import com.vo.Report;
public class ChairService {
static public void addMember(Person person,String pc_code)
{
MemberDao memberdao = new MemberDao();
memberdao.insertMember(person,pc_code);
}
static public void delMember(int person_id)
{
MemberDao memberdao = new MemberDao();
memberdao.deleteMember(person_id);
}
static public void addAssign(String pc_code,int paper_number)
{
AssignDao assigndao = new AssignDao ();
assigndao.assigPaper(pc_code, paper_number);
}
static public void delAssign(String pc_code,int paper_number)
{
AssignDao assigndao = new AssignDao ();
assigndao.deleteAssign(paper_number, pc_code);
}
static public boolean accept(String spn) throws IOException, FileNotFoundException
{
if(spn != null)
{
int paper_number = Integer.parseInt(spn);
PaperDao paperdao = new PaperDao();
PersonDao personDao = new PersonDao();
AuthorDao authordao = new AuthorDao();
Paper paper = paperdao.searchPaper(paper_number);
ReportDao reportdao = new ReportDao();
Person conAuthor = null;
ArrayList<Author> authorList = authordao.searchAuthor(paper_number);
ArrayList <Report> reportList = reportdao.searchReport(paper_number);
if(authorList != null)
{
Iterator <Author> it1 = authorList.iterator();
while(it1.hasNext()){
Author author = it1.next();
Person p = personDao.searchUser(author.getPerson_id());
if(author.getIs_contact().equals("Y"))
{
conAuthor = p;
}
}
}
// 收件人的电子邮件
String to = conAuthor.getEmail();
// 发件人的电子邮件
String from = "[email protected]";
// 假设你是从本地主机发送电子邮件
String host = "localhost";
// 获取系统属性对象
Properties properties = System.getProperties();
properties.setProperty("mail.user", "[email protected]");
properties.setProperty("mail.password", "xxxxx");
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
// 获取默认的Session对象。
Session mailSession = Session.getDefaultInstance(properties);
try{
// 创建一个默认的MimeMessage对象。
MimeMessage message = new MimeMessage(mailSession);
// 设置 From: 头部的header字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部的header字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 设置 Subject: header字段
message.setSubject("论文通知函");
// 现在设置的实际消息
String text = "尊敬的"+conAuthor.getName()+":\r\n" +
"\r\n" +
"IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很荣幸通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"已被本会议接收。 \r\n" +
"\r\n" +
"谨致问候 \r\n" +
"\r\n" +
"Fred Lochovsky \r\n" +
"程序委员会主席 ";
//message.setText(text);
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 填充消息
messageBodyPart.setText(text);
// 创建多媒体消息
Multipart multipart = new MimeMultipart();
// 设置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
if(reportList != null )
{
Iterator <Report> it1 = reportList.iterator();
int k=0;
while(it1.hasNext())
{
k++;
Report report = it1.next();
String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code());
File file = new File("D:/report"+k+".html");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write(html);
writer.flush();
writer.close();
BodyPart bp = new MimeBodyPart();
String filename = "report"+k+".html";
// 得到数据源
FileDataSource fds = new FileDataSource(file);
// 得到附件本身并至入BodyPart
bp.setDataHandler(new DataHandler(fds));
bp.setFileName(filename);
multipart.addBodyPart(bp);
}
}
message.setContent(multipart);
Transport transport = mailSession.getTransport("smtp");
transport.connect("smtp.com","[email protected]","xxxxx");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
paperdao.acceptPaper(paper_number);
return true;
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
return false;
}
static public boolean reject(String spn) throws IOException, FileNotFoundException
{
if(spn != null)
{
int paper_number = Integer.parseInt(spn);
PaperDao paperdao = new PaperDao();
PersonDao personDao = new PersonDao();
AuthorDao authordao = new AuthorDao();
Paper paper = paperdao.searchPaper(paper_number);
ReportDao reportdao = new ReportDao();
Person conAuthor = null;
ArrayList<Author> authorList = authordao.searchAuthor(paper_number);
ArrayList <Report> reportList = reportdao.searchReport(paper_number);
if(authorList != null)
{
Iterator <Author> it1 = authorList.iterator();
while(it1.hasNext()){
Author author = it1.next();
Person p = personDao.searchUser(author.getPerson_id());
if(author.getIs_contact().equals("Y"))
{
conAuthor = p;
}
}
}
// 收件人的电子邮件
String to = conAuthor.getEmail();
// 发件人的电子邮件
String from = "[email protected]";
// 假设你是从本地主机发送电子邮件
String host = "localhost";
// 获取系统属性对象
Properties properties = System.getProperties();
properties.setProperty("mail.user", "[email protected]");
properties.setProperty("mail.password", "xxxx");
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
// 获取默认的Session对象。
Session mailSession = Session.getDefaultInstance(properties);
try{
// 创建一个默认的MimeMessage对象。
MimeMessage message = new MimeMessage(mailSession);
// 设置 From: 头部的header字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部的header字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 设置 Subject: header字段
message.setSubject("论文通知函");
// 现在设置的实际消息
String text = "尊敬的"+conAuthor.getName()+":\r\n" +
"\r\n" +
"IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很遗憾地通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"未被本会议接收。 \r\n" +
"\r\n" +
"谨致问候 \r\n" +
"\r\n" +
"Fred Lochovsky \r\n" +
"程序委员会主席 ";
//message.setText(text);
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 填充消息
messageBodyPart.setText(text);
// 创建多媒体消息
Multipart multipart = new MimeMultipart();
// 设置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
if(reportList != null )
{
Iterator <Report> it1 = reportList.iterator();
int k=0;
while(it1.hasNext())
{
k++;
Report report = it1.next();
String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code());
File file = new File("D:/report"+k+".html");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write(html);
writer.flush();
writer.close();
BodyPart bp = new MimeBodyPart();
String filename = "report"+k+".html";
// 得到数据源
FileDataSource fds = new FileDataSource(file);
// 得到附件本身并至入BodyPart
bp.setDataHandler(new DataHandler(fds));
bp.setFileName(filename);
multipart.addBodyPart(bp);
}
}
message.setContent(multipart);
Transport transport = mailSession.getTransport("smtp");
transport.connect("smtp.com","[email protected]","xxxxxxxx");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
paperdao.rejectPaper(paper_number);
return true;
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
return false;
}
}
| Blacklth/CPRMS | src/com/service/ChairService.java | 2,857 | // 设置邮件服务器 | line_comment | zh-cn | package com.service;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.dao.AssignDao;
import com.dao.AuthorDao;
import com.dao.MemberDao;
import com.dao.PaperDao;
import com.dao.PersonDao;
import com.dao.ReportDao;
import com.service.JspToHtml;
import com.vo.Author;
import com.vo.Paper;
import com.vo.Person;
import com.vo.Report;
public class ChairService {
static public void addMember(Person person,String pc_code)
{
MemberDao memberdao = new MemberDao();
memberdao.insertMember(person,pc_code);
}
static public void delMember(int person_id)
{
MemberDao memberdao = new MemberDao();
memberdao.deleteMember(person_id);
}
static public void addAssign(String pc_code,int paper_number)
{
AssignDao assigndao = new AssignDao ();
assigndao.assigPaper(pc_code, paper_number);
}
static public void delAssign(String pc_code,int paper_number)
{
AssignDao assigndao = new AssignDao ();
assigndao.deleteAssign(paper_number, pc_code);
}
static public boolean accept(String spn) throws IOException, FileNotFoundException
{
if(spn != null)
{
int paper_number = Integer.parseInt(spn);
PaperDao paperdao = new PaperDao();
PersonDao personDao = new PersonDao();
AuthorDao authordao = new AuthorDao();
Paper paper = paperdao.searchPaper(paper_number);
ReportDao reportdao = new ReportDao();
Person conAuthor = null;
ArrayList<Author> authorList = authordao.searchAuthor(paper_number);
ArrayList <Report> reportList = reportdao.searchReport(paper_number);
if(authorList != null)
{
Iterator <Author> it1 = authorList.iterator();
while(it1.hasNext()){
Author author = it1.next();
Person p = personDao.searchUser(author.getPerson_id());
if(author.getIs_contact().equals("Y"))
{
conAuthor = p;
}
}
}
// 收件人的电子邮件
String to = conAuthor.getEmail();
// 发件人的电子邮件
String from = "[email protected]";
// 假设你是从本地主机发送电子邮件
String host = "localhost";
// 获取系统属性对象
Properties properties = System.getProperties();
properties.setProperty("mail.user", "[email protected]");
properties.setProperty("mail.password", "xxxxx");
// 设置 <SUF>
properties.setProperty("mail.smtp.host", host);
// 获取默认的Session对象。
Session mailSession = Session.getDefaultInstance(properties);
try{
// 创建一个默认的MimeMessage对象。
MimeMessage message = new MimeMessage(mailSession);
// 设置 From: 头部的header字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部的header字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 设置 Subject: header字段
message.setSubject("论文通知函");
// 现在设置的实际消息
String text = "尊敬的"+conAuthor.getName()+":\r\n" +
"\r\n" +
"IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很荣幸通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"已被本会议接收。 \r\n" +
"\r\n" +
"谨致问候 \r\n" +
"\r\n" +
"Fred Lochovsky \r\n" +
"程序委员会主席 ";
//message.setText(text);
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 填充消息
messageBodyPart.setText(text);
// 创建多媒体消息
Multipart multipart = new MimeMultipart();
// 设置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
if(reportList != null )
{
Iterator <Report> it1 = reportList.iterator();
int k=0;
while(it1.hasNext())
{
k++;
Report report = it1.next();
String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code());
File file = new File("D:/report"+k+".html");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write(html);
writer.flush();
writer.close();
BodyPart bp = new MimeBodyPart();
String filename = "report"+k+".html";
// 得到数据源
FileDataSource fds = new FileDataSource(file);
// 得到附件本身并至入BodyPart
bp.setDataHandler(new DataHandler(fds));
bp.setFileName(filename);
multipart.addBodyPart(bp);
}
}
message.setContent(multipart);
Transport transport = mailSession.getTransport("smtp");
transport.connect("smtp.com","[email protected]","xxxxx");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
paperdao.acceptPaper(paper_number);
return true;
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
return false;
}
static public boolean reject(String spn) throws IOException, FileNotFoundException
{
if(spn != null)
{
int paper_number = Integer.parseInt(spn);
PaperDao paperdao = new PaperDao();
PersonDao personDao = new PersonDao();
AuthorDao authordao = new AuthorDao();
Paper paper = paperdao.searchPaper(paper_number);
ReportDao reportdao = new ReportDao();
Person conAuthor = null;
ArrayList<Author> authorList = authordao.searchAuthor(paper_number);
ArrayList <Report> reportList = reportdao.searchReport(paper_number);
if(authorList != null)
{
Iterator <Author> it1 = authorList.iterator();
while(it1.hasNext()){
Author author = it1.next();
Person p = personDao.searchUser(author.getPerson_id());
if(author.getIs_contact().equals("Y"))
{
conAuthor = p;
}
}
}
// 收件人的电子邮件
String to = conAuthor.getEmail();
// 发件人的电子邮件
String from = "[email protected]";
// 假设你是从本地主机发送电子邮件
String host = "localhost";
// 获取系统属性对象
Properties properties = System.getProperties();
properties.setProperty("mail.user", "[email protected]");
properties.setProperty("mail.password", "xxxx");
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
// 获取默认的Session对象。
Session mailSession = Session.getDefaultInstance(properties);
try{
// 创建一个默认的MimeMessage对象。
MimeMessage message = new MimeMessage(mailSession);
// 设置 From: 头部的header字段
message.setFrom(new InternetAddress(from));
// 设置 To: 头部的header字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// 设置 Subject: header字段
message.setSubject("论文通知函");
// 现在设置的实际消息
String text = "尊敬的"+conAuthor.getName()+":\r\n" +
"\r\n" +
"IFIP 2.6的会议程序委员会收到了来自全世界的多篇论文提交。因此,我们必须在许多优秀的提交中做出决定。很遗憾地通知您,您的论文《"+paper.getTitle()+"》 编号"+paper.getPaper_number()+"未被本会议接收。 \r\n" +
"\r\n" +
"谨致问候 \r\n" +
"\r\n" +
"Fred Lochovsky \r\n" +
"程序委员会主席 ";
//message.setText(text);
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 填充消息
messageBodyPart.setText(text);
// 创建多媒体消息
Multipart multipart = new MimeMultipart();
// 设置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
if(reportList != null )
{
Iterator <Report> it1 = reportList.iterator();
int k=0;
while(it1.hasNext())
{
k++;
Report report = it1.next();
String html=JspToHtml.getCode("http://localhost:8080/CPRMS/report.jsp?paper_number="+report.getPaper_number()+"&pc_code="+report.getPc_code());
File file = new File("D:/report"+k+".html");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write(html);
writer.flush();
writer.close();
BodyPart bp = new MimeBodyPart();
String filename = "report"+k+".html";
// 得到数据源
FileDataSource fds = new FileDataSource(file);
// 得到附件本身并至入BodyPart
bp.setDataHandler(new DataHandler(fds));
bp.setFileName(filename);
multipart.addBodyPart(bp);
}
}
message.setContent(multipart);
Transport transport = mailSession.getTransport("smtp");
transport.connect("smtp.com","[email protected]","xxxxxxxx");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
paperdao.rejectPaper(paper_number);
return true;
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
return false;
}
}
| 1 | 10 | 1 |
1169_6 | package com.blankj.subutil.util;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.RomUtils;
import com.blankj.utilcode.util.Utils;
import java.util.List;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/05/20
* desc : utils about app store
* </pre>
*/
public final class AppStoreUtils {
private static final String TAG = "AppStoreUtils";
private static final String GOOGLE_PLAY_APP_STORE_PACKAGE_NAME = "com.android.vending";
/**
* 获取跳转到应用商店的 Intent
*
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent() {
return getAppStoreIntent(Utils.getApp().getPackageName(), false);
}
/**
* 获取跳转到应用商店的 Intent
*
* @param isIncludeGooglePlayStore 是否包括 Google Play 商店
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent(boolean isIncludeGooglePlayStore) {
return getAppStoreIntent(Utils.getApp().getPackageName(), isIncludeGooglePlayStore);
}
/**
* 获取跳转到应用商店的 Intent
*
* @param packageName 包名
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent(final String packageName) {
return getAppStoreIntent(packageName, false);
}
/**
* 获取跳转到应用商店的 Intent
* <p>优先跳转到手机自带的应用市场</p>
*
* @param packageName 包名
* @param isIncludeGooglePlayStore 是否包括 Google Play 商店
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent(final String packageName, boolean isIncludeGooglePlayStore) {
if (RomUtils.isSamsung()) {// 三星单独处理跳转三星市场
Intent samsungAppStoreIntent = getSamsungAppStoreIntent(packageName);
if (samsungAppStoreIntent != null) return samsungAppStoreIntent;
}
if (RomUtils.isLeeco()) {// 乐视单独处理跳转乐视市场
Intent leecoAppStoreIntent = getLeecoAppStoreIntent(packageName);
if (leecoAppStoreIntent != null) return leecoAppStoreIntent;
}
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent intent = new Intent();
intent.setData(uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
List<ResolveInfo> resolveInfos = Utils.getApp().getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfos == null || resolveInfos.size() == 0) {
Log.e(TAG, "No app store!");
return null;
}
Intent googleIntent = null;
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.packageName;
if (!GOOGLE_PLAY_APP_STORE_PACKAGE_NAME.equals(pkgName)) {
if (AppUtils.isAppSystem(pkgName)) {
intent.setPackage(pkgName);
return intent;
}
} else {
intent.setPackage(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME);
googleIntent = intent;
}
}
if (isIncludeGooglePlayStore && googleIntent != null) {
return googleIntent;
}
intent.setPackage(resolveInfos.get(0).activityInfo.packageName);
return intent;
}
private static Intent getSamsungAppStoreIntent(final String packageName) {
Intent intent = new Intent();
intent.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main");
intent.setData(Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getAvailableIntentSize(intent) > 0) {
return intent;
}
return null;
}
private static Intent getLeecoAppStoreIntent(final String packageName) {
Intent intent = new Intent();
intent.setClassName("com.letv.app.appstore", "com.letv.app.appstore.appmodule.details.DetailsActivity");
intent.setAction("com.letv.app.appstore.appdetailactivity");
intent.putExtra("packageName", packageName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getAvailableIntentSize(intent) > 0) {
return intent;
}
return null;
}
private static int getAvailableIntentSize(final Intent intent) {
return Utils.getApp().getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
.size();
}
}
| Blankj/AndroidUtilCode | lib/subutil/src/main/java/com/blankj/subutil/util/AppStoreUtils.java | 1,216 | // 乐视单独处理跳转乐视市场 | line_comment | zh-cn | package com.blankj.subutil.util;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.RomUtils;
import com.blankj.utilcode.util.Utils;
import java.util.List;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/05/20
* desc : utils about app store
* </pre>
*/
public final class AppStoreUtils {
private static final String TAG = "AppStoreUtils";
private static final String GOOGLE_PLAY_APP_STORE_PACKAGE_NAME = "com.android.vending";
/**
* 获取跳转到应用商店的 Intent
*
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent() {
return getAppStoreIntent(Utils.getApp().getPackageName(), false);
}
/**
* 获取跳转到应用商店的 Intent
*
* @param isIncludeGooglePlayStore 是否包括 Google Play 商店
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent(boolean isIncludeGooglePlayStore) {
return getAppStoreIntent(Utils.getApp().getPackageName(), isIncludeGooglePlayStore);
}
/**
* 获取跳转到应用商店的 Intent
*
* @param packageName 包名
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent(final String packageName) {
return getAppStoreIntent(packageName, false);
}
/**
* 获取跳转到应用商店的 Intent
* <p>优先跳转到手机自带的应用市场</p>
*
* @param packageName 包名
* @param isIncludeGooglePlayStore 是否包括 Google Play 商店
* @return 跳转到应用商店的 Intent
*/
public static Intent getAppStoreIntent(final String packageName, boolean isIncludeGooglePlayStore) {
if (RomUtils.isSamsung()) {// 三星单独处理跳转三星市场
Intent samsungAppStoreIntent = getSamsungAppStoreIntent(packageName);
if (samsungAppStoreIntent != null) return samsungAppStoreIntent;
}
if (RomUtils.isLeeco()) {// 乐视 <SUF>
Intent leecoAppStoreIntent = getLeecoAppStoreIntent(packageName);
if (leecoAppStoreIntent != null) return leecoAppStoreIntent;
}
Uri uri = Uri.parse("market://details?id=" + packageName);
Intent intent = new Intent();
intent.setData(uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
List<ResolveInfo> resolveInfos = Utils.getApp().getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfos == null || resolveInfos.size() == 0) {
Log.e(TAG, "No app store!");
return null;
}
Intent googleIntent = null;
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.packageName;
if (!GOOGLE_PLAY_APP_STORE_PACKAGE_NAME.equals(pkgName)) {
if (AppUtils.isAppSystem(pkgName)) {
intent.setPackage(pkgName);
return intent;
}
} else {
intent.setPackage(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME);
googleIntent = intent;
}
}
if (isIncludeGooglePlayStore && googleIntent != null) {
return googleIntent;
}
intent.setPackage(resolveInfos.get(0).activityInfo.packageName);
return intent;
}
private static Intent getSamsungAppStoreIntent(final String packageName) {
Intent intent = new Intent();
intent.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main");
intent.setData(Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + packageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getAvailableIntentSize(intent) > 0) {
return intent;
}
return null;
}
private static Intent getLeecoAppStoreIntent(final String packageName) {
Intent intent = new Intent();
intent.setClassName("com.letv.app.appstore", "com.letv.app.appstore.appmodule.details.DetailsActivity");
intent.setAction("com.letv.app.appstore.appdetailactivity");
intent.putExtra("packageName", packageName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getAvailableIntentSize(intent) > 0) {
return intent;
}
return null;
}
private static int getAvailableIntentSize(final Intent intent) {
return Utils.getApp().getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
.size();
}
}
| 1 | 15 | 1 |
691_1 | package com.blankj.medium._0067;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2020/07/07
* desc :
* </pre>
*/
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
// 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法,
// 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0;
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {
dp[i][0] = 1;
}
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
dp[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 0) {
// 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}};
System.out.println(solution.uniquePathsWithObstacles(obstacleGrid));
}
}
| Blankj/awesome-java-leetcode | src/com/blankj/medium/_0067/Solution.java | 489 | // 其初始态第 1 列(行)的格子只有从其上(左)边格子走过去这一种走法, | line_comment | zh-cn | package com.blankj.medium._0067;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2020/07/07
* desc :
* </pre>
*/
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
// 其初 <SUF>
// 因此初始化 dp[i][0](dp[0][j])值为 1,且遇到障碍物时后面值都为 0;
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {
dp[i][0] = 1;
}
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {
dp[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 0) {
// 当 (i, j) 有障碍物时,dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}};
System.out.println(solution.uniquePathsWithObstacles(obstacleGrid));
}
}
| 1 | 38 | 1 |
45488_0 | package com.blend.algorithm.thread;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
/**
* 多核心:也指单芯片多处理器,将大规模并行处理器集成到同一芯片内。
* 核心数、线程数:目前主流CPU有双核、三核和四核,六核也在2010年发布。增加核心数目就是为了增加线程数,因为操作系统是通过
* 线程来执行任务的,一般情况下它们是1:1对应关系,也就是说四核CPU一般拥有四个线程。但 Intel引入超线程技术后,使核心数与
* 线程数形成1:2的关系。
* <p>
* CPU时间片轮转机制:RR调度。每个进程被分配一个时间段,称作它的时间片,即该进程允许运行的时间。
* 线程切换:有时也称作上下文切换。
* 时间片轮转调度中唯一有趣的一点是时间片的长度。时间片设得太短会导致过多的进程切换,降低了CPU效率:而设得太长又可能引起
* 对短的交互请求的响应变差。将时间片设为100ms通常是一个比较合理的折衷。
* <p>
* 进程是程序运行资源分配的最小单位,其中资源包括:CPU、内存空间、磁盘10等。
* 线程是CPU调度的最小单位,必须依赖于进程而存在,线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计
* 数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的全部资源。
* <p>
* 并行和并发:
* 当谈论并发的时候一定要加个单位时间,也就是说单位时间内并发量是多少?离开了单位时间其实是没有意义的。
* 一个是交替执行,一个是同时执行。
* <p>
* 高并发编程的意义:
* 1.充分利用CPU的资源。
* 2.加快用户响应时间。
* 注意事项:
* 1.线程之间的安全性。多线程对同一个变量的读写。
* 2.线程之间的死锁。
* 3.线程数目过多将服务器资源耗尽形成死机和宕机。某些系统资源是有限的,如文件描述符。多线程程序可能耗尽资源,因为每个线程都
* 可能希望有一个这样的资源。如果线程数相当大,或者某个资源的侯选线程数远远超过了可用的资源数则最好使用资源池。
* <p>
* java程序天生就是多线程:
* [5] Attach Listener。内存dump,线程dump,类信息统计,获取系统属性等
* [4] Signal Dispatcher。分发处理发送给JVM信号的线程
* [3] Finalizer。调用对象finalize方法的线程
* [2] Reference Handler。清除Reference的线程
* [1] main。用户程序入口
* <p>
* 注意点:
* 1.进程和CPU是没有关系的。
* 2.一次线程的上下文切换,需要耗费20000个CPU时间周期。
* 3.一个线程可以有多个Runnable,但是只有Thread是操作系统对线程的抽象。
* 4.sleep()可以中止,调用interrupt()中止。
* 5.sleep和wait的区别。wait就是等到资源满足调用notify/notifyAll来唤醒;sleep则等待时间结束。
* 6.线程的优先级和操作系统的优先级对不上号,不要指望使用线程的优先级来保证线程的执行顺序。
* 7.保证线程的执行顺序应该使用:join或者CountDownLatch。
* 8.yield和sleep不会释放锁,wait会释放锁。
* <p>
* 额外:
* 4.线程的所有方法有哪些?
* join():把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。
* yield():使当前线程让出CPU占有权,但让出的时间是不可设定的。也不会释放锁资源,所有执行yield()的线程有可能在进入到可执行状态后马上又被执行。
* sleep()
* interrupt()
* start()
* 而wait()/notify()是Object的方法。
* <p>
*/
class ThreadMain {
public static void main(String[] args) {
//天生多线程
more();
}
private static void more() {
/*虚拟机线程管理接口*/
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
/*取得线程信息*/
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
for (ThreadInfo threadInfo : threadInfos) {
System.out.println("[" + threadInfo.getThreadId() + "]" + " "
+ threadInfo.getThreadName());
}
}
}
| BlendGitAndroid/AndroidAdvanced | algorithm/src/main/java/com/blend/algorithm/thread/ThreadMain.java | 1,227 | /**
* 多核心:也指单芯片多处理器,将大规模并行处理器集成到同一芯片内。
* 核心数、线程数:目前主流CPU有双核、三核和四核,六核也在2010年发布。增加核心数目就是为了增加线程数,因为操作系统是通过
* 线程来执行任务的,一般情况下它们是1:1对应关系,也就是说四核CPU一般拥有四个线程。但 Intel引入超线程技术后,使核心数与
* 线程数形成1:2的关系。
* <p>
* CPU时间片轮转机制:RR调度。每个进程被分配一个时间段,称作它的时间片,即该进程允许运行的时间。
* 线程切换:有时也称作上下文切换。
* 时间片轮转调度中唯一有趣的一点是时间片的长度。时间片设得太短会导致过多的进程切换,降低了CPU效率:而设得太长又可能引起
* 对短的交互请求的响应变差。将时间片设为100ms通常是一个比较合理的折衷。
* <p>
* 进程是程序运行资源分配的最小单位,其中资源包括:CPU、内存空间、磁盘10等。
* 线程是CPU调度的最小单位,必须依赖于进程而存在,线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计
* 数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的全部资源。
* <p>
* 并行和并发:
* 当谈论并发的时候一定要加个单位时间,也就是说单位时间内并发量是多少?离开了单位时间其实是没有意义的。
* 一个是交替执行,一个是同时执行。
* <p>
* 高并发编程的意义:
* 1.充分利用CPU的资源。
* 2.加快用户响应时间。
* 注意事项:
* 1.线程之间的安全性。多线程对同一个变量的读写。
* 2.线程之间的死锁。
* 3.线程数目过多将服务器资源耗尽形成死机和宕机。某些系统资源是有限的,如文件描述符。多线程程序可能耗尽资源,因为每个线程都
* 可能希望有一个这样的资源。如果线程数相当大,或者某个资源的侯选线程数远远超过了可用的资源数则最好使用资源池。
* <p>
* java程序天生就是多线程:
* [5] Attach Listener。内存dump,线程dump,类信息统计,获取系统属性等
* [4] Signal Dispatcher。分发处理发送给JVM信号的线程
* [3] Finalizer。调用对象finalize方法的线程
* [2] Reference Handler。清除Reference的线程
* [1] main。用户程序入口
* <p>
* 注意点:
* 1.进程和CPU是没有关系的。
* 2.一次线程的上下文切换,需要耗费20000个CPU时间周期。
* 3.一个线程可以有多个Runnable,但是只有Thread是操作系统对线程的抽象。
* 4.sleep()可以中止,调用interrupt()中止。
* 5.sleep和wait的区别。wait就是等到资源满足调用notify/notifyAll来唤醒;sleep则等待时间结束。
* 6.线程的优先级和操作系统的优先级对不上号,不要指望使用线程的优先级来保证线程的执行顺序。
* 7.保证线程的执行顺序应该使用:join或者CountDownLatch。
* 8.yield和sleep不会释放锁,wait会释放锁。
* <p>
* 额外:
* 4.线程的所有方法有哪些?
* join():把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。
* yield():使当前线程让出CPU占有权,但让出的时间是不可设定的。也不会释放锁资源,所有执行yield()的线程有可能在进入到可执行状态后马上又被执行。
* sleep()
* interrupt()
* start()
* 而wait()/notify()是Object的方法。
* <p>
*/ | block_comment | zh-cn | package com.blend.algorithm.thread;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
/**
* 多核心 <SUF>*/
class ThreadMain {
public static void main(String[] args) {
//天生多线程
more();
}
private static void more() {
/*虚拟机线程管理接口*/
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
/*取得线程信息*/
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
for (ThreadInfo threadInfo : threadInfos) {
System.out.println("[" + threadInfo.getThreadId() + "]" + " "
+ threadInfo.getThreadName());
}
}
}
| 0 | 1,641 | 0 |
47931_2 | package tools;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import core.Music;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
/**
* @author BlindingDark 调用音乐播放器。 默认是 windows media player 。
* 确保 C:/Program Files (x86)/Windows Media Player/wmplayer.exe 存在
*
* 如果不想使用WMP,请修改 String musicPlayer = "javaPlayer";
*/
public class Mp3Player {
Music music;
BufferedInputStream buffer;
Player player;
boolean stop = false;
String musicPlayer = "WMPplayer";
//String musicPlayer = "javaPlayer";
/**
* 切歌
*/
public void cut() {
this.stop = true;
switch (musicPlayer) {
case "WMPplayer":
String command = "taskkill /F /IM wmplayer.exe";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e1) {
}
break;
case "javaPlayer":
player.close();
break;
default:
break;
}
}
/**
* 播放
* @param _music
*/
public void play(Music _music) {
switch (musicPlayer) {
case "WMPplayer":
this.WMPplay(_music);
break;
case "javaPlayer":
this.javaPlay(_music);
break;
default:
break;
}
}
public void WMPplay(Music _music) {
this.music = _music;
String musicURL = music.getMusicURL();
String command = "C:/Program Files (x86)/Windows Media Player/wmplayer.exe \"" + musicURL + "\"";
try {
Runtime.getRuntime().exec(command);
} catch (IOException e1) {
}
stop = false;
try {
int timer = music.getDuration() / 1000 + 2;
while ((!stop) && (timer > 0)) {
Thread.sleep(1000);
timer--;
}
} catch (InterruptedException e) {
// e.printStackTrace();
}
}
/**
* 不稳定的纯 java mp3 播放器
*
* @param _music
*/
public void javaPlay(Music _music) {
try {
this.music = _music;
try {
player = new Player(new URL(music.getMusicURL()).openStream());
} catch (MalformedURLException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
} catch (IOException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
} catch (JavaLayerException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
}
stop = false;
player.play();
} catch (JavaLayerException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
} finally {
}
}
/**
* 测试
*
* @param args
*/
public static void main(String args[]) {
String command = "C:/Program Files (x86)/Windows Media Player/wmplayer.exe \"http://p1.music.126.net/qHexK855tbfvuYPumSBgAQ==/7997847580846443.mp3\"";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
| BlindingDark/bilibiliDM | src/tools/Mp3Player.java | 1,025 | /**
* 切歌
*/ | block_comment | zh-cn | package tools;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import core.Music;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
/**
* @author BlindingDark 调用音乐播放器。 默认是 windows media player 。
* 确保 C:/Program Files (x86)/Windows Media Player/wmplayer.exe 存在
*
* 如果不想使用WMP,请修改 String musicPlayer = "javaPlayer";
*/
public class Mp3Player {
Music music;
BufferedInputStream buffer;
Player player;
boolean stop = false;
String musicPlayer = "WMPplayer";
//String musicPlayer = "javaPlayer";
/**
* 切歌
<SUF>*/
public void cut() {
this.stop = true;
switch (musicPlayer) {
case "WMPplayer":
String command = "taskkill /F /IM wmplayer.exe";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e1) {
}
break;
case "javaPlayer":
player.close();
break;
default:
break;
}
}
/**
* 播放
* @param _music
*/
public void play(Music _music) {
switch (musicPlayer) {
case "WMPplayer":
this.WMPplay(_music);
break;
case "javaPlayer":
this.javaPlay(_music);
break;
default:
break;
}
}
public void WMPplay(Music _music) {
this.music = _music;
String musicURL = music.getMusicURL();
String command = "C:/Program Files (x86)/Windows Media Player/wmplayer.exe \"" + musicURL + "\"";
try {
Runtime.getRuntime().exec(command);
} catch (IOException e1) {
}
stop = false;
try {
int timer = music.getDuration() / 1000 + 2;
while ((!stop) && (timer > 0)) {
Thread.sleep(1000);
timer--;
}
} catch (InterruptedException e) {
// e.printStackTrace();
}
}
/**
* 不稳定的纯 java mp3 播放器
*
* @param _music
*/
public void javaPlay(Music _music) {
try {
this.music = _music;
try {
player = new Player(new URL(music.getMusicURL()).openStream());
} catch (MalformedURLException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
} catch (IOException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
} catch (JavaLayerException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
}
stop = false;
player.play();
} catch (JavaLayerException e) {
System.out.println("由于版权问题或网络问题," + _music.getMusicName() + " 播放失败");
} finally {
}
}
/**
* 测试
*
* @param args
*/
public static void main(String args[]) {
String command = "C:/Program Files (x86)/Windows Media Player/wmplayer.exe \"http://p1.music.126.net/qHexK855tbfvuYPumSBgAQ==/7997847580846443.mp3\"";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
| 0 | 15 | 0 |
19798_6 |
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static String getMD5(String str) throws NoSuchAlgorithmException {
try {
// 创建加密对象
MessageDigest digest = MessageDigest.getInstance("md5");
// 调用加密对象的方法,加密的动作已经完成
byte[] bs = digest.digest(str.getBytes());
// 接下来,我们要对加密后的结果,进行优化,按照mysql的优化思路走
// mysql的优化思路:
// 第一步,将数据全部转换成正数:
String hexString = "";
for (byte b : bs) {
// 第一步,将数据全部转换成正数:
// 解释:为什么采用b&255
/*
* b:它本来是一个byte类型的数据(1个字节) 255:是一个int类型的数据(4个字节)
* byte类型的数据与int类型的数据进行运算,会自动类型提升为int类型 eg: b: 1001 1100(原始数据) 运算时: b: 0000 0000
* 0000 0000 0000 0000 1001 1100 255: 0000 0000 0000 0000 0000 0000 1111 1111
* 结果:0000 0000 0000 0000 0000 0000 1001 1100 此时的temp是一个int类型的整数
*/
int temp = b & 255;
// 第二步,将所有的数据转换成16进制的形式
// 注意:转换的时候注意if正数>=0&&<16,那么如果使用Integer.toHexString(),可能会造成缺少位数
// 因此,需要对temp进行判断
if (temp < 16 && temp >= 0) {
// 手动补上一个“0”
hexString = hexString + "0" + Integer.toHexString(temp);
} else {
hexString = hexString + Integer.toHexString(temp);
}
}
return hexString;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
}
| BlissYang91/note | utils/MD5.java | 573 | // 解释:为什么采用b&255 | line_comment | zh-cn |
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static String getMD5(String str) throws NoSuchAlgorithmException {
try {
// 创建加密对象
MessageDigest digest = MessageDigest.getInstance("md5");
// 调用加密对象的方法,加密的动作已经完成
byte[] bs = digest.digest(str.getBytes());
// 接下来,我们要对加密后的结果,进行优化,按照mysql的优化思路走
// mysql的优化思路:
// 第一步,将数据全部转换成正数:
String hexString = "";
for (byte b : bs) {
// 第一步,将数据全部转换成正数:
// 解释 <SUF>
/*
* b:它本来是一个byte类型的数据(1个字节) 255:是一个int类型的数据(4个字节)
* byte类型的数据与int类型的数据进行运算,会自动类型提升为int类型 eg: b: 1001 1100(原始数据) 运算时: b: 0000 0000
* 0000 0000 0000 0000 1001 1100 255: 0000 0000 0000 0000 0000 0000 1111 1111
* 结果:0000 0000 0000 0000 0000 0000 1001 1100 此时的temp是一个int类型的整数
*/
int temp = b & 255;
// 第二步,将所有的数据转换成16进制的形式
// 注意:转换的时候注意if正数>=0&&<16,那么如果使用Integer.toHexString(),可能会造成缺少位数
// 因此,需要对temp进行判断
if (temp < 16 && temp >= 0) {
// 手动补上一个“0”
hexString = hexString + "0" + Integer.toHexString(temp);
} else {
hexString = hexString + Integer.toHexString(temp);
}
}
return hexString;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
}
| 1 | 16 | 1 |
58365_12 | package leetcode.editor.cn;
//一场比赛中共有 n 支队伍,按从 0 到 n - 1 编号。
//
// 给你一个下标从 0 开始、大小为 n * n 的二维布尔矩阵 grid 。对于满足 0 <= i, j <= n - 1 且 i != j 的所有 i,
//j :如果 grid[i][j] == 1,那么 i 队比 j 队 强 ;否则,j 队比 i 队 强 。
//
// 在这场比赛中,如果不存在某支强于 a 队的队伍,则认为 a 队将会是 冠军 。
//
// 返回这场比赛中将会成为冠军的队伍。
//
//
//
// 示例 1:
//
//
//输入:grid = [[0,1],[0,0]]
//输出:0
//解释:比赛中有两支队伍。
//grid[0][1] == 1 表示 0 队比 1 队强。所以 0 队是冠军。
//
//
// 示例 2:
//
//
//输入:grid = [[0,0,1],[1,0,1],[0,0,0]]
//输出:1
//解释:比赛中有三支队伍。
//grid[1][0] == 1 表示 1 队比 0 队强。
//grid[1][2] == 1 表示 1 队比 2 队强。
//所以 1 队是冠军。
//
//
//
//
// 提示:
//
//
// n == grid.length
// n == grid[i].length
// 2 <= n <= 100
// grid[i][j] 的值为 0 或 1
//
// 对于所有 i, grid[i][i] 等于 0.
// 对于满足 i != j 的所有 i, j ,grid[i][j] != grid[j][i] 均成立
// 生成的输入满足:如果 a 队比 b 队强,b 队比 c 队强,那么 a 队比 c 队强
//
//
// 👍 8 👎 0
/**
* 找到冠军 I
*
* @author IronSid
* @version 1.0
* @since 2024-04-12 01:26:29
*/
public class FindChampionISolution {
static
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findChampion(int[][] grid) {
int n = grid.length;
for (int i = 0; i < n; i++) {
int cnt = 0;
// 统计比它弱的队的数量
for (int j = 0; j < n; j++) {
cnt += grid[i][j];
}
if (cnt == n - 1) return i;
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| BloodSid/LeetCode_Sid | leetcodeEditor/src/main/java/leetcode/editor/cn/FindChampionISolution.java | 774 | //输出:1 | line_comment | zh-cn | package leetcode.editor.cn;
//一场比赛中共有 n 支队伍,按从 0 到 n - 1 编号。
//
// 给你一个下标从 0 开始、大小为 n * n 的二维布尔矩阵 grid 。对于满足 0 <= i, j <= n - 1 且 i != j 的所有 i,
//j :如果 grid[i][j] == 1,那么 i 队比 j 队 强 ;否则,j 队比 i 队 强 。
//
// 在这场比赛中,如果不存在某支强于 a 队的队伍,则认为 a 队将会是 冠军 。
//
// 返回这场比赛中将会成为冠军的队伍。
//
//
//
// 示例 1:
//
//
//输入:grid = [[0,1],[0,0]]
//输出:0
//解释:比赛中有两支队伍。
//grid[0][1] == 1 表示 0 队比 1 队强。所以 0 队是冠军。
//
//
// 示例 2:
//
//
//输入:grid = [[0,0,1],[1,0,1],[0,0,0]]
//输出 <SUF>
//解释:比赛中有三支队伍。
//grid[1][0] == 1 表示 1 队比 0 队强。
//grid[1][2] == 1 表示 1 队比 2 队强。
//所以 1 队是冠军。
//
//
//
//
// 提示:
//
//
// n == grid.length
// n == grid[i].length
// 2 <= n <= 100
// grid[i][j] 的值为 0 或 1
//
// 对于所有 i, grid[i][i] 等于 0.
// 对于满足 i != j 的所有 i, j ,grid[i][j] != grid[j][i] 均成立
// 生成的输入满足:如果 a 队比 b 队强,b 队比 c 队强,那么 a 队比 c 队强
//
//
// 👍 8 👎 0
/**
* 找到冠军 I
*
* @author IronSid
* @version 1.0
* @since 2024-04-12 01:26:29
*/
public class FindChampionISolution {
static
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findChampion(int[][] grid) {
int n = grid.length;
for (int i = 0; i < n; i++) {
int cnt = 0;
// 统计比它弱的队的数量
for (int j = 0; j < n; j++) {
cnt += grid[i][j];
}
if (cnt == n - 1) return i;
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| 1 | 6 | 1 |
46575_25 | package Model;
import View.ChooseLevel;
/**
* Created by Blossoming on 2016/12/6.
*/
public class Computer {
private int test=0;
private int scores;
private Coord coord=new Coord();
private int everyPlayerPointScore[][]=new int[19][19];
private int everyComputerPointScore[][]=new int[19][19];
/**
* 计算下棋位置
* @param role 角色 chess[][]棋盘
*/
public Coord computePos(int role,int chess[][],int level)
{
int x, y, posX, posY;
//初级
if(level== ChooseLevel.PRIMARY_LEVEL) {
while (true) {
posX = (int) (Math.random() * 10 + Math.random() * 9);
posY = (int) (Math.random() * 10 + Math.random() * 9);
if (chess[posX][posY] == Chess.NO_CHESS) {
coord.setX(posX);
coord.setY(posY);
return coord;
}
}
}
//中级
else if(level==ChooseLevel.MEDIUM_LEVEL)
{
countMaxLines_primary(chess, Chess.WHITE);
return coord;
}
else if(level==ChooseLevel.SENIOR_LEVEL)
{
countMaxLines_medium(chess,Chess.WHITE);
return coord;
}
return coord;
}
/**********************下面是中级人机*************************************/
/**
* 找出分数最大的坐标
* @param chess 棋盘数组
* @param role 白棋还是黑棋
*/
public void countMaxLines_medium(int chess[][],int role)
{
Coord playerCoord=new Coord();
Coord computerCoord=new Coord();
int x,y;
for(x=0;x<19;x++)
{
for(y=0;y<19;y++)
{
if(chess[x][y]==Chess.NO_CHESS) {
countEveryPos_medium(x, y, chess, role);
everyPlayerPointScore[x][y] = scores;
countEveryPos_medium(x, y, chess, Chess.BLACK);
everyComputerPointScore[x][y] = scores;
}
else
{
everyPlayerPointScore[x][y]=0;
everyComputerPointScore[x][y]=0;
}
}
}
if(findBestPos_medium(everyPlayerPointScore, playerCoord)>=findBestPos(everyComputerPointScore,computerCoord))
{
coord=playerCoord;
}
else
{
coord=computerCoord;
}
}
/**
* 找到最大分数点的坐标
* @param a 数组 存储每个点的分数
* @param c 保存最大分数点的坐标
* @return
*/
public int findBestPos_medium(int a[][],Coord c)
{
int i,j,max=0;
for(i=0;i<19;i++)
{
for(j=0;j<19;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
c.setX(i);
c.setY(j);
}
}
}
return max;
}
/**
* 估分函数
* @param count 每一个方向上的相同颜色的总个数
* @param i 不同颜色的个数
*/
public void mark_medium(int count,int i,int countTwo,int role)
{
if(count==1)
{
scores=scores+10;
}
//活二
else if(count==2&&i==0&&role==Chess.WHITE&&countTwo<=1)
{
scores=scores+200;
//System.out.println("白子活二"+scores);
}
else if(count==2&&i==0&&role==Chess.BLACK&&countTwo<=1)
{
scores=scores+400;
// System.out.println("黑子活二"+scores);
}
//冲二
else if(count==2&&i==1)
{
scores=scores+50;
// System.out.println("冲二"+scores);
}
//双活二
else if(count==2&&i==0&&countTwo>1)
{
scores=scores+84000;
System.out.println("双活二"+scores);
}
//活三(黑子和白子同时活三的时候选择黑子成)
else if(count==3&&i==0&&role==Chess.WHITE)
{
scores=scores+85000;
//System.out.println("白子活三"+scores);
}
else if(count==3&&i==0&&role==Chess.BLACK)
{
scores=scores+86000;
//System.out.println("黑子活三"+scores);
}
//冲三
else if(count==3&&i==1&&role==Chess.WHITE)
{
scores=scores+300;
System.out.println("白子冲三"+scores);
}
else if(count==3&&i==1&&role==Chess.BLACK)
{
scores=scores+1000;
System.out.println("黑子冲三"+scores);
}
//白子活四
else if(count==4&&i==0&&role==Chess.WHITE)
{
scores=scores+90000;
//System.out.println("活四"+scores);
}
//黑子活四
else if(count==4&&i==0&&role==Chess.BLACK)
{
scores=scores+91000;
}
//冲四
else if(count==4&&i==1)
{
scores=scores+87000;
//System.out.println("冲四"+scores);
}
else if(count==5)
{
scores=scores+100000;
}
}
public void basicScore(int x,int y)
{
if(x==0||y==0)
{
scores=scores+3;
}
else
{
scores=scores+5;
}
}
/**
* 计算每个坐标的分数
* @param x
* @param y
* @param chess
* @param role
*/
public void countEveryPos_medium(int x,int y,int chess[][],int role)
{
scores=0;
basicScore(x,y);
//countTwo代表有一个坐标向八个方向数 两个连一起的个数
int matchRole,startX=x,startY=y,
count=0,up=0,down=0,left=0,right=0,
leftUp=0,leftDown=0,rightUp=0,rightDown=0,countTwo=0;
if(role==Chess.BLACK)
{
matchRole=Chess.WHITE;
}
else
{
matchRole=Chess.BLACK;
}
//竖直方向上判断输赢
while (true)
{
//向上判断
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||y<0){
up++;
break;
}
else
{
break;
}
}
y = startY;
while (true) {
//向下判断
y = y + 1;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||y>19){
down++;
break;
}
else
{
break;
}
}
//此处代表在上下方向有二连 或者 夹了一个空子两边各有一个棋子 并且两端没有其他子挡住
if(count==2&&(up+down==0))
{
countTwo++;
//System.out.println("出现二连"+countTwo);
}
mark_medium(count, up + down, countTwo,role);
//水平方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左判断
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x==0){
left++;
break;
}
else
{
break;
}
}
x = startX;
while (true) {
//向右判断
x++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x>19){
right++;
break;
}
else
{
break;
}
}
if(count==2&&(left+right==0))
{
countTwo++;
//System.out.println("出现二连"+countTwo);
}
mark_medium(count, left + right, countTwo,role);
//右倾斜方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左上判断
y--;
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x<0||y<0){
leftUp++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右下判断
x++;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x>19||y>19){
rightDown++;
break;
}
else
{
break;
}
}
if(count==2&&(leftUp+rightDown==0))
{
countTwo++;
// System.out.println("出现二连"+countTwo);
}
mark_medium(count, leftUp + rightDown, countTwo,role);
//左倾斜方向判断
x = startX;
y = startY;
count = 0;
while (true) {
//向左下判断
x--;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x<0||y>19){
leftDown++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右上判断
x++;
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x>19||y<0){
rightUp++;
break;
}
else
{
break;
}
}
if(count==2&&(leftDown+rightUp==0))
{
countTwo++;
// System.out.println("出现二连"+countTwo);
}
mark_medium(count, leftDown + rightUp, countTwo,role);
}
/*********************下面是初级人机*************************************/
/**
* 找出分数最大的坐标
* @param chess 棋盘数组
* @param role 白棋还是黑棋
*/
public void countMaxLines_primary(int chess[][],int role)
{
Coord playerCoord=new Coord();
Coord computerCoord=new Coord();
int x,y;
for(x=0;x<19;x++)
{
for(y=0;y<19;y++)
{
if(chess[x][y]==Chess.NO_CHESS) {
countEveryPos_primary(x, y, chess, role);
everyPlayerPointScore[x][y] = scores;
countEveryPos_primary(x, y, chess, Chess.BLACK);
everyComputerPointScore[x][y] = scores;
}
else
{
everyPlayerPointScore[x][y]=0;
everyComputerPointScore[x][y]=0;
}
}
}
if(findBestPos(everyPlayerPointScore,playerCoord)>=findBestPos(everyComputerPointScore,computerCoord))
{
coord=playerCoord;
}
else
{
coord=computerCoord;
}
}
/**
* 找到最大分数点的坐标
* @param a 数组 存储每个点的分数
* @param c 保存最大分数点的坐标
* @return
*/
public int findBestPos(int a[][],Coord c)
{
int i,j,max=0;
for(i=0;i<19;i++)
{
for(j=0;j<19;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
c.setX(i);
c.setY(j);
}
}
}
return max;
}
/**
* 估分函数
* @param count 每一个方向上的相同颜色的总个数
* @param i 不同颜色的个数
*/
public void mark_primary(int count,int i)
{
if(count==1)
{
scores=scores+10;
}
//活二
else if(count==2&&i==0)
{
scores=scores+200;
}
//冲二
else if(count==2&&i==1)
{
scores=scores+50;
}
//活三
else if(count==3&&i==0)
{
scores=scores+85000;
System.out.println("分数"+scores);
}
//冲三
else if(count==3&&i==1)
{
scores=scores+150;
System.out.println("分数"+scores);
}
//活四
else if(count==4&&i==0)
{
scores=scores+90000;
System.out.println("分数"+scores);
}
//冲四
else if(count==4&&i==1)
{
scores=scores+87000;
System.out.println("分数"+scores);
}
else if(count==5)
{
scores=scores+100000;
}
}
/**
* 计算每个坐标的分数
* @param x
* @param y
* @param chess
* @param role
*/
public void countEveryPos_primary(int x,int y,int chess[][],int role)
{
scores=0;
int matchRole,startX=x,startY=y,count=0,up=0,down=0,left=0,right=0,leftUp=0,leftDown=0,rightUp=0,rightDown=0;
if(role==Chess.BLACK)
{
matchRole=Chess.WHITE;
}
else
{
matchRole=Chess.BLACK;
}
//竖直方向上判断输赢
while (true)
{
//向上判断
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
up++;
break;
}
else
{
break;
}
}
y = startY;
while (true) {
//向下判断
y = y + 1;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
down++;
break;
}
else
{
break;
}
}
mark_primary(count, up + down);
//水平方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左判断
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
down++;
break;
}
else
{
break;
}
}
x = startX;
while (true) {
//向右判断
x++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
right++;
break;
}
else
{
break;
}
}
mark_primary(count, left + right);
//右倾斜方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左上判断
y--;
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
leftUp++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右下判断
x++;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
rightDown++;
break;
}
else
{
break;
}
}
mark_primary(count, leftUp + rightDown);
//左倾斜方向判断
x = startX;
y = startY;
count = 0;
while (true) {
//向左下判断
x--;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
leftDown++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右上判断
x++;
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
rightUp++;
break;
}
else
{
break;
}
}
mark_primary(count, leftDown +rightUp);
}
/* public void countEveryPos(int x,int y,int chess[][],int role)
{
scores=0;
int startX=x,startY=y,count=0;
//竖直方向上判断输赢
while (true)
{
//向上判断
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
y = startY;
while (true) {
//向下判断
y = y + 1;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
//水平方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左判断
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
x = startX;
while (true) {
//向右判断
x++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
//右倾斜方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左上判断
y--;
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
x = startX;
y = startY;
while (true) {
//向右下判断
x++;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
//左倾斜方向判断
x = startX;
y = startY;
count = 0;
while (true) {
//向左下判断
x--;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
x = startX;
y = startY;
while (true) {
//向右上判断
x++;
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
}*/
}
| BlossomingL/gobang | src/Model/Computer.java | 5,754 | //向左判断 | line_comment | zh-cn | package Model;
import View.ChooseLevel;
/**
* Created by Blossoming on 2016/12/6.
*/
public class Computer {
private int test=0;
private int scores;
private Coord coord=new Coord();
private int everyPlayerPointScore[][]=new int[19][19];
private int everyComputerPointScore[][]=new int[19][19];
/**
* 计算下棋位置
* @param role 角色 chess[][]棋盘
*/
public Coord computePos(int role,int chess[][],int level)
{
int x, y, posX, posY;
//初级
if(level== ChooseLevel.PRIMARY_LEVEL) {
while (true) {
posX = (int) (Math.random() * 10 + Math.random() * 9);
posY = (int) (Math.random() * 10 + Math.random() * 9);
if (chess[posX][posY] == Chess.NO_CHESS) {
coord.setX(posX);
coord.setY(posY);
return coord;
}
}
}
//中级
else if(level==ChooseLevel.MEDIUM_LEVEL)
{
countMaxLines_primary(chess, Chess.WHITE);
return coord;
}
else if(level==ChooseLevel.SENIOR_LEVEL)
{
countMaxLines_medium(chess,Chess.WHITE);
return coord;
}
return coord;
}
/**********************下面是中级人机*************************************/
/**
* 找出分数最大的坐标
* @param chess 棋盘数组
* @param role 白棋还是黑棋
*/
public void countMaxLines_medium(int chess[][],int role)
{
Coord playerCoord=new Coord();
Coord computerCoord=new Coord();
int x,y;
for(x=0;x<19;x++)
{
for(y=0;y<19;y++)
{
if(chess[x][y]==Chess.NO_CHESS) {
countEveryPos_medium(x, y, chess, role);
everyPlayerPointScore[x][y] = scores;
countEveryPos_medium(x, y, chess, Chess.BLACK);
everyComputerPointScore[x][y] = scores;
}
else
{
everyPlayerPointScore[x][y]=0;
everyComputerPointScore[x][y]=0;
}
}
}
if(findBestPos_medium(everyPlayerPointScore, playerCoord)>=findBestPos(everyComputerPointScore,computerCoord))
{
coord=playerCoord;
}
else
{
coord=computerCoord;
}
}
/**
* 找到最大分数点的坐标
* @param a 数组 存储每个点的分数
* @param c 保存最大分数点的坐标
* @return
*/
public int findBestPos_medium(int a[][],Coord c)
{
int i,j,max=0;
for(i=0;i<19;i++)
{
for(j=0;j<19;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
c.setX(i);
c.setY(j);
}
}
}
return max;
}
/**
* 估分函数
* @param count 每一个方向上的相同颜色的总个数
* @param i 不同颜色的个数
*/
public void mark_medium(int count,int i,int countTwo,int role)
{
if(count==1)
{
scores=scores+10;
}
//活二
else if(count==2&&i==0&&role==Chess.WHITE&&countTwo<=1)
{
scores=scores+200;
//System.out.println("白子活二"+scores);
}
else if(count==2&&i==0&&role==Chess.BLACK&&countTwo<=1)
{
scores=scores+400;
// System.out.println("黑子活二"+scores);
}
//冲二
else if(count==2&&i==1)
{
scores=scores+50;
// System.out.println("冲二"+scores);
}
//双活二
else if(count==2&&i==0&&countTwo>1)
{
scores=scores+84000;
System.out.println("双活二"+scores);
}
//活三(黑子和白子同时活三的时候选择黑子成)
else if(count==3&&i==0&&role==Chess.WHITE)
{
scores=scores+85000;
//System.out.println("白子活三"+scores);
}
else if(count==3&&i==0&&role==Chess.BLACK)
{
scores=scores+86000;
//System.out.println("黑子活三"+scores);
}
//冲三
else if(count==3&&i==1&&role==Chess.WHITE)
{
scores=scores+300;
System.out.println("白子冲三"+scores);
}
else if(count==3&&i==1&&role==Chess.BLACK)
{
scores=scores+1000;
System.out.println("黑子冲三"+scores);
}
//白子活四
else if(count==4&&i==0&&role==Chess.WHITE)
{
scores=scores+90000;
//System.out.println("活四"+scores);
}
//黑子活四
else if(count==4&&i==0&&role==Chess.BLACK)
{
scores=scores+91000;
}
//冲四
else if(count==4&&i==1)
{
scores=scores+87000;
//System.out.println("冲四"+scores);
}
else if(count==5)
{
scores=scores+100000;
}
}
public void basicScore(int x,int y)
{
if(x==0||y==0)
{
scores=scores+3;
}
else
{
scores=scores+5;
}
}
/**
* 计算每个坐标的分数
* @param x
* @param y
* @param chess
* @param role
*/
public void countEveryPos_medium(int x,int y,int chess[][],int role)
{
scores=0;
basicScore(x,y);
//countTwo代表有一个坐标向八个方向数 两个连一起的个数
int matchRole,startX=x,startY=y,
count=0,up=0,down=0,left=0,right=0,
leftUp=0,leftDown=0,rightUp=0,rightDown=0,countTwo=0;
if(role==Chess.BLACK)
{
matchRole=Chess.WHITE;
}
else
{
matchRole=Chess.BLACK;
}
//竖直方向上判断输赢
while (true)
{
//向上判断
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||y<0){
up++;
break;
}
else
{
break;
}
}
y = startY;
while (true) {
//向下判断
y = y + 1;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||y>19){
down++;
break;
}
else
{
break;
}
}
//此处代表在上下方向有二连 或者 夹了一个空子两边各有一个棋子 并且两端没有其他子挡住
if(count==2&&(up+down==0))
{
countTwo++;
//System.out.println("出现二连"+countTwo);
}
mark_medium(count, up + down, countTwo,role);
//水平方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左 <SUF>
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x==0){
left++;
break;
}
else
{
break;
}
}
x = startX;
while (true) {
//向右判断
x++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x>19){
right++;
break;
}
else
{
break;
}
}
if(count==2&&(left+right==0))
{
countTwo++;
//System.out.println("出现二连"+countTwo);
}
mark_medium(count, left + right, countTwo,role);
//右倾斜方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左上判断
y--;
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x<0||y<0){
leftUp++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右下判断
x++;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x>19||y>19){
rightDown++;
break;
}
else
{
break;
}
}
if(count==2&&(leftUp+rightDown==0))
{
countTwo++;
// System.out.println("出现二连"+countTwo);
}
mark_medium(count, leftUp + rightDown, countTwo,role);
//左倾斜方向判断
x = startX;
y = startY;
count = 0;
while (true) {
//向左下判断
x--;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x<0||y>19){
leftDown++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右上判断
x++;
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if((x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole)||x>19||y<0){
rightUp++;
break;
}
else
{
break;
}
}
if(count==2&&(leftDown+rightUp==0))
{
countTwo++;
// System.out.println("出现二连"+countTwo);
}
mark_medium(count, leftDown + rightUp, countTwo,role);
}
/*********************下面是初级人机*************************************/
/**
* 找出分数最大的坐标
* @param chess 棋盘数组
* @param role 白棋还是黑棋
*/
public void countMaxLines_primary(int chess[][],int role)
{
Coord playerCoord=new Coord();
Coord computerCoord=new Coord();
int x,y;
for(x=0;x<19;x++)
{
for(y=0;y<19;y++)
{
if(chess[x][y]==Chess.NO_CHESS) {
countEveryPos_primary(x, y, chess, role);
everyPlayerPointScore[x][y] = scores;
countEveryPos_primary(x, y, chess, Chess.BLACK);
everyComputerPointScore[x][y] = scores;
}
else
{
everyPlayerPointScore[x][y]=0;
everyComputerPointScore[x][y]=0;
}
}
}
if(findBestPos(everyPlayerPointScore,playerCoord)>=findBestPos(everyComputerPointScore,computerCoord))
{
coord=playerCoord;
}
else
{
coord=computerCoord;
}
}
/**
* 找到最大分数点的坐标
* @param a 数组 存储每个点的分数
* @param c 保存最大分数点的坐标
* @return
*/
public int findBestPos(int a[][],Coord c)
{
int i,j,max=0;
for(i=0;i<19;i++)
{
for(j=0;j<19;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
c.setX(i);
c.setY(j);
}
}
}
return max;
}
/**
* 估分函数
* @param count 每一个方向上的相同颜色的总个数
* @param i 不同颜色的个数
*/
public void mark_primary(int count,int i)
{
if(count==1)
{
scores=scores+10;
}
//活二
else if(count==2&&i==0)
{
scores=scores+200;
}
//冲二
else if(count==2&&i==1)
{
scores=scores+50;
}
//活三
else if(count==3&&i==0)
{
scores=scores+85000;
System.out.println("分数"+scores);
}
//冲三
else if(count==3&&i==1)
{
scores=scores+150;
System.out.println("分数"+scores);
}
//活四
else if(count==4&&i==0)
{
scores=scores+90000;
System.out.println("分数"+scores);
}
//冲四
else if(count==4&&i==1)
{
scores=scores+87000;
System.out.println("分数"+scores);
}
else if(count==5)
{
scores=scores+100000;
}
}
/**
* 计算每个坐标的分数
* @param x
* @param y
* @param chess
* @param role
*/
public void countEveryPos_primary(int x,int y,int chess[][],int role)
{
scores=0;
int matchRole,startX=x,startY=y,count=0,up=0,down=0,left=0,right=0,leftUp=0,leftDown=0,rightUp=0,rightDown=0;
if(role==Chess.BLACK)
{
matchRole=Chess.WHITE;
}
else
{
matchRole=Chess.BLACK;
}
//竖直方向上判断输赢
while (true)
{
//向上判断
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
up++;
break;
}
else
{
break;
}
}
y = startY;
while (true) {
//向下判断
y = y + 1;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
down++;
break;
}
else
{
break;
}
}
mark_primary(count, up + down);
//水平方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左判断
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
down++;
break;
}
else
{
break;
}
}
x = startX;
while (true) {
//向右判断
x++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
right++;
break;
}
else
{
break;
}
}
mark_primary(count, left + right);
//右倾斜方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左上判断
y--;
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
leftUp++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右下判断
x++;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
rightDown++;
break;
}
else
{
break;
}
}
mark_primary(count, leftUp + rightDown);
//左倾斜方向判断
x = startX;
y = startY;
count = 0;
while (true) {
//向左下判断
x--;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
leftDown++;
break;
}
else
{
break;
}
}
x = startX;
y = startY;
while (true) {
//向右上判断
x++;
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
}else if(x >= 0 && x < 19 && y >= 0 && y < 19 &&chess[x][y]==matchRole){
rightUp++;
break;
}
else
{
break;
}
}
mark_primary(count, leftDown +rightUp);
}
/* public void countEveryPos(int x,int y,int chess[][],int role)
{
scores=0;
int startX=x,startY=y,count=0;
//竖直方向上判断输赢
while (true)
{
//向上判断
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
y = startY;
while (true) {
//向下判断
y = y + 1;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
//水平方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左判断
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
x = startX;
while (true) {
//向右判断
x++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
//右倾斜方向判断输赢
x = startX;
y = startY;
count = 0;
while (true) {
//向左上判断
y--;
x--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
x = startX;
y = startY;
while (true) {
//向右下判断
x++;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
//左倾斜方向判断
x = startX;
y = startY;
count = 0;
while (true) {
//向左下判断
x--;
y++;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
x = startX;
y = startY;
while (true) {
//向右上判断
x++;
y--;
if (x >= 0 && x < 19 && y >= 0 && y < 19 && chess[x][y] == role) {
count++;
} else {
break;
}
}
mark(count);
}*/
}
| 1 | 6 | 1 |
19509_6 | package com.own.send.server.util;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/**
* @Description: 发送邮件和接收邮件
* @author: Blucezhang
*/
public class SendMail {
public static void sendMail(String email, String title, String content, String iocMailSmtpHost, String iocMailSmtpAuth,
String iocSmtp, String iocMailFrom, String iocMailFromUser, String iocMailFromPassWord
) throws AddressException, MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", iocMailSmtpHost);
//指定是否需要SMTP验证
props.put("mail.smtp.auth", iocMailSmtpAuth);
Session mailSession = Session.getDefaultInstance(props);
Transport transport = mailSession.getTransport(iocSmtp);
mailSession.setDebug(true);//是否在控制台显示debug信息
Message message = new MimeMessage(mailSession);
try {
message.setFrom(new InternetAddress(MimeUtility.encodeText(iocMailFrom), "汇金贷"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));//收件人
message.setSubject(title);//邮件主题
/** 代表正文的bodypart **/
MimeBodyPart text = new MimeBodyPart();
text.setContent(content, "text/html;charset=utf-8");
/** 代表正文所引用的图片的bodypart **/
/* MimeBodyPart image = new MimeBodyPart();
DataHandler dh1 = new DataHandler(new FileDataSource("E:/17.png"));
image.setDataHandler(dh1);
image.setContentID("17.png");*/
/** 代表附件的bodypart **/
/* MimeBodyPart attach = new MimeBodyPart();
DataHandler dh2 = new DataHandler(new FileDataSource("E:杰克逊.wav"));
attach.setDataHandler(dh2);
//System.out.println(dh2.getName());
attach.setFileName(MimeUtility.encodeText(dh2.getName())); */
MimeMultipart text_image = new MimeMultipart("related");
text_image.addBodyPart(text);
//text_image.addBodyPart(image);
MimeBodyPart text_image_body = new MimeBodyPart();
text_image_body.setContent(text_image);
/** 封装了所有邮件数据的容器 **/
MimeMultipart multipart = new MimeMultipart("mixed");
multipart.addBodyPart(text_image_body);
message.setContent(multipart);
message.saveChanges();
transport.connect(iocMailSmtpHost, iocMailFromUser, iocMailFromPassWord); //这个邮箱可随便使用
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
| Blucezhang/micro-server-own | own-send-server/src/main/java/com/own/send/server/util/SendMail.java | 792 | //邮件主题 | line_comment | zh-cn | package com.own.send.server.util;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/**
* @Description: 发送邮件和接收邮件
* @author: Blucezhang
*/
public class SendMail {
public static void sendMail(String email, String title, String content, String iocMailSmtpHost, String iocMailSmtpAuth,
String iocSmtp, String iocMailFrom, String iocMailFromUser, String iocMailFromPassWord
) throws AddressException, MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", iocMailSmtpHost);
//指定是否需要SMTP验证
props.put("mail.smtp.auth", iocMailSmtpAuth);
Session mailSession = Session.getDefaultInstance(props);
Transport transport = mailSession.getTransport(iocSmtp);
mailSession.setDebug(true);//是否在控制台显示debug信息
Message message = new MimeMessage(mailSession);
try {
message.setFrom(new InternetAddress(MimeUtility.encodeText(iocMailFrom), "汇金贷"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));//收件人
message.setSubject(title);//邮件 <SUF>
/** 代表正文的bodypart **/
MimeBodyPart text = new MimeBodyPart();
text.setContent(content, "text/html;charset=utf-8");
/** 代表正文所引用的图片的bodypart **/
/* MimeBodyPart image = new MimeBodyPart();
DataHandler dh1 = new DataHandler(new FileDataSource("E:/17.png"));
image.setDataHandler(dh1);
image.setContentID("17.png");*/
/** 代表附件的bodypart **/
/* MimeBodyPart attach = new MimeBodyPart();
DataHandler dh2 = new DataHandler(new FileDataSource("E:杰克逊.wav"));
attach.setDataHandler(dh2);
//System.out.println(dh2.getName());
attach.setFileName(MimeUtility.encodeText(dh2.getName())); */
MimeMultipart text_image = new MimeMultipart("related");
text_image.addBodyPart(text);
//text_image.addBodyPart(image);
MimeBodyPart text_image_body = new MimeBodyPart();
text_image_body.setContent(text_image);
/** 封装了所有邮件数据的容器 **/
MimeMultipart multipart = new MimeMultipart("mixed");
multipart.addBodyPart(text_image_body);
message.setContent(multipart);
message.saveChanges();
transport.connect(iocMailSmtpHost, iocMailFromUser, iocMailFromPassWord); //这个邮箱可随便使用
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
| 1 | 6 | 1 |
27910_15 | package jxau.sms.anping.po;
import java.io.Serializable;
import java.util.Date;
import jxau.sms.chenjiang.po.StuBasicInfo;
/**
* 医保
* @author anping
* 2014-4-13
* TODO
*/
public class HosInsuranceInfo implements Serializable{
private int hosNo;//编号
private StuBasicInfo student;//学号
private String hosType;//类型
private String hospitalAddress;//住院地址
private Date hospitalDate;//住院日期
private Date leaveDate;//出院日期
private int hosDate;//住院天数
private int localCity;//本市还是转外
private String conditon;//病情
private double cost;//总费用
private Date applyTime;//申请时间
private int accept;//是否受理//数据等于0表示在等待,否则-1不受理1受理
private int collarCard;//是否领卡 0 表示现待受理,1表示已领卡,-1表示未领卡
private Date submitTime;//递交案子时间
private String refuseReason;//未受理原因
private String resultDeal;//处理结果
private String companyRemark;//商业保险备注
private double reimbursementAmount;//医保处已报金额
private int bill;//是否有结算单
private Date getcardTime;//领卡时间
private String jumingRemark;//居民医保备注
private String bankcardID;//银行卡号
private int complete;//除结算单材料是否齐全
private Date insurerTime;//保险公司接案子的时间
private String notinsurerReason;//没有结算的原因
private String baoxiaoRemark;//已报销备注
private String stateRemark;//审核状态备注
private String returnMark;//返回消息备注
private String hosState;//审核状态
public int getHosNo() {
return hosNo;
}
public void setHosNo(int hosNo) {
this.hosNo = hosNo;
}
public StuBasicInfo getStudent() {
return student;
}
public void setStudent(StuBasicInfo student) {
this.student = student;
}
public String getHosType() {
return hosType;
}
public void setHosType(String hosType) {
this.hosType = hosType;
}
public String getHospitalAddress() {
return hospitalAddress;
}
public void setHospitalAddress(String hospitalAddress) {
this.hospitalAddress = hospitalAddress;
}
public Date getHospitalDate() {
return hospitalDate;
}
public void setHospitalDate(Date hospitalDate) {
this.hospitalDate = hospitalDate;
}
public Date getLeaveDate() {
return leaveDate;
}
public void setLeaveDate(Date leaveDate) {
this.leaveDate = leaveDate;
}
public int getHosDate() {
return hosDate;
}
public void setHosDate(int hosDate) {
this.hosDate = hosDate;
}
public int getLocalCity() {
return localCity;
}
public void setLocalCity(int localCity) {
this.localCity = localCity;
}
public String getConditon() {
return conditon;
}
public void setConditon(String conditon) {
this.conditon = conditon;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public Date getApplyTime() {
return applyTime;
}
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
public int getAccept() {
return accept;
}
public void setAccept(int accept) {
this.accept = accept;
}
public int getCollarCard() {
return collarCard;
}
public void setCollarCard(int collarCard) {
this.collarCard = collarCard;
}
public Date getSubmitTime() {
return submitTime;
}
public void setSubmitTime(Date submitTime) {
this.submitTime = submitTime;
}
public String getRefuseReason() {
return refuseReason;
}
public void setRefuseReason(String refuseReason) {
this.refuseReason = refuseReason;
}
public String getResultDeal() {
return resultDeal;
}
public void setResultDeal(String resultDeal) {
this.resultDeal = resultDeal;
}
public String getCompanyRemark() {
return companyRemark;
}
public void setCompanyRemark(String companyRemark) {
this.companyRemark = companyRemark;
}
public double getReimbursementAmount() {
return reimbursementAmount;
}
public void setReimbursementAmount(double reimbursementAmount) {
this.reimbursementAmount = reimbursementAmount;
}
public int getBill() {
return bill;
}
public void setBill(int bill) {
this.bill = bill;
}
public Date getGetcardTime() {
return getcardTime;
}
public void setGetcardTime(Date getcardTime) {
this.getcardTime = getcardTime;
}
public String getJumingRemark() {
return jumingRemark;
}
public void setJumingRemark(String jumingRemark) {
this.jumingRemark = jumingRemark;
}
public String getBankcardID() {
return bankcardID;
}
public void setBankcardID(String bankcardID) {
this.bankcardID = bankcardID;
}
public int getComplete() {
return complete;
}
public void setComplete(int complete) {
this.complete = complete;
}
public Date getInsurerTime() {
return insurerTime;
}
public void setInsurerTime(Date insurerTime) {
this.insurerTime = insurerTime;
}
public String getNotinsurerReason() {
return notinsurerReason;
}
public void setNotinsurerReason(String notinsurerReason) {
this.notinsurerReason = notinsurerReason;
}
public String getBaoxiaoRemark() {
return baoxiaoRemark;
}
public void setBaoxiaoRemark(String baoxiaoRemark) {
this.baoxiaoRemark = baoxiaoRemark;
}
public String getStateRemark() {
return stateRemark;
}
public void setStateRemark(String stateRemark) {
this.stateRemark = stateRemark;
}
public String getReturnMark() {
return returnMark;
}
public void setReturnMark(String returnMark) {
this.returnMark = returnMark;
}
public String getHosState() {
return hosState;
}
public void setHosState(String hosState) {
this.hosState = hosState;
}
}
| BlueDots/sms | sms/src/jxau/sms/anping/po/HosInsuranceInfo.java | 1,819 | //是否有结算单 | line_comment | zh-cn | package jxau.sms.anping.po;
import java.io.Serializable;
import java.util.Date;
import jxau.sms.chenjiang.po.StuBasicInfo;
/**
* 医保
* @author anping
* 2014-4-13
* TODO
*/
public class HosInsuranceInfo implements Serializable{
private int hosNo;//编号
private StuBasicInfo student;//学号
private String hosType;//类型
private String hospitalAddress;//住院地址
private Date hospitalDate;//住院日期
private Date leaveDate;//出院日期
private int hosDate;//住院天数
private int localCity;//本市还是转外
private String conditon;//病情
private double cost;//总费用
private Date applyTime;//申请时间
private int accept;//是否受理//数据等于0表示在等待,否则-1不受理1受理
private int collarCard;//是否领卡 0 表示现待受理,1表示已领卡,-1表示未领卡
private Date submitTime;//递交案子时间
private String refuseReason;//未受理原因
private String resultDeal;//处理结果
private String companyRemark;//商业保险备注
private double reimbursementAmount;//医保处已报金额
private int bill;//是否 <SUF>
private Date getcardTime;//领卡时间
private String jumingRemark;//居民医保备注
private String bankcardID;//银行卡号
private int complete;//除结算单材料是否齐全
private Date insurerTime;//保险公司接案子的时间
private String notinsurerReason;//没有结算的原因
private String baoxiaoRemark;//已报销备注
private String stateRemark;//审核状态备注
private String returnMark;//返回消息备注
private String hosState;//审核状态
public int getHosNo() {
return hosNo;
}
public void setHosNo(int hosNo) {
this.hosNo = hosNo;
}
public StuBasicInfo getStudent() {
return student;
}
public void setStudent(StuBasicInfo student) {
this.student = student;
}
public String getHosType() {
return hosType;
}
public void setHosType(String hosType) {
this.hosType = hosType;
}
public String getHospitalAddress() {
return hospitalAddress;
}
public void setHospitalAddress(String hospitalAddress) {
this.hospitalAddress = hospitalAddress;
}
public Date getHospitalDate() {
return hospitalDate;
}
public void setHospitalDate(Date hospitalDate) {
this.hospitalDate = hospitalDate;
}
public Date getLeaveDate() {
return leaveDate;
}
public void setLeaveDate(Date leaveDate) {
this.leaveDate = leaveDate;
}
public int getHosDate() {
return hosDate;
}
public void setHosDate(int hosDate) {
this.hosDate = hosDate;
}
public int getLocalCity() {
return localCity;
}
public void setLocalCity(int localCity) {
this.localCity = localCity;
}
public String getConditon() {
return conditon;
}
public void setConditon(String conditon) {
this.conditon = conditon;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public Date getApplyTime() {
return applyTime;
}
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
public int getAccept() {
return accept;
}
public void setAccept(int accept) {
this.accept = accept;
}
public int getCollarCard() {
return collarCard;
}
public void setCollarCard(int collarCard) {
this.collarCard = collarCard;
}
public Date getSubmitTime() {
return submitTime;
}
public void setSubmitTime(Date submitTime) {
this.submitTime = submitTime;
}
public String getRefuseReason() {
return refuseReason;
}
public void setRefuseReason(String refuseReason) {
this.refuseReason = refuseReason;
}
public String getResultDeal() {
return resultDeal;
}
public void setResultDeal(String resultDeal) {
this.resultDeal = resultDeal;
}
public String getCompanyRemark() {
return companyRemark;
}
public void setCompanyRemark(String companyRemark) {
this.companyRemark = companyRemark;
}
public double getReimbursementAmount() {
return reimbursementAmount;
}
public void setReimbursementAmount(double reimbursementAmount) {
this.reimbursementAmount = reimbursementAmount;
}
public int getBill() {
return bill;
}
public void setBill(int bill) {
this.bill = bill;
}
public Date getGetcardTime() {
return getcardTime;
}
public void setGetcardTime(Date getcardTime) {
this.getcardTime = getcardTime;
}
public String getJumingRemark() {
return jumingRemark;
}
public void setJumingRemark(String jumingRemark) {
this.jumingRemark = jumingRemark;
}
public String getBankcardID() {
return bankcardID;
}
public void setBankcardID(String bankcardID) {
this.bankcardID = bankcardID;
}
public int getComplete() {
return complete;
}
public void setComplete(int complete) {
this.complete = complete;
}
public Date getInsurerTime() {
return insurerTime;
}
public void setInsurerTime(Date insurerTime) {
this.insurerTime = insurerTime;
}
public String getNotinsurerReason() {
return notinsurerReason;
}
public void setNotinsurerReason(String notinsurerReason) {
this.notinsurerReason = notinsurerReason;
}
public String getBaoxiaoRemark() {
return baoxiaoRemark;
}
public void setBaoxiaoRemark(String baoxiaoRemark) {
this.baoxiaoRemark = baoxiaoRemark;
}
public String getStateRemark() {
return stateRemark;
}
public void setStateRemark(String stateRemark) {
this.stateRemark = stateRemark;
}
public String getReturnMark() {
return returnMark;
}
public void setReturnMark(String returnMark) {
this.returnMark = returnMark;
}
public String getHosState() {
return hosState;
}
public void setHosState(String hosState) {
this.hosState = hosState;
}
}
| 1 | 8 | 1 |
39775_26 | package com.ucac.Work.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.ucac.Work.service.WorkService;
import com.ucac.dao.EntityDao;
import com.ucac.dao.impl.EntityDaoImpl;
import com.ucac.exception.DBException;
import com.ucac.exception.ErrorException;
import com.ucac.po.Applicant;
import com.ucac.po.Work;
import com.ucac.syw.util.UploadUtils;
import com.ucac.vo.QueryResult;
import com.ucac.vo.WorkInfo;
import com.ucac.vo.WorkResult;
import com.ucac.vo.WorkUrl;
//chengjiang
public class WorkServiceImpl implements WorkService{
private WorkServiceImpl(){}
private EntityDao entityDao = EntityDaoImpl.getInstance();
private static class WorkServiceHelp {
static final WorkService INSTANCE = new WorkServiceImpl();
}
public static WorkService getInstance() {
return WorkServiceHelp.INSTANCE;
}
@Override
/**
*
* 李轶翔
* @todo 比赛结果展示
* @param page 当前为第几页
* @param maxSize 每页的数量
* @param category 类别 1-7 7为全部
* @param sortType 排序方式,0降序,1升序, -1为游客查看界面调用(为降序)
* @return
* @returntype QueryResult<WorkResult>
* QueryResult为自定义容器
* WorkResult为VO,用于指定容器的类型
*/
public QueryResult<WorkResult> showWorkResult(int page, int maxSize,
int category, int sortType) throws DBException {
/**
* 该方法调用Entitydao的findAllEntityByCompose方法
*/
//用于存放dao方法的返回值
List<WorkResult> list = new ArrayList<WorkResult>();
//作为此service方法的返回值
QueryResult<WorkResult> query = new QueryResult<WorkResult>();
//用于对带有?的sql语句参数赋值
List<Object> parames = new ArrayList<Object>();
//sql语句初始化
String sql = "";
String sqlAll = "";
//判断是否为全部查询
if(category==7){
//排序选择
if(sortType==1){
//后台比赛结果查询界面1 升序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking asc limit ? , ?;";
}else{
//后台比赛结果查询界面0 降序
//前台比赛结果查询界面-1 降序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking desc limit ? , ?;";
}
//调用dao的方法
try {
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,null);
//查询一共有多少条数据
sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and w.work_state=1; ";
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//带有?的赋值
parames.add(category);
//sql语句的赋值
if(sortType==1){
//后台比赛结果查询界面1 升序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking asc limit ? , ?;";
}else{
//后台比赛结果查询界面0 降序
//前台比赛结果查询界面-1 降序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking desc limit ? , ?;";
}
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
//查询一共有多少条数据
sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1; ";
}
int size = entityDao.getAllCount(sqlAll, parames);
//对于返回值的赋值处理
query.setResults(list);
//数据库中一共有多少条数据
query.setTotalCount(size);
return query;
}
/**
*
* 李轶翔
* @todo 比赛结果的搜索
* @param schoolName 学校名称
* @param communityName 社团名称
* @return
* @throws DBException
* @throws ErrorException
* @returntype QueryResult<WorkResult>
* QueryResult为自定义容器
* WorkResult为VO,用于指定容器的类型
*/
@Override
public QueryResult<WorkResult> searchWorkResult(String schoolName,
String communityName) throws ErrorException, DBException {
// TODO Auto-generated method stub
//用于存放dao方法的返回值
List<WorkResult> list = new ArrayList<WorkResult>();
//用于对带有?的sql语句参数赋值
List<Object> parames = new ArrayList<Object>();
//返回值初始化
QueryResult<WorkResult> query = new QueryResult<WorkResult>();
// where条件的传入参数
String sql = "";
//搜索结果分页赋值
int page = 1;
int maxSize = 500;
//判断传入的搜索条件
if(schoolName==""&&communityName==""){
//学校名称和社团名称都为空
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;";
parames.add("狗屎+狗屎=狗屎");
parames.add("狗屎+狗屎=狗屎");
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
}else if(schoolName==""&&communityName!=""){
//只根据社团名称查询
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and community_name like \"%\"?\"%\" limit ? , ?;";
parames.add(communityName);
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
}else if(communityName==""&&schoolName!=""){
//只根据学校名称查询
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" limit ? , ?;";
parames.add(schoolName);
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
} else {
//根据学校名称和社团名称查询
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;";
parames.add(schoolName);
parames.add(communityName);
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
}
//对于返回值的赋值处理
query.setResults(list);
//设置用于分页时一共有多少页
query.setTotalCount((list.size()/maxSize)+1);
return query;
}
@Override
public WorkUrl findSpecificWorkById(String id) {
WorkUrl wUrl = new WorkUrl();
String path = UploadUtils.getWorksDirectory();
wUrl.setVideoUrl(path+id+"-video.flv");
wUrl.setDocumentUrl(path+id+"-material.doc");
wUrl.setPictureUrl1(path+id+"-pic1.jpg");
wUrl.setPictureUrl2(path+id+"-pic2.jpg");
wUrl.setApplyFormUrl(path+id+"-regForm.doc");
return wUrl;
}
@Override
public int checkWorkContent(List<Applicant> applicants, String assessType) throws ErrorException, DBException {
int count = 0;
Work work = new Work();
if(assessType.equals("assess")) {
for(int i=0;i<applicants.size();i++) {
work.setId(applicants.get(i).getId());
work.setWorkState(1);
entityDao.update(work);
count++;
}
}else if(assessType.equals("notAssess")){
for(int i=0;i<applicants.size();i++) {
work.setId(applicants.get(i).getId());
work.setWorkState(0);
entityDao.update(work);
count++;
}
}
return count;
}
@Override
public QueryResult<WorkInfo> showWorkInfos(int nowpage,int maxSize) throws DBException {
QueryResult<WorkInfo> wResult = new QueryResult<WorkInfo>();
List<WorkInfo> workInfos = null;
String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?";
workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, (nowpage-1)*maxSize, maxSize, sql, null);
wResult.setResults(workInfos);
wResult.setTotalCount(numofWorkInfo());
return wResult;
}
@Override
public int numofWorkInfo() throws DBException {
List<WorkInfo> workInfos = new ArrayList<WorkInfo>();
String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?";
workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, 0, 10000, sql, null);
return workInfos.size();
}
}
| BlueDots/ucac | uacc/src/com/ucac/Work/service/impl/WorkServiceImpl.java | 3,043 | //用于对带有?的sql语句参数赋值
| line_comment | zh-cn | package com.ucac.Work.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.ucac.Work.service.WorkService;
import com.ucac.dao.EntityDao;
import com.ucac.dao.impl.EntityDaoImpl;
import com.ucac.exception.DBException;
import com.ucac.exception.ErrorException;
import com.ucac.po.Applicant;
import com.ucac.po.Work;
import com.ucac.syw.util.UploadUtils;
import com.ucac.vo.QueryResult;
import com.ucac.vo.WorkInfo;
import com.ucac.vo.WorkResult;
import com.ucac.vo.WorkUrl;
//chengjiang
public class WorkServiceImpl implements WorkService{
private WorkServiceImpl(){}
private EntityDao entityDao = EntityDaoImpl.getInstance();
private static class WorkServiceHelp {
static final WorkService INSTANCE = new WorkServiceImpl();
}
public static WorkService getInstance() {
return WorkServiceHelp.INSTANCE;
}
@Override
/**
*
* 李轶翔
* @todo 比赛结果展示
* @param page 当前为第几页
* @param maxSize 每页的数量
* @param category 类别 1-7 7为全部
* @param sortType 排序方式,0降序,1升序, -1为游客查看界面调用(为降序)
* @return
* @returntype QueryResult<WorkResult>
* QueryResult为自定义容器
* WorkResult为VO,用于指定容器的类型
*/
public QueryResult<WorkResult> showWorkResult(int page, int maxSize,
int category, int sortType) throws DBException {
/**
* 该方法调用Entitydao的findAllEntityByCompose方法
*/
//用于存放dao方法的返回值
List<WorkResult> list = new ArrayList<WorkResult>();
//作为此service方法的返回值
QueryResult<WorkResult> query = new QueryResult<WorkResult>();
//用于对带有?的sql语句参数赋值
List<Object> parames = new ArrayList<Object>();
//sql语句初始化
String sql = "";
String sqlAll = "";
//判断是否为全部查询
if(category==7){
//排序选择
if(sortType==1){
//后台比赛结果查询界面1 升序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking asc limit ? , ?;";
}else{
//后台比赛结果查询界面0 降序
//前台比赛结果查询界面-1 降序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 order by w.ranking desc limit ? , ?;";
}
//调用dao的方法
try {
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,null);
//查询一共有多少条数据
sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and w.work_state=1; ";
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//带有?的赋值
parames.add(category);
//sql语句的赋值
if(sortType==1){
//后台比赛结果查询界面1 升序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking asc limit ? , ?;";
}else{
//后台比赛结果查询界面0 降序
//前台比赛结果查询界面-1 降序
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1 order by w.ranking desc limit ? , ?;";
}
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
//查询一共有多少条数据
sqlAll ="select count(*) from t_applicant a,t_work w where a.id=w.id and category=? and w.work_state=1; ";
}
int size = entityDao.getAllCount(sqlAll, parames);
//对于返回值的赋值处理
query.setResults(list);
//数据库中一共有多少条数据
query.setTotalCount(size);
return query;
}
/**
*
* 李轶翔
* @todo 比赛结果的搜索
* @param schoolName 学校名称
* @param communityName 社团名称
* @return
* @throws DBException
* @throws ErrorException
* @returntype QueryResult<WorkResult>
* QueryResult为自定义容器
* WorkResult为VO,用于指定容器的类型
*/
@Override
public QueryResult<WorkResult> searchWorkResult(String schoolName,
String communityName) throws ErrorException, DBException {
// TODO Auto-generated method stub
//用于存放dao方法的返回值
List<WorkResult> list = new ArrayList<WorkResult>();
//用于 <SUF>
List<Object> parames = new ArrayList<Object>();
//返回值初始化
QueryResult<WorkResult> query = new QueryResult<WorkResult>();
// where条件的传入参数
String sql = "";
//搜索结果分页赋值
int page = 1;
int maxSize = 500;
//判断传入的搜索条件
if(schoolName==""&&communityName==""){
//学校名称和社团名称都为空
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;";
parames.add("狗屎+狗屎=狗屎");
parames.add("狗屎+狗屎=狗屎");
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
}else if(schoolName==""&&communityName!=""){
//只根据社团名称查询
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and community_name like \"%\"?\"%\" limit ? , ?;";
parames.add(communityName);
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
}else if(communityName==""&&schoolName!=""){
//只根据学校名称查询
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" limit ? , ?;";
parames.add(schoolName);
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
} else {
//根据学校名称和社团名称查询
sql = "select a.id applicant_id,a.community_name,a.school,a.category,w.picture_score,w.video_score,w.document_score,w.score,w.ranking from t_applicant a,t_work w where a.id=w.id and w.work_state=1 and school like \"%\"?\"%\" and community_name like \"%\"?\"%\" limit ? , ?;";
parames.add(schoolName);
parames.add(communityName);
list = entityDao.findAllEntityByCompose(WorkResult.class,(page-1)*maxSize,maxSize, sql,parames);
}
//对于返回值的赋值处理
query.setResults(list);
//设置用于分页时一共有多少页
query.setTotalCount((list.size()/maxSize)+1);
return query;
}
@Override
public WorkUrl findSpecificWorkById(String id) {
WorkUrl wUrl = new WorkUrl();
String path = UploadUtils.getWorksDirectory();
wUrl.setVideoUrl(path+id+"-video.flv");
wUrl.setDocumentUrl(path+id+"-material.doc");
wUrl.setPictureUrl1(path+id+"-pic1.jpg");
wUrl.setPictureUrl2(path+id+"-pic2.jpg");
wUrl.setApplyFormUrl(path+id+"-regForm.doc");
return wUrl;
}
@Override
public int checkWorkContent(List<Applicant> applicants, String assessType) throws ErrorException, DBException {
int count = 0;
Work work = new Work();
if(assessType.equals("assess")) {
for(int i=0;i<applicants.size();i++) {
work.setId(applicants.get(i).getId());
work.setWorkState(1);
entityDao.update(work);
count++;
}
}else if(assessType.equals("notAssess")){
for(int i=0;i<applicants.size();i++) {
work.setId(applicants.get(i).getId());
work.setWorkState(0);
entityDao.update(work);
count++;
}
}
return count;
}
@Override
public QueryResult<WorkInfo> showWorkInfos(int nowpage,int maxSize) throws DBException {
QueryResult<WorkInfo> wResult = new QueryResult<WorkInfo>();
List<WorkInfo> workInfos = null;
String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?";
workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, (nowpage-1)*maxSize, maxSize, sql, null);
wResult.setResults(workInfos);
wResult.setTotalCount(numofWorkInfo());
return wResult;
}
@Override
public int numofWorkInfo() throws DBException {
List<WorkInfo> workInfos = new ArrayList<WorkInfo>();
String sql = "select a.id,community_name,school,a.category,work_state from t_applicant a,t_work b where a.id = b.id limit ?,?";
workInfos = entityDao.findAllEntityByCompose(WorkInfo.class, 0, 10000, sql, null);
return workInfos.size();
}
}
| 1 | 19 | 1 |
7972_40 | package com.sp.questionnaire.utils;
import com.sp.questionnaire.entity.Paper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
/*
* Author: Seven
* Email : [email protected]
* 2018-09-15 Saturday 08:11
*/
@Service
public class MailUtils {
// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
// PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
// 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
public static String myEmailAccount = "[email protected]";
public static String myEmailPassword = "pkqifoxowfikdcfg";
// 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
// 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
// QQ邮箱的为smtp.qq.com
public static String myEmailSMTPHost = "smtp.qq.com";
private String senderName = "在线问卷系统";
private String themeActivate = "在线问卷系统账号激活通知";
private String themePaperStart = "问卷生效通知";
private String themePaperEnd = "问卷结束通知";
@Value("${mail.ActivatePrefix}")
private String url;
@Value("${mail.startPaperPrefix}")
private String paperUrl;
@Value("${home.url}")
private String homeUrl;
@Autowired
private CommonUtils commonUtils;
public void sendActivateMail(String receiveMailAccount, String nickName, String randomCode) throws MessagingException {
StringBuffer content = new StringBuffer();
content.append("<b>您已在本系统成功注册账号<br>昵称为:").append(nickName).append("<br><br>")
.append("现在<a href='").append(url).append(randomCode).append("'>点击这里激活账号</a>即可开始使用!")
.append("</b><br>如非本人操作,请忽略本邮件。");
mailSettings(senderName, themeActivate, receiveMailAccount, nickName, content.toString());
}
public void sendPaperStartMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException {
StringBuffer content = new StringBuffer();
content.append("<b>尊敬的").append(nickName).append("<br><br>")
.append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime()))
.append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经可以正式答卷了,快点分享出去吧!<br><br>")
.append("现在<a href='").append(paperUrl).append(paper.getId()).append("'>点击这里</a>即可查看问卷详情!</b>")
.append("<br><br>使用提示:打开链接后可复制问卷链接或直接分享给他人,亦可<a href='").append(homeUrl).append("'>登录账号</a>查看更多信息。");
mailSettings(senderName, themePaperStart, receiveMailAccount, nickName, content.toString());
}
public void sendPaperEndMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException {
StringBuffer content = new StringBuffer();
content.append("<b>尊敬的").append(nickName).append("<br><br>")
.append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime()))
.append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经结束了!<br><br>")
.append("现在<a href='").append(homeUrl).append(paper.getId()).append("'>登录账号</a>即可查看问卷数据详情!</b>")
.append("<br><br>使用提示:为便于显示请使用电脑查看。");
mailSettings(senderName, themePaperEnd, receiveMailAccount, nickName, content.toString());
}
//(session, myEmailAccount, receiveMailAccount, "发件人名字","收件人名字","同志","标题","内容:2943<a href='http://www.baidu.com'>Baidu</a>");
public void mailSettings(String senderName, String theme, String receiveMailAccount,
String nickName, String content) throws MessagingException {
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
// PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
// 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
// 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
final String smtpPort = "465";
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getDefaultInstance(props);
session.setDebug(false); // 设置为debug模式, 可以查看详细的发送 log
// 3. 创建一封邮件,
// Session session, String sendMail,String receiveMail, String sender, String recipients, String theme, String content
//session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,邮件标题,邮件内容
MimeMessage message = null;
try {
message = createMimeMessage(session, myEmailAccount, receiveMailAccount,
senderName, nickName, theme, content);
} catch (Exception e) {
e.printStackTrace();
}
//发第二条
/*receiveMailAccount = "[email protected]";
MimeMessage message2 = createMimeMessage(session, myEmailAccount, receiveMailAccount,
"发件人名字","收件人名字","标题","内容:134");
*/
// 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());
//transport.sendMessage(message2, message2.getAllRecipients());
// 7. 关闭连接
transport.close();
}
/**
* 创建一封只包含文本的简单邮件
*
* @param session 和服务器交互的会话
* @param senderMailAccount 发件人邮箱
* @param receiverMailAccount 收件人邮箱
* @return
* @throws Exception
*/
//session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,称呼(例:***同学,老师等),邮件标题,邮件内容
public MimeMessage createMimeMessage(
Session session, String senderMailAccount, String receiverMailAccount, String senderName, String receiverName,
String theme, String content) throws Exception {
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(senderMailAccount, senderName, "UTF-8"));
// 3. To: 收件人(可以增加多个收件人、抄送、密送)
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiverMailAccount, receiverName, "UTF-8"));
// 4. Subject: 邮件主题
message.setSubject(theme, "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
message.setContent(content, "text/html;charset=UTF-8");
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}
}
| BlueDriver/questionnaire_online | src/main/java/com/sp/questionnaire/utils/MailUtils.java | 2,511 | // 7. 关闭连接 | line_comment | zh-cn | package com.sp.questionnaire.utils;
import com.sp.questionnaire.entity.Paper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
/*
* Author: Seven
* Email : [email protected]
* 2018-09-15 Saturday 08:11
*/
@Service
public class MailUtils {
// 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
// PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
// 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
public static String myEmailAccount = "[email protected]";
public static String myEmailPassword = "pkqifoxowfikdcfg";
// 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
// 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
// QQ邮箱的为smtp.qq.com
public static String myEmailSMTPHost = "smtp.qq.com";
private String senderName = "在线问卷系统";
private String themeActivate = "在线问卷系统账号激活通知";
private String themePaperStart = "问卷生效通知";
private String themePaperEnd = "问卷结束通知";
@Value("${mail.ActivatePrefix}")
private String url;
@Value("${mail.startPaperPrefix}")
private String paperUrl;
@Value("${home.url}")
private String homeUrl;
@Autowired
private CommonUtils commonUtils;
public void sendActivateMail(String receiveMailAccount, String nickName, String randomCode) throws MessagingException {
StringBuffer content = new StringBuffer();
content.append("<b>您已在本系统成功注册账号<br>昵称为:").append(nickName).append("<br><br>")
.append("现在<a href='").append(url).append(randomCode).append("'>点击这里激活账号</a>即可开始使用!")
.append("</b><br>如非本人操作,请忽略本邮件。");
mailSettings(senderName, themeActivate, receiveMailAccount, nickName, content.toString());
}
public void sendPaperStartMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException {
StringBuffer content = new StringBuffer();
content.append("<b>尊敬的").append(nickName).append("<br><br>")
.append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime()))
.append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经可以正式答卷了,快点分享出去吧!<br><br>")
.append("现在<a href='").append(paperUrl).append(paper.getId()).append("'>点击这里</a>即可查看问卷详情!</b>")
.append("<br><br>使用提示:打开链接后可复制问卷链接或直接分享给他人,亦可<a href='").append(homeUrl).append("'>登录账号</a>查看更多信息。");
mailSettings(senderName, themePaperStart, receiveMailAccount, nickName, content.toString());
}
public void sendPaperEndMail(String receiveMailAccount, String nickName, Paper paper) throws MessagingException {
StringBuffer content = new StringBuffer();
content.append("<b>尊敬的").append(nickName).append("<br><br>")
.append("您于").append(commonUtils.getFormatDateTime(paper.getCreateTime()))
.append("创建的标题为“").append(paper.getTitle()).append("”的问卷,已经结束了!<br><br>")
.append("现在<a href='").append(homeUrl).append(paper.getId()).append("'>登录账号</a>即可查看问卷数据详情!</b>")
.append("<br><br>使用提示:为便于显示请使用电脑查看。");
mailSettings(senderName, themePaperEnd, receiveMailAccount, nickName, content.toString());
}
//(session, myEmailAccount, receiveMailAccount, "发件人名字","收件人名字","同志","标题","内容:2943<a href='http://www.baidu.com'>Baidu</a>");
public void mailSettings(String senderName, String theme, String receiveMailAccount,
String nickName, String content) throws MessagingException {
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
// PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
// 如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
// 打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
// 需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
// QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
final String smtpPort = "465";
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getDefaultInstance(props);
session.setDebug(false); // 设置为debug模式, 可以查看详细的发送 log
// 3. 创建一封邮件,
// Session session, String sendMail,String receiveMail, String sender, String recipients, String theme, String content
//session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,邮件标题,邮件内容
MimeMessage message = null;
try {
message = createMimeMessage(session, myEmailAccount, receiveMailAccount,
senderName, nickName, theme, content);
} catch (Exception e) {
e.printStackTrace();
}
//发第二条
/*receiveMailAccount = "[email protected]";
MimeMessage message2 = createMimeMessage(session, myEmailAccount, receiveMailAccount,
"发件人名字","收件人名字","标题","内容:134");
*/
// 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());
//transport.sendMessage(message2, message2.getAllRecipients());
// 7. <SUF>
transport.close();
}
/**
* 创建一封只包含文本的简单邮件
*
* @param session 和服务器交互的会话
* @param senderMailAccount 发件人邮箱
* @param receiverMailAccount 收件人邮箱
* @return
* @throws Exception
*/
//session,发件人邮箱,收件人邮箱,发件人名字,收件人名字,称呼(例:***同学,老师等),邮件标题,邮件内容
public MimeMessage createMimeMessage(
Session session, String senderMailAccount, String receiverMailAccount, String senderName, String receiverName,
String theme, String content) throws Exception {
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(senderMailAccount, senderName, "UTF-8"));
// 3. To: 收件人(可以增加多个收件人、抄送、密送)
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiverMailAccount, receiverName, "UTF-8"));
// 4. Subject: 邮件主题
message.setSubject(theme, "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
message.setContent(content, "text/html;charset=UTF-8");
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}
}
| 1 | 10 | 1 |
22711_1 | package android.study.leer.coolweather.util;
import java.util.Random;
/**
* Created by Leer on 2017/6/26.
*/
public class DayWords {
//注意种子数和生成随机数的区间无关
private static Random mRandom = new Random();
private static String[] mDayWords = new String[]{
"聪明人是快乐的,自以为聪明的才烦恼。帮助别人减轻三分烦恼,自己就会享受七分快乐",
"每个人都有潜在的能量,只是很容易被习惯所掩盖,被时间所迷离,被惰性所消磨",
"有理想在的地方,地狱就是天堂。有希望在的地方,痛苦也成欢乐",
"不要对挫折叹气,姑且把这一切看成是在你成大事之前,必须经受的准备工作",
"河流之所以能够到达目的地,是因为它懂得怎样避开障碍",
"一个成功的竞争者应该经得起风雨,应该具有抗挫折的能力。在竞争中流泪是弱者,只有在困境中奋起,才能成为强者",
"成功沒有捷径,历史上有成就的人,总是敢于行动,也会经常失败。不要让对失败的恐惧,绊住你尝试新事物的脚步",
"学会理解,因为只有理解别人,才会被别人理解",
"学会忘记,因为只有忘记已经失去的才能立足当前,展望未来",
"学会快乐,因为只有开心度过每一天,活得才精彩"
};
public static String getDayWord() {
int index = mRandom.nextInt(10);
if (index < 0) {
index = 0;
} else if (index > mDayWords.length - 1) {
index = mDayWords.length-1;
}
return mDayWords[index];
}
}
| BlueLeer/XiaoTianQi | app/src/main/java/android/study/leer/coolweather/util/DayWords.java | 526 | //注意种子数和生成随机数的区间无关 | line_comment | zh-cn | package android.study.leer.coolweather.util;
import java.util.Random;
/**
* Created by Leer on 2017/6/26.
*/
public class DayWords {
//注意 <SUF>
private static Random mRandom = new Random();
private static String[] mDayWords = new String[]{
"聪明人是快乐的,自以为聪明的才烦恼。帮助别人减轻三分烦恼,自己就会享受七分快乐",
"每个人都有潜在的能量,只是很容易被习惯所掩盖,被时间所迷离,被惰性所消磨",
"有理想在的地方,地狱就是天堂。有希望在的地方,痛苦也成欢乐",
"不要对挫折叹气,姑且把这一切看成是在你成大事之前,必须经受的准备工作",
"河流之所以能够到达目的地,是因为它懂得怎样避开障碍",
"一个成功的竞争者应该经得起风雨,应该具有抗挫折的能力。在竞争中流泪是弱者,只有在困境中奋起,才能成为强者",
"成功沒有捷径,历史上有成就的人,总是敢于行动,也会经常失败。不要让对失败的恐惧,绊住你尝试新事物的脚步",
"学会理解,因为只有理解别人,才会被别人理解",
"学会忘记,因为只有忘记已经失去的才能立足当前,展望未来",
"学会快乐,因为只有开心度过每一天,活得才精彩"
};
public static String getDayWord() {
int index = mRandom.nextInt(10);
if (index < 0) {
index = 0;
} else if (index > mDayWords.length - 1) {
index = mDayWords.length-1;
}
return mDayWords[index];
}
}
| 1 | 18 | 1 |
64482_5 | /**
* 设置游戏难度及开始新游戏
*/
package Controller;
import Model.Sudoku;
import View.*;
public class Game {
private static Window window;
public static Sudoku sudoku;
// 游戏难度,设定一个 0 ~ 1 之间的小数,表示初始数独的完成度
// 程序保证所有数独一定有至少一个正确答案
// 完成度越高游戏越简单,对计算机性能要求越高,建议设置最高 0.45
private static double percent = 0.36;
// 创建游戏
private Game() {
GameTimer.init();
sudoku = new Sudoku(percent);
window = new Window();
}
// 新游戏
public static void next() {
GameTimer.init();
sudoku.next();
window.next();
}
// 游戏答案
public static void solve() {
sudoku.solve(0);
window.stop();
}
// 获取游戏时间
public static String getTime() {
String gameTime = GameTimer.getTime();
GameTimer.updateTime();
return gameTime;
}
public static void main(String[] args) {
new Game();
}
}
| BlueSky-07/Sudoku-Java-Swing-Game | Controller/Game.java | 282 | // 新游戏 | line_comment | zh-cn | /**
* 设置游戏难度及开始新游戏
*/
package Controller;
import Model.Sudoku;
import View.*;
public class Game {
private static Window window;
public static Sudoku sudoku;
// 游戏难度,设定一个 0 ~ 1 之间的小数,表示初始数独的完成度
// 程序保证所有数独一定有至少一个正确答案
// 完成度越高游戏越简单,对计算机性能要求越高,建议设置最高 0.45
private static double percent = 0.36;
// 创建游戏
private Game() {
GameTimer.init();
sudoku = new Sudoku(percent);
window = new Window();
}
// 新游 <SUF>
public static void next() {
GameTimer.init();
sudoku.next();
window.next();
}
// 游戏答案
public static void solve() {
sudoku.solve(0);
window.stop();
}
// 获取游戏时间
public static String getTime() {
String gameTime = GameTimer.getTime();
GameTimer.updateTime();
return gameTime;
}
public static void main(String[] args) {
new Game();
}
}
| 1 | 6 | 1 |
53951_9 | /*
输出信息到控制台
System.out.println(...);
在Java中怎么接收键盘的输入?
以下代码目前看不懂,在学习面向对象之后才能够理解
*/
public class KeyInput{
public static void main(String[] args){
//创建一个键盘扫描器对象
java.util.Scanner s = new java.util.Scanner(System.in);//s是变量名,可以修改,其他不能修改
//接受用户的输入,从键盘上接收一个int类型
int userInputNum = s.nextInt();//代码执行到这里的时候会暂停下来
//等待用户的输入,用户可以从键盘上输入一个整数,然后回车,回车之后变量userInputnum就有值了,
//保存的是用户输入的数字.userInputnum的作用就是接受用户的输入的
System.out.println("您输入的数字是:" + userInputNum);
//从键盘上接受字符串
String str = s.next();//同样,程序运行到此处会停下来,等待用户输入字符串
System.out.println("您输入了:" + str);
//更加完整的
System.out.print("请输入用户名:");
String name = s.next();
System.out.println("欢迎" + name + "回来!");
}
} | Bluuur/MarkdownNotes | Java/JavaSECode/HomeWork/src/KeyInput.java | 320 | //更加完整的 | line_comment | zh-cn | /*
输出信息到控制台
System.out.println(...);
在Java中怎么接收键盘的输入?
以下代码目前看不懂,在学习面向对象之后才能够理解
*/
public class KeyInput{
public static void main(String[] args){
//创建一个键盘扫描器对象
java.util.Scanner s = new java.util.Scanner(System.in);//s是变量名,可以修改,其他不能修改
//接受用户的输入,从键盘上接收一个int类型
int userInputNum = s.nextInt();//代码执行到这里的时候会暂停下来
//等待用户的输入,用户可以从键盘上输入一个整数,然后回车,回车之后变量userInputnum就有值了,
//保存的是用户输入的数字.userInputnum的作用就是接受用户的输入的
System.out.println("您输入的数字是:" + userInputNum);
//从键盘上接受字符串
String str = s.next();//同样,程序运行到此处会停下来,等待用户输入字符串
System.out.println("您输入了:" + str);
//更加 <SUF>
System.out.print("请输入用户名:");
String name = s.next();
System.out.println("欢迎" + name + "回来!");
}
} | 1 | 7 | 1 |