file_id
stringlengths 5
9
| content
stringlengths 24
16.1k
| repo
stringlengths 8
84
| path
stringlengths 7
167
| token_length
int64 18
3.48k
| original_comment
stringlengths 5
2.57k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 11
16.1k
| excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 14
3.27k
| comment-tokens-Qwen/Qwen2-7B
int64 2
1.74k
| file-tokens-bigcode/starcoder2-7b
int64 18
3.48k
| comment-tokens-bigcode/starcoder2-7b
int64 2
2.11k
| file-tokens-google/codegemma-7b
int64 14
3.57k
| comment-tokens-google/codegemma-7b
int64 2
1.75k
| file-tokens-ibm-granite/granite-8b-code-base
int64 18
3.48k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 2
2.11k
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 31
3.93k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
2.71k
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
49686_27 | package protocol;
import timer.TimeModel;
import timer.Timer;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.SocketTimeoutException;
import java.util.HashSet;
import java.util.Set;
/**
* 模拟一个运行SR协议个主机。
*/
public class SRHost extends MyHost {
private boolean isSending = false;
private boolean isReceiving = false;
/*SR协议相关*/
/**
* 作为发送方时发送过的分组。
*/
private Set<Integer> senderSentSet = new HashSet<>();
/**
* 作为发送方时收到的ACK。
*/
private Set<Integer> senderReceivedACKSet = new HashSet<>();
/**
* 作为接收方时收到的分组,用来作为缓存。
*/
private Set<Integer> receiverReceivedSet = new HashSet<>();
public SRHost(int RECEIVE_PORT, int WINDOW_SIZE, int DATA_NUMBER, int TIMEOUT, String name) throws IOException {
super(RECEIVE_PORT, WINDOW_SIZE, DATA_NUMBER, TIMEOUT, name);
}
/**
* 将这个实例作为SR协议的发送端开始发送数据。
* @throws IOException IO相关异常发生时抛出
*/
@Override
public void sendData() throws IOException {
this.isSending = true;
TimeModel timeModel = new TimeModel();
Timer timer = new Timer(this, timeModel);
timeModel.setTime(0);
timer.start();
while (isSending) {
// 发送分组循环
while (nextSeq < base + WINDOW_SIZE && nextSeq <= DATA_NUMBER && !senderSentSet.contains(nextSeq)) {
// 模拟数据丢失
if (nextSeq % 5 != 0) {
// 不丢失
String sendData = hostName + ": Sending to port " + destPort + ", Seq = " + nextSeq;
// 模拟发送分组
byte[] data = sendData.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(data, data.length, destAddress, destPort);
sendSocket.send(datagramPacket);
System.out.println(hostName + "发送到" + destPort + "端口, Seq = " + nextSeq);
} else {
// 丢失
System.out.println("假装丢失Seq = " + nextSeq);
}
senderSentSet.add(nextSeq); // 加入已发送set
if (nextSeq == base) {
// 开始计时,等待接收端返回ACK
timeModel.setTime(TIMEOUT);
}
nextSeq++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 接收ACK
// 从服务器端接受ACK
byte[] bytes = new byte[4096];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
sendSocket.setSoTimeout(4000);
try {
sendSocket.receive(datagramPacket);
} catch (SocketTimeoutException ex) {
// timeout 因为对方未回应任何数据
System.out.println(hostName + "等待ACK超时");
nextSeq--; // 让它重新进入上面的循环里
senderSentSet.remove(nextSeq);
continue;
}
// 转换成String
String fromServer = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
// 解析出ACK编号
int ack = Integer.parseInt(fromServer.substring(fromServer.indexOf("ACK: ") + 5).trim());
senderReceivedACKSet.add(ack); // 加入已收到set
if (base == ack) {
// 向右滑动
while (senderReceivedACKSet.contains(base)) {
base++;
}
System.out.println("\n当前窗口 base = " + base + ",最大发送到 " + (base + WINDOW_SIZE - 1) + " \n");
}
if (ack >= base + WINDOW_SIZE) {
// 理论上一定false
assert false;
}
if (base == nextSeq) {
// 停止计时器
timeModel.setTime(0);
} else {
// 开始计时器
timeModel.setTime(TIMEOUT);
}
System.out.println(hostName + "收到了 ACK: " + ack);
// System.out.println(hostName + "当前base = " + base);
System.out.println();
// 发送完了,此时base会滑到右边多一格
if (base == DATA_NUMBER + 1) {
// 停止计时器
timeModel.setTime(0);
System.out.println(hostName + "发送完毕,接收方反馈已全部正确接收");
this.isSending = false;
System.exit(0);
}
}
}
@Override
public void timeOut() throws IOException {
Set<Integer> temp = new HashSet<>(senderSentSet);
temp.removeAll(senderReceivedACKSet);
System.out.println("\n" + temp + "\n");
for (int i : temp) {
String resendData = hostName
+ ": Resending to port " + destPort + ", Seq = " + i;
byte[] data = resendData.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(data,
data.length, destAddress, destPort);
sendSocket.send(datagramPacket);
System.out.println(hostName
+ "重新发送发送到" + destPort + "端口, Seq = " + i);
break; // 只发一次就break
}
}
@Override
public void receive() throws IOException {
this.isReceiving = true;
int rcvBase = 1;
while (isReceiving) {
byte[] receivedData = new byte[4096];
DatagramPacket receivePacket = new DatagramPacket(receivedData, receivedData.length);
receiveSocket.setSoTimeout(5000);
try {
receiveSocket.receive(receivePacket);
} catch (SocketTimeoutException ex) {
System.out.println(hostName + " 等待下一个分组超时");
continue;
}
// 收到的数据
String received = new String(receivedData, 0, receivePacket.getLength());
int seqIndex = received.indexOf("Seq = ");
if (seqIndex == -1) {
System.out.println(hostName + " 收到错误数据");
// 仍发送之前的ACK
sendACK(expectedSeq - 1, receivePacket.getAddress(), receivePacket.getPort());
} else {
int seq = Integer.parseInt(received.substring(seqIndex + 6).trim());
if (seq >= rcvBase && seq <= rcvBase + WINDOW_SIZE - 1) {
receiverReceivedSet.add(seq);
System.out.println(hostName + "收到一个窗口内的分组,Seq = " + seq + "已确认\n");
// 模拟ACK丢失。
// 用seq mod一个数,不发送ACK来模拟,其他操作正常进行
if (seq % 17 != 0) {
// 发送ACK
sendACK(seq, receivePacket.getAddress(), receivePacket.getPort());
} else {
System.out.println(hostName + "假装丢失ACK: " + seq);
}
if (seq == rcvBase) {
// 收到这个分组后可以开始滑动
while (receiverReceivedSet.contains(rcvBase)) {
rcvBase++;
}
}
} else if (seq >= rcvBase - WINDOW_SIZE && seq <= rcvBase - 1) {
System.out.println(hostName + "收到一个已经确认过的分组,Seq = " + seq + "已再次确认");
sendACK(seq, receivePacket.getAddress(), receivePacket.getPort());
} else {
// 这个分组序列号太大,不在窗口内,应该舍弃
System.out.println(hostName + "收到一个不在窗口内的分组,Seq = " + seq + "已舍弃");
}
}
}
}
@Override
public void stopHost() {
this.isSending = false;
this.isReceiving = false;
}
}
| NormanZyq/Computer-Networking-Labs | lab2+3/src/protocol/SRHost.java | 1,929 | // 收到的数据 | line_comment | zh-cn | package protocol;
import timer.TimeModel;
import timer.Timer;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.SocketTimeoutException;
import java.util.HashSet;
import java.util.Set;
/**
* 模拟一个运行SR协议个主机。
*/
public class SRHost extends MyHost {
private boolean isSending = false;
private boolean isReceiving = false;
/*SR协议相关*/
/**
* 作为发送方时发送过的分组。
*/
private Set<Integer> senderSentSet = new HashSet<>();
/**
* 作为发送方时收到的ACK。
*/
private Set<Integer> senderReceivedACKSet = new HashSet<>();
/**
* 作为接收方时收到的分组,用来作为缓存。
*/
private Set<Integer> receiverReceivedSet = new HashSet<>();
public SRHost(int RECEIVE_PORT, int WINDOW_SIZE, int DATA_NUMBER, int TIMEOUT, String name) throws IOException {
super(RECEIVE_PORT, WINDOW_SIZE, DATA_NUMBER, TIMEOUT, name);
}
/**
* 将这个实例作为SR协议的发送端开始发送数据。
* @throws IOException IO相关异常发生时抛出
*/
@Override
public void sendData() throws IOException {
this.isSending = true;
TimeModel timeModel = new TimeModel();
Timer timer = new Timer(this, timeModel);
timeModel.setTime(0);
timer.start();
while (isSending) {
// 发送分组循环
while (nextSeq < base + WINDOW_SIZE && nextSeq <= DATA_NUMBER && !senderSentSet.contains(nextSeq)) {
// 模拟数据丢失
if (nextSeq % 5 != 0) {
// 不丢失
String sendData = hostName + ": Sending to port " + destPort + ", Seq = " + nextSeq;
// 模拟发送分组
byte[] data = sendData.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(data, data.length, destAddress, destPort);
sendSocket.send(datagramPacket);
System.out.println(hostName + "发送到" + destPort + "端口, Seq = " + nextSeq);
} else {
// 丢失
System.out.println("假装丢失Seq = " + nextSeq);
}
senderSentSet.add(nextSeq); // 加入已发送set
if (nextSeq == base) {
// 开始计时,等待接收端返回ACK
timeModel.setTime(TIMEOUT);
}
nextSeq++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 接收ACK
// 从服务器端接受ACK
byte[] bytes = new byte[4096];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
sendSocket.setSoTimeout(4000);
try {
sendSocket.receive(datagramPacket);
} catch (SocketTimeoutException ex) {
// timeout 因为对方未回应任何数据
System.out.println(hostName + "等待ACK超时");
nextSeq--; // 让它重新进入上面的循环里
senderSentSet.remove(nextSeq);
continue;
}
// 转换成String
String fromServer = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
// 解析出ACK编号
int ack = Integer.parseInt(fromServer.substring(fromServer.indexOf("ACK: ") + 5).trim());
senderReceivedACKSet.add(ack); // 加入已收到set
if (base == ack) {
// 向右滑动
while (senderReceivedACKSet.contains(base)) {
base++;
}
System.out.println("\n当前窗口 base = " + base + ",最大发送到 " + (base + WINDOW_SIZE - 1) + " \n");
}
if (ack >= base + WINDOW_SIZE) {
// 理论上一定false
assert false;
}
if (base == nextSeq) {
// 停止计时器
timeModel.setTime(0);
} else {
// 开始计时器
timeModel.setTime(TIMEOUT);
}
System.out.println(hostName + "收到了 ACK: " + ack);
// System.out.println(hostName + "当前base = " + base);
System.out.println();
// 发送完了,此时base会滑到右边多一格
if (base == DATA_NUMBER + 1) {
// 停止计时器
timeModel.setTime(0);
System.out.println(hostName + "发送完毕,接收方反馈已全部正确接收");
this.isSending = false;
System.exit(0);
}
}
}
@Override
public void timeOut() throws IOException {
Set<Integer> temp = new HashSet<>(senderSentSet);
temp.removeAll(senderReceivedACKSet);
System.out.println("\n" + temp + "\n");
for (int i : temp) {
String resendData = hostName
+ ": Resending to port " + destPort + ", Seq = " + i;
byte[] data = resendData.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(data,
data.length, destAddress, destPort);
sendSocket.send(datagramPacket);
System.out.println(hostName
+ "重新发送发送到" + destPort + "端口, Seq = " + i);
break; // 只发一次就break
}
}
@Override
public void receive() throws IOException {
this.isReceiving = true;
int rcvBase = 1;
while (isReceiving) {
byte[] receivedData = new byte[4096];
DatagramPacket receivePacket = new DatagramPacket(receivedData, receivedData.length);
receiveSocket.setSoTimeout(5000);
try {
receiveSocket.receive(receivePacket);
} catch (SocketTimeoutException ex) {
System.out.println(hostName + " 等待下一个分组超时");
continue;
}
// 收到 <SUF>
String received = new String(receivedData, 0, receivePacket.getLength());
int seqIndex = received.indexOf("Seq = ");
if (seqIndex == -1) {
System.out.println(hostName + " 收到错误数据");
// 仍发送之前的ACK
sendACK(expectedSeq - 1, receivePacket.getAddress(), receivePacket.getPort());
} else {
int seq = Integer.parseInt(received.substring(seqIndex + 6).trim());
if (seq >= rcvBase && seq <= rcvBase + WINDOW_SIZE - 1) {
receiverReceivedSet.add(seq);
System.out.println(hostName + "收到一个窗口内的分组,Seq = " + seq + "已确认\n");
// 模拟ACK丢失。
// 用seq mod一个数,不发送ACK来模拟,其他操作正常进行
if (seq % 17 != 0) {
// 发送ACK
sendACK(seq, receivePacket.getAddress(), receivePacket.getPort());
} else {
System.out.println(hostName + "假装丢失ACK: " + seq);
}
if (seq == rcvBase) {
// 收到这个分组后可以开始滑动
while (receiverReceivedSet.contains(rcvBase)) {
rcvBase++;
}
}
} else if (seq >= rcvBase - WINDOW_SIZE && seq <= rcvBase - 1) {
System.out.println(hostName + "收到一个已经确认过的分组,Seq = " + seq + "已再次确认");
sendACK(seq, receivePacket.getAddress(), receivePacket.getPort());
} else {
// 这个分组序列号太大,不在窗口内,应该舍弃
System.out.println(hostName + "收到一个不在窗口内的分组,Seq = " + seq + "已舍弃");
}
}
}
}
@Override
public void stopHost() {
this.isSending = false;
this.isReceiving = false;
}
}
| false | 1,769 | 5 | 1,929 | 5 | 2,010 | 4 | 1,929 | 5 | 2,501 | 7 | false | false | false | false | false | true |
37991_2 | package com.business;
/**
* 汽车(即硬件设备)信息
* 对应数据库中的vehicle数据表
* 注释带星号*的表示在数据库中有对应字段
*/
public class Vehicle {
private int id; // 数据库自增id *
private String number; // 硬件设备唯一标识编号 *
private String brand; // 汽车品牌 *
private String model; // 汽车型号 *
private String plate; // 车牌号码 *
private int userId; // 管理员用户id *
private double longitude; // 经度 *
private double latitude; // 纬度 *
private String date; // 硬件设备投入使用的日期 *
private double direction; // 行驶方向 *
private double speed; // 行驶速度 *
private double temperature; // 温度 *
private double humidity; // 湿度 *
private double voltage; // 电压 *
private double current; // 电流 *
private String updateDate; // 更新时间 *
public String getUserPhone() {
return Database.findUser(Integer.toString(userId)).getPhone();
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getDirection() {
return direction;
}
public void setDirection(double direction) {
this.direction = direction;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public double getHumidity() {
return humidity;
}
public void setHumidity(double humidity) {
this.humidity = humidity;
}
public double getVoltage() {
return voltage;
}
public void setVoltage(double voltage) {
this.voltage = voltage;
}
public double getCurrent() {
return current;
}
public void setCurrent(double current) {
this.current = current;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| NorwegianForest/BatteryServer | src/com/business/Vehicle.java | 786 | // 硬件设备唯一标识编号 * | line_comment | zh-cn | package com.business;
/**
* 汽车(即硬件设备)信息
* 对应数据库中的vehicle数据表
* 注释带星号*的表示在数据库中有对应字段
*/
public class Vehicle {
private int id; // 数据库自增id *
private String number; // 硬件 <SUF>
private String brand; // 汽车品牌 *
private String model; // 汽车型号 *
private String plate; // 车牌号码 *
private int userId; // 管理员用户id *
private double longitude; // 经度 *
private double latitude; // 纬度 *
private String date; // 硬件设备投入使用的日期 *
private double direction; // 行驶方向 *
private double speed; // 行驶速度 *
private double temperature; // 温度 *
private double humidity; // 湿度 *
private double voltage; // 电压 *
private double current; // 电流 *
private String updateDate; // 更新时间 *
public String getUserPhone() {
return Database.findUser(Integer.toString(userId)).getPhone();
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getDirection() {
return direction;
}
public void setDirection(double direction) {
this.direction = direction;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public double getHumidity() {
return humidity;
}
public void setHumidity(double humidity) {
this.humidity = humidity;
}
public double getVoltage() {
return voltage;
}
public void setVoltage(double voltage) {
this.voltage = voltage;
}
public double getCurrent() {
return current;
}
public void setCurrent(double current) {
this.current = current;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| false | 735 | 10 | 786 | 9 | 856 | 8 | 786 | 9 | 1,062 | 21 | false | false | false | false | false | true |
44417_1 | package com.business;
import com.DBQuery.DataProcess;
import java.util.ArrayList;
import java.util.List;
/**
* 描述一章学习资料,对应数据库中的materials表
*/
public class Material {
private int number; // 序号
private String title; // 标题
private String fileName; // 对应的文件名
public Material(String title, String fileName) {
this.title = title;
this.fileName = fileName;
}
public static List<Material> getFiveMaterialList() {
List<Material> materialList = new ArrayList<>();
String sql = "select * from materials limit 5";
DataProcess.loadMaterialList(sql, materialList);
return materialList;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
| NorwegianForest/CHelp | src/com/business/Material.java | 268 | // 对应的文件名 | line_comment | zh-cn | package com.business;
import com.DBQuery.DataProcess;
import java.util.ArrayList;
import java.util.List;
/**
* 描述一章学习资料,对应数据库中的materials表
*/
public class Material {
private int number; // 序号
private String title; // 标题
private String fileName; // 对应 <SUF>
public Material(String title, String fileName) {
this.title = title;
this.fileName = fileName;
}
public static List<Material> getFiveMaterialList() {
List<Material> materialList = new ArrayList<>();
String sql = "select * from materials limit 5";
DataProcess.loadMaterialList(sql, materialList);
return materialList;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
| false | 241 | 6 | 268 | 5 | 288 | 4 | 268 | 5 | 329 | 8 | false | false | false | false | false | true |
50139_6 | package com.hasee.minibuslocalhost.transmit.Class;
import com.hasee.minibuslocalhost.util.ByteUtil;
import com.hasee.minibuslocalhost.util.LogUtil;
import java.util.HashMap;
import java.util.Map;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_Alam;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_DangerAlarm;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_Demister_Control;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_DoorLock;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_Driver_model;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_FANPWM_Control;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_HighBeam;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_LeftTurningLamp;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_LowBeam;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_RearFogLamp;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_RightTurningLamp;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_SystemRuningStatus;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_TotalOdmeter;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_air_grade;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_air_model;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_eBooster_Warning;
import static com.hasee.minibuslocalhost.util.ByteUtil.setBits;
public class HMI extends BaseClass {
private final static String TAG = "HMI";
private final static int offset = 4;
// status
// 灯光和门
public static final int POINTLESS = 0; // 无意义
public static final int OFF = 1; // 关
public static final int ON = 2; // 开
// 驾驶控制
public static final int DRIVE_MODEL_AUTO = 0; // 自动
public static final int DRIVE_MODEL_REMOTE = 1; // 远程
public static final int DRIVE_MODEL_AUTO_AWAIT = 2; // 待定
// 低速报警
public static final int Ord_Alam_POINTLESS = 0; // 无输入
public static final int Ord_Alam_OFF = 1; // 不报警
public static final int Ord_Alam_ON = 2; // 报警
// 空调
public static final int AIR_MODEL_COOL = 0; // 制冷
public static final int AIR_MODEL_HEAT = 1; // 制热
public static final int AIR_MODEL_DEMIST = 2; // 除雾
public static final int AIR_MODEL_AWAIT = 2; // 待定
public static final int AIR_GRADE_OFF = 0; // 关闭
public static final int AIR_GRADE_FIRST_GEAR = 1; // 1挡
public static final int AIR_GRADE_SECOND_GEAR = 2; // 2挡
public static final int AIR_GRADE_THIRD_GEAR = 3; // 3挡
public static final int AIR_GRADE_FOURTH_GEAR = 4; // 4挡
public static final int AIR_GRADE_FIVE_GEAR = 5; // 5挡
public static final int AIR_GRADE_SIX_GEAR = 6; // 无输入
// 制动液面报警
public static final int eBooster_Warning_ON = 1; // 报警
public static final int eBooster_Warning_OFF = 0; // 正常
// HMI控制器运行状态
public static final int Ord_SystemRuningStatus_ONINPUT = 0; // 无输入
public static final int Ord_SystemRuningStatus_NORMAL = 1; // 正常
public static final int Ord_SystemRuningStatus_ERROR = 2; // 故障
public static final int Ord_SystemRuningStatus_AWAIT = 3; // 预留
//
private Map<String, ? super BaseClass> NAME_AND_CLASS;
public HMI() {
}
public void setNAME_AND_CLASS(Map<String, ? super BaseClass> NAME_AND_CLASS) {
this.NAME_AND_CLASS = NAME_AND_CLASS;
}
private byte[] bytes = {(byte) 0xFF, (byte) 0xAA, 0x03, (byte) 0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02};
public void changeStatus(int command, Object status) {
switch (command) {
case HMI_Dig_Ord_HighBeam:
setBits(bytes, (int) status, offset, 0, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 2, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 4, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 5, false);
break;
case HMI_Dig_Ord_LowBeam:
setBits(bytes, (int) status, offset, 2, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 0, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 5, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 4, false);
break;
case HMI_Dig_Ord_LeftTurningLamp:
setBits(bytes, (int) status, offset, 4, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 6, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 1, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 2, false);
break;
case HMI_Dig_Ord_RightTurningLamp:
setBits(bytes, (int) status, offset, 6, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 4, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 2, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 1, false);
break;
case HMI_Dig_Ord_RearFogLamp:
setBits(bytes, (int) status, offset, 8, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 6, (int) status == ON);
break;
case HMI_Dig_Ord_DoorLock:
setBits(bytes, (int) status, offset, 10, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_Alam:
setBits(bytes, (int) status, offset, 12, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_Driver_model:
setBits(bytes, (int) status, offset, 14, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_air_model:
setBits(bytes, (int) status, offset, 16, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_air_grade:
setBits(bytes, (int) status, offset, 18, 3, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_eBooster_Warning:
setBits(bytes, (int) status, offset, 21, 1, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_DangerAlarm:
setBits(bytes, (int) status, offset, 22, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 7, (int) status == ON);
break;
case HMI_Dig_Ord_FANPWM_Control:
setBits(bytes, (int) status, offset, 24, 8, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_Demister_Control:
setBits(bytes, (int) status, offset, 38, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_TotalOdmeter:
setBits(bytes, (int) status, offset, 48, 20, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_SystemRuningStatus:
setBits(bytes, (int) status, offset, 36, 2, ByteUtil.Motorola);
break;
default:
LogUtil.d(TAG, "消息转换错误");
break;
}
}
@Override
public int getState() {
return ByteUtil.Motorola;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public String getTAG() {
return TAG;
}
@Override
public Object getValue(Map.Entry<Integer, MyPair<Integer>> entry, byte[] bytes) {
return null;
}
@Override
public HashMap<Integer, MyPair<Integer>> getFields() {
return null;
}
}
| NorwinYu/UoN-Final-Year-Project-Public-Database | Download-Java-Files/Defective/i-20-c-5-HMI.java | 2,580 | // 不报警 | line_comment | zh-cn | package com.hasee.minibuslocalhost.transmit.Class;
import com.hasee.minibuslocalhost.util.ByteUtil;
import com.hasee.minibuslocalhost.util.LogUtil;
import java.util.HashMap;
import java.util.Map;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_Alam;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_DangerAlarm;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_Demister_Control;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_DoorLock;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_Driver_model;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_FANPWM_Control;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_HighBeam;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_LeftTurningLamp;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_LowBeam;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_RearFogLamp;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_RightTurningLamp;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_SystemRuningStatus;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_TotalOdmeter;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_air_grade;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_air_model;
import static com.hasee.minibuslocalhost.bean.IntegerCommand.HMI_Dig_Ord_eBooster_Warning;
import static com.hasee.minibuslocalhost.util.ByteUtil.setBits;
public class HMI extends BaseClass {
private final static String TAG = "HMI";
private final static int offset = 4;
// status
// 灯光和门
public static final int POINTLESS = 0; // 无意义
public static final int OFF = 1; // 关
public static final int ON = 2; // 开
// 驾驶控制
public static final int DRIVE_MODEL_AUTO = 0; // 自动
public static final int DRIVE_MODEL_REMOTE = 1; // 远程
public static final int DRIVE_MODEL_AUTO_AWAIT = 2; // 待定
// 低速报警
public static final int Ord_Alam_POINTLESS = 0; // 无输入
public static final int Ord_Alam_OFF = 1; // 不报 <SUF>
public static final int Ord_Alam_ON = 2; // 报警
// 空调
public static final int AIR_MODEL_COOL = 0; // 制冷
public static final int AIR_MODEL_HEAT = 1; // 制热
public static final int AIR_MODEL_DEMIST = 2; // 除雾
public static final int AIR_MODEL_AWAIT = 2; // 待定
public static final int AIR_GRADE_OFF = 0; // 关闭
public static final int AIR_GRADE_FIRST_GEAR = 1; // 1挡
public static final int AIR_GRADE_SECOND_GEAR = 2; // 2挡
public static final int AIR_GRADE_THIRD_GEAR = 3; // 3挡
public static final int AIR_GRADE_FOURTH_GEAR = 4; // 4挡
public static final int AIR_GRADE_FIVE_GEAR = 5; // 5挡
public static final int AIR_GRADE_SIX_GEAR = 6; // 无输入
// 制动液面报警
public static final int eBooster_Warning_ON = 1; // 报警
public static final int eBooster_Warning_OFF = 0; // 正常
// HMI控制器运行状态
public static final int Ord_SystemRuningStatus_ONINPUT = 0; // 无输入
public static final int Ord_SystemRuningStatus_NORMAL = 1; // 正常
public static final int Ord_SystemRuningStatus_ERROR = 2; // 故障
public static final int Ord_SystemRuningStatus_AWAIT = 3; // 预留
//
private Map<String, ? super BaseClass> NAME_AND_CLASS;
public HMI() {
}
public void setNAME_AND_CLASS(Map<String, ? super BaseClass> NAME_AND_CLASS) {
this.NAME_AND_CLASS = NAME_AND_CLASS;
}
private byte[] bytes = {(byte) 0xFF, (byte) 0xAA, 0x03, (byte) 0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02};
public void changeStatus(int command, Object status) {
switch (command) {
case HMI_Dig_Ord_HighBeam:
setBits(bytes, (int) status, offset, 0, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 2, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 4, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 5, false);
break;
case HMI_Dig_Ord_LowBeam:
setBits(bytes, (int) status, offset, 2, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 0, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 5, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 4, false);
break;
case HMI_Dig_Ord_LeftTurningLamp:
setBits(bytes, (int) status, offset, 4, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 6, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 1, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 2, false);
break;
case HMI_Dig_Ord_RightTurningLamp:
setBits(bytes, (int) status, offset, 6, 2, ByteUtil.Motorola);
if ((int) status != POINTLESS)
setBits(bytes, OFF, offset, 4, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 2, (int) status == ON);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 1, false);
break;
case HMI_Dig_Ord_RearFogLamp:
setBits(bytes, (int) status, offset, 8, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 6, (int) status == ON);
break;
case HMI_Dig_Ord_DoorLock:
setBits(bytes, (int) status, offset, 10, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_Alam:
setBits(bytes, (int) status, offset, 12, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_Driver_model:
setBits(bytes, (int) status, offset, 14, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_air_model:
setBits(bytes, (int) status, offset, 16, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_air_grade:
setBits(bytes, (int) status, offset, 18, 3, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_eBooster_Warning:
setBits(bytes, (int) status, offset, 21, 1, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_DangerAlarm:
setBits(bytes, (int) status, offset, 22, 2, ByteUtil.Motorola);
// ((BCM1) NAME_AND_CLASS.get("BCM1")).setBytes(0, 7, (int) status == ON);
break;
case HMI_Dig_Ord_FANPWM_Control:
setBits(bytes, (int) status, offset, 24, 8, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_Demister_Control:
setBits(bytes, (int) status, offset, 38, 2, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_TotalOdmeter:
setBits(bytes, (int) status, offset, 48, 20, ByteUtil.Motorola);
break;
case HMI_Dig_Ord_SystemRuningStatus:
setBits(bytes, (int) status, offset, 36, 2, ByteUtil.Motorola);
break;
default:
LogUtil.d(TAG, "消息转换错误");
break;
}
}
@Override
public int getState() {
return ByteUtil.Motorola;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public String getTAG() {
return TAG;
}
@Override
public Object getValue(Map.Entry<Integer, MyPair<Integer>> entry, byte[] bytes) {
return null;
}
@Override
public HashMap<Integer, MyPair<Integer>> getFields() {
return null;
}
}
| false | 2,325 | 3 | 2,580 | 4 | 2,569 | 3 | 2,580 | 4 | 3,006 | 9 | false | false | false | false | false | true |
61149_35 | /*
* Copyright (c) 2023. felord.cn
* 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
* https://www.apache.org/licenses/LICENSE-2.0
* Website:
* https://felord.cn
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.felord.enumeration;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Arrays;
/**
* 操作类型
*
* @author dax
* @since 2024/10/9
*/
public enum OptType {
/**
* 上传
*/
UPLOAD(101),
/**
* 新建文件夹
*/
NEW_FOLDER(102),
/**
* 下载
*/
DOWNLOAD(103),
/**
* 更新
*/
UPDATE(104),
/**
* 星标
*/
STAR(105),
/**
* 移动
*/
MOVE(106),
/**
* 复制
*/
COPY(107),
/**
* 重命名
*/
RENAME(108),
/**
* 删除
*/
DELETE(109),
/**
* 恢复
*/
RECOVER(110),
/**
* 彻底删除
*/
DELETE_COMPLETELY(111),
/**
* 转发到企业微信
*/
SHARE_TO_WECOM(112),
/**
* 通过链接下载
*/
DOWNLOAD_VIA_LINK(113),
/**
* 获取分享链接
*/
GET_SHARE_LINK(114),
/**
* 修改分享链接
*/
EDIT_SHARING_LINK(115),
/**
* 关闭分享链接
*/
TURN_OFF_SHARING_LINKS(116),
/**
* 收藏
*/
COLLECTION(117),
/**
* 新建文档
*/
NEW_DOCUMENT(118),
/**
* 新建表格
*/
NEW_TABLE(119),
/**
* 打开
*/
OPEN_IT(121),
/**
* 导出文件
*/
EXPORT_FILE(124),
/**
* 添加文件成员
*/
ADD_FILE_MEMBERS(127),
/**
* 修改文件成员权限
*/
MODIFY_FILE_MEMBER_PERMISSIONS(128),
/**
* 移除文件成员
*/
REMOVE_FILE_MEMBERS(129),
/**
* 设置文档水印
*/
SET_DOCUMENT_WATERMARK(130),
/**
* 修改企业内权限
*/
MODIFY_PERMISSIONS_INTERNAL(131),
/**
* 修改企业外权限
*/
MODIFY_PERMISSIONS_EXTERNAL(132),
/**
* 添加快捷入口
*/
ADD_SHORTCUT(133),
/**
* 转发到微信
*/
SHARE_TO_WECHAT(134),
/**
* 预览
*/
PREVIEW(135),
/**
* 权限管理
*/
PERMISSION_MANAGEMENT(136),
/**
* 安全设置
*/
SECURITY_SETTINGS(139),
/**
* 通过邮件分享
*/
SHARE_VIA_EMAIL(140),
/**
* 离职成员文件转交
*/
TRANS_OF_DOC_DEPART_MEMBER(142),
/**
* 通过下载申请
*/
APPLY_DOWNLOAD(10001),
/**
* 拒绝下载申请
*/
REJECT_DOWNLOAD(10002);
private final int type;
OptType(int type) {
this.type = type;
}
/**
* Deserialize OptType
*
* @param type the type
* @return the opt type
*/
@JsonCreator
public static OptType deserialize(int type) {
return Arrays.stream(OptType.values())
.filter(opttype -> opttype.type == type)
.findFirst()
.orElse(null);
}
/**
* Gets type.
*
* @return the type
*/
@JsonValue
public int getType() {
return type;
}
}
| NotFound403/wecom-sdk | wecom-objects/src/main/java/cn/felord/enumeration/OptType.java | 1,098 | /**
* 离职成员文件转交
*/ | block_comment | zh-cn | /*
* Copyright (c) 2023. felord.cn
* 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
* https://www.apache.org/licenses/LICENSE-2.0
* Website:
* https://felord.cn
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.felord.enumeration;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Arrays;
/**
* 操作类型
*
* @author dax
* @since 2024/10/9
*/
public enum OptType {
/**
* 上传
*/
UPLOAD(101),
/**
* 新建文件夹
*/
NEW_FOLDER(102),
/**
* 下载
*/
DOWNLOAD(103),
/**
* 更新
*/
UPDATE(104),
/**
* 星标
*/
STAR(105),
/**
* 移动
*/
MOVE(106),
/**
* 复制
*/
COPY(107),
/**
* 重命名
*/
RENAME(108),
/**
* 删除
*/
DELETE(109),
/**
* 恢复
*/
RECOVER(110),
/**
* 彻底删除
*/
DELETE_COMPLETELY(111),
/**
* 转发到企业微信
*/
SHARE_TO_WECOM(112),
/**
* 通过链接下载
*/
DOWNLOAD_VIA_LINK(113),
/**
* 获取分享链接
*/
GET_SHARE_LINK(114),
/**
* 修改分享链接
*/
EDIT_SHARING_LINK(115),
/**
* 关闭分享链接
*/
TURN_OFF_SHARING_LINKS(116),
/**
* 收藏
*/
COLLECTION(117),
/**
* 新建文档
*/
NEW_DOCUMENT(118),
/**
* 新建表格
*/
NEW_TABLE(119),
/**
* 打开
*/
OPEN_IT(121),
/**
* 导出文件
*/
EXPORT_FILE(124),
/**
* 添加文件成员
*/
ADD_FILE_MEMBERS(127),
/**
* 修改文件成员权限
*/
MODIFY_FILE_MEMBER_PERMISSIONS(128),
/**
* 移除文件成员
*/
REMOVE_FILE_MEMBERS(129),
/**
* 设置文档水印
*/
SET_DOCUMENT_WATERMARK(130),
/**
* 修改企业内权限
*/
MODIFY_PERMISSIONS_INTERNAL(131),
/**
* 修改企业外权限
*/
MODIFY_PERMISSIONS_EXTERNAL(132),
/**
* 添加快捷入口
*/
ADD_SHORTCUT(133),
/**
* 转发到微信
*/
SHARE_TO_WECHAT(134),
/**
* 预览
*/
PREVIEW(135),
/**
* 权限管理
*/
PERMISSION_MANAGEMENT(136),
/**
* 安全设置
*/
SECURITY_SETTINGS(139),
/**
* 通过邮件分享
*/
SHARE_VIA_EMAIL(140),
/**
* 离职成 <SUF>*/
TRANS_OF_DOC_DEPART_MEMBER(142),
/**
* 通过下载申请
*/
APPLY_DOWNLOAD(10001),
/**
* 拒绝下载申请
*/
REJECT_DOWNLOAD(10002);
private final int type;
OptType(int type) {
this.type = type;
}
/**
* Deserialize OptType
*
* @param type the type
* @return the opt type
*/
@JsonCreator
public static OptType deserialize(int type) {
return Arrays.stream(OptType.values())
.filter(opttype -> opttype.type == type)
.findFirst()
.orElse(null);
}
/**
* Gets type.
*
* @return the type
*/
@JsonValue
public int getType() {
return type;
}
}
| false | 1,054 | 14 | 1,098 | 12 | 1,225 | 14 | 1,098 | 12 | 1,550 | 20 | false | false | false | false | false | true |
21657_0 | package org.nulla.kcrw.skill;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.nulla.kcrw.KCItems;
import org.nulla.kcrw.KeyCraft_Rewrite;
import org.nulla.nullacore.api.damage.NullaDamageSource;
import org.nulla.nullacore.api.skill.Skill;
/**
* 出自《Rewrite Harvest festa!》中灰太狼在战胜御堂后获得的技能“オーロラ+フォゴ剣”。
* 在原作中伤害很高,所以在这里给了物伤、魔伤和火伤的混合伤害。可惜对下界生物(毕竟抗火)效果很差啊。
* 然而毕竟是Aurora剑发动的技能,所以会崩掉手里的剑。。【大概
*/
public class SkillAuroraFoguBlade extends Skill {
public SkillAuroraFoguBlade(String name, int auroraRequired, int auroraCost, int cd) {
super(name, auroraRequired, auroraCost, cd);
this.mIcon = new ResourceLocation(KeyCraft_Rewrite.MODID, "textures/icons/skills/aurora_fogu_blade.png");
}
@Override
public boolean canLearnSkill(EntityPlayer player) {
return SkillsRw.AuroraSolidification.getExperience(player) >= 512;
}
@Override
public boolean onUse(EntityPlayer player) {
ItemStack held = player.getHeldItem();
if (held == null) {
return false;
}
if (held.getItem() != KCItems.aurora_blade) {
return false;
}
Entity targetCl = Minecraft.getMinecraft().pointedEntity;
Entity targetSr = null;
if (targetCl != null) {
targetSr = player.worldObj.getEntityByID(targetCl.getEntityId());
}
if (targetSr instanceof EntityLivingBase) {
EntityLivingBase entity = (EntityLivingBase) targetSr;
float damage = 2F * 4096 / (2048 - this.getExperience(player));
entity.attackEntityFrom(DamageSource.causePlayerDamage(player), 8F);
entity.attackEntityFrom(DamageSource.causePlayerDamage(player).setFireDamage(), damage);
entity.attackEntityFrom(NullaDamageSource.CauseAuroraDamage(player), damage);
} else {
return false;
}
//移除手中的剑
player.setCurrentItemOrArmor(0, null);
//蹦剑
SkillsRw.AuroraSolidification.onBladeDead(player, 1);
// 随机事件只在服务器发生
if (!player.worldObj.isRemote) {
Random rand = new Random();
int exp = rand.nextInt(10) + 1;
modifyExperience(player, exp);
}
return true;
}
} | NullaDev/KeyCraft-Rewrite | main/java/org/nulla/kcrw/skill/SkillAuroraFoguBlade.java | 906 | /**
* 出自《Rewrite Harvest festa!》中灰太狼在战胜御堂后获得的技能“オーロラ+フォゴ剣”。
* 在原作中伤害很高,所以在这里给了物伤、魔伤和火伤的混合伤害。可惜对下界生物(毕竟抗火)效果很差啊。
* 然而毕竟是Aurora剑发动的技能,所以会崩掉手里的剑。。【大概
*/ | block_comment | zh-cn | package org.nulla.kcrw.skill;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.monster.EntitySlime;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.nulla.kcrw.KCItems;
import org.nulla.kcrw.KeyCraft_Rewrite;
import org.nulla.nullacore.api.damage.NullaDamageSource;
import org.nulla.nullacore.api.skill.Skill;
/**
* 出自《 <SUF>*/
public class SkillAuroraFoguBlade extends Skill {
public SkillAuroraFoguBlade(String name, int auroraRequired, int auroraCost, int cd) {
super(name, auroraRequired, auroraCost, cd);
this.mIcon = new ResourceLocation(KeyCraft_Rewrite.MODID, "textures/icons/skills/aurora_fogu_blade.png");
}
@Override
public boolean canLearnSkill(EntityPlayer player) {
return SkillsRw.AuroraSolidification.getExperience(player) >= 512;
}
@Override
public boolean onUse(EntityPlayer player) {
ItemStack held = player.getHeldItem();
if (held == null) {
return false;
}
if (held.getItem() != KCItems.aurora_blade) {
return false;
}
Entity targetCl = Minecraft.getMinecraft().pointedEntity;
Entity targetSr = null;
if (targetCl != null) {
targetSr = player.worldObj.getEntityByID(targetCl.getEntityId());
}
if (targetSr instanceof EntityLivingBase) {
EntityLivingBase entity = (EntityLivingBase) targetSr;
float damage = 2F * 4096 / (2048 - this.getExperience(player));
entity.attackEntityFrom(DamageSource.causePlayerDamage(player), 8F);
entity.attackEntityFrom(DamageSource.causePlayerDamage(player).setFireDamage(), damage);
entity.attackEntityFrom(NullaDamageSource.CauseAuroraDamage(player), damage);
} else {
return false;
}
//移除手中的剑
player.setCurrentItemOrArmor(0, null);
//蹦剑
SkillsRw.AuroraSolidification.onBladeDead(player, 1);
// 随机事件只在服务器发生
if (!player.worldObj.isRemote) {
Random rand = new Random();
int exp = rand.nextInt(10) + 1;
modifyExperience(player, exp);
}
return true;
}
} | false | 733 | 100 | 906 | 139 | 850 | 93 | 906 | 139 | 1,145 | 186 | false | false | false | false | false | true |
31985_10 | package com.Nxer.TwistSpaceTechnology.recipe.specialRecipe;
import static thaumcraft.common.config.ConfigBlocks.blockMetalDevice;
import static thaumcraft.common.config.ConfigBlocks.blockStoneDevice;
import net.minecraft.item.ItemStack;
import com.Nxer.TwistSpaceTechnology.common.GTCMItemList;
import com.Nxer.TwistSpaceTechnology.config.Config;
import com.Nxer.TwistSpaceTechnology.util.TextEnums;
import gregtech.api.enums.ItemList;
import gregtech.api.enums.Materials;
import gregtech.api.enums.OrePrefixes;
import gregtech.api.util.GT_OreDictUnificator;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
import thaumcraft.api.crafting.InfusionRecipe;
import thaumcraft.api.research.ResearchItem;
import thaumcraft.api.research.ResearchPage;
import vazkii.botania.common.block.ModBlocks;
import vazkii.botania.common.item.ModItems;
public class TCResearches {
public void loadResearches() {
new ResearchItem(
"BH_ELVEN_WORKSHOP",
"botanichorizons",
(new AspectList()).merge(Aspect.EARTH, 1)
.merge(Aspect.MECHANISM, 1)
.merge(Aspect.MAGIC, 1),
4,
-9,
3,
GTCMItemList.ElvenWorkshop.get(1, 0)).setParents("BH_GAIA_PYLON")
.setPages(
new ResearchPage("tc.research_text.BH_ELVEN_WORKSHOP.1"),
new ResearchPage("tc.research_text.BH_ELVEN_WORKSHOP.2"),
new ResearchPage(
new InfusionRecipe(
"BH_ELVEN_WORKSHOP",
GTCMItemList.ElvenWorkshop.get(1, 0),
10,
(new AspectList()).merge(Aspect.LIFE, 64)
.merge(Aspect.EARTH, 64)
.merge(Aspect.MAGIC, 64)
.merge(Aspect.MECHANISM, 64),
new ItemStack(ModBlocks.terraPlate),
new ItemStack[] { ItemList.Field_Generator_EV.get(1), ItemList.Casing_IV.get(1),
Materials.Steeleaf.getPlates(1), new ItemStack(ModItems.spawnerMover, 1),
ItemList.Field_Generator_EV.get(1), ItemList.Casing_IV.get(1),
Materials.Steeleaf.getPlates(1), new ItemStack(ModItems.spawnerMover, 1) })))
.registerResearchItem();
if (Config.Enable_IndustrialMagicMatrix) {
new ResearchItem(
"INDUSTRIAL_MAGIC_MATRIX",
"BASICS",
(new AspectList()).merge(Aspect.EARTH, 1)
.merge(Aspect.MECHANISM, 1)
.merge(Aspect.MAGIC, 1),
4,
-9,
5,
GTCMItemList.IndustrialMagicMatrix.get(1, 0))/* .setParents("ICHORIUM") */
.setPages(
// #tr tc.research_text.INDUSTRIAL_MAGIC_MATRIX.1
// # Death, Evil, Abomination, Grievance, Murderous Intent, Curse of Misfortune, Hell,
// Ethics,Fool,
// Tyrant, Sinner, Cunning, Thief, Despicable, Evil, Poison, Hunger, Epidemic,
// Earthquake,Heavenly
// Change, Alien, Human, Calamity Forever, Time, Spirit, Root, Fiction, Darkness,
// Innocence,Life, or
// Something Called Fear.
// #zh_CN
// 死、邪恶、憎恶、怨嗟、杀意、不幸诅咒、地狱、伦理、愚者、暴君、罪人、狡猾、贼徒、卑劣、恶、毒、饥饿、疫病、地震、天变、异形、人间、灾厄永远、时间、精神、根源、虚构、黑暗、无垢、命或者被称为恐惧之物。
new ResearchPage(TextEnums.tr("tc.research_text.INDUSTRIAL_MAGIC_MATRIX.1")),
new ResearchPage(
new InfusionRecipe(
"INDUSTRIAL_MAGIC_MATRIX",
GTCMItemList.IndustrialMagicMatrix.get(1, 0),
25,
(new AspectList()).merge(Aspect.LIFE, 128)
.merge(Aspect.EARTH, 128)
.merge(Aspect.MAGIC, 128)
.merge(Aspect.MECHANISM, 128)
.merge(Aspect.AIR, 128)
.merge(Aspect.EARTH, 128)
.merge(Aspect.FIRE, 128)
.merge(Aspect.WATER, 128)
.merge(Aspect.ORDER, 128)
.merge(Aspect.ENTROPY, 128),
ItemList.Machine_Multi_Assemblyline.get(1, 0),
new ItemStack[] { GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12),
GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12),
GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12),
GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12) })))
.registerResearchItem();
}
}
}
| Nxer/Twist-Space-Technology-Mod | src/main/java/com/Nxer/TwistSpaceTechnology/recipe/specialRecipe/TCResearches.java | 1,622 | // 死、邪恶、憎恶、怨嗟、杀意、不幸诅咒、地狱、伦理、愚者、暴君、罪人、狡猾、贼徒、卑劣、恶、毒、饥饿、疫病、地震、天变、异形、人间、灾厄永远、时间、精神、根源、虚构、黑暗、无垢、命或者被称为恐惧之物。 | line_comment | zh-cn | package com.Nxer.TwistSpaceTechnology.recipe.specialRecipe;
import static thaumcraft.common.config.ConfigBlocks.blockMetalDevice;
import static thaumcraft.common.config.ConfigBlocks.blockStoneDevice;
import net.minecraft.item.ItemStack;
import com.Nxer.TwistSpaceTechnology.common.GTCMItemList;
import com.Nxer.TwistSpaceTechnology.config.Config;
import com.Nxer.TwistSpaceTechnology.util.TextEnums;
import gregtech.api.enums.ItemList;
import gregtech.api.enums.Materials;
import gregtech.api.enums.OrePrefixes;
import gregtech.api.util.GT_OreDictUnificator;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
import thaumcraft.api.crafting.InfusionRecipe;
import thaumcraft.api.research.ResearchItem;
import thaumcraft.api.research.ResearchPage;
import vazkii.botania.common.block.ModBlocks;
import vazkii.botania.common.item.ModItems;
public class TCResearches {
public void loadResearches() {
new ResearchItem(
"BH_ELVEN_WORKSHOP",
"botanichorizons",
(new AspectList()).merge(Aspect.EARTH, 1)
.merge(Aspect.MECHANISM, 1)
.merge(Aspect.MAGIC, 1),
4,
-9,
3,
GTCMItemList.ElvenWorkshop.get(1, 0)).setParents("BH_GAIA_PYLON")
.setPages(
new ResearchPage("tc.research_text.BH_ELVEN_WORKSHOP.1"),
new ResearchPage("tc.research_text.BH_ELVEN_WORKSHOP.2"),
new ResearchPage(
new InfusionRecipe(
"BH_ELVEN_WORKSHOP",
GTCMItemList.ElvenWorkshop.get(1, 0),
10,
(new AspectList()).merge(Aspect.LIFE, 64)
.merge(Aspect.EARTH, 64)
.merge(Aspect.MAGIC, 64)
.merge(Aspect.MECHANISM, 64),
new ItemStack(ModBlocks.terraPlate),
new ItemStack[] { ItemList.Field_Generator_EV.get(1), ItemList.Casing_IV.get(1),
Materials.Steeleaf.getPlates(1), new ItemStack(ModItems.spawnerMover, 1),
ItemList.Field_Generator_EV.get(1), ItemList.Casing_IV.get(1),
Materials.Steeleaf.getPlates(1), new ItemStack(ModItems.spawnerMover, 1) })))
.registerResearchItem();
if (Config.Enable_IndustrialMagicMatrix) {
new ResearchItem(
"INDUSTRIAL_MAGIC_MATRIX",
"BASICS",
(new AspectList()).merge(Aspect.EARTH, 1)
.merge(Aspect.MECHANISM, 1)
.merge(Aspect.MAGIC, 1),
4,
-9,
5,
GTCMItemList.IndustrialMagicMatrix.get(1, 0))/* .setParents("ICHORIUM") */
.setPages(
// #tr tc.research_text.INDUSTRIAL_MAGIC_MATRIX.1
// # Death, Evil, Abomination, Grievance, Murderous Intent, Curse of Misfortune, Hell,
// Ethics,Fool,
// Tyrant, Sinner, Cunning, Thief, Despicable, Evil, Poison, Hunger, Epidemic,
// Earthquake,Heavenly
// Change, Alien, Human, Calamity Forever, Time, Spirit, Root, Fiction, Darkness,
// Innocence,Life, or
// Something Called Fear.
// #zh_CN
// 死、 <SUF>
new ResearchPage(TextEnums.tr("tc.research_text.INDUSTRIAL_MAGIC_MATRIX.1")),
new ResearchPage(
new InfusionRecipe(
"INDUSTRIAL_MAGIC_MATRIX",
GTCMItemList.IndustrialMagicMatrix.get(1, 0),
25,
(new AspectList()).merge(Aspect.LIFE, 128)
.merge(Aspect.EARTH, 128)
.merge(Aspect.MAGIC, 128)
.merge(Aspect.MECHANISM, 128)
.merge(Aspect.AIR, 128)
.merge(Aspect.EARTH, 128)
.merge(Aspect.FIRE, 128)
.merge(Aspect.WATER, 128)
.merge(Aspect.ORDER, 128)
.merge(Aspect.ENTROPY, 128),
ItemList.Machine_Multi_Assemblyline.get(1, 0),
new ItemStack[] { GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12),
GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12),
GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12),
GT_OreDictUnificator.get(OrePrefixes.circuit, Materials.Master, 1L),
new ItemStack(blockStoneDevice, 1, 2), new ItemStack(blockMetalDevice, 1, 3),
new ItemStack(blockMetalDevice, 1, 12) })))
.registerResearchItem();
}
}
}
| false | 1,375 | 84 | 1,622 | 133 | 1,564 | 88 | 1,622 | 133 | 1,999 | 177 | false | false | false | false | false | true |
43259_3 | package books;
/**
* @program JavaBooks
* @description: 机器人的运动范围
* @author: mf
* @create: 2019/08/25 09:45
*/
/*
地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动
它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标
的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35, 37), 因为
3+5+3+7=18。但它不能进入方格(35, 38),因为3+5+3+8=19。请问?
该机器人能够到达多少个格子。
*/
public class T13 {
public static void main(String[] args) {
int count = movingCount(18, 40, 40);
System.out.println(count);
}
public static int movingCount(int threshold, int rows, int cols) {
if (threshold < 0 || rows < 1 || cols < 0) return 0;
boolean[][] visited = new boolean[rows][cols];
int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
return count;
}
public static int movingCountCore(int threshold, int rows, int cols, int i, int j, boolean[][] visited) {
int count = 0;
if (check(threshold, rows, cols, i, j, visited)) {
visited[i][j] = true;
// 核心之二
count = 1 + movingCountCore(threshold, rows, cols, i, j - 1, visited)
+ movingCountCore(threshold, rows, cols, i, j + 1, visited)
+ movingCountCore(threshold, rows, cols, i - 1, j, visited)
+ movingCountCore(threshold, rows, cols, i + 1, j, visited);
}
return count;
}
public static boolean check(int threshold, int rows, int cols, int i, int j, boolean[][] visited) {
// 核心之一
if (i >=0 && j >= 0 && i < rows && j < cols
&& getDigiSum(i) + getDigiSum(j) <= threshold
&& !visited[i][j]) return true;
return false;
}
// 常用方法,求一个数的总和
public static int getDigiSum(int i) {
int sum = 0;
while (i > 0 ) {
sum += i % 10;
i /= 10;
}
return sum;
}
}
| OAmbre/Java-Interview | SwordOffer/src/books/T13.java | 647 | // 核心之一 | line_comment | zh-cn | package books;
/**
* @program JavaBooks
* @description: 机器人的运动范围
* @author: mf
* @create: 2019/08/25 09:45
*/
/*
地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动
它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标
的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35, 37), 因为
3+5+3+7=18。但它不能进入方格(35, 38),因为3+5+3+8=19。请问?
该机器人能够到达多少个格子。
*/
public class T13 {
public static void main(String[] args) {
int count = movingCount(18, 40, 40);
System.out.println(count);
}
public static int movingCount(int threshold, int rows, int cols) {
if (threshold < 0 || rows < 1 || cols < 0) return 0;
boolean[][] visited = new boolean[rows][cols];
int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
return count;
}
public static int movingCountCore(int threshold, int rows, int cols, int i, int j, boolean[][] visited) {
int count = 0;
if (check(threshold, rows, cols, i, j, visited)) {
visited[i][j] = true;
// 核心之二
count = 1 + movingCountCore(threshold, rows, cols, i, j - 1, visited)
+ movingCountCore(threshold, rows, cols, i, j + 1, visited)
+ movingCountCore(threshold, rows, cols, i - 1, j, visited)
+ movingCountCore(threshold, rows, cols, i + 1, j, visited);
}
return count;
}
public static boolean check(int threshold, int rows, int cols, int i, int j, boolean[][] visited) {
// 核心 <SUF>
if (i >=0 && j >= 0 && i < rows && j < cols
&& getDigiSum(i) + getDigiSum(j) <= threshold
&& !visited[i][j]) return true;
return false;
}
// 常用方法,求一个数的总和
public static int getDigiSum(int i) {
int sum = 0;
while (i > 0 ) {
sum += i % 10;
i /= 10;
}
return sum;
}
}
| false | 624 | 5 | 647 | 5 | 667 | 4 | 647 | 5 | 772 | 8 | false | false | false | false | false | true |
58539_6 | /*
* 官网地站:http://www.mob.com
* 技术支持QQ: 4006852216
* 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复)
*
* Copyright (c) 2013年 mob.com. All rights reserved.
*/
package cn.sharesdk.onekeyshare;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import com.mob.MobSDK;
import com.mob.tools.utils.BitmapHelper;
import com.mob.tools.utils.ResHelper;
import java.util.ArrayList;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
/**
* 快捷分享的入口
* <p>
* 通过不同的setter设置参数,然后调用{@link #show(Context)}方法启动快捷分享
*/
public class OnekeyShare {
private HashMap<String, Object> params;
public OnekeyShare() {
params = new HashMap<String, Object>();
params.put("customers", new ArrayList<CustomerLogo>());
params.put("hiddenPlatforms", new HashMap<String, String>());
}
/** address是接收人地址,仅在信息和邮件使用,否则可以不提供 */
public void setAddress(String address) {
params.put("address", address);
}
/**
* title标题,在印象笔记、邮箱、信息、微信(包括好友、朋友圈和收藏)、
* 易信(包括好友、朋友圈)、人人网和QQ空间使用,否则可以不提供
*/
public void setTitle(String title) {
params.put("title", title);
}
/** titleUrl是标题的网络链接,仅在人人网和QQ空间使用,否则可以不提供 */
public void setTitleUrl(String titleUrl) {
params.put("titleUrl", titleUrl);
}
/** text是分享文本,所有平台都需要这个字段 */
public void setText(String text) {
params.put("text", text);
}
/** 获取text字段的值 */
public String getText() {
return params.containsKey("text") ? String.valueOf(params.get("text")) : null;
}
/** imagePath是本地的图片路径,除Linked-In外的所有平台都支持这个字段 */
public void setImagePath(String imagePath) {
if(!TextUtils.isEmpty(imagePath)) {
params.put("imagePath", imagePath);
}
}
/** imageUrl是图片的网络路径,新浪微博、人人网、QQ空间和Linked-In支持此字段 */
public void setImageUrl(String imageUrl) {
if (!TextUtils.isEmpty(imageUrl)) {
params.put("imageUrl", imageUrl);
}
}
/** url在微信(包括好友、朋友圈收藏)和易信(包括好友和朋友圈)中使用,否则可以不提供 */
public void setUrl(String url) {
params.put("url", url);
}
/** filePath是待分享应用程序的本地路劲,仅在微信(易信)好友和Dropbox中使用,否则可以不提供 */
public void setFilePath(String filePath) {
params.put("filePath", filePath);
}
/** comment是我对这条分享的评论,仅在人人网和QQ空间使用,否则可以不提供 */
public void setComment(String comment) {
params.put("comment", comment);
}
/** site是分享此内容的网站名称,仅在QQ空间使用,否则可以不提供 */
public void setSite(String site) {
params.put("site", site);
}
/** siteUrl是分享此内容的网站地址,仅在QQ空间使用,否则可以不提供 */
public void setSiteUrl(String siteUrl) {
params.put("siteUrl", siteUrl);
}
/** foursquare分享时的地方名 */
public void setVenueName(String venueName) {
params.put("venueName", venueName);
}
/** foursquare分享时的地方描述 */
public void setVenueDescription(String venueDescription) {
params.put("venueDescription", venueDescription);
}
/** 分享地纬度,新浪微博、腾讯微博和foursquare支持此字段 */
public void setLatitude(float latitude) {
params.put("latitude", latitude);
}
/** 分享地经度,新浪微博、腾讯微博和foursquare支持此字段 */
public void setLongitude(float longitude) {
params.put("longitude", longitude);
}
/** 是否直接分享 */
public void setSilent(boolean silent) {
params.put("silent", silent);
}
/** 设置编辑页的初始化选中平台 */
public void setPlatform(String platform) {
params.put("platform", platform);
}
/** 设置KakaoTalk的应用下载地址 */
public void setInstallUrl(String installurl) {
params.put("installurl", installurl);
}
/** 设置KakaoTalk的应用打开地址 */
public void setExecuteUrl(String executeurl) {
params.put("executeurl", executeurl);
}
/** 设置微信分享的音乐的地址 */
public void setMusicUrl(String musicUrl) {
params.put("musicUrl", musicUrl);
}
/** 设置自定义的外部回调 */
public void setCallback(PlatformActionListener callback) {
params.put("callback", callback);
}
/** 返回操作回调 */
public PlatformActionListener getCallback() {
return ResHelper.forceCast(params.get("callback"));
}
/** 设置用于分享过程中,根据不同平台自定义分享内容的回调 */
public void setShareContentCustomizeCallback(ShareContentCustomizeCallback callback) {
params.put("customizeCallback", callback);
}
/** 自定义不同平台分享不同内容的回调 */
public ShareContentCustomizeCallback getShareContentCustomizeCallback() {
return ResHelper.forceCast(params.get("customizeCallback"));
}
/** 设置自己图标和点击事件,可以重复调用添加多次 */
public void setCustomerLogo(Bitmap logo, String label, OnClickListener ocl) {
CustomerLogo cl = new CustomerLogo();
cl.logo = logo;
cl.label = label;
cl.listener = ocl;
ArrayList<CustomerLogo> customers = ResHelper.forceCast(params.get("customers"));
customers.add(cl);
}
/** 设置一个总开关,用于在分享前若需要授权,则禁用sso功能 */
public void disableSSOWhenAuthorize() {
params.put("disableSSO", true);
}
/** 设置视频网络地址 */
public void setVideoUrl(String url) {
params.put("url", url);
params.put("shareType", Platform.SHARE_VIDEO);
}
/** 设置编辑页面的显示模式为Dialog模式 */
@Deprecated
public void setDialogMode() {
params.put("dialogMode", true);
}
/** 添加一个隐藏的platform */
public void addHiddenPlatform(String platform) {
HashMap<String, String> hiddenPlatforms = ResHelper.forceCast(params.get("hiddenPlatforms"));
hiddenPlatforms.put(platform, platform);
}
/** 设置一个将被截图分享的View , surfaceView是截不了图片的*/
public void setViewToShare(View viewToShare) {
try {
Bitmap bm = BitmapHelper.captureView(viewToShare, viewToShare.getWidth(), viewToShare.getHeight());
params.put("viewToShare", bm);
} catch (Throwable e) {
e.printStackTrace();
}
}
/** 腾讯微博分享多张图片 */
public void setImageArray(String[] imageArray) {
params.put("imageArray", imageArray);
}
/** 设置在执行分享到QQ或QZone的同时,分享相同的内容腾讯微博 */
public void setShareToTencentWeiboWhenPerformingQQOrQZoneSharing() {
params.put("isShareTencentWeibo", true);
}
/** 设置分享界面的样式,目前只有一种,不需要设置 */
public void setTheme(OnekeyShareTheme theme) {
params.put("theme", theme.getValue());
}
@SuppressWarnings("unchecked")
public void show(Context context) {
HashMap<String, Object> shareParamsMap = new HashMap<String, Object>();
shareParamsMap.putAll(params);
MobSDK.init(context.getApplicationContext());
ShareSDK.initSDK(context);
// 打开分享菜单的统计
ShareSDK.logDemoEvent(1, null);
int iTheme = 0;
try {
iTheme = ResHelper.parseInt(String.valueOf(shareParamsMap.remove("theme")));
} catch (Throwable t) {}
OnekeyShareTheme theme = OnekeyShareTheme.fromValue(iTheme);
OnekeyShareThemeImpl themeImpl = theme.getImpl();
themeImpl.setShareParamsMap(shareParamsMap);
themeImpl.setDialogMode(shareParamsMap.containsKey("dialogMode") ? ((Boolean) shareParamsMap.remove("dialogMode")) : false);
themeImpl.setSilent(shareParamsMap.containsKey("silent") ? ((Boolean) shareParamsMap.remove("silent")) : false);
themeImpl.setCustomerLogos((ArrayList<CustomerLogo>) shareParamsMap.remove("customers"));
themeImpl.setHiddenPlatforms((HashMap<String, String>) shareParamsMap.remove("hiddenPlatforms"));
themeImpl.setPlatformActionListener((PlatformActionListener) shareParamsMap.remove("callback"));
themeImpl.setShareContentCustomizeCallback((ShareContentCustomizeCallback) shareParamsMap.remove("customizeCallback"));
if (shareParamsMap.containsKey("disableSSO") ? ((Boolean) shareParamsMap.remove("disableSSO")) : false) {
themeImpl.disableSSO();
}
themeImpl.show(context.getApplicationContext());
}
}
| OCNYang/QBox | app/src/main/java/cn/sharesdk/onekeyshare/OnekeyShare.java | 2,537 | /** 获取text字段的值 */ | block_comment | zh-cn | /*
* 官网地站:http://www.mob.com
* 技术支持QQ: 4006852216
* 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复)
*
* Copyright (c) 2013年 mob.com. All rights reserved.
*/
package cn.sharesdk.onekeyshare;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import com.mob.MobSDK;
import com.mob.tools.utils.BitmapHelper;
import com.mob.tools.utils.ResHelper;
import java.util.ArrayList;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
/**
* 快捷分享的入口
* <p>
* 通过不同的setter设置参数,然后调用{@link #show(Context)}方法启动快捷分享
*/
public class OnekeyShare {
private HashMap<String, Object> params;
public OnekeyShare() {
params = new HashMap<String, Object>();
params.put("customers", new ArrayList<CustomerLogo>());
params.put("hiddenPlatforms", new HashMap<String, String>());
}
/** address是接收人地址,仅在信息和邮件使用,否则可以不提供 */
public void setAddress(String address) {
params.put("address", address);
}
/**
* title标题,在印象笔记、邮箱、信息、微信(包括好友、朋友圈和收藏)、
* 易信(包括好友、朋友圈)、人人网和QQ空间使用,否则可以不提供
*/
public void setTitle(String title) {
params.put("title", title);
}
/** titleUrl是标题的网络链接,仅在人人网和QQ空间使用,否则可以不提供 */
public void setTitleUrl(String titleUrl) {
params.put("titleUrl", titleUrl);
}
/** text是分享文本,所有平台都需要这个字段 */
public void setText(String text) {
params.put("text", text);
}
/** 获取t <SUF>*/
public String getText() {
return params.containsKey("text") ? String.valueOf(params.get("text")) : null;
}
/** imagePath是本地的图片路径,除Linked-In外的所有平台都支持这个字段 */
public void setImagePath(String imagePath) {
if(!TextUtils.isEmpty(imagePath)) {
params.put("imagePath", imagePath);
}
}
/** imageUrl是图片的网络路径,新浪微博、人人网、QQ空间和Linked-In支持此字段 */
public void setImageUrl(String imageUrl) {
if (!TextUtils.isEmpty(imageUrl)) {
params.put("imageUrl", imageUrl);
}
}
/** url在微信(包括好友、朋友圈收藏)和易信(包括好友和朋友圈)中使用,否则可以不提供 */
public void setUrl(String url) {
params.put("url", url);
}
/** filePath是待分享应用程序的本地路劲,仅在微信(易信)好友和Dropbox中使用,否则可以不提供 */
public void setFilePath(String filePath) {
params.put("filePath", filePath);
}
/** comment是我对这条分享的评论,仅在人人网和QQ空间使用,否则可以不提供 */
public void setComment(String comment) {
params.put("comment", comment);
}
/** site是分享此内容的网站名称,仅在QQ空间使用,否则可以不提供 */
public void setSite(String site) {
params.put("site", site);
}
/** siteUrl是分享此内容的网站地址,仅在QQ空间使用,否则可以不提供 */
public void setSiteUrl(String siteUrl) {
params.put("siteUrl", siteUrl);
}
/** foursquare分享时的地方名 */
public void setVenueName(String venueName) {
params.put("venueName", venueName);
}
/** foursquare分享时的地方描述 */
public void setVenueDescription(String venueDescription) {
params.put("venueDescription", venueDescription);
}
/** 分享地纬度,新浪微博、腾讯微博和foursquare支持此字段 */
public void setLatitude(float latitude) {
params.put("latitude", latitude);
}
/** 分享地经度,新浪微博、腾讯微博和foursquare支持此字段 */
public void setLongitude(float longitude) {
params.put("longitude", longitude);
}
/** 是否直接分享 */
public void setSilent(boolean silent) {
params.put("silent", silent);
}
/** 设置编辑页的初始化选中平台 */
public void setPlatform(String platform) {
params.put("platform", platform);
}
/** 设置KakaoTalk的应用下载地址 */
public void setInstallUrl(String installurl) {
params.put("installurl", installurl);
}
/** 设置KakaoTalk的应用打开地址 */
public void setExecuteUrl(String executeurl) {
params.put("executeurl", executeurl);
}
/** 设置微信分享的音乐的地址 */
public void setMusicUrl(String musicUrl) {
params.put("musicUrl", musicUrl);
}
/** 设置自定义的外部回调 */
public void setCallback(PlatformActionListener callback) {
params.put("callback", callback);
}
/** 返回操作回调 */
public PlatformActionListener getCallback() {
return ResHelper.forceCast(params.get("callback"));
}
/** 设置用于分享过程中,根据不同平台自定义分享内容的回调 */
public void setShareContentCustomizeCallback(ShareContentCustomizeCallback callback) {
params.put("customizeCallback", callback);
}
/** 自定义不同平台分享不同内容的回调 */
public ShareContentCustomizeCallback getShareContentCustomizeCallback() {
return ResHelper.forceCast(params.get("customizeCallback"));
}
/** 设置自己图标和点击事件,可以重复调用添加多次 */
public void setCustomerLogo(Bitmap logo, String label, OnClickListener ocl) {
CustomerLogo cl = new CustomerLogo();
cl.logo = logo;
cl.label = label;
cl.listener = ocl;
ArrayList<CustomerLogo> customers = ResHelper.forceCast(params.get("customers"));
customers.add(cl);
}
/** 设置一个总开关,用于在分享前若需要授权,则禁用sso功能 */
public void disableSSOWhenAuthorize() {
params.put("disableSSO", true);
}
/** 设置视频网络地址 */
public void setVideoUrl(String url) {
params.put("url", url);
params.put("shareType", Platform.SHARE_VIDEO);
}
/** 设置编辑页面的显示模式为Dialog模式 */
@Deprecated
public void setDialogMode() {
params.put("dialogMode", true);
}
/** 添加一个隐藏的platform */
public void addHiddenPlatform(String platform) {
HashMap<String, String> hiddenPlatforms = ResHelper.forceCast(params.get("hiddenPlatforms"));
hiddenPlatforms.put(platform, platform);
}
/** 设置一个将被截图分享的View , surfaceView是截不了图片的*/
public void setViewToShare(View viewToShare) {
try {
Bitmap bm = BitmapHelper.captureView(viewToShare, viewToShare.getWidth(), viewToShare.getHeight());
params.put("viewToShare", bm);
} catch (Throwable e) {
e.printStackTrace();
}
}
/** 腾讯微博分享多张图片 */
public void setImageArray(String[] imageArray) {
params.put("imageArray", imageArray);
}
/** 设置在执行分享到QQ或QZone的同时,分享相同的内容腾讯微博 */
public void setShareToTencentWeiboWhenPerformingQQOrQZoneSharing() {
params.put("isShareTencentWeibo", true);
}
/** 设置分享界面的样式,目前只有一种,不需要设置 */
public void setTheme(OnekeyShareTheme theme) {
params.put("theme", theme.getValue());
}
@SuppressWarnings("unchecked")
public void show(Context context) {
HashMap<String, Object> shareParamsMap = new HashMap<String, Object>();
shareParamsMap.putAll(params);
MobSDK.init(context.getApplicationContext());
ShareSDK.initSDK(context);
// 打开分享菜单的统计
ShareSDK.logDemoEvent(1, null);
int iTheme = 0;
try {
iTheme = ResHelper.parseInt(String.valueOf(shareParamsMap.remove("theme")));
} catch (Throwable t) {}
OnekeyShareTheme theme = OnekeyShareTheme.fromValue(iTheme);
OnekeyShareThemeImpl themeImpl = theme.getImpl();
themeImpl.setShareParamsMap(shareParamsMap);
themeImpl.setDialogMode(shareParamsMap.containsKey("dialogMode") ? ((Boolean) shareParamsMap.remove("dialogMode")) : false);
themeImpl.setSilent(shareParamsMap.containsKey("silent") ? ((Boolean) shareParamsMap.remove("silent")) : false);
themeImpl.setCustomerLogos((ArrayList<CustomerLogo>) shareParamsMap.remove("customers"));
themeImpl.setHiddenPlatforms((HashMap<String, String>) shareParamsMap.remove("hiddenPlatforms"));
themeImpl.setPlatformActionListener((PlatformActionListener) shareParamsMap.remove("callback"));
themeImpl.setShareContentCustomizeCallback((ShareContentCustomizeCallback) shareParamsMap.remove("customizeCallback"));
if (shareParamsMap.containsKey("disableSSO") ? ((Boolean) shareParamsMap.remove("disableSSO")) : false) {
themeImpl.disableSSO();
}
themeImpl.show(context.getApplicationContext());
}
}
| false | 2,073 | 7 | 2,537 | 6 | 2,424 | 6 | 2,537 | 6 | 3,275 | 10 | false | false | false | false | false | true |
40249_56 | //package com.sky.service.impl;
//
//import com.sky.build.OrderItem;
//import com.sky.build.OrderItemBuilder;
//import com.sky.constant.MessageConstant;
//import com.sky.context.BaseContext;
//import com.sky.dto.OrdersPageQueryDTO;
//import com.sky.dto.OrdersPaymentDTO;
//import com.sky.dto.OrdersSubmitDTO;
//import com.sky.entity.*;
//import com.sky.exception.AddressBookBusinessException;
//import com.sky.exception.ShoppingCartBusinessException;
//import com.sky.mapper.*;
//import com.sky.result.PageResult;
//import com.sky.service.OrderService;
//import com.sky.vo.OrderPaymentVO;
//import com.sky.vo.OrderSubmitVO;
//import com.sky.vo.OrderVO;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.time.LocalDateTime;
//import java.util.ArrayList;
//import java.util.List;
//
//@Service
//public class OrderServiceImpl_Bulider implements OrderService {
//
// @Autowired
// private AddressBookMapper addressBookMapper;
//
// @Autowired
// private ShoppingCartMapper cartMapper;
//
// @Autowired
// private UserMapper userMapper;
//
// @Autowired
// private OrderMapper orderMapper;
//
// @Autowired
// private OrderDetailMapper orderDetailMapper;
//
// @Override
// public OrderSubmitVO oderSubmit(OrdersSubmitDTO submitDTO) {
// /**
// * 构造器设计模式
// * 我们现在使用的构造器设计模式其实都是利用lombok 这哥们帮我们生成
// * 1、普通场景,本来你可以用set的,现在你就替换成lombok 生成的构造器设计模式的代码,但是这种方式其实没有什么实际的意义
// * 2、就用于构建复杂的对象,比如说,以后我们某个实体类里边可能包含 上百个字段,或者是有很多个实体类对象,就无比适合我们的构造器设计模式
// * 我们可以利用一个builder 去构建出来一个当前实体类中需要使用到的所有内容的实体类,然后再利用这个builder类去获得里边内容
// * 通过这个构造器设计模式 我就将一类一类的数据封装 封装成了一个一个build方法,如果我们进行修改代码,或者我们要进行修改bug,我们就只需要找到具体的
// * 这个build方法不就OK了,而不用像之前一样,去漫无目的的把所有代码都阅读一遍
// */
//
// // 学完苍穹外卖之后,我们学习 微服务框架 微服务框架高级
// // 90以上
// // 18K 以上 20K
//
//
// /*
// OrderItemBuilder orderBuilder = new OrderItemBuilder();
// OrderItem orderItem = orderBuilder.buildOrderDetails()
// .buildAddress();
// List<OrderDetail> orderDetails = orderItem.getOrderDetails();
// Orders order = orderItem.getOrder();
// User user = orderItem.getUser();*/
//
// // 1、面试官问:哥们有没有使用过设计模式 0、他的场景 1、提高代码阅读性 2、方便后期维护
// // 2、在使用构造器设计模式:就是如何在类与类之间传参数
// //构造器传参 //@Component @Autowire(就不好传递非spring管理的类型) // threadLocal
// // 3、有关分库分表的 高表以及宽表对应的知识
//
// // 只有主干,没有分支
// OrderItemBuilder orderItemBuilder =
// new OrderItemBuilder(addressBookMapper,cartMapper,userMapper,submitDTO);
// OrderItem orderItem = orderItemBuilder.builderOrders()
// .builderOrderDetails()
// .build();
//
// Orders orders = orderItem.getOrders();
// List<OrderDetail> orderDetailList = orderItem.getOrderDetailList();
// orderMapper.insertOrders(orders);
// orderDetailMapper.insertDetailList(orderDetailList);
// //5、删除购物车
// ShoppingCart shoppingCart = new ShoppingCart();
// shoppingCart.setUserId(BaseContext.getCurrentId());
// cartMapper.deleteByUserId(shoppingCart);
//
// OrderSubmitVO orderVO = buildeOrderVo(orders);//封装前端VO对象提交返回信息
// return orderVO;
// }
//
// private OrderSubmitVO buildeOrderVo(Orders orders) {
// OrderSubmitVO orderVO = new OrderSubmitVO();
// orderVO.setId(orders.getId());
// //正常操作是需要验价的
// orderVO.setOrderAmount(orders.getAmount());
// orderVO.setOrderTime(orders.getOrderTime());
// orderVO.setId(orders.getId());
// return orderVO;
// }
//
// @Override
// public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
// return null;
// }
//
// @Override
// public void paySuccess(String outTradeNo) {
//
// }
//
// @Override
// public PageResult checkHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
// return null;
// }
//
// @Override
// public OrderVO checkOrderDetail(Long id) {
// return null;
// }
//
// @Override
// public void cancelOrder(Long id) throws Exception {
//
// }
//
// @Override
// public void orderAgain(Long id) {
//
// }
//
// /* @Override
// public OrderVO submitOrders(OrdersSubmitDTO submitDTO) {
// // 订单幂等性问题
// //1、查询地址
// AddressBook addressBook = addressBookMapper.getById(submitDTO.getAddressBookId());
// if(addressBook == null){
// throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
// }
// //2、需要使用到 userId 查询购物车
// ShoppingCart cart = new ShoppingCart();
// Long userId = BaseContext.getCurrentId();
// cart.setUserId(userId);
// List<ShoppingCart> cartList = cartMapper.list(cart);
// if(cartList == null || cartList.size() == 0){
// throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
// }
// // 需要填充时使用到的实体类都有了
// Orders orders = new Orders();
// BeanUtils.copyProperties(submitDTO,orders);
// //一般订单号确实需要单独处理成一个字段,主要原因是因为 1、支付时候需要使用 2、订单号通常都会具备一些特有含义
// User user = userMapper.getById(userId);
// orders.setUserName(user.getName());
// orders.setNumber(String.valueOf(System.currentTimeMillis()));
// orders.setStatus(Orders.PENDING_PAYMENT); //魔法数字 使用枚举来限制入参
// orders.setUserId(BaseContext.getCurrentId());
// orders.setOrderTime(LocalDateTime.now());
// orders.setPayStatus(Orders.UN_PAID);
// orders.setPhone(addressBook.getPhone());
// orders.setAddress(addressBook.getDetail());
// orders.setConsignee(addressBook.getConsignee());
// // 需要主键返回
// //4、保存order,保存orderDetails
// orderMapper.insert(orders);
// //3、根据地址和购物车填充 order和orderDetails
// //4、进行批量插入
// List<OrderDetail> orderDetails = new ArrayList<>();
// for (ShoppingCart shoppingCart : cartList) {
// OrderDetail orderDetail = new OrderDetail();
// BeanUtils.copyProperties(shoppingCart,orderDetail);
// orderDetail.setOrderId(orders.getId());
// orderDetails.add(orderDetail);
// }
// orderDetailMapper.insertBatch(orderDetails);
// //5、删除购物车
// cartMapper.deleteByUserId(userId);
// //6、封装vo返回
// OrderVO orderVO = new OrderVO();
// orderVO.setId(orders.getId());
// //正常操作是需要验价的
// orderVO.setAmount(orders.getAmount());
// orderVO.setOrderTime(orders.getOrderTime());
// orderVO.setNumber(orders.getNumber());
// return orderVO;
// }*/
//
//}
| ODentist/SkyTakeOut | sky-server/src/main/java/com/sky/service/impl/OrderServiceImpl_Bulider.java | 2,159 | // // 3、有关分库分表的 高表以及宽表对应的知识 | line_comment | zh-cn | //package com.sky.service.impl;
//
//import com.sky.build.OrderItem;
//import com.sky.build.OrderItemBuilder;
//import com.sky.constant.MessageConstant;
//import com.sky.context.BaseContext;
//import com.sky.dto.OrdersPageQueryDTO;
//import com.sky.dto.OrdersPaymentDTO;
//import com.sky.dto.OrdersSubmitDTO;
//import com.sky.entity.*;
//import com.sky.exception.AddressBookBusinessException;
//import com.sky.exception.ShoppingCartBusinessException;
//import com.sky.mapper.*;
//import com.sky.result.PageResult;
//import com.sky.service.OrderService;
//import com.sky.vo.OrderPaymentVO;
//import com.sky.vo.OrderSubmitVO;
//import com.sky.vo.OrderVO;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.time.LocalDateTime;
//import java.util.ArrayList;
//import java.util.List;
//
//@Service
//public class OrderServiceImpl_Bulider implements OrderService {
//
// @Autowired
// private AddressBookMapper addressBookMapper;
//
// @Autowired
// private ShoppingCartMapper cartMapper;
//
// @Autowired
// private UserMapper userMapper;
//
// @Autowired
// private OrderMapper orderMapper;
//
// @Autowired
// private OrderDetailMapper orderDetailMapper;
//
// @Override
// public OrderSubmitVO oderSubmit(OrdersSubmitDTO submitDTO) {
// /**
// * 构造器设计模式
// * 我们现在使用的构造器设计模式其实都是利用lombok 这哥们帮我们生成
// * 1、普通场景,本来你可以用set的,现在你就替换成lombok 生成的构造器设计模式的代码,但是这种方式其实没有什么实际的意义
// * 2、就用于构建复杂的对象,比如说,以后我们某个实体类里边可能包含 上百个字段,或者是有很多个实体类对象,就无比适合我们的构造器设计模式
// * 我们可以利用一个builder 去构建出来一个当前实体类中需要使用到的所有内容的实体类,然后再利用这个builder类去获得里边内容
// * 通过这个构造器设计模式 我就将一类一类的数据封装 封装成了一个一个build方法,如果我们进行修改代码,或者我们要进行修改bug,我们就只需要找到具体的
// * 这个build方法不就OK了,而不用像之前一样,去漫无目的的把所有代码都阅读一遍
// */
//
// // 学完苍穹外卖之后,我们学习 微服务框架 微服务框架高级
// // 90以上
// // 18K 以上 20K
//
//
// /*
// OrderItemBuilder orderBuilder = new OrderItemBuilder();
// OrderItem orderItem = orderBuilder.buildOrderDetails()
// .buildAddress();
// List<OrderDetail> orderDetails = orderItem.getOrderDetails();
// Orders order = orderItem.getOrder();
// User user = orderItem.getUser();*/
//
// // 1、面试官问:哥们有没有使用过设计模式 0、他的场景 1、提高代码阅读性 2、方便后期维护
// // 2、在使用构造器设计模式:就是如何在类与类之间传参数
// //构造器传参 //@Component @Autowire(就不好传递非spring管理的类型) // threadLocal
// // 3、 <SUF>
//
// // 只有主干,没有分支
// OrderItemBuilder orderItemBuilder =
// new OrderItemBuilder(addressBookMapper,cartMapper,userMapper,submitDTO);
// OrderItem orderItem = orderItemBuilder.builderOrders()
// .builderOrderDetails()
// .build();
//
// Orders orders = orderItem.getOrders();
// List<OrderDetail> orderDetailList = orderItem.getOrderDetailList();
// orderMapper.insertOrders(orders);
// orderDetailMapper.insertDetailList(orderDetailList);
// //5、删除购物车
// ShoppingCart shoppingCart = new ShoppingCart();
// shoppingCart.setUserId(BaseContext.getCurrentId());
// cartMapper.deleteByUserId(shoppingCart);
//
// OrderSubmitVO orderVO = buildeOrderVo(orders);//封装前端VO对象提交返回信息
// return orderVO;
// }
//
// private OrderSubmitVO buildeOrderVo(Orders orders) {
// OrderSubmitVO orderVO = new OrderSubmitVO();
// orderVO.setId(orders.getId());
// //正常操作是需要验价的
// orderVO.setOrderAmount(orders.getAmount());
// orderVO.setOrderTime(orders.getOrderTime());
// orderVO.setId(orders.getId());
// return orderVO;
// }
//
// @Override
// public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
// return null;
// }
//
// @Override
// public void paySuccess(String outTradeNo) {
//
// }
//
// @Override
// public PageResult checkHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
// return null;
// }
//
// @Override
// public OrderVO checkOrderDetail(Long id) {
// return null;
// }
//
// @Override
// public void cancelOrder(Long id) throws Exception {
//
// }
//
// @Override
// public void orderAgain(Long id) {
//
// }
//
// /* @Override
// public OrderVO submitOrders(OrdersSubmitDTO submitDTO) {
// // 订单幂等性问题
// //1、查询地址
// AddressBook addressBook = addressBookMapper.getById(submitDTO.getAddressBookId());
// if(addressBook == null){
// throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
// }
// //2、需要使用到 userId 查询购物车
// ShoppingCart cart = new ShoppingCart();
// Long userId = BaseContext.getCurrentId();
// cart.setUserId(userId);
// List<ShoppingCart> cartList = cartMapper.list(cart);
// if(cartList == null || cartList.size() == 0){
// throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
// }
// // 需要填充时使用到的实体类都有了
// Orders orders = new Orders();
// BeanUtils.copyProperties(submitDTO,orders);
// //一般订单号确实需要单独处理成一个字段,主要原因是因为 1、支付时候需要使用 2、订单号通常都会具备一些特有含义
// User user = userMapper.getById(userId);
// orders.setUserName(user.getName());
// orders.setNumber(String.valueOf(System.currentTimeMillis()));
// orders.setStatus(Orders.PENDING_PAYMENT); //魔法数字 使用枚举来限制入参
// orders.setUserId(BaseContext.getCurrentId());
// orders.setOrderTime(LocalDateTime.now());
// orders.setPayStatus(Orders.UN_PAID);
// orders.setPhone(addressBook.getPhone());
// orders.setAddress(addressBook.getDetail());
// orders.setConsignee(addressBook.getConsignee());
// // 需要主键返回
// //4、保存order,保存orderDetails
// orderMapper.insert(orders);
// //3、根据地址和购物车填充 order和orderDetails
// //4、进行批量插入
// List<OrderDetail> orderDetails = new ArrayList<>();
// for (ShoppingCart shoppingCart : cartList) {
// OrderDetail orderDetail = new OrderDetail();
// BeanUtils.copyProperties(shoppingCart,orderDetail);
// orderDetail.setOrderId(orders.getId());
// orderDetails.add(orderDetail);
// }
// orderDetailMapper.insertBatch(orderDetails);
// //5、删除购物车
// cartMapper.deleteByUserId(userId);
// //6、封装vo返回
// OrderVO orderVO = new OrderVO();
// orderVO.setId(orders.getId());
// //正常操作是需要验价的
// orderVO.setAmount(orders.getAmount());
// orderVO.setOrderTime(orders.getOrderTime());
// orderVO.setNumber(orders.getNumber());
// return orderVO;
// }*/
//
//}
| false | 1,804 | 21 | 2,159 | 22 | 2,046 | 19 | 2,159 | 22 | 2,634 | 29 | false | false | false | false | false | true |
808_2 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int u = input.nextInt();
int d = input.nextInt();
int time = 0, dist = 0;
while (true) { // 用死循环来枚举
dist += u;
time++;
if (dist >= n) {
break; // 满足条件则退出死循环
}
dist -= d;
}
System.out.println(time); // 输出得到的结果
input.close();
}
}
| OI-wiki/OI-wiki | docs/basic/code/simulate/simulate_1.java | 150 | // 输出得到的结果 | line_comment | zh-cn | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int u = input.nextInt();
int d = input.nextInt();
int time = 0, dist = 0;
while (true) { // 用死循环来枚举
dist += u;
time++;
if (dist >= n) {
break; // 满足条件则退出死循环
}
dist -= d;
}
System.out.println(time); // 输出 <SUF>
input.close();
}
}
| false | 136 | 4 | 150 | 6 | 162 | 4 | 150 | 6 | 194 | 9 | false | false | false | false | false | true |
18057_11 | import java.awt.Robot;
import java.util.Random;
import java.awt.AWTException;
import java.awt.event.InputEvent;
public class crot extends Thread {
static boolean first = true; // 控制 开/关
static boolean sors = false; // 控制 开/关
static int smax;
static int smin;
static int np;
static int probability;
static int amount = 0;
static Robot robot;
public static void cstart(int imax, int imin, int aprobability) throws InterruptedException {
System.out.println("---------");
System.out.println("max " + imax + "ms");
System.out.println("min " + imin + "ms");
System.out.println("ChangeProbability " + (100 - aprobability) + "%");
smax = imax;
smin = imin;
probability = aprobability;
sors = true;
if (first) {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
first = false;
}
Random r = new Random();
while (sors) {
int pbi = r.nextInt(101) + 1;
if (pbi != 0 && pbi > probability) {
int rdelay = r.nextInt(smin - smax) + smax;// 最大值为smin 最小值为smax 之间的随机数
np = rdelay;
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);// 按下左键
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);// 松开左键
amount = amount + 1;// 计数器
System.out.print("-" + rdelay);
gui.information.setText("NOW: " + rdelay + " ms");
robot.delay(rdelay);// 间隔时间, 使用上面获得的随机数\
} else if (pbi != 0 && pbi <= probability) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);// 按下左键
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);// 松开左键
amount = amount + 1;// 计数器
System.out.print("-" + np);
gui.information.setText("NOW: " + np + " ms");
robot.delay(np);// 间隔时间, 使用上面获得的随机数
}
}
}
public static void cstop() {
for (; sors; sors = false) {gui.information.setText("关闭中");}
gui.information.setText("此次共点击 " + amount + " 下");
System.out.println("\n此次共点击 " + amount + " 下");
System.out.println("---------");
amount = 0;// 计数器清零
}
} | ObcbO/Click | src/crot.java | 663 | // 计数器清零 | line_comment | zh-cn | import java.awt.Robot;
import java.util.Random;
import java.awt.AWTException;
import java.awt.event.InputEvent;
public class crot extends Thread {
static boolean first = true; // 控制 开/关
static boolean sors = false; // 控制 开/关
static int smax;
static int smin;
static int np;
static int probability;
static int amount = 0;
static Robot robot;
public static void cstart(int imax, int imin, int aprobability) throws InterruptedException {
System.out.println("---------");
System.out.println("max " + imax + "ms");
System.out.println("min " + imin + "ms");
System.out.println("ChangeProbability " + (100 - aprobability) + "%");
smax = imax;
smin = imin;
probability = aprobability;
sors = true;
if (first) {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
first = false;
}
Random r = new Random();
while (sors) {
int pbi = r.nextInt(101) + 1;
if (pbi != 0 && pbi > probability) {
int rdelay = r.nextInt(smin - smax) + smax;// 最大值为smin 最小值为smax 之间的随机数
np = rdelay;
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);// 按下左键
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);// 松开左键
amount = amount + 1;// 计数器
System.out.print("-" + rdelay);
gui.information.setText("NOW: " + rdelay + " ms");
robot.delay(rdelay);// 间隔时间, 使用上面获得的随机数\
} else if (pbi != 0 && pbi <= probability) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);// 按下左键
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);// 松开左键
amount = amount + 1;// 计数器
System.out.print("-" + np);
gui.information.setText("NOW: " + np + " ms");
robot.delay(np);// 间隔时间, 使用上面获得的随机数
}
}
}
public static void cstop() {
for (; sors; sors = false) {gui.information.setText("关闭中");}
gui.information.setText("此次共点击 " + amount + " 下");
System.out.println("\n此次共点击 " + amount + " 下");
System.out.println("---------");
amount = 0;// 计数 <SUF>
}
} | false | 606 | 7 | 663 | 7 | 696 | 6 | 663 | 7 | 820 | 9 | false | false | false | false | false | true |
48513_3 | // 猜拳
import java.util.Scanner;
import java.util.Random;
class FingerFlashing {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
Random rand = new Random();
String[] hands = {"石头", "剪刀", "布"};
int retry; // 再来一次吗?
do {
// 生成0, 1, 2的随机数,作为计算机的手势
int comp = rand.nextInt(3);
// 读入玩家的手势0, 1, 2
int user;
do {
System.out.print("石头剪刀布");
for (int i = 0; i < 3; i++)
System.out.printf("(%d)%s ", i, hands[i]);
System.out.print(":");
user = stdIn.nextInt();
} while (user < 0 || user > 2);
// 显示双方的手势
System.out.println("我出" + hands[comp] + ",你出" +
hands[user] + "。");
// 判断
int judge = (user - comp + 3) % 3;
switch (judge) {
case 0: System.out.println("平局。"); break;
case 1: System.out.println("你输了。"); break;
case 2: System.out.println("你赢了。"); break;
}
// 确认是否再来一次
do {
System.out.print("再来一次? (0)否 (1)是:");
retry = stdIn.nextInt();
} while (retry != 0 && retry != 1);
} while (retry == 1);
}
}
| OctopusLian/MingJieJava | Chap15/FingerFlashing.java | 452 | // 显示双方的手势 | line_comment | zh-cn | // 猜拳
import java.util.Scanner;
import java.util.Random;
class FingerFlashing {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
Random rand = new Random();
String[] hands = {"石头", "剪刀", "布"};
int retry; // 再来一次吗?
do {
// 生成0, 1, 2的随机数,作为计算机的手势
int comp = rand.nextInt(3);
// 读入玩家的手势0, 1, 2
int user;
do {
System.out.print("石头剪刀布");
for (int i = 0; i < 3; i++)
System.out.printf("(%d)%s ", i, hands[i]);
System.out.print(":");
user = stdIn.nextInt();
} while (user < 0 || user > 2);
// 显示 <SUF>
System.out.println("我出" + hands[comp] + ",你出" +
hands[user] + "。");
// 判断
int judge = (user - comp + 3) % 3;
switch (judge) {
case 0: System.out.println("平局。"); break;
case 1: System.out.println("你输了。"); break;
case 2: System.out.println("你赢了。"); break;
}
// 确认是否再来一次
do {
System.out.print("再来一次? (0)否 (1)是:");
retry = stdIn.nextInt();
} while (retry != 0 && retry != 1);
} while (retry == 1);
}
}
| false | 386 | 6 | 452 | 8 | 432 | 5 | 452 | 8 | 586 | 11 | false | false | false | false | false | true |
41471_7 | package com.online.taxi.constatnt;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 功能描述
*
* @author yueyi2019
* @date 2018/9/1
*/
@Getter
@AllArgsConstructor
public enum OrderStatusEnum implements CodeEnum {
/**
* 预估订单
*/
CALL_ORDER_FORECAST(0,"预估订单"),
/**
* 订单开始
*/
STATUS_ORDER_START(1, "订单开始"),
/**
* 司机接单
*/
STATUS_DRIVER_ACCEPT(2, "司机接单"),
/**
* 去接乘客
*/
STATUS_RESERVED_ORDER_TO_PICK_UP(3, "去接乘客"),
/**
* 司机到达乘客起点
*/
STATUS_DRIVER_ARRIVED(4, "司机到达乘客起点"),
/**
* 乘客上车,司机开始行程
*/
STATUS_DRIVER_TRAVEL_START(5, "乘客上车,司机开始行程"),
/**
* 到达目的地,行程结束,未支付
*/
STATUS_DRIVER_TRAVEL_END(6, "到达目的地,行程结束,未支付"),
/**
* 发起收款
*/
STATUS_PAY_START(7, "发起收款"),
/**
* 支付完成
*/
STATUS_PAY_END(8, "支付完成");
private int code;
private String value;
}
| OiPunk/OnlineTaxi | online-taxi/online-taxi-common/src/main/java/com/online/taxi/common/constatnt/OrderStatusEnum.java | 371 | /**
* 到达目的地,行程结束,未支付
*/ | block_comment | zh-cn | package com.online.taxi.constatnt;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 功能描述
*
* @author yueyi2019
* @date 2018/9/1
*/
@Getter
@AllArgsConstructor
public enum OrderStatusEnum implements CodeEnum {
/**
* 预估订单
*/
CALL_ORDER_FORECAST(0,"预估订单"),
/**
* 订单开始
*/
STATUS_ORDER_START(1, "订单开始"),
/**
* 司机接单
*/
STATUS_DRIVER_ACCEPT(2, "司机接单"),
/**
* 去接乘客
*/
STATUS_RESERVED_ORDER_TO_PICK_UP(3, "去接乘客"),
/**
* 司机到达乘客起点
*/
STATUS_DRIVER_ARRIVED(4, "司机到达乘客起点"),
/**
* 乘客上车,司机开始行程
*/
STATUS_DRIVER_TRAVEL_START(5, "乘客上车,司机开始行程"),
/**
* 到达目 <SUF>*/
STATUS_DRIVER_TRAVEL_END(6, "到达目的地,行程结束,未支付"),
/**
* 发起收款
*/
STATUS_PAY_START(7, "发起收款"),
/**
* 支付完成
*/
STATUS_PAY_END(8, "支付完成");
private int code;
private String value;
}
| false | 309 | 16 | 371 | 17 | 366 | 16 | 371 | 17 | 516 | 24 | false | false | false | false | false | true |
59496_9 | package com.model;
/**
* 教练
* @author Administrator
*
*/
public class Coach implements java.io.Serializable{
private static final long serialVersionUID = 1L;
/**编号*/
private int id;
/** 头像*/
private String url;
/** 账号*/
private String uname;
/** 密码*/
private String upwd;
/**姓名*/
private String name;
/**性别*/
private String sex;
/**性别*/
private String age;
/**电话*/
private String tel;
/**专业特长*/
private String zhuanye;
/** 状态0无权限 1 有权限*/
private Integer state;
public Coach() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getZhuanye() {
return zhuanye;
}
public void setZhuanye(String zhuanye) {
this.zhuanye = zhuanye;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}
| OlvasdNight/jsfgl | src/com/model/Coach.java | 596 | /**专业特长*/ | block_comment | zh-cn | package com.model;
/**
* 教练
* @author Administrator
*
*/
public class Coach implements java.io.Serializable{
private static final long serialVersionUID = 1L;
/**编号*/
private int id;
/** 头像*/
private String url;
/** 账号*/
private String uname;
/** 密码*/
private String upwd;
/**姓名*/
private String name;
/**性别*/
private String sex;
/**性别*/
private String age;
/**电话*/
private String tel;
/**专业特 <SUF>*/
private String zhuanye;
/** 状态0无权限 1 有权限*/
private Integer state;
public Coach() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getZhuanye() {
return zhuanye;
}
public void setZhuanye(String zhuanye) {
this.zhuanye = zhuanye;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}
| false | 445 | 4 | 596 | 6 | 583 | 5 | 596 | 6 | 718 | 6 | false | false | false | false | false | true |
13210_16 | package com.cins.daily.common;
/**
* Created by Eric on 2017/1/16.
*/
public class ApiConstants {
public static final String NETEAST_HOST = "http://c.m.163.com/";
public static final String END_URL = "-20.html";
public static final String ENDDETAIL_URL = "/full.html";
// 新闻详情
public static final String NEWS_DETAIL = NETEAST_HOST + "nc/article/";
// 头条TYPE
public static final String HEADLINE_TYPE = "headline";
// 房产TYPE
public static final String HOUSE_TYPE = "house";
// 其他TYPE
public static final String OTHER_TYPE = "list";
// // 北京
// public static final String LOCAL_TYPE = "local";
// // 北京的Id
// public static final String BEIJING_ID = "5YyX5Lqs";
// 头条id
public static final String HEADLINE_ID = "T1348647909107";
// 房产id
public static final String HOUSE_ID = "5YyX5Lqs";
// 足球
public static final String FOOTBALL_ID = "T1399700447917";
// 娱乐
public static final String ENTERTAINMENT_ID = "T1348648517839";
// 体育
public static final String SPORTS_ID = "T1348649079062";
// 财经
public static final String FINANCE_ID = "T1348648756099";
// 科技
public static final String TECH_ID = "T1348649580692";
// 电影
public static final String MOVIE_ID = "T1348648650048";
// 汽车
public static final String CAR_ID = "T1348654060988";
// 笑话
public static final String JOKE_ID = "T1350383429665";
// 游戏
public static final String GAME_ID = "T1348654151579";
// 时尚
public static final String FASHION_ID = "T1348650593803";
// 情感
public static final String EMOTION_ID = "T1348650839000";
// 精选
public static final String CHOICE_ID = "T1370583240249";
// 电台
public static final String RADIO_ID = "T1379038288239";
// nba
public static final String NBA_ID = "T1348649145984";
// 数码
public static final String DIGITAL_ID = "T1348649776727";
// 移动
public static final String MOBILE_ID = "T1351233117091";
// 彩票
public static final String LOTTERY_ID = "T1356600029035";
// 教育
public static final String EDUCATION_ID = "T1348654225495";
// 论坛
public static final String FORUM_ID = "T1349837670307";
// 旅游
public static final String TOUR_ID = "T1348654204705";
// 手机
public static final String PHONE_ID = "T1348649654285";
// 博客
public static final String BLOG_ID = "T1349837698345";
// 社会
public static final String SOCIETY_ID = "T1348648037603";
// 家居
public static final String FURNISHING_ID = "T1348654105308";
// 暴雪游戏
public static final String BLIZZARD_ID = "T1397016069906";
// 亲子
public static final String PATERNITY_ID = "T1397116135282";
// CBA
public static final String CBA_ID = "T1348649475931";
// 消息
public static final String MSG_ID = "T1371543208049";
// 军事
public static final String MILITARY_ID = "T1348648141035";
/**
* 视频 http://c.3g.163.com/nc/video/list/V9LG4B3A0/n/10-10.html
*/
public static final String Video = "nc/video/list/";
public static final String VIDEO_CENTER = "/n/";
public static final String VIDEO_END_URL = "-10.html";
// 热点视频
public static final String VIDEO_HOT_ID = "V9LG4B3A0";
// 娱乐视频
public static final String VIDEO_ENTERTAINMENT_ID = "V9LG4CHOR";
// 搞笑视频
public static final String VIDEO_FUN_ID = "V9LG4E6VR";
// 精品视频
public static final String VIDEO_CHOICE_ID = "00850FRB";
/**
* 天气预报url
*/
public static final String WEATHER_HOST = "http://wthrcdn.etouch.cn/";
/**
* 新浪图片新闻
*/
public static final String SINA_PHOTO_HOST = "http://gank.io/api/";
// 精选列表
public static final String SINA_PHOTO_CHOICE_ID = "hdpic_toutiao";
// 趣图列表
public static final String SINA_PHOTO_FUN_ID = "hdpic_funny";
// 美图列表
public static final String SINA_PHOTO_PRETTY_ID = "hdpic_pretty";
// 故事列表
public static final String SINA_PHOTO_STORY_ID = "hdpic_story";
// 图片详情
public static final String SINA_PHOTO_DETAIL_ID = "hdpic_hdpic_toutiao_4";
/**
* 新闻id获取类型
*
* @param id 新闻id
* @return 新闻类型
*/
public static String getType(String id) {
switch (id) {
case HEADLINE_ID:
return HEADLINE_TYPE;
case HOUSE_ID:
return HOUSE_TYPE;
default:
break;
}
return OTHER_TYPE;
}
/**
* 获取对应的host
*
* @param hostType host类型
* @return host
*/
public static String getHost(int hostType) {
String host;
switch (hostType) {
case HostType.NETEASE_NEWS_VIDEO:
host = NETEAST_HOST;
break;
case HostType.GANK_GIRL_PHOTO:
host = SINA_PHOTO_HOST;
break;
case HostType.NEWS_DETAIL_HTML_PHOTO:
host = "http://kaku.com/";
break;
default:
host = "";
break;
}
return host;
}
}
| Omiknight/Daily | app/src/main/java/com/cins/daily/common/ApiConstants.java | 1,873 | // 娱乐视频 | line_comment | zh-cn | package com.cins.daily.common;
/**
* Created by Eric on 2017/1/16.
*/
public class ApiConstants {
public static final String NETEAST_HOST = "http://c.m.163.com/";
public static final String END_URL = "-20.html";
public static final String ENDDETAIL_URL = "/full.html";
// 新闻详情
public static final String NEWS_DETAIL = NETEAST_HOST + "nc/article/";
// 头条TYPE
public static final String HEADLINE_TYPE = "headline";
// 房产TYPE
public static final String HOUSE_TYPE = "house";
// 其他TYPE
public static final String OTHER_TYPE = "list";
// // 北京
// public static final String LOCAL_TYPE = "local";
// // 北京的Id
// public static final String BEIJING_ID = "5YyX5Lqs";
// 头条id
public static final String HEADLINE_ID = "T1348647909107";
// 房产id
public static final String HOUSE_ID = "5YyX5Lqs";
// 足球
public static final String FOOTBALL_ID = "T1399700447917";
// 娱乐
public static final String ENTERTAINMENT_ID = "T1348648517839";
// 体育
public static final String SPORTS_ID = "T1348649079062";
// 财经
public static final String FINANCE_ID = "T1348648756099";
// 科技
public static final String TECH_ID = "T1348649580692";
// 电影
public static final String MOVIE_ID = "T1348648650048";
// 汽车
public static final String CAR_ID = "T1348654060988";
// 笑话
public static final String JOKE_ID = "T1350383429665";
// 游戏
public static final String GAME_ID = "T1348654151579";
// 时尚
public static final String FASHION_ID = "T1348650593803";
// 情感
public static final String EMOTION_ID = "T1348650839000";
// 精选
public static final String CHOICE_ID = "T1370583240249";
// 电台
public static final String RADIO_ID = "T1379038288239";
// nba
public static final String NBA_ID = "T1348649145984";
// 数码
public static final String DIGITAL_ID = "T1348649776727";
// 移动
public static final String MOBILE_ID = "T1351233117091";
// 彩票
public static final String LOTTERY_ID = "T1356600029035";
// 教育
public static final String EDUCATION_ID = "T1348654225495";
// 论坛
public static final String FORUM_ID = "T1349837670307";
// 旅游
public static final String TOUR_ID = "T1348654204705";
// 手机
public static final String PHONE_ID = "T1348649654285";
// 博客
public static final String BLOG_ID = "T1349837698345";
// 社会
public static final String SOCIETY_ID = "T1348648037603";
// 家居
public static final String FURNISHING_ID = "T1348654105308";
// 暴雪游戏
public static final String BLIZZARD_ID = "T1397016069906";
// 亲子
public static final String PATERNITY_ID = "T1397116135282";
// CBA
public static final String CBA_ID = "T1348649475931";
// 消息
public static final String MSG_ID = "T1371543208049";
// 军事
public static final String MILITARY_ID = "T1348648141035";
/**
* 视频 http://c.3g.163.com/nc/video/list/V9LG4B3A0/n/10-10.html
*/
public static final String Video = "nc/video/list/";
public static final String VIDEO_CENTER = "/n/";
public static final String VIDEO_END_URL = "-10.html";
// 热点视频
public static final String VIDEO_HOT_ID = "V9LG4B3A0";
// 娱乐 <SUF>
public static final String VIDEO_ENTERTAINMENT_ID = "V9LG4CHOR";
// 搞笑视频
public static final String VIDEO_FUN_ID = "V9LG4E6VR";
// 精品视频
public static final String VIDEO_CHOICE_ID = "00850FRB";
/**
* 天气预报url
*/
public static final String WEATHER_HOST = "http://wthrcdn.etouch.cn/";
/**
* 新浪图片新闻
*/
public static final String SINA_PHOTO_HOST = "http://gank.io/api/";
// 精选列表
public static final String SINA_PHOTO_CHOICE_ID = "hdpic_toutiao";
// 趣图列表
public static final String SINA_PHOTO_FUN_ID = "hdpic_funny";
// 美图列表
public static final String SINA_PHOTO_PRETTY_ID = "hdpic_pretty";
// 故事列表
public static final String SINA_PHOTO_STORY_ID = "hdpic_story";
// 图片详情
public static final String SINA_PHOTO_DETAIL_ID = "hdpic_hdpic_toutiao_4";
/**
* 新闻id获取类型
*
* @param id 新闻id
* @return 新闻类型
*/
public static String getType(String id) {
switch (id) {
case HEADLINE_ID:
return HEADLINE_TYPE;
case HOUSE_ID:
return HOUSE_TYPE;
default:
break;
}
return OTHER_TYPE;
}
/**
* 获取对应的host
*
* @param hostType host类型
* @return host
*/
public static String getHost(int hostType) {
String host;
switch (hostType) {
case HostType.NETEASE_NEWS_VIDEO:
host = NETEAST_HOST;
break;
case HostType.GANK_GIRL_PHOTO:
host = SINA_PHOTO_HOST;
break;
case HostType.NEWS_DETAIL_HTML_PHOTO:
host = "http://kaku.com/";
break;
default:
host = "";
break;
}
return host;
}
}
| false | 1,766 | 6 | 1,873 | 6 | 1,866 | 4 | 1,873 | 6 | 2,231 | 10 | false | false | false | false | false | true |
8774_2 | package com.ruoyi.simulation.config;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.simulation.call.CallPaddleSpeech;
import com.ruoyi.simulation.call.CallUE4Engine;
import com.ruoyi.simulation.call.CallWizardCoder;
import com.ruoyi.simulation.util.*;
import com.ruoyi.simulation.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
@Component
public class ProcessCommandListener implements ApplicationListener<ApplicationStartedEvent> {
private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
public static final LinkedBlockingQueue<VoiceUtil> readingQueue = new LinkedBlockingQueue<VoiceUtil>(5);
@Resource
private ProcessOperationUtil processUtil;
@Resource
private CallWizardCoder callWizardCoder;
@Resource
private CallUE4Engine callUE4Engine;
@Resource
RedisTemplate<Object, Object> redisTemplate;
@Override
public void onApplicationEvent(ApplicationStartedEvent e) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
processCommand();
}
}
});
thread.start();
}
/**
* 处理语音请求
*/
private void processCommand() {
String sessionId = null;
try {
//从队列中去除元素,若队列为空,则阻塞
logger.info("语音队列长度:"+WebSocketServer.commandQueue.size());
ElementUtil element = WebSocketServer.commandQueue.take();
String command = element.getCommand();
sessionId = element.getSessionId();
//判断是否只是提问
if(!answer(command,sessionId)){
return;
}
SendResponseUtil.sendHandleResponse(command, sessionId);
//第二步,发送文字命令,调用“大模型”获取生成交通场景模型所需的代码
long start = System.currentTimeMillis();
List<String> codeList = this.callWizardCoder.generateCode(command);
String codeStr = ListUtil.toString(codeList);
logger.info("调用WizardCoder生成代码如下:\n" + codeStr);
long end = System.currentTimeMillis();
logger.info("调用WizardCoder耗费时间:" + (end-start));
start = System.currentTimeMillis();
//根据指令以及进程id杀死指定进程
processUtil.killProcess(codeStr);
end = System.currentTimeMillis();
logger.info("杀死互斥进程耗费时间:" + (end-start));
//第三步,调用“UE4”渲染三维效果像素流
codeStr = this.executeCommand(codeStr,sessionId);
SendResponseUtil.sendFinalResponse(codeStr, sessionId);
} catch (Exception e) {
LoggerUtil.printLoggerStace(e);
if(!StringUtils.isEmpty(sessionId)){
SendResponseUtil.sendErrorResponse(e, sessionId);
}
}
}
/**
* 执行附加进程
* @param codeStr
*/
private String executeCommand(String codeStr, String sessionId) {
Set<String> commandList = WebSocketServer.webSocketCommandMap.get(sessionId);
//当第二次进入相应场景时,则不隐藏建筑
if(codeStr.contains("get_maps.py --mapname")){
String mapName = codeStr.replace("get_maps.py --mapname","").trim();
if(commandList.contains(mapName+" get_buildings.py")){
codeStr = codeStr.replace("get_maps.py","get_mapsfast.py");
}
}
//记录下每个场景的添加建筑命令
if(StringUtils.equals(codeStr,"get_buildings.py")){
String mapName = this.callWizardCoder.getMapName("get_mapname.py");
if(!StringUtils.isEmpty(mapName)&&mapName.contains("/")){
mapName = mapName.substring(mapName.lastIndexOf("/")+1);
}
commandList.add(mapName+" get_buildings.py");
}
//执行驾驶进程
if(StringUtils.equals(codeStr, "control_steeringwheel.py")||StringUtils.equals(codeStr, "automatic_control_steeringwheel.py")
||StringUtils.equals(codeStr,"automatic_control_revised.py")){
codeStr = "Carla_control_G29.py";
}
if(codeStr.contains("generate_traffic.py --number-of-vehicles")){
int add = Integer.parseInt(codeStr.replace("generate_traffic.py --number-of-vehicles","").trim());
int count = 0;
if(WebSocketServer.carCountMap.containsKey(sessionId)){
count = WebSocketServer.carCountMap.get(sessionId);
}
WebSocketServer.carCountMap.put(sessionId, count+add);
}
logger.info(codeStr);
this.callWizardCoder.executeExample(codeStr);
return codeStr;
}
/**
* 判断是否为问答
* @param text
* @return
* @throws InterruptedException
*/
public boolean answer(String text, String sessionId) {
if((text.contains("做什么")||text.contains("干什么")||text.contains("有什么"))&&text.contains("大模型")){
String message = "我是智慧交通大模型,能生成交通的三维数字孪生场景,譬如生成汽车、人,安装摄像头、交通信号灯,也能生成导航路线以进行直观浏览、开展自动路线调度。还能根据突发事件和应急预案,进行可视化调度等。要不请您来试用一下我的功能吧!";
SendResponseUtil.sendDialogueResponse(message, sessionId);
return false;
}
return true;
}
}
| OpenHUTB/intelligent_traffic | ruoyi-simulation/src/main/java/com/ruoyi/simulation/config/ProcessCommandListener.java | 1,418 | //判断是否只是提问 | line_comment | zh-cn | package com.ruoyi.simulation.config;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.simulation.call.CallPaddleSpeech;
import com.ruoyi.simulation.call.CallUE4Engine;
import com.ruoyi.simulation.call.CallWizardCoder;
import com.ruoyi.simulation.util.*;
import com.ruoyi.simulation.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
@Component
public class ProcessCommandListener implements ApplicationListener<ApplicationStartedEvent> {
private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
public static final LinkedBlockingQueue<VoiceUtil> readingQueue = new LinkedBlockingQueue<VoiceUtil>(5);
@Resource
private ProcessOperationUtil processUtil;
@Resource
private CallWizardCoder callWizardCoder;
@Resource
private CallUE4Engine callUE4Engine;
@Resource
RedisTemplate<Object, Object> redisTemplate;
@Override
public void onApplicationEvent(ApplicationStartedEvent e) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
processCommand();
}
}
});
thread.start();
}
/**
* 处理语音请求
*/
private void processCommand() {
String sessionId = null;
try {
//从队列中去除元素,若队列为空,则阻塞
logger.info("语音队列长度:"+WebSocketServer.commandQueue.size());
ElementUtil element = WebSocketServer.commandQueue.take();
String command = element.getCommand();
sessionId = element.getSessionId();
//判断 <SUF>
if(!answer(command,sessionId)){
return;
}
SendResponseUtil.sendHandleResponse(command, sessionId);
//第二步,发送文字命令,调用“大模型”获取生成交通场景模型所需的代码
long start = System.currentTimeMillis();
List<String> codeList = this.callWizardCoder.generateCode(command);
String codeStr = ListUtil.toString(codeList);
logger.info("调用WizardCoder生成代码如下:\n" + codeStr);
long end = System.currentTimeMillis();
logger.info("调用WizardCoder耗费时间:" + (end-start));
start = System.currentTimeMillis();
//根据指令以及进程id杀死指定进程
processUtil.killProcess(codeStr);
end = System.currentTimeMillis();
logger.info("杀死互斥进程耗费时间:" + (end-start));
//第三步,调用“UE4”渲染三维效果像素流
codeStr = this.executeCommand(codeStr,sessionId);
SendResponseUtil.sendFinalResponse(codeStr, sessionId);
} catch (Exception e) {
LoggerUtil.printLoggerStace(e);
if(!StringUtils.isEmpty(sessionId)){
SendResponseUtil.sendErrorResponse(e, sessionId);
}
}
}
/**
* 执行附加进程
* @param codeStr
*/
private String executeCommand(String codeStr, String sessionId) {
Set<String> commandList = WebSocketServer.webSocketCommandMap.get(sessionId);
//当第二次进入相应场景时,则不隐藏建筑
if(codeStr.contains("get_maps.py --mapname")){
String mapName = codeStr.replace("get_maps.py --mapname","").trim();
if(commandList.contains(mapName+" get_buildings.py")){
codeStr = codeStr.replace("get_maps.py","get_mapsfast.py");
}
}
//记录下每个场景的添加建筑命令
if(StringUtils.equals(codeStr,"get_buildings.py")){
String mapName = this.callWizardCoder.getMapName("get_mapname.py");
if(!StringUtils.isEmpty(mapName)&&mapName.contains("/")){
mapName = mapName.substring(mapName.lastIndexOf("/")+1);
}
commandList.add(mapName+" get_buildings.py");
}
//执行驾驶进程
if(StringUtils.equals(codeStr, "control_steeringwheel.py")||StringUtils.equals(codeStr, "automatic_control_steeringwheel.py")
||StringUtils.equals(codeStr,"automatic_control_revised.py")){
codeStr = "Carla_control_G29.py";
}
if(codeStr.contains("generate_traffic.py --number-of-vehicles")){
int add = Integer.parseInt(codeStr.replace("generate_traffic.py --number-of-vehicles","").trim());
int count = 0;
if(WebSocketServer.carCountMap.containsKey(sessionId)){
count = WebSocketServer.carCountMap.get(sessionId);
}
WebSocketServer.carCountMap.put(sessionId, count+add);
}
logger.info(codeStr);
this.callWizardCoder.executeExample(codeStr);
return codeStr;
}
/**
* 判断是否为问答
* @param text
* @return
* @throws InterruptedException
*/
public boolean answer(String text, String sessionId) {
if((text.contains("做什么")||text.contains("干什么")||text.contains("有什么"))&&text.contains("大模型")){
String message = "我是智慧交通大模型,能生成交通的三维数字孪生场景,譬如生成汽车、人,安装摄像头、交通信号灯,也能生成导航路线以进行直观浏览、开展自动路线调度。还能根据突发事件和应急预案,进行可视化调度等。要不请您来试用一下我的功能吧!";
SendResponseUtil.sendDialogueResponse(message, sessionId);
return false;
}
return true;
}
}
| false | 1,190 | 5 | 1,418 | 6 | 1,467 | 5 | 1,418 | 6 | 1,822 | 9 | false | false | false | false | false | true |
66246_36 | package org.openokr.manage.vo;
import com.zzheng.framework.base.vo.BaseVO;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class ObjectivesVO extends BaseVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private String id;
/**
* 时间段id
*/
private String timeSessionId;
/**
* 名称
*/
private String name;
/**
* 描述
*/
private String description;
/**
* 负责人id
*/
private String ownerId;
/**
* 父目标
*/
private String parentId;
/**
* 信心指数
*/
private String confidenceLevel;
/**
* 公开类型 1-公开 2-团队公开 3-保密
*/
private String visibility;
/**
* 类型 1-个人 2-团队 3-公司
*/
private String type;
/**
* 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回
*/
private String status;
/**
* 删除标识 0-否 1-是
*/
private String delFlag;
/**
* 当前进度(百分比)
*/
private BigDecimal progress;
/**
* 评分(季度结束的时候要对O的完成情况进行评分和自评)
*/
private String score;
/**
* 评分说明(季度结束的时候要对O的完成情况进行评分和自评)
*/
private String assessment;
/**
* 创建时间
*/
private Date createTs;
/**
* 创建者
*/
private String createUserId;
/**
* 更新时间
*/
private Date updateTs;
/**
* 更新者
*/
private String updateUserId;
/**
* 团队ID(type为团队和公司的时候才存储)
*/
private String teamId;
/**
* 排序
*/
private Integer sort;
/**
* 主键
*/
public String getId() {
return id;
}
/**
* 主键
*/
public void setId(String id) {
this.id = id;
}
/**
* 时间段id
*/
public String getTimeSessionId() {
return timeSessionId;
}
/**
* 时间段id
*/
public void setTimeSessionId(String timeSessionId) {
this.timeSessionId = timeSessionId;
}
/**
* 名称
*/
public String getName() {
return name;
}
/**
* 名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 描述
*/
public String getDescription() {
return description;
}
/**
* 描述
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 负责人id
*/
public String getOwnerId() {
return ownerId;
}
/**
* 负责人id
*/
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
/**
* 父目标
*/
public String getParentId() {
return parentId;
}
/**
* 父目标
*/
public void setParentId(String parentId) {
this.parentId = parentId;
}
/**
* 信心指数
*/
public String getConfidenceLevel() {
return confidenceLevel;
}
/**
* 信心指数
*/
public void setConfidenceLevel(String confidenceLevel) {
this.confidenceLevel = confidenceLevel;
}
/**
* 公开类型 1-公开 2-团队公开 3-保密
*/
public String getVisibility() {
return visibility;
}
/**
* 公开类型 1-公开 2-团队公开 3-保密
*/
public void setVisibility(String visibility) {
this.visibility = visibility;
}
/**
* 类型 1-个人 2-团队 3-公司
*/
public String getType() {
return type;
}
/**
* 类型 1-个人 2-团队 3-公司
*/
public void setType(String type) {
this.type = type;
}
/**
* 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回
*/
public String getStatus() {
return status;
}
/**
* 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回
*/
public void setStatus(String status) {
this.status = status;
}
/**
* 删除标识 0-否 1-是
*/
public String getDelFlag() {
return delFlag;
}
/**
* 删除标识 0-否 1-是
*/
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
/**
* 当前进度(百分比)
*/
public BigDecimal getProgress() {
return progress;
}
/**
* 当前进度(百分比)
*/
public void setProgress(BigDecimal progress) {
this.progress = progress;
}
/**
* 评分(季度结束的时候要对O的完成情况进行评分和自评)
*/
public String getScore() {
return score;
}
/**
* 评分(季度结束的时候要对O的完成情况进行评分和自评)
*/
public void setScore(String score) {
this.score = score;
}
/**
* 评分说明(季度结束的时候要对O的完成情况进行评分和自评)
*/
public String getAssessment() {
return assessment;
}
/**
* 评分说明(季度结束的时候要对O的完成情况进行评分和自评)
*/
public void setAssessment(String assessment) {
this.assessment = assessment;
}
/**
* 创建时间
*/
public Date getCreateTs() {
return createTs;
}
/**
* 创建时间
*/
public void setCreateTs(Date createTs) {
this.createTs = createTs;
}
/**
* 创建者
*/
public String getCreateUserId() {
return createUserId;
}
/**
* 创建者
*/
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
/**
* 更新时间
*/
public Date getUpdateTs() {
return updateTs;
}
/**
* 更新时间
*/
public void setUpdateTs(Date updateTs) {
this.updateTs = updateTs;
}
/**
* 更新者
*/
public String getUpdateUserId() {
return updateUserId;
}
/**
* 更新者
*/
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
/**
* 团队ID(type为团队和公司的时候才存储)
*/
public String getTeamId() {
return teamId;
}
/**
* 团队ID(type为团队和公司的时候才存储)
*/
public void setTeamId(String teamId) {
this.teamId = teamId;
}
/**
* 排序
*/
public Integer getSort() {
return sort;
}
/**
* 排序
*/
public void setSort(Integer sort) {
this.sort = sort;
}
} | OpenOKR/OpenOKR | okr-api/src/main/java/org/openokr/manage/vo/ObjectivesVO.java | 1,752 | /**
* 类型 1-个人 2-团队 3-公司
*/ | block_comment | zh-cn | package org.openokr.manage.vo;
import com.zzheng.framework.base.vo.BaseVO;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class ObjectivesVO extends BaseVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private String id;
/**
* 时间段id
*/
private String timeSessionId;
/**
* 名称
*/
private String name;
/**
* 描述
*/
private String description;
/**
* 负责人id
*/
private String ownerId;
/**
* 父目标
*/
private String parentId;
/**
* 信心指数
*/
private String confidenceLevel;
/**
* 公开类型 1-公开 2-团队公开 3-保密
*/
private String visibility;
/**
* 类型 1-个人 2-团队 3-公司
*/
private String type;
/**
* 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回
*/
private String status;
/**
* 删除标识 0-否 1-是
*/
private String delFlag;
/**
* 当前进度(百分比)
*/
private BigDecimal progress;
/**
* 评分(季度结束的时候要对O的完成情况进行评分和自评)
*/
private String score;
/**
* 评分说明(季度结束的时候要对O的完成情况进行评分和自评)
*/
private String assessment;
/**
* 创建时间
*/
private Date createTs;
/**
* 创建者
*/
private String createUserId;
/**
* 更新时间
*/
private Date updateTs;
/**
* 更新者
*/
private String updateUserId;
/**
* 团队ID(type为团队和公司的时候才存储)
*/
private String teamId;
/**
* 排序
*/
private Integer sort;
/**
* 主键
*/
public String getId() {
return id;
}
/**
* 主键
*/
public void setId(String id) {
this.id = id;
}
/**
* 时间段id
*/
public String getTimeSessionId() {
return timeSessionId;
}
/**
* 时间段id
*/
public void setTimeSessionId(String timeSessionId) {
this.timeSessionId = timeSessionId;
}
/**
* 名称
*/
public String getName() {
return name;
}
/**
* 名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 描述
*/
public String getDescription() {
return description;
}
/**
* 描述
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 负责人id
*/
public String getOwnerId() {
return ownerId;
}
/**
* 负责人id
*/
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
/**
* 父目标
*/
public String getParentId() {
return parentId;
}
/**
* 父目标
*/
public void setParentId(String parentId) {
this.parentId = parentId;
}
/**
* 信心指数
*/
public String getConfidenceLevel() {
return confidenceLevel;
}
/**
* 信心指数
*/
public void setConfidenceLevel(String confidenceLevel) {
this.confidenceLevel = confidenceLevel;
}
/**
* 公开类型 1-公开 2-团队公开 3-保密
*/
public String getVisibility() {
return visibility;
}
/**
* 公开类型 1-公开 2-团队公开 3-保密
*/
public void setVisibility(String visibility) {
this.visibility = visibility;
}
/**
* 类型 <SUF>*/
public String getType() {
return type;
}
/**
* 类型 1-个人 2-团队 3-公司
*/
public void setType(String type) {
this.type = type;
}
/**
* 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回
*/
public String getStatus() {
return status;
}
/**
* 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回
*/
public void setStatus(String status) {
this.status = status;
}
/**
* 删除标识 0-否 1-是
*/
public String getDelFlag() {
return delFlag;
}
/**
* 删除标识 0-否 1-是
*/
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
/**
* 当前进度(百分比)
*/
public BigDecimal getProgress() {
return progress;
}
/**
* 当前进度(百分比)
*/
public void setProgress(BigDecimal progress) {
this.progress = progress;
}
/**
* 评分(季度结束的时候要对O的完成情况进行评分和自评)
*/
public String getScore() {
return score;
}
/**
* 评分(季度结束的时候要对O的完成情况进行评分和自评)
*/
public void setScore(String score) {
this.score = score;
}
/**
* 评分说明(季度结束的时候要对O的完成情况进行评分和自评)
*/
public String getAssessment() {
return assessment;
}
/**
* 评分说明(季度结束的时候要对O的完成情况进行评分和自评)
*/
public void setAssessment(String assessment) {
this.assessment = assessment;
}
/**
* 创建时间
*/
public Date getCreateTs() {
return createTs;
}
/**
* 创建时间
*/
public void setCreateTs(Date createTs) {
this.createTs = createTs;
}
/**
* 创建者
*/
public String getCreateUserId() {
return createUserId;
}
/**
* 创建者
*/
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
/**
* 更新时间
*/
public Date getUpdateTs() {
return updateTs;
}
/**
* 更新时间
*/
public void setUpdateTs(Date updateTs) {
this.updateTs = updateTs;
}
/**
* 更新者
*/
public String getUpdateUserId() {
return updateUserId;
}
/**
* 更新者
*/
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
/**
* 团队ID(type为团队和公司的时候才存储)
*/
public String getTeamId() {
return teamId;
}
/**
* 团队ID(type为团队和公司的时候才存储)
*/
public void setTeamId(String teamId) {
this.teamId = teamId;
}
/**
* 排序
*/
public Integer getSort() {
return sort;
}
/**
* 排序
*/
public void setSort(Integer sort) {
this.sort = sort;
}
} | false | 1,690 | 20 | 1,752 | 20 | 1,976 | 20 | 1,752 | 20 | 2,526 | 29 | false | false | false | false | false | true |
38116_15 | package com.optimalorange.cooltechnologies.network;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.optimalorange.cooltechnologies.entity.Video;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.support.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Zhou Peican on 2014/12/9.
*/
public class SearchRequest extends JsonRequest<List<Video>> {
private static final String YOUKU_API_JSON_VIDEOS_ATTRIBUTE_NAME = "videos";
public SearchRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<List<Video>> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest == null ? null : jsonRequest.toString(), listener,
errorListener);
}
@Override
protected Response<List<Video>> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray videosJson = jsonObject.getJSONArray(YOUKU_API_JSON_VIDEOS_ATTRIBUTE_NAME);
int length = videosJson.length();
List<Video> videos = new ArrayList<>(length);
for (int i = 0; i < length; i++) {
videos.add(new Video(videosJson.getJSONObject(i)));
}
return Response.success(videos,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
public static class Builder {
public static final String DEFAULT_CATEGORY_LABEL = "科技";
private static final int DEFAULT_TIMELESS = 0;
private static final int DEFAULT_TIMEMORE = 0;
private static final int YOUKU_API_REQUEST_METHOD = Request.Method.GET;
private static final String YOUKU_API_SEARCHES_VIDEOS_BY_KEYWORD
= "https://openapi.youku.com/v2/searches/video/by_keyword.json";
/**
* A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
*/
@Nullable
private JSONObject mJsonRequest;
/**
* Listener to receive the videos response
*/
private Response.Listener<List<Video>> mResponseListener;
/**
* Error listener, or null to ignore errors.
*/
@Nullable
private Response.ErrorListener mErrorListener;
/** 应用Key(必设) */
private String client_id;
/** 关键字 多个关键字用空格分隔(必设) */
private String keyword;
/**
* 分类<br />
* 示例:资讯
* 默认值:{@link #DEFAULT_CATEGORY_LABEL}
*/
@Nullable
private String category = DEFAULT_CATEGORY_LABEL;
/** 时间范围 */
@Nullable
private PERIOD period;
/** 排序 */
@Nullable
private ORDER_BY orderby;
/** 公开类型 all */
@Nullable
private PUBLIC_TYPE public_type;
/** 付费状态 付费 1 免费 0 */
@Nullable
private PAID paid;
/**
* 视频时长筛选:定义时长小 于几分钟(不包含),默认 0表示不筛选
*/
@Nullable
private int timeless = DEFAULT_TIMELESS;
/**
* 视频时长筛选:定义时长大 于等于几分钟(不包含)
*/
@Nullable
private int timemore = DEFAULT_TIMEMORE;
/**
* 格式筛选(逗号分隔,表示‘或’关系)
* | 1:mp4(高清) | 2:3gp | 1,2,3 3:H263FLV |
* 4:3GPHD | 5:H264FLV(FLV升级版h264) |
* 6:Hd2 720P(超清) |
*/
@Nullable
private STREAMTYPES streamtypes;
/**
* 页数<br />
* 示例:1
*/
@Nullable
private Integer page;
/**
* 页大小<br />
* 示例:20
*/
@Nullable
private Integer count;
/**
* 应用Key(必设参数)
*/
public Builder setClient_id(String client_id) {
this.client_id = client_id;
return this;
}
/**
* 关键字 多个关键字用空格分隔
*/
public Builder setKeyword(String keyword) {
this.keyword = keyword;
return this;
}
/**
* 分类<br />
* 示例:资讯
* 默认值:{@link #DEFAULT_CATEGORY_LABEL}
*/
public Builder setCategory(@Nullable String category) {
this.category = category;
return this;
}
/** 时间范围 */
public Builder setPeriod(@Nullable PERIOD period) {
this.period = period;
return this;
}
/** 排序 */
public Builder setOrderby(@Nullable ORDER_BY orderby) {
this.orderby = orderby;
return this;
}
/** 公开类型 */
public Builder setPublic_type(@Nullable PUBLIC_TYPE public_type) {
this.public_type = public_type;
return this;
}
/** 付费状态 */
public Builder setPaid(@Nullable PAID paid) {
this.paid = paid;
return this;
}
/** 视频时长筛选:定义时长小 于几分钟(不包含) */
public Builder setTimeless(@Nullable int timeLess) {
this.timeless = timeless;
return this;
}
/** 视频时长筛选:定义时长大 于等于几分钟(不包含) */
public Builder setTimemore(@Nullable int timemore) {
this.timemore = timemore;
return this;
}
/** 格式筛选 */
public Builder setStreamtypes(@Nullable STREAMTYPES streamtypes) {
this.streamtypes = streamtypes;
return this;
}
/**
* 页数<br />
* 示例:1
*/
public Builder setPage(@Nullable Integer page) {
this.page = page;
return this;
}
/**
* 页大小<br />
* 示例:20
*/
public Builder setCount(@Nullable Integer count) {
this.count = count;
return this;
}
/**
* A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
*/
public Builder setJsonRequest(@Nullable JSONObject jsonRequest) {
mJsonRequest = jsonRequest;
return this;
}
/**
* Listener to receive the videos response
*/
public Builder setResponseListener(Response.Listener<List<Video>> responseListener) {
mResponseListener = responseListener;
return this;
}
/**
* Error listener, or null to ignore errors.
*/
public Builder setErrorListener(@Nullable Response.ErrorListener errorListener) {
mErrorListener = errorListener;
return this;
}
public SearchRequest build() {
return new SearchRequest(
YOUKU_API_REQUEST_METHOD,
buildUrl(),
mJsonRequest,
mResponseListener,
mErrorListener
);
}
private String buildUrl() {
final Uri.Builder urlBuilder = Uri.parse(YOUKU_API_SEARCHES_VIDEOS_BY_KEYWORD)
.buildUpon();
if (client_id == null) {
throw new IllegalStateException("Please set client_id before build");
}
urlBuilder.appendQueryParameter("client_id", client_id);
if (keyword == null) {
throw new IllegalStateException("Please input keyword before build");
}
urlBuilder.appendQueryParameter("keyword", keyword);
if (category != null) {
urlBuilder.appendQueryParameter("category", category);
}
if (period != null) {
urlBuilder.appendQueryParameter("period", period.toString());
}
if (orderby != null) {
urlBuilder.appendQueryParameter("orderby", orderby.toString());
}
if (public_type != null) {
urlBuilder.appendQueryParameter("public_type", public_type.toString());
}
if (paid != null) {
urlBuilder.appendQueryParameter("paid", PAID.fromPaidType(paid));
}
if (timeless != 0) {
urlBuilder.appendQueryParameter("timeless", String.valueOf(timeless));
}
if (timemore != 0) {
urlBuilder.appendQueryParameter("timemore", String.valueOf(timemore));
}
if (streamtypes != null) {
urlBuilder.appendQueryParameter("streamtypes",
STREAMTYPES.fromStreamTypes(streamtypes));
}
if (page != null) {
urlBuilder.appendQueryParameter("page", page.toString());
}
if (count != null) {
urlBuilder.appendQueryParameter("count", count.toString());
}
return urlBuilder.build().toString();
}
/** 时间范围 */
public static enum PERIOD {
/** 今日 */
TODAY,
/** 本周 */
WEEK,
/** 本月 */
MONTH,
/** 历史 */
HISTORY;
public String toString() {
return name().toLowerCase(Locale.US);
}
}
/** 排序 */
public static enum ORDER_BY {
/** 发布时间 */
PUBLISHED,
/** 总播放数 */
VIEW_COUNT,
/** 总评论数 */
COMMENT_COUNT,
/** 总引用 */
REFERENCE_COUNT,
/** 总收藏数 */
FAVORITE_COUNT,
/** 相关度 */
RELEVANCE;
public String toString() {
return name().toLowerCase(Locale.US).replace('_', '-');
}
}
/** 公开类型 */
public static enum PUBLIC_TYPE {
/** 公开 */
ALL,
/** 仅好友观看 */
FRIEND,
/** 输入密码观看 */
PASSWORD;
@Override
public String toString() {
return name().toLowerCase(Locale.US);
}
}
/** 付费状态 */
public static enum PAID {
/** 免费 0 */
FREE,
/** 付费 1 */
PAY;
public static String fromPaidType(PAID paid) {
return String.valueOf(paid.ordinal());
}
}
/** 格式筛选 */
public static enum STREAMTYPES {
/** 1:mp4(高清) */
MP4,
/** 2:3gp */
_3GP,
/** 3:H263FLV */
H263FLV,
/** 4:3GPHD */
_3GPHD,
/** 5:H264FLV */
H264FLV,
/** 6:Hd2 */
Hd2;
public static String fromStreamTypes(STREAMTYPES streamtypes) {
return String.valueOf(streamtypes.ordinal() + 1);
}
}
}
}
| OptimalOrange/CoolTechnologies | app/src/main/java/com/optimalorange/cooltechnologies/network/SearchRequest.java | 2,699 | /**
* 页数<br />
* 示例:1
*/ | block_comment | zh-cn | package com.optimalorange.cooltechnologies.network;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.optimalorange.cooltechnologies.entity.Video;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.support.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Zhou Peican on 2014/12/9.
*/
public class SearchRequest extends JsonRequest<List<Video>> {
private static final String YOUKU_API_JSON_VIDEOS_ATTRIBUTE_NAME = "videos";
public SearchRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<List<Video>> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest == null ? null : jsonRequest.toString(), listener,
errorListener);
}
@Override
protected Response<List<Video>> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray videosJson = jsonObject.getJSONArray(YOUKU_API_JSON_VIDEOS_ATTRIBUTE_NAME);
int length = videosJson.length();
List<Video> videos = new ArrayList<>(length);
for (int i = 0; i < length; i++) {
videos.add(new Video(videosJson.getJSONObject(i)));
}
return Response.success(videos,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
public static class Builder {
public static final String DEFAULT_CATEGORY_LABEL = "科技";
private static final int DEFAULT_TIMELESS = 0;
private static final int DEFAULT_TIMEMORE = 0;
private static final int YOUKU_API_REQUEST_METHOD = Request.Method.GET;
private static final String YOUKU_API_SEARCHES_VIDEOS_BY_KEYWORD
= "https://openapi.youku.com/v2/searches/video/by_keyword.json";
/**
* A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
*/
@Nullable
private JSONObject mJsonRequest;
/**
* Listener to receive the videos response
*/
private Response.Listener<List<Video>> mResponseListener;
/**
* Error listener, or null to ignore errors.
*/
@Nullable
private Response.ErrorListener mErrorListener;
/** 应用Key(必设) */
private String client_id;
/** 关键字 多个关键字用空格分隔(必设) */
private String keyword;
/**
* 分类<br />
* 示例:资讯
* 默认值:{@link #DEFAULT_CATEGORY_LABEL}
*/
@Nullable
private String category = DEFAULT_CATEGORY_LABEL;
/** 时间范围 */
@Nullable
private PERIOD period;
/** 排序 */
@Nullable
private ORDER_BY orderby;
/** 公开类型 all */
@Nullable
private PUBLIC_TYPE public_type;
/** 付费状态 付费 1 免费 0 */
@Nullable
private PAID paid;
/**
* 视频时长筛选:定义时长小 于几分钟(不包含),默认 0表示不筛选
*/
@Nullable
private int timeless = DEFAULT_TIMELESS;
/**
* 视频时长筛选:定义时长大 于等于几分钟(不包含)
*/
@Nullable
private int timemore = DEFAULT_TIMEMORE;
/**
* 格式筛选(逗号分隔,表示‘或’关系)
* | 1:mp4(高清) | 2:3gp | 1,2,3 3:H263FLV |
* 4:3GPHD | 5:H264FLV(FLV升级版h264) |
* 6:Hd2 720P(超清) |
*/
@Nullable
private STREAMTYPES streamtypes;
/**
* 页数< <SUF>*/
@Nullable
private Integer page;
/**
* 页大小<br />
* 示例:20
*/
@Nullable
private Integer count;
/**
* 应用Key(必设参数)
*/
public Builder setClient_id(String client_id) {
this.client_id = client_id;
return this;
}
/**
* 关键字 多个关键字用空格分隔
*/
public Builder setKeyword(String keyword) {
this.keyword = keyword;
return this;
}
/**
* 分类<br />
* 示例:资讯
* 默认值:{@link #DEFAULT_CATEGORY_LABEL}
*/
public Builder setCategory(@Nullable String category) {
this.category = category;
return this;
}
/** 时间范围 */
public Builder setPeriod(@Nullable PERIOD period) {
this.period = period;
return this;
}
/** 排序 */
public Builder setOrderby(@Nullable ORDER_BY orderby) {
this.orderby = orderby;
return this;
}
/** 公开类型 */
public Builder setPublic_type(@Nullable PUBLIC_TYPE public_type) {
this.public_type = public_type;
return this;
}
/** 付费状态 */
public Builder setPaid(@Nullable PAID paid) {
this.paid = paid;
return this;
}
/** 视频时长筛选:定义时长小 于几分钟(不包含) */
public Builder setTimeless(@Nullable int timeLess) {
this.timeless = timeless;
return this;
}
/** 视频时长筛选:定义时长大 于等于几分钟(不包含) */
public Builder setTimemore(@Nullable int timemore) {
this.timemore = timemore;
return this;
}
/** 格式筛选 */
public Builder setStreamtypes(@Nullable STREAMTYPES streamtypes) {
this.streamtypes = streamtypes;
return this;
}
/**
* 页数<br />
* 示例:1
*/
public Builder setPage(@Nullable Integer page) {
this.page = page;
return this;
}
/**
* 页大小<br />
* 示例:20
*/
public Builder setCount(@Nullable Integer count) {
this.count = count;
return this;
}
/**
* A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
*/
public Builder setJsonRequest(@Nullable JSONObject jsonRequest) {
mJsonRequest = jsonRequest;
return this;
}
/**
* Listener to receive the videos response
*/
public Builder setResponseListener(Response.Listener<List<Video>> responseListener) {
mResponseListener = responseListener;
return this;
}
/**
* Error listener, or null to ignore errors.
*/
public Builder setErrorListener(@Nullable Response.ErrorListener errorListener) {
mErrorListener = errorListener;
return this;
}
public SearchRequest build() {
return new SearchRequest(
YOUKU_API_REQUEST_METHOD,
buildUrl(),
mJsonRequest,
mResponseListener,
mErrorListener
);
}
private String buildUrl() {
final Uri.Builder urlBuilder = Uri.parse(YOUKU_API_SEARCHES_VIDEOS_BY_KEYWORD)
.buildUpon();
if (client_id == null) {
throw new IllegalStateException("Please set client_id before build");
}
urlBuilder.appendQueryParameter("client_id", client_id);
if (keyword == null) {
throw new IllegalStateException("Please input keyword before build");
}
urlBuilder.appendQueryParameter("keyword", keyword);
if (category != null) {
urlBuilder.appendQueryParameter("category", category);
}
if (period != null) {
urlBuilder.appendQueryParameter("period", period.toString());
}
if (orderby != null) {
urlBuilder.appendQueryParameter("orderby", orderby.toString());
}
if (public_type != null) {
urlBuilder.appendQueryParameter("public_type", public_type.toString());
}
if (paid != null) {
urlBuilder.appendQueryParameter("paid", PAID.fromPaidType(paid));
}
if (timeless != 0) {
urlBuilder.appendQueryParameter("timeless", String.valueOf(timeless));
}
if (timemore != 0) {
urlBuilder.appendQueryParameter("timemore", String.valueOf(timemore));
}
if (streamtypes != null) {
urlBuilder.appendQueryParameter("streamtypes",
STREAMTYPES.fromStreamTypes(streamtypes));
}
if (page != null) {
urlBuilder.appendQueryParameter("page", page.toString());
}
if (count != null) {
urlBuilder.appendQueryParameter("count", count.toString());
}
return urlBuilder.build().toString();
}
/** 时间范围 */
public static enum PERIOD {
/** 今日 */
TODAY,
/** 本周 */
WEEK,
/** 本月 */
MONTH,
/** 历史 */
HISTORY;
public String toString() {
return name().toLowerCase(Locale.US);
}
}
/** 排序 */
public static enum ORDER_BY {
/** 发布时间 */
PUBLISHED,
/** 总播放数 */
VIEW_COUNT,
/** 总评论数 */
COMMENT_COUNT,
/** 总引用 */
REFERENCE_COUNT,
/** 总收藏数 */
FAVORITE_COUNT,
/** 相关度 */
RELEVANCE;
public String toString() {
return name().toLowerCase(Locale.US).replace('_', '-');
}
}
/** 公开类型 */
public static enum PUBLIC_TYPE {
/** 公开 */
ALL,
/** 仅好友观看 */
FRIEND,
/** 输入密码观看 */
PASSWORD;
@Override
public String toString() {
return name().toLowerCase(Locale.US);
}
}
/** 付费状态 */
public static enum PAID {
/** 免费 0 */
FREE,
/** 付费 1 */
PAY;
public static String fromPaidType(PAID paid) {
return String.valueOf(paid.ordinal());
}
}
/** 格式筛选 */
public static enum STREAMTYPES {
/** 1:mp4(高清) */
MP4,
/** 2:3gp */
_3GP,
/** 3:H263FLV */
H263FLV,
/** 4:3GPHD */
_3GPHD,
/** 5:H264FLV */
H264FLV,
/** 6:Hd2 */
Hd2;
public static String fromStreamTypes(STREAMTYPES streamtypes) {
return String.valueOf(streamtypes.ordinal() + 1);
}
}
}
}
| false | 2,444 | 16 | 2,699 | 17 | 2,888 | 18 | 2,699 | 17 | 3,523 | 21 | false | false | false | false | false | true |
64242_6 | package top.misec.task;
import static top.misec.task.TaskInfoHolder.STATUS_CODE_STR;
import static top.misec.task.TaskInfoHolder.getVideoId;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import top.misec.api.ApiList;
import top.misec.api.OftenApi;
import top.misec.config.ConfigLoader;
import top.misec.utils.HelpUtil;
import top.misec.utils.HttpUtils;
import top.misec.utils.SleepTime;
/**
* 投币任务.
*
* @author @JunzhouLiu @Kurenai
* @since 2020-11-22 5:28
*/
@SuppressWarnings("StringConcatenationArgumentToLogCall")
@Slf4j
public class CoinAdd implements Task {
/**
* 检查是否投币.
*
* @param bvid av号
* @return 返回是否投过硬币了. true没有投币,false投过了。
*/
static boolean isCoinAdded(String bvid) {
String urlParam = "?bvid=" + bvid;
JsonObject result = HttpUtils.doGet(ApiList.IS_COIN + urlParam);
int multiply = result.getAsJsonObject("data").get("multiply").getAsInt();
return multiply <= 0;
}
@Override
public void run() {
//投币最多操作数 解决csrf校验失败时死循环的问题
int addCoinOperateCount = 0;
//安全检查,最多投币数
final int maxNumberOfCoins = 5;
//获取自定义配置投币数 配置写在src/main/resources/taskConfig.json中
int setCoin = ConfigLoader.helperConfig.getTaskConfig().getNumberOfCoins();
// 预留硬币数
int reserveCoins = ConfigLoader.helperConfig.getTaskConfig().getReserveCoins();
//已投的硬币
int useCoin = TaskInfoHolder.expConfirm();
//投币策略
int coinAddPriority = ConfigLoader.helperConfig.getTaskConfig().getCoinAddPriority();
if (setCoin > maxNumberOfCoins) {
log.info("自定义投币数为: {}枚,为保护你的资产,自定义投币数重置为: " + maxNumberOfCoins + "枚", setCoin);
setCoin = maxNumberOfCoins;
}
log.info("自定义投币数为: {}枚,程序执行前已投: {}枚", setCoin, useCoin);
//调整投币数 设置投币数-已经投过的硬币数
int needCoins = setCoin - useCoin;
//投币前硬币余额
Double beforeAddCoinBalance = OftenApi.getCoinBalance();
int coinBalance = (int) Math.floor(beforeAddCoinBalance);
if (needCoins <= 0) {
log.info("已完成设定的投币任务,今日无需再投币了");
return;
} else {
log.info("投币数调整为: {}枚", needCoins);
//投币数大于余额时,按余额投
if (needCoins > coinBalance) {
log.info("完成今日设定投币任务还需要投: {}枚硬币,但是余额只有: {}", needCoins, beforeAddCoinBalance);
log.info("投币数调整为: {}", coinBalance);
needCoins = coinBalance;
}
}
if (coinBalance < reserveCoins) {
log.info("剩余硬币数为{},低于预留硬币数{},今日不再投币", beforeAddCoinBalance, reserveCoins);
log.info("tips: 当硬币余额少于你配置的预留硬币数时,则会暂停当日投币任务");
return;
}
log.info("投币前余额为 : {}", beforeAddCoinBalance);
/*
* 请勿修改 max_numberOfCoins 这里多判断一次保证投币数超过5时 不执行投币操作.
* 最后一道安全判断,保证即使前面的判断逻辑错了,也不至于发生投币事故.
*/
while (needCoins > 0 && needCoins <= maxNumberOfCoins) {
String bvid;
if (coinAddPriority == 1 && addCoinOperateCount < 7) {
bvid = getVideoId.getFollowUpRandomVideoBvid();
} else {
bvid = getVideoId.getRegionRankingVideoBvid();
}
addCoinOperateCount++;
boolean flag = coinAdd(bvid, 1, ConfigLoader.helperConfig.getTaskConfig().getSelectLike());
if (flag) {
needCoins--;
new SleepTime().sleepDefault();
}
if (addCoinOperateCount > 15) {
log.info("尝试投币/投币失败次数太多");
break;
}
}
log.info("投币任务完成后余额为: {}", OftenApi.getCoinBalance());
}
/**
* 投币操作工具类.
*
* @param bvid av号
* @param multiply 投币数量
* @param selectLike 是否同时点赞 1是
* @return 是否投币成功
*/
private boolean coinAdd(String bvid, int multiply, int selectLike) {
String videoTitle = OftenApi.getVideoTitle(bvid);
//判断曾经是否对此av投币过
if (isCoinAdded(bvid)) {
Map<String, String> headers = new HashMap<>(10);
headers.put("Referer", "https://www.bilibili.com/video/" + bvid);
headers.put("Origin", "https://www.bilibili.com");
String requestBody = "aid=" + HelpUtil.bv2av(bvid)
+ "&multiply=" + multiply
+ "&select_like=" + selectLike
+ "&cross_domain=" + "true"
+ "&csrf=" + ConfigLoader.helperConfig.getBiliVerify().getBiliJct();
new VideoWatch().watchVideo(bvid);
JsonObject jsonObject = HttpUtils.doPost(ApiList.COIN_ADD, requestBody, headers);
if (jsonObject.get(STATUS_CODE_STR).getAsInt() == 0) {
log.info("为 " + videoTitle + " 投币成功");
return true;
} else {
log.info("投币失败" + jsonObject.get("message").getAsString());
return false;
}
} else {
log.info("已经为" + videoTitle + "投过币了");
return false;
}
}
@Override
public String getName() {
return "投币任务";
}
}
| OreosLab/bili | src/main/java/top/misec/task/CoinAdd.java | 1,593 | //已投的硬币 | line_comment | zh-cn | package top.misec.task;
import static top.misec.task.TaskInfoHolder.STATUS_CODE_STR;
import static top.misec.task.TaskInfoHolder.getVideoId;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import top.misec.api.ApiList;
import top.misec.api.OftenApi;
import top.misec.config.ConfigLoader;
import top.misec.utils.HelpUtil;
import top.misec.utils.HttpUtils;
import top.misec.utils.SleepTime;
/**
* 投币任务.
*
* @author @JunzhouLiu @Kurenai
* @since 2020-11-22 5:28
*/
@SuppressWarnings("StringConcatenationArgumentToLogCall")
@Slf4j
public class CoinAdd implements Task {
/**
* 检查是否投币.
*
* @param bvid av号
* @return 返回是否投过硬币了. true没有投币,false投过了。
*/
static boolean isCoinAdded(String bvid) {
String urlParam = "?bvid=" + bvid;
JsonObject result = HttpUtils.doGet(ApiList.IS_COIN + urlParam);
int multiply = result.getAsJsonObject("data").get("multiply").getAsInt();
return multiply <= 0;
}
@Override
public void run() {
//投币最多操作数 解决csrf校验失败时死循环的问题
int addCoinOperateCount = 0;
//安全检查,最多投币数
final int maxNumberOfCoins = 5;
//获取自定义配置投币数 配置写在src/main/resources/taskConfig.json中
int setCoin = ConfigLoader.helperConfig.getTaskConfig().getNumberOfCoins();
// 预留硬币数
int reserveCoins = ConfigLoader.helperConfig.getTaskConfig().getReserveCoins();
//已投 <SUF>
int useCoin = TaskInfoHolder.expConfirm();
//投币策略
int coinAddPriority = ConfigLoader.helperConfig.getTaskConfig().getCoinAddPriority();
if (setCoin > maxNumberOfCoins) {
log.info("自定义投币数为: {}枚,为保护你的资产,自定义投币数重置为: " + maxNumberOfCoins + "枚", setCoin);
setCoin = maxNumberOfCoins;
}
log.info("自定义投币数为: {}枚,程序执行前已投: {}枚", setCoin, useCoin);
//调整投币数 设置投币数-已经投过的硬币数
int needCoins = setCoin - useCoin;
//投币前硬币余额
Double beforeAddCoinBalance = OftenApi.getCoinBalance();
int coinBalance = (int) Math.floor(beforeAddCoinBalance);
if (needCoins <= 0) {
log.info("已完成设定的投币任务,今日无需再投币了");
return;
} else {
log.info("投币数调整为: {}枚", needCoins);
//投币数大于余额时,按余额投
if (needCoins > coinBalance) {
log.info("完成今日设定投币任务还需要投: {}枚硬币,但是余额只有: {}", needCoins, beforeAddCoinBalance);
log.info("投币数调整为: {}", coinBalance);
needCoins = coinBalance;
}
}
if (coinBalance < reserveCoins) {
log.info("剩余硬币数为{},低于预留硬币数{},今日不再投币", beforeAddCoinBalance, reserveCoins);
log.info("tips: 当硬币余额少于你配置的预留硬币数时,则会暂停当日投币任务");
return;
}
log.info("投币前余额为 : {}", beforeAddCoinBalance);
/*
* 请勿修改 max_numberOfCoins 这里多判断一次保证投币数超过5时 不执行投币操作.
* 最后一道安全判断,保证即使前面的判断逻辑错了,也不至于发生投币事故.
*/
while (needCoins > 0 && needCoins <= maxNumberOfCoins) {
String bvid;
if (coinAddPriority == 1 && addCoinOperateCount < 7) {
bvid = getVideoId.getFollowUpRandomVideoBvid();
} else {
bvid = getVideoId.getRegionRankingVideoBvid();
}
addCoinOperateCount++;
boolean flag = coinAdd(bvid, 1, ConfigLoader.helperConfig.getTaskConfig().getSelectLike());
if (flag) {
needCoins--;
new SleepTime().sleepDefault();
}
if (addCoinOperateCount > 15) {
log.info("尝试投币/投币失败次数太多");
break;
}
}
log.info("投币任务完成后余额为: {}", OftenApi.getCoinBalance());
}
/**
* 投币操作工具类.
*
* @param bvid av号
* @param multiply 投币数量
* @param selectLike 是否同时点赞 1是
* @return 是否投币成功
*/
private boolean coinAdd(String bvid, int multiply, int selectLike) {
String videoTitle = OftenApi.getVideoTitle(bvid);
//判断曾经是否对此av投币过
if (isCoinAdded(bvid)) {
Map<String, String> headers = new HashMap<>(10);
headers.put("Referer", "https://www.bilibili.com/video/" + bvid);
headers.put("Origin", "https://www.bilibili.com");
String requestBody = "aid=" + HelpUtil.bv2av(bvid)
+ "&multiply=" + multiply
+ "&select_like=" + selectLike
+ "&cross_domain=" + "true"
+ "&csrf=" + ConfigLoader.helperConfig.getBiliVerify().getBiliJct();
new VideoWatch().watchVideo(bvid);
JsonObject jsonObject = HttpUtils.doPost(ApiList.COIN_ADD, requestBody, headers);
if (jsonObject.get(STATUS_CODE_STR).getAsInt() == 0) {
log.info("为 " + videoTitle + " 投币成功");
return true;
} else {
log.info("投币失败" + jsonObject.get("message").getAsString());
return false;
}
} else {
log.info("已经为" + videoTitle + "投过币了");
return false;
}
}
@Override
public String getName() {
return "投币任务";
}
}
| false | 1,444 | 6 | 1,593 | 6 | 1,621 | 6 | 1,593 | 6 | 2,244 | 12 | false | false | false | false | false | true |
36486_7 | package PATFoo;
import java.util.Scanner;
/**
* Manacher算法
* 马拉车算法的核心思想就是:关于回文中心对称(且两者都在最右回文边界内时)的字符的回文半径等于Math.min(radius[2*c-i],R-i+1)
* 再通俗一点,利用回文对称的性质,使用以前计算的每个字符的回文半径作为关于回文中心对称的字符的回文半径基础值,以便减少时间复杂度
* 以上条件不满足时,计算回文半径的方法同一般方法
* @author SunFeiran
* https://www.jianshu.com/p/116aa58b7d81
* https://www.jianshu.com/p/392172762e55
*
*/
public class _1040 {
public static void main(String[] args) {
Scanner scaner = new Scanner(System.in);
String str = scaner.nextLine();
scaner.close();
System.out.println(manacher(str));
}
public static char[] manacherString(String str){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
sb.append("#");
sb.append(str.charAt(i));
}
sb.append("#");
return sb.toString().toCharArray();
}
public static int manacher(String str){
if(str == null || str.length() < 1)
return 0;
char[] charArr = manacherString(str);
int[] radius = new int[charArr.length];
//最右回文边界
int R = -1;
//最右回文中心
int c = -1;
//最大回文长度
int max = Integer.MIN_VALUE;
//遍历新回文数组
for (int i = 0; i < radius.length; i++) {
/*
* 若i小于最右回文边界,radius[i]初始化为Math.min(radius[2*c-i],R-i+1);在该情况下又有两种情况
* 第一种情况radius[2*c-i]代表i的回文右边界小于等于最右回文边界
* 第二种情况R-i+1代表i的回文右边界大于最右回文边界
*/
/*
* 若i大于等于最右回文边界,radius[i]初始化为1,因为当R==i时,下一轮循环进行时,下一个字符已经跳出回文序列了所以要初始化为1
*/
//存在radius[2*c-i]大于R-i+1的情况,比如i距离字符串结尾很近时,可能会出现这种情况
radius[i] = R > i ? Math.min(radius[2*c-i],R-i+1):1;
if(R > i) {
System.out.println("第" + i + "次的radius[2*c-i]值: " + radius[2*c-i]);
System.out.println("第" + i + "次的R-i+1值: " + (R-i+1));
}
System.out.println("第" + i + "次的radius[" + i + "]初始值: " + radius[i]);
while(i+radius[i] < charArr.length && i - radius[i] > -1){
if(charArr[i-radius[i]] == charArr[i+radius[i]])
radius[i]++;
else
break;
}
System.out.println("第" + i + "次的radius[" + i + "]修改后值: " + radius[i]);
if(i + radius[i] > R){
R = i + radius[i]-1;//R代表最右回文边界的索引值,该边界包含在回文中,而不是回文的边界+1与其他的程序有区别
c = i;
}
System.out.println("第" + i + "次的R值: " + R);
System.out.println("第" + i + "次的c值: " + c);
max = Math.max(max,radius[i]);
}
return max-1;
}
}
| OrientTraveller/PAT_Solution_Java | _1040.java | 1,045 | //存在radius[2*c-i]大于R-i+1的情况,比如i距离字符串结尾很近时,可能会出现这种情况
| line_comment | zh-cn | package PATFoo;
import java.util.Scanner;
/**
* Manacher算法
* 马拉车算法的核心思想就是:关于回文中心对称(且两者都在最右回文边界内时)的字符的回文半径等于Math.min(radius[2*c-i],R-i+1)
* 再通俗一点,利用回文对称的性质,使用以前计算的每个字符的回文半径作为关于回文中心对称的字符的回文半径基础值,以便减少时间复杂度
* 以上条件不满足时,计算回文半径的方法同一般方法
* @author SunFeiran
* https://www.jianshu.com/p/116aa58b7d81
* https://www.jianshu.com/p/392172762e55
*
*/
public class _1040 {
public static void main(String[] args) {
Scanner scaner = new Scanner(System.in);
String str = scaner.nextLine();
scaner.close();
System.out.println(manacher(str));
}
public static char[] manacherString(String str){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
sb.append("#");
sb.append(str.charAt(i));
}
sb.append("#");
return sb.toString().toCharArray();
}
public static int manacher(String str){
if(str == null || str.length() < 1)
return 0;
char[] charArr = manacherString(str);
int[] radius = new int[charArr.length];
//最右回文边界
int R = -1;
//最右回文中心
int c = -1;
//最大回文长度
int max = Integer.MIN_VALUE;
//遍历新回文数组
for (int i = 0; i < radius.length; i++) {
/*
* 若i小于最右回文边界,radius[i]初始化为Math.min(radius[2*c-i],R-i+1);在该情况下又有两种情况
* 第一种情况radius[2*c-i]代表i的回文右边界小于等于最右回文边界
* 第二种情况R-i+1代表i的回文右边界大于最右回文边界
*/
/*
* 若i大于等于最右回文边界,radius[i]初始化为1,因为当R==i时,下一轮循环进行时,下一个字符已经跳出回文序列了所以要初始化为1
*/
//存在 <SUF>
radius[i] = R > i ? Math.min(radius[2*c-i],R-i+1):1;
if(R > i) {
System.out.println("第" + i + "次的radius[2*c-i]值: " + radius[2*c-i]);
System.out.println("第" + i + "次的R-i+1值: " + (R-i+1));
}
System.out.println("第" + i + "次的radius[" + i + "]初始值: " + radius[i]);
while(i+radius[i] < charArr.length && i - radius[i] > -1){
if(charArr[i-radius[i]] == charArr[i+radius[i]])
radius[i]++;
else
break;
}
System.out.println("第" + i + "次的radius[" + i + "]修改后值: " + radius[i]);
if(i + radius[i] > R){
R = i + radius[i]-1;//R代表最右回文边界的索引值,该边界包含在回文中,而不是回文的边界+1与其他的程序有区别
c = i;
}
System.out.println("第" + i + "次的R值: " + R);
System.out.println("第" + i + "次的c值: " + c);
max = Math.max(max,radius[i]);
}
return max-1;
}
}
| false | 907 | 28 | 1,036 | 34 | 1,054 | 31 | 1,037 | 34 | 1,277 | 56 | false | false | false | false | false | true |
61404_13 | package ir;
import java.util.*;
import asm.IRRegisterMap;
import asm.RegisterAllocator;
import asm.operand.*;
import ir.instruction.*;
import ir.entity.*;
public class LinearScan {
// 先搞一个寄存器 HashSet,把所有能用的寄存器存下来
final LinkedHashMap<String, ASMPhysicalRegister> callerSave = new LinkedHashMap<>() {
{ // t0 和 t1 倒出来
put("t2", new ASMPhysicalRegister("t2"));
put("t3", new ASMPhysicalRegister("t3"));
put("t4", new ASMPhysicalRegister("t4"));
put("t5", new ASMPhysicalRegister("t5"));
put("t6", new ASMPhysicalRegister("t6"));
put("a0", new ASMPhysicalRegister("a0"));
put("a1", new ASMPhysicalRegister("a1"));
put("a2", new ASMPhysicalRegister("a2"));
put("a3", new ASMPhysicalRegister("a3"));
put("a4", new ASMPhysicalRegister("a4"));
put("a5", new ASMPhysicalRegister("a5"));
put("a6", new ASMPhysicalRegister("a6"));
put("a7", new ASMPhysicalRegister("a7"));
}
};
final LinkedHashMap<String, ASMPhysicalRegister> calleeSave = new LinkedHashMap<>() {
// s0 through s11
{
put("s0", new ASMPhysicalRegister("s0"));
put("s1", new ASMPhysicalRegister("s1"));
put("s2", new ASMPhysicalRegister("s2"));
put("s3", new ASMPhysicalRegister("s3"));
put("s4", new ASMPhysicalRegister("s4"));
put("s5", new ASMPhysicalRegister("s5"));
put("s6", new ASMPhysicalRegister("s6"));
put("s7", new ASMPhysicalRegister("s7"));
put("s8", new ASMPhysicalRegister("s8"));
put("s9", new ASMPhysicalRegister("s9"));
put("s10", new ASMPhysicalRegister("s10"));
put("s11", new ASMPhysicalRegister("s11"));
}
};
IRFunction curFunc;
private TreeSet<VariableLiveness> activeCaller = new TreeSet<>(new CompareEnd());
private TreeSet<VariableLiveness> activeCallee = new TreeSet<>(new CompareEnd());
HashSet<ASMPhysicalRegister> remainingCaller = new HashSet<>(), remainingCallee = new HashSet<>();
ArrayList<IRBasicBlock> reversePostOrder = new ArrayList<>();
HashSet<IRBasicBlock> inRPO = new HashSet<>();
LinkedHashMap<IRRegister, VariableLiveness> livenessMap = new LinkedHashMap<>();
private ArrayList<Integer> callIndex = new ArrayList<>();
private TreeSet<VariableLiveness> livenessSet = new TreeSet<>(new CompareBegin());
public class VariableLiveness {
public int begin = 2147483647, end = -1;
public IRRegister original;
public ASMRegister reg;
public boolean throughCallInst = false;
// 如果经过 call,那么 caller saved registers 可能被占,不能分配
public VariableLiveness(int begin, int end, IRRegister reg) {
this.begin = begin;
this.end = end;
this.original = reg;
}
}
public class CompareBegin implements Comparator<VariableLiveness> {
@Override
public int compare(VariableLiveness a, VariableLiveness b) {
return a.begin - b.begin;
}
}
public class CompareEnd implements Comparator<VariableLiveness> {
@Override
public int compare(VariableLiveness a, VariableLiveness b) {
return a.end - b.end;
}
}
public LinearScan(IRFunction func) {
this.curFunc = func;
LinearScanRegisterAllocation();
IRRegisterMap.irRegisterMap = new LinkedHashMap<>();
LinearScanRegisterAllocation();
for (var interval: livenessSet) {
// fuck s5
// if (Objects.equals(((ASMPhysicalRegister) interval.reg).label, "s5")) {
// System.err.println(interval.begin + " " + interval.end);
// }
interval.original.asmRegister = interval.reg;
}
}
public void dfs(IRBasicBlock curBlk) {
inRPO.add(curBlk);
for (var succ: curBlk.suc) {
if (!inRPO.contains(succ)) {
// System.err.println(curBlk.label + " " + succ.label);
// inRPO.add(succ); // succ 可能连了一通连到自己,导致无限递归
dfs(succ);
}
}
reversePostOrder.add(curBlk);
}
public void getRPO() {
// TODO
dfs(curFunc.blocks.getFirst());
Collections.reverse(reversePostOrder);
// System.err.println("fuck that shit");
}
public void setEnd(VariableLiveness liveness, int idx) {
liveness.end = Math.max(liveness.end, idx);
}
public void init() {
LivenessAnalysis.analyze(curFunc);
// 先扫一遍,获得生命周期信息
// Reverse post order
getRPO();
// 从前往后扫一遍,查生命周期
int idx = 0; // 指令编号,用于表示记录生命周期起终点
for (var arg: curFunc.paramList) {
assert(arg != null);
VariableLiveness liveness = new VariableLiveness(idx, -1, arg);
livenessMap.put(arg, liveness);
}
for (IRBasicBlock blk: reversePostOrder) {
for (IRInstruction ins: blk.instructions) {
// System.out.println(ins.toString());
if (ins instanceof IRCall) {
// System.out.println(ins.toString());
// System.out.println(idx);
callIndex.add(idx);
}
// 第一次出现的变量一定是 def
if (!ins.def.isEmpty()) {
for (var def: ins.def) {
assert(def != null);
VariableLiveness liveness = null;
if (livenessMap.containsKey(def)) {
liveness = livenessMap.get(def);
liveness.begin = Math.min(liveness.begin, idx);
}
else {
liveness = new VariableLiveness(idx, -1, def);
livenessMap.put(def, liveness);
}
}
}
if (!ins.use.isEmpty()) {
for (var use: ins.use) {
VariableLiveness liveness = livenessMap.get(use);
setEnd(liveness, idx);
}
}
++idx;
}
HashSet<IRRegister> terminalUse = blk.terminal.use;
for (var use: terminalUse) {
VariableLiveness liveness = livenessMap.get(use);
setEnd(liveness, idx);
}
++idx;
// 别把 liveout 忘了!!要不然分析生命周期干啥
for (var liveOut: blk.liveOut) {
// System.err.println(liveOut.name + "_" + liveOut.id);
VariableLiveness liveness = livenessMap.get(liveOut);
// 找不到怎么办!稳啦!都稳啦!
if (liveness != null)
setEnd(liveness, idx);
}
}
// TODO: 穿过 call 指令怎么判断?
livenessSet.addAll(livenessMap.values());
for (var liveness: livenessSet) {
// boolean flag = false;
assert(liveness.original != null);
// if (Objects.equals(liveness.original.name, "tmp_subscript") && liveness.original.id == 10) {
// System.err.println(liveness.begin + " " + liveness.end);
// flag = true;
// }
// ????????????????????????????????????????????????for (int i = 0; i < callIndex.size() - 1; ++i) { 我tm在干什么?
for (int i = 0; i < callIndex.size(); ++i) {
if (liveness.begin < callIndex.get(i) && liveness.end >= callIndex.get(i)) {
liveness.throughCallInst = true;
break;
}
}
}
}
public void LinearScanRegisterAllocation() {
// init
remainingCaller.clear();
remainingCallee.clear();
remainingCaller.addAll(callerSave.values());
remainingCallee.addAll(calleeSave.values());
activeCaller.clear();
activeCallee.clear();
reversePostOrder.clear();
inRPO.clear();
livenessMap.clear();
callIndex.clear();
livenessSet.clear();
this.init();
// 开始分配
for (var interval: livenessSet) {
ExpireOldIntervals(interval);
if (interval.throughCallInst) {
// 只分配 callee saved registers
if (remainingCallee.isEmpty()) {
CalleeSpill(interval);
}
else {
interval.reg = remainingCallee.iterator().next();
remainingCallee.remove(interval.reg);
activeCallee.add(interval);
}
}
else {
// 先分配 caller saved registers
if (!remainingCaller.isEmpty()) {
interval.reg = remainingCaller.iterator().next();
remainingCaller.remove(interval.reg);
activeCaller.add(interval);
}
else if (!remainingCallee.isEmpty()) {
interval.reg = remainingCallee.iterator().next();
remainingCallee.remove(interval.reg);
activeCallee.add(interval);
}
else {
// 随便挑谁折磨吧
CallerSpill(interval);
}
}
}
}
void ExpireOldIntervals(VariableLiveness interval) {
for (var j = activeCaller.iterator(); j.hasNext();) {
var it = j.next();
if (it.end >= interval.begin) {
return;
}
remainingCaller.add((ASMPhysicalRegister) it.reg);
j.remove();
}
for (var j = activeCallee.iterator(); j.hasNext();) {
var it = j.next();
if (it.end >= interval.begin) {
return;
}
remainingCallee.add((ASMPhysicalRegister) it.reg);
j.remove();
}
}
void CalleeSpill(VariableLiveness interval) {
// TODO
VariableLiveness spill = activeCallee.last();
if (spill.end > interval.end) {
interval.reg = spill.reg;
spill.reg = null;
activeCallee.remove(spill);
activeCallee.add(interval);
// 栈的分配到时候再说
}
else {
interval.reg = null;
}
}
void CallerSpill(VariableLiveness interval) {
// TODO
VariableLiveness spill = activeCaller.last();
if (spill.end > interval.end) {
interval.reg = spill.reg;
spill.reg = null;
activeCaller.remove(spill);
activeCaller.add(interval);
// 栈的分配到时候再说
}
else {
interval.reg = null;
}
}
} | OrientalHorizon/Mx-Compiler | src/ir/LinearScan.java | 2,754 | // 从前往后扫一遍,查生命周期
| line_comment | zh-cn | package ir;
import java.util.*;
import asm.IRRegisterMap;
import asm.RegisterAllocator;
import asm.operand.*;
import ir.instruction.*;
import ir.entity.*;
public class LinearScan {
// 先搞一个寄存器 HashSet,把所有能用的寄存器存下来
final LinkedHashMap<String, ASMPhysicalRegister> callerSave = new LinkedHashMap<>() {
{ // t0 和 t1 倒出来
put("t2", new ASMPhysicalRegister("t2"));
put("t3", new ASMPhysicalRegister("t3"));
put("t4", new ASMPhysicalRegister("t4"));
put("t5", new ASMPhysicalRegister("t5"));
put("t6", new ASMPhysicalRegister("t6"));
put("a0", new ASMPhysicalRegister("a0"));
put("a1", new ASMPhysicalRegister("a1"));
put("a2", new ASMPhysicalRegister("a2"));
put("a3", new ASMPhysicalRegister("a3"));
put("a4", new ASMPhysicalRegister("a4"));
put("a5", new ASMPhysicalRegister("a5"));
put("a6", new ASMPhysicalRegister("a6"));
put("a7", new ASMPhysicalRegister("a7"));
}
};
final LinkedHashMap<String, ASMPhysicalRegister> calleeSave = new LinkedHashMap<>() {
// s0 through s11
{
put("s0", new ASMPhysicalRegister("s0"));
put("s1", new ASMPhysicalRegister("s1"));
put("s2", new ASMPhysicalRegister("s2"));
put("s3", new ASMPhysicalRegister("s3"));
put("s4", new ASMPhysicalRegister("s4"));
put("s5", new ASMPhysicalRegister("s5"));
put("s6", new ASMPhysicalRegister("s6"));
put("s7", new ASMPhysicalRegister("s7"));
put("s8", new ASMPhysicalRegister("s8"));
put("s9", new ASMPhysicalRegister("s9"));
put("s10", new ASMPhysicalRegister("s10"));
put("s11", new ASMPhysicalRegister("s11"));
}
};
IRFunction curFunc;
private TreeSet<VariableLiveness> activeCaller = new TreeSet<>(new CompareEnd());
private TreeSet<VariableLiveness> activeCallee = new TreeSet<>(new CompareEnd());
HashSet<ASMPhysicalRegister> remainingCaller = new HashSet<>(), remainingCallee = new HashSet<>();
ArrayList<IRBasicBlock> reversePostOrder = new ArrayList<>();
HashSet<IRBasicBlock> inRPO = new HashSet<>();
LinkedHashMap<IRRegister, VariableLiveness> livenessMap = new LinkedHashMap<>();
private ArrayList<Integer> callIndex = new ArrayList<>();
private TreeSet<VariableLiveness> livenessSet = new TreeSet<>(new CompareBegin());
public class VariableLiveness {
public int begin = 2147483647, end = -1;
public IRRegister original;
public ASMRegister reg;
public boolean throughCallInst = false;
// 如果经过 call,那么 caller saved registers 可能被占,不能分配
public VariableLiveness(int begin, int end, IRRegister reg) {
this.begin = begin;
this.end = end;
this.original = reg;
}
}
public class CompareBegin implements Comparator<VariableLiveness> {
@Override
public int compare(VariableLiveness a, VariableLiveness b) {
return a.begin - b.begin;
}
}
public class CompareEnd implements Comparator<VariableLiveness> {
@Override
public int compare(VariableLiveness a, VariableLiveness b) {
return a.end - b.end;
}
}
public LinearScan(IRFunction func) {
this.curFunc = func;
LinearScanRegisterAllocation();
IRRegisterMap.irRegisterMap = new LinkedHashMap<>();
LinearScanRegisterAllocation();
for (var interval: livenessSet) {
// fuck s5
// if (Objects.equals(((ASMPhysicalRegister) interval.reg).label, "s5")) {
// System.err.println(interval.begin + " " + interval.end);
// }
interval.original.asmRegister = interval.reg;
}
}
public void dfs(IRBasicBlock curBlk) {
inRPO.add(curBlk);
for (var succ: curBlk.suc) {
if (!inRPO.contains(succ)) {
// System.err.println(curBlk.label + " " + succ.label);
// inRPO.add(succ); // succ 可能连了一通连到自己,导致无限递归
dfs(succ);
}
}
reversePostOrder.add(curBlk);
}
public void getRPO() {
// TODO
dfs(curFunc.blocks.getFirst());
Collections.reverse(reversePostOrder);
// System.err.println("fuck that shit");
}
public void setEnd(VariableLiveness liveness, int idx) {
liveness.end = Math.max(liveness.end, idx);
}
public void init() {
LivenessAnalysis.analyze(curFunc);
// 先扫一遍,获得生命周期信息
// Reverse post order
getRPO();
// 从前 <SUF>
int idx = 0; // 指令编号,用于表示记录生命周期起终点
for (var arg: curFunc.paramList) {
assert(arg != null);
VariableLiveness liveness = new VariableLiveness(idx, -1, arg);
livenessMap.put(arg, liveness);
}
for (IRBasicBlock blk: reversePostOrder) {
for (IRInstruction ins: blk.instructions) {
// System.out.println(ins.toString());
if (ins instanceof IRCall) {
// System.out.println(ins.toString());
// System.out.println(idx);
callIndex.add(idx);
}
// 第一次出现的变量一定是 def
if (!ins.def.isEmpty()) {
for (var def: ins.def) {
assert(def != null);
VariableLiveness liveness = null;
if (livenessMap.containsKey(def)) {
liveness = livenessMap.get(def);
liveness.begin = Math.min(liveness.begin, idx);
}
else {
liveness = new VariableLiveness(idx, -1, def);
livenessMap.put(def, liveness);
}
}
}
if (!ins.use.isEmpty()) {
for (var use: ins.use) {
VariableLiveness liveness = livenessMap.get(use);
setEnd(liveness, idx);
}
}
++idx;
}
HashSet<IRRegister> terminalUse = blk.terminal.use;
for (var use: terminalUse) {
VariableLiveness liveness = livenessMap.get(use);
setEnd(liveness, idx);
}
++idx;
// 别把 liveout 忘了!!要不然分析生命周期干啥
for (var liveOut: blk.liveOut) {
// System.err.println(liveOut.name + "_" + liveOut.id);
VariableLiveness liveness = livenessMap.get(liveOut);
// 找不到怎么办!稳啦!都稳啦!
if (liveness != null)
setEnd(liveness, idx);
}
}
// TODO: 穿过 call 指令怎么判断?
livenessSet.addAll(livenessMap.values());
for (var liveness: livenessSet) {
// boolean flag = false;
assert(liveness.original != null);
// if (Objects.equals(liveness.original.name, "tmp_subscript") && liveness.original.id == 10) {
// System.err.println(liveness.begin + " " + liveness.end);
// flag = true;
// }
// ????????????????????????????????????????????????for (int i = 0; i < callIndex.size() - 1; ++i) { 我tm在干什么?
for (int i = 0; i < callIndex.size(); ++i) {
if (liveness.begin < callIndex.get(i) && liveness.end >= callIndex.get(i)) {
liveness.throughCallInst = true;
break;
}
}
}
}
public void LinearScanRegisterAllocation() {
// init
remainingCaller.clear();
remainingCallee.clear();
remainingCaller.addAll(callerSave.values());
remainingCallee.addAll(calleeSave.values());
activeCaller.clear();
activeCallee.clear();
reversePostOrder.clear();
inRPO.clear();
livenessMap.clear();
callIndex.clear();
livenessSet.clear();
this.init();
// 开始分配
for (var interval: livenessSet) {
ExpireOldIntervals(interval);
if (interval.throughCallInst) {
// 只分配 callee saved registers
if (remainingCallee.isEmpty()) {
CalleeSpill(interval);
}
else {
interval.reg = remainingCallee.iterator().next();
remainingCallee.remove(interval.reg);
activeCallee.add(interval);
}
}
else {
// 先分配 caller saved registers
if (!remainingCaller.isEmpty()) {
interval.reg = remainingCaller.iterator().next();
remainingCaller.remove(interval.reg);
activeCaller.add(interval);
}
else if (!remainingCallee.isEmpty()) {
interval.reg = remainingCallee.iterator().next();
remainingCallee.remove(interval.reg);
activeCallee.add(interval);
}
else {
// 随便挑谁折磨吧
CallerSpill(interval);
}
}
}
}
void ExpireOldIntervals(VariableLiveness interval) {
for (var j = activeCaller.iterator(); j.hasNext();) {
var it = j.next();
if (it.end >= interval.begin) {
return;
}
remainingCaller.add((ASMPhysicalRegister) it.reg);
j.remove();
}
for (var j = activeCallee.iterator(); j.hasNext();) {
var it = j.next();
if (it.end >= interval.begin) {
return;
}
remainingCallee.add((ASMPhysicalRegister) it.reg);
j.remove();
}
}
void CalleeSpill(VariableLiveness interval) {
// TODO
VariableLiveness spill = activeCallee.last();
if (spill.end > interval.end) {
interval.reg = spill.reg;
spill.reg = null;
activeCallee.remove(spill);
activeCallee.add(interval);
// 栈的分配到时候再说
}
else {
interval.reg = null;
}
}
void CallerSpill(VariableLiveness interval) {
// TODO
VariableLiveness spill = activeCaller.last();
if (spill.end > interval.end) {
interval.reg = spill.reg;
spill.reg = null;
activeCaller.remove(spill);
activeCaller.add(interval);
// 栈的分配到时候再说
}
else {
interval.reg = null;
}
}
} | false | 2,396 | 11 | 2,740 | 13 | 2,808 | 11 | 2,740 | 13 | 3,279 | 22 | false | false | false | false | false | true |
43818_13 | package org.orisland.wows.dataPack;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.promeg.pinyinhelper.Pinyin;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.console.command.CommandSenderOnMessage;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.message.data.Image;
import org.orisland.wows.ApiConfig;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.orisland.wows.ApiConfig.*;
import static org.orisland.wows.ApiConfig.dataDirNa;
@Slf4j
public class StringToMeaningful {
/**
* 鉴权
*/
public static boolean isAdmin(CommandSenderOnMessage sender){
String adminQQ = String.valueOf(sender.getFromEvent().getSender().getId());
if (!Arrays.asList(Admin).contains(adminQQ)){
log.info("鉴权不通过!");
return false;
}else
return true;
}
/**
* 构建图片
* @param sender
* @param pic
* @return
* @throws IOException
*/
public static Image getImage(CommandSenderOnMessage sender, String pic) throws IOException {
// InputStream resourceAsStream = WowsPlugin.class.getClassLoader().getResourceAsStream("prImg" + File.separator + pic);
return Contact.uploadImage(sender.getSubject(), new File(pic));
}
/**
* 通过船只名称查找船只
* @param shipName 船只名字
* @return 查询结果
*/
public static JsonNode ShipNameToShipId(String shipName){
// 查找是否为纯英语
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(shipName);
String s = shipName.trim().replaceAll("\\s", "").toUpperCase();
char[] chars = s.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
if(shipName.contains("-")){
shipName = shipName.split("-")[0] + shipName.split("-")[1];
}
int count = 0;
for (char aChar : chars) {
if (Pinyin.isChinese(aChar)){
char c = Pinyin.toPinyin(aChar).toCharArray()[0];
stringBuilder.append(String.valueOf(c).toLowerCase());
continue;
}
stringBuilder.append(aChar);
count++;
}
String ship = count == chars.length ? shipName : stringBuilder.toString();
// 包含汉语
if (m.find()){
// 精确匹配
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("zh").asText().equals(shipName)){
return jsonNode;
}
}
log.info("汉语精确匹配失败!");
// 模糊匹配
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("zh").asText().contains(shipName)){
return jsonNode;
}
}
log.info("汉语精确匹配失败!");
// 不包含汉语
}else {
// 英语精确匹配
for (JsonNode jsonNode : LocalShipInfo) {
String en = jsonNode.get("en").asText();
String text = "";
if (en.contains("-"))
text = en.split("-")[0] + en.split("-")[1];
else
text = en;
if (text.equalsIgnoreCase(shipName)){
return jsonNode;
}
}
log.info("英语精确匹配失败!");
// 英语模糊匹配
for (JsonNode jsonNode : LocalShipInfo) {
String en = jsonNode.get("en").asText();
String text = "";
if (en.contains("-"))
text = en.split("-")[0] + en.split("-")[1];
else
text = en;
if (text.toUpperCase().contains(shipName.toUpperCase())){
return jsonNode;
}
}
log.info("英语模糊匹配失败!");
}
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("py").asText().equals(ship)){
return jsonNode;
}
}
log.info("拼音精确匹配失败!");
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("py").asText().contains(ship)){
return jsonNode;
}
}
log.info("拼音模糊匹配失败!");
log.warn("{}不存在!",shipName);
return null;
}
/**
* 根据区服选择保存地址
* @param server 区服
* @return 保存地址
*/
public static String ServerToDir(Server server){
switch (server){
case EU:
return dataDirEu;
case ASIA:
return dataDirAsia;
case RU:
return dataDirRu;
case NA:
case com:
return dataDirNa;
default:
log.error("出现了意料之外的数据!");
return null;
}
}
/**
* 将字符串识别为区服信息
* @param str 待转化信息
* @return 枚举变量区服
*/
public static Server StringToServer(String str){
str = str.toUpperCase();
switch (str){
case "欧服":
case "欧":
case "EU":
return Server.EU;
case "亚服":
case "亚":
case "ASIA":
return Server.ASIA;
case "COM":
case "NA":
case "美服":
case "美":
return Server.com;
// 将俄服暂时全部合并入欧服
case "俄服":
case "俄":
case "RU":
return Server.EU;
default:
log.error("出现了预料之外的问题!");
return null;
}
}
/**
* 将char转化为国家,若不匹配则返回unknown
* @param charStr 字符串
* @return 国家
*/
public static String iWarShipToNation(char charStr){
switch (charStr){
case 'E':
return "英联邦";
case 'W':
return "欧洲";
case 'F':
return "法国";
case 'D':
return "德国";
case 'I':
return "意大利";
case 'R':
return "日本";
case 'H':
return "荷兰";
case 'V':
return "泛美";
case 'C':
return "泛亚";
case 'S':
// 这里西班牙也是S,需要在后续的处理单独区分
return "苏联";
case 'M':
return "美国";
case 'Y':
return "英国";
default:
log.warn("{}出现了未知char!", charStr);
return "Unknown";
}
}
/**
* 将wg的国籍数据转化为
* @return
*/
public static String WgToNation(String string){
switch (string){
case "commonwealth":
return "英联邦";
case "europe":
return "欧洲";
case "pan_america":
return "泛美";
case "france":
return "法国";
case "usa":
return "美国";
case "germany":
return "德国";
case "italy":
return "意大利";
case "uk":
return "应该";
case "japan":
return "日本";
case "netherlands":
return "荷兰";
case "pan_asia":
return "泛亚";
case "ussr":
return "苏联";
case "spain":
return "西班牙";
default:
log.warn("出现了意料之外的国籍");
return "unknown";
}
}
/**
* 将char转化为不同的舰种
* @param charStr 字符
* @return
*/
public static String charToType(char charStr){
switch (charStr){
case 'A':
return "航母";
case 'B':
return "战列";
case 'D':
return "驱逐";
case 'C':
return "巡洋";
case 'S':
return "潜艇";
default:
log.warn("{}出现了未知的char!", charStr);
return "Unknown";
}
}
/**
* 将字符串转化为不同的数据类型
* @param str 字符串
* @return 所需的type
*/
public static Type StringToType(String str){
str = str.toUpperCase();
switch (str){
case "SJ":
case "随机":
case "RANDOM":
return Type.random;
case "PW":
case "排位":
case "RANK":
return Type.rank;
case "ALL":
case "NORMAL":
case "全部":
default:
return Type.normal;
}
}
}
| Orisland/WowsHelper | src/main/java/org/orisland/wows/dataPack/StringToMeaningful.java | 2,168 | // 将俄服暂时全部合并入欧服 | line_comment | zh-cn | package org.orisland.wows.dataPack;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.promeg.pinyinhelper.Pinyin;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.console.command.CommandSenderOnMessage;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.message.data.Image;
import org.orisland.wows.ApiConfig;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.orisland.wows.ApiConfig.*;
import static org.orisland.wows.ApiConfig.dataDirNa;
@Slf4j
public class StringToMeaningful {
/**
* 鉴权
*/
public static boolean isAdmin(CommandSenderOnMessage sender){
String adminQQ = String.valueOf(sender.getFromEvent().getSender().getId());
if (!Arrays.asList(Admin).contains(adminQQ)){
log.info("鉴权不通过!");
return false;
}else
return true;
}
/**
* 构建图片
* @param sender
* @param pic
* @return
* @throws IOException
*/
public static Image getImage(CommandSenderOnMessage sender, String pic) throws IOException {
// InputStream resourceAsStream = WowsPlugin.class.getClassLoader().getResourceAsStream("prImg" + File.separator + pic);
return Contact.uploadImage(sender.getSubject(), new File(pic));
}
/**
* 通过船只名称查找船只
* @param shipName 船只名字
* @return 查询结果
*/
public static JsonNode ShipNameToShipId(String shipName){
// 查找是否为纯英语
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(shipName);
String s = shipName.trim().replaceAll("\\s", "").toUpperCase();
char[] chars = s.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
if(shipName.contains("-")){
shipName = shipName.split("-")[0] + shipName.split("-")[1];
}
int count = 0;
for (char aChar : chars) {
if (Pinyin.isChinese(aChar)){
char c = Pinyin.toPinyin(aChar).toCharArray()[0];
stringBuilder.append(String.valueOf(c).toLowerCase());
continue;
}
stringBuilder.append(aChar);
count++;
}
String ship = count == chars.length ? shipName : stringBuilder.toString();
// 包含汉语
if (m.find()){
// 精确匹配
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("zh").asText().equals(shipName)){
return jsonNode;
}
}
log.info("汉语精确匹配失败!");
// 模糊匹配
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("zh").asText().contains(shipName)){
return jsonNode;
}
}
log.info("汉语精确匹配失败!");
// 不包含汉语
}else {
// 英语精确匹配
for (JsonNode jsonNode : LocalShipInfo) {
String en = jsonNode.get("en").asText();
String text = "";
if (en.contains("-"))
text = en.split("-")[0] + en.split("-")[1];
else
text = en;
if (text.equalsIgnoreCase(shipName)){
return jsonNode;
}
}
log.info("英语精确匹配失败!");
// 英语模糊匹配
for (JsonNode jsonNode : LocalShipInfo) {
String en = jsonNode.get("en").asText();
String text = "";
if (en.contains("-"))
text = en.split("-")[0] + en.split("-")[1];
else
text = en;
if (text.toUpperCase().contains(shipName.toUpperCase())){
return jsonNode;
}
}
log.info("英语模糊匹配失败!");
}
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("py").asText().equals(ship)){
return jsonNode;
}
}
log.info("拼音精确匹配失败!");
for (JsonNode jsonNode : LocalShipInfo) {
if (jsonNode.get("py").asText().contains(ship)){
return jsonNode;
}
}
log.info("拼音模糊匹配失败!");
log.warn("{}不存在!",shipName);
return null;
}
/**
* 根据区服选择保存地址
* @param server 区服
* @return 保存地址
*/
public static String ServerToDir(Server server){
switch (server){
case EU:
return dataDirEu;
case ASIA:
return dataDirAsia;
case RU:
return dataDirRu;
case NA:
case com:
return dataDirNa;
default:
log.error("出现了意料之外的数据!");
return null;
}
}
/**
* 将字符串识别为区服信息
* @param str 待转化信息
* @return 枚举变量区服
*/
public static Server StringToServer(String str){
str = str.toUpperCase();
switch (str){
case "欧服":
case "欧":
case "EU":
return Server.EU;
case "亚服":
case "亚":
case "ASIA":
return Server.ASIA;
case "COM":
case "NA":
case "美服":
case "美":
return Server.com;
// 将俄 <SUF>
case "俄服":
case "俄":
case "RU":
return Server.EU;
default:
log.error("出现了预料之外的问题!");
return null;
}
}
/**
* 将char转化为国家,若不匹配则返回unknown
* @param charStr 字符串
* @return 国家
*/
public static String iWarShipToNation(char charStr){
switch (charStr){
case 'E':
return "英联邦";
case 'W':
return "欧洲";
case 'F':
return "法国";
case 'D':
return "德国";
case 'I':
return "意大利";
case 'R':
return "日本";
case 'H':
return "荷兰";
case 'V':
return "泛美";
case 'C':
return "泛亚";
case 'S':
// 这里西班牙也是S,需要在后续的处理单独区分
return "苏联";
case 'M':
return "美国";
case 'Y':
return "英国";
default:
log.warn("{}出现了未知char!", charStr);
return "Unknown";
}
}
/**
* 将wg的国籍数据转化为
* @return
*/
public static String WgToNation(String string){
switch (string){
case "commonwealth":
return "英联邦";
case "europe":
return "欧洲";
case "pan_america":
return "泛美";
case "france":
return "法国";
case "usa":
return "美国";
case "germany":
return "德国";
case "italy":
return "意大利";
case "uk":
return "应该";
case "japan":
return "日本";
case "netherlands":
return "荷兰";
case "pan_asia":
return "泛亚";
case "ussr":
return "苏联";
case "spain":
return "西班牙";
default:
log.warn("出现了意料之外的国籍");
return "unknown";
}
}
/**
* 将char转化为不同的舰种
* @param charStr 字符
* @return
*/
public static String charToType(char charStr){
switch (charStr){
case 'A':
return "航母";
case 'B':
return "战列";
case 'D':
return "驱逐";
case 'C':
return "巡洋";
case 'S':
return "潜艇";
default:
log.warn("{}出现了未知的char!", charStr);
return "Unknown";
}
}
/**
* 将字符串转化为不同的数据类型
* @param str 字符串
* @return 所需的type
*/
public static Type StringToType(String str){
str = str.toUpperCase();
switch (str){
case "SJ":
case "随机":
case "RANDOM":
return Type.random;
case "PW":
case "排位":
case "RANK":
return Type.rank;
case "ALL":
case "NORMAL":
case "全部":
default:
return Type.normal;
}
}
}
| false | 1,956 | 12 | 2,168 | 14 | 2,287 | 11 | 2,168 | 14 | 2,790 | 20 | false | false | false | false | false | true |
24655_0 | package com.example.outlier.prictace_1.AboutMe;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.outlier.prictace_1.AboutMe.AllClass.commentAdapter;
import com.example.outlier.prictace_1.AboutMe.AllClass.commentItem;
import com.example.outlier.prictace_1.R;
import java.util.ArrayList;
import java.util.List;
public class mycomment extends Activity {
private List<commentItem> commentList=new ArrayList<>();
private ListView listView;
private commentAdapter adapter;
private TextView labelTitle;
private ImageView iconBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycomment);
//初始化评论数据
initeComment();
adapter=new commentAdapter(mycomment.this, R.layout.comment_item,commentList);
listView=(ListView)findViewById(R.id.list_comment);
listView.setAdapter(adapter);
initeView();
}
private void initeComment(){
commentItem firstOne=new commentItem("2017/3/4","阿拉斯加","随便写的一段话.......");
commentList.add(firstOne);
commentItem secondOne=new commentItem("2017/3/4","纽约","随便写的一段话.......");
commentList.add(secondOne);
commentItem thirdOne=new commentItem("2017/3/4","巴黎","随便写的一段话.......");
commentList.add(thirdOne);
commentItem forthOne=new commentItem("2017/3/4","孟加拉","随便写的一段话.......");
commentList.add(forthOne);
commentItem fifthOne=new commentItem("2017/3/4","新德里","随便写的一段话.......");
commentList.add(fifthOne);
}
private void initeView(){
//初始化标题栏
labelTitle=(TextView)findViewById(R.id.label_title);
labelTitle.setText("我的点评");
//定义所有点击事件
iconBack=(ImageView)findViewById(R.id.icon_back);
iconBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//对于listView中的长按事件删除功能
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
//定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框
AlertDialog.Builder builder=new AlertDialog.Builder(mycomment.this);
builder.setMessage("确定删除?");
builder.setTitle("提示");
//添加AlertDialog.Builder对象的setPositiveButton()方法
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(commentList.remove(position)!=null){
System.out.println("success");
}else {
System.out.println("failed");
}
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), "删除列表项", Toast.LENGTH_SHORT).show();
}
});
//添加AlertDialog.Builder对象的setNegativeButton()方法
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
}
});
}
}
| Outliwer/Android-App | app/src/main/java/com/example/outlier/prictace_1/AboutMe/mycomment.java | 933 | //初始化评论数据
| line_comment | zh-cn | package com.example.outlier.prictace_1.AboutMe;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.outlier.prictace_1.AboutMe.AllClass.commentAdapter;
import com.example.outlier.prictace_1.AboutMe.AllClass.commentItem;
import com.example.outlier.prictace_1.R;
import java.util.ArrayList;
import java.util.List;
public class mycomment extends Activity {
private List<commentItem> commentList=new ArrayList<>();
private ListView listView;
private commentAdapter adapter;
private TextView labelTitle;
private ImageView iconBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycomment);
//初始 <SUF>
initeComment();
adapter=new commentAdapter(mycomment.this, R.layout.comment_item,commentList);
listView=(ListView)findViewById(R.id.list_comment);
listView.setAdapter(adapter);
initeView();
}
private void initeComment(){
commentItem firstOne=new commentItem("2017/3/4","阿拉斯加","随便写的一段话.......");
commentList.add(firstOne);
commentItem secondOne=new commentItem("2017/3/4","纽约","随便写的一段话.......");
commentList.add(secondOne);
commentItem thirdOne=new commentItem("2017/3/4","巴黎","随便写的一段话.......");
commentList.add(thirdOne);
commentItem forthOne=new commentItem("2017/3/4","孟加拉","随便写的一段话.......");
commentList.add(forthOne);
commentItem fifthOne=new commentItem("2017/3/4","新德里","随便写的一段话.......");
commentList.add(fifthOne);
}
private void initeView(){
//初始化标题栏
labelTitle=(TextView)findViewById(R.id.label_title);
labelTitle.setText("我的点评");
//定义所有点击事件
iconBack=(ImageView)findViewById(R.id.icon_back);
iconBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//对于listView中的长按事件删除功能
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
//定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框
AlertDialog.Builder builder=new AlertDialog.Builder(mycomment.this);
builder.setMessage("确定删除?");
builder.setTitle("提示");
//添加AlertDialog.Builder对象的setPositiveButton()方法
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(commentList.remove(position)!=null){
System.out.println("success");
}else {
System.out.println("failed");
}
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), "删除列表项", Toast.LENGTH_SHORT).show();
}
});
//添加AlertDialog.Builder对象的setNegativeButton()方法
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return false;
}
});
}
}
| false | 757 | 5 | 918 | 5 | 956 | 5 | 918 | 5 | 1,141 | 13 | false | false | false | false | false | true |
42239_3 | package lattice;
public class TestAdjList {
public static void main(String[] args) {
String sentence="有意见分歧";
int len = sentence.length();//字符串长度
AdjList g = new AdjList(len+1);//存储所有被切分的可能的词
//第一个节点结尾的边
g.addEdge(new CnToken(0, 1, 1.0, "有"));
//第二个节点结尾的边
g.addEdge(new CnToken(0, 2, 1.0, "有意"));
g.addEdge(new CnToken(1, 2, 1.0, "意"));
//第三个节点结尾的边
g.addEdge(new CnToken(1, 3, 1.0, "意见"));
g.addEdge(new CnToken(2, 3, 1.0, "见"));
//第四个节点结尾的边
g.addEdge(new CnToken(3, 4, 1.0, "分"));
//第五个节点结尾的边
g.addEdge(new CnToken(3, 5, 1.0, "分岐"));
System.out.println(g.toString());
for(CnToken t:g){
System.out.println(t);
}
}
}
| Owen864720655/nlp-book | src/lattice/TestAdjList.java | 342 | //第二个节点结尾的边 | line_comment | zh-cn | package lattice;
public class TestAdjList {
public static void main(String[] args) {
String sentence="有意见分歧";
int len = sentence.length();//字符串长度
AdjList g = new AdjList(len+1);//存储所有被切分的可能的词
//第一个节点结尾的边
g.addEdge(new CnToken(0, 1, 1.0, "有"));
//第二 <SUF>
g.addEdge(new CnToken(0, 2, 1.0, "有意"));
g.addEdge(new CnToken(1, 2, 1.0, "意"));
//第三个节点结尾的边
g.addEdge(new CnToken(1, 3, 1.0, "意见"));
g.addEdge(new CnToken(2, 3, 1.0, "见"));
//第四个节点结尾的边
g.addEdge(new CnToken(3, 4, 1.0, "分"));
//第五个节点结尾的边
g.addEdge(new CnToken(3, 5, 1.0, "分岐"));
System.out.println(g.toString());
for(CnToken t:g){
System.out.println(t);
}
}
}
| false | 282 | 6 | 342 | 8 | 312 | 6 | 342 | 8 | 404 | 10 | false | false | false | false | false | true |
41896_2 | package com.java.g39.data;
/**
* Created by equation on 9/8/17.
* 定义一些常量
*/
final public class Constant {
/**
* 新闻分类
*/
final public static String[] CATEGORYS = {
"推荐",
"科技",
"教育",
"军事",
"国内",
"社会",
"文化",
"汽车",
"国际",
"体育",
"财经",
"健康",
"娱乐"
};
/**
* 新闻分类总数
*/
final public static int CATEGORY_COUNT = CATEGORYS.length;
}
| OxOOo/Knows | app/src/main/java/com/java/g39/data/Constant.java | 167 | /**
* 新闻分类总数
*/ | block_comment | zh-cn | package com.java.g39.data;
/**
* Created by equation on 9/8/17.
* 定义一些常量
*/
final public class Constant {
/**
* 新闻分类
*/
final public static String[] CATEGORYS = {
"推荐",
"科技",
"教育",
"军事",
"国内",
"社会",
"文化",
"汽车",
"国际",
"体育",
"财经",
"健康",
"娱乐"
};
/**
* 新闻分 <SUF>*/
final public static int CATEGORY_COUNT = CATEGORYS.length;
}
| false | 134 | 10 | 167 | 11 | 167 | 11 | 167 | 11 | 218 | 18 | false | false | false | false | false | true |
31859_0 | package leetcode.ciof2;
/**
* Description:
* 请实现一个函数用来匹配包含'. '和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。
* 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但与"aa.a"和"ab*a"均不匹配。
*
* 示例 1:
* 输入:
* s = "aa"
* p = "a"
* 输出: false
* 解释: "a" 无法匹配 "aa" 整个字符串。
*
* 示例 2:
* 输入:
* s = "aa"
* p = "a*"
* 输出: true
* 解释:因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。
*
* 示例 3:
* 输入:
* s = "ab"
* p = ".*"
* 输出: true
* 解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。
*
* 示例 4:
* 输入:
* s = "aab"
* p = "c*a*b"
* 输出: true
* 解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
*
*
*
* @Author: YangGC
* DateTime: 06-05
*/
public class q019 {
public boolean isMatch(String A, String B) {
//如果字符串长度为0,需要检测下正则串
if (A.length() == 0) {
//如果正则串长度为奇数,必定不匹配, 比如“.”"ab*"必须是a*b*这种形式,*在奇数位上
if (B.length() % 2 != 0) {
return false;
}
int i = 1;
while (i < B.length()) {
if (B.charAt(i) != '*') {
return false;
}
i += 2;
}
return true;
}
//如果字符串长度为0,但是正则串没了,return false
if(B.length() == 0){
return false;
}
//C1和C2分别是两个串的当前位,C3是正则串当前位的后一位,如果存在的话,就更新一下
char c1 = A.charAt(0);
char c2 = B.charAt(0);
char c3 = 'a';
if (B.length() > 1) {
c3 = B.charAt(1);
}
//和dp一样,后一位分别是‘*’和不是'*'两种情况
if(c3 != '*'){
if(c1 == c2 || c2 == '.'){
return isMatch(A.substring(1),B.substring(1));
}else{
//否则不匹配
return false;
}
} else {
//如果该位字符串一样,或是正则串该位是‘.’,和dp一样,有看和不看两种情况
if(c1 == c2 || c2 == '.'){
return isMatch(A.substring(1),B) || isMatch(A,B.substring(2));
}else{
//不一样,那么正则串这两位就忽略,直接往后走
return isMatch(A,B.substring(2));
}
}
}
}
| OxYGC/leetcode | src/leetcode/ciof2/q019.java | 889 | /**
* Description:
* 请实现一个函数用来匹配包含'. '和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。
* 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但与"aa.a"和"ab*a"均不匹配。
*
* 示例 1:
* 输入:
* s = "aa"
* p = "a"
* 输出: false
* 解释: "a" 无法匹配 "aa" 整个字符串。
*
* 示例 2:
* 输入:
* s = "aa"
* p = "a*"
* 输出: true
* 解释:因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。
*
* 示例 3:
* 输入:
* s = "ab"
* p = ".*"
* 输出: true
* 解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。
*
* 示例 4:
* 输入:
* s = "aab"
* p = "c*a*b"
* 输出: true
* 解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
*
*
*
* @Author: YangGC
* DateTime: 06-05
*/ | block_comment | zh-cn | package leetcode.ciof2;
/**
* Des <SUF>*/
public class q019 {
public boolean isMatch(String A, String B) {
//如果字符串长度为0,需要检测下正则串
if (A.length() == 0) {
//如果正则串长度为奇数,必定不匹配, 比如“.”"ab*"必须是a*b*这种形式,*在奇数位上
if (B.length() % 2 != 0) {
return false;
}
int i = 1;
while (i < B.length()) {
if (B.charAt(i) != '*') {
return false;
}
i += 2;
}
return true;
}
//如果字符串长度为0,但是正则串没了,return false
if(B.length() == 0){
return false;
}
//C1和C2分别是两个串的当前位,C3是正则串当前位的后一位,如果存在的话,就更新一下
char c1 = A.charAt(0);
char c2 = B.charAt(0);
char c3 = 'a';
if (B.length() > 1) {
c3 = B.charAt(1);
}
//和dp一样,后一位分别是‘*’和不是'*'两种情况
if(c3 != '*'){
if(c1 == c2 || c2 == '.'){
return isMatch(A.substring(1),B.substring(1));
}else{
//否则不匹配
return false;
}
} else {
//如果该位字符串一样,或是正则串该位是‘.’,和dp一样,有看和不看两种情况
if(c1 == c2 || c2 == '.'){
return isMatch(A.substring(1),B) || isMatch(A,B.substring(2));
}else{
//不一样,那么正则串这两位就忽略,直接往后走
return isMatch(A,B.substring(2));
}
}
}
}
| false | 811 | 364 | 889 | 404 | 894 | 382 | 889 | 404 | 1,169 | 559 | true | true | true | true | true | false |
26113_4 | package com.doooly.entity.reachad;
import java.util.Date;
/**
* @Description: 家庭关系表
* @author: qing.zhang
* @date: 2017-07-25
*/
public class AdFamilyUser {
private Long id;
private Long familyId;//家庭表主键ID
private Long userId;//家庭表主键ID
private Integer isPointShare;//积分共享开关 0:开 1:关
private Integer familyRelationship;//与员工家庭关系 1:父亲或爸爸 2:母亲或妈妈 3:儿子 4:女儿 5:哥哥 6:姐姐 7:弟弟 8:妹妹
private Integer delFlag;//0:有效 1:无效
private Date updateDate;//更新时间
private Date createDate;//创建时间
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getFamilyId() {
return familyId;
}
public void setFamilyId(Long familyId) {
this.familyId = familyId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getIsPointShare() {
return isPointShare;
}
public void setIsPointShare(Integer isPointShare) {
this.isPointShare = isPointShare;
}
public Integer getFamilyRelationship() {
return familyRelationship;
}
public void setFamilyRelationship(Integer familyRelationship) {
this.familyRelationship = familyRelationship;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
| P79N6A/doooly2.x | src/main/java/com/doooly/entity/reachad/AdFamilyUser.java | 518 | //与员工家庭关系 1:父亲或爸爸 2:母亲或妈妈 3:儿子 4:女儿 5:哥哥 6:姐姐 7:弟弟 8:妹妹
| line_comment | zh-cn | package com.doooly.entity.reachad;
import java.util.Date;
/**
* @Description: 家庭关系表
* @author: qing.zhang
* @date: 2017-07-25
*/
public class AdFamilyUser {
private Long id;
private Long familyId;//家庭表主键ID
private Long userId;//家庭表主键ID
private Integer isPointShare;//积分共享开关 0:开 1:关
private Integer familyRelationship;//与员 <SUF>
private Integer delFlag;//0:有效 1:无效
private Date updateDate;//更新时间
private Date createDate;//创建时间
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getFamilyId() {
return familyId;
}
public void setFamilyId(Long familyId) {
this.familyId = familyId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getIsPointShare() {
return isPointShare;
}
public void setIsPointShare(Integer isPointShare) {
this.isPointShare = isPointShare;
}
public Integer getFamilyRelationship() {
return familyRelationship;
}
public void setFamilyRelationship(Integer familyRelationship) {
this.familyRelationship = familyRelationship;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
| false | 457 | 42 | 516 | 67 | 523 | 42 | 516 | 67 | 671 | 91 | false | false | false | false | false | true |
46226_7 | package common.enums;
/**
* 枚举:婚姻状况
*
* @description
*
* @author DaiZhengmiao
* @createDate 2015年12月9日
*/
public enum Marital {
/** 未婚*/
UNMARRRIED(10,"未婚"),
/** 已婚 */
MARRIED(20,"已婚"),
/** 丧偶 */
WIDOWED(30,"丧偶"),
/** 离婚 */
DIVORCE(40,"离婚"),
/** 未知*/
NOMARRRIED(90,"未知"),
/** 未婚*/
UNMARRRIEDS(0,"未婚"),
/** 已婚 */
MARRIEDS(1,"已婚");
public int code;
public String value;
private Marital(int code, String value) {
this.code = code;
this.value = value;
}
public static Marital getEnum(int code){
Marital[] maritals = Marital.values();
for (Marital marital : maritals) {
if (marital.code == code) {
return marital;
}
}
return null;
}
}
| P79N6A/oyph | sp2p_sjzyj.common/app/common/enums/Marital.java | 333 | /** 已婚 */ | block_comment | zh-cn | package common.enums;
/**
* 枚举:婚姻状况
*
* @description
*
* @author DaiZhengmiao
* @createDate 2015年12月9日
*/
public enum Marital {
/** 未婚*/
UNMARRRIED(10,"未婚"),
/** 已婚 */
MARRIED(20,"已婚"),
/** 丧偶 */
WIDOWED(30,"丧偶"),
/** 离婚 */
DIVORCE(40,"离婚"),
/** 未知*/
NOMARRRIED(90,"未知"),
/** 未婚*/
UNMARRRIEDS(0,"未婚"),
/** 已婚 <SUF>*/
MARRIEDS(1,"已婚");
public int code;
public String value;
private Marital(int code, String value) {
this.code = code;
this.value = value;
}
public static Marital getEnum(int code){
Marital[] maritals = Marital.values();
for (Marital marital : maritals) {
if (marital.code == code) {
return marital;
}
}
return null;
}
}
| false | 267 | 5 | 333 | 6 | 310 | 4 | 333 | 6 | 409 | 7 | false | false | false | false | false | true |
39453_1 | package mmp.lock;
import java.util.concurrent.TimeUnit;
/**
* 可重入 互斥 独占锁
*/
public class ReentrantLock implements Lock {
private final Sync sync;
abstract static class Sync extends AbstractQueuedSynchronizer {
abstract void lock();
/**
* 尝试释放锁
*/
@Override
protected final boolean tryRelease(int releases) {
// releases对于独占锁是1
int c = getState() - releases; // 可重入,要释放重入获取的锁
// 如果当前线程没持有该锁
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// 如果剩余c==0(没有线程持有锁),当前线程就是最后一个持有锁的线程,唤醒下一个需要锁的AQS节点
// 否则就只是减少锁持有的计数器
if (c == 0) {
// 只有全部释放才返回true
free = true;
// 设置锁的持有者为null,同步队列的节点可以去获取同步状态了
setExclusiveOwnerThread(null);
}
// 设置锁状态
setState(c);
return free;
}
/**
* 相比较公平锁的 tryAcquire方法,少了hasQueuedPredecessors
* 直接抢锁,抢不到再进入队列,等待他的前继节点唤醒
*/
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 如果锁空闲
if (c == 0) {
// 获取到同步状态
if (compareAndSetState(0, acquires)) {
// 设置当前线程占有锁
setExclusiveOwnerThread(current);
return true;
}
}
// 线程已经占有锁了 重入
else if (current == getExclusiveOwnerThread()) {
// 同步状态记录重入的次数
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
@Override
protected final boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {
return new ConditionObject();
}
}
static final class NonfairSync extends Sync {
/**
* 非公平锁中,抢到AQS的同步状态的未必是FIFO同步队列的首节点
* 只要通过CAS抢到了同步状态或在acquire中抢到同步状态,就优先占有锁
*/
@Override
final void lock() {
// CAS设置同步状态,成功就设置锁的持有线程为自己 非公平
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
// 获取失败 进入AQS同步队列排队 执行AQS的acquire方法 公平
else
acquire(1);
}
@Override
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
static final class FairSync extends Sync {
@Override
final void lock() {
// 按AQS的同步队列去获取同步状态 公平
// 公平锁直接调用AQS的acquire方法,acquire中调用tryAcquire
acquire(1);
}
/**
* 和非公平锁相比,这里不会CAS,之后tryAcquire抢锁时,也会先调用hasQueuedPredecessors确定是否有前继节点等待
*/
@Override
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 如果锁空闲
if (c == 0) {
// 没有前驱节点(公平) && CAS设置state成功
if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) {
// 设置当前线程为锁的持有线程
setExclusiveOwnerThread(current);
// 抢锁成功
return true;
}
}
// 如果锁不空闲,但当前线程和锁的持有线程相同 重入
else if (current == getExclusiveOwnerThread()) {
// 重入次数
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
// 不用compareAndSetState,因为独占锁是当前线程,不需要CAS
setState(nextc);
return true;
}
return false;
}
}
/**
* 默认非公平锁
*/
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
/**
* 获取锁 阻塞
*/
@Override
public void lock() {
sync.lock();
}
/**
* 获取锁 阻塞 可以响应中断而停止阻塞返回
*/
@Override
public void lockInterruptibly() throws InterruptedException {
// 调用AQS#acquireInterruptibly
sync.acquireInterruptibly(1);
}
/**
* 获取锁 非阻塞 返回boolean
*/
@Override
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}
@Override
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
/**
* 释放锁
*/
@Override
public void unlock() {
sync.release(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
}
| P79N6A/whatever | juc/src/main/java/mmp/lock/ReentrantLock.java | 1,313 | /**
* 尝试释放锁
*/ | block_comment | zh-cn | package mmp.lock;
import java.util.concurrent.TimeUnit;
/**
* 可重入 互斥 独占锁
*/
public class ReentrantLock implements Lock {
private final Sync sync;
abstract static class Sync extends AbstractQueuedSynchronizer {
abstract void lock();
/**
* 尝试释 <SUF>*/
@Override
protected final boolean tryRelease(int releases) {
// releases对于独占锁是1
int c = getState() - releases; // 可重入,要释放重入获取的锁
// 如果当前线程没持有该锁
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// 如果剩余c==0(没有线程持有锁),当前线程就是最后一个持有锁的线程,唤醒下一个需要锁的AQS节点
// 否则就只是减少锁持有的计数器
if (c == 0) {
// 只有全部释放才返回true
free = true;
// 设置锁的持有者为null,同步队列的节点可以去获取同步状态了
setExclusiveOwnerThread(null);
}
// 设置锁状态
setState(c);
return free;
}
/**
* 相比较公平锁的 tryAcquire方法,少了hasQueuedPredecessors
* 直接抢锁,抢不到再进入队列,等待他的前继节点唤醒
*/
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 如果锁空闲
if (c == 0) {
// 获取到同步状态
if (compareAndSetState(0, acquires)) {
// 设置当前线程占有锁
setExclusiveOwnerThread(current);
return true;
}
}
// 线程已经占有锁了 重入
else if (current == getExclusiveOwnerThread()) {
// 同步状态记录重入的次数
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
@Override
protected final boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {
return new ConditionObject();
}
}
static final class NonfairSync extends Sync {
/**
* 非公平锁中,抢到AQS的同步状态的未必是FIFO同步队列的首节点
* 只要通过CAS抢到了同步状态或在acquire中抢到同步状态,就优先占有锁
*/
@Override
final void lock() {
// CAS设置同步状态,成功就设置锁的持有线程为自己 非公平
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
// 获取失败 进入AQS同步队列排队 执行AQS的acquire方法 公平
else
acquire(1);
}
@Override
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
static final class FairSync extends Sync {
@Override
final void lock() {
// 按AQS的同步队列去获取同步状态 公平
// 公平锁直接调用AQS的acquire方法,acquire中调用tryAcquire
acquire(1);
}
/**
* 和非公平锁相比,这里不会CAS,之后tryAcquire抢锁时,也会先调用hasQueuedPredecessors确定是否有前继节点等待
*/
@Override
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 如果锁空闲
if (c == 0) {
// 没有前驱节点(公平) && CAS设置state成功
if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) {
// 设置当前线程为锁的持有线程
setExclusiveOwnerThread(current);
// 抢锁成功
return true;
}
}
// 如果锁不空闲,但当前线程和锁的持有线程相同 重入
else if (current == getExclusiveOwnerThread()) {
// 重入次数
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
// 不用compareAndSetState,因为独占锁是当前线程,不需要CAS
setState(nextc);
return true;
}
return false;
}
}
/**
* 默认非公平锁
*/
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
/**
* 获取锁 阻塞
*/
@Override
public void lock() {
sync.lock();
}
/**
* 获取锁 阻塞 可以响应中断而停止阻塞返回
*/
@Override
public void lockInterruptibly() throws InterruptedException {
// 调用AQS#acquireInterruptibly
sync.acquireInterruptibly(1);
}
/**
* 获取锁 非阻塞 返回boolean
*/
@Override
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}
@Override
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
/**
* 释放锁
*/
@Override
public void unlock() {
sync.release(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
}
| false | 1,336 | 11 | 1,312 | 9 | 1,402 | 11 | 1,313 | 9 | 1,964 | 19 | false | false | false | false | false | true |
27246_3 | package com.pgzxc.live.data.bean;
/**
* 礼物
*/
public class Gif {
public String userName; //送礼人
public String giftName; //礼物名
public int giftType; //礼物图像
public int gifNum; //送礼数
public int avatar;//头像
public String gitCost;//礼物费用
private boolean isSelected;//是否选中
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getGiftName() {
return giftName;
}
public void setGiftName(String giftName) {
this.giftName = giftName;
}
public int getGiftType() {
return giftType;
}
public void setGiftType(int giftType) {
this.giftType = giftType;
}
public int getGifNum() {
return gifNum;
}
public void setGifNum(int gifNum) {
this.gifNum = gifNum;
}
public int getAvatar() {
return avatar;
}
public void setAvatar(int avatar) {
this.avatar = avatar;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getGitCost() {
return gitCost;
}
public void setGitCost(String gitCost) {
this.gitCost = gitCost;
}
}
| PGzxc/Live | app/src/main/java/com/pgzxc/live/data/bean/Gif.java | 351 | //礼物图像 | line_comment | zh-cn | package com.pgzxc.live.data.bean;
/**
* 礼物
*/
public class Gif {
public String userName; //送礼人
public String giftName; //礼物名
public int giftType; //礼物 <SUF>
public int gifNum; //送礼数
public int avatar;//头像
public String gitCost;//礼物费用
private boolean isSelected;//是否选中
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getGiftName() {
return giftName;
}
public void setGiftName(String giftName) {
this.giftName = giftName;
}
public int getGiftType() {
return giftType;
}
public void setGiftType(int giftType) {
this.giftType = giftType;
}
public int getGifNum() {
return gifNum;
}
public void setGifNum(int gifNum) {
this.gifNum = gifNum;
}
public int getAvatar() {
return avatar;
}
public void setAvatar(int avatar) {
this.avatar = avatar;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getGitCost() {
return gitCost;
}
public void setGitCost(String gitCost) {
this.gitCost = gitCost;
}
}
| false | 324 | 3 | 351 | 5 | 379 | 3 | 351 | 5 | 454 | 7 | false | false | false | false | false | true |
37914_22 | package com.xsjsglxt.domain.DO;
public class xsjsglxt_handle {
private String xsjsglxt_handle_id;//办案ID
private String handle_orderNumber;//序号
private String handle_administrativeCase;//行政案件名称
private String handle_suspectName;//违法嫌疑人姓名
private String handle_administrativeAttachment;//行政拘留
private String handle_arrest;//逮捕
private String handle_prosecute;//起诉
private String handle_checkback;//退查
private String handle_pbat;//取保候审
private String handle_lhus;//监视居住
private String handle_StartTimeaOfDetention;//拘留起始时间
private String handle_arrestTime;//逮捕时间
private String handle_prosecuteTime;//起诉时间
private String handle_checkbackTime;//退查时间
private String handle_pbatTime;//取保候审时间
private String handle_lhusTime;//监视居住时间
private String handle_detentionDay;//拘留时间
private String handle_FinancialName;// 财物名称
private String handle_handTime;//上交时间
private String handle_handleTime;//处理时间
private String handle_processMode;//处理方式
private String handle_squadronleader;//中队长
private String handle_PoliceInHandlingCases;//办案民警
private String handle_gnt_create;//创建时间
private String handle_gmt_modified;//修改时间
public xsjsglxt_handle() {
// TODO Auto-generated constructor stub
}
public xsjsglxt_handle(String xsjsglxt_handle_id, String handle_orderNumber, String handle_administrativeCase,
String handle_suspectName, String handle_administrativeAttachment, String handle_arrest,
String handle_prosecute, String handle_checkback, String handle_pbat, String handle_lhus,
String handle_StartTimeaOfDetention, String handle_arrestTime, String handle_prosecuteTime,
String handle_checkbackTime, String handle_pbatTime, String handle_lhusTime, String handle_detentionDay,
String handle_FinancialName, String handle_handTime, String handle_handleTime, String handle_processMode,
String handle_squadronleader, String handle_PoliceInHandlingCases, String handle_gnt_create,
String handle_gmt_modified) {
this.xsjsglxt_handle_id = xsjsglxt_handle_id;
this.handle_orderNumber = handle_orderNumber;
this.handle_administrativeCase = handle_administrativeCase;
this.handle_suspectName = handle_suspectName;
this.handle_administrativeAttachment = handle_administrativeAttachment;
this.handle_arrest = handle_arrest;
this.handle_prosecute = handle_prosecute;
this.handle_checkback = handle_checkback;
this.handle_pbat = handle_pbat;
this.handle_lhus = handle_lhus;
this.handle_StartTimeaOfDetention = handle_StartTimeaOfDetention;
this.handle_arrestTime = handle_arrestTime;
this.handle_prosecuteTime = handle_prosecuteTime;
this.handle_checkbackTime = handle_checkbackTime;
this.handle_pbatTime = handle_pbatTime;
this.handle_lhusTime = handle_lhusTime;
this.handle_detentionDay = handle_detentionDay;
this.handle_FinancialName = handle_FinancialName;
this.handle_handTime = handle_handTime;
this.handle_handleTime = handle_handleTime;
this.handle_processMode = handle_processMode;
this.handle_squadronleader = handle_squadronleader;
this.handle_PoliceInHandlingCases = handle_PoliceInHandlingCases;
this.handle_gnt_create = handle_gnt_create;
this.handle_gmt_modified = handle_gmt_modified;
}
@Override
public String toString() {
return "xsjsglxt_handle [xsjsglxt_handle_id=" + xsjsglxt_handle_id + ", handle_orderNumber=" + handle_orderNumber
+ ", handle_administrativeCase=" + handle_administrativeCase + ", handle_suspectName=" + handle_suspectName
+ ", handle_administrativeAttachment=" + handle_administrativeAttachment + ", handle_arrest="
+ handle_arrest + ", handle_prosecute=" + handle_prosecute + ", handle_checkback=" + handle_checkback
+ ", handle_pbat=" + handle_pbat + ", handle_lhus=" + handle_lhus + ", handle_StartTimeaOfDetention="
+ handle_StartTimeaOfDetention + ", handle_arrestTime=" + handle_arrestTime + ", handle_prosecuteTime="
+ handle_prosecuteTime + ", handle_checkbackTime=" + handle_checkbackTime + ", handle_pbatTime="
+ handle_pbatTime + ", handle_lhusTime=" + handle_lhusTime + ", handle_detentionDay=" + handle_detentionDay
+ ", handle_FinancialName=" + handle_FinancialName + ", handle_handTime=" + handle_handTime
+ ", handle_handleTime=" + handle_handleTime + ", handle_processMode=" + handle_processMode
+ ", handle_squadronleader=" + handle_squadronleader + ", handle_PoliceInHandlingCases="
+ handle_PoliceInHandlingCases + ", handle_gnt_create=" + handle_gnt_create + ", handle_gmt_modified="
+ handle_gmt_modified + "]";
}
public String getXsjsglxt_handle_id() {
return xsjsglxt_handle_id;
}
public void setXsjsglxt_handle_id(String xsjsglxt_handle_id) {
this.xsjsglxt_handle_id = xsjsglxt_handle_id;
}
public String getHandle_orderNumber() {
return handle_orderNumber;
}
public void setHandle_orderNumber(String handle_orderNumber) {
this.handle_orderNumber = handle_orderNumber;
}
public String getHandle_administrativeCase() {
return handle_administrativeCase;
}
public void setHandle_administrativeCase(String handle_administrativeCase) {
this.handle_administrativeCase = handle_administrativeCase;
}
public String getHandle_suspectName() {
return handle_suspectName;
}
public void setHandle_suspectName(String handle_suspectName) {
this.handle_suspectName = handle_suspectName;
}
public String getHandle_administrativeAttachment() {
return handle_administrativeAttachment;
}
public void setHandle_administrativeAttachment(String handle_administrativeAttachment) {
this.handle_administrativeAttachment = handle_administrativeAttachment;
}
public String getHandle_arrest() {
return handle_arrest;
}
public void setHandle_arrest(String handle_arrest) {
this.handle_arrest = handle_arrest;
}
public String getHandle_prosecute() {
return handle_prosecute;
}
public void setHandle_prosecute(String handle_prosecute) {
this.handle_prosecute = handle_prosecute;
}
public String getHandle_checkback() {
return handle_checkback;
}
public void setHandle_checkback(String handle_checkback) {
this.handle_checkback = handle_checkback;
}
public String getHandle_pbat() {
return handle_pbat;
}
public void setHandle_pbat(String handle_pbat) {
this.handle_pbat = handle_pbat;
}
public String getHandle_lhus() {
return handle_lhus;
}
public void setHandle_lhus(String handle_lhus) {
this.handle_lhus = handle_lhus;
}
public String getHandle_StartTimeaOfDetention() {
return handle_StartTimeaOfDetention;
}
public void setHandle_StartTimeaOfDetention(String handle_StartTimeaOfDetention) {
this.handle_StartTimeaOfDetention = handle_StartTimeaOfDetention;
}
public String getHandle_arrestTime() {
return handle_arrestTime;
}
public void setHandle_arrestTime(String handle_arrestTime) {
this.handle_arrestTime = handle_arrestTime;
}
public String getHandle_prosecuteTime() {
return handle_prosecuteTime;
}
public void setHandle_prosecuteTime(String handle_prosecuteTime) {
this.handle_prosecuteTime = handle_prosecuteTime;
}
public String getHandle_checkbackTime() {
return handle_checkbackTime;
}
public void setHandle_checkbackTime(String handle_checkbackTime) {
this.handle_checkbackTime = handle_checkbackTime;
}
public String getHandle_pbatTime() {
return handle_pbatTime;
}
public void setHandle_pbatTime(String handle_pbatTime) {
this.handle_pbatTime = handle_pbatTime;
}
public String getHandle_lhusTime() {
return handle_lhusTime;
}
public void setHandle_lhusTime(String handle_lhusTime) {
this.handle_lhusTime = handle_lhusTime;
}
public String getHandle_detentionDay() {
return handle_detentionDay;
}
public void setHandle_detentionDay(String handle_detentionDay) {
this.handle_detentionDay = handle_detentionDay;
}
public String getHandle_FinancialName() {
return handle_FinancialName;
}
public void setHandle_FinancialName(String handle_FinancialName) {
this.handle_FinancialName = handle_FinancialName;
}
public String getHandle_handTime() {
return handle_handTime;
}
public void setHandle_handTime(String handle_handTime) {
this.handle_handTime = handle_handTime;
}
public String getHandle_handleTime() {
return handle_handleTime;
}
public void setHandle_handleTime(String handle_handleTime) {
this.handle_handleTime = handle_handleTime;
}
public String getHandle_processMode() {
return handle_processMode;
}
public void setHandle_processMode(String handle_processMode) {
this.handle_processMode = handle_processMode;
}
public String getHandle_squadronleader() {
return handle_squadronleader;
}
public void setHandle_squadronleader(String handle_squadronleader) {
this.handle_squadronleader = handle_squadronleader;
}
public String getHandle_PoliceInHandlingCases() {
return handle_PoliceInHandlingCases;
}
public void setHandle_PoliceInHandlingCases(String handle_PoliceInHandlingCases) {
this.handle_PoliceInHandlingCases = handle_PoliceInHandlingCases;
}
public String getHandle_gnt_create() {
return handle_gnt_create;
}
public void setHandle_gnt_create(String handle_gnt_create) {
this.handle_gnt_create = handle_gnt_create;
}
public String getHandle_gmt_modified() {
return handle_gmt_modified;
}
public void setHandle_gmt_modified(String handle_gmt_modified) {
this.handle_gmt_modified = handle_gmt_modified;
}
}
| PPMonkeyStudio/xsjsglxt | src/com/xsjsglxt/domain/DO/xsjsglxt_handle.java | 2,958 | //办案民警
| line_comment | zh-cn | package com.xsjsglxt.domain.DO;
public class xsjsglxt_handle {
private String xsjsglxt_handle_id;//办案ID
private String handle_orderNumber;//序号
private String handle_administrativeCase;//行政案件名称
private String handle_suspectName;//违法嫌疑人姓名
private String handle_administrativeAttachment;//行政拘留
private String handle_arrest;//逮捕
private String handle_prosecute;//起诉
private String handle_checkback;//退查
private String handle_pbat;//取保候审
private String handle_lhus;//监视居住
private String handle_StartTimeaOfDetention;//拘留起始时间
private String handle_arrestTime;//逮捕时间
private String handle_prosecuteTime;//起诉时间
private String handle_checkbackTime;//退查时间
private String handle_pbatTime;//取保候审时间
private String handle_lhusTime;//监视居住时间
private String handle_detentionDay;//拘留时间
private String handle_FinancialName;// 财物名称
private String handle_handTime;//上交时间
private String handle_handleTime;//处理时间
private String handle_processMode;//处理方式
private String handle_squadronleader;//中队长
private String handle_PoliceInHandlingCases;//办案 <SUF>
private String handle_gnt_create;//创建时间
private String handle_gmt_modified;//修改时间
public xsjsglxt_handle() {
// TODO Auto-generated constructor stub
}
public xsjsglxt_handle(String xsjsglxt_handle_id, String handle_orderNumber, String handle_administrativeCase,
String handle_suspectName, String handle_administrativeAttachment, String handle_arrest,
String handle_prosecute, String handle_checkback, String handle_pbat, String handle_lhus,
String handle_StartTimeaOfDetention, String handle_arrestTime, String handle_prosecuteTime,
String handle_checkbackTime, String handle_pbatTime, String handle_lhusTime, String handle_detentionDay,
String handle_FinancialName, String handle_handTime, String handle_handleTime, String handle_processMode,
String handle_squadronleader, String handle_PoliceInHandlingCases, String handle_gnt_create,
String handle_gmt_modified) {
this.xsjsglxt_handle_id = xsjsglxt_handle_id;
this.handle_orderNumber = handle_orderNumber;
this.handle_administrativeCase = handle_administrativeCase;
this.handle_suspectName = handle_suspectName;
this.handle_administrativeAttachment = handle_administrativeAttachment;
this.handle_arrest = handle_arrest;
this.handle_prosecute = handle_prosecute;
this.handle_checkback = handle_checkback;
this.handle_pbat = handle_pbat;
this.handle_lhus = handle_lhus;
this.handle_StartTimeaOfDetention = handle_StartTimeaOfDetention;
this.handle_arrestTime = handle_arrestTime;
this.handle_prosecuteTime = handle_prosecuteTime;
this.handle_checkbackTime = handle_checkbackTime;
this.handle_pbatTime = handle_pbatTime;
this.handle_lhusTime = handle_lhusTime;
this.handle_detentionDay = handle_detentionDay;
this.handle_FinancialName = handle_FinancialName;
this.handle_handTime = handle_handTime;
this.handle_handleTime = handle_handleTime;
this.handle_processMode = handle_processMode;
this.handle_squadronleader = handle_squadronleader;
this.handle_PoliceInHandlingCases = handle_PoliceInHandlingCases;
this.handle_gnt_create = handle_gnt_create;
this.handle_gmt_modified = handle_gmt_modified;
}
@Override
public String toString() {
return "xsjsglxt_handle [xsjsglxt_handle_id=" + xsjsglxt_handle_id + ", handle_orderNumber=" + handle_orderNumber
+ ", handle_administrativeCase=" + handle_administrativeCase + ", handle_suspectName=" + handle_suspectName
+ ", handle_administrativeAttachment=" + handle_administrativeAttachment + ", handle_arrest="
+ handle_arrest + ", handle_prosecute=" + handle_prosecute + ", handle_checkback=" + handle_checkback
+ ", handle_pbat=" + handle_pbat + ", handle_lhus=" + handle_lhus + ", handle_StartTimeaOfDetention="
+ handle_StartTimeaOfDetention + ", handle_arrestTime=" + handle_arrestTime + ", handle_prosecuteTime="
+ handle_prosecuteTime + ", handle_checkbackTime=" + handle_checkbackTime + ", handle_pbatTime="
+ handle_pbatTime + ", handle_lhusTime=" + handle_lhusTime + ", handle_detentionDay=" + handle_detentionDay
+ ", handle_FinancialName=" + handle_FinancialName + ", handle_handTime=" + handle_handTime
+ ", handle_handleTime=" + handle_handleTime + ", handle_processMode=" + handle_processMode
+ ", handle_squadronleader=" + handle_squadronleader + ", handle_PoliceInHandlingCases="
+ handle_PoliceInHandlingCases + ", handle_gnt_create=" + handle_gnt_create + ", handle_gmt_modified="
+ handle_gmt_modified + "]";
}
public String getXsjsglxt_handle_id() {
return xsjsglxt_handle_id;
}
public void setXsjsglxt_handle_id(String xsjsglxt_handle_id) {
this.xsjsglxt_handle_id = xsjsglxt_handle_id;
}
public String getHandle_orderNumber() {
return handle_orderNumber;
}
public void setHandle_orderNumber(String handle_orderNumber) {
this.handle_orderNumber = handle_orderNumber;
}
public String getHandle_administrativeCase() {
return handle_administrativeCase;
}
public void setHandle_administrativeCase(String handle_administrativeCase) {
this.handle_administrativeCase = handle_administrativeCase;
}
public String getHandle_suspectName() {
return handle_suspectName;
}
public void setHandle_suspectName(String handle_suspectName) {
this.handle_suspectName = handle_suspectName;
}
public String getHandle_administrativeAttachment() {
return handle_administrativeAttachment;
}
public void setHandle_administrativeAttachment(String handle_administrativeAttachment) {
this.handle_administrativeAttachment = handle_administrativeAttachment;
}
public String getHandle_arrest() {
return handle_arrest;
}
public void setHandle_arrest(String handle_arrest) {
this.handle_arrest = handle_arrest;
}
public String getHandle_prosecute() {
return handle_prosecute;
}
public void setHandle_prosecute(String handle_prosecute) {
this.handle_prosecute = handle_prosecute;
}
public String getHandle_checkback() {
return handle_checkback;
}
public void setHandle_checkback(String handle_checkback) {
this.handle_checkback = handle_checkback;
}
public String getHandle_pbat() {
return handle_pbat;
}
public void setHandle_pbat(String handle_pbat) {
this.handle_pbat = handle_pbat;
}
public String getHandle_lhus() {
return handle_lhus;
}
public void setHandle_lhus(String handle_lhus) {
this.handle_lhus = handle_lhus;
}
public String getHandle_StartTimeaOfDetention() {
return handle_StartTimeaOfDetention;
}
public void setHandle_StartTimeaOfDetention(String handle_StartTimeaOfDetention) {
this.handle_StartTimeaOfDetention = handle_StartTimeaOfDetention;
}
public String getHandle_arrestTime() {
return handle_arrestTime;
}
public void setHandle_arrestTime(String handle_arrestTime) {
this.handle_arrestTime = handle_arrestTime;
}
public String getHandle_prosecuteTime() {
return handle_prosecuteTime;
}
public void setHandle_prosecuteTime(String handle_prosecuteTime) {
this.handle_prosecuteTime = handle_prosecuteTime;
}
public String getHandle_checkbackTime() {
return handle_checkbackTime;
}
public void setHandle_checkbackTime(String handle_checkbackTime) {
this.handle_checkbackTime = handle_checkbackTime;
}
public String getHandle_pbatTime() {
return handle_pbatTime;
}
public void setHandle_pbatTime(String handle_pbatTime) {
this.handle_pbatTime = handle_pbatTime;
}
public String getHandle_lhusTime() {
return handle_lhusTime;
}
public void setHandle_lhusTime(String handle_lhusTime) {
this.handle_lhusTime = handle_lhusTime;
}
public String getHandle_detentionDay() {
return handle_detentionDay;
}
public void setHandle_detentionDay(String handle_detentionDay) {
this.handle_detentionDay = handle_detentionDay;
}
public String getHandle_FinancialName() {
return handle_FinancialName;
}
public void setHandle_FinancialName(String handle_FinancialName) {
this.handle_FinancialName = handle_FinancialName;
}
public String getHandle_handTime() {
return handle_handTime;
}
public void setHandle_handTime(String handle_handTime) {
this.handle_handTime = handle_handTime;
}
public String getHandle_handleTime() {
return handle_handleTime;
}
public void setHandle_handleTime(String handle_handleTime) {
this.handle_handleTime = handle_handleTime;
}
public String getHandle_processMode() {
return handle_processMode;
}
public void setHandle_processMode(String handle_processMode) {
this.handle_processMode = handle_processMode;
}
public String getHandle_squadronleader() {
return handle_squadronleader;
}
public void setHandle_squadronleader(String handle_squadronleader) {
this.handle_squadronleader = handle_squadronleader;
}
public String getHandle_PoliceInHandlingCases() {
return handle_PoliceInHandlingCases;
}
public void setHandle_PoliceInHandlingCases(String handle_PoliceInHandlingCases) {
this.handle_PoliceInHandlingCases = handle_PoliceInHandlingCases;
}
public String getHandle_gnt_create() {
return handle_gnt_create;
}
public void setHandle_gnt_create(String handle_gnt_create) {
this.handle_gnt_create = handle_gnt_create;
}
public String getHandle_gmt_modified() {
return handle_gmt_modified;
}
public void setHandle_gmt_modified(String handle_gmt_modified) {
this.handle_gmt_modified = handle_gmt_modified;
}
}
| false | 2,222 | 4 | 2,827 | 6 | 2,728 | 6 | 2,827 | 6 | 3,108 | 12 | false | false | false | false | false | true |
43161_1 | package com.example.orders.chat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.example.orders.R;
import com.example.orders.activity.OrderProcessActivity;
import com.example.orders.avatar.AvatarActivity;
import com.example.orders.dialog.PromptDialog;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
public class ChatActivity extends Activity implements OnClickListener {
private Button mBtnSend;
private EditText mEditTextContent;
private ChatMsgViewAdapter mAdapter;
private ListView mListView;
private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();
private Button function_order_add;
private Button funtionButton;
private Button function_oeder_process;
private ImageButton chat_imageButton1;
private RelativeLayout rl_bottom_down;
public String isRead;
private boolean isShow = false;
public TableRow tableRow_function_button;
private String addMoney;
private String addReason;
private String contString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.chatting_activity_pusher);
initView();
initData();
function_order_add = (Button) findViewById(R.id.function_order_add);
function_order_add.setOnClickListener(new AddListener());
chat_imageButton1 = (ImageButton) findViewById(R.id.chat_imageButton1);
chat_imageButton1.setOnClickListener(new AvatarListener());
rl_bottom_down = (RelativeLayout) findViewById(R.id.rl_bottom_down);
Bundle bundle = getIntent().getExtras(); // 得到传过来的bundle
isRead = bundle.getString("isRead");// 读出数据
if (isRead.equals("false")) {
rl_bottom_down.setVisibility(View.GONE);
} else {
rl_bottom_down.setVisibility(View.VISIBLE);
}
tableRow_function_button = (TableRow) findViewById(R.id.tableRow_function_button);
tableRow_function_button.setVisibility(View.GONE);
funtionButton = (Button) findViewById(R.id.funtionButton);
funtionButton.setOnClickListener(new ShowFunctionButtonListener());
function_oeder_process = (Button) findViewById(R.id.function_oeder_process);
function_oeder_process.setOnClickListener(new LookOrderListener());
}
public void showAlertDialog(View view) {
PromptDialog.Builder builder = new PromptDialog.Builder(this);
builder.setMessage("修改金额:" + addMoney + '\n' + "修改原因:" + addReason);
builder.setTitle("是否确认");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 在这里处理修改订单信息
}
});
builder.setNegativeButton("取消",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
public class LookOrderListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
tableRow_function_button.setVisibility(View.GONE);
isShow = false;
Intent intent = new Intent();
intent.setClass(ChatActivity.this, OrderProcessActivity.class);
ChatActivity.this.startActivity(intent);
}
}
public class ShowFunctionButtonListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
if (isShow) {
tableRow_function_button.setVisibility(View.GONE);
isShow = false;
} else {
tableRow_function_button.setVisibility(View.VISIBLE);
isShow = true;
}
}
}
public class AddListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
tableRow_function_button.setVisibility(View.GONE);
isShow = false;
startActivityForResult(new Intent(ChatActivity.this,
AddMoneyActivity.class), 10000);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (null != data && resultCode == Activity.RESULT_OK) {
addMoney = data.getStringExtra("add_M");
addReason = data.getStringExtra("add_R");
if (addMoney != null && addReason != null) {
contString = " " + "重要信息:" + '\n' + " " + "修改金额:"
+ addMoney + '\n' + " " + "修改原因:" + addReason;
send(contString, false, true);
}
}
tableRow_function_button.setVisibility(View.GONE);
}
public class AvatarListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(ChatActivity.this, AvatarActivity.class);
ChatActivity.this.startActivity(intent);
}
}
private void initView() {
mListView = (ListView) findViewById(R.id.chat_listview);
mBtnSend = (Button) findViewById(R.id.btn_send);
mBtnSend.setOnClickListener(this);
mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
}
private String[] msgArray = new String[] { "在么?", "在,怎么了?", "干么呢?", "不干吗",
"哦", "。。。", "拜拜", "拜拜" };
private String[] dataArray = new String[] { "2015-05-15 18:00",
"2015-05-15 18:10", "2015-05-15 18:11", "2015-05-15 18:20",
"2015-05-15 18:30", "2015-05-15 18:35", "2015-05-15 18:40",
"2015-05-15 18:50" };
private int COUNT = msgArray.length;
private void initData() {
for (int i = 0; i < COUNT; i++) {
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(dataArray[i]);
if (i % 2 == 0) {
entity.setName("下单");
entity.setMsgType(false);
entity.setMsgTypeImport(false);
} else {
entity.setName("接单");
entity.setMsgType(true);
entity.setMsgTypeImport(false);
}
entity.setText(msgArray[i]);
mDataArrays.add(entity);
}
mAdapter = new ChatMsgViewAdapter(this, mDataArrays);
mListView.setAdapter(mAdapter);
}
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.btn_send:
send(mEditTextContent.getText().toString(), false, false);
break;
}
}
private void send(String s, boolean type, boolean typeImport) {
if (s.length() > 0) {
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(getDate());
entity.setName("下单");
entity.setMsgType(type);
entity.setMsgTypeImport(typeImport);
entity.setText(s);
mDataArrays.add(entity);
mAdapter.notifyDataSetChanged();
mEditTextContent.setText("");
mListView.setSelection(mListView.getCount());
}
}
private String getDate() {
Calendar c = Calendar.getInstance();
String year = String.valueOf(c.get(Calendar.YEAR));
String month = String.valueOf(c.get(Calendar.MONTH));
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
String mins = String.valueOf(c.get(Calendar.MINUTE));
StringBuffer sbBuffer = new StringBuffer();
sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
+ mins);
return sbBuffer.toString();
}
}
| PaiGaVR/Orders | src/com/example/orders/chat/ChatActivity.java | 2,280 | // 读出数据
| line_comment | zh-cn | package com.example.orders.chat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.example.orders.R;
import com.example.orders.activity.OrderProcessActivity;
import com.example.orders.avatar.AvatarActivity;
import com.example.orders.dialog.PromptDialog;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
public class ChatActivity extends Activity implements OnClickListener {
private Button mBtnSend;
private EditText mEditTextContent;
private ChatMsgViewAdapter mAdapter;
private ListView mListView;
private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();
private Button function_order_add;
private Button funtionButton;
private Button function_oeder_process;
private ImageButton chat_imageButton1;
private RelativeLayout rl_bottom_down;
public String isRead;
private boolean isShow = false;
public TableRow tableRow_function_button;
private String addMoney;
private String addReason;
private String contString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.chatting_activity_pusher);
initView();
initData();
function_order_add = (Button) findViewById(R.id.function_order_add);
function_order_add.setOnClickListener(new AddListener());
chat_imageButton1 = (ImageButton) findViewById(R.id.chat_imageButton1);
chat_imageButton1.setOnClickListener(new AvatarListener());
rl_bottom_down = (RelativeLayout) findViewById(R.id.rl_bottom_down);
Bundle bundle = getIntent().getExtras(); // 得到传过来的bundle
isRead = bundle.getString("isRead");// 读出 <SUF>
if (isRead.equals("false")) {
rl_bottom_down.setVisibility(View.GONE);
} else {
rl_bottom_down.setVisibility(View.VISIBLE);
}
tableRow_function_button = (TableRow) findViewById(R.id.tableRow_function_button);
tableRow_function_button.setVisibility(View.GONE);
funtionButton = (Button) findViewById(R.id.funtionButton);
funtionButton.setOnClickListener(new ShowFunctionButtonListener());
function_oeder_process = (Button) findViewById(R.id.function_oeder_process);
function_oeder_process.setOnClickListener(new LookOrderListener());
}
public void showAlertDialog(View view) {
PromptDialog.Builder builder = new PromptDialog.Builder(this);
builder.setMessage("修改金额:" + addMoney + '\n' + "修改原因:" + addReason);
builder.setTitle("是否确认");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 在这里处理修改订单信息
}
});
builder.setNegativeButton("取消",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
public class LookOrderListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
tableRow_function_button.setVisibility(View.GONE);
isShow = false;
Intent intent = new Intent();
intent.setClass(ChatActivity.this, OrderProcessActivity.class);
ChatActivity.this.startActivity(intent);
}
}
public class ShowFunctionButtonListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
if (isShow) {
tableRow_function_button.setVisibility(View.GONE);
isShow = false;
} else {
tableRow_function_button.setVisibility(View.VISIBLE);
isShow = true;
}
}
}
public class AddListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
tableRow_function_button.setVisibility(View.GONE);
isShow = false;
startActivityForResult(new Intent(ChatActivity.this,
AddMoneyActivity.class), 10000);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (null != data && resultCode == Activity.RESULT_OK) {
addMoney = data.getStringExtra("add_M");
addReason = data.getStringExtra("add_R");
if (addMoney != null && addReason != null) {
contString = " " + "重要信息:" + '\n' + " " + "修改金额:"
+ addMoney + '\n' + " " + "修改原因:" + addReason;
send(contString, false, true);
}
}
tableRow_function_button.setVisibility(View.GONE);
}
public class AvatarListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(ChatActivity.this, AvatarActivity.class);
ChatActivity.this.startActivity(intent);
}
}
private void initView() {
mListView = (ListView) findViewById(R.id.chat_listview);
mBtnSend = (Button) findViewById(R.id.btn_send);
mBtnSend.setOnClickListener(this);
mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
}
private String[] msgArray = new String[] { "在么?", "在,怎么了?", "干么呢?", "不干吗",
"哦", "。。。", "拜拜", "拜拜" };
private String[] dataArray = new String[] { "2015-05-15 18:00",
"2015-05-15 18:10", "2015-05-15 18:11", "2015-05-15 18:20",
"2015-05-15 18:30", "2015-05-15 18:35", "2015-05-15 18:40",
"2015-05-15 18:50" };
private int COUNT = msgArray.length;
private void initData() {
for (int i = 0; i < COUNT; i++) {
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(dataArray[i]);
if (i % 2 == 0) {
entity.setName("下单");
entity.setMsgType(false);
entity.setMsgTypeImport(false);
} else {
entity.setName("接单");
entity.setMsgType(true);
entity.setMsgTypeImport(false);
}
entity.setText(msgArray[i]);
mDataArrays.add(entity);
}
mAdapter = new ChatMsgViewAdapter(this, mDataArrays);
mListView.setAdapter(mAdapter);
}
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.btn_send:
send(mEditTextContent.getText().toString(), false, false);
break;
}
}
private void send(String s, boolean type, boolean typeImport) {
if (s.length() > 0) {
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(getDate());
entity.setName("下单");
entity.setMsgType(type);
entity.setMsgTypeImport(typeImport);
entity.setText(s);
mDataArrays.add(entity);
mAdapter.notifyDataSetChanged();
mEditTextContent.setText("");
mListView.setSelection(mListView.getCount());
}
}
private String getDate() {
Calendar c = Calendar.getInstance();
String year = String.valueOf(c.get(Calendar.YEAR));
String month = String.valueOf(c.get(Calendar.MONTH));
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
String mins = String.valueOf(c.get(Calendar.MINUTE));
StringBuffer sbBuffer = new StringBuffer();
sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
+ mins);
return sbBuffer.toString();
}
}
| false | 1,741 | 6 | 2,262 | 6 | 2,202 | 5 | 2,262 | 6 | 2,686 | 9 | false | false | false | false | false | true |
57058_6 | package com.pandaq.pandaeye.config;
/**
* Created by PandaQ on 2016/9/8.
* email : [email protected]
* 应用配置类,用于配置
*/
public class Config {
public static final boolean DEBUG = true;
public static String DOUBAN_API_URL = "http://api.douban.com/v2/";
public static String ZHIHU_API_URL = "http://news-at.zhihu.com/api/4/";
public static String NETEASY_NEWS_API = "http://c.m.163.com/nc/article/";
public static String MOVIE_API_URL = "http://api.svipmovie.com/front/";
public static String GITHUB_API_URL = "https://api.github.com/";
/**
* 视频分类ID
*/
//热点资讯
public static final String MOVIE_TYPE_HOT = "402834815584e463015584e539700019";
//精彩推荐
public static final String MOVIE_TYPE_RECOMMEND = "402834815584e463015584e53843000b";
//好莱坞
public static final String MOVIE_TYPE_HOLLYWOOD = "402834815584e463015584e538140009";
//专题 根据当前时间戳获取
// public static String MOVIE_TYPE_TOPIC = "402834815584e463015584e538140009";
//直播专区
public static final String MOVIE_TYPE_LIVE = "402834815584e463015584e537d00006";
//微电影
public static final String MOVIE_TYPE_LITTLEMOVIE = "0000000055b9a5a00155ba33b405000d";
//日韩精选
public static final String MOVIE_TYPE_JSKS = "402834815584e463015584e538a2000f";
//大咖剧场
public static final String MOVIE_TYPE_BIGBRO = "402834815584e463015584e537bf0005";
//午夜剧场
public static final String MOVIE_TYPE_MIDNIGHT = "402834815584e463015584e5390d0014";
//大片抢先看
public static final String MOVIE_TYPE_BIG = "402834815584e463015584e539330016";
//香港印象
public static final String MOVIE_TYPE_HONGKONG = "ff8080815b9075a6015b94ef79dc0284";
}
| PandaQAQ/PandaEye | app/src/main/java/com/pandaq/pandaeye/config/Config.java | 812 | /**
* 视频分类ID
*/ | block_comment | zh-cn | package com.pandaq.pandaeye.config;
/**
* Created by PandaQ on 2016/9/8.
* email : [email protected]
* 应用配置类,用于配置
*/
public class Config {
public static final boolean DEBUG = true;
public static String DOUBAN_API_URL = "http://api.douban.com/v2/";
public static String ZHIHU_API_URL = "http://news-at.zhihu.com/api/4/";
public static String NETEASY_NEWS_API = "http://c.m.163.com/nc/article/";
public static String MOVIE_API_URL = "http://api.svipmovie.com/front/";
public static String GITHUB_API_URL = "https://api.github.com/";
/**
* 视频分 <SUF>*/
//热点资讯
public static final String MOVIE_TYPE_HOT = "402834815584e463015584e539700019";
//精彩推荐
public static final String MOVIE_TYPE_RECOMMEND = "402834815584e463015584e53843000b";
//好莱坞
public static final String MOVIE_TYPE_HOLLYWOOD = "402834815584e463015584e538140009";
//专题 根据当前时间戳获取
// public static String MOVIE_TYPE_TOPIC = "402834815584e463015584e538140009";
//直播专区
public static final String MOVIE_TYPE_LIVE = "402834815584e463015584e537d00006";
//微电影
public static final String MOVIE_TYPE_LITTLEMOVIE = "0000000055b9a5a00155ba33b405000d";
//日韩精选
public static final String MOVIE_TYPE_JSKS = "402834815584e463015584e538a2000f";
//大咖剧场
public static final String MOVIE_TYPE_BIGBRO = "402834815584e463015584e537bf0005";
//午夜剧场
public static final String MOVIE_TYPE_MIDNIGHT = "402834815584e463015584e5390d0014";
//大片抢先看
public static final String MOVIE_TYPE_BIG = "402834815584e463015584e539330016";
//香港印象
public static final String MOVIE_TYPE_HONGKONG = "ff8080815b9075a6015b94ef79dc0284";
}
| false | 745 | 11 | 812 | 9 | 794 | 10 | 812 | 9 | 922 | 15 | false | false | false | false | false | true |
20917_9 | package com.lp.javafeature;
import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemoryHandles;
import jdk.incubator.foreign.MemorySegment;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.invoke.VarHandle;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Java {
public static void main(String[] args) {
// write your code here
}
/**
* Java17
*/
public static void java17() {
// nothing
}
/**
* Java16
*/
public static void java16() {
/**
* Collectors.teeing()
* teeing 收集器已公开为静态方法Collectors::teeing。该收集器将其输入转发给其他两个收集器,然后将它们的结果使用函数合并。
*/
List<Student> list = Arrays.asList(
new Student("唐一", 55),
new Student("唐二", 60),
new Student("唐三", 90));
//平均分 总分
String result = list.stream().collect(Collectors.teeing(
Collectors.averagingInt(Student::getScore),
Collectors.summingInt(Student::getScore),
(s1, s2) -> s1 + ":" + s2));
//最低分 最高分
String result2 = list.stream().collect(Collectors.teeing(
Collectors.minBy(Comparator.comparing(Student::getScore)),
Collectors.maxBy(Comparator.comparing(Student::getScore)),
(s1, s2) -> s1.orElseThrow() + ":" + s2.orElseThrow()
));
System.out.println(result);
System.out.println(result2);
/**
* 添加Stream.toList方法
*/
List<String> list = Arrays.asList("1", "2", "3");
//之前这样写
List<Integer> oneList = list.stream()
.map(Integer::parseInt)
.collect(Collectors.toList());
//现在可以这样写
List<Integer> twoList = list.stream()
.map(Integer::parseInt)
.toList();
}
/**
* Java15
*/
public static void java15() {
// https://stackoverflow.com/questions/64188082/what-is-the-point-of-a-sealed-interface-in-java
// https://www.it610.com/article/1290457869514252288.htm
}
public sealed class Airport permits PrintingAirport {
// ...
}
/**
* Java14
*/
public static void java14() {
UserDTO user = new UserDTO("1697301681936888","空无","https://juejin.cn/user/1697301681936888");
System.out.println(user.id);
System.out.println(user.nickname);
System.out.println(user.id);
memoryOperation();
}
public record UserDTO(String id,String nickname,String homepage) { };
public static void memoryOperation() {
try {
// 分配 200B 堆外内存
MemorySegment memorySegment = MemorySegment.allocateNative(200);
// 用 ByteBuffer 分配,然后包装为 MemorySegment
MemorySegment memorySegment2 = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200));
// MMAP 当然也可以
MemorySegment memorySegment3 = MemorySegment.mapFile(
Path.of("/tmp/memory.txt"), 0, 200, FileChannel.MapMode.READ_WRITE);
// 获取堆外内存地址
MemoryAddress address = MemorySegment.allocateNative(100).address();//baseAddress();
// 组合拳,堆外分配,堆外赋值
long value = 10;
MemoryAddress memoryAddress = MemorySegment.allocateNative(8).address();//baseAddress();
// 获取句柄
VarHandle varHandle = MemoryHandles.varHandle(long.class, ByteOrder.nativeOrder());
varHandle.set(memoryAddress, value);
// 释放就这么简单,想想 DirectByteBuffer 的释放……多奇怪
memorySegment.close();
} catch (IOException e) {
}
}
/**
* Java13
*/
public static void java13() {
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
var typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
case SATURDAY, SUNDAY -> {
yield "Working Day";
}
};
// String json = "{\"id\":\"1697301681936888\",\"nickname\":\"空无\",\"homepage\":\"https://juejin.cn/user/1697301681936888\"}";
String json = """
{
"id":"1697301681936888",
"nickname":"空无",
"homepage":"https://juejin.cn/user/1697301681936888"
}
""";
}
/**
* Java12
*/
public static void java12() {
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
var typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
case SATURDAY, SUNDAY -> "Day Off";
};
Object obj = "Hello Java 12!";
if (obj instanceof String str) {
int length = str.length();
}
}
/**
* Java11
*/
public static void java11() {
List<String> languages = Arrays.asList("Java", "Groovy");
String language = languages.stream()
.map((var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assert(language).equals("Java, Groovy");
}
/**
* Java10
*/
public static void java10() {
var message = "hello";
var i = 13;
var b = false;
var ss = new int[]{1, 2, 3};
}
/**
* Java9
*/
public static void java9() throws IOException {
//
List<Integer> integers = new ArrayList<Integer>() {
public void handle() {
System.out.println("");
}
};
//
BufferedReader br = new BufferedReader(new InputStreamReader(new InputStream() {
@Override
public int read() throws IOException {
return 0;
}
}));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new OutputStream() {
@Override
public void write(int b) throws IOException {
}
}));
try(br; bw) {
}
//
interface InterfacePrivateMethodTest {
default void wrapMethod() {
innerMethod();
}
private void innerMethod() {
System.out.println("interface private method...");
}
}
}
}
| Panl99/codebook | java/Java.java | 1,806 | //现在可以这样写 | line_comment | zh-cn | package com.lp.javafeature;
import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemoryHandles;
import jdk.incubator.foreign.MemorySegment;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.invoke.VarHandle;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Java {
public static void main(String[] args) {
// write your code here
}
/**
* Java17
*/
public static void java17() {
// nothing
}
/**
* Java16
*/
public static void java16() {
/**
* Collectors.teeing()
* teeing 收集器已公开为静态方法Collectors::teeing。该收集器将其输入转发给其他两个收集器,然后将它们的结果使用函数合并。
*/
List<Student> list = Arrays.asList(
new Student("唐一", 55),
new Student("唐二", 60),
new Student("唐三", 90));
//平均分 总分
String result = list.stream().collect(Collectors.teeing(
Collectors.averagingInt(Student::getScore),
Collectors.summingInt(Student::getScore),
(s1, s2) -> s1 + ":" + s2));
//最低分 最高分
String result2 = list.stream().collect(Collectors.teeing(
Collectors.minBy(Comparator.comparing(Student::getScore)),
Collectors.maxBy(Comparator.comparing(Student::getScore)),
(s1, s2) -> s1.orElseThrow() + ":" + s2.orElseThrow()
));
System.out.println(result);
System.out.println(result2);
/**
* 添加Stream.toList方法
*/
List<String> list = Arrays.asList("1", "2", "3");
//之前这样写
List<Integer> oneList = list.stream()
.map(Integer::parseInt)
.collect(Collectors.toList());
//现在 <SUF>
List<Integer> twoList = list.stream()
.map(Integer::parseInt)
.toList();
}
/**
* Java15
*/
public static void java15() {
// https://stackoverflow.com/questions/64188082/what-is-the-point-of-a-sealed-interface-in-java
// https://www.it610.com/article/1290457869514252288.htm
}
public sealed class Airport permits PrintingAirport {
// ...
}
/**
* Java14
*/
public static void java14() {
UserDTO user = new UserDTO("1697301681936888","空无","https://juejin.cn/user/1697301681936888");
System.out.println(user.id);
System.out.println(user.nickname);
System.out.println(user.id);
memoryOperation();
}
public record UserDTO(String id,String nickname,String homepage) { };
public static void memoryOperation() {
try {
// 分配 200B 堆外内存
MemorySegment memorySegment = MemorySegment.allocateNative(200);
// 用 ByteBuffer 分配,然后包装为 MemorySegment
MemorySegment memorySegment2 = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200));
// MMAP 当然也可以
MemorySegment memorySegment3 = MemorySegment.mapFile(
Path.of("/tmp/memory.txt"), 0, 200, FileChannel.MapMode.READ_WRITE);
// 获取堆外内存地址
MemoryAddress address = MemorySegment.allocateNative(100).address();//baseAddress();
// 组合拳,堆外分配,堆外赋值
long value = 10;
MemoryAddress memoryAddress = MemorySegment.allocateNative(8).address();//baseAddress();
// 获取句柄
VarHandle varHandle = MemoryHandles.varHandle(long.class, ByteOrder.nativeOrder());
varHandle.set(memoryAddress, value);
// 释放就这么简单,想想 DirectByteBuffer 的释放……多奇怪
memorySegment.close();
} catch (IOException e) {
}
}
/**
* Java13
*/
public static void java13() {
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
var typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
case SATURDAY, SUNDAY -> {
yield "Working Day";
}
};
// String json = "{\"id\":\"1697301681936888\",\"nickname\":\"空无\",\"homepage\":\"https://juejin.cn/user/1697301681936888\"}";
String json = """
{
"id":"1697301681936888",
"nickname":"空无",
"homepage":"https://juejin.cn/user/1697301681936888"
}
""";
}
/**
* Java12
*/
public static void java12() {
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
var typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
case SATURDAY, SUNDAY -> "Day Off";
};
Object obj = "Hello Java 12!";
if (obj instanceof String str) {
int length = str.length();
}
}
/**
* Java11
*/
public static void java11() {
List<String> languages = Arrays.asList("Java", "Groovy");
String language = languages.stream()
.map((var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assert(language).equals("Java, Groovy");
}
/**
* Java10
*/
public static void java10() {
var message = "hello";
var i = 13;
var b = false;
var ss = new int[]{1, 2, 3};
}
/**
* Java9
*/
public static void java9() throws IOException {
//
List<Integer> integers = new ArrayList<Integer>() {
public void handle() {
System.out.println("");
}
};
//
BufferedReader br = new BufferedReader(new InputStreamReader(new InputStream() {
@Override
public int read() throws IOException {
return 0;
}
}));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new OutputStream() {
@Override
public void write(int b) throws IOException {
}
}));
try(br; bw) {
}
//
interface InterfacePrivateMethodTest {
default void wrapMethod() {
innerMethod();
}
private void innerMethod() {
System.out.println("interface private method...");
}
}
}
}
| false | 1,642 | 5 | 1,806 | 5 | 1,908 | 5 | 1,806 | 5 | 2,231 | 8 | false | false | false | false | false | true |
8155_20 | package com.bomaos.orders.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bomaos.common.core.utils.*;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.dashboard.DateStrUtil;
import com.bomaos.orders.entity.Orders;
import com.bomaos.orders.mapper.OrdersMapper;
import com.bomaos.orders.service.OrdersService;
import com.bomaos.products.entity.Products;
import com.bomaos.products.mapper.ProductsMapper;
import com.bomaos.settings.entity.Coupon;
import com.bomaos.settings.entity.Pays;
import com.bomaos.settings.mapper.CouponMapper;
import com.bomaos.settings.mapper.PaysMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 订单表服务实现类
* Created by Panyoujie on 2021-03-29 16:24:28
*/
@Service
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
private static final Logger logger = LoggerFactory.getLogger(OrdersServiceImpl.class);
@Resource
private ProductsMapper productsMapper;
@Resource
private CouponMapper couponMapper;
@Resource
private PaysMapper paysMapper;
@Override
public PageResult<Orders> listPage(PageParam<Orders> page) {
List<Orders> records = baseMapper.listPage(page);
return new PageResult<>(records, page.getTotal());
}
@Override
public List<Orders> listAll(Map<String, Object> page) {
return baseMapper.listAll(page);
}
/**
* 创建订单
*
* @param productId 商品id
* @param number 购买数量
* @param payType 支付驱动
* @param request
* @return
*/
@Override
public Map<String, String> buy(Integer productId, Integer number, String contact, Integer couponId, String payType, String password, HttpServletRequest request) {
// 记得 map 第二个泛型是数组 要取 第一个元素 即[0]
Map<String, String> params = RequestParamsUtil.getParameterMap(request);
Products products = productsMapper.selectById(productId);
Map<String, String> map = new HashMap<>();
Orders orders = new Orders();
/**
* 是否为附加信息
*/
Integer isCustomize = products.getIsCustomize();
if (isCustomize == 1) {
String customizeInput = products.getCustomizeInput();
String[] customize = customizeInput.split("\\n");
StringBuilder attachInfo = new StringBuilder();
for (String s : customize) {
String[] split = s.split("=");
String s1 = params.get(split[0]); // get到提交过来的字段内容
attachInfo.append(split[1]).append("=").append(s1).append(",");
}
// 去除多余尾部的逗号
String result = attachInfo.deleteCharAt(attachInfo.length() - 1).toString();
orders.setAttachInfo(result);
}
orders.setPrice(products.getPrice());
orders.setStatus(0); // 1 为支付,0未支付
orders.setProductId(productId);
orders.setProductName(products.getName());
orders.setShipType(products.getShipType());
orders.setPayType(payType);
orders.setNumber(number); // 订单数量
orders.setContact(contact);
if (!StringUtils.isEmpty(password)) { // 不为空的时候
orders.setPassword(password);
}
// 得到商品的实际支付金额
BigDecimal multiply = products.getPrice().multiply(new BigDecimal(number));
// 判断是不是批发商品
if (products.getIsWholesale() == 1) {
String wholesale = products.getWholesale();
String[] split = wholesale.split("\\n");
for (String s : split) {
String[] split1 = s.split("=");
if (number >= Integer.parseInt(split1[0])) {
multiply = new BigDecimal(split1[1]).multiply(new BigDecimal(number));
}
}
}
if (!StringUtils.isEmpty(couponId)) {
orders.setIsCoupon(1); // 1 为使用优惠了
orders.setCouponId(couponId);
/**
* 查出对应的优惠券
*/
Coupon coupon = couponMapper.selectById(couponId);
if (coupon.getDiscountType() == 0) { // 满减优惠券
if (multiply.compareTo(coupon.getFullReduction()) > -1) { // 判断实际支付金额是否满足满减的对滴金额
// 得到满减后的价格
BigDecimal bigDecimal = multiply.subtract(coupon.getDiscountVal()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
orders.setMoney(bigDecimal);
} else {
orders.setMoney(multiply);
}
} else { // 折扣优惠券
if (multiply.compareTo(coupon.getFullReduction()) > -1) { // 判断实际支付金额是否满足满减的对滴金额
BigDecimal bigDecimal = multiply.multiply(toPoint(coupon.getDiscountVal().toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
orders.setMoney(bigDecimal);
} else {
orders.setMoney(multiply);
}
}
Coupon coupon1 = new Coupon();
coupon1.setId(coupon.getId());
// 判断优惠券 是一次性还是重复
if (coupon.getType() == 0) { // 一次性
coupon1.setStatus(1); // 设置为已使用
couponMapper.updateById(coupon1);
} else { // 重复使用
if (coupon.getCountAll() != 1) { // 表示最后一次使用
coupon1.setCountAll(coupon.getCountAll() - 1);
coupon1.setCountUsed(coupon.getCountUsed() + 1);
} else {
coupon1.setCountAll(coupon.getCountAll() - 1);
coupon1.setCountUsed(coupon.getCountUsed() + 1);
coupon1.setStatus(1); // 设置为已使用
}
couponMapper.updateById(coupon1);
}
} else {
orders.setMoney(multiply);
orders.setIsCoupon(0); // 1 为使用优惠了
}
/**
* 计算手续费
*/
Pays pays = paysMapper.selectOne(Wrappers.<Pays>lambdaQuery().eq(Pays::getDriver, orders.getPayType()));
if (!Objects.isNull(pays.getIsHandlingFee())) {
if (pays.getIsHandlingFee() == 1 && !Objects.isNull(pays.getHandlingFee())) {
BigDecimal handlingFee = orders.getMoney().multiply(toPoint100(pays.getHandlingFee().toString())).setScale(2, BigDecimal.ROUND_HALF_DOWN);
BigDecimal decimal = orders.getMoney().add(handlingFee).setScale(2, BigDecimal.ROUND_HALF_DOWN);
orders.setMoney(decimal);
orders.setHandlingFee(handlingFee);
} else {
orders.setHandlingFee(new BigDecimal(0.00));
}
} else {
orders.setHandlingFee(new BigDecimal(0.00));
}
logger.info("订单数:{}", number);
logger.info("总价:{}", multiply);
logger.info("实际支付价格:{}", orders.getMoney());
/**
* 判断下是不是电子邮件
* 如果是测写入到email entity
*/
if (FormCheckUtil.isEmail(contact)) {
orders.setEmail(contact);
}
orders.setMember("TUD" + DateUtil.subData() + StringUtil.getRandomString(6));
orders.setCreateTime(new Date());
UserAgentGetter agentGetter = new UserAgentGetter(request);
orders.setIp(agentGetter.getIp());
orders.setDevice(agentGetter.getDevice());
baseMapper.insert(orders);
map.put("total_price", multiply.toString());
map.put("money", orders.getMoney().toString());
map.put("member", orders.getMember());
map.put("handling_fee", orders.getHandlingFee().toString());
return map;
}
public static BigDecimal toPoint(String percent) {
percent = percent.replace("%", "");
Double f = Double.valueOf(percent) / 10;
// Float f = Float.valueOf(percent) / 10;
BigDecimal decimal = new BigDecimal(f);
return decimal;
}
public static BigDecimal toPoint100(String percent) {
percent = percent.replace("%", "");
Double f = Double.valueOf(percent) / 100;
// Float f = Float.valueOf(percent) / 100;
BigDecimal decimal = new BigDecimal(f);
return decimal;
}
@Override
public Orders selectByMember(String member) {
Orders orders = baseMapper.selectOne(new QueryWrapper<Orders>().eq("member", member));
return orders;
}
@Override
public boolean clearRemove() {
QueryWrapper<Orders> status = new QueryWrapper<>();
status.eq("status", 0);
return baseMapper.delete(status) >= 1;
}
@Override
public boolean clearAllRemove() {
Date startDayTime = DateStrUtil.getStartDayTime(-+6);
QueryWrapper queryWrapper = getQueryWrapper(startDayTime);
List<Orders> list = this.list(queryWrapper);
List<Integer> ids = new ArrayList<>();
for (Orders orders : list) {
ids.add(orders.getId());
}
boolean removeByIds = this.removeByIds(ids);
return removeByIds;
}
@Override
public boolean deleteById(Integer id) {
return this.removeById(id);
}
/**
* 根据时间查询七天前的数据
*
* @param StartTime 开始的时间
* @return queryWrapper
*/
public static QueryWrapper getQueryWrapper(Date StartTime) {
QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String DayStartTime = formatter.format(StartTime);
//查询条件为时间范围
queryWrapper.apply("UNIX_TIMESTAMP(create_time) <= UNIX_TIMESTAMP('" + DayStartTime + "')");
return queryWrapper;
}
}
| Panyoujies/bomaos-shop | src/main/java/com/bomaos/orders/service/impl/OrdersServiceImpl.java | 2,576 | // 设置为已使用 | line_comment | zh-cn | package com.bomaos.orders.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bomaos.common.core.utils.*;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.dashboard.DateStrUtil;
import com.bomaos.orders.entity.Orders;
import com.bomaos.orders.mapper.OrdersMapper;
import com.bomaos.orders.service.OrdersService;
import com.bomaos.products.entity.Products;
import com.bomaos.products.mapper.ProductsMapper;
import com.bomaos.settings.entity.Coupon;
import com.bomaos.settings.entity.Pays;
import com.bomaos.settings.mapper.CouponMapper;
import com.bomaos.settings.mapper.PaysMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 订单表服务实现类
* Created by Panyoujie on 2021-03-29 16:24:28
*/
@Service
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
private static final Logger logger = LoggerFactory.getLogger(OrdersServiceImpl.class);
@Resource
private ProductsMapper productsMapper;
@Resource
private CouponMapper couponMapper;
@Resource
private PaysMapper paysMapper;
@Override
public PageResult<Orders> listPage(PageParam<Orders> page) {
List<Orders> records = baseMapper.listPage(page);
return new PageResult<>(records, page.getTotal());
}
@Override
public List<Orders> listAll(Map<String, Object> page) {
return baseMapper.listAll(page);
}
/**
* 创建订单
*
* @param productId 商品id
* @param number 购买数量
* @param payType 支付驱动
* @param request
* @return
*/
@Override
public Map<String, String> buy(Integer productId, Integer number, String contact, Integer couponId, String payType, String password, HttpServletRequest request) {
// 记得 map 第二个泛型是数组 要取 第一个元素 即[0]
Map<String, String> params = RequestParamsUtil.getParameterMap(request);
Products products = productsMapper.selectById(productId);
Map<String, String> map = new HashMap<>();
Orders orders = new Orders();
/**
* 是否为附加信息
*/
Integer isCustomize = products.getIsCustomize();
if (isCustomize == 1) {
String customizeInput = products.getCustomizeInput();
String[] customize = customizeInput.split("\\n");
StringBuilder attachInfo = new StringBuilder();
for (String s : customize) {
String[] split = s.split("=");
String s1 = params.get(split[0]); // get到提交过来的字段内容
attachInfo.append(split[1]).append("=").append(s1).append(",");
}
// 去除多余尾部的逗号
String result = attachInfo.deleteCharAt(attachInfo.length() - 1).toString();
orders.setAttachInfo(result);
}
orders.setPrice(products.getPrice());
orders.setStatus(0); // 1 为支付,0未支付
orders.setProductId(productId);
orders.setProductName(products.getName());
orders.setShipType(products.getShipType());
orders.setPayType(payType);
orders.setNumber(number); // 订单数量
orders.setContact(contact);
if (!StringUtils.isEmpty(password)) { // 不为空的时候
orders.setPassword(password);
}
// 得到商品的实际支付金额
BigDecimal multiply = products.getPrice().multiply(new BigDecimal(number));
// 判断是不是批发商品
if (products.getIsWholesale() == 1) {
String wholesale = products.getWholesale();
String[] split = wholesale.split("\\n");
for (String s : split) {
String[] split1 = s.split("=");
if (number >= Integer.parseInt(split1[0])) {
multiply = new BigDecimal(split1[1]).multiply(new BigDecimal(number));
}
}
}
if (!StringUtils.isEmpty(couponId)) {
orders.setIsCoupon(1); // 1 为使用优惠了
orders.setCouponId(couponId);
/**
* 查出对应的优惠券
*/
Coupon coupon = couponMapper.selectById(couponId);
if (coupon.getDiscountType() == 0) { // 满减优惠券
if (multiply.compareTo(coupon.getFullReduction()) > -1) { // 判断实际支付金额是否满足满减的对滴金额
// 得到满减后的价格
BigDecimal bigDecimal = multiply.subtract(coupon.getDiscountVal()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
orders.setMoney(bigDecimal);
} else {
orders.setMoney(multiply);
}
} else { // 折扣优惠券
if (multiply.compareTo(coupon.getFullReduction()) > -1) { // 判断实际支付金额是否满足满减的对滴金额
BigDecimal bigDecimal = multiply.multiply(toPoint(coupon.getDiscountVal().toString()).setScale(2, BigDecimal.ROUND_HALF_DOWN)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
orders.setMoney(bigDecimal);
} else {
orders.setMoney(multiply);
}
}
Coupon coupon1 = new Coupon();
coupon1.setId(coupon.getId());
// 判断优惠券 是一次性还是重复
if (coupon.getType() == 0) { // 一次性
coupon1.setStatus(1); // 设置 <SUF>
couponMapper.updateById(coupon1);
} else { // 重复使用
if (coupon.getCountAll() != 1) { // 表示最后一次使用
coupon1.setCountAll(coupon.getCountAll() - 1);
coupon1.setCountUsed(coupon.getCountUsed() + 1);
} else {
coupon1.setCountAll(coupon.getCountAll() - 1);
coupon1.setCountUsed(coupon.getCountUsed() + 1);
coupon1.setStatus(1); // 设置为已使用
}
couponMapper.updateById(coupon1);
}
} else {
orders.setMoney(multiply);
orders.setIsCoupon(0); // 1 为使用优惠了
}
/**
* 计算手续费
*/
Pays pays = paysMapper.selectOne(Wrappers.<Pays>lambdaQuery().eq(Pays::getDriver, orders.getPayType()));
if (!Objects.isNull(pays.getIsHandlingFee())) {
if (pays.getIsHandlingFee() == 1 && !Objects.isNull(pays.getHandlingFee())) {
BigDecimal handlingFee = orders.getMoney().multiply(toPoint100(pays.getHandlingFee().toString())).setScale(2, BigDecimal.ROUND_HALF_DOWN);
BigDecimal decimal = orders.getMoney().add(handlingFee).setScale(2, BigDecimal.ROUND_HALF_DOWN);
orders.setMoney(decimal);
orders.setHandlingFee(handlingFee);
} else {
orders.setHandlingFee(new BigDecimal(0.00));
}
} else {
orders.setHandlingFee(new BigDecimal(0.00));
}
logger.info("订单数:{}", number);
logger.info("总价:{}", multiply);
logger.info("实际支付价格:{}", orders.getMoney());
/**
* 判断下是不是电子邮件
* 如果是测写入到email entity
*/
if (FormCheckUtil.isEmail(contact)) {
orders.setEmail(contact);
}
orders.setMember("TUD" + DateUtil.subData() + StringUtil.getRandomString(6));
orders.setCreateTime(new Date());
UserAgentGetter agentGetter = new UserAgentGetter(request);
orders.setIp(agentGetter.getIp());
orders.setDevice(agentGetter.getDevice());
baseMapper.insert(orders);
map.put("total_price", multiply.toString());
map.put("money", orders.getMoney().toString());
map.put("member", orders.getMember());
map.put("handling_fee", orders.getHandlingFee().toString());
return map;
}
public static BigDecimal toPoint(String percent) {
percent = percent.replace("%", "");
Double f = Double.valueOf(percent) / 10;
// Float f = Float.valueOf(percent) / 10;
BigDecimal decimal = new BigDecimal(f);
return decimal;
}
public static BigDecimal toPoint100(String percent) {
percent = percent.replace("%", "");
Double f = Double.valueOf(percent) / 100;
// Float f = Float.valueOf(percent) / 100;
BigDecimal decimal = new BigDecimal(f);
return decimal;
}
@Override
public Orders selectByMember(String member) {
Orders orders = baseMapper.selectOne(new QueryWrapper<Orders>().eq("member", member));
return orders;
}
@Override
public boolean clearRemove() {
QueryWrapper<Orders> status = new QueryWrapper<>();
status.eq("status", 0);
return baseMapper.delete(status) >= 1;
}
@Override
public boolean clearAllRemove() {
Date startDayTime = DateStrUtil.getStartDayTime(-+6);
QueryWrapper queryWrapper = getQueryWrapper(startDayTime);
List<Orders> list = this.list(queryWrapper);
List<Integer> ids = new ArrayList<>();
for (Orders orders : list) {
ids.add(orders.getId());
}
boolean removeByIds = this.removeByIds(ids);
return removeByIds;
}
@Override
public boolean deleteById(Integer id) {
return this.removeById(id);
}
/**
* 根据时间查询七天前的数据
*
* @param StartTime 开始的时间
* @return queryWrapper
*/
public static QueryWrapper getQueryWrapper(Date StartTime) {
QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String DayStartTime = formatter.format(StartTime);
//查询条件为时间范围
queryWrapper.apply("UNIX_TIMESTAMP(create_time) <= UNIX_TIMESTAMP('" + DayStartTime + "')");
return queryWrapper;
}
}
| false | 2,252 | 5 | 2,576 | 5 | 2,687 | 5 | 2,576 | 5 | 3,351 | 8 | false | false | false | false | false | true |
33646_7 | package com.kingyu.flappybird.app;
import com.kingyu.flappybird.component.GameElementLayer;
import com.kingyu.flappybird.component.Bird;
import com.kingyu.flappybird.component.GameBackground;
import com.kingyu.flappybird.component.GameForeground;
import com.kingyu.flappybird.component.WelcomeAnimation;
import static com.kingyu.flappybird.util.Constant.FRAME_HEIGHT;
import static com.kingyu.flappybird.util.Constant.FRAME_WIDTH;
import static com.kingyu.flappybird.util.Constant.FRAME_X;
import static com.kingyu.flappybird.util.Constant.FRAME_Y;
import static com.kingyu.flappybird.util.Constant.FPS;
import static com.kingyu.flappybird.util.Constant.GAME_TITLE;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.BufferedImage;
/**
* 游戏主体,管理游戏的组件和窗口绘制
*
* @author Kingyu
*/
public class Game extends Frame {
private static final long serialVersionUID = 1L; // 保持版本的兼容性
private static int gameState; // 游戏状态
public static final int GAME_READY = 0; // 游戏未开始
public static final int GAME_START = 1; // 游戏开始
public static final int STATE_OVER = 2; // 游戏结束
private GameBackground background; // 游戏背景对象
private GameForeground foreground; // 游戏前景对象
private Bird bird; // 小鸟对象
private GameElementLayer gameElement; // 游戏元素对象
private WelcomeAnimation welcomeAnimation; // 游戏未开始时对象
// 在构造器中初始化
public Game() {
initFrame(); // 初始化游戏窗口
setVisible(true); // 窗口默认为不可见,设置为可见
initGame(); // 初始化游戏对象
}
// 初始化游戏窗口
private void initFrame() {
setSize(FRAME_WIDTH, FRAME_HEIGHT); // 设置窗口大小
setTitle(GAME_TITLE); // 设置窗口标题
setLocation(FRAME_X, FRAME_Y); // 窗口初始位置
setResizable(false); // 设置窗口大小不可变
// 添加关闭窗口事件(监听窗口发生的事件,派发给参数对象,参数对象调用对应的方法)
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); // 结束程序
}
});
addKeyListener(new BirdKeyListener()); // 添加按键监听
}
// 用于接收按键事件的对象的内部类
class BirdKeyListener implements KeyListener {
// 按键按下,根据游戏当前的状态调用不同的方法
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
switch (gameState) {
case GAME_READY:
if (keycode == KeyEvent.VK_SPACE) {
// 游戏启动界面时按下空格,小鸟振翅一次并开始受重力影响
bird.birdFlap();
bird.birdFall();
setGameState(GAME_START); // 游戏状态改变
}
break;
case GAME_START:
if (keycode == KeyEvent.VK_SPACE) {
//游戏过程中按下空格则振翅一次,并持续受重力影响
bird.birdFlap();
bird.birdFall();
}
break;
case STATE_OVER:
if (keycode == KeyEvent.VK_SPACE) {
//游戏结束时按下空格,重新开始游戏
resetGame();
}
break;
}
}
// 重新开始游戏
private void resetGame() {
setGameState(GAME_READY);
gameElement.reset();
bird.reset();
}
// 按键松开,更改按键状态标志
public void keyReleased(KeyEvent e) {
int keycode = e.getKeyChar();
if (keycode == KeyEvent.VK_SPACE) {
bird.keyReleased();
}
}
public void keyTyped(KeyEvent e) {
}
}
// 初始化游戏中的各个对象
private void initGame() {
background = new GameBackground();
gameElement = new GameElementLayer();
foreground = new GameForeground();
welcomeAnimation = new WelcomeAnimation();
bird = new Bird();
setGameState(GAME_READY);
// 启动用于刷新窗口的线程
new Thread(() ->{
while (true) {
repaint(); // 通过调用repaint(),让JVM调用update()
try {
Thread.sleep(FPS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// 项目中存在两个线程:系统线程,自定义的线程:调用repaint()。
// 系统线程:屏幕内容的绘制,窗口事件的监听与处理
// 两个线程会抢夺系统资源,可能会出现一次刷新周期所绘制的内容,并没有在一次刷新周期内完成
// (双缓冲)单独定义一张图片,将需要绘制的内容绘制到这张图片,再一次性地将图片绘制到窗口
private final BufferedImage bufImg = new BufferedImage(FRAME_WIDTH, FRAME_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);
/**
* 绘制游戏内容 当repaint()方法被调用时,JVM会调用update(),参数g是系统提供的画笔,由系统进行实例化
* 单独启动一个线程,不断地快速调用repaint(),让系统对整个窗口进行重绘
*/
public void update(Graphics g) {
Graphics bufG = bufImg.getGraphics(); // 获得图片画笔
// 使用图片画笔将需要绘制的内容绘制到图片
background.draw(bufG, bird); // 背景层
foreground.draw(bufG, bird); // 前景层
if (gameState == GAME_READY) { // 游戏未开始
welcomeAnimation.draw(bufG);
} else { // 游戏结束
gameElement.draw(bufG, bird); // 游戏元素层
}
bird.draw(bufG);
g.drawImage(bufImg, 0, 0, null); // 一次性将图片绘制到屏幕上
}
public static void setGameState(int gameState) {
Game.gameState = gameState;
}
}
| PaoNeke2019/JuxtUX | src/main/java/com/kingyu/flappybird/app/Game.java | 1,502 | // 游戏前景对象 | line_comment | zh-cn | package com.kingyu.flappybird.app;
import com.kingyu.flappybird.component.GameElementLayer;
import com.kingyu.flappybird.component.Bird;
import com.kingyu.flappybird.component.GameBackground;
import com.kingyu.flappybird.component.GameForeground;
import com.kingyu.flappybird.component.WelcomeAnimation;
import static com.kingyu.flappybird.util.Constant.FRAME_HEIGHT;
import static com.kingyu.flappybird.util.Constant.FRAME_WIDTH;
import static com.kingyu.flappybird.util.Constant.FRAME_X;
import static com.kingyu.flappybird.util.Constant.FRAME_Y;
import static com.kingyu.flappybird.util.Constant.FPS;
import static com.kingyu.flappybird.util.Constant.GAME_TITLE;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.BufferedImage;
/**
* 游戏主体,管理游戏的组件和窗口绘制
*
* @author Kingyu
*/
public class Game extends Frame {
private static final long serialVersionUID = 1L; // 保持版本的兼容性
private static int gameState; // 游戏状态
public static final int GAME_READY = 0; // 游戏未开始
public static final int GAME_START = 1; // 游戏开始
public static final int STATE_OVER = 2; // 游戏结束
private GameBackground background; // 游戏背景对象
private GameForeground foreground; // 游戏 <SUF>
private Bird bird; // 小鸟对象
private GameElementLayer gameElement; // 游戏元素对象
private WelcomeAnimation welcomeAnimation; // 游戏未开始时对象
// 在构造器中初始化
public Game() {
initFrame(); // 初始化游戏窗口
setVisible(true); // 窗口默认为不可见,设置为可见
initGame(); // 初始化游戏对象
}
// 初始化游戏窗口
private void initFrame() {
setSize(FRAME_WIDTH, FRAME_HEIGHT); // 设置窗口大小
setTitle(GAME_TITLE); // 设置窗口标题
setLocation(FRAME_X, FRAME_Y); // 窗口初始位置
setResizable(false); // 设置窗口大小不可变
// 添加关闭窗口事件(监听窗口发生的事件,派发给参数对象,参数对象调用对应的方法)
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); // 结束程序
}
});
addKeyListener(new BirdKeyListener()); // 添加按键监听
}
// 用于接收按键事件的对象的内部类
class BirdKeyListener implements KeyListener {
// 按键按下,根据游戏当前的状态调用不同的方法
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
switch (gameState) {
case GAME_READY:
if (keycode == KeyEvent.VK_SPACE) {
// 游戏启动界面时按下空格,小鸟振翅一次并开始受重力影响
bird.birdFlap();
bird.birdFall();
setGameState(GAME_START); // 游戏状态改变
}
break;
case GAME_START:
if (keycode == KeyEvent.VK_SPACE) {
//游戏过程中按下空格则振翅一次,并持续受重力影响
bird.birdFlap();
bird.birdFall();
}
break;
case STATE_OVER:
if (keycode == KeyEvent.VK_SPACE) {
//游戏结束时按下空格,重新开始游戏
resetGame();
}
break;
}
}
// 重新开始游戏
private void resetGame() {
setGameState(GAME_READY);
gameElement.reset();
bird.reset();
}
// 按键松开,更改按键状态标志
public void keyReleased(KeyEvent e) {
int keycode = e.getKeyChar();
if (keycode == KeyEvent.VK_SPACE) {
bird.keyReleased();
}
}
public void keyTyped(KeyEvent e) {
}
}
// 初始化游戏中的各个对象
private void initGame() {
background = new GameBackground();
gameElement = new GameElementLayer();
foreground = new GameForeground();
welcomeAnimation = new WelcomeAnimation();
bird = new Bird();
setGameState(GAME_READY);
// 启动用于刷新窗口的线程
new Thread(() ->{
while (true) {
repaint(); // 通过调用repaint(),让JVM调用update()
try {
Thread.sleep(FPS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// 项目中存在两个线程:系统线程,自定义的线程:调用repaint()。
// 系统线程:屏幕内容的绘制,窗口事件的监听与处理
// 两个线程会抢夺系统资源,可能会出现一次刷新周期所绘制的内容,并没有在一次刷新周期内完成
// (双缓冲)单独定义一张图片,将需要绘制的内容绘制到这张图片,再一次性地将图片绘制到窗口
private final BufferedImage bufImg = new BufferedImage(FRAME_WIDTH, FRAME_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);
/**
* 绘制游戏内容 当repaint()方法被调用时,JVM会调用update(),参数g是系统提供的画笔,由系统进行实例化
* 单独启动一个线程,不断地快速调用repaint(),让系统对整个窗口进行重绘
*/
public void update(Graphics g) {
Graphics bufG = bufImg.getGraphics(); // 获得图片画笔
// 使用图片画笔将需要绘制的内容绘制到图片
background.draw(bufG, bird); // 背景层
foreground.draw(bufG, bird); // 前景层
if (gameState == GAME_READY) { // 游戏未开始
welcomeAnimation.draw(bufG);
} else { // 游戏结束
gameElement.draw(bufG, bird); // 游戏元素层
}
bird.draw(bufG);
g.drawImage(bufImg, 0, 0, null); // 一次性将图片绘制到屏幕上
}
public static void setGameState(int gameState) {
Game.gameState = gameState;
}
}
| false | 1,385 | 6 | 1,502 | 7 | 1,499 | 4 | 1,502 | 7 | 2,260 | 12 | false | false | false | false | false | true |
32112_23 | package com.paperairplane.music.share;
import android.net.Uri;
import android.provider.MediaStore;
/**
* 程序中使用的常量
*
* @author Harry Chen (<a href="mailto:[email protected]">Harry Chen</a>)
* @author Xavier Yao (<a href="mailto:[email protected]">Xavier Yao</a>)
* @see <a
* href="http://www.github.com/PaperAirPlane-Dev-Team/Music-Share-Android">Our
* GitHub</a>
*/
public class Consts {
public final static String[] MEDIA_INFO = new String[] {
MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.MIME_TYPE };
public final static String RENREN_SCOPE = "publish_feed publish_share";
public final static String DEBUG_TAG = "Music Share DEBUG";
public final static String WEIBO_APP_KEY = "1006183120";
public final static String RENREN_APP_KEY = "57593d1b7858483ca66ae1a304f8296e" ;
public final static String FEEDBACK = "#纸飞机音乐分享反馈# @一抔学渣 @HarryChen-SIGKILL- ";
public final static String RELEASE_DATE = "2014.9.1";
public final static String ORIGIN_COLOR = "#FFFFFFFF";
public final static Uri ARTWORK_URI = Uri
.parse("content://media/external/audio/albumart");
public final static int NULL = -1;
// 是否Debug直接在Manifest里面改
public final static boolean ON_PLAY_STORE = true;
public final static int LOOK_FOR_SUGGESTION_REQUEST_CODE = 233;
public final static int PICK_BACKGROUND_REQUEST_CODE = 234;
public final static char UNKNOWN_CHAR = 91;
public final static String LASTFM_API_KEY = "263b7e634ce4560652c40b174addc1d4";
/**
* 网络功能所用的Url
*/
public final class Url {
public final static String API_SUGGESTION = "https://api.weibo.com/2/search/suggestions/at_users.json";
public final static String API_QUERY = "https://api.douban.com/v2/music/search?appkey=039b0d83358026730ad12889a0807359&count=1&q=";
public final static String INFO_REDIRECT = "http://papdt.info/music-share/redirect.php?id=";
public final static String FEEDBACK = "http://papdt.info/music-share/feedback.php";
public final static String CHECK_UPDATE = "http://papdt.info/music-share/update.php";
public final static String CHECK_TEST_UPDATE = CHECK_UPDATE;
public final static String AUTH_REDIRECT = "https://api.weibo.com/oauth2/default.html";
public final static String WEIBO_AUTH_URL = "https://open.weibo.cn/oauth2/authorize";
public final static String RENREN_AUTH_URL = "https://graph.renren.com/oauth/authorize";
public final static String WEIBO_STATUSES_UPDATE = "https://api.weibo.com/2/statuses/update.json";
public final static String WEIBO_FOLLOW_API = "https://api.weibo.com/2/friendships/create.json";
public final static String WEIBO_ACCOUNT_GET_UID_API = "https://api.weibo.com/2/account/get_uid.json";
public final static String RENREN_API = "https://api.renren.com/restserver.do";
public final static String RENREN_REDIRECT_URI = "http://graph.renren.com/oauth/login_success.html ";
public final static String WEIBO_USERS_SHOW_API = "https://api.weibo.com/2/users/show.json";
}
public static enum SNS{
WEIBO,RENREN;
}
/**
* 程序中操作UI线程的Message ID
*/
public final class Status {
public static final int INTERNET_ERROR = 0;
public static final int SEND_WEIBO = 1;
public static final int SEND_SUCCEED = 2;
public static final int AUTH_ERROR = 3;
public static final int SEND_ERROR = 4;
public static final int NOT_AUTHORIZED_ERROR = 5;
public static final int AUTH_SUCCEED = 6;
public static final int FEEDBACK_SUCCEED = 7;
public static final int FEEDBACK_FAIL = 8;
public static final int NO_UPDATE = 9;
public static final int HAS_UPDATE = 10;
public static final int REFRESH_LIST_FINISHED = 11;
public static final int DATA_CHANGED = 12;
public static final int MUSIC_INFO_FETCHED = 13;
}
/**
* 我承认……用在"关注开发者"功能里面
*/
public final class WeiboUid {
public static final int HARRY_UID = 1689129907;
public static final int XAVIER_UID = 2121014783;
public static final int APP_UID = 1153267341;
}
/**
* 传递信息所用的数组下标
*/
public final class ArraySubscript {
public static final int MUSIC = 0;
public static final int ARTWORK = 1;
public static final int ARTIST = 2;
public static final int ALBUM = 3;
public static final int VERSION = 4;
public static final int UPDATE_INFO = 0;
public static final int DOWNLOAD_URL = 1;
}
/**
* 分享意图,以便于不同的反应
*/
public final class ShareMeans {
public static final int WEIBO = 0;
public static final int OTHERS = 1;
public static final int INTERNAL = 2;
}
/**
* 显示对话框的类型
*
* @see Main.showCustomDialog
*/
public final class Dialogs {
public static final int SHARE = 0;
public static final int ABOUT = 1;
public static final int SEARCH = 2;
public static final int EMPTY = 3;
public static final int CHANGE_COLOR = 4;
public static final int CHANGE_BACKGROUND = 5;
}
/**
* 所储存的各种配置的键值名
*/
public final class Preferences {
public final static String WEIBO = "com_weibo_sdk_android";
public final static String SHARE = "ShareStatus";
public final static String FEEDBACK = "FeedbackStatus";
public final static String GENERAL = "General";
// public final static String BG_COLOR = "overlay_bg_color";
public final static String TEXT_COLOR = "text_color";
public final static String BG_PATH = "background_path";
// public final static String OVERLAY = "overlay";
}
/**
* 编码添加的菜单项目,用来判断
*
* @see Main.onPrepareOptionsMenu()
*/
public final class MenuItem {
public final static int SEARCH = 4;
public final static int REFRESH = 3;
public final static int AUTH = 1;
public final static int UNAUTH = 2;
}
/**
* 更改颜色用到的数组下标
*/
public final class Color {
public final static int RED = 0;
public final static int GREEN = 1;
public final static int BLUE = 2;
public final static int OPACITY = 3;
}
/**
* 反馈信息用到的数组下标
*/
public final class FeedbackContentsItem {
public final static int CONTENT = 0;
public final static int NAME = 1;
public final static int EMAIL = 2;
}
/**
* 操作联网线程的Message ID
* @author Xavier
*
*/
public final class NetAccessIntent{
public final static int SEND_FEEDBACK = 0;
public final static int CHECK_FOR_UPDATE = 1;
public final static int QUERY_AND_SHARE_MUSIC_INFO = 2;
}
}
| PaperAirplane-Dev-Team/Music-Share-Android | src/com/paperairplane/music/share/Consts.java | 2,208 | /**
* 所储存的各种配置的键值名
*/ | block_comment | zh-cn | package com.paperairplane.music.share;
import android.net.Uri;
import android.provider.MediaStore;
/**
* 程序中使用的常量
*
* @author Harry Chen (<a href="mailto:[email protected]">Harry Chen</a>)
* @author Xavier Yao (<a href="mailto:[email protected]">Xavier Yao</a>)
* @see <a
* href="http://www.github.com/PaperAirPlane-Dev-Team/Music-Share-Android">Our
* GitHub</a>
*/
public class Consts {
public final static String[] MEDIA_INFO = new String[] {
MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.MIME_TYPE };
public final static String RENREN_SCOPE = "publish_feed publish_share";
public final static String DEBUG_TAG = "Music Share DEBUG";
public final static String WEIBO_APP_KEY = "1006183120";
public final static String RENREN_APP_KEY = "57593d1b7858483ca66ae1a304f8296e" ;
public final static String FEEDBACK = "#纸飞机音乐分享反馈# @一抔学渣 @HarryChen-SIGKILL- ";
public final static String RELEASE_DATE = "2014.9.1";
public final static String ORIGIN_COLOR = "#FFFFFFFF";
public final static Uri ARTWORK_URI = Uri
.parse("content://media/external/audio/albumart");
public final static int NULL = -1;
// 是否Debug直接在Manifest里面改
public final static boolean ON_PLAY_STORE = true;
public final static int LOOK_FOR_SUGGESTION_REQUEST_CODE = 233;
public final static int PICK_BACKGROUND_REQUEST_CODE = 234;
public final static char UNKNOWN_CHAR = 91;
public final static String LASTFM_API_KEY = "263b7e634ce4560652c40b174addc1d4";
/**
* 网络功能所用的Url
*/
public final class Url {
public final static String API_SUGGESTION = "https://api.weibo.com/2/search/suggestions/at_users.json";
public final static String API_QUERY = "https://api.douban.com/v2/music/search?appkey=039b0d83358026730ad12889a0807359&count=1&q=";
public final static String INFO_REDIRECT = "http://papdt.info/music-share/redirect.php?id=";
public final static String FEEDBACK = "http://papdt.info/music-share/feedback.php";
public final static String CHECK_UPDATE = "http://papdt.info/music-share/update.php";
public final static String CHECK_TEST_UPDATE = CHECK_UPDATE;
public final static String AUTH_REDIRECT = "https://api.weibo.com/oauth2/default.html";
public final static String WEIBO_AUTH_URL = "https://open.weibo.cn/oauth2/authorize";
public final static String RENREN_AUTH_URL = "https://graph.renren.com/oauth/authorize";
public final static String WEIBO_STATUSES_UPDATE = "https://api.weibo.com/2/statuses/update.json";
public final static String WEIBO_FOLLOW_API = "https://api.weibo.com/2/friendships/create.json";
public final static String WEIBO_ACCOUNT_GET_UID_API = "https://api.weibo.com/2/account/get_uid.json";
public final static String RENREN_API = "https://api.renren.com/restserver.do";
public final static String RENREN_REDIRECT_URI = "http://graph.renren.com/oauth/login_success.html ";
public final static String WEIBO_USERS_SHOW_API = "https://api.weibo.com/2/users/show.json";
}
public static enum SNS{
WEIBO,RENREN;
}
/**
* 程序中操作UI线程的Message ID
*/
public final class Status {
public static final int INTERNET_ERROR = 0;
public static final int SEND_WEIBO = 1;
public static final int SEND_SUCCEED = 2;
public static final int AUTH_ERROR = 3;
public static final int SEND_ERROR = 4;
public static final int NOT_AUTHORIZED_ERROR = 5;
public static final int AUTH_SUCCEED = 6;
public static final int FEEDBACK_SUCCEED = 7;
public static final int FEEDBACK_FAIL = 8;
public static final int NO_UPDATE = 9;
public static final int HAS_UPDATE = 10;
public static final int REFRESH_LIST_FINISHED = 11;
public static final int DATA_CHANGED = 12;
public static final int MUSIC_INFO_FETCHED = 13;
}
/**
* 我承认……用在"关注开发者"功能里面
*/
public final class WeiboUid {
public static final int HARRY_UID = 1689129907;
public static final int XAVIER_UID = 2121014783;
public static final int APP_UID = 1153267341;
}
/**
* 传递信息所用的数组下标
*/
public final class ArraySubscript {
public static final int MUSIC = 0;
public static final int ARTWORK = 1;
public static final int ARTIST = 2;
public static final int ALBUM = 3;
public static final int VERSION = 4;
public static final int UPDATE_INFO = 0;
public static final int DOWNLOAD_URL = 1;
}
/**
* 分享意图,以便于不同的反应
*/
public final class ShareMeans {
public static final int WEIBO = 0;
public static final int OTHERS = 1;
public static final int INTERNAL = 2;
}
/**
* 显示对话框的类型
*
* @see Main.showCustomDialog
*/
public final class Dialogs {
public static final int SHARE = 0;
public static final int ABOUT = 1;
public static final int SEARCH = 2;
public static final int EMPTY = 3;
public static final int CHANGE_COLOR = 4;
public static final int CHANGE_BACKGROUND = 5;
}
/**
* 所储存 <SUF>*/
public final class Preferences {
public final static String WEIBO = "com_weibo_sdk_android";
public final static String SHARE = "ShareStatus";
public final static String FEEDBACK = "FeedbackStatus";
public final static String GENERAL = "General";
// public final static String BG_COLOR = "overlay_bg_color";
public final static String TEXT_COLOR = "text_color";
public final static String BG_PATH = "background_path";
// public final static String OVERLAY = "overlay";
}
/**
* 编码添加的菜单项目,用来判断
*
* @see Main.onPrepareOptionsMenu()
*/
public final class MenuItem {
public final static int SEARCH = 4;
public final static int REFRESH = 3;
public final static int AUTH = 1;
public final static int UNAUTH = 2;
}
/**
* 更改颜色用到的数组下标
*/
public final class Color {
public final static int RED = 0;
public final static int GREEN = 1;
public final static int BLUE = 2;
public final static int OPACITY = 3;
}
/**
* 反馈信息用到的数组下标
*/
public final class FeedbackContentsItem {
public final static int CONTENT = 0;
public final static int NAME = 1;
public final static int EMAIL = 2;
}
/**
* 操作联网线程的Message ID
* @author Xavier
*
*/
public final class NetAccessIntent{
public final static int SEND_FEEDBACK = 0;
public final static int CHECK_FOR_UPDATE = 1;
public final static int QUERY_AND_SHARE_MUSIC_INFO = 2;
}
}
| false | 1,849 | 15 | 2,208 | 16 | 2,118 | 16 | 2,208 | 16 | 2,599 | 26 | false | false | false | false | false | true |
36163_1 | package com.gome.meetings.controller;
import com.gome.meetings.bo.MenuEvent;
import com.gome.meetings.common.CommonConstant;
import com.gome.meetings.model.UserMenu;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import java.text.ParseException;
import java.util.*;
/**
* 订单控制器
*
* @author JinLiang
* @datetime 2014年4月26日 下午8:55:23
*/
public class UserMenuController extends Controller {
/**
* 获取时间段内的订单
*/
public void getDurationEvent() {
List<UserMenu> list = UserMenu.dao.getDurationOrder(getParaToInt("userId"), getParaToLong("start"), getParaToLong("end"));
List<MenuEvent> events = new ArrayList<>();
Date today = getToday();
for (UserMenu userMenu : list) {
MenuEvent event = new MenuEvent(userMenu.getInt("id"),
userMenu.getStr("menu_name"),
userMenu.getTimestamp("order_date"),
userMenu.getFloat("price"),
userMenu.getInt("state"),
userMenu.getInt("menuid"));
if (userMenu.getTimestamp("order_date").before(today)) {
event.setColor(CommonConstant.COLOR_FOR_PAST_EVENT);
event.setIsExpire(1);
} else if (userMenu.getTimestamp("order_date").after(today)) {
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
} else {
if (new Date().before(getForeRuleDate())) {
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
} else if (new Date().after(getAfterRuleDate())) {
event.setColor(CommonConstant.COLOR_FOR_PAST_EVENT);
event.setIsExpire(1);
} else {
if (userMenu.getInt("state") == 1) {
event.setColor(CommonConstant.COLOR_FOR_PAST_EVENT);
event.setIsExpire(1);
} else {
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
}
}
}
events.add(event);
}
renderJson(events);
}
/**
* 新增订单
*/
public void addFoodEvent() {
Map<String, Object> returnMap = new HashMap<>();
returnMap.put("isSuccess", false);
returnMap.put("msgOption", 0);
Date start = getParaToDate("start");
returnMap = isLegalOrder(getParaToInt("state"), start);
if ((boolean) returnMap.get("flag")) {
UserMenu u = UserMenu.dao.getSingleOrder(getParaToInt("userId"), getParaToInt("state"), getPara("start"));
if (u == null) {
boolean isSuccess = new UserMenu().set("userid", getParaToInt("userId"))
.set("menuid", getParaToInt("menuId"))
.set("state", getParaToInt("state"))
.set("order_date", start)
.set("create_date", new Date())
.save();
returnMap.put("isSuccess", isSuccess);
if (!isSuccess) {
returnMap.put("msg", "提交失败!");
} else {
MenuEvent event = getSingleEvent(getParaToInt("userId"), getParaToInt("state"), DateFormatUtils.format(start, "yyyy-MM-dd"));
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
returnMap.put("event", event);
}
} else {
if (u.getInt("menuid") == getParaToInt("menuId") && u.getInt("state") == getParaToInt("state")) {
renderNull();
return;
} else if (getParaToInt("state") == 1) {
returnMap.put("msgOption", 1);
returnMap.put("msg", getPara("start") + "午餐已定,确认替换为");
} else if (getParaToInt("state") == 2) {
returnMap.put("msgOption", 1);
returnMap.put("msg", getPara("start") + "晚餐已定,确认替换为");
} else {
returnMap.put("msg", "参数传递有误!");
}
}
}
renderJson(returnMap);
}
public void updateFoodEvent() {
UserMenu userMenu = UserMenu.dao.getSingleOrder(getParaToInt("userId"), getParaToInt("state"), getPara("start"));
userMenu.set("menuid", getParaToInt("menuId"));
boolean isSuccess = userMenu.update();
MenuEvent event = getSingleEvent(getParaToInt("userId"), getParaToInt("state"), getPara("start"));
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
Map<String, Object> returnMap = new HashMap<>();
returnMap.put("isSuccess", isSuccess);
returnMap.put("event", event);
renderJson(returnMap);
}
public void delFootEvent() {
Record record = Db.findById("user_menu", getPara(0));
if (record.getTimestamp("order_date").before(getToday())) {
renderNull();
}
Db.deleteById("user_menu", getPara(0));
redirect("/");
}
/**
* 获取指定用户某天中餐/晚餐订单
*
* @param userId 用户ID
* @param state 1:中餐;2:晚餐
* @param startDate 日期
* @return
*/
private MenuEvent getSingleEvent(int userId, int state, String startDate) {
UserMenu userMenu = UserMenu.dao.getSingleOrder(userId, state, startDate);
MenuEvent event = new MenuEvent(userMenu.getInt("id"),
userMenu.getStr("menu_name"),
userMenu.getTimestamp("order_date"),
userMenu.getFloat("price"),
userMenu.getInt("state"),
userMenu.getInt("menuid"));
return event;
}
/**
* 判断下单时间是否合法
* 规则:
* 1.下单当天之前的日期不接受订单;
* 2.下单当天之后的日期正常下单;
* 3.当天11:30后不接受午餐订单;
* 4.当天19:00后不接受晚餐订单。
*
* @param state
* @param start
* @return
* @throws ParseException
*/
private Map<String, Object> isLegalOrder(int state, Date start) {
Map<String, Object> returnMap = new HashMap<>();
returnMap.put("flag", false);
Date date = new Date();
if (start.before(getToday())) {
returnMap.put("msg", "选择的日期已过期,不接受订单!");
} else if (start.after(getToday())) {
returnMap.put("flag", true);
} else if (state == 1 && date.after(getForeRuleDate())) {
returnMap.put("msg", "抱歉,今天已不接受午餐订单!");
} else if (state == 2 && date.after(getAfterRuleDate())) {
returnMap.put("msg", "抱歉,今天已不接受晚餐订单!");
} else if (state == 1 || state == 2) {
returnMap.put("flag", true);
} else {
returnMap.put("msg", "参数传递有误");
}
return returnMap;
}
private Date getToday() {
Date date = null;
try {
date = DateUtils.parseDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd");
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 午餐订单截止时间(11:30)
*
* @return
* @throws ParseException
*/
private Date getForeRuleDate() {
return DateUtils.addMinutes(getToday(), 690);
}
/**
* 晚餐订单截止时间(19:00)
*
* @return
* @throws ParseException
*/
private Date getAfterRuleDate() {
return DateUtils.addHours(getToday(), 19);
}
}
| PasseRR/meetings | src/main/java/com/gome/meetings/controller/UserMenuController.java | 2,017 | /**
* 获取时间段内的订单
*/ | block_comment | zh-cn | package com.gome.meetings.controller;
import com.gome.meetings.bo.MenuEvent;
import com.gome.meetings.common.CommonConstant;
import com.gome.meetings.model.UserMenu;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import java.text.ParseException;
import java.util.*;
/**
* 订单控制器
*
* @author JinLiang
* @datetime 2014年4月26日 下午8:55:23
*/
public class UserMenuController extends Controller {
/**
* 获取时 <SUF>*/
public void getDurationEvent() {
List<UserMenu> list = UserMenu.dao.getDurationOrder(getParaToInt("userId"), getParaToLong("start"), getParaToLong("end"));
List<MenuEvent> events = new ArrayList<>();
Date today = getToday();
for (UserMenu userMenu : list) {
MenuEvent event = new MenuEvent(userMenu.getInt("id"),
userMenu.getStr("menu_name"),
userMenu.getTimestamp("order_date"),
userMenu.getFloat("price"),
userMenu.getInt("state"),
userMenu.getInt("menuid"));
if (userMenu.getTimestamp("order_date").before(today)) {
event.setColor(CommonConstant.COLOR_FOR_PAST_EVENT);
event.setIsExpire(1);
} else if (userMenu.getTimestamp("order_date").after(today)) {
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
} else {
if (new Date().before(getForeRuleDate())) {
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
} else if (new Date().after(getAfterRuleDate())) {
event.setColor(CommonConstant.COLOR_FOR_PAST_EVENT);
event.setIsExpire(1);
} else {
if (userMenu.getInt("state") == 1) {
event.setColor(CommonConstant.COLOR_FOR_PAST_EVENT);
event.setIsExpire(1);
} else {
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
}
}
}
events.add(event);
}
renderJson(events);
}
/**
* 新增订单
*/
public void addFoodEvent() {
Map<String, Object> returnMap = new HashMap<>();
returnMap.put("isSuccess", false);
returnMap.put("msgOption", 0);
Date start = getParaToDate("start");
returnMap = isLegalOrder(getParaToInt("state"), start);
if ((boolean) returnMap.get("flag")) {
UserMenu u = UserMenu.dao.getSingleOrder(getParaToInt("userId"), getParaToInt("state"), getPara("start"));
if (u == null) {
boolean isSuccess = new UserMenu().set("userid", getParaToInt("userId"))
.set("menuid", getParaToInt("menuId"))
.set("state", getParaToInt("state"))
.set("order_date", start)
.set("create_date", new Date())
.save();
returnMap.put("isSuccess", isSuccess);
if (!isSuccess) {
returnMap.put("msg", "提交失败!");
} else {
MenuEvent event = getSingleEvent(getParaToInt("userId"), getParaToInt("state"), DateFormatUtils.format(start, "yyyy-MM-dd"));
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
returnMap.put("event", event);
}
} else {
if (u.getInt("menuid") == getParaToInt("menuId") && u.getInt("state") == getParaToInt("state")) {
renderNull();
return;
} else if (getParaToInt("state") == 1) {
returnMap.put("msgOption", 1);
returnMap.put("msg", getPara("start") + "午餐已定,确认替换为");
} else if (getParaToInt("state") == 2) {
returnMap.put("msgOption", 1);
returnMap.put("msg", getPara("start") + "晚餐已定,确认替换为");
} else {
returnMap.put("msg", "参数传递有误!");
}
}
}
renderJson(returnMap);
}
public void updateFoodEvent() {
UserMenu userMenu = UserMenu.dao.getSingleOrder(getParaToInt("userId"), getParaToInt("state"), getPara("start"));
userMenu.set("menuid", getParaToInt("menuId"));
boolean isSuccess = userMenu.update();
MenuEvent event = getSingleEvent(getParaToInt("userId"), getParaToInt("state"), getPara("start"));
event.setColor(CommonConstant.COLOR_FOR_FUTURE_EVENT);
Map<String, Object> returnMap = new HashMap<>();
returnMap.put("isSuccess", isSuccess);
returnMap.put("event", event);
renderJson(returnMap);
}
public void delFootEvent() {
Record record = Db.findById("user_menu", getPara(0));
if (record.getTimestamp("order_date").before(getToday())) {
renderNull();
}
Db.deleteById("user_menu", getPara(0));
redirect("/");
}
/**
* 获取指定用户某天中餐/晚餐订单
*
* @param userId 用户ID
* @param state 1:中餐;2:晚餐
* @param startDate 日期
* @return
*/
private MenuEvent getSingleEvent(int userId, int state, String startDate) {
UserMenu userMenu = UserMenu.dao.getSingleOrder(userId, state, startDate);
MenuEvent event = new MenuEvent(userMenu.getInt("id"),
userMenu.getStr("menu_name"),
userMenu.getTimestamp("order_date"),
userMenu.getFloat("price"),
userMenu.getInt("state"),
userMenu.getInt("menuid"));
return event;
}
/**
* 判断下单时间是否合法
* 规则:
* 1.下单当天之前的日期不接受订单;
* 2.下单当天之后的日期正常下单;
* 3.当天11:30后不接受午餐订单;
* 4.当天19:00后不接受晚餐订单。
*
* @param state
* @param start
* @return
* @throws ParseException
*/
private Map<String, Object> isLegalOrder(int state, Date start) {
Map<String, Object> returnMap = new HashMap<>();
returnMap.put("flag", false);
Date date = new Date();
if (start.before(getToday())) {
returnMap.put("msg", "选择的日期已过期,不接受订单!");
} else if (start.after(getToday())) {
returnMap.put("flag", true);
} else if (state == 1 && date.after(getForeRuleDate())) {
returnMap.put("msg", "抱歉,今天已不接受午餐订单!");
} else if (state == 2 && date.after(getAfterRuleDate())) {
returnMap.put("msg", "抱歉,今天已不接受晚餐订单!");
} else if (state == 1 || state == 2) {
returnMap.put("flag", true);
} else {
returnMap.put("msg", "参数传递有误");
}
return returnMap;
}
private Date getToday() {
Date date = null;
try {
date = DateUtils.parseDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd");
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 午餐订单截止时间(11:30)
*
* @return
* @throws ParseException
*/
private Date getForeRuleDate() {
return DateUtils.addMinutes(getToday(), 690);
}
/**
* 晚餐订单截止时间(19:00)
*
* @return
* @throws ParseException
*/
private Date getAfterRuleDate() {
return DateUtils.addHours(getToday(), 19);
}
}
| false | 1,764 | 10 | 2,017 | 11 | 2,094 | 12 | 2,017 | 11 | 2,531 | 19 | false | false | false | false | false | true |
44711_2 | package com.lly835.bestpay.service.impl.wx;
import com.lly835.bestpay.constants.WxPayConstants;
import com.lly835.bestpay.model.OrderQueryRequest;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.wxpay.WxPayApi;
import com.lly835.bestpay.model.wxpay.request.WxPayUnifiedorderRequest;
import com.lly835.bestpay.model.wxpay.response.WxPaySyncResponse;
import com.lly835.bestpay.service.impl.WxPayServiceImpl;
import com.lly835.bestpay.service.impl.WxPaySignature;
import com.lly835.bestpay.utils.MapUtil;
import com.lly835.bestpay.utils.MoneyUtil;
import com.lly835.bestpay.utils.RandomUtil;
import com.lly835.bestpay.utils.XmlUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Call;
import retrofit2.Response;
import java.io.IOException;
/**
* @author zicheng
* @date 2020/10/14
* Description:
*/
public class WxPayMicroServiceImpl extends WxPayServiceImpl {
/**
* 微信付款码支付
* 提交支付请求后微信会同步返回支付结果。
* 当返回结果为“系统错误 {@link WxPayConstants#SYSTEMERROR}”时,商户系统等待5秒后调用【查询订单API {@link WxPayServiceImpl#query(OrderQueryRequest)}】,查询支付实际交易结果;
* 当返回结果为“正在支付 {@link WxPayConstants#USERPAYING}”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议30秒);
*
* @param request
* @return
*/
@Override
public PayResponse pay(PayRequest request) {
WxPayUnifiedorderRequest wxRequest = new WxPayUnifiedorderRequest();
wxRequest.setOutTradeNo(request.getOrderId());
wxRequest.setTotalFee(MoneyUtil.Yuan2Fen(request.getOrderAmount()));
wxRequest.setBody(request.getOrderName());
wxRequest.setOpenid(request.getOpenid());
wxRequest.setAuthCode(request.getAuthCode());
wxRequest.setAppid(wxPayConfig.getAppId());
wxRequest.setMchId(wxPayConfig.getMchId());
wxRequest.setNonceStr(RandomUtil.getRandomStr());
wxRequest.setSpbillCreateIp(StringUtils.isEmpty(request.getSpbillCreateIp()) ? "8.8.8.8" : request.getSpbillCreateIp());
wxRequest.setAttach(request.getAttach());
wxRequest.setSign(WxPaySignature.sign(MapUtil.buildMap(wxRequest), wxPayConfig.getMchKey()));
//对付款码支付无用的字段
wxRequest.setNotifyUrl("");
wxRequest.setTradeType("");
RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), XmlUtil.toString(wxRequest));
WxPayApi api = null;
if (wxPayConfig.isSandbox()) {
api = devRetrofit.create(WxPayApi.class);
} else {
api = retrofit.create(WxPayApi.class);
}
Call<WxPaySyncResponse> call = api.micropay(body);
Response<WxPaySyncResponse> retrofitResponse = null;
try {
retrofitResponse = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
assert retrofitResponse != null;
if (!retrofitResponse.isSuccessful()) {
throw new RuntimeException("【微信付款码支付】发起支付, 网络异常");
}
return buildPayResponse(retrofitResponse.body());
}
}
| Pay-Group/best-pay-sdk | src/main/java/com/lly835/bestpay/service/impl/wx/WxPayMicroServiceImpl.java | 984 | //对付款码支付无用的字段 | line_comment | zh-cn | package com.lly835.bestpay.service.impl.wx;
import com.lly835.bestpay.constants.WxPayConstants;
import com.lly835.bestpay.model.OrderQueryRequest;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.wxpay.WxPayApi;
import com.lly835.bestpay.model.wxpay.request.WxPayUnifiedorderRequest;
import com.lly835.bestpay.model.wxpay.response.WxPaySyncResponse;
import com.lly835.bestpay.service.impl.WxPayServiceImpl;
import com.lly835.bestpay.service.impl.WxPaySignature;
import com.lly835.bestpay.utils.MapUtil;
import com.lly835.bestpay.utils.MoneyUtil;
import com.lly835.bestpay.utils.RandomUtil;
import com.lly835.bestpay.utils.XmlUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Call;
import retrofit2.Response;
import java.io.IOException;
/**
* @author zicheng
* @date 2020/10/14
* Description:
*/
public class WxPayMicroServiceImpl extends WxPayServiceImpl {
/**
* 微信付款码支付
* 提交支付请求后微信会同步返回支付结果。
* 当返回结果为“系统错误 {@link WxPayConstants#SYSTEMERROR}”时,商户系统等待5秒后调用【查询订单API {@link WxPayServiceImpl#query(OrderQueryRequest)}】,查询支付实际交易结果;
* 当返回结果为“正在支付 {@link WxPayConstants#USERPAYING}”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议30秒);
*
* @param request
* @return
*/
@Override
public PayResponse pay(PayRequest request) {
WxPayUnifiedorderRequest wxRequest = new WxPayUnifiedorderRequest();
wxRequest.setOutTradeNo(request.getOrderId());
wxRequest.setTotalFee(MoneyUtil.Yuan2Fen(request.getOrderAmount()));
wxRequest.setBody(request.getOrderName());
wxRequest.setOpenid(request.getOpenid());
wxRequest.setAuthCode(request.getAuthCode());
wxRequest.setAppid(wxPayConfig.getAppId());
wxRequest.setMchId(wxPayConfig.getMchId());
wxRequest.setNonceStr(RandomUtil.getRandomStr());
wxRequest.setSpbillCreateIp(StringUtils.isEmpty(request.getSpbillCreateIp()) ? "8.8.8.8" : request.getSpbillCreateIp());
wxRequest.setAttach(request.getAttach());
wxRequest.setSign(WxPaySignature.sign(MapUtil.buildMap(wxRequest), wxPayConfig.getMchKey()));
//对付 <SUF>
wxRequest.setNotifyUrl("");
wxRequest.setTradeType("");
RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), XmlUtil.toString(wxRequest));
WxPayApi api = null;
if (wxPayConfig.isSandbox()) {
api = devRetrofit.create(WxPayApi.class);
} else {
api = retrofit.create(WxPayApi.class);
}
Call<WxPaySyncResponse> call = api.micropay(body);
Response<WxPaySyncResponse> retrofitResponse = null;
try {
retrofitResponse = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
assert retrofitResponse != null;
if (!retrofitResponse.isSuccessful()) {
throw new RuntimeException("【微信付款码支付】发起支付, 网络异常");
}
return buildPayResponse(retrofitResponse.body());
}
}
| false | 833 | 9 | 984 | 9 | 985 | 8 | 984 | 9 | 1,195 | 14 | false | false | false | false | false | true |
19811_6 | package ManagementSystem;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class ScoreRead extends JFrame implements ActionListener{
private static final Object[] String = null;
private Connection conn=null;
private PreparedStatement perstmt=null;
private JRadioButton jrbutton1,jrbutton2,jrbutton3;//课程号、课程名、学分
private ButtonGroup buttongroup;
private JTextField field;
private JLabel label,label2,label3,label4;
private JPanel panel,panel2;
private JButton button;
private DefaultTableModel model;
private JTable table;
private JScrollPane jsp;
public ScoreRead(String string,Connection conn,PreparedStatement perstmt){
this.conn=conn;
this.perstmt=perstmt;
Font font=new Font("",Font.BOLD,22);
Font font1=new Font("",Font.BOLD,17);
label=new JLabel("请选择查询方式:");
label2=new JLabel("输入框");
label.setFont(font);
label2.setFont(font);
jrbutton1=new JRadioButton("某科挂科名单(课程号)");
jrbutton2=new JRadioButton("某科90分及以上人数(课程号)");
jrbutton3=new JRadioButton("按学号查成绩");
jrbutton1.setFont(font1);
jrbutton2.setFont(font1);
jrbutton3.setFont(font1);
buttongroup=new ButtonGroup();
buttongroup.add(jrbutton1);
buttongroup.add(jrbutton2);
buttongroup.add(jrbutton3);;
jrbutton1.setSelected(true);
field=new JTextField(10);
field.setFont(font);
button=new JButton("查询");
button.setFont(font);
panel=new JPanel();
panel.setLayout(new FlowLayout());
panel.add(label2);
panel.add(field);
panel.add(button);
panel2=new JPanel();
label3=new JLabel(" ");
panel2.setLayout(new FlowLayout());
panel2.add(label3);
panel2.add(jrbutton1);
panel2.add(jrbutton2);
panel2.add(jrbutton3);
//设置表格
String[] columnsNames = { "学 号", "课程号", "成 绩"};
model = new DefaultTableModel(columnsNames,8);
table = new JTable(model);
table.setFont(font1);
jsp = new JScrollPane(table);
label4=new JLabel("成绩信息表:");
label4.setFont(font);
this.setTitle(string);
this.setVisible(true);
this.setLocation(700,300);
this.setSize(700,500);
this.setLayout(new GridLayout(5,1));
this.add(label);
this.add(panel2);
this.add(panel);
this.add(label4);
this.add(jsp);
//设置监听
jrbutton1.addActionListener(this);
jrbutton2.addActionListener(this);
jrbutton3.addActionListener(this);
button.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource().equals(button)){
if(field.getText().isEmpty()){
JOptionPane.showMessageDialog(null,"请先输入信息","警告",JOptionPane.WARNING_MESSAGE);
}else{
if(jrbutton1.isSelected()){
String Sname;
String[] str = new String[20];
try{
String sql;
sql = "select sname from s where sno in(select sno from sc where cno=? and grade<60)";
perstmt=conn.prepareStatement(sql);
perstmt.setString(1,field.getText());
perstmt.executeUpdate();
for(int ik=0;ik<table.getRowCount();ik++){ //让表的数据清空
for(int jk=0;jk<table.getColumnCount();jk++){
table.setValueAt("",ik,jk);
}
}
ResultSet rs = perstmt.executeQuery();
int i=0;
while(rs.next()){
Sname=rs.getString("sname");
//按格式处理变量
str[i]=Sname;
i++;
}
String result="";
for(int j=0;j<str.length;j++){
if(str[j]!=null){
result=result+str[j]+"、";
}
}
JOptionPane.showMessageDialog(null,result,"不及格名单",JOptionPane.INFORMATION_MESSAGE);
}catch(Exception te){
JOptionPane.showMessageDialog(null,"仔细看看是哪出错了呢","提示",JOptionPane.QUESTION_MESSAGE);
}
}else if(jrbutton2.isSelected()){
try{
String sql;
sql = "select * from sc where grade>=90 and cno=?";
perstmt=conn.prepareStatement(sql);
perstmt.setString(1,field.getText());
perstmt.executeUpdate();
ResultSet rs = perstmt.executeQuery();
int number=0;
while(rs.next()){
number++;
}
if(number!=0){
JOptionPane.showMessageDialog(null,number+"人上90分","查询结果",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,"没有人上90分","查询结果",JOptionPane.INFORMATION_MESSAGE);
}
}catch(Exception te){
JOptionPane.showMessageDialog(null,"仔细看看是哪出错了呢","提示",JOptionPane.QUESTION_MESSAGE);
}
}else if(jrbutton3.isSelected()){
String Sno,Cno,Grade;
try{
String sql;
sql = "select * from sc where sno=? ";
perstmt=conn.prepareStatement(sql);
perstmt.setString(1,field.getText());
perstmt.executeUpdate();
for(int ik=0;ik<table.getRowCount();ik++){ //让表的数据清空
for(int jk=0;jk<table.getColumnCount();jk++){
table.setValueAt("",ik,jk);
}
}
ResultSet rs = perstmt.executeQuery();
int number=0;
while(rs.next()){
Sno = rs.getString("sno");
Cno = rs.getString("cno");
Grade = rs.getString("grade");
//按格式处理变量 将数据填入表格
table.setValueAt(Sno,number,0);
table.setValueAt(Cno,number,1);
table.setValueAt(Grade,number,2);
number++;
}
if(number!=0){
JOptionPane.showMessageDialog(null,"查询完毕","结果",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,"没有该学生","提示",JOptionPane.INFORMATION_MESSAGE);
}
}catch(Exception te){
JOptionPane.showMessageDialog(null,"仔细看看是哪出错了呢","提示",JOptionPane.QUESTION_MESSAGE);
}
}
}
}
}
}
| Peithon/ManagementSystem | ScoreRead.java | 1,829 | //让表的数据清空 | line_comment | zh-cn | package ManagementSystem;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class ScoreRead extends JFrame implements ActionListener{
private static final Object[] String = null;
private Connection conn=null;
private PreparedStatement perstmt=null;
private JRadioButton jrbutton1,jrbutton2,jrbutton3;//课程号、课程名、学分
private ButtonGroup buttongroup;
private JTextField field;
private JLabel label,label2,label3,label4;
private JPanel panel,panel2;
private JButton button;
private DefaultTableModel model;
private JTable table;
private JScrollPane jsp;
public ScoreRead(String string,Connection conn,PreparedStatement perstmt){
this.conn=conn;
this.perstmt=perstmt;
Font font=new Font("",Font.BOLD,22);
Font font1=new Font("",Font.BOLD,17);
label=new JLabel("请选择查询方式:");
label2=new JLabel("输入框");
label.setFont(font);
label2.setFont(font);
jrbutton1=new JRadioButton("某科挂科名单(课程号)");
jrbutton2=new JRadioButton("某科90分及以上人数(课程号)");
jrbutton3=new JRadioButton("按学号查成绩");
jrbutton1.setFont(font1);
jrbutton2.setFont(font1);
jrbutton3.setFont(font1);
buttongroup=new ButtonGroup();
buttongroup.add(jrbutton1);
buttongroup.add(jrbutton2);
buttongroup.add(jrbutton3);;
jrbutton1.setSelected(true);
field=new JTextField(10);
field.setFont(font);
button=new JButton("查询");
button.setFont(font);
panel=new JPanel();
panel.setLayout(new FlowLayout());
panel.add(label2);
panel.add(field);
panel.add(button);
panel2=new JPanel();
label3=new JLabel(" ");
panel2.setLayout(new FlowLayout());
panel2.add(label3);
panel2.add(jrbutton1);
panel2.add(jrbutton2);
panel2.add(jrbutton3);
//设置表格
String[] columnsNames = { "学 号", "课程号", "成 绩"};
model = new DefaultTableModel(columnsNames,8);
table = new JTable(model);
table.setFont(font1);
jsp = new JScrollPane(table);
label4=new JLabel("成绩信息表:");
label4.setFont(font);
this.setTitle(string);
this.setVisible(true);
this.setLocation(700,300);
this.setSize(700,500);
this.setLayout(new GridLayout(5,1));
this.add(label);
this.add(panel2);
this.add(panel);
this.add(label4);
this.add(jsp);
//设置监听
jrbutton1.addActionListener(this);
jrbutton2.addActionListener(this);
jrbutton3.addActionListener(this);
button.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource().equals(button)){
if(field.getText().isEmpty()){
JOptionPane.showMessageDialog(null,"请先输入信息","警告",JOptionPane.WARNING_MESSAGE);
}else{
if(jrbutton1.isSelected()){
String Sname;
String[] str = new String[20];
try{
String sql;
sql = "select sname from s where sno in(select sno from sc where cno=? and grade<60)";
perstmt=conn.prepareStatement(sql);
perstmt.setString(1,field.getText());
perstmt.executeUpdate();
for(int ik=0;ik<table.getRowCount();ik++){ //让表的数据清空
for(int jk=0;jk<table.getColumnCount();jk++){
table.setValueAt("",ik,jk);
}
}
ResultSet rs = perstmt.executeQuery();
int i=0;
while(rs.next()){
Sname=rs.getString("sname");
//按格式处理变量
str[i]=Sname;
i++;
}
String result="";
for(int j=0;j<str.length;j++){
if(str[j]!=null){
result=result+str[j]+"、";
}
}
JOptionPane.showMessageDialog(null,result,"不及格名单",JOptionPane.INFORMATION_MESSAGE);
}catch(Exception te){
JOptionPane.showMessageDialog(null,"仔细看看是哪出错了呢","提示",JOptionPane.QUESTION_MESSAGE);
}
}else if(jrbutton2.isSelected()){
try{
String sql;
sql = "select * from sc where grade>=90 and cno=?";
perstmt=conn.prepareStatement(sql);
perstmt.setString(1,field.getText());
perstmt.executeUpdate();
ResultSet rs = perstmt.executeQuery();
int number=0;
while(rs.next()){
number++;
}
if(number!=0){
JOptionPane.showMessageDialog(null,number+"人上90分","查询结果",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,"没有人上90分","查询结果",JOptionPane.INFORMATION_MESSAGE);
}
}catch(Exception te){
JOptionPane.showMessageDialog(null,"仔细看看是哪出错了呢","提示",JOptionPane.QUESTION_MESSAGE);
}
}else if(jrbutton3.isSelected()){
String Sno,Cno,Grade;
try{
String sql;
sql = "select * from sc where sno=? ";
perstmt=conn.prepareStatement(sql);
perstmt.setString(1,field.getText());
perstmt.executeUpdate();
for(int ik=0;ik<table.getRowCount();ik++){ //让表 <SUF>
for(int jk=0;jk<table.getColumnCount();jk++){
table.setValueAt("",ik,jk);
}
}
ResultSet rs = perstmt.executeQuery();
int number=0;
while(rs.next()){
Sno = rs.getString("sno");
Cno = rs.getString("cno");
Grade = rs.getString("grade");
//按格式处理变量 将数据填入表格
table.setValueAt(Sno,number,0);
table.setValueAt(Cno,number,1);
table.setValueAt(Grade,number,2);
number++;
}
if(number!=0){
JOptionPane.showMessageDialog(null,"查询完毕","结果",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,"没有该学生","提示",JOptionPane.INFORMATION_MESSAGE);
}
}catch(Exception te){
JOptionPane.showMessageDialog(null,"仔细看看是哪出错了呢","提示",JOptionPane.QUESTION_MESSAGE);
}
}
}
}
}
}
| false | 1,520 | 6 | 1,829 | 6 | 1,996 | 5 | 1,829 | 6 | 3,098 | 10 | false | false | false | false | false | true |
50082_1 | /**
* @Title: 2611.老鼠和奶酪
* @TitleSlug: miceAndCheese
* @Author: Neo
* @Date: 2023-06-07 18:09:59
*/
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.PriorityQueue;
public class 老鼠和奶酪 {
public static void main(String[] args) {
//测试代码
Solution solution = new 老鼠和奶酪().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int miceAndCheese(int[] reward1, int[] reward2, int k) {
int n = reward1.length;
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> (b - a));
int ans = 0;
for (int i = 0; i < n; i++) {
pq.offer(reward1[i] - reward2[i]);
ans += reward2[i];
}
while (k-- > 0) {
int t = pq.poll();
ans += t;
}
return ans;cewd
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| Pengppi/leetcode | src/leetcode/editor/cn/老鼠和奶酪.java | 314 | //测试代码 | line_comment | zh-cn | /**
* @Title: 2611.老鼠和奶酪
* @TitleSlug: miceAndCheese
* @Author: Neo
* @Date: 2023-06-07 18:09:59
*/
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.PriorityQueue;
public class 老鼠和奶酪 {
public static void main(String[] args) {
//测试 <SUF>
Solution solution = new 老鼠和奶酪().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int miceAndCheese(int[] reward1, int[] reward2, int k) {
int n = reward1.length;
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> (b - a));
int ans = 0;
for (int i = 0; i < n; i++) {
pq.offer(reward1[i] - reward2[i]);
ans += reward2[i];
}
while (k-- > 0) {
int t = pq.poll();
ans += t;
}
return ans;cewd
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| false | 279 | 3 | 314 | 3 | 314 | 3 | 314 | 3 | 369 | 5 | false | false | false | false | false | true |
26481_2 | import java.io.*;
import java.util.Date;
/**
* @author Pengxinjie
* @DATE 2020/5/29 - 14:52
*/
public class ATM {
private Account acc;
private File dataFile;
private String filePath = "data.txt";
public ATM() throws IOException {
this.acc = new Account();
try {
this.dataFile = new File(this.filePath);
if (!this.dataFile.exists()) {
this.dataFile.createNewFile();
}
} catch (IOException io) {
System.err.println("文件无法打开!");
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void interact() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("\n账号:");
String AccountName = br.readLine();
String password;
System.out.print("密码:");
password = br.readLine();
if (AccountName.equals("") || password.equals("")){
System.err.println("账号或密码输入错误!请重新输入!");
}
else if (!this.acc.isValid(Long.parseLong(AccountName.trim()), password.trim())) {
System.err.println("账号或密码输入错误!请重新输入!");
}else{
break;
}
}
int c = 100;
while (c != 0) {
System.out.println(" ----------------------------------------");
System.out.println(" |1. 查询余额 2. ATM取款 |\n " +
"|3. ATM存款 4. 修改密码|\n |5. 查询记录" +
" 0. 退出程序|");
System.out.print(" ---------------------------------------- 请输入:");
String str = br.readLine();
try {
c = Integer.parseInt(str.trim());
} catch (NumberFormatException nfe) {
System.err.println("无效的选择!");
System.out.println();
continue;
}
switch (c) {
case 0:
System.out.println("祝您愉快!");
break;
case 1:
System.out.println("余额: " + this.acc.getBalance());
break;
case 2:
System.out.print("取款数额:");
String Num = br.readLine();
try {
long Amm = Long.parseLong(Num.trim());
if(this.acc.withdraw(Amm)) {
FileWriter fw = new FileWriter("data.txt",true);
//更新记录文件
fw.write("账号: " + this.acc.getAccNo() + " " + new Date() + " 取款:" + Amm + "元," + "账户余额:" + this.acc.getBalance() + "元\n");
fw.close();
}
break;
} catch (NumberFormatException nfe) {
System.err.println("无效的数字!");
continue;
}
case 3:
System.out.print("存款数额:");
Num = br.readLine();
try {
long Amm = Long.parseLong(Num.trim());
if(this.acc.deposit(Amm)) {
FileWriter fw = new FileWriter("data.txt",true);
//更新记录文件
fw.write("账号: " + this.acc.getAccNo() + " " + new Date() + " 存款:" + Amm + "元," + "账户余额:" + this.acc.getBalance() + "元\n");
fw.close();
}
break;
} catch (NumberFormatException nfe) {
System.err.print("无效的数字!\n");
continue;
}
case 4:
System.out.print("密码:");
String oldPassword = br.readLine();
System.out.print("新密码:");
String newPassword = br.readLine();
System.out.print("请再输入一遍:");
String confirmPass = br.readLine();
this.acc.changePassword(oldPassword,newPassword,confirmPass);
break;
case 5:
FileReader fileReader = new FileReader("data.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int len;
char[] c1 = new char[10];
System.out.println("当前账户的存取款记录如下:");
while ((len = bufferedReader.read(c1)) != -1){
System.out.print(new String(c1,0,len));
}
bufferedReader.close();
fileReader.close();
break;
default:
System.err.println("无效的输入!");
System.out.println();
break;
}
}
//更新账户文件
FileWriter writer = new FileWriter("account.txt");
writer.write(this.acc.toString());
writer.close();
}
}
| Pengxinjie/ATM-Simulation-System | src/ATM.java | 1,152 | //更新记录文件 | line_comment | zh-cn | import java.io.*;
import java.util.Date;
/**
* @author Pengxinjie
* @DATE 2020/5/29 - 14:52
*/
public class ATM {
private Account acc;
private File dataFile;
private String filePath = "data.txt";
public ATM() throws IOException {
this.acc = new Account();
try {
this.dataFile = new File(this.filePath);
if (!this.dataFile.exists()) {
this.dataFile.createNewFile();
}
} catch (IOException io) {
System.err.println("文件无法打开!");
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void interact() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("\n账号:");
String AccountName = br.readLine();
String password;
System.out.print("密码:");
password = br.readLine();
if (AccountName.equals("") || password.equals("")){
System.err.println("账号或密码输入错误!请重新输入!");
}
else if (!this.acc.isValid(Long.parseLong(AccountName.trim()), password.trim())) {
System.err.println("账号或密码输入错误!请重新输入!");
}else{
break;
}
}
int c = 100;
while (c != 0) {
System.out.println(" ----------------------------------------");
System.out.println(" |1. 查询余额 2. ATM取款 |\n " +
"|3. ATM存款 4. 修改密码|\n |5. 查询记录" +
" 0. 退出程序|");
System.out.print(" ---------------------------------------- 请输入:");
String str = br.readLine();
try {
c = Integer.parseInt(str.trim());
} catch (NumberFormatException nfe) {
System.err.println("无效的选择!");
System.out.println();
continue;
}
switch (c) {
case 0:
System.out.println("祝您愉快!");
break;
case 1:
System.out.println("余额: " + this.acc.getBalance());
break;
case 2:
System.out.print("取款数额:");
String Num = br.readLine();
try {
long Amm = Long.parseLong(Num.trim());
if(this.acc.withdraw(Amm)) {
FileWriter fw = new FileWriter("data.txt",true);
//更新记录文件
fw.write("账号: " + this.acc.getAccNo() + " " + new Date() + " 取款:" + Amm + "元," + "账户余额:" + this.acc.getBalance() + "元\n");
fw.close();
}
break;
} catch (NumberFormatException nfe) {
System.err.println("无效的数字!");
continue;
}
case 3:
System.out.print("存款数额:");
Num = br.readLine();
try {
long Amm = Long.parseLong(Num.trim());
if(this.acc.deposit(Amm)) {
FileWriter fw = new FileWriter("data.txt",true);
//更新 <SUF>
fw.write("账号: " + this.acc.getAccNo() + " " + new Date() + " 存款:" + Amm + "元," + "账户余额:" + this.acc.getBalance() + "元\n");
fw.close();
}
break;
} catch (NumberFormatException nfe) {
System.err.print("无效的数字!\n");
continue;
}
case 4:
System.out.print("密码:");
String oldPassword = br.readLine();
System.out.print("新密码:");
String newPassword = br.readLine();
System.out.print("请再输入一遍:");
String confirmPass = br.readLine();
this.acc.changePassword(oldPassword,newPassword,confirmPass);
break;
case 5:
FileReader fileReader = new FileReader("data.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int len;
char[] c1 = new char[10];
System.out.println("当前账户的存取款记录如下:");
while ((len = bufferedReader.read(c1)) != -1){
System.out.print(new String(c1,0,len));
}
bufferedReader.close();
fileReader.close();
break;
default:
System.err.println("无效的输入!");
System.out.println();
break;
}
}
//更新账户文件
FileWriter writer = new FileWriter("account.txt");
writer.write(this.acc.toString());
writer.close();
}
}
| false | 984 | 4 | 1,152 | 4 | 1,225 | 4 | 1,152 | 4 | 1,513 | 7 | false | false | false | false | false | true |
46626_9 | /**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; } }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (k == 0 || head == null)
return head;
ListNode end = head; // 增加尾指针
int len = 1; // 链表的长度
while (end.next != null) // 找到尾节点
{
len++; // 长度加1
end = end.next;
}
int move = k % len; // k很大时会有周期,取余减少操作
if (move == 0) // 正好和原链表一致
return head;
move = len - move; // 真正的移动数
end.next = head; // 形成循环链表
while (move-- != 0) // 旋转,移动两个节点
{
end = end.next;
head = head.next;
}
end.next = null; // 取消尾指针
return head;
}
} | Perry961002/Algorithms-LeetCode | Java/061-旋转链表.java | 251 | // 旋转,移动两个节点 | line_comment | zh-cn | /**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; } }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (k == 0 || head == null)
return head;
ListNode end = head; // 增加尾指针
int len = 1; // 链表的长度
while (end.next != null) // 找到尾节点
{
len++; // 长度加1
end = end.next;
}
int move = k % len; // k很大时会有周期,取余减少操作
if (move == 0) // 正好和原链表一致
return head;
move = len - move; // 真正的移动数
end.next = head; // 形成循环链表
while (move-- != 0) // 旋转 <SUF>
{
end = end.next;
head = head.next;
}
end.next = null; // 取消尾指针
return head;
}
} | false | 255 | 7 | 250 | 9 | 263 | 7 | 251 | 9 | 327 | 13 | false | false | false | false | false | true |
54390_2 | package top.philsongzi.templateMethod;
/**
* @author 小子松
* @version 1.0
* @date 2023/5/26
* @description 主类,测试行为。
*/
public class Main {
public static void main(String[] args) {
// 生成类的实例
AbstractDisplay abstractDisplay = new CharDisplay('H');
AbstractDisplay abstractDisplay1 = new StringDisplay("hello,world.");
// 好的,确实是大笨蛋,用自带换行的 println 来输出本该在一行呈现的内容,精彩。。。
AbstractDisplay abstractDisplay2 = new StringDisplay("你好,小子松大笨蛋。");
// 调用display方法
abstractDisplay.display();
abstractDisplay1.display();
abstractDisplay2.display();
}
}
| PhilSongZi/design-models | src/main/java/top/philsongzi/templateMethod/Main.java | 198 | // 好的,确实是大笨蛋,用自带换行的 println 来输出本该在一行呈现的内容,精彩。。。 | line_comment | zh-cn | package top.philsongzi.templateMethod;
/**
* @author 小子松
* @version 1.0
* @date 2023/5/26
* @description 主类,测试行为。
*/
public class Main {
public static void main(String[] args) {
// 生成类的实例
AbstractDisplay abstractDisplay = new CharDisplay('H');
AbstractDisplay abstractDisplay1 = new StringDisplay("hello,world.");
// 好的 <SUF>
AbstractDisplay abstractDisplay2 = new StringDisplay("你好,小子松大笨蛋。");
// 调用display方法
abstractDisplay.display();
abstractDisplay1.display();
abstractDisplay2.display();
}
}
| false | 179 | 29 | 198 | 37 | 188 | 25 | 198 | 37 | 234 | 51 | false | false | false | false | false | true |
64902_5 | package com.hims.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hims.pojo.*;
import com.hims.service.ISignService;
import com.hims.utils.DateUtils;
import com.hims.utils.PageUtils;
import com.hims.utils.ResultCode;
import com.hims.utils.ResultCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author bruce
* @since 2021-08-30
*/
@Controller
@RequestMapping("/sign")
public class SignController {
@Autowired
ISignService signService;
/**
* 01-录入体征数据
* @return
*/
@PostMapping("signSave")
@ResponseBody
public ResultCommon signSave(Sign sign, HttpSession session){
User user= (User) session.getAttribute("loginUser");
sign.setUserId(user.getUserId());
sign.setUserName(user.getUserName());
sign.setCreateTime(DateUtils.nowTime());
System.out.println("要新增的对象:"+sign);
boolean b = signService.save(sign);
if(b){
return ResultCommon.success(ResultCode.SUCCESS);
}else{
return ResultCommon.success(ResultCode.FAIL);
}
}
/**
* 02-体征数据查询
* @param model
* @return
*/
@Secured(value = {"ROLE_护士"})
@RequestMapping("find")
public String find(Model model, SignVo signVo, @RequestParam(defaultValue = "1") Long pageIndex,
@RequestParam(defaultValue = "10") Long pageSize){
QueryWrapper<Sign> qw = new QueryWrapper<Sign>();
if(signVo.getPatientId()!=null&&!signVo.getPatientId().equals("")){
qw.like("patientId",signVo.getPatientId());
}
if(signVo.getTestStartTime()!=null&&!signVo.getTestStartTime().equals("")){
qw.ge("measureTime",signVo.getTestStartTime());
}
if(signVo.getTestEndTime()!=null&&!signVo.getTestEndTime().equals("")){
qw.le("measureTime",signVo.getTestEndTime());
}
//分页API
IPage<Sign> pager = signService.page(new Page<Sign>(pageIndex, pageSize), qw);
List<Sign> signs = pager.getRecords();
long totalCount = pager.getTotal();
long pageCount = pager.getPages();
//封装一个分页工具类
PageUtils<Sign> pageUtils=new PageUtils<Sign>(pageIndex,pageSize,totalCount,pageCount,signs);
model.addAttribute("pageUtils",pageUtils);
model.addAttribute("signVo",signVo); // 查询数据回显
return "sign-query";
}
}
| Piercely/HIMS_master | HIMS/src/main/java/com/hims/controller/SignController.java | 771 | // 查询数据回显 | line_comment | zh-cn | package com.hims.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hims.pojo.*;
import com.hims.service.ISignService;
import com.hims.utils.DateUtils;
import com.hims.utils.PageUtils;
import com.hims.utils.ResultCode;
import com.hims.utils.ResultCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author bruce
* @since 2021-08-30
*/
@Controller
@RequestMapping("/sign")
public class SignController {
@Autowired
ISignService signService;
/**
* 01-录入体征数据
* @return
*/
@PostMapping("signSave")
@ResponseBody
public ResultCommon signSave(Sign sign, HttpSession session){
User user= (User) session.getAttribute("loginUser");
sign.setUserId(user.getUserId());
sign.setUserName(user.getUserName());
sign.setCreateTime(DateUtils.nowTime());
System.out.println("要新增的对象:"+sign);
boolean b = signService.save(sign);
if(b){
return ResultCommon.success(ResultCode.SUCCESS);
}else{
return ResultCommon.success(ResultCode.FAIL);
}
}
/**
* 02-体征数据查询
* @param model
* @return
*/
@Secured(value = {"ROLE_护士"})
@RequestMapping("find")
public String find(Model model, SignVo signVo, @RequestParam(defaultValue = "1") Long pageIndex,
@RequestParam(defaultValue = "10") Long pageSize){
QueryWrapper<Sign> qw = new QueryWrapper<Sign>();
if(signVo.getPatientId()!=null&&!signVo.getPatientId().equals("")){
qw.like("patientId",signVo.getPatientId());
}
if(signVo.getTestStartTime()!=null&&!signVo.getTestStartTime().equals("")){
qw.ge("measureTime",signVo.getTestStartTime());
}
if(signVo.getTestEndTime()!=null&&!signVo.getTestEndTime().equals("")){
qw.le("measureTime",signVo.getTestEndTime());
}
//分页API
IPage<Sign> pager = signService.page(new Page<Sign>(pageIndex, pageSize), qw);
List<Sign> signs = pager.getRecords();
long totalCount = pager.getTotal();
long pageCount = pager.getPages();
//封装一个分页工具类
PageUtils<Sign> pageUtils=new PageUtils<Sign>(pageIndex,pageSize,totalCount,pageCount,signs);
model.addAttribute("pageUtils",pageUtils);
model.addAttribute("signVo",signVo); // 查询 <SUF>
return "sign-query";
}
}
| false | 640 | 5 | 771 | 5 | 796 | 5 | 771 | 5 | 960 | 10 | false | false | false | false | false | true |
52178_1 | package com.platon.aton.entity;
import android.support.annotation.StringRes;
import com.platon.aton.R;
import java.util.HashMap;
import java.util.Map;
public enum TransactionType {
/**
* 未知
*/
UNKNOWN(-1, R.string.unknown),
/**
* 转账
*/
TRANSFER(0, R.string.transfer),
/**
* 合约创建
*/
CONTRACT_CREATION(1, R.string.contract_creation),
/**
* 合约执行
*/
CONTRACT_EXECUTION(2, R.string.contract_execution),
/**
* 其他收入
*/
OTHER_INCOME(3, R.string.other_income),
/**
* 其他支出
*/
OTHER_EXPENSES(4, R.string.other_expenses),
/**
* MPC交易
*/
MPC_TRANSACTION(5, R.string.mpc_transaction),
/**
* 发起质押(创建验证人)
*/
CREATE_VALIDATOR(1000, R.string.create_validator),
/**
* 修改质押信息(编辑验证人)
*/
EDIT_VALIDATOR(1001, R.string.edit_validator),
/**
* 增加自有质押
*/
INCREASE_STAKING(1002, R.string.increase_staking),
/**
* 退出验证人(包括撤销验证人创建,撤销质押)
*/
EXIT_VALIDATOR(1003, R.string.exit_validator),
/**
* 发起委托(委托)
*/
DELEGATE(1004, R.string.delegate),
/**
* 减持/撤销委托(赎回委托)
*/
UNDELEGATE(1005, R.string.undelegate),
/**
* 创建文提案
*/
CREATE_TEXT_PROPOSAL(2000, R.string.create_proposal),
/**
* 创建升级提案
*/
CREATE_UPGRADE_PROPOSAL(2001, R.string.create_proposal),
/**
* 创建参数提案
*/
CREATE_PARAMETER_PROPOSAL(2002, R.string.create_proposal),
/**
* 给提案投票
*/
VOTING_PROPOSAL(2003, R.string.voting_proposal),
/**
* 版本声明
*/
DECLARE_VERSION(2004, R.string.declare_version),
/**
* 创建取消提案
*/
CANCEL_PROPOSAL(2005, R.string.create_proposal),
/**
* 举报多签(举报验证人)
*/
REPORT_VALIDATOR(3000, R.string.report_validator),
/**
* 创建锁仓计划(创建锁仓)
*/
CREATE_RESTRICTING(4000, R.string.create_restricting),
/**
* 领取奖励
*/
CLAIM_REWARDS(5000, R.string.claim_rewards);
private int value;
private @StringRes
int descRes;
TransactionType(int value, int descRes) {
this.value = value;
this.descRes = descRes;
}
private static Map<Integer, TransactionType> map = new HashMap<>();
static {
for (TransactionType status : values()) {
map.put(status.value, status);
}
}
public static TransactionType getTxTypeByValue(int value) {
TransactionType transactionType = map.get(value);
return transactionType == null ? TransactionType.UNKNOWN : transactionType;
}
public int getTxTypeDescRes() {
return descRes;
}
public int getTxTypeValue() {
return value;
}
}
| PlatONnetwork/ATON-Android | wallet/src/main/java/com/platon/aton/entity/TransactionType.java | 913 | /**
* 转账
*/ | block_comment | zh-cn | package com.platon.aton.entity;
import android.support.annotation.StringRes;
import com.platon.aton.R;
import java.util.HashMap;
import java.util.Map;
public enum TransactionType {
/**
* 未知
*/
UNKNOWN(-1, R.string.unknown),
/**
* 转账
<SUF>*/
TRANSFER(0, R.string.transfer),
/**
* 合约创建
*/
CONTRACT_CREATION(1, R.string.contract_creation),
/**
* 合约执行
*/
CONTRACT_EXECUTION(2, R.string.contract_execution),
/**
* 其他收入
*/
OTHER_INCOME(3, R.string.other_income),
/**
* 其他支出
*/
OTHER_EXPENSES(4, R.string.other_expenses),
/**
* MPC交易
*/
MPC_TRANSACTION(5, R.string.mpc_transaction),
/**
* 发起质押(创建验证人)
*/
CREATE_VALIDATOR(1000, R.string.create_validator),
/**
* 修改质押信息(编辑验证人)
*/
EDIT_VALIDATOR(1001, R.string.edit_validator),
/**
* 增加自有质押
*/
INCREASE_STAKING(1002, R.string.increase_staking),
/**
* 退出验证人(包括撤销验证人创建,撤销质押)
*/
EXIT_VALIDATOR(1003, R.string.exit_validator),
/**
* 发起委托(委托)
*/
DELEGATE(1004, R.string.delegate),
/**
* 减持/撤销委托(赎回委托)
*/
UNDELEGATE(1005, R.string.undelegate),
/**
* 创建文提案
*/
CREATE_TEXT_PROPOSAL(2000, R.string.create_proposal),
/**
* 创建升级提案
*/
CREATE_UPGRADE_PROPOSAL(2001, R.string.create_proposal),
/**
* 创建参数提案
*/
CREATE_PARAMETER_PROPOSAL(2002, R.string.create_proposal),
/**
* 给提案投票
*/
VOTING_PROPOSAL(2003, R.string.voting_proposal),
/**
* 版本声明
*/
DECLARE_VERSION(2004, R.string.declare_version),
/**
* 创建取消提案
*/
CANCEL_PROPOSAL(2005, R.string.create_proposal),
/**
* 举报多签(举报验证人)
*/
REPORT_VALIDATOR(3000, R.string.report_validator),
/**
* 创建锁仓计划(创建锁仓)
*/
CREATE_RESTRICTING(4000, R.string.create_restricting),
/**
* 领取奖励
*/
CLAIM_REWARDS(5000, R.string.claim_rewards);
private int value;
private @StringRes
int descRes;
TransactionType(int value, int descRes) {
this.value = value;
this.descRes = descRes;
}
private static Map<Integer, TransactionType> map = new HashMap<>();
static {
for (TransactionType status : values()) {
map.put(status.value, status);
}
}
public static TransactionType getTxTypeByValue(int value) {
TransactionType transactionType = map.get(value);
return transactionType == null ? TransactionType.UNKNOWN : transactionType;
}
public int getTxTypeDescRes() {
return descRes;
}
public int getTxTypeValue() {
return value;
}
}
| false | 791 | 10 | 913 | 8 | 966 | 9 | 913 | 8 | 1,271 | 12 | false | false | false | false | false | true |
34709_6 | package handwrite_rec201809;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
* 手写识别界面类,主要是创建界面和添加监听器
*
* @author Poe
*
*/
public class HwrSurface extends JPanel implements ActionListener, MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
static final int width = 8;// 格子宽
static final int ROW_NUM = 60;// 格子列数
static final int COL_NUM = 80;// 格行数
private boolean do_recoginize = false;
private Graphics hwr_graphics;
private JFrame jframe_window;
private JPanel show_recoginion;
private JButton[] rec_but;
private JTextArea input;
private boolean train = false;
private String train_character;
private JButton add_data;
private int x1, y1, x2, y2;
private int[][] flag;// 用于存储1,0
// 构造函数
public HwrSurface() {
jframe_window = new JFrame();
jframe_window.setSize(1000, 618);
jframe_window.setTitle("手写识别");
jframe_window.setDefaultCloseOperation(3);
jframe_window.setLocationRelativeTo(null);
jframe_window.setLayout(new FlowLayout());
Dimension size_dim = new Dimension(width * COL_NUM, width * ROW_NUM);
this.setPreferredSize(size_dim);
this.setBackground(Color.pink);
jframe_window.add(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
flag = new int[ROW_NUM][COL_NUM];
show_recoginion = new JPanel();// 用于显示识别出的字符
show_recoginion.setLayout(new FlowLayout());
show_recoginion.setPreferredSize(new Dimension(width * COL_NUM, 30));
show_recoginion.setBackground(Color.white);
jframe_window.add(show_recoginion);
// 向show_recoginion里面添加识别出的字符
rec_but = new JButton[Recoginize.CHAR_NUM];
for (int i = 0; i < rec_but.length; i++) {
rec_but[i] = new JButton();
rec_but[i].setPreferredSize(new Dimension(width * COL_NUM / (Recoginize.CHAR_NUM+1), 25));
rec_but[i].setBorder(null);
rec_but[i].setBackground(Color.white);
rec_but[i].setFocusable(false);
rec_but[i].addActionListener(this);
show_recoginion.add(rec_but[i]);
}
input = new JTextArea();// 用于输入字符
input.setPreferredSize(new Dimension(width * COL_NUM - 195, 30));
input.setBackground(Color.white);
jframe_window.add(input);
JButton chose_button = new JButton("重写");
chose_button.setFocusable(false);
chose_button.addActionListener(this);
jframe_window.add(chose_button);
jframe_window.setVisible(true);
hwr_graphics = this.getGraphics();
hwr_graphics.setColor(Color.BLACK);
add_data = new JButton("训练");// 加入训练集
add_data.setFocusable(false);
jframe_window.add(add_data);
add_data.addActionListener(this);
JButton imgBtn = new JButton("图片");// 图片识别
imgBtn.setFocusable(false);
jframe_window.add(imgBtn);
imgBtn.addActionListener(this);
}
public JButton[] getRec_but() {
return rec_but;
}
// 画线 28*16的大小
public void paint(Graphics gra) {
super.paint(gra);
gra.setColor(Color.BLACK);
for (int i = 0; i < flag.length; i++) {// 重置数组
for (int j = 0; j < flag[0].length; j++) {
flag[i][j] = 0;
}
}
}
// 动作监听器
@Override
public void actionPerformed(ActionEvent arg0) {
String command = arg0.getActionCommand();
if (command == "训练") {// 将该数据加入到训练集
String option = JOptionPane.showInputDialog("请输入要训练的字符");
train_character=option;//要训练的字符
if (option != null) {
JOptionPane.showMessageDialog(jframe_window, "请在写字板中写字,写完后移开写字板,每写完一个字生成一个样本,训练结束后请点击停止按钮,返回到字符识别", "提示", JOptionPane.INFORMATION_MESSAGE);
train=true;
add_data.setText("停止");
}
} else if (command == "重写") {// 选中的是识别出的字符
this.repaint();// 重绘
for (int i = 0; i < flag.length; i++) {// 重置数组
for (int j = 0; j < flag[0].length; j++) {
flag[i][j] = 0;
}
}
}else if (command == "图片") {// 选中的是识别出的字符
new PicChose(rec_but);
} else if (command == "停止") {// 选中的是识别出的字符
train=false;
add_data.setText("训练");
}
else {// 选中识别字符
input.append(command);
this.repaint();// 重绘
for (int i = 0; i < flag.length; i++) {// 重置数组
for (int j = 0; j < flag[0].length; j++) {
flag[i][j] = 0;
}
}
}
}
// 鼠标监听器
@Override
public void mouseClicked(MouseEvent arg0) {
x1 = arg0.getX();
y1 = arg0.getY();
}
@Override
public void mouseEntered(MouseEvent arg0) {
do_recoginize = false;
}
// 鼠标移出画板开始识别
@Override
public void mouseExited(MouseEvent arg0) {
if (do_recoginize&&train) {//训练
Recoginize rec = new Recoginize(flag);
rec.generatData(train_character);
int[][] flagup=flag;
int[][] flagdown=flag;
int[][] flagleft=flag;
int[][] flagright=flag;
stop1:
while(true) {
for(int i=0;i<flagup.length;i++) {
for(int j=0;j<flagup[0].length;j++) {
if(flagup[i][j]==1&&i-3>0) {
flagup[i-3][j]=flagup[i][j];
flagup[i][j] = 0;
}else if(flagup[i][j]==1&&i-3<=0) {
break stop1;
}
}
}
rec.setFlag(flagup);
rec.generatData(train_character);
}
stop2:
while(true) {
for(int i=flagdown.length-1;i>=0;i--) {
for(int j=0;j<flagdown[0].length;j++) {
if(flagdown[i][j]==1&&i+3<flagdown.length) {
flagdown[i+3][j]=flagdown[i][j];
flagdown[i][j] = 0;
}else if(flagdown[i][j]==1&&i+3>=flagdown.length) {
break stop2;
}
}
}
rec.setFlag(flagdown);
rec.generatData(train_character);
}
stop3:
while(true) {
for(int i=0;i<flagleft.length;i++) {
for(int j=0;j<flagleft[0].length;j++) {
if(flagleft[i][j]==1&&j-3>0) {
flagleft[i][j-3]=flagleft[i][j];
flagleft[i][j] = 0;
}else if(flagleft[i][j]==1&&j-3<=0) {
break stop3;
}
}
}
rec.setFlag(flagleft);
rec.generatData(train_character);
}
stop4:
while(true) {
for(int i=0;i<flagright.length;i++) {
for(int j=flagright[0].length-1;j>=0;j--) {
if(flagright[i][j]==1&&j+3<flagright[0].length) {
flagright[i][j+3]=flagright[i][j];
flagright[i][j] = 0;
}else if(flagright[i][j]==1&&j+3>=flagright[0].length) {
break stop4;
}
}
}
rec.setFlag(flagright);
rec.generatData(train_character);
}
}
}
@Override
public void mousePressed(MouseEvent arg0) {
x1 = arg0.getX();
y1 = arg0.getY();
}
@Override
public void mouseReleased(MouseEvent arg0) {
if(!train){
Recoginize rec = new Recoginize(flag);
char[] rec_result = rec.getChars_result();// 获得结果
// 向show_recoginion中添加识别出的字符
for (int i = 0; i < rec_result.length; i++) {
rec_but[i].setText("" + rec_result[i]);
}
}
}
@Override
public void mouseDragged(MouseEvent e) {
Graphics2D g2d = (Graphics2D) hwr_graphics;
BasicStroke stokeLine = new BasicStroke(5.0f);
g2d.setStroke(stokeLine);
x2 = e.getX();
y2 = e.getY();
g2d.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
int index_x = x1 / width;
int index_y = y1 / width;
if (index_x >= COL_NUM)
index_x = COL_NUM-1;
if (index_y >= ROW_NUM)
index_y = ROW_NUM-1;
if (index_x < 0)
index_x = 0;
if (index_y < 0)
index_y = 0;
flag[index_y][index_x] = 1;
do_recoginize = true;
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
| Poe2016/HandWriteRecoginize | src/handwrite_rec201809/HwrSurface.java | 2,958 | // 用于显示识别出的字符 | line_comment | zh-cn | package handwrite_rec201809;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
* 手写识别界面类,主要是创建界面和添加监听器
*
* @author Poe
*
*/
public class HwrSurface extends JPanel implements ActionListener, MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
static final int width = 8;// 格子宽
static final int ROW_NUM = 60;// 格子列数
static final int COL_NUM = 80;// 格行数
private boolean do_recoginize = false;
private Graphics hwr_graphics;
private JFrame jframe_window;
private JPanel show_recoginion;
private JButton[] rec_but;
private JTextArea input;
private boolean train = false;
private String train_character;
private JButton add_data;
private int x1, y1, x2, y2;
private int[][] flag;// 用于存储1,0
// 构造函数
public HwrSurface() {
jframe_window = new JFrame();
jframe_window.setSize(1000, 618);
jframe_window.setTitle("手写识别");
jframe_window.setDefaultCloseOperation(3);
jframe_window.setLocationRelativeTo(null);
jframe_window.setLayout(new FlowLayout());
Dimension size_dim = new Dimension(width * COL_NUM, width * ROW_NUM);
this.setPreferredSize(size_dim);
this.setBackground(Color.pink);
jframe_window.add(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
flag = new int[ROW_NUM][COL_NUM];
show_recoginion = new JPanel();// 用于 <SUF>
show_recoginion.setLayout(new FlowLayout());
show_recoginion.setPreferredSize(new Dimension(width * COL_NUM, 30));
show_recoginion.setBackground(Color.white);
jframe_window.add(show_recoginion);
// 向show_recoginion里面添加识别出的字符
rec_but = new JButton[Recoginize.CHAR_NUM];
for (int i = 0; i < rec_but.length; i++) {
rec_but[i] = new JButton();
rec_but[i].setPreferredSize(new Dimension(width * COL_NUM / (Recoginize.CHAR_NUM+1), 25));
rec_but[i].setBorder(null);
rec_but[i].setBackground(Color.white);
rec_but[i].setFocusable(false);
rec_but[i].addActionListener(this);
show_recoginion.add(rec_but[i]);
}
input = new JTextArea();// 用于输入字符
input.setPreferredSize(new Dimension(width * COL_NUM - 195, 30));
input.setBackground(Color.white);
jframe_window.add(input);
JButton chose_button = new JButton("重写");
chose_button.setFocusable(false);
chose_button.addActionListener(this);
jframe_window.add(chose_button);
jframe_window.setVisible(true);
hwr_graphics = this.getGraphics();
hwr_graphics.setColor(Color.BLACK);
add_data = new JButton("训练");// 加入训练集
add_data.setFocusable(false);
jframe_window.add(add_data);
add_data.addActionListener(this);
JButton imgBtn = new JButton("图片");// 图片识别
imgBtn.setFocusable(false);
jframe_window.add(imgBtn);
imgBtn.addActionListener(this);
}
public JButton[] getRec_but() {
return rec_but;
}
// 画线 28*16的大小
public void paint(Graphics gra) {
super.paint(gra);
gra.setColor(Color.BLACK);
for (int i = 0; i < flag.length; i++) {// 重置数组
for (int j = 0; j < flag[0].length; j++) {
flag[i][j] = 0;
}
}
}
// 动作监听器
@Override
public void actionPerformed(ActionEvent arg0) {
String command = arg0.getActionCommand();
if (command == "训练") {// 将该数据加入到训练集
String option = JOptionPane.showInputDialog("请输入要训练的字符");
train_character=option;//要训练的字符
if (option != null) {
JOptionPane.showMessageDialog(jframe_window, "请在写字板中写字,写完后移开写字板,每写完一个字生成一个样本,训练结束后请点击停止按钮,返回到字符识别", "提示", JOptionPane.INFORMATION_MESSAGE);
train=true;
add_data.setText("停止");
}
} else if (command == "重写") {// 选中的是识别出的字符
this.repaint();// 重绘
for (int i = 0; i < flag.length; i++) {// 重置数组
for (int j = 0; j < flag[0].length; j++) {
flag[i][j] = 0;
}
}
}else if (command == "图片") {// 选中的是识别出的字符
new PicChose(rec_but);
} else if (command == "停止") {// 选中的是识别出的字符
train=false;
add_data.setText("训练");
}
else {// 选中识别字符
input.append(command);
this.repaint();// 重绘
for (int i = 0; i < flag.length; i++) {// 重置数组
for (int j = 0; j < flag[0].length; j++) {
flag[i][j] = 0;
}
}
}
}
// 鼠标监听器
@Override
public void mouseClicked(MouseEvent arg0) {
x1 = arg0.getX();
y1 = arg0.getY();
}
@Override
public void mouseEntered(MouseEvent arg0) {
do_recoginize = false;
}
// 鼠标移出画板开始识别
@Override
public void mouseExited(MouseEvent arg0) {
if (do_recoginize&&train) {//训练
Recoginize rec = new Recoginize(flag);
rec.generatData(train_character);
int[][] flagup=flag;
int[][] flagdown=flag;
int[][] flagleft=flag;
int[][] flagright=flag;
stop1:
while(true) {
for(int i=0;i<flagup.length;i++) {
for(int j=0;j<flagup[0].length;j++) {
if(flagup[i][j]==1&&i-3>0) {
flagup[i-3][j]=flagup[i][j];
flagup[i][j] = 0;
}else if(flagup[i][j]==1&&i-3<=0) {
break stop1;
}
}
}
rec.setFlag(flagup);
rec.generatData(train_character);
}
stop2:
while(true) {
for(int i=flagdown.length-1;i>=0;i--) {
for(int j=0;j<flagdown[0].length;j++) {
if(flagdown[i][j]==1&&i+3<flagdown.length) {
flagdown[i+3][j]=flagdown[i][j];
flagdown[i][j] = 0;
}else if(flagdown[i][j]==1&&i+3>=flagdown.length) {
break stop2;
}
}
}
rec.setFlag(flagdown);
rec.generatData(train_character);
}
stop3:
while(true) {
for(int i=0;i<flagleft.length;i++) {
for(int j=0;j<flagleft[0].length;j++) {
if(flagleft[i][j]==1&&j-3>0) {
flagleft[i][j-3]=flagleft[i][j];
flagleft[i][j] = 0;
}else if(flagleft[i][j]==1&&j-3<=0) {
break stop3;
}
}
}
rec.setFlag(flagleft);
rec.generatData(train_character);
}
stop4:
while(true) {
for(int i=0;i<flagright.length;i++) {
for(int j=flagright[0].length-1;j>=0;j--) {
if(flagright[i][j]==1&&j+3<flagright[0].length) {
flagright[i][j+3]=flagright[i][j];
flagright[i][j] = 0;
}else if(flagright[i][j]==1&&j+3>=flagright[0].length) {
break stop4;
}
}
}
rec.setFlag(flagright);
rec.generatData(train_character);
}
}
}
@Override
public void mousePressed(MouseEvent arg0) {
x1 = arg0.getX();
y1 = arg0.getY();
}
@Override
public void mouseReleased(MouseEvent arg0) {
if(!train){
Recoginize rec = new Recoginize(flag);
char[] rec_result = rec.getChars_result();// 获得结果
// 向show_recoginion中添加识别出的字符
for (int i = 0; i < rec_result.length; i++) {
rec_but[i].setText("" + rec_result[i]);
}
}
}
@Override
public void mouseDragged(MouseEvent e) {
Graphics2D g2d = (Graphics2D) hwr_graphics;
BasicStroke stokeLine = new BasicStroke(5.0f);
g2d.setStroke(stokeLine);
x2 = e.getX();
y2 = e.getY();
g2d.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
int index_x = x1 / width;
int index_y = y1 / width;
if (index_x >= COL_NUM)
index_x = COL_NUM-1;
if (index_y >= ROW_NUM)
index_y = ROW_NUM-1;
if (index_x < 0)
index_x = 0;
if (index_y < 0)
index_y = 0;
flag[index_y][index_x] = 1;
do_recoginize = true;
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
| false | 2,382 | 8 | 2,958 | 7 | 2,892 | 6 | 2,958 | 7 | 3,849 | 16 | false | false | false | false | false | true |
26173_3 | package com.west2.java.work2;
/**
* 动物商店接口
*
* @author Poldroc
* @date 2023/10/25
*/
public interface AnimalShop {
/**
* 买入新动物
*
* @param animal 动物
* @throws InsufficientBalanceException 余额不足异常
*/
void buyAnimal(Animal animal) throws InsufficientBalanceException;
/**
* 招待客户
*
* @param customer 客户
* @param animal 动物
* @throws AnimalNotFoundException 动物未找到异常
* @throws IllegalStateException 动物商店未开业异常
*/
void greetCustomer(Customer customer, Animal animal) throws AnimalNotFoundException, IllegalStateException;
/**
* 歇业
*/
void close();
/**
* 开业
*/
void open();
}
| Poldroc/work2-demo | src/com/west2/java/work2/AnimalShop.java | 207 | /**
* 歇业
*/ | block_comment | zh-cn | package com.west2.java.work2;
/**
* 动物商店接口
*
* @author Poldroc
* @date 2023/10/25
*/
public interface AnimalShop {
/**
* 买入新动物
*
* @param animal 动物
* @throws InsufficientBalanceException 余额不足异常
*/
void buyAnimal(Animal animal) throws InsufficientBalanceException;
/**
* 招待客户
*
* @param customer 客户
* @param animal 动物
* @throws AnimalNotFoundException 动物未找到异常
* @throws IllegalStateException 动物商店未开业异常
*/
void greetCustomer(Customer customer, Animal animal) throws AnimalNotFoundException, IllegalStateException;
/**
* 歇业
<SUF>*/
void close();
/**
* 开业
*/
void open();
}
| false | 199 | 9 | 207 | 9 | 211 | 10 | 207 | 9 | 278 | 12 | false | false | false | false | false | true |
59504_3 | package com.portable.server.type;
import com.portable.server.exception.ExceptionTextType;
import lombok.Getter;
import java.util.Objects;
/**
* @author shiroha
*/
@Getter
public enum OrganizationType implements ExceptionTextType {
/**
* 00000000 学生
*/
STUDENT(0x0, "普通学生"),
/**
* 00000001 特别的学生
*/
SPECIAL_STUDENT(0x01, "特别的学生"),
/**
* 00000011 老师
*/
TEACHER(0x03, "老师"),
/**
* 00000101 集训队
*/
ACMER(0x05, "集训队成员"),
/**
* 00000111 ACM 会长
*/
PRESIDENT(0x07, "ACM 会长"),
/**
* 00001111 荣誉管理
*/
HONOR(0x0f, "荣誉集训队成员"),
/**
* 00011111 教练
*/
BOSS(0x1f, "教练"),
/**
* 11111111 超级管理员
*/
ADMIN(0xff, "超级管理员"),
;
private final Integer code;
private final String text;
OrganizationType(Integer code, String text) {
this.code = code;
this.text = text;
}
public Boolean isDominate(OrganizationType organizationType) {
return !Objects.equals(this, organizationType) && Integer.valueOf((this.code & organizationType.code)).equals(organizationType.getCode());
}
}
| PortableOJ/portable-server | portable-dao/src/main/java/com/portable/server/type/OrganizationType.java | 426 | /**
* 00000011 老师
*/ | block_comment | zh-cn | package com.portable.server.type;
import com.portable.server.exception.ExceptionTextType;
import lombok.Getter;
import java.util.Objects;
/**
* @author shiroha
*/
@Getter
public enum OrganizationType implements ExceptionTextType {
/**
* 00000000 学生
*/
STUDENT(0x0, "普通学生"),
/**
* 00000001 特别的学生
*/
SPECIAL_STUDENT(0x01, "特别的学生"),
/**
* 000 <SUF>*/
TEACHER(0x03, "老师"),
/**
* 00000101 集训队
*/
ACMER(0x05, "集训队成员"),
/**
* 00000111 ACM 会长
*/
PRESIDENT(0x07, "ACM 会长"),
/**
* 00001111 荣誉管理
*/
HONOR(0x0f, "荣誉集训队成员"),
/**
* 00011111 教练
*/
BOSS(0x1f, "教练"),
/**
* 11111111 超级管理员
*/
ADMIN(0xff, "超级管理员"),
;
private final Integer code;
private final String text;
OrganizationType(Integer code, String text) {
this.code = code;
this.text = text;
}
public Boolean isDominate(OrganizationType organizationType) {
return !Objects.equals(this, organizationType) && Integer.valueOf((this.code & organizationType.code)).equals(organizationType.getCode());
}
}
| false | 394 | 19 | 426 | 17 | 436 | 18 | 426 | 17 | 549 | 21 | false | false | false | false | false | true |
59750_2 |
// Definition for singly-linked list.
import java.util.PriorityQueue;
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class MergeKSortedList {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) return null;
// 虚拟头结点
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
// 优先级队列,最小堆
PriorityQueue<ListNode> pq = new PriorityQueue<>(
lists.length, (a, b)->(a.val - b.val));
// 将 k 个链表的头结点加入最小堆
for (ListNode head : lists) {
if (head != null)
pq.add(head);
}
while (!pq.isEmpty()) {
// 获取最小节点,接到结果链表中
ListNode node = pq.poll();
p.next = node;
if (node.next != null) {
pq.add(node.next);
}
// p 指针不断前进
p = p.next;
}
return dummy.next;
}
}
// 详细解析参见:
// https://labuladong.github.io/article/?qno=23
| Portland-Chinese-folks-PoP-leetcode/Leetcode_solution | linked_list/MergeKSortedList.java | 319 | // 优先级队列,最小堆 | line_comment | zh-cn |
// Definition for singly-linked list.
import java.util.PriorityQueue;
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class MergeKSortedList {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) return null;
// 虚拟头结点
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
// 优先 <SUF>
PriorityQueue<ListNode> pq = new PriorityQueue<>(
lists.length, (a, b)->(a.val - b.val));
// 将 k 个链表的头结点加入最小堆
for (ListNode head : lists) {
if (head != null)
pq.add(head);
}
while (!pq.isEmpty()) {
// 获取最小节点,接到结果链表中
ListNode node = pq.poll();
p.next = node;
if (node.next != null) {
pq.add(node.next);
}
// p 指针不断前进
p = p.next;
}
return dummy.next;
}
}
// 详细解析参见:
// https://labuladong.github.io/article/?qno=23
| false | 293 | 9 | 319 | 8 | 339 | 8 | 319 | 8 | 428 | 19 | false | false | false | false | false | true |
22661_2 | package com.zhbit.lw.model.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.zhbit.lw.Logs.Logs;
import com.zhbit.lw.model.dao.ChatTable;
import com.zhbit.lw.model.dao.ChatTableDao;
import com.zhbit.lw.model.dao.FriendTable;
import com.zhbit.lw.model.dao.FriendTableDao;
import com.zhbit.lw.model.dao.InvitationTable;
import com.zhbit.lw.model.dao.MomentTable;
import com.zhbit.lw.model.dao.MomentTableDao;
import com.zhbit.lw.model.dao.UserTable;
import com.zhbit.lw.model.dao.UserTableDao;
/**
* Created by fl5900 on 2017/5/11.
*/
public class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context, String name){
super(context, name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 先判断是否存在表 如果存在就先删除
db.execSQL("DROP TABLE IF EXISTS moment;");
db.execSQL("DROP TABLE IF EXISTS user_infor;");
db.execSQL("DROP TABLE IF EXISTS friend_infor;");
db.execSQL("DROP TABLE IF EXISTS chat_msg;");
db.execSQL("DROP TABLE IF EXISTS invitation;");
//创建朋友圈表
db.execSQL(MomentTable.CreateTable);
Logs.d("TABLE",MomentTable.CreateTable);
//创建个人信息表
db.execSQL(UserTable.CREATE_TABLE);
Logs.d("TABLE",UserTable.CREATE_TABLE);
//创建好友表
db.execSQL(FriendTable.CREATE_TABLE);
Logs.d("TABLE",FriendTable.CREATE_TABLE);
//创建聊天表
db.execSQL(ChatTable.CREATE_TABLE);
Logs.d("TABLE",ChatTable.CREATE_TABLE);
//创建邀请表
db.execSQL(InvitationTable.CREATE_TABLE);
Logs.d("TABLE",InvitationTable.CREATE_TABLE);
// // 插入聊天的测试数据
// String chatSql = "insert into chat_msg(user_id, friend_id, chat_msg_content, chat_msg_time, chat_msg_type, show_time_flag)" +
// " values(1, 2, '您好,好久不见,近来可好。', '2017-2-16 12:30', 'receive', 1)";
// String secondChatSql = "insert into chat_msg(user_id, friend_id, chat_msg_content, chat_msg_time, chat_msg_type, show_time_flag)" +
// " values(1, 2, '还不错啦。', '2017-2-16 12:32', 'send', 1)";
// String thirdChatSql = "insert into chat_msg(user_id, friend_id, chat_msg_content, chat_msg_time, chat_msg_type, show_time_flag)" +
// " values(1, 3, '在吗?。', '2017-2-16 11:30', 'send', 1)";
// db.execSQL(chatSql);
// db.execSQL(secondChatSql);
// db.execSQL(thirdChatSql);
// 插入用户的测试数据
// String userSql = "insert into user_infor(user_id, user_name, user_head, user_sex, user_account, user_location, user_sign)"
// +"values(1, 'Wjh', 'R.drawable.head', '男', 'XR_HUI', '清远市', '水流心赤.')";
// db.execSQL(userSql);
// 插入好友的测试数据
// String friendSql = "insert into friend_infor(user_id, friend_id, group_name, friend_name, nick_name, friend_sex, friend_account, friend_head, friend_location, friend_recent_photo, new_friend_flag, new_friend_request_msg)"
// +"values(1, 2, 'friend', '2: 一本正经、', 'nick_name', '男', 'BLCHAT_01', 'R.drawable.head', '英德市', null, 1, '您好,我是您的老同学。')";
// String senondFriendSql = "insert into friend_infor(user_id, friend_id, group_name, friend_name, nick_name, friend_sex, friend_account, friend_head, friend_location, friend_recent_photo, new_friend_flag, new_friend_request_msg)"
// +"values(1, 3, 'family', '3: 胡说八道、', 'second_name', '女', 'BLCHAT_02', 'R.drawable.head', '珠海市', null, 1, '您好,还记得我吗?')";
// db.execSQL(friendSql);
// db.execSQL(senondFriendSql);
// 插入朋友圈的测试数据
String momentSql = "insert into moment(friendname,friendid,headphoto,publishtime,publishtext,publishImg)"
+"values('Gavin Lin','liz0607','@drawable/head','2017/5/12','富强、民主、文明、和谐,倡导自由"
+ "、平等、公正、法治,倡导爱国、敬业、诚信、友善','@drawable/app_icon')";
db.execSQL(momentSql);
db.execSQL(momentSql);
//插入新好友邀请
// String newInvitation = "insert into invitation(account,reason,status) values('Gavin','希望能认识你',1);";
// String newInvitation2 = "insert into invitation(account,reason,status) values('Gavin12','希望能认识你',1);";
// db.execSQL(newInvitation);
// db.execSQL(newInvitation2);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| PowerDos/BLChat | app/src/main/java/com/zhbit/lw/model/db/DBHelper.java | 1,577 | //创建朋友圈表 | line_comment | zh-cn | package com.zhbit.lw.model.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.zhbit.lw.Logs.Logs;
import com.zhbit.lw.model.dao.ChatTable;
import com.zhbit.lw.model.dao.ChatTableDao;
import com.zhbit.lw.model.dao.FriendTable;
import com.zhbit.lw.model.dao.FriendTableDao;
import com.zhbit.lw.model.dao.InvitationTable;
import com.zhbit.lw.model.dao.MomentTable;
import com.zhbit.lw.model.dao.MomentTableDao;
import com.zhbit.lw.model.dao.UserTable;
import com.zhbit.lw.model.dao.UserTableDao;
/**
* Created by fl5900 on 2017/5/11.
*/
public class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context, String name){
super(context, name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 先判断是否存在表 如果存在就先删除
db.execSQL("DROP TABLE IF EXISTS moment;");
db.execSQL("DROP TABLE IF EXISTS user_infor;");
db.execSQL("DROP TABLE IF EXISTS friend_infor;");
db.execSQL("DROP TABLE IF EXISTS chat_msg;");
db.execSQL("DROP TABLE IF EXISTS invitation;");
//创建 <SUF>
db.execSQL(MomentTable.CreateTable);
Logs.d("TABLE",MomentTable.CreateTable);
//创建个人信息表
db.execSQL(UserTable.CREATE_TABLE);
Logs.d("TABLE",UserTable.CREATE_TABLE);
//创建好友表
db.execSQL(FriendTable.CREATE_TABLE);
Logs.d("TABLE",FriendTable.CREATE_TABLE);
//创建聊天表
db.execSQL(ChatTable.CREATE_TABLE);
Logs.d("TABLE",ChatTable.CREATE_TABLE);
//创建邀请表
db.execSQL(InvitationTable.CREATE_TABLE);
Logs.d("TABLE",InvitationTable.CREATE_TABLE);
// // 插入聊天的测试数据
// String chatSql = "insert into chat_msg(user_id, friend_id, chat_msg_content, chat_msg_time, chat_msg_type, show_time_flag)" +
// " values(1, 2, '您好,好久不见,近来可好。', '2017-2-16 12:30', 'receive', 1)";
// String secondChatSql = "insert into chat_msg(user_id, friend_id, chat_msg_content, chat_msg_time, chat_msg_type, show_time_flag)" +
// " values(1, 2, '还不错啦。', '2017-2-16 12:32', 'send', 1)";
// String thirdChatSql = "insert into chat_msg(user_id, friend_id, chat_msg_content, chat_msg_time, chat_msg_type, show_time_flag)" +
// " values(1, 3, '在吗?。', '2017-2-16 11:30', 'send', 1)";
// db.execSQL(chatSql);
// db.execSQL(secondChatSql);
// db.execSQL(thirdChatSql);
// 插入用户的测试数据
// String userSql = "insert into user_infor(user_id, user_name, user_head, user_sex, user_account, user_location, user_sign)"
// +"values(1, 'Wjh', 'R.drawable.head', '男', 'XR_HUI', '清远市', '水流心赤.')";
// db.execSQL(userSql);
// 插入好友的测试数据
// String friendSql = "insert into friend_infor(user_id, friend_id, group_name, friend_name, nick_name, friend_sex, friend_account, friend_head, friend_location, friend_recent_photo, new_friend_flag, new_friend_request_msg)"
// +"values(1, 2, 'friend', '2: 一本正经、', 'nick_name', '男', 'BLCHAT_01', 'R.drawable.head', '英德市', null, 1, '您好,我是您的老同学。')";
// String senondFriendSql = "insert into friend_infor(user_id, friend_id, group_name, friend_name, nick_name, friend_sex, friend_account, friend_head, friend_location, friend_recent_photo, new_friend_flag, new_friend_request_msg)"
// +"values(1, 3, 'family', '3: 胡说八道、', 'second_name', '女', 'BLCHAT_02', 'R.drawable.head', '珠海市', null, 1, '您好,还记得我吗?')";
// db.execSQL(friendSql);
// db.execSQL(senondFriendSql);
// 插入朋友圈的测试数据
String momentSql = "insert into moment(friendname,friendid,headphoto,publishtime,publishtext,publishImg)"
+"values('Gavin Lin','liz0607','@drawable/head','2017/5/12','富强、民主、文明、和谐,倡导自由"
+ "、平等、公正、法治,倡导爱国、敬业、诚信、友善','@drawable/app_icon')";
db.execSQL(momentSql);
db.execSQL(momentSql);
//插入新好友邀请
// String newInvitation = "insert into invitation(account,reason,status) values('Gavin','希望能认识你',1);";
// String newInvitation2 = "insert into invitation(account,reason,status) values('Gavin12','希望能认识你',1);";
// db.execSQL(newInvitation);
// db.execSQL(newInvitation2);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| false | 1,257 | 4 | 1,577 | 8 | 1,511 | 4 | 1,577 | 8 | 1,798 | 11 | false | false | false | false | false | true |
7538_10 | package com.mall.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
* 商品评论
*/
@Entity
@Table(name = "goods_comment")
public class GoodsComment {
/**
* TODO
* 1.增加评论
* POST:
* {
* commemtContent: '评论信息',
* commentLevel: 4,
* tags: "好用,不错,货美价廉",
* username: "Gavin",
* userid: 1,
* goodsId: 1,
* attrTitle: "4.7英寸-深邃蓝",
* attrId: 102,
* orderId: 2
* }
*
* 注意:goodsId 是外键,连接商品
*
* 2. 获取评论
* 方法 goodsService.findById() 获取单个商品时,需要返回字段 comment
* 具体展示内容如下:
*
* comment: {
* commentNum: 16, // 总评论数
* remarksNumDetail: [ 2, 2, 2, 3, 1 ] // 分别是5个评论等级的评论数(字段:commentLevel), [ 好评, 满意, 一般, 差, 非常差 ]
* detail: [ // 评论详细内容
* {
* username: "Gavin", // 用户名
* commentLevel: 5, // 等级
* commemtContent: "颜色很好看,质量也不错!", // 评论
* attrTitle: "4.7英寸-深邃蓝",
* tags: "好用,不错,货美价廉",
* createAt: "2018-05-15 09:20"
* },
* {
* username: "Gavin", // 用户名
* commentLevel: 5, // 等级
* commemtContent: "颜色很好看,质量也不错!", // 评论
* attrTitle: "4.7英寸-深邃蓝",
* tags: "好用,不错,货美价廉",
* createAt: "2018-05-15 09:20"
* }
* ]
* }
*/
// 唯一标识 ID
@Id
@GeneratedValue(generator = "id")
@GenericGenerator(name = "id", strategy = "native")
private int id;
// 评价内容
private String commentContent;
// 评价等级:星星数量
private int commentLevel;
// 评论标签 例:"好用,不错,货美价廉" 前台写死规定几个标签供选择
private String tags;
// 用户名
private String username;
// 用户id
private int userid;
// 商品Id # 外键
private int goodsId;
// 套餐描述
private String attrTitle;
// 评论时间
private Date createAt;
// 订单号
private String orderId;
// @ManyToOne
// private Goods goods;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCommentContent() {
return commentContent;
}
public void setCommentContent(String commentContent) {
this.commentContent = commentContent;
}
public int getCommentLevel() {
return commentLevel;
}
public void setCommentLevel(int commentLevel) {
this.commentLevel = commentLevel;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
tags = tags;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getGoodsId() {
return goodsId;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public String getAttrTitle() {
return attrTitle;
}
public void setAttrTitle(String attrTitle) {
this.attrTitle = attrTitle;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
}
| PowerDos/Mall-Server | src/main/java/com/mall/model/GoodsComment.java | 1,114 | // 评论时间 | line_comment | zh-cn | package com.mall.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
* 商品评论
*/
@Entity
@Table(name = "goods_comment")
public class GoodsComment {
/**
* TODO
* 1.增加评论
* POST:
* {
* commemtContent: '评论信息',
* commentLevel: 4,
* tags: "好用,不错,货美价廉",
* username: "Gavin",
* userid: 1,
* goodsId: 1,
* attrTitle: "4.7英寸-深邃蓝",
* attrId: 102,
* orderId: 2
* }
*
* 注意:goodsId 是外键,连接商品
*
* 2. 获取评论
* 方法 goodsService.findById() 获取单个商品时,需要返回字段 comment
* 具体展示内容如下:
*
* comment: {
* commentNum: 16, // 总评论数
* remarksNumDetail: [ 2, 2, 2, 3, 1 ] // 分别是5个评论等级的评论数(字段:commentLevel), [ 好评, 满意, 一般, 差, 非常差 ]
* detail: [ // 评论详细内容
* {
* username: "Gavin", // 用户名
* commentLevel: 5, // 等级
* commemtContent: "颜色很好看,质量也不错!", // 评论
* attrTitle: "4.7英寸-深邃蓝",
* tags: "好用,不错,货美价廉",
* createAt: "2018-05-15 09:20"
* },
* {
* username: "Gavin", // 用户名
* commentLevel: 5, // 等级
* commemtContent: "颜色很好看,质量也不错!", // 评论
* attrTitle: "4.7英寸-深邃蓝",
* tags: "好用,不错,货美价廉",
* createAt: "2018-05-15 09:20"
* }
* ]
* }
*/
// 唯一标识 ID
@Id
@GeneratedValue(generator = "id")
@GenericGenerator(name = "id", strategy = "native")
private int id;
// 评价内容
private String commentContent;
// 评价等级:星星数量
private int commentLevel;
// 评论标签 例:"好用,不错,货美价廉" 前台写死规定几个标签供选择
private String tags;
// 用户名
private String username;
// 用户id
private int userid;
// 商品Id # 外键
private int goodsId;
// 套餐描述
private String attrTitle;
// 评论 <SUF>
private Date createAt;
// 订单号
private String orderId;
// @ManyToOne
// private Goods goods;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCommentContent() {
return commentContent;
}
public void setCommentContent(String commentContent) {
this.commentContent = commentContent;
}
public int getCommentLevel() {
return commentLevel;
}
public void setCommentLevel(int commentLevel) {
this.commentLevel = commentLevel;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
tags = tags;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getGoodsId() {
return goodsId;
}
public void setGoodsId(int goodsId) {
this.goodsId = goodsId;
}
public String getAttrTitle() {
return attrTitle;
}
public void setAttrTitle(String attrTitle) {
this.attrTitle = attrTitle;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
}
| false | 1,058 | 4 | 1,114 | 4 | 1,176 | 4 | 1,114 | 4 | 1,525 | 10 | false | false | false | false | false | true |
21619_9 | package com.pojo;
/**
* 王月妍
* 日报对象实体封装类
* 2017-2-23
* 秦杰 将workload改为int型,添加depid部门id 2017-2-27
*/
import java.util.Date;
public class Ribaodata {
private String baoid; //日报ID
private String proid; //项目ID
private String proname; //项目名称
private String proprp; //日报PRP
private String context; //任务
private int workload; //工作量
private int addtime; //加班时间
private Date uptime; //日报上传时间
private String renid; //编写人ID
private String renname; //编写人名
private String upid; //上司ID
private String upstate; //上传状态
private String shenstate; //日报审核状态
private String reason; //原因
private String depid; //部门id
public String getBaoid() {
return baoid;
}
public void setBaoid(String baoid) {
this.baoid = baoid;
}
public String getProid() {
return proid;
}
public void setProid(String proid) {
this.proid = proid;
}
public String getProname() {
return proname;
}
public void setProname(String proname) {
this.proname = proname;
}
public String getProprp() {
return proprp;
}
public void setProprp(String proprp) {
this.proprp = proprp;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public int getWorkload() {
return workload;
}
public void setWorkload(int workload) {
this.workload = workload;
}
public int getAddtime() {
return addtime;
}
public void setAddtime(int addtime) {
this.addtime = addtime;
}
public Date getUptime() {
return uptime;
}
public void setUptime(Date uptime) {
this.uptime = uptime;
}
public String getRenid() {
return renid;
}
public void setRenid(String renid) {
this.renid = renid;
}
public String getRenname() {
return renname;
}
public void setRenname(String renname) {
this.renname = renname;
}
public String getUpid() {
return upid;
}
public void setUpid(String upid) {
this.upid = upid;
}
public String getUpstate() {
return upstate;
}
public void setUpstate(String upstate) {
this.upstate = upstate;
}
public String getShenstate() {
return shenstate;
}
public void setShenstate(String shenstate) {
this.shenstate = shenstate;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getDepid() {
return depid;
}
public void setDepid(String depid) {
this.depid = depid;
}
}
| Presciman/DailyPaperMS_Neu | src/com/pojo/Ribaodata.java | 918 | //编写人ID
| line_comment | zh-cn | package com.pojo;
/**
* 王月妍
* 日报对象实体封装类
* 2017-2-23
* 秦杰 将workload改为int型,添加depid部门id 2017-2-27
*/
import java.util.Date;
public class Ribaodata {
private String baoid; //日报ID
private String proid; //项目ID
private String proname; //项目名称
private String proprp; //日报PRP
private String context; //任务
private int workload; //工作量
private int addtime; //加班时间
private Date uptime; //日报上传时间
private String renid; //编写 <SUF>
private String renname; //编写人名
private String upid; //上司ID
private String upstate; //上传状态
private String shenstate; //日报审核状态
private String reason; //原因
private String depid; //部门id
public String getBaoid() {
return baoid;
}
public void setBaoid(String baoid) {
this.baoid = baoid;
}
public String getProid() {
return proid;
}
public void setProid(String proid) {
this.proid = proid;
}
public String getProname() {
return proname;
}
public void setProname(String proname) {
this.proname = proname;
}
public String getProprp() {
return proprp;
}
public void setProprp(String proprp) {
this.proprp = proprp;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public int getWorkload() {
return workload;
}
public void setWorkload(int workload) {
this.workload = workload;
}
public int getAddtime() {
return addtime;
}
public void setAddtime(int addtime) {
this.addtime = addtime;
}
public Date getUptime() {
return uptime;
}
public void setUptime(Date uptime) {
this.uptime = uptime;
}
public String getRenid() {
return renid;
}
public void setRenid(String renid) {
this.renid = renid;
}
public String getRenname() {
return renname;
}
public void setRenname(String renname) {
this.renname = renname;
}
public String getUpid() {
return upid;
}
public void setUpid(String upid) {
this.upid = upid;
}
public String getUpstate() {
return upstate;
}
public void setUpstate(String upstate) {
this.upstate = upstate;
}
public String getShenstate() {
return shenstate;
}
public void setShenstate(String shenstate) {
this.shenstate = shenstate;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getDepid() {
return depid;
}
public void setDepid(String depid) {
this.depid = depid;
}
}
| false | 730 | 5 | 916 | 5 | 887 | 5 | 916 | 5 | 1,044 | 6 | false | false | false | false | false | true |
17260_3 | package com.cyw.leetcode;
public class DecodeWaysProblem91 {
/**
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
反编码
"12": "AB" (1 2) or "L" (12). 反编码方式的个数
* @param s
* @return
*/
public int numDecodings(String s) {
if(s==null || s.length()<=0) return 0;
//1-26。其实是对字符串数的一个分段。跟IP分割一样
//每次取一个字符或者两个字符
int len = s.length();
int[] cache = new int[len];
if(s.charAt(0)!='0') cache[0] = 1;
else return 0;
if(s.length()==1) return cache[0];
//各位个数不能为0
//分割一个字符
if(s.charAt(1)!='0') cache[1] = cache[0];
else cache[1] = 0;
//分割两个字符 注意前面不能从0开始
int tem = Integer.parseInt(s.substring(0, 2));
if(tem>0 && tem<=26 ) cache[1] += 1;
// else cache[1] = 1;
if(cache[1]==0) return 0;
for(int i=2;i<len;i++){
//分割一个字符
if(s.charAt(i)!='0') cache[i] = cache[i-1];
else cache[i] = 0;
//分割两个字符 注意前面不能从0开始
int temp = Integer.parseInt(s.substring(i-1, i+1));
if(temp>0 && temp<=26 && s.charAt(i-1)!='0') cache[i] += cache[i-2];
if(cache[1]==0) return 0;
}
return cache[len-1];
}
public static void main(String[] args) {
DecodeWaysProblem91 de = new DecodeWaysProblem91();
//自己多想一下test cases
//12 "" 0 1 10 101 100 301 30
System.out.println(de.numDecodings("301"));
}
}
| PrivateVictory/Leetcode | src/cyw/DP/DecodeWaysProblem91.java | 616 | //各位个数不能为0 | line_comment | zh-cn | package com.cyw.leetcode;
public class DecodeWaysProblem91 {
/**
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
反编码
"12": "AB" (1 2) or "L" (12). 反编码方式的个数
* @param s
* @return
*/
public int numDecodings(String s) {
if(s==null || s.length()<=0) return 0;
//1-26。其实是对字符串数的一个分段。跟IP分割一样
//每次取一个字符或者两个字符
int len = s.length();
int[] cache = new int[len];
if(s.charAt(0)!='0') cache[0] = 1;
else return 0;
if(s.length()==1) return cache[0];
//各位 <SUF>
//分割一个字符
if(s.charAt(1)!='0') cache[1] = cache[0];
else cache[1] = 0;
//分割两个字符 注意前面不能从0开始
int tem = Integer.parseInt(s.substring(0, 2));
if(tem>0 && tem<=26 ) cache[1] += 1;
// else cache[1] = 1;
if(cache[1]==0) return 0;
for(int i=2;i<len;i++){
//分割一个字符
if(s.charAt(i)!='0') cache[i] = cache[i-1];
else cache[i] = 0;
//分割两个字符 注意前面不能从0开始
int temp = Integer.parseInt(s.substring(i-1, i+1));
if(temp>0 && temp<=26 && s.charAt(i-1)!='0') cache[i] += cache[i-2];
if(cache[1]==0) return 0;
}
return cache[len-1];
}
public static void main(String[] args) {
DecodeWaysProblem91 de = new DecodeWaysProblem91();
//自己多想一下test cases
//12 "" 0 1 10 101 100 301 30
System.out.println(de.numDecodings("301"));
}
}
| false | 546 | 7 | 616 | 7 | 636 | 6 | 616 | 7 | 729 | 11 | false | false | false | false | false | true |
13938_4 | package tool;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import static tool.Tools.getValidNumber;
/**
* Created by Eldath on 2017/1/21 0021.
*
* @author Eldath
*/
@SuppressWarnings({"WeakerAccess", "SameParameterValue"})
public class VerifyAccount {
static {
logger = LoggerFactory.getLogger(VerifyAccount.class);
}
private static VerifyAccount instance;
private static final Logger logger;
private static final String SOFApiRoot = "http://api.stackexchange.com/2.2/";
private static final String ZhihuApiRoot = "https://www.zhihu.com/node/MemberProfileCardV2?params={\"url_token\"%%3A\"%s\"}";
private VerifyAccount() {
}
@NotNull
public static VerifyAccount getInstance() {
if (instance == null) instance = new VerifyAccount();
return instance;
}
//FIXME: 既然返回是布尔干嘛说是重要性。。直接checkIfIsIpInZhihu
// 听说这里很慢
public boolean verifyZhihuImportance(@NotNull @NonNls String username) {
try {
IntTokenizer tokenizer = null;
Document page = Jsoup.parse(
new URL(String.format(ZhihuApiRoot,username)),
5000
);
Elements root = page.select("div[class='meta']");
tokenizer = IntTokenizer.of(root.text());
int reputationPoint = tokenizer.nextToken();
tokenizer.nextToken();
int likesPoint = tokenizer.nextToken();
return (reputationPoint >= 50 && likesPoint >= 40);
} catch (IOException e) {
throw new RuntimeException("unable to fetch data from zhihu", e);
}
}
public boolean verifyStackOverFlowImportance(@NotNull @NonNls String username) {
try {
String url = SOFApiRoot + String.format(
"users?order=asc&min=%s&max=%s&sort=name&inname=%s&site=stackoverflow&filter=!9YdnSAffT",
username,
username,
username
);
HttpURLConnection conn = HttpURLConnection.class.cast(new URL(url).openConnection());
if(conn.getResponseCode() != 200) return false;
JSONTokener tokener = new JSONTokener(new GZIPInputStream(conn.getInputStream()));
JSONObject object = JSONObject.class.cast(tokener.nextValue());
conn.disconnect();
if (object.getJSONArray("items").length() == 0)
return false;
else {
JSONObject user = JSONObject.class.cast(object.getJSONArray("items").get(0));
return user.getInt("answer_count") >= 5;
}
} catch (IOException e) {
throw new RuntimeException("unable to fetch data from stackoverflow", e);
}
}
public boolean verifyZhihuAccount(@NotNull @NonNls String username) {
return verify("https://www.zhihu.com/people/", username);
//FIXME: 由于严重违反知乎社区规范,该用户帐号已被停用。 这个是返回200的,测试账号fu-qian-yi-55
//回上 , 这个账号测试返回404 。。。。。 具体去看test case
}
public boolean verifyStackOverFlowAccount(@NotNull @NonNls String username) {
try {
String url = SOFApiRoot + String.format(
"users?order=asc&min=%s&max=%s&sort=name&inname=%s&site=stackoverflow",
username,
username,
username
);
HttpURLConnection conn = HttpURLConnection.class.cast(new URL(url).openConnection());
if (conn.getResponseCode() != 200) return false;
JSONTokener tokener = new JSONTokener(new GZIPInputStream(conn.getInputStream()));
// note that it was compressed
JSONObject object = JSONObject.class.cast(tokener.nextValue());
conn.disconnect();
return object.getJSONArray("items").length() != 0;
// 特判一下吧还是。。昨晚查询不存在用户返回的是200 ...和一个json
// 上面打这段注释的,没注意到我判断了返回的结果是否包含有效用户吗 =-= , bug 'fixed'
} catch (IOException e) {
throw new RuntimeException("unable to fetch data from stackoverflow", e);
}
}
public boolean verifyGitHubAccount(@NotNull @NonNls String username) {
return verify("https://github.com/", username);
}
private boolean verify(
@NotNull @NonNls String contextPath,
@NotNull @NonNls String username) {
try {
URL url = new URL(contextPath + username);
HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection());
connection.connect();
return connection.getResponseCode() == 200;
// 要是人家不404 呢?
// 其实之前写的是 if (reCo == 404) return false; else return true...我就给改了 ---ice
// 改得好,搞个大新闻批判一番 - 磷
} catch (MalformedURLException e) {
logger.warn("URL exception: ", e);
return false;
} catch (IOException ex) {
logger.warn("IO exception: ", ex);
return false;
}
}
}
| ProgramLeague/strictfp-back-end | src/main/java/tool/VerifyAccount.java | 1,496 | // 听说这里很慢 | line_comment | zh-cn | package tool;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import static tool.Tools.getValidNumber;
/**
* Created by Eldath on 2017/1/21 0021.
*
* @author Eldath
*/
@SuppressWarnings({"WeakerAccess", "SameParameterValue"})
public class VerifyAccount {
static {
logger = LoggerFactory.getLogger(VerifyAccount.class);
}
private static VerifyAccount instance;
private static final Logger logger;
private static final String SOFApiRoot = "http://api.stackexchange.com/2.2/";
private static final String ZhihuApiRoot = "https://www.zhihu.com/node/MemberProfileCardV2?params={\"url_token\"%%3A\"%s\"}";
private VerifyAccount() {
}
@NotNull
public static VerifyAccount getInstance() {
if (instance == null) instance = new VerifyAccount();
return instance;
}
//FIXME: 既然返回是布尔干嘛说是重要性。。直接checkIfIsIpInZhihu
// 听说 <SUF>
public boolean verifyZhihuImportance(@NotNull @NonNls String username) {
try {
IntTokenizer tokenizer = null;
Document page = Jsoup.parse(
new URL(String.format(ZhihuApiRoot,username)),
5000
);
Elements root = page.select("div[class='meta']");
tokenizer = IntTokenizer.of(root.text());
int reputationPoint = tokenizer.nextToken();
tokenizer.nextToken();
int likesPoint = tokenizer.nextToken();
return (reputationPoint >= 50 && likesPoint >= 40);
} catch (IOException e) {
throw new RuntimeException("unable to fetch data from zhihu", e);
}
}
public boolean verifyStackOverFlowImportance(@NotNull @NonNls String username) {
try {
String url = SOFApiRoot + String.format(
"users?order=asc&min=%s&max=%s&sort=name&inname=%s&site=stackoverflow&filter=!9YdnSAffT",
username,
username,
username
);
HttpURLConnection conn = HttpURLConnection.class.cast(new URL(url).openConnection());
if(conn.getResponseCode() != 200) return false;
JSONTokener tokener = new JSONTokener(new GZIPInputStream(conn.getInputStream()));
JSONObject object = JSONObject.class.cast(tokener.nextValue());
conn.disconnect();
if (object.getJSONArray("items").length() == 0)
return false;
else {
JSONObject user = JSONObject.class.cast(object.getJSONArray("items").get(0));
return user.getInt("answer_count") >= 5;
}
} catch (IOException e) {
throw new RuntimeException("unable to fetch data from stackoverflow", e);
}
}
public boolean verifyZhihuAccount(@NotNull @NonNls String username) {
return verify("https://www.zhihu.com/people/", username);
//FIXME: 由于严重违反知乎社区规范,该用户帐号已被停用。 这个是返回200的,测试账号fu-qian-yi-55
//回上 , 这个账号测试返回404 。。。。。 具体去看test case
}
public boolean verifyStackOverFlowAccount(@NotNull @NonNls String username) {
try {
String url = SOFApiRoot + String.format(
"users?order=asc&min=%s&max=%s&sort=name&inname=%s&site=stackoverflow",
username,
username,
username
);
HttpURLConnection conn = HttpURLConnection.class.cast(new URL(url).openConnection());
if (conn.getResponseCode() != 200) return false;
JSONTokener tokener = new JSONTokener(new GZIPInputStream(conn.getInputStream()));
// note that it was compressed
JSONObject object = JSONObject.class.cast(tokener.nextValue());
conn.disconnect();
return object.getJSONArray("items").length() != 0;
// 特判一下吧还是。。昨晚查询不存在用户返回的是200 ...和一个json
// 上面打这段注释的,没注意到我判断了返回的结果是否包含有效用户吗 =-= , bug 'fixed'
} catch (IOException e) {
throw new RuntimeException("unable to fetch data from stackoverflow", e);
}
}
public boolean verifyGitHubAccount(@NotNull @NonNls String username) {
return verify("https://github.com/", username);
}
private boolean verify(
@NotNull @NonNls String contextPath,
@NotNull @NonNls String username) {
try {
URL url = new URL(contextPath + username);
HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection());
connection.connect();
return connection.getResponseCode() == 200;
// 要是人家不404 呢?
// 其实之前写的是 if (reCo == 404) return false; else return true...我就给改了 ---ice
// 改得好,搞个大新闻批判一番 - 磷
} catch (MalformedURLException e) {
logger.warn("URL exception: ", e);
return false;
} catch (IOException ex) {
logger.warn("IO exception: ", ex);
return false;
}
}
}
| false | 1,250 | 7 | 1,496 | 7 | 1,445 | 6 | 1,496 | 7 | 1,860 | 14 | false | false | false | false | false | true |
24778_11 | package cn.shaoxiongdu.chapter4;
import java.lang.ref.SoftReference;
/**
* 软引用的测试:内存不足即回收
* -Xms10m -Xmx10m -XX:+PrintGCDetails
*/
public class SoftReferenceTest {
public static class User {
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int id;
public String name;
@Override
public String toString() {
return "[id=" + id + ", name=" + name + "] ";
}
}
public static void main(String[] args) {
//创建对象,建立软引用
// SoftReference<User> userSoftRef = new SoftReference<User>(new User(1, "songhk"));
//上面的一行代码,等价于如下的三行代码
User u1 = new User(1,"songhk");
SoftReference<User> userSoftRef = new SoftReference<User>(u1);
u1 = null;//取消强引用
//从软引用中重新获得强引用对象
System.out.println("GC之前软引用获取的对象" + userSoftRef.get());
System.gc();
//垃圾回收之后获得软引用中的对象
System.out.println("GC之后软引用获取的对象" + userSoftRef.get());//由于堆空间内存足够,所有不会回收软引用的可达对象。
try {
//让系统认为内存资源紧张、不够
// byte[] b = new byte[1024 * 1024 * 7];
byte[] b = new byte[1024 * 7168 - 399 * 1024];//恰好能放下数组又放不下u1的内存分配大小 不会报OOM
} catch (Throwable e) {
e.printStackTrace();
} finally {
//再次从软引用中获取数据
System.out.println("资源不足之后GC:软引用获取的对象" + userSoftRef.get());//在报OOM之前,垃圾回收器会回收软引用的可达对象。
}
}
}
| Programming-With-Love/JVMStudy | demo/src/cn/shaoxiongdu/chapter4/SoftReferenceTest.java | 515 | //再次从软引用中获取数据 | line_comment | zh-cn | package cn.shaoxiongdu.chapter4;
import java.lang.ref.SoftReference;
/**
* 软引用的测试:内存不足即回收
* -Xms10m -Xmx10m -XX:+PrintGCDetails
*/
public class SoftReferenceTest {
public static class User {
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int id;
public String name;
@Override
public String toString() {
return "[id=" + id + ", name=" + name + "] ";
}
}
public static void main(String[] args) {
//创建对象,建立软引用
// SoftReference<User> userSoftRef = new SoftReference<User>(new User(1, "songhk"));
//上面的一行代码,等价于如下的三行代码
User u1 = new User(1,"songhk");
SoftReference<User> userSoftRef = new SoftReference<User>(u1);
u1 = null;//取消强引用
//从软引用中重新获得强引用对象
System.out.println("GC之前软引用获取的对象" + userSoftRef.get());
System.gc();
//垃圾回收之后获得软引用中的对象
System.out.println("GC之后软引用获取的对象" + userSoftRef.get());//由于堆空间内存足够,所有不会回收软引用的可达对象。
try {
//让系统认为内存资源紧张、不够
// byte[] b = new byte[1024 * 1024 * 7];
byte[] b = new byte[1024 * 7168 - 399 * 1024];//恰好能放下数组又放不下u1的内存分配大小 不会报OOM
} catch (Throwable e) {
e.printStackTrace();
} finally {
//再次 <SUF>
System.out.println("资源不足之后GC:软引用获取的对象" + userSoftRef.get());//在报OOM之前,垃圾回收器会回收软引用的可达对象。
}
}
}
| false | 461 | 8 | 515 | 9 | 518 | 8 | 515 | 9 | 685 | 14 | false | false | false | false | false | true |
56580_2 | /*
* 版权所有 (c) 2021. 写Bug的小杜 <https://github.com/shaoxiongdu> 保留所有权利
*/
package cn.shaoxiongdu.po;
import javax.persistence.*;
import java.util.Date;
/**
* 网站访问记录
*/
@Table(name = "t_record")
@Entity
public class Record {
@Id
@GeneratedValue
private Long id;
private String ip;
private String address;
@Temporal(TemporalType.TIMESTAMP)
private Date lastVisitTime;
@Override
public String toString() {
return "访问记录[" +
"记录ID:" + id +
", IP='" + ip + '\'' +
", 地区='" + address + '\'' +
", 访问时间=" + lastVisitTime +
", 总访问次数=" + totalNumberOfVisits +
']';
}
/**
* 访问总次数
*/
private Long totalNumberOfVisits;
public Long getTotalNumberOfVisits() {
return totalNumberOfVisits;
}
public void setTotalNumberOfVisits(Long totalNumberOfVisits) {
this.totalNumberOfVisits = totalNumberOfVisits;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getLastVisitTime() {
return lastVisitTime;
}
public void setLastVisitTime(Date dateTime) {
this.lastVisitTime = dateTime;
}
public Record() {
}
}
| Programming-With-Love/blog | src/main/java/cn/shaoxiongdu/po/Record.java | 423 | /**
* 访问总次数
*/ | block_comment | zh-cn | /*
* 版权所有 (c) 2021. 写Bug的小杜 <https://github.com/shaoxiongdu> 保留所有权利
*/
package cn.shaoxiongdu.po;
import javax.persistence.*;
import java.util.Date;
/**
* 网站访问记录
*/
@Table(name = "t_record")
@Entity
public class Record {
@Id
@GeneratedValue
private Long id;
private String ip;
private String address;
@Temporal(TemporalType.TIMESTAMP)
private Date lastVisitTime;
@Override
public String toString() {
return "访问记录[" +
"记录ID:" + id +
", IP='" + ip + '\'' +
", 地区='" + address + '\'' +
", 访问时间=" + lastVisitTime +
", 总访问次数=" + totalNumberOfVisits +
']';
}
/**
* 访问总 <SUF>*/
private Long totalNumberOfVisits;
public Long getTotalNumberOfVisits() {
return totalNumberOfVisits;
}
public void setTotalNumberOfVisits(Long totalNumberOfVisits) {
this.totalNumberOfVisits = totalNumberOfVisits;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getLastVisitTime() {
return lastVisitTime;
}
public void setLastVisitTime(Date dateTime) {
this.lastVisitTime = dateTime;
}
public Record() {
}
}
| false | 392 | 11 | 423 | 9 | 450 | 11 | 423 | 9 | 567 | 17 | false | false | false | false | false | true |
23055_3 | package Algorithm.leetcode.String;
/**
*
* Created by tujietg on Nov 6, 2019
*/
public class No541 {
public String reverseStr(String s, int k) {
// 隔着K然后反转K
int len = s.length();
char[] c = s.toCharArray();
for (int i = 0; i < len; i += 2 * k) {
if (i + k <= len) {
reverse(c, i, i + k - 1);
} else {
reverse(c, i, len - 1);
}
}
// 字符数组转化为字符串 直接new String (c)
return new String(c);
}
// 反转方法的实现
public void reverse(char[] c, int start, int end) {
// 从start到end结束 之中进行反转
while (start < end) {
char temp = c[start];
c[start] = c[end];
c[end] = temp;
start++;
end--;
}
}
}
| Programming-With-Love/leetcode | String/No541.java | 279 | // 反转方法的实现 | line_comment | zh-cn | package Algorithm.leetcode.String;
/**
*
* Created by tujietg on Nov 6, 2019
*/
public class No541 {
public String reverseStr(String s, int k) {
// 隔着K然后反转K
int len = s.length();
char[] c = s.toCharArray();
for (int i = 0; i < len; i += 2 * k) {
if (i + k <= len) {
reverse(c, i, i + k - 1);
} else {
reverse(c, i, len - 1);
}
}
// 字符数组转化为字符串 直接new String (c)
return new String(c);
}
// 反转 <SUF>
public void reverse(char[] c, int start, int end) {
// 从start到end结束 之中进行反转
while (start < end) {
char temp = c[start];
c[start] = c[end];
c[end] = temp;
start++;
end--;
}
}
}
| false | 244 | 7 | 279 | 7 | 272 | 6 | 279 | 7 | 336 | 9 | false | false | false | false | false | true |
66336_5 | package moe.protector.pe.game;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import moe.protector.pe.bean.challenge.DealtoBean;
import moe.protector.pe.bean.challenge.GetChallengeListBean;
import moe.protector.pe.bean.challenge.GetResultBean;
import moe.protector.pe.bean.challenge.SpyBean;
import moe.protector.pe.bean.common.FleetVo;
import moe.protector.pe.bean.friend.FriendGetlistBean;
import moe.protector.pe.bean.friend.FriendVisitorFriendBean;
import moe.protector.pe.bean.task.TaskBean;
import moe.protector.pe.exception.HmException;
import moe.protector.pe.util.CommonUtil;
public class GamePvp extends GameBattle {
private static final String TAG = "GamePvp";
private int format;
private int fleet;
private boolean doNightWar;
public GamePvp(TaskBean taskBean) {
this.format = taskBean.pvpData.format;
this.fleet = taskBean.pvpData.fleet;
this.doNightWar = taskBean.pvpData.night;
}
public enum Finish {
FINISH, ERROR
}
public Finish execute() {
try {
List<PvpUser> pvpList = new ArrayList<>();
// 获取演习列表
GetChallengeListBean getPvpList = this.getChallengeList();
for (GetChallengeListBean.UserList user : getPvpList.list) {
if (user.resultLevel == 0) {
pvpList.add(new PvpUser(user.uid, "pvp", user.username, user.fleetName));
}
}
// 获取好友列表
List<PvpUser> friendList = new ArrayList<>();
String friendData = netSender.friendGetlist();
FriendGetlistBean friendGetlistBean = JSON.parseObject(friendData, FriendGetlistBean.class);
for (FriendGetlistBean.Friend friend : friendGetlistBean.list) {
String data = netSender.friendVisitorFriend(friend.uid);
FriendVisitorFriendBean visitorFriend = JSON.parseObject(data, FriendVisitorFriendBean.class);
if (3 - visitorFriend.challengeNum - friendList.size() <= 0) {
break;
}
if (visitorFriend.challengeScore == 0 && visitorFriend.friendFleet.size() > 0) {
friendList.add(new PvpUser(friend.uid, "friend", friend.username, "驻防编队"));
}
}
pvpList.addAll(friendList);
while (pvpList.size() > 0) {
PvpUser user = pvpList.get(0);
UserData userData = UserData.getInstance();
FleetVo fleetVo = userData.getFleet().get(String.valueOf(this.fleet));
// 开始演习逻辑
head = user.type;
// 演习索敌
SpyBean spyBean = this.pvpSpy(head, user.uid, this.fleet); // 获取索敌数据
UIUpdate.detailLog(TAG, "[演习] " + (user.type.equals("pvp") ? "对手" : "好友") + ": " + user.username + "-" + user.fleetName);
CommonUtil.delay(2000);
// 开始战斗
DealtoBean dealtoBean = this.pvpChallenge(head, user.uid, this.fleet, this.format);
int randomInt = CommonUtil.randomInt(10, 20);
UIUpdate.detailLog(TAG, "[演习] 开始战斗, 等待" + randomInt + "s");
CommonUtil.delay(randomInt * 1000);
// 准备夜战
GetResultBean resultBean = this.challengeGetWarResult(head, dealtoBean.warReport.canDoNightWar == 1 && this.doNightWar);
if (dealtoBean.warReport.canDoNightWar == 1) {
randomInt = CommonUtil.randomInt(10, 15);
UIUpdate.detailLog(TAG, "[演习] 夜战中, 等待" + randomInt + "s");
CommonUtil.delay(randomInt * 1000);
}
// 战斗结束
String[] assess = {"-", "SS", "S", "A", "B", "C", "D"};
String resultLevel = assess[resultBean.warResult.resultLevel];
// 获取mvp
String mvp = "-";
for (int i = 0; i < fleetVo.ships.size(); i++) {
GetResultBean.ShipResult result = resultBean.warResult.selfShipResults.get(i);
if (result.isMvp == 1) {
mvp = userData.getShipName(fleetVo.ships.get(i));
}
}
// 更新任务
if (resultBean.updateTaskVo != null) {
userData.updateTaskVo(resultBean.updateTaskVo);
}
UIUpdate.log(TAG, String.format("[演习] %s 评价:%s mvp:<%s>", user.username, resultLevel, mvp));
CommonUtil.delay(5000);
pvpList.remove(0);
}
return Finish.FINISH;
} catch (HmException e) {
Log.e(TAG, "演习出错:" + e.getCode() + e.getMessage());
}
return Finish.ERROR;
}
}
class PvpUser {
String uid;
String type;
String username;
String fleetName;
PvpUser(String uid, String type, String username, String fleetName) {
this.uid = uid;
this.type = type;
this.username = username;
this.fleetName = fleetName;
}
} | ProtectorMoe/pe-protector-moe | app/src/main/java/moe/protector/pe/game/GamePvp.java | 1,413 | // 开始战斗 | line_comment | zh-cn | package moe.protector.pe.game;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import moe.protector.pe.bean.challenge.DealtoBean;
import moe.protector.pe.bean.challenge.GetChallengeListBean;
import moe.protector.pe.bean.challenge.GetResultBean;
import moe.protector.pe.bean.challenge.SpyBean;
import moe.protector.pe.bean.common.FleetVo;
import moe.protector.pe.bean.friend.FriendGetlistBean;
import moe.protector.pe.bean.friend.FriendVisitorFriendBean;
import moe.protector.pe.bean.task.TaskBean;
import moe.protector.pe.exception.HmException;
import moe.protector.pe.util.CommonUtil;
public class GamePvp extends GameBattle {
private static final String TAG = "GamePvp";
private int format;
private int fleet;
private boolean doNightWar;
public GamePvp(TaskBean taskBean) {
this.format = taskBean.pvpData.format;
this.fleet = taskBean.pvpData.fleet;
this.doNightWar = taskBean.pvpData.night;
}
public enum Finish {
FINISH, ERROR
}
public Finish execute() {
try {
List<PvpUser> pvpList = new ArrayList<>();
// 获取演习列表
GetChallengeListBean getPvpList = this.getChallengeList();
for (GetChallengeListBean.UserList user : getPvpList.list) {
if (user.resultLevel == 0) {
pvpList.add(new PvpUser(user.uid, "pvp", user.username, user.fleetName));
}
}
// 获取好友列表
List<PvpUser> friendList = new ArrayList<>();
String friendData = netSender.friendGetlist();
FriendGetlistBean friendGetlistBean = JSON.parseObject(friendData, FriendGetlistBean.class);
for (FriendGetlistBean.Friend friend : friendGetlistBean.list) {
String data = netSender.friendVisitorFriend(friend.uid);
FriendVisitorFriendBean visitorFriend = JSON.parseObject(data, FriendVisitorFriendBean.class);
if (3 - visitorFriend.challengeNum - friendList.size() <= 0) {
break;
}
if (visitorFriend.challengeScore == 0 && visitorFriend.friendFleet.size() > 0) {
friendList.add(new PvpUser(friend.uid, "friend", friend.username, "驻防编队"));
}
}
pvpList.addAll(friendList);
while (pvpList.size() > 0) {
PvpUser user = pvpList.get(0);
UserData userData = UserData.getInstance();
FleetVo fleetVo = userData.getFleet().get(String.valueOf(this.fleet));
// 开始演习逻辑
head = user.type;
// 演习索敌
SpyBean spyBean = this.pvpSpy(head, user.uid, this.fleet); // 获取索敌数据
UIUpdate.detailLog(TAG, "[演习] " + (user.type.equals("pvp") ? "对手" : "好友") + ": " + user.username + "-" + user.fleetName);
CommonUtil.delay(2000);
// 开始 <SUF>
DealtoBean dealtoBean = this.pvpChallenge(head, user.uid, this.fleet, this.format);
int randomInt = CommonUtil.randomInt(10, 20);
UIUpdate.detailLog(TAG, "[演习] 开始战斗, 等待" + randomInt + "s");
CommonUtil.delay(randomInt * 1000);
// 准备夜战
GetResultBean resultBean = this.challengeGetWarResult(head, dealtoBean.warReport.canDoNightWar == 1 && this.doNightWar);
if (dealtoBean.warReport.canDoNightWar == 1) {
randomInt = CommonUtil.randomInt(10, 15);
UIUpdate.detailLog(TAG, "[演习] 夜战中, 等待" + randomInt + "s");
CommonUtil.delay(randomInt * 1000);
}
// 战斗结束
String[] assess = {"-", "SS", "S", "A", "B", "C", "D"};
String resultLevel = assess[resultBean.warResult.resultLevel];
// 获取mvp
String mvp = "-";
for (int i = 0; i < fleetVo.ships.size(); i++) {
GetResultBean.ShipResult result = resultBean.warResult.selfShipResults.get(i);
if (result.isMvp == 1) {
mvp = userData.getShipName(fleetVo.ships.get(i));
}
}
// 更新任务
if (resultBean.updateTaskVo != null) {
userData.updateTaskVo(resultBean.updateTaskVo);
}
UIUpdate.log(TAG, String.format("[演习] %s 评价:%s mvp:<%s>", user.username, resultLevel, mvp));
CommonUtil.delay(5000);
pvpList.remove(0);
}
return Finish.FINISH;
} catch (HmException e) {
Log.e(TAG, "演习出错:" + e.getCode() + e.getMessage());
}
return Finish.ERROR;
}
}
class PvpUser {
String uid;
String type;
String username;
String fleetName;
PvpUser(String uid, String type, String username, String fleetName) {
this.uid = uid;
this.type = type;
this.username = username;
this.fleetName = fleetName;
}
} | false | 1,222 | 4 | 1,413 | 6 | 1,437 | 3 | 1,413 | 6 | 1,743 | 10 | false | false | false | false | false | true |
47376_8 | package com.buguagaoshu.community.dto;
import lombok.Data;
/**
* @author Pu Zhiwei {@literal [email protected]}
* create 2019-09-15 14:56
*/
@Data
public class UserDto implements Comparable<UserDto> {
private long id = -1;
private String userId;
private String userName;
private String email;
private int age;
private String birthday;
private String sex;
private String school;
private String major;
private String headUrl;
/**
* 一句话介绍
* */
private String simpleSelfIntroduction;
/**
* 自我介绍
* */
private String selfIntroduction;
/**
* 爱好
* */
private String likes;
private int power;
/**
* 问题数
* */
private long questionCount;
/**
* 关注数
* */
private long followCount;
/**
* 粉丝数
* */
private long fansCount;
/**
* 获赞数
* */
private long likeCount;
/**
* 排序权值
* */
private long sortWeight;
@Override
public int compareTo(UserDto o) {
if(this.sortWeight > o.sortWeight) {
return -1;
} else if (this.sortWeight == o.sortWeight){
return 0;
} else {
return 1;
}
}
}
| PuZhiweizuishuai/community | src/main/java/com/buguagaoshu/community/dto/UserDto.java | 350 | /**
* 排序权值
* */ | block_comment | zh-cn | package com.buguagaoshu.community.dto;
import lombok.Data;
/**
* @author Pu Zhiwei {@literal [email protected]}
* create 2019-09-15 14:56
*/
@Data
public class UserDto implements Comparable<UserDto> {
private long id = -1;
private String userId;
private String userName;
private String email;
private int age;
private String birthday;
private String sex;
private String school;
private String major;
private String headUrl;
/**
* 一句话介绍
* */
private String simpleSelfIntroduction;
/**
* 自我介绍
* */
private String selfIntroduction;
/**
* 爱好
* */
private String likes;
private int power;
/**
* 问题数
* */
private long questionCount;
/**
* 关注数
* */
private long followCount;
/**
* 粉丝数
* */
private long fansCount;
/**
* 获赞数
* */
private long likeCount;
/**
* 排序权 <SUF>*/
private long sortWeight;
@Override
public int compareTo(UserDto o) {
if(this.sortWeight > o.sortWeight) {
return -1;
} else if (this.sortWeight == o.sortWeight){
return 0;
} else {
return 1;
}
}
}
| false | 333 | 12 | 350 | 10 | 387 | 12 | 350 | 10 | 455 | 17 | false | false | false | false | false | true |
42092_5 | package ml.puredark.hviewer.configs;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.disk.NoOpDiskTrimmableRegistry;
import com.facebook.common.internal.Supplier;
import com.facebook.common.memory.MemoryTrimType;
import com.facebook.common.memory.MemoryTrimmable;
import com.facebook.common.memory.NoOpMemoryTrimmableRegistry;
import com.facebook.common.util.ByteConstants;
import com.facebook.imagepipeline.cache.MemoryCacheParams;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.io.File;
import java.util.concurrent.TimeUnit;
import ml.puredark.hviewer.HViewerApplication;
import ml.puredark.hviewer.helpers.Logger;
import ml.puredark.hviewer.http.HttpDns;
import ml.puredark.hviewer.http.MyOkHttpNetworkFetcher;
import ml.puredark.hviewer.ui.fragments.SettingFragment;
import ml.puredark.hviewer.utils.SharedPreferencesUtil;
import okhttp3.OkHttpClient;
/**
* Created by PureDark on 2016/9/27.
*/
public class ImagePipelineConfigBuilder {
//分配的可用内存
private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory();
//使用的缓存数量
private static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4;
//小图极低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图)
private static final int MAX_SMALL_DISK_VERYLOW_CACHE_SIZE = 40 * ByteConstants.MB;
//小图低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图)
private static final int MAX_SMALL_DISK_LOW_CACHE_SIZE = 100 * ByteConstants.MB;
//小图所放路径的文件夹名
private static final String IMAGE_PIPELINE_SMALL_CACHE_DIR = "ImagePipelineCacheSmall";
//默认图所放路径的文件夹名
private static final String IMAGE_PIPELINE_CACHE_DIR = "ImagePipelineCacheDefault";
//默认图极低磁盘空间缓存的最大值
private static int MAX_DISK_CACHE_VERYLOW_SIZE = 60 * ByteConstants.MB;
//默认图低磁盘空间缓存的最大值
private static int MAX_DISK_CACHE_LOW_SIZE = 180 * ByteConstants.MB;
//默认图磁盘缓存的最大值
private static int MAX_DISK_CACHE_SIZE = 300 * ByteConstants.MB;
public static ImagePipelineConfig getDefaultImagePipelineConfig(Context context) {
final int cacheSize = (int) SharedPreferencesUtil.getData(HViewerApplication.mContext,
SettingFragment.KEY_PREF_CACHE_SIZE, 300);
MAX_DISK_CACHE_VERYLOW_SIZE = cacheSize / 5 * ByteConstants.MB;
MAX_DISK_CACHE_LOW_SIZE = cacheSize * 3 / 5 * ByteConstants.MB;
MAX_DISK_CACHE_SIZE = cacheSize * ByteConstants.MB;
//内存配置
final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams(
MAX_MEMORY_CACHE_SIZE, // 内存缓存中总图片的最大大小,以字节为单位。
Integer.MAX_VALUE, // 内存缓存中图片的最大数量。
MAX_MEMORY_CACHE_SIZE, // 内存缓存中准备清除但尚未被删除的总图片的最大大小,以字节为单位。
Integer.MAX_VALUE, // 内存缓存中准备清除的总图片的最大数量。
Integer.MAX_VALUE); // 内存缓存中单个图片的最大大小。
//修改内存图片缓存数量,空间策略(这个方式有点恶心)
Supplier<MemoryCacheParams> mSupplierMemoryCacheParams = new Supplier<MemoryCacheParams>() {
@Override
public MemoryCacheParams get() {
return bitmapCacheParams;
}
};
//小图片的磁盘配置
DiskCacheConfig diskSmallCacheConfig = DiskCacheConfig.newBuilder(context)
.setBaseDirectoryPath(getDiskCacheDir(context)) //缓存图片基路径
.setBaseDirectoryName(IMAGE_PIPELINE_SMALL_CACHE_DIR) //文件夹名
.setMaxCacheSize(MAX_DISK_CACHE_SIZE) //默认缓存的最大大小。
.setMaxCacheSizeOnLowDiskSpace(MAX_SMALL_DISK_LOW_CACHE_SIZE) //缓存的最大大小,使用设备时低磁盘空间。
.setMaxCacheSizeOnVeryLowDiskSpace(MAX_SMALL_DISK_VERYLOW_CACHE_SIZE) //缓存的最大大小,当设备极低磁盘空间
.setDiskTrimmableRegistry(NoOpDiskTrimmableRegistry.getInstance())
.build();
//默认图片的磁盘配置
DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context)
.setBaseDirectoryPath(getDiskCacheDir(context))//缓存图片基路径
.setBaseDirectoryName(IMAGE_PIPELINE_CACHE_DIR) //文件夹名
.setMaxCacheSize(MAX_DISK_CACHE_SIZE) //默认缓存的最大大小。
.setMaxCacheSizeOnLowDiskSpace(MAX_DISK_CACHE_LOW_SIZE) //缓存的最大大小,使用设备时低磁盘空间。
.setMaxCacheSizeOnVeryLowDiskSpace(MAX_DISK_CACHE_VERYLOW_SIZE) //缓存的最大大小,当设备极低磁盘空间
.setDiskTrimmableRegistry(NoOpDiskTrimmableRegistry.getInstance())
.build();
// 自定义使用okhttp进行请求
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.dns(new HttpDns())
.build();
//缓存图片配置
ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig.newBuilder(context)
.setBitmapsConfig(Bitmap.Config.RGB_565)
.setBitmapMemoryCacheParamsSupplier(mSupplierMemoryCacheParams)
.setSmallImageDiskCacheConfig(diskSmallCacheConfig)
.setMainDiskCacheConfig(diskCacheConfig)
.setMemoryTrimmableRegistry(NoOpMemoryTrimmableRegistry.getInstance())
.setResizeAndRotateEnabledForNetwork(true)
.setNetworkFetcher(new MyOkHttpNetworkFetcher(okHttpClient));
// 这段代码用于清理缓存
NoOpMemoryTrimmableRegistry.getInstance().registerMemoryTrimmable(new MemoryTrimmable() {
@Override
public void trim(MemoryTrimType trimType) {
final double suggestedTrimRatio = trimType.getSuggestedTrimRatio();
Logger.d("ImagePipeline", String.format("onCreate suggestedTrimRatio : %d", suggestedTrimRatio));
if (MemoryTrimType.OnCloseToDalvikHeapLimit.getSuggestedTrimRatio() == suggestedTrimRatio
|| MemoryTrimType.OnSystemLowMemoryWhileAppInBackground.getSuggestedTrimRatio() == suggestedTrimRatio
|| MemoryTrimType.OnSystemLowMemoryWhileAppInForeground.getSuggestedTrimRatio() == suggestedTrimRatio
) {
ImagePipelineFactory.getInstance().getImagePipeline().clearMemoryCaches();
}
}
});
return configBuilder.build();
}
public static File getDiskCacheDir(Context context) {
File cacheDir;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
cacheDir = context.getExternalCacheDir();
} else {
cacheDir = context.getCacheDir();
}
return cacheDir;
}
}
| PureDark/H-Viewer | app/src/main/java/ml/puredark/hviewer/configs/ImagePipelineConfigBuilder.java | 1,908 | //小图所放路径的文件夹名 | line_comment | zh-cn | package ml.puredark.hviewer.configs;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.disk.NoOpDiskTrimmableRegistry;
import com.facebook.common.internal.Supplier;
import com.facebook.common.memory.MemoryTrimType;
import com.facebook.common.memory.MemoryTrimmable;
import com.facebook.common.memory.NoOpMemoryTrimmableRegistry;
import com.facebook.common.util.ByteConstants;
import com.facebook.imagepipeline.cache.MemoryCacheParams;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.io.File;
import java.util.concurrent.TimeUnit;
import ml.puredark.hviewer.HViewerApplication;
import ml.puredark.hviewer.helpers.Logger;
import ml.puredark.hviewer.http.HttpDns;
import ml.puredark.hviewer.http.MyOkHttpNetworkFetcher;
import ml.puredark.hviewer.ui.fragments.SettingFragment;
import ml.puredark.hviewer.utils.SharedPreferencesUtil;
import okhttp3.OkHttpClient;
/**
* Created by PureDark on 2016/9/27.
*/
public class ImagePipelineConfigBuilder {
//分配的可用内存
private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory();
//使用的缓存数量
private static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4;
//小图极低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图)
private static final int MAX_SMALL_DISK_VERYLOW_CACHE_SIZE = 40 * ByteConstants.MB;
//小图低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图)
private static final int MAX_SMALL_DISK_LOW_CACHE_SIZE = 100 * ByteConstants.MB;
//小图 <SUF>
private static final String IMAGE_PIPELINE_SMALL_CACHE_DIR = "ImagePipelineCacheSmall";
//默认图所放路径的文件夹名
private static final String IMAGE_PIPELINE_CACHE_DIR = "ImagePipelineCacheDefault";
//默认图极低磁盘空间缓存的最大值
private static int MAX_DISK_CACHE_VERYLOW_SIZE = 60 * ByteConstants.MB;
//默认图低磁盘空间缓存的最大值
private static int MAX_DISK_CACHE_LOW_SIZE = 180 * ByteConstants.MB;
//默认图磁盘缓存的最大值
private static int MAX_DISK_CACHE_SIZE = 300 * ByteConstants.MB;
public static ImagePipelineConfig getDefaultImagePipelineConfig(Context context) {
final int cacheSize = (int) SharedPreferencesUtil.getData(HViewerApplication.mContext,
SettingFragment.KEY_PREF_CACHE_SIZE, 300);
MAX_DISK_CACHE_VERYLOW_SIZE = cacheSize / 5 * ByteConstants.MB;
MAX_DISK_CACHE_LOW_SIZE = cacheSize * 3 / 5 * ByteConstants.MB;
MAX_DISK_CACHE_SIZE = cacheSize * ByteConstants.MB;
//内存配置
final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams(
MAX_MEMORY_CACHE_SIZE, // 内存缓存中总图片的最大大小,以字节为单位。
Integer.MAX_VALUE, // 内存缓存中图片的最大数量。
MAX_MEMORY_CACHE_SIZE, // 内存缓存中准备清除但尚未被删除的总图片的最大大小,以字节为单位。
Integer.MAX_VALUE, // 内存缓存中准备清除的总图片的最大数量。
Integer.MAX_VALUE); // 内存缓存中单个图片的最大大小。
//修改内存图片缓存数量,空间策略(这个方式有点恶心)
Supplier<MemoryCacheParams> mSupplierMemoryCacheParams = new Supplier<MemoryCacheParams>() {
@Override
public MemoryCacheParams get() {
return bitmapCacheParams;
}
};
//小图片的磁盘配置
DiskCacheConfig diskSmallCacheConfig = DiskCacheConfig.newBuilder(context)
.setBaseDirectoryPath(getDiskCacheDir(context)) //缓存图片基路径
.setBaseDirectoryName(IMAGE_PIPELINE_SMALL_CACHE_DIR) //文件夹名
.setMaxCacheSize(MAX_DISK_CACHE_SIZE) //默认缓存的最大大小。
.setMaxCacheSizeOnLowDiskSpace(MAX_SMALL_DISK_LOW_CACHE_SIZE) //缓存的最大大小,使用设备时低磁盘空间。
.setMaxCacheSizeOnVeryLowDiskSpace(MAX_SMALL_DISK_VERYLOW_CACHE_SIZE) //缓存的最大大小,当设备极低磁盘空间
.setDiskTrimmableRegistry(NoOpDiskTrimmableRegistry.getInstance())
.build();
//默认图片的磁盘配置
DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context)
.setBaseDirectoryPath(getDiskCacheDir(context))//缓存图片基路径
.setBaseDirectoryName(IMAGE_PIPELINE_CACHE_DIR) //文件夹名
.setMaxCacheSize(MAX_DISK_CACHE_SIZE) //默认缓存的最大大小。
.setMaxCacheSizeOnLowDiskSpace(MAX_DISK_CACHE_LOW_SIZE) //缓存的最大大小,使用设备时低磁盘空间。
.setMaxCacheSizeOnVeryLowDiskSpace(MAX_DISK_CACHE_VERYLOW_SIZE) //缓存的最大大小,当设备极低磁盘空间
.setDiskTrimmableRegistry(NoOpDiskTrimmableRegistry.getInstance())
.build();
// 自定义使用okhttp进行请求
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.dns(new HttpDns())
.build();
//缓存图片配置
ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig.newBuilder(context)
.setBitmapsConfig(Bitmap.Config.RGB_565)
.setBitmapMemoryCacheParamsSupplier(mSupplierMemoryCacheParams)
.setSmallImageDiskCacheConfig(diskSmallCacheConfig)
.setMainDiskCacheConfig(diskCacheConfig)
.setMemoryTrimmableRegistry(NoOpMemoryTrimmableRegistry.getInstance())
.setResizeAndRotateEnabledForNetwork(true)
.setNetworkFetcher(new MyOkHttpNetworkFetcher(okHttpClient));
// 这段代码用于清理缓存
NoOpMemoryTrimmableRegistry.getInstance().registerMemoryTrimmable(new MemoryTrimmable() {
@Override
public void trim(MemoryTrimType trimType) {
final double suggestedTrimRatio = trimType.getSuggestedTrimRatio();
Logger.d("ImagePipeline", String.format("onCreate suggestedTrimRatio : %d", suggestedTrimRatio));
if (MemoryTrimType.OnCloseToDalvikHeapLimit.getSuggestedTrimRatio() == suggestedTrimRatio
|| MemoryTrimType.OnSystemLowMemoryWhileAppInBackground.getSuggestedTrimRatio() == suggestedTrimRatio
|| MemoryTrimType.OnSystemLowMemoryWhileAppInForeground.getSuggestedTrimRatio() == suggestedTrimRatio
) {
ImagePipelineFactory.getInstance().getImagePipeline().clearMemoryCaches();
}
}
});
return configBuilder.build();
}
public static File getDiskCacheDir(Context context) {
File cacheDir;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
cacheDir = context.getExternalCacheDir();
} else {
cacheDir = context.getCacheDir();
}
return cacheDir;
}
}
| false | 1,644 | 10 | 1,908 | 9 | 1,912 | 9 | 1,908 | 9 | 2,600 | 16 | false | false | false | false | false | true |
23090_10 | package Sort;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
/**
* Created with IntelliJ IDEA.
*
* @Author PurpleSword
* @Date 2020/6/27 0:06
* @Version 1.0
* @Description
*/
public class Insertion {
public Insertion() {
}
//String实现了Comparable接口,所以每一个String对象均可以看作Comparable对象
public static void sort(Comparable[] a) {
int n = a.length;
// 标记,为0表示已排好序
int exchange = 0;
// 放置最小元素为哨兵
// 牺牲最小元素作为哨兵,避免检查时可能出现数组越界的情况
for (int i = n - 1; i > 0; --i) {
if (less(a[i], a[i - 1])) {
exch(a, i, i - 1);
++exchange;
}
}
if (exchange == 0) {
return;
}
//半交换插入排序(需要前移的元素直接放在最后的位置,而不是一个个前移)
for (int i = 2; i < n; ++i) {
// v就是临时变量,将其存储,找到合适的位置直接放下
// v前方均有序,将大于v的元素后移
Comparable v = a[i];
int j = i;
while (less(v, a[j - 1])) {
// 这里j不会一直减下去是因为前面有设置哨兵
a[j] = a[j - 1];
--j;
}
a[j] = v;
}
assert isSorted(a);
}
/**
* v<w时返回True
*
* @param v 元素v
* @param w 元素w
* @return
*/
private static boolean less(Comparable v, Comparable w) {
// v<w 返回小于0的值
return v.compareTo(w) < 0;
}
private static void exch(Object[] a, int i, int j) {
//交换两个元素顺序
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
private static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; ++i) {
if (less(a[i], a[i - 1])) {
return false;
}
}
return true;
}
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; ++i) {
StdOut.println(a[i]);
}
}
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Insertion.sort(a);
show(a);
}
}
| PurpleSwords/algorithms | src/Sort/Insertion.java | 770 | // v<w 返回小于0的值 | line_comment | zh-cn | package Sort;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
/**
* Created with IntelliJ IDEA.
*
* @Author PurpleSword
* @Date 2020/6/27 0:06
* @Version 1.0
* @Description
*/
public class Insertion {
public Insertion() {
}
//String实现了Comparable接口,所以每一个String对象均可以看作Comparable对象
public static void sort(Comparable[] a) {
int n = a.length;
// 标记,为0表示已排好序
int exchange = 0;
// 放置最小元素为哨兵
// 牺牲最小元素作为哨兵,避免检查时可能出现数组越界的情况
for (int i = n - 1; i > 0; --i) {
if (less(a[i], a[i - 1])) {
exch(a, i, i - 1);
++exchange;
}
}
if (exchange == 0) {
return;
}
//半交换插入排序(需要前移的元素直接放在最后的位置,而不是一个个前移)
for (int i = 2; i < n; ++i) {
// v就是临时变量,将其存储,找到合适的位置直接放下
// v前方均有序,将大于v的元素后移
Comparable v = a[i];
int j = i;
while (less(v, a[j - 1])) {
// 这里j不会一直减下去是因为前面有设置哨兵
a[j] = a[j - 1];
--j;
}
a[j] = v;
}
assert isSorted(a);
}
/**
* v<w时返回True
*
* @param v 元素v
* @param w 元素w
* @return
*/
private static boolean less(Comparable v, Comparable w) {
// v< <SUF>
return v.compareTo(w) < 0;
}
private static void exch(Object[] a, int i, int j) {
//交换两个元素顺序
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
private static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; ++i) {
if (less(a[i], a[i - 1])) {
return false;
}
}
return true;
}
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; ++i) {
StdOut.println(a[i]);
}
}
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Insertion.sort(a);
show(a);
}
}
| false | 657 | 8 | 770 | 9 | 735 | 8 | 770 | 9 | 970 | 12 | false | false | false | false | false | true |
59706_2 | package org.hzz.msgpack.client;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import org.hzz.msgpack.domain.User;
import org.hzz.msgpack.domain.UserContact;
import java.util.concurrent.atomic.AtomicInteger;
public class ClientBusiHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final int sendNumber;
private AtomicInteger counter = new AtomicInteger(0);
public ClientBusiHandler(int sendNumber){this.sendNumber = sendNumber;}
/*** 客户端被通知channel活跃后,做事*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
User[] users = makeUsers();
//发送数据
for(User user:users){
System.out.println("Send user:"+user);
ctx.write(user);
}
ctx.flush();
}
/*** 发生异常后的处理*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
/*生成用户实体类的数组,以供发送*/
private User[] makeUsers(){
User[] users=new User[sendNumber];
User user =null;
for(int i=0;i<sendNumber;i++){
user=new User();
user.setAge(i);
String userName = "ABCDEFG --->"+i;
user.setUserName(userName);
user.setId("No:"+(sendNumber-i));
user.setUserContact(
new UserContact(userName+"@xiangxue.com","133"));
users[i]=user;
}
return users;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("client Accept["+msg.toString(CharsetUtil.UTF_8)
+"] and the counter is:"+counter.incrementAndGet());
}
}
| Q10Viking/learncode | Netty/HelloWorld/src/main/java/org/hzz/msgpack/client/ClientBusiHandler.java | 487 | /*** 发生异常后的处理*/ | block_comment | zh-cn | package org.hzz.msgpack.client;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import org.hzz.msgpack.domain.User;
import org.hzz.msgpack.domain.UserContact;
import java.util.concurrent.atomic.AtomicInteger;
public class ClientBusiHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final int sendNumber;
private AtomicInteger counter = new AtomicInteger(0);
public ClientBusiHandler(int sendNumber){this.sendNumber = sendNumber;}
/*** 客户端被通知channel活跃后,做事*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
User[] users = makeUsers();
//发送数据
for(User user:users){
System.out.println("Send user:"+user);
ctx.write(user);
}
ctx.flush();
}
/*** 发生异 <SUF>*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
/*生成用户实体类的数组,以供发送*/
private User[] makeUsers(){
User[] users=new User[sendNumber];
User user =null;
for(int i=0;i<sendNumber;i++){
user=new User();
user.setAge(i);
String userName = "ABCDEFG --->"+i;
user.setUserName(userName);
user.setId("No:"+(sendNumber-i));
user.setUserContact(
new UserContact(userName+"@xiangxue.com","133"));
users[i]=user;
}
return users;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("client Accept["+msg.toString(CharsetUtil.UTF_8)
+"] and the counter is:"+counter.incrementAndGet());
}
}
| false | 416 | 7 | 487 | 7 | 514 | 7 | 487 | 7 | 592 | 14 | false | false | false | false | false | true |
22527_15 | package com.github.tusharepro.core.bean;
import com.github.tusharepro.core.http.BaseRequestParam;
/**
* 上市公司基本信息
* https://tushare.pro/document/2?doc_id=112
*/
public interface StockCompany extends BaseBean {
String API_NAME = "stock_company";
interface Fields {
String ts_code = "ts_code"; // 股票代码
String exchange = "exchange"; // 交易所代码 ,SSE上交所 SZSE深交所
String chairman = "chairman"; // 法人代表
String manager = "manager"; // 总经理
String secretary = "secretary"; // 董秘
String reg_capital = "reg_capital"; // 注册资本
String setup_date = "setup_date"; // 注册日期
String province = "province"; // 所在省份
String city = "city"; // 所在城市
String introduction = "introduction"; // 公司介绍
String website = "website"; // 公司主页
String email = "email"; // 电子邮件
String office = "office"; // 办公室
String employees = "employees"; // 员工人数
String main_business = "main_business"; // 主要业务及产品
String business_scope = "business_scope"; // 经营范围
}
interface Params {
exchange exchange = new exchange(); // 交易所代码 ,SSE上交所 SZSE深交所 ,默认SSE
class exchange extends BaseRequestParam {
{key = "exchange";}
}
}
} | QHh6eQ/tushare-pro-java-sdk | src/main/java/com/github/tusharepro/core/bean/StockCompany.java | 390 | // 经营范围 | line_comment | zh-cn | package com.github.tusharepro.core.bean;
import com.github.tusharepro.core.http.BaseRequestParam;
/**
* 上市公司基本信息
* https://tushare.pro/document/2?doc_id=112
*/
public interface StockCompany extends BaseBean {
String API_NAME = "stock_company";
interface Fields {
String ts_code = "ts_code"; // 股票代码
String exchange = "exchange"; // 交易所代码 ,SSE上交所 SZSE深交所
String chairman = "chairman"; // 法人代表
String manager = "manager"; // 总经理
String secretary = "secretary"; // 董秘
String reg_capital = "reg_capital"; // 注册资本
String setup_date = "setup_date"; // 注册日期
String province = "province"; // 所在省份
String city = "city"; // 所在城市
String introduction = "introduction"; // 公司介绍
String website = "website"; // 公司主页
String email = "email"; // 电子邮件
String office = "office"; // 办公室
String employees = "employees"; // 员工人数
String main_business = "main_business"; // 主要业务及产品
String business_scope = "business_scope"; // 经营 <SUF>
}
interface Params {
exchange exchange = new exchange(); // 交易所代码 ,SSE上交所 SZSE深交所 ,默认SSE
class exchange extends BaseRequestParam {
{key = "exchange";}
}
}
} | false | 365 | 5 | 390 | 5 | 380 | 4 | 390 | 5 | 496 | 12 | false | false | false | false | false | true |
54912_2 | import java.util.*;
public class Solution {
public ArrayList<Integer> function(String s, int index){
Stack<Integer> stack = new Stack<Integer>();
int num = 0;
char op = '+';
int i;
for(i = index; i < s.length(); i++){
//数字转换成int数字
//判断是否为数字
if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){
num = num * 10 + s.charAt(i) - '0';
if(i != s.length() - 1)
continue;
}
//碰到'('时,把整个括号内的当成一个数字处理
if(s.charAt(i) == '('){
//递归处理括号
ArrayList<Integer> res = function(s, i + 1);
num = res.get(0);
i = res.get(1);
if(i != s.length() - 1)
continue;
}
switch(op){
//加减号先入栈
case '+':
stack.push(num);
break;
case '-':
//相反数
stack.push(-num);
break;
//优先计算乘号
case '*':
int temp = stack.pop();
stack.push(temp * num);
break;
}
num = 0;
//右括号结束递归
if(s.charAt(i) == ')')
break;
else
op = s.charAt(i);
}
int sum = 0;
//栈中元素相加
while(!stack.isEmpty())
sum += stack.pop();
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(sum);
temp.add(i);
return temp;
}
public int solve (String s) {
ArrayList<Integer> res = function(s, 0);
return res.get(0);
}
}
| QLPTw/QLPTw | 11月/表达式求值.java | 455 | //碰到'('时,把整个括号内的当成一个数字处理
| line_comment | zh-cn | import java.util.*;
public class Solution {
public ArrayList<Integer> function(String s, int index){
Stack<Integer> stack = new Stack<Integer>();
int num = 0;
char op = '+';
int i;
for(i = index; i < s.length(); i++){
//数字转换成int数字
//判断是否为数字
if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){
num = num * 10 + s.charAt(i) - '0';
if(i != s.length() - 1)
continue;
}
//碰到 <SUF>
if(s.charAt(i) == '('){
//递归处理括号
ArrayList<Integer> res = function(s, i + 1);
num = res.get(0);
i = res.get(1);
if(i != s.length() - 1)
continue;
}
switch(op){
//加减号先入栈
case '+':
stack.push(num);
break;
case '-':
//相反数
stack.push(-num);
break;
//优先计算乘号
case '*':
int temp = stack.pop();
stack.push(temp * num);
break;
}
num = 0;
//右括号结束递归
if(s.charAt(i) == ')')
break;
else
op = s.charAt(i);
}
int sum = 0;
//栈中元素相加
while(!stack.isEmpty())
sum += stack.pop();
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(sum);
temp.add(i);
return temp;
}
public int solve (String s) {
ArrayList<Integer> res = function(s, 0);
return res.get(0);
}
}
| false | 412 | 16 | 450 | 20 | 505 | 16 | 450 | 20 | 575 | 31 | false | false | false | false | false | true |
15_13 | package dshomewrok;
import java.util.*;
/*ZigZagging on a Tree
*/
public class Zigzagtree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private static int find(int[] array, int v) {
for (int i = 0; i < array.length; i++) {
if (array[i] == v) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int n = 0;
int i = 0,j = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int[] arr1,arr2;
arr1 = new int[n]; // inorder
arr2 = new int[n]; // postorder
for(i = 0;i < arr1.length;i++) {
arr1[i] = sc.nextInt();
}
for(i = 0;i < arr2.length;i++) {
arr2[i] = sc.nextInt();
}
sc.close();
TreeNode root1 = BuildTree(arr1,arr2);
}
/*build a Tree from postorder and inorder
后序遍历的最后一个数为根结点,根据这个根结点来划分中序遍历,将其分为左子树和右子树
②确定左右子树的中序遍历和后遍历中的界限,中序从0 - root为左, root+1 到最后为右. 后序0-root为左,root到postOrder.length-1 为右.
③递归调用
*/
public static TreeNode BuildTree(int[] inOrder, int[] postOrder ) {
if(postOrder.length == 0) {
return null;
}
if(postOrder.length == 1) {
TreeNode tmp = new TreeNode(postOrder[postOrder.length-1]);
return tmp;
}
TreeNode root = new TreeNode(postOrder[postOrder.length-1]); //先判断特殊,再new 一个.
int rootpos = find(inOrder,root.val);
int[] leftInorder = Arrays.copyOfRange(inOrder, 0, rootpos); //copyOfRange 包括0 不包括rootpos.
int[] rightInorder = Arrays.copyOfRange(inOrder, rootpos+1, inOrder.length);
//System.out.println(rootpos);
//System.out.println(Arrays.toString(rightInorder));
//System.out.println(Arrays.toString(leftInorder)); //不能直接打印数组要tostring
int[] leftPostorder = Arrays.copyOfRange(postOrder, 0, rootpos);
int[] rightPostorder = Arrays.copyOfRange(postOrder, rootpos, postOrder.length-1);;
//System.out.println(Arrays.toString(leftPostorder));
//System.out.println(Arrays.toString(rightPostorder));
root.left = BuildTree(leftInorder,leftPostorder);
root.right = BuildTree(rightInorder,rightPostorder);
return root;
}
/*要进行层次遍历,需要建立一个循环队列。先将二叉树头结点入队列,然后出队列,访问该结点,如果它有左子树
则将左子树的根结点入队:如果它有右子树,则将右子树的根结点入队。然后出队列,对出队结点访问,如此反复,直到队列为空为止。
z字形层次遍历是对层次遍历加上了一个限制条件(即相邻层,从左到右的遍历顺序相反),
我们取queue大小,就是上一层的结点数. for循环把这一层都加入进去,如果奇数层就第一个结点开始(因为上一层是偶数)先加右再加左.
如果偶数层就最后结点开始(因为上一层是奇数)先加左再加右.
一层结束深度增加,同时用一个栈,因为遍历下一层的数据 和输出这一层的数据 是刚好相反的..
data arraylist是因为他最后不要空格, 所以全部保存了再输出. 不然stack其实就有正确答案了,最后多一个空格.
*/
public static void zigzagorder(JudgeRedBlackTree.TreeNode root ) {
ArrayDeque<JudgeRedBlackTree.TreeNode> queue = new ArrayDeque<JudgeRedBlackTree.TreeNode>(32);
ArrayList<Integer> data = new ArrayList<Integer>(32); //no int but Integer
JudgeRedBlackTree.TreeNode temp = root;
Stack<JudgeRedBlackTree.TreeNode> res = new Stack<JudgeRedBlackTree.TreeNode>(); // 就是把他
queue.add(temp);
int depth = 0 ,i = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(i =0;i<size;i++) {
if(depth %2 == 0) {
temp = queue.pollLast();
if(temp.left != null) {
queue.addFirst(temp.left);
}
if(temp.right != null){
queue.addFirst(temp.right);
}
}
else {
temp = queue.poll();
if(temp.right != null){
queue.add(temp.right);
}
if(temp.left != null) {
queue.add(temp.left);
}
}
res.push(temp);
}
while(!res.empty())
data.add(res.pop().val);
depth ++;
}
for(i = 0;i<data.size()-1;i++) {
System.out.print(data.get(i)+" ");
}
System.out.print(data.get(i));
}
}
| QSCTech/zju-icicles | 数据结构基础/作业/dsHomework/tree/Zigzagtree.java | 1,463 | // 就是把他 | line_comment | zh-cn | package dshomewrok;
import java.util.*;
/*ZigZagging on a Tree
*/
public class Zigzagtree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private static int find(int[] array, int v) {
for (int i = 0; i < array.length; i++) {
if (array[i] == v) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int n = 0;
int i = 0,j = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int[] arr1,arr2;
arr1 = new int[n]; // inorder
arr2 = new int[n]; // postorder
for(i = 0;i < arr1.length;i++) {
arr1[i] = sc.nextInt();
}
for(i = 0;i < arr2.length;i++) {
arr2[i] = sc.nextInt();
}
sc.close();
TreeNode root1 = BuildTree(arr1,arr2);
}
/*build a Tree from postorder and inorder
后序遍历的最后一个数为根结点,根据这个根结点来划分中序遍历,将其分为左子树和右子树
②确定左右子树的中序遍历和后遍历中的界限,中序从0 - root为左, root+1 到最后为右. 后序0-root为左,root到postOrder.length-1 为右.
③递归调用
*/
public static TreeNode BuildTree(int[] inOrder, int[] postOrder ) {
if(postOrder.length == 0) {
return null;
}
if(postOrder.length == 1) {
TreeNode tmp = new TreeNode(postOrder[postOrder.length-1]);
return tmp;
}
TreeNode root = new TreeNode(postOrder[postOrder.length-1]); //先判断特殊,再new 一个.
int rootpos = find(inOrder,root.val);
int[] leftInorder = Arrays.copyOfRange(inOrder, 0, rootpos); //copyOfRange 包括0 不包括rootpos.
int[] rightInorder = Arrays.copyOfRange(inOrder, rootpos+1, inOrder.length);
//System.out.println(rootpos);
//System.out.println(Arrays.toString(rightInorder));
//System.out.println(Arrays.toString(leftInorder)); //不能直接打印数组要tostring
int[] leftPostorder = Arrays.copyOfRange(postOrder, 0, rootpos);
int[] rightPostorder = Arrays.copyOfRange(postOrder, rootpos, postOrder.length-1);;
//System.out.println(Arrays.toString(leftPostorder));
//System.out.println(Arrays.toString(rightPostorder));
root.left = BuildTree(leftInorder,leftPostorder);
root.right = BuildTree(rightInorder,rightPostorder);
return root;
}
/*要进行层次遍历,需要建立一个循环队列。先将二叉树头结点入队列,然后出队列,访问该结点,如果它有左子树
则将左子树的根结点入队:如果它有右子树,则将右子树的根结点入队。然后出队列,对出队结点访问,如此反复,直到队列为空为止。
z字形层次遍历是对层次遍历加上了一个限制条件(即相邻层,从左到右的遍历顺序相反),
我们取queue大小,就是上一层的结点数. for循环把这一层都加入进去,如果奇数层就第一个结点开始(因为上一层是偶数)先加右再加左.
如果偶数层就最后结点开始(因为上一层是奇数)先加左再加右.
一层结束深度增加,同时用一个栈,因为遍历下一层的数据 和输出这一层的数据 是刚好相反的..
data arraylist是因为他最后不要空格, 所以全部保存了再输出. 不然stack其实就有正确答案了,最后多一个空格.
*/
public static void zigzagorder(JudgeRedBlackTree.TreeNode root ) {
ArrayDeque<JudgeRedBlackTree.TreeNode> queue = new ArrayDeque<JudgeRedBlackTree.TreeNode>(32);
ArrayList<Integer> data = new ArrayList<Integer>(32); //no int but Integer
JudgeRedBlackTree.TreeNode temp = root;
Stack<JudgeRedBlackTree.TreeNode> res = new Stack<JudgeRedBlackTree.TreeNode>(); // 就是 <SUF>
queue.add(temp);
int depth = 0 ,i = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(i =0;i<size;i++) {
if(depth %2 == 0) {
temp = queue.pollLast();
if(temp.left != null) {
queue.addFirst(temp.left);
}
if(temp.right != null){
queue.addFirst(temp.right);
}
}
else {
temp = queue.poll();
if(temp.right != null){
queue.add(temp.right);
}
if(temp.left != null) {
queue.add(temp.left);
}
}
res.push(temp);
}
while(!res.empty())
data.add(res.pop().val);
depth ++;
}
for(i = 0;i<data.size()-1;i++) {
System.out.print(data.get(i)+" ");
}
System.out.print(data.get(i));
}
}
| false | 1,256 | 5 | 1,463 | 5 | 1,465 | 3 | 1,463 | 5 | 1,964 | 8 | false | false | false | false | false | true |
5010_3 | package pub.developers.forum.app.listener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import pub.developers.forum.app.support.Pair;
import pub.developers.forum.common.support.EventBus;
import pub.developers.forum.domain.entity.Article;
import pub.developers.forum.domain.repository.ArticleTypeRepository;
import pub.developers.forum.domain.repository.TagRepository;
import javax.annotation.Resource;
import java.util.Set;
/**
* @author Qiangqiang.Bian
* @create 2020/11/5
* @desc
**/
@Component
public class ArticleUpdateListener extends EventBus.EventHandler<Pair<Article>> {
@Resource
private ArticleTypeRepository articleTypeRepository;
@Resource
private TagRepository tagRepository;
@Override
public EventBus.Topic topic() {
return EventBus.Topic.ARTICLE_UPDATE;
}
@Override
public void onMessage(Pair<Article> pair) {
Article oldArticle = pair.getValue0();
Article newArticle = pair.getValue1();
// 更新文章类型引用计数
if (!oldArticle.getType().equals(newArticle.getType())) {
articleTypeRepository.decreaseRefCount(oldArticle.getType().getId());
articleTypeRepository.increaseRefCount(newArticle.getType().getId());
}
// 由于ArticleManager里已经减了一遍标签的引用计数,需把原来的加回来
Set<Long> oldTags=Pair.tagToLong(oldArticle.getTags());
tagRepository.increaseRefCount(oldTags);
// 更新标签引用计数
Set<Long> addTags = Pair.diff(newArticle.getTags(), oldArticle.getTags());
Set<Long> removeTags = Pair.diff(oldArticle.getTags(), newArticle.getTags());
if (!ObjectUtils.isEmpty(addTags)) {
tagRepository.increaseRefCount(addTags);
}
if (!ObjectUtils.isEmpty(removeTags)) {
tagRepository.decreaseRefCount(removeTags);
}
}
}
| Qbian61/forum-java | forum-app/src/main/java/pub/developers/forum/app/listener/ArticleUpdateListener.java | 480 | // 更新标签引用计数 | line_comment | zh-cn | package pub.developers.forum.app.listener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import pub.developers.forum.app.support.Pair;
import pub.developers.forum.common.support.EventBus;
import pub.developers.forum.domain.entity.Article;
import pub.developers.forum.domain.repository.ArticleTypeRepository;
import pub.developers.forum.domain.repository.TagRepository;
import javax.annotation.Resource;
import java.util.Set;
/**
* @author Qiangqiang.Bian
* @create 2020/11/5
* @desc
**/
@Component
public class ArticleUpdateListener extends EventBus.EventHandler<Pair<Article>> {
@Resource
private ArticleTypeRepository articleTypeRepository;
@Resource
private TagRepository tagRepository;
@Override
public EventBus.Topic topic() {
return EventBus.Topic.ARTICLE_UPDATE;
}
@Override
public void onMessage(Pair<Article> pair) {
Article oldArticle = pair.getValue0();
Article newArticle = pair.getValue1();
// 更新文章类型引用计数
if (!oldArticle.getType().equals(newArticle.getType())) {
articleTypeRepository.decreaseRefCount(oldArticle.getType().getId());
articleTypeRepository.increaseRefCount(newArticle.getType().getId());
}
// 由于ArticleManager里已经减了一遍标签的引用计数,需把原来的加回来
Set<Long> oldTags=Pair.tagToLong(oldArticle.getTags());
tagRepository.increaseRefCount(oldTags);
// 更新 <SUF>
Set<Long> addTags = Pair.diff(newArticle.getTags(), oldArticle.getTags());
Set<Long> removeTags = Pair.diff(oldArticle.getTags(), newArticle.getTags());
if (!ObjectUtils.isEmpty(addTags)) {
tagRepository.increaseRefCount(addTags);
}
if (!ObjectUtils.isEmpty(removeTags)) {
tagRepository.decreaseRefCount(removeTags);
}
}
}
| false | 405 | 6 | 482 | 6 | 502 | 5 | 480 | 6 | 591 | 12 | false | false | false | false | false | true |
16765_3 | import java.util.TreeMap;
import com.qcloud.QcloudApiModuleCenter;
import com.qcloud.Module.Cvm;
public class CvmV3Demo {
public static void main(String[] args) {
// 从环境变量中读取信息,设置代理,如果没有代理则不需要设置
System.setProperty("https.proxyHost", System.getenv("HTTPS_PROXY_HOST"));
System.setProperty("https.proxyPort", System.getenv("HTTPS_PROXY_PORT"));
TreeMap<String, Object> config = new TreeMap<String, Object>();
// 从环境变量中读取信息,设置密钥对,请不要把密钥对明文写在代码中以防泄漏
// 如果读取环境变量失败,运行代码时将报java.lang.NullPointerException错误
config.put("SecretId", System.getenv("QCLOUD_SECRET_ID"));
config.put("SecretKey", System.getenv("QCLOUD_SECRET_KEY"));
// 请求方法类型 POST、GET
//config.put("RequestMethod", "POST");
// 区域参数,例如 ap-guangzhou
// 参考:https://cloud.tencent.com/document/api/213/9456
config.put("DefaultRegion", "ap-guangzhou");
// 在这里指定所要用的签名算法,不指定默认为 HmacSHA1
config.put("SignatureMethod", "HmacSHA256");
// 示例服务:CVM
// 示例:DescribeInstances
// API 文档地址:https://cloud.tencent.com/document/api/213/9388
QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Cvm(), config);
String action = "DescribeInstances";
TreeMap<String, Object> params = new TreeMap<String, Object>();
// 必须设置 Version = 2017-03-12 才能使用对应版本的 CVM API
params.put("Version", "2017-03-12");
// 将需要输入的参数都放入 params 里面,必选参数是必填的。
// DescribeInstances 接口的部分可选参数如下
params.put("Offset", 0);
params.put("Limit", 1);
// generateUrl 方法生成请求串,可用于调试使用
System.out.println(module.generateUrl(action, params));
String result = null;
try {
// call 方法正式向指定的接口名发送请求,并把请求参数 params 传入,返回即是接口的请求结果。
result = module.call(action, params);
System.out.println(result);
} catch (Exception e) {
System.out.println("error..." + e.getMessage());
}
}
}
| QcloudApi/qcloudapi-sdk-java | src/CvmV3Demo.java | 625 | // 请求方法类型 POST、GET | line_comment | zh-cn | import java.util.TreeMap;
import com.qcloud.QcloudApiModuleCenter;
import com.qcloud.Module.Cvm;
public class CvmV3Demo {
public static void main(String[] args) {
// 从环境变量中读取信息,设置代理,如果没有代理则不需要设置
System.setProperty("https.proxyHost", System.getenv("HTTPS_PROXY_HOST"));
System.setProperty("https.proxyPort", System.getenv("HTTPS_PROXY_PORT"));
TreeMap<String, Object> config = new TreeMap<String, Object>();
// 从环境变量中读取信息,设置密钥对,请不要把密钥对明文写在代码中以防泄漏
// 如果读取环境变量失败,运行代码时将报java.lang.NullPointerException错误
config.put("SecretId", System.getenv("QCLOUD_SECRET_ID"));
config.put("SecretKey", System.getenv("QCLOUD_SECRET_KEY"));
// 请求 <SUF>
//config.put("RequestMethod", "POST");
// 区域参数,例如 ap-guangzhou
// 参考:https://cloud.tencent.com/document/api/213/9456
config.put("DefaultRegion", "ap-guangzhou");
// 在这里指定所要用的签名算法,不指定默认为 HmacSHA1
config.put("SignatureMethod", "HmacSHA256");
// 示例服务:CVM
// 示例:DescribeInstances
// API 文档地址:https://cloud.tencent.com/document/api/213/9388
QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Cvm(), config);
String action = "DescribeInstances";
TreeMap<String, Object> params = new TreeMap<String, Object>();
// 必须设置 Version = 2017-03-12 才能使用对应版本的 CVM API
params.put("Version", "2017-03-12");
// 将需要输入的参数都放入 params 里面,必选参数是必填的。
// DescribeInstances 接口的部分可选参数如下
params.put("Offset", 0);
params.put("Limit", 1);
// generateUrl 方法生成请求串,可用于调试使用
System.out.println(module.generateUrl(action, params));
String result = null;
try {
// call 方法正式向指定的接口名发送请求,并把请求参数 params 传入,返回即是接口的请求结果。
result = module.call(action, params);
System.out.println(result);
} catch (Exception e) {
System.out.println("error..." + e.getMessage());
}
}
}
| false | 571 | 7 | 625 | 7 | 645 | 7 | 625 | 7 | 842 | 11 | false | false | false | false | false | true |
51608_0 | package com.study.Polymorphic_Train;
public class Hero
{
public String name;
protected float hp;
public void kill(Mortal m)
{
System.out.println(name + "放了一个大招");
m.die();
}
//类方法,静态方法
//通过类就可以直接调用
public static void battleWin()
{
System.out.println("hero battle win");
}
public static void main(String[] args)
{
Hero h = new Hero();
h.name = "盖伦";
ADHero ad = new ADHero();
ad.name = "艾希";
APHero ap = new APHero();
ap.name = "安妮";
ADAPHero adap = new ADAPHero();
adap.name = "库奇";
h.kill(ad);
h.kill(ap);
h.kill(adap);
}
}
| QiYi92/StudyLab | JAVA/study_lab/src/com/study/Polymorphic_Train/Hero.java | 216 | //类方法,静态方法 | line_comment | zh-cn | package com.study.Polymorphic_Train;
public class Hero
{
public String name;
protected float hp;
public void kill(Mortal m)
{
System.out.println(name + "放了一个大招");
m.die();
}
//类方 <SUF>
//通过类就可以直接调用
public static void battleWin()
{
System.out.println("hero battle win");
}
public static void main(String[] args)
{
Hero h = new Hero();
h.name = "盖伦";
ADHero ad = new ADHero();
ad.name = "艾希";
APHero ap = new APHero();
ap.name = "安妮";
ADAPHero adap = new ADAPHero();
adap.name = "库奇";
h.kill(ad);
h.kill(ap);
h.kill(adap);
}
}
| false | 190 | 6 | 216 | 6 | 231 | 6 | 216 | 6 | 282 | 11 | false | false | false | false | false | true |
32673_17 | package com.johnny.dialog;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 通知对话框
*
* @param v
*/
public void showNotifyDialog(View v) {
/*初始化dialog构造器*/
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("通知对话框:");/*设置dialog的title*/
builder.setMessage("通知对话框弹出了");/*设置dialog的内容*/
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {/*设置dialog确认按钮的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {/*设置dialog取消按钮的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);/*设置是否可以通过返回键消失, 默认true*/
builder.show();/*显示dialog*/
/* 第二种显示方法
* AlertDialog dialog = builder.create();
* dialog.show();
*/
}
/**
* 显示列表对话框
*
* @param v
*/
public void showListDialog(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请选中您喜欢的数字:");
builder.setIcon(R.mipmap.ic_launcher);/*设置图标*/
final String[] items = new String[]{"8", "6", "2", "1", "3"};/*设置列表的内容*/
builder.setItems(items, new DialogInterface.OnClickListener() {/*设置列表的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();
}
/**
* 显示单选对话框
*
* @param v
*/
public void showSinpleChioceDialog(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("选择性别:");
builder.setIcon(R.mipmap.ic_launcher);
final String[] items = new String[]{"男", "女", "妖"};
builder.setSingleChoiceItems(items, 2, new DialogInterface.OnClickListener() {/*设置单选条件的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();
}
/**
* 显示多选对话框
*
* @param v
*/
public void showMultiChioceDialog(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("于谦:");
builder.setIcon(R.mipmap.ic_launcher);
final String[] items = new String[]{"抽烟", "喝酒", "烫头"};/*设置多选的内容*/
final boolean[] checkedItems = new boolean[]{false, true, false};/*设置多选默认状态*/
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {/*设置多选的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
Toast.makeText(MainActivity.this, items[which] + " 状态: " + isChecked, Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();
}
/**
* 显示进度对话框
*
* @param v
*/
public void showProgressDialog(View v) {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("提醒");/*设置进度对话框的title*/
dialog.setMessage("正在加载中,请稍后...");/*设置进度对话框的内容*/
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);/*设置进度对话框的样式*/
dialog.setMax(100);/*设置进度对话框的最大进度*/
dialog.setCancelable(false);
dialog.show();/*在show时, 别忘了初始化进度*/
dialog.setProgress(23);/*设置进度*/
new Thread() {
public void run() {
while (true) {
if (dialog.getProgress() == 100)
return;
SystemClock.sleep(100);
dialog.incrementProgressBy(1);/*更新进度,每一次以5来递增(dialog.setProgress(dialog.getProgress() + 5))*/
if (dialog.getProgress() >= dialog.getMax()) {
runOnUiThread(new Runnable() {/*在主线程执行*/
@Override
public void run() {
Toast.makeText(MainActivity.this, "加载完毕", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}
}
}.start();
}
}
| Qiang3570/Dialog | app/src/main/java/com/johnny/dialog/MainActivity.java | 1,531 | /*设置多选默认状态*/ | block_comment | zh-cn | package com.johnny.dialog;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 通知对话框
*
* @param v
*/
public void showNotifyDialog(View v) {
/*初始化dialog构造器*/
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("通知对话框:");/*设置dialog的title*/
builder.setMessage("通知对话框弹出了");/*设置dialog的内容*/
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {/*设置dialog确认按钮的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {/*设置dialog取消按钮的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);/*设置是否可以通过返回键消失, 默认true*/
builder.show();/*显示dialog*/
/* 第二种显示方法
* AlertDialog dialog = builder.create();
* dialog.show();
*/
}
/**
* 显示列表对话框
*
* @param v
*/
public void showListDialog(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请选中您喜欢的数字:");
builder.setIcon(R.mipmap.ic_launcher);/*设置图标*/
final String[] items = new String[]{"8", "6", "2", "1", "3"};/*设置列表的内容*/
builder.setItems(items, new DialogInterface.OnClickListener() {/*设置列表的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();
}
/**
* 显示单选对话框
*
* @param v
*/
public void showSinpleChioceDialog(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("选择性别:");
builder.setIcon(R.mipmap.ic_launcher);
final String[] items = new String[]{"男", "女", "妖"};
builder.setSingleChoiceItems(items, 2, new DialogInterface.OnClickListener() {/*设置单选条件的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();
}
/**
* 显示多选对话框
*
* @param v
*/
public void showMultiChioceDialog(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("于谦:");
builder.setIcon(R.mipmap.ic_launcher);
final String[] items = new String[]{"抽烟", "喝酒", "烫头"};/*设置多选的内容*/
final boolean[] checkedItems = new boolean[]{false, true, false};/*设置多 <SUF>*/
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {/*设置多选的点击事件*/
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
Toast.makeText(MainActivity.this, items[which] + " 状态: " + isChecked, Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();
}
/**
* 显示进度对话框
*
* @param v
*/
public void showProgressDialog(View v) {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("提醒");/*设置进度对话框的title*/
dialog.setMessage("正在加载中,请稍后...");/*设置进度对话框的内容*/
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);/*设置进度对话框的样式*/
dialog.setMax(100);/*设置进度对话框的最大进度*/
dialog.setCancelable(false);
dialog.show();/*在show时, 别忘了初始化进度*/
dialog.setProgress(23);/*设置进度*/
new Thread() {
public void run() {
while (true) {
if (dialog.getProgress() == 100)
return;
SystemClock.sleep(100);
dialog.incrementProgressBy(1);/*更新进度,每一次以5来递增(dialog.setProgress(dialog.getProgress() + 5))*/
if (dialog.getProgress() >= dialog.getMax()) {
runOnUiThread(new Runnable() {/*在主线程执行*/
@Override
public void run() {
Toast.makeText(MainActivity.this, "加载完毕", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}
}
}.start();
}
}
| false | 1,277 | 7 | 1,531 | 7 | 1,583 | 7 | 1,531 | 7 | 1,948 | 10 | false | false | false | false | false | true |
65892_0 | package com.tw.game.player;
import com.google.common.base.Optional;
import com.tw.game.armor.Armor;
import com.tw.game.weapon.MiddleWeapon;
import com.tw.game.weapon.Weapon;
/**
* 战士只能装备 中 武器
* */
public class Solider extends NormalPlayer {
private Weapon weapon;
private Armor armor;
public Solider(String name, int blood, int attack, Weapon weapon, Armor armor) {
super(name, blood, attack);
this.job = "战士";
this.weapon = weapon;
this.armor = armor;
this.defense = this.armor.getDefense();
}
@Override
public void dropBlood(NormalPlayer player2) {
int droppedBlood;
if(player2 instanceof Solider){
droppedBlood = this.getAttack() - player2.getDefense();
}else{
droppedBlood = this.getAttack();
}
if(weapon.hasFeature() && weapon.getWeaponFeature().getType().equals("tripleDamage")){
droppedBlood *= 3;
}
player2.setBlood(player2.getBlood() - droppedBlood);
}
@Override
public boolean hasWeapon() {
return true;
}
@Override
public boolean hasArmor() {
return true;
}
@Override
public Optional<Weapon> getWeapon() {
return Optional.of(this.weapon);
}
@Override
public Optional<Armor> getArmor() {
return Optional.of(this.armor);
}
@Override
public int getAttack() {
return this.getWeapon().get().getAttack() + super.getAttack();
}
@Override
public int getDefense() {
return getArmor().get().getDefense();
}
@Override
public String getWeaponExtraEffect() {
if(weapon instanceof MiddleWeapon){
return weapon.extraEffect();
}
return "";
}
}
| QiannanXu/WhistGame | src/main/java/com/tw/game/player/Solider.java | 454 | /**
* 战士只能装备 中 武器
* */ | block_comment | zh-cn | package com.tw.game.player;
import com.google.common.base.Optional;
import com.tw.game.armor.Armor;
import com.tw.game.weapon.MiddleWeapon;
import com.tw.game.weapon.Weapon;
/**
* 战士只 <SUF>*/
public class Solider extends NormalPlayer {
private Weapon weapon;
private Armor armor;
public Solider(String name, int blood, int attack, Weapon weapon, Armor armor) {
super(name, blood, attack);
this.job = "战士";
this.weapon = weapon;
this.armor = armor;
this.defense = this.armor.getDefense();
}
@Override
public void dropBlood(NormalPlayer player2) {
int droppedBlood;
if(player2 instanceof Solider){
droppedBlood = this.getAttack() - player2.getDefense();
}else{
droppedBlood = this.getAttack();
}
if(weapon.hasFeature() && weapon.getWeaponFeature().getType().equals("tripleDamage")){
droppedBlood *= 3;
}
player2.setBlood(player2.getBlood() - droppedBlood);
}
@Override
public boolean hasWeapon() {
return true;
}
@Override
public boolean hasArmor() {
return true;
}
@Override
public Optional<Weapon> getWeapon() {
return Optional.of(this.weapon);
}
@Override
public Optional<Armor> getArmor() {
return Optional.of(this.armor);
}
@Override
public int getAttack() {
return this.getWeapon().get().getAttack() + super.getAttack();
}
@Override
public int getDefense() {
return getArmor().get().getDefense();
}
@Override
public String getWeaponExtraEffect() {
if(weapon instanceof MiddleWeapon){
return weapon.extraEffect();
}
return "";
}
}
| false | 404 | 14 | 454 | 16 | 492 | 13 | 454 | 16 | 597 | 22 | false | false | false | false | false | true |
47007_1 | package com.yishian.command.gm;
import com.yishian.common.CommonPluginEnum;
/**
* @author XinQi
*/
public enum GmModeEnum {
/**
* 游戏模式切换
*/
GM_COMMAND("gm", "游戏模式切换"),
GM_PERMISSION(CommonPluginEnum.PLUGHIN_NAME.getCommand() + "." + GM_COMMAND.getCommand(), "模式切换的权限"),
CREATIVE("creative","创造"),
SURVIVAL("survival","生存"),
ADVENTURE("adventure","冒险"),
SPECTATOR("spectator","旁观");
private final String command;
private final String msg;
GmModeEnum(String command, String msg) {
this.command = command;
this.msg = msg;
}
public String getCommand() {
return command;
}
public String getMsg() {
return msg;
}
}
| Qing-JiuJiu/SpigotPlugins-UtilityToolbox | src/main/java/com/yishian/command/gm/GmModeEnum.java | 218 | /**
* 游戏模式切换
*/ | block_comment | zh-cn | package com.yishian.command.gm;
import com.yishian.common.CommonPluginEnum;
/**
* @author XinQi
*/
public enum GmModeEnum {
/**
* 游戏模 <SUF>*/
GM_COMMAND("gm", "游戏模式切换"),
GM_PERMISSION(CommonPluginEnum.PLUGHIN_NAME.getCommand() + "." + GM_COMMAND.getCommand(), "模式切换的权限"),
CREATIVE("creative","创造"),
SURVIVAL("survival","生存"),
ADVENTURE("adventure","冒险"),
SPECTATOR("spectator","旁观");
private final String command;
private final String msg;
GmModeEnum(String command, String msg) {
this.command = command;
this.msg = msg;
}
public String getCommand() {
return command;
}
public String getMsg() {
return msg;
}
}
| false | 189 | 11 | 218 | 10 | 223 | 10 | 218 | 10 | 291 | 18 | false | false | false | false | false | true |
39570_0 | /*
3、功能:设计一组类和接口,满足如下要求:(编译成功即可)
a.游戏模拟:兵种包括轰炸机、直升机、重型坦克、轻型坦克、音波坦克、步兵、飞行兵
b.轰炸机、直升机、飞行兵属于空军;步兵、轻型坦克、重型坦克属于陆军,音波坦克属于水陆两栖;
(提示:设计时,音波坦克内有标记inWater,在构造时填入,若为true,则表示目前音波坦克在水中,否则就是在陆地上)
c.轻型坦克、步兵只能攻击陆军,音波坦克只能攻击空军,轰炸机可攻击陆军、海军;重型坦克可攻击陆军、空军,直升机、飞行兵可攻击海军、陆军、空军;
并验证设计效果。(即向兵种变量填入海/陆/空军兵种,检测a.attack(b)的输出)
*/
package homework.week10.Answers;
//【【【注意:加入海陆两栖后,变化:步兵攻击陆军,陆军可能是水中的音波坦克 == 不能攻击
//解决策略:先单独判断两栖类,再判断单类,详见轰炸机类
interface 陆军 {
} // 陆军标签
interface 空军 {
} // 空军标签
interface 海军 {
} // 空军标签
interface 海陆两栖 extends 海军, 陆军 {// 由于可以在陆地或海洋,故需要能获得该兵种的位置标记
boolean isInWater();
}
interface 可攻击陆军 { // 可以攻击陆军属性标签
default void attack(陆军 x) {
System.out.println("攻击陆军");
}
}
interface 可攻击空军 { // 可以攻击空军属性标签
default void attack(空军 x) {
System.out.println("攻击空军");
}
}
interface 可攻击海军 { // 可以攻击空军属性标签
default void attack(海军 x) {
System.out.println("攻击海军");
}
}
abstract class 兵种 { // 兵种总基类
private String type;
public 兵种(String n) {
type = n;
}
public abstract void attack(兵种 x);
public String attackInfo(兵种 x) {
return type + " 遇见 " + x;
}
public String toString() {
return type;
}
}
abstract class 飞行器 extends 兵种 implements 空军 { // 飞行器基类(都是空军)
public 飞行器(String n) {
super(n);
}
}
abstract class 坦克 extends 兵种 { // 坦克基类
public 坦克(String n) {
super(n);
}
}
abstract class 士兵 extends 兵种 { // 士兵基类
public 士兵(String n) {
super(n);
}
}
// 飞行器子类
class 轰炸机 extends 飞行器 implements 可攻击陆军, 可攻击海军 { // 轰炸机类
public 轰炸机() {
super("轰炸机");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
attack((海军) x);
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x); // 此处是单型的陆军
else if (x instanceof 海军)
attack((海军) x); // 此处是单型的海军
else
System.out.print("不能攻击");
}
}
class 直升机 extends 飞行器 implements 可攻击陆军, 可攻击空军, 可攻击海军 { // 直升机类
public 直升机() {
super("直升机");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
attack((海军) x);
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else if (x instanceof 空军)
attack((空军) x);
else if (x instanceof 海军)
attack((海军) x);
else
System.out.print("不能攻击");
}
}
// 坦克子类
class 重型坦克 extends 坦克 implements 陆军, 可攻击陆军, 可攻击空军 { // 重型坦克类
public 重型坦克() {
super("重型坦克");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
System.out.print("不能攻击");
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else if (x instanceof 空军)
attack((空军) x);
else
System.out.print("不能攻击");
}
}
class 轻型坦克 extends 坦克 implements 陆军, 可攻击陆军 { // 轻型坦克类
public 轻型坦克() {
super("轻型坦克");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
System.out.print("不能攻击");
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else
System.out.print("不能攻击");
}
}
class 音波坦克 extends 坦克 implements 海陆两栖, 可攻击空军 { // 音波坦克类
private boolean inWater;
public 音波坦克(boolean flag) {
super("音波坦克");
inWater = flag;
}
public boolean isInWater() {
return inWater;
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 空军)
attack((空军) x);
else
System.out.print("不能攻击");
}
public String toString() {
String s = "在陆地";
if (inWater == true)
s = "在水中";
return "音波坦克-" + s;
}
}
// 士兵子类
class 步兵 extends 士兵 implements 陆军, 可攻击陆军 { // 步兵类
public 步兵() {
super("步兵");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
System.out.print("不能攻击");
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else
System.out.print("不能攻击");
}
}
class 飞行兵 extends 士兵 implements 空军, 可攻击陆军, 可攻击海军, 可攻击空军 { // 飞行兵类
public 飞行兵() {
super("飞行兵");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
attack((海军) x);
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else if (x instanceof 空军)
attack((空军) x);
else
System.out.print("不能攻击");
}
}
class App {
public static void main(String[] args) {
兵种[] a = { new 轰炸机(), new 直升机(), new 重型坦克(), new 轻型坦克(), new 步兵(), new 飞行兵() };
兵种[] b = { new 音波坦克(false), new 音波坦克(true), new 音波坦克(true), new 音波坦克(false),
new 直升机(), new 轰炸机() };
for (int i = 0; i < a.length; i++)
a[i].attack(b[i]);
}
} | Qingxian0/JXNU-Java-OOP | homework/week10/Answers/Game.java | 2,525 | /*
3、功能:设计一组类和接口,满足如下要求:(编译成功即可)
a.游戏模拟:兵种包括轰炸机、直升机、重型坦克、轻型坦克、音波坦克、步兵、飞行兵
b.轰炸机、直升机、飞行兵属于空军;步兵、轻型坦克、重型坦克属于陆军,音波坦克属于水陆两栖;
(提示:设计时,音波坦克内有标记inWater,在构造时填入,若为true,则表示目前音波坦克在水中,否则就是在陆地上)
c.轻型坦克、步兵只能攻击陆军,音波坦克只能攻击空军,轰炸机可攻击陆军、海军;重型坦克可攻击陆军、空军,直升机、飞行兵可攻击海军、陆军、空军;
并验证设计效果。(即向兵种变量填入海/陆/空军兵种,检测a.attack(b)的输出)
*/ | block_comment | zh-cn | /*
3、功 <SUF>*/
package homework.week10.Answers;
//【【【注意:加入海陆两栖后,变化:步兵攻击陆军,陆军可能是水中的音波坦克 == 不能攻击
//解决策略:先单独判断两栖类,再判断单类,详见轰炸机类
interface 陆军 {
} // 陆军标签
interface 空军 {
} // 空军标签
interface 海军 {
} // 空军标签
interface 海陆两栖 extends 海军, 陆军 {// 由于可以在陆地或海洋,故需要能获得该兵种的位置标记
boolean isInWater();
}
interface 可攻击陆军 { // 可以攻击陆军属性标签
default void attack(陆军 x) {
System.out.println("攻击陆军");
}
}
interface 可攻击空军 { // 可以攻击空军属性标签
default void attack(空军 x) {
System.out.println("攻击空军");
}
}
interface 可攻击海军 { // 可以攻击空军属性标签
default void attack(海军 x) {
System.out.println("攻击海军");
}
}
abstract class 兵种 { // 兵种总基类
private String type;
public 兵种(String n) {
type = n;
}
public abstract void attack(兵种 x);
public String attackInfo(兵种 x) {
return type + " 遇见 " + x;
}
public String toString() {
return type;
}
}
abstract class 飞行器 extends 兵种 implements 空军 { // 飞行器基类(都是空军)
public 飞行器(String n) {
super(n);
}
}
abstract class 坦克 extends 兵种 { // 坦克基类
public 坦克(String n) {
super(n);
}
}
abstract class 士兵 extends 兵种 { // 士兵基类
public 士兵(String n) {
super(n);
}
}
// 飞行器子类
class 轰炸机 extends 飞行器 implements 可攻击陆军, 可攻击海军 { // 轰炸机类
public 轰炸机() {
super("轰炸机");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
attack((海军) x);
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x); // 此处是单型的陆军
else if (x instanceof 海军)
attack((海军) x); // 此处是单型的海军
else
System.out.print("不能攻击");
}
}
class 直升机 extends 飞行器 implements 可攻击陆军, 可攻击空军, 可攻击海军 { // 直升机类
public 直升机() {
super("直升机");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
attack((海军) x);
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else if (x instanceof 空军)
attack((空军) x);
else if (x instanceof 海军)
attack((海军) x);
else
System.out.print("不能攻击");
}
}
// 坦克子类
class 重型坦克 extends 坦克 implements 陆军, 可攻击陆军, 可攻击空军 { // 重型坦克类
public 重型坦克() {
super("重型坦克");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
System.out.print("不能攻击");
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else if (x instanceof 空军)
attack((空军) x);
else
System.out.print("不能攻击");
}
}
class 轻型坦克 extends 坦克 implements 陆军, 可攻击陆军 { // 轻型坦克类
public 轻型坦克() {
super("轻型坦克");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
System.out.print("不能攻击");
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else
System.out.print("不能攻击");
}
}
class 音波坦克 extends 坦克 implements 海陆两栖, 可攻击空军 { // 音波坦克类
private boolean inWater;
public 音波坦克(boolean flag) {
super("音波坦克");
inWater = flag;
}
public boolean isInWater() {
return inWater;
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 空军)
attack((空军) x);
else
System.out.print("不能攻击");
}
public String toString() {
String s = "在陆地";
if (inWater == true)
s = "在水中";
return "音波坦克-" + s;
}
}
// 士兵子类
class 步兵 extends 士兵 implements 陆军, 可攻击陆军 { // 步兵类
public 步兵() {
super("步兵");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
System.out.print("不能攻击");
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else
System.out.print("不能攻击");
}
}
class 飞行兵 extends 士兵 implements 空军, 可攻击陆军, 可攻击海军, 可攻击空军 { // 飞行兵类
public 飞行兵() {
super("飞行兵");
}
public void attack(兵种 x) {
System.out.print("\n" + attackInfo(x) + ": ");
if (x instanceof 海陆两栖) {// 先单独判断两栖类,
海陆两栖 y = (海陆两栖) x;
if (y.isInWater() == true)
attack((海军) x);
else
attack((陆军) x);
} // 再判断单型类
else if (x instanceof 陆军)
attack((陆军) x);
else if (x instanceof 空军)
attack((空军) x);
else
System.out.print("不能攻击");
}
}
class App {
public static void main(String[] args) {
兵种[] a = { new 轰炸机(), new 直升机(), new 重型坦克(), new 轻型坦克(), new 步兵(), new 飞行兵() };
兵种[] b = { new 音波坦克(false), new 音波坦克(true), new 音波坦克(true), new 音波坦克(false),
new 直升机(), new 轰炸机() };
for (int i = 0; i < a.length; i++)
a[i].attack(b[i]);
}
} | false | 2,143 | 197 | 2,495 | 285 | 2,307 | 228 | 2,495 | 285 | 3,210 | 399 | false | false | false | false | false | true |
50302_0 | package Player;
import java.util.ArrayList;
import java.util.List;
import Actor.AttackWithWeapon;
import Actor.Defence;
import Actor.Health;
import Battle.BattleMemberBase;
import Choice.IChoice;
import Choice.battle.BattleAttack;
import Choice.battle.BattleBackpack;
import Choice.battle.BattleDefence;
import Choice.battle.BattleEscape;
import Mgr.ChoiceMgr;
import Mgr.SoundMgr;
public class PlayerBattle extends BattleMemberBase implements PlayerMaker {
// 攻击、背包、防御、逃跑
private static volatile PlayerBattle instance;
static List<IChoice> choices=new ArrayList<>();
private PlayerBattle() {
if (instance != null) {
throw new IllegalStateException("Already initialized.");
} else {
instance = this;
name=Player.playername;
SetHealth(new Health(100));
SetAttack(new AttackWithWeapon(5));
SetDefence(new Defence(2));
choices.add(new BattleAttack(this));
choices.add(new BattleDefence(this));
choices.add(new BattleBackpack(this));
choices.add(new BattleEscape(this));
}
}
public static PlayerBattle GetInstance() {
var result = instance;
if (result == null) {
synchronized (PlayerBattle.class) {
result = instance;
if (result == null) {
instance = result = new PlayerBattle();
}
}
}
return result;
}
public void OneRoundUp() throws InterruptedException {
super.OneRoundUp();
System.out.println(Player.playername + "决定");
ChooseAction();
}
public void ChooseAction() throws InterruptedException
{
ChoiceMgr.GetInstance().Choose(choices);
}
public void Fall() throws InterruptedException // 倒下
{
SoundMgr.GetInstance().PlayPlayerFallSound();
iBattleMediator.RemoveMember(this);
}
}
| Qiuqiu0529/FarmRPG | src/Player/PlayerBattle.java | 450 | // 攻击、背包、防御、逃跑 | line_comment | zh-cn | package Player;
import java.util.ArrayList;
import java.util.List;
import Actor.AttackWithWeapon;
import Actor.Defence;
import Actor.Health;
import Battle.BattleMemberBase;
import Choice.IChoice;
import Choice.battle.BattleAttack;
import Choice.battle.BattleBackpack;
import Choice.battle.BattleDefence;
import Choice.battle.BattleEscape;
import Mgr.ChoiceMgr;
import Mgr.SoundMgr;
public class PlayerBattle extends BattleMemberBase implements PlayerMaker {
// 攻击 <SUF>
private static volatile PlayerBattle instance;
static List<IChoice> choices=new ArrayList<>();
private PlayerBattle() {
if (instance != null) {
throw new IllegalStateException("Already initialized.");
} else {
instance = this;
name=Player.playername;
SetHealth(new Health(100));
SetAttack(new AttackWithWeapon(5));
SetDefence(new Defence(2));
choices.add(new BattleAttack(this));
choices.add(new BattleDefence(this));
choices.add(new BattleBackpack(this));
choices.add(new BattleEscape(this));
}
}
public static PlayerBattle GetInstance() {
var result = instance;
if (result == null) {
synchronized (PlayerBattle.class) {
result = instance;
if (result == null) {
instance = result = new PlayerBattle();
}
}
}
return result;
}
public void OneRoundUp() throws InterruptedException {
super.OneRoundUp();
System.out.println(Player.playername + "决定");
ChooseAction();
}
public void ChooseAction() throws InterruptedException
{
ChoiceMgr.GetInstance().Choose(choices);
}
public void Fall() throws InterruptedException // 倒下
{
SoundMgr.GetInstance().PlayPlayerFallSound();
iBattleMediator.RemoveMember(this);
}
}
| false | 392 | 10 | 450 | 16 | 483 | 9 | 450 | 16 | 583 | 23 | false | false | false | false | false | true |
2262_2 | package com.upc.learnmooc.activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.upc.learnmooc.R;
import com.upc.learnmooc.domain.NoteDetail;
import com.upc.learnmooc.global.GlobalConstants;
import com.upc.learnmooc.utils.ToastUtils;
import com.upc.learnmooc.utils.UserInfoCacheUtils;
import java.util.ArrayList;
import cn.pedant.SweetAlert.SweetAlertDialog;
/**
* 笔记详情
* Created by Explorer on 2016/4/9.
*/
public class NoteDetailActivity extends BaseActivity {
private ListView mListView;
private String mUrl;
private String courseName;
private ArrayList<NoteDetail.NoteContent> noteContent;
private SweetAlertDialog pDialog;
private ListViewAdapter mAdapter;
private String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_detail_activity);
initViews();
initData();
}
@Override
public void initViews() {
mListView = (ListView) findViewById(R.id.lv_note_detail);
}
private void initData() {
mUrl = GlobalConstants.GET_NOTE_DETAIL;
url = GlobalConstants.REMOVE_NOTE;
courseName = getIntent().getStringExtra("courseName");
getDataFromServer();
}
private void getDataFromServer() {
HttpUtils httpUtils = new HttpUtils();
httpUtils.configCurrentHttpCacheExpiry(5 * 1000);
httpUtils.configTimeout(1000 * 5);
//GET参数为用户id 和 courseId
RequestParams params = new RequestParams();
params.addQueryStringParameter("userId", UserInfoCacheUtils.getLong(NoteDetailActivity.this, "id", 0) + "");
params.addQueryStringParameter("courseName", courseName);
httpUtils.send(HttpRequest.HttpMethod.GET, mUrl, params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
parseData(responseInfo.result);
}
@Override
public void onFailure(HttpException e, String s) {
e.printStackTrace();
}
});
}
private void parseData(String result) {
Gson gson = new Gson();
NoteDetail noteDetail = gson.fromJson(result, NoteDetail.class);
noteContent = noteDetail.noteDetail;
if (noteContent != null) {
mAdapter = new ListViewAdapter();
mListView.setAdapter(mAdapter);
}
}
class ListViewAdapter extends BaseAdapter {
@Override
public int getCount() {
return noteContent.size();
}
@Override
public Object getItem(int position) {
return noteContent.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(NoteDetailActivity.this, R.layout.item_note_detail_listview, null);
holder = new ViewHolder();
holder.tvTime = (TextView) convertView.findViewById(R.id.tv_note_time);
holder.tvContent = (TextView) convertView.findViewById(R.id.tv_note_content);
holder.ivDel = (ImageView) convertView.findViewById(R.id.iv_del);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final NoteDetail.NoteContent noteContentData = noteContent.get(position);
holder.tvTime.setText(noteContentData.getTime().substring(0,16));
holder.tvContent.setText(noteContentData.getContent());
holder.ivDel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDeleteDialog(position);
}
});
return convertView;
}
}
/**
* 显示删除提示的弹窗
*/
protected void showDeleteDialog(final int position) {
pDialog = new SweetAlertDialog(this)
.setTitleText("真的要删掉我吗?")
.setContentText("~T_T~")
.setConfirmText("真的")
.setCancelText("逗你的");
//取消
pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
pDialog.dismiss();
}
});
//删除
pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
pDialog.dismiss();
// 删除对应的note记录
HttpUtils httpUtils = new HttpUtils();
httpUtils.configCurrentHttpCacheExpiry(5 * 1000);
httpUtils.configTimeout(1000 * 5);
// noteId
RequestParams params = new RequestParams();
params.addQueryStringParameter("noteId", noteContent.get(position).getNoteId() + "");
httpUtils.send(HttpRequest.HttpMethod.GET, url, params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
if (responseInfo.result.equals("success")) {
noteContent.remove(position);
mAdapter.notifyDataSetChanged();
}
ToastUtils.showToastShort(NoteDetailActivity.this, responseInfo.result);
}
@Override
public void onFailure(HttpException e, String s) {
e.printStackTrace();
ToastUtils.showToastShort(NoteDetailActivity.this, "删除异常 请重试");
}
});
}
});
pDialog.show();
}
static class ViewHolder {
public TextView tvTime;
public TextView tvContent;
public ImageView ivDel;
}
}
| Qloop/learnMooc_android | app/src/main/java/com/upc/learnmooc/activity/NoteDetailActivity.java | 1,651 | /**
* 显示删除提示的弹窗
*/ | block_comment | zh-cn | package com.upc.learnmooc.activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.upc.learnmooc.R;
import com.upc.learnmooc.domain.NoteDetail;
import com.upc.learnmooc.global.GlobalConstants;
import com.upc.learnmooc.utils.ToastUtils;
import com.upc.learnmooc.utils.UserInfoCacheUtils;
import java.util.ArrayList;
import cn.pedant.SweetAlert.SweetAlertDialog;
/**
* 笔记详情
* Created by Explorer on 2016/4/9.
*/
public class NoteDetailActivity extends BaseActivity {
private ListView mListView;
private String mUrl;
private String courseName;
private ArrayList<NoteDetail.NoteContent> noteContent;
private SweetAlertDialog pDialog;
private ListViewAdapter mAdapter;
private String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_detail_activity);
initViews();
initData();
}
@Override
public void initViews() {
mListView = (ListView) findViewById(R.id.lv_note_detail);
}
private void initData() {
mUrl = GlobalConstants.GET_NOTE_DETAIL;
url = GlobalConstants.REMOVE_NOTE;
courseName = getIntent().getStringExtra("courseName");
getDataFromServer();
}
private void getDataFromServer() {
HttpUtils httpUtils = new HttpUtils();
httpUtils.configCurrentHttpCacheExpiry(5 * 1000);
httpUtils.configTimeout(1000 * 5);
//GET参数为用户id 和 courseId
RequestParams params = new RequestParams();
params.addQueryStringParameter("userId", UserInfoCacheUtils.getLong(NoteDetailActivity.this, "id", 0) + "");
params.addQueryStringParameter("courseName", courseName);
httpUtils.send(HttpRequest.HttpMethod.GET, mUrl, params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
parseData(responseInfo.result);
}
@Override
public void onFailure(HttpException e, String s) {
e.printStackTrace();
}
});
}
private void parseData(String result) {
Gson gson = new Gson();
NoteDetail noteDetail = gson.fromJson(result, NoteDetail.class);
noteContent = noteDetail.noteDetail;
if (noteContent != null) {
mAdapter = new ListViewAdapter();
mListView.setAdapter(mAdapter);
}
}
class ListViewAdapter extends BaseAdapter {
@Override
public int getCount() {
return noteContent.size();
}
@Override
public Object getItem(int position) {
return noteContent.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(NoteDetailActivity.this, R.layout.item_note_detail_listview, null);
holder = new ViewHolder();
holder.tvTime = (TextView) convertView.findViewById(R.id.tv_note_time);
holder.tvContent = (TextView) convertView.findViewById(R.id.tv_note_content);
holder.ivDel = (ImageView) convertView.findViewById(R.id.iv_del);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final NoteDetail.NoteContent noteContentData = noteContent.get(position);
holder.tvTime.setText(noteContentData.getTime().substring(0,16));
holder.tvContent.setText(noteContentData.getContent());
holder.ivDel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDeleteDialog(position);
}
});
return convertView;
}
}
/**
* 显示删 <SUF>*/
protected void showDeleteDialog(final int position) {
pDialog = new SweetAlertDialog(this)
.setTitleText("真的要删掉我吗?")
.setContentText("~T_T~")
.setConfirmText("真的")
.setCancelText("逗你的");
//取消
pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
pDialog.dismiss();
}
});
//删除
pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
pDialog.dismiss();
// 删除对应的note记录
HttpUtils httpUtils = new HttpUtils();
httpUtils.configCurrentHttpCacheExpiry(5 * 1000);
httpUtils.configTimeout(1000 * 5);
// noteId
RequestParams params = new RequestParams();
params.addQueryStringParameter("noteId", noteContent.get(position).getNoteId() + "");
httpUtils.send(HttpRequest.HttpMethod.GET, url, params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
if (responseInfo.result.equals("success")) {
noteContent.remove(position);
mAdapter.notifyDataSetChanged();
}
ToastUtils.showToastShort(NoteDetailActivity.this, responseInfo.result);
}
@Override
public void onFailure(HttpException e, String s) {
e.printStackTrace();
ToastUtils.showToastShort(NoteDetailActivity.this, "删除异常 请重试");
}
});
}
});
pDialog.show();
}
static class ViewHolder {
public TextView tvTime;
public TextView tvContent;
public ImageView ivDel;
}
}
| false | 1,298 | 13 | 1,651 | 12 | 1,590 | 12 | 1,651 | 12 | 2,044 | 21 | false | false | false | false | false | true |
22662_0 | package concurrent;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 举一个很简单的例子,今天晚上我们哥们4个去Happy。
* 就互相通知了一下:晚上八点准时到xx酒吧门前集合,不见不散!。有个哥们住的近,早早就到了。
* 有的事务繁忙,刚好踩点到了。无论怎样,先来的都不能独自行动,只能等待所有人
*/
public class TestCyclicBarrier1 {
public static void main(String[] args) {
//new 一个线程池
ExecutorService exec = Executors.newCachedThreadPool();
final Random random = new Random();
final CyclicBarrier barrier = new CyclicBarrier(4, new Runnable() {
@Override
public void run() {
System.out.println("大家都到齐了,开始happy去");
}
});
for (int i = 0; i < 4; i++) {
exec.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(random.nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "到了,其他哥们呢");
try {
barrier.await();// 等待其他哥们
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
});
}
exec.shutdown();
}
}
| Qstar/JavaCases | src/main/java/concurrent/TestCyclicBarrier1.java | 402 | /**
* 举一个很简单的例子,今天晚上我们哥们4个去Happy。
* 就互相通知了一下:晚上八点准时到xx酒吧门前集合,不见不散!。有个哥们住的近,早早就到了。
* 有的事务繁忙,刚好踩点到了。无论怎样,先来的都不能独自行动,只能等待所有人
*/ | block_comment | zh-cn | package concurrent;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 举一个 <SUF>*/
public class TestCyclicBarrier1 {
public static void main(String[] args) {
//new 一个线程池
ExecutorService exec = Executors.newCachedThreadPool();
final Random random = new Random();
final CyclicBarrier barrier = new CyclicBarrier(4, new Runnable() {
@Override
public void run() {
System.out.println("大家都到齐了,开始happy去");
}
});
for (int i = 0; i < 4; i++) {
exec.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(random.nextInt(10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "到了,其他哥们呢");
try {
barrier.await();// 等待其他哥们
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
});
}
exec.shutdown();
}
}
| false | 331 | 75 | 402 | 106 | 397 | 82 | 402 | 106 | 548 | 165 | false | false | false | false | false | true |
21033_2 | package core.base;
/**
* Created by Qtyearlin on 2017/2/6.
*/
public class RxjavaInstall {
/*前两篇为大家介绍了使用RxJava打印多个字符串的方法
Observable.just("Hellow", "Wrold").subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.i(TAG, s);
}
});
这样的例子基本没有实际用处,只是为大家演示如何使用Rxjava。今天就抛开这个例子。
map
在使用map之前要先说道一个接口:Func1,Func1和上一篇提到的Action1相似。Func1 和 Action的区别在于, Func1 包装的是有返回值的方法。
接下来就是map的用法,看代码更直观点;
例:得到多个Student对象中的name,保存到nameList中
Observable.just(student1, student2, student2)
//使用map进行转换,参数1:转换前的类型,参数2:转换后的类型
.map(new Func1<Student, String>() {
@Override
public String call(Student i) {
String name = i.getName();//获取Student对象中的name
return name;//返回name
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
nameList.add(s);
}
});
可以看到Observable中原来的参数是Student对象,而最后我们需要的是name,这里使用了map来实现这一转换的过程。当然,map可以多次使用。
//多次使用map,想用几个用几个
Observable.just("Hello", "World")
.map(new Func1<String, Integer>() {//将String类型的转化为Integer类型的哈希码
@Override
public Integer call(String s) {
return s.hashCode();
}
})
.map(new Func1<Integer, String>() {//将转化后得到的Integer类型的哈希码再转化为String类型
@Override
public String call(Integer integer) {
return integer.intValue() + "";
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.i(TAG, s);
}
});
flatMap
flatMap是一个比教难理解的一个转换,在这里先假设一个需求,需要打印多个Student所学的课程。这跟之前获取Student的name又不同了,这里先确定一下关系,一个Student类中只有一个name,而一个Student却有多门课程(Course),Student我们可以理解成这样:
*//**
* 学生类
*//*
class Student {
private String name;//姓名
private List<Course> coursesList;//所修的课程
...
}
*//**
* 课程类
*//*
class Course {
private String name;//课程名
private String id;
...
}
如果使用map来实现打印所有学生所修个课程名,实现的代码是这样的:
List<Student> students = new ArrayList<Student>();
students.add...
...
Action1<List<Course>> action1 = new Action1<List<Course>>() {
@Override
public void call(List<Course> courses) {
//遍历courses,输出cuouses的name
for (int i = 0; i < courses.size(); i++){
Log.i(TAG, courses.get(i).getName());
}
}
};
Observable.from(students)
.map(new Func1<Student, List<Course>>() {
@Override
public List<Course> call(Student student) {
//返回coursesList
return student.getCoursesList();
}
})
.subscribe(action1);
可以看到,在Action1中出现了for来循环打印课程名,使用RxJava就是为了剔除这样的嵌套结构,使得整体的逻辑性更强。这时候就可以使用flatMap了,使用flatMap实现的代码是这样的:
List<Student> students = new ArrayList<Student>();
students.add...
...
Observable.from(students)
.flatMap(new Func1<Student, Observable<Course>>() {
@Override
public Observable<Course> call(Student student) {
return Observable.from(student.getCoursesList());
}
})
.subscribe(new Action1<Course>() {
@Override
public void call(Course course) {
Log.i(TAG, course.getName());
}
});
这样就实现了跟上面代码一样的效果,看起来有点懵?确实,flatMap理解起来有点绕,刚接触flatMap的时候我也是懵逼一个。下面我将flatMap的示意图,希望能帮助理解:
flatMap示意图
由上图可以看出Student1、Student2经过flatMap后,按顺序依次经历了Observable1、Observable2,分别转化为Course。最后按顺序得到Course1、Course2、Course3、Course4、Course5、Course6,其中1-3由Student1得到,4-6由Student2得到。
结合代码和示意图,是不是对flatMap有了一定的理解。
其他操作符
除了map和flatMap之外,还有其他操作符以供使用。这里就不一一列举他们的用法了,其他常用的操作符如下:
filter:集合进行过滤
each:遍历集合
take:取出集合中的前几个
skip:跳过前几个元素
unique:相当于按照数学上的集合处理,去重*/
}
| QtyearLin/MVP | Tdroid/core/src/main/java/core/base/RxjavaInstall.java | 1,276 | /**
* 学生类
*/ | block_comment | zh-cn | package core.base;
/**
* Created by Qtyearlin on 2017/2/6.
*/
public class RxjavaInstall {
/*前两篇为大家介绍了使用RxJava打印多个字符串的方法
Observable.just("Hellow", "Wrold").subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.i(TAG, s);
}
});
这样的例子基本没有实际用处,只是为大家演示如何使用Rxjava。今天就抛开这个例子。
map
在使用map之前要先说道一个接口:Func1,Func1和上一篇提到的Action1相似。Func1 和 Action的区别在于, Func1 包装的是有返回值的方法。
接下来就是map的用法,看代码更直观点;
例:得到多个Student对象中的name,保存到nameList中
Observable.just(student1, student2, student2)
//使用map进行转换,参数1:转换前的类型,参数2:转换后的类型
.map(new Func1<Student, String>() {
@Override
public String call(Student i) {
String name = i.getName();//获取Student对象中的name
return name;//返回name
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
nameList.add(s);
}
});
可以看到Observable中原来的参数是Student对象,而最后我们需要的是name,这里使用了map来实现这一转换的过程。当然,map可以多次使用。
//多次使用map,想用几个用几个
Observable.just("Hello", "World")
.map(new Func1<String, Integer>() {//将String类型的转化为Integer类型的哈希码
@Override
public Integer call(String s) {
return s.hashCode();
}
})
.map(new Func1<Integer, String>() {//将转化后得到的Integer类型的哈希码再转化为String类型
@Override
public String call(Integer integer) {
return integer.intValue() + "";
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.i(TAG, s);
}
});
flatMap
flatMap是一个比教难理解的一个转换,在这里先假设一个需求,需要打印多个Student所学的课程。这跟之前获取Student的name又不同了,这里先确定一下关系,一个Student类中只有一个name,而一个Student却有多门课程(Course),Student我们可以理解成这样:
*//**
* 学生类 <SUF>*//*
class Student {
private String name;//姓名
private List<Course> coursesList;//所修的课程
...
}
*//**
* 课程类
*//*
class Course {
private String name;//课程名
private String id;
...
}
如果使用map来实现打印所有学生所修个课程名,实现的代码是这样的:
List<Student> students = new ArrayList<Student>();
students.add...
...
Action1<List<Course>> action1 = new Action1<List<Course>>() {
@Override
public void call(List<Course> courses) {
//遍历courses,输出cuouses的name
for (int i = 0; i < courses.size(); i++){
Log.i(TAG, courses.get(i).getName());
}
}
};
Observable.from(students)
.map(new Func1<Student, List<Course>>() {
@Override
public List<Course> call(Student student) {
//返回coursesList
return student.getCoursesList();
}
})
.subscribe(action1);
可以看到,在Action1中出现了for来循环打印课程名,使用RxJava就是为了剔除这样的嵌套结构,使得整体的逻辑性更强。这时候就可以使用flatMap了,使用flatMap实现的代码是这样的:
List<Student> students = new ArrayList<Student>();
students.add...
...
Observable.from(students)
.flatMap(new Func1<Student, Observable<Course>>() {
@Override
public Observable<Course> call(Student student) {
return Observable.from(student.getCoursesList());
}
})
.subscribe(new Action1<Course>() {
@Override
public void call(Course course) {
Log.i(TAG, course.getName());
}
});
这样就实现了跟上面代码一样的效果,看起来有点懵?确实,flatMap理解起来有点绕,刚接触flatMap的时候我也是懵逼一个。下面我将flatMap的示意图,希望能帮助理解:
flatMap示意图
由上图可以看出Student1、Student2经过flatMap后,按顺序依次经历了Observable1、Observable2,分别转化为Course。最后按顺序得到Course1、Course2、Course3、Course4、Course5、Course6,其中1-3由Student1得到,4-6由Student2得到。
结合代码和示意图,是不是对flatMap有了一定的理解。
其他操作符
除了map和flatMap之外,还有其他操作符以供使用。这里就不一一列举他们的用法了,其他常用的操作符如下:
filter:集合进行过滤
each:遍历集合
take:取出集合中的前几个
skip:跳过前几个元素
unique:相当于按照数学上的集合处理,去重*/
}
| false | 1,163 | 10 | 1,276 | 8 | 1,290 | 9 | 1,276 | 8 | 1,786 | 11 | false | false | false | false | false | true |
31190_3 | package cn.qjq.bean;
/**
* 用户类
* Created by qjq on 2020/2/2 16:12
*/
@SuppressWarnings("all")
public class User {
private int id;//用户id
private String uname;//用户名
private String upass;//用户密码
private int type;//用户类型 1:管理员 2:学生
public User() {
}
public User(String uname, String upass) {
this.uname = uname;
this.upass = upass;
}
public User(String uname, String upass, int type) {
this.uname = uname;
this.upass = upass;
this.type = type;
}
public User(int id, String uname, String upass, int type) {
this.id = id;
this.uname = uname;
this.upass = upass;
this.type = type;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", uname='" + uname + '\'' +
", upass='" + upass + '\'' +
", type=" + type +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| Qu-jq/Student-Manage-System | src/cn/qjq/bean/User.java | 413 | //用户密码 | line_comment | zh-cn | package cn.qjq.bean;
/**
* 用户类
* Created by qjq on 2020/2/2 16:12
*/
@SuppressWarnings("all")
public class User {
private int id;//用户id
private String uname;//用户名
private String upass;//用户 <SUF>
private int type;//用户类型 1:管理员 2:学生
public User() {
}
public User(String uname, String upass) {
this.uname = uname;
this.upass = upass;
}
public User(String uname, String upass, int type) {
this.uname = uname;
this.upass = upass;
this.type = type;
}
public User(int id, String uname, String upass, int type) {
this.id = id;
this.uname = uname;
this.upass = upass;
this.type = type;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", uname='" + uname + '\'' +
", upass='" + upass + '\'' +
", type=" + type +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| false | 379 | 3 | 413 | 3 | 453 | 3 | 413 | 3 | 517 | 5 | false | false | false | false | false | true |
61664_2 | package principle.interfaceisolation.version1;
import principle.interfaceisolation.version1.AbstractSearcher;
import principle.interfaceisolation.version1.IPettyGirl;
import principle.interfaceisolation.version1.PettyGirl;
import principle.interfaceisolation.version1.Searcher;
import principle.interfaceisolation.version2.IGoodBodyGirl;
import principle.interfaceisolation.version2.PettyGirl2;
/**
* @author Lan
* @createTime 2024-03-13 11:18
**/
public class Client {
public static void main(String[] args) {
//定义一个美女
IPettyGirl yanYan = new PettyGirl("嫣嫣");
AbstractSearcher searcher = new Searcher(yanYan);
searcher.show();
}
}
/**
* 思考一下IPettyGirl这个接口,这个接口是否做到了最优化设计?答案是没有,还可以对接口进行优化。
* 我们的审美观点都在改变,美女的定义也在变化。唐朝的杨贵妃如果活在现在这个年代
* 非羞愧而死不可,为什么?胖呀!但是胖并不影响她入选中国四大美女,说明当时的审美观
* 与现在是有差异的。当然,随着时代的发展我们的审美观也在变化,当你发现有一个女孩,
* 脸蛋不怎么样,身材也一般般,但是气质非常好,我相信大部分人都会把这样的女孩叫美
* 女,审美素质提升了,就产生了气质型美女,但是我们的接口却定义了美女必须是三者都具
* 备,按照这个标准,气质型美女就不能算美女,那怎么办?可能你要说了,我重新扩展一个
* 美女类,只实现greatTemperament方法,其他两个方法置空,什么都不写,不就可以了吗?
* 聪明,但是行不通!为什么呢?星探AbstractSearcher依赖的是IPettyGirl接口,它有三个方
* 法,你只实现了两个方法,星探的方法是不是要修改?我们上面的程序打印出来的信息少了
* 两条,还让星探怎么去辨别是不是美女呢?
*
* 分析到这里,我们发现接口IPettyGirl的设计是有缺陷的,过于庞大了,容纳了一些可变
* 的因素,根据接口隔离原则,星探AbstractSearcher应该依赖于具有部分特质的女孩子,而我
* 们却把这些特质都封装了起来,放到了一个接口中,封装过度了!
*
* 把原IPettyGirl接口拆分为两个接口,一种是外形美的美女IGoodBodyGirl,这类美女的特
* 点就是脸蛋和身材极棒,超一流,但是没有审美素质,比如随地吐痰,文化程度比较低;另
* 外一种是气质美的美女IGreatTemperamentGirl,谈吐和修养都非常高。我们把一个比较臃肿
* 的接口拆分成了两个专门的接口,灵活性提高了,可维护性也增加了,不管以后是要外形美
* 的美女还是气质美的美女都可以轻松地通过PettyGirl定义。
*/
| QuanWenLan/designPattern | src/main/java/principle/interfaceisolation/version1/Client.java | 852 | /**
* 思考一下IPettyGirl这个接口,这个接口是否做到了最优化设计?答案是没有,还可以对接口进行优化。
* 我们的审美观点都在改变,美女的定义也在变化。唐朝的杨贵妃如果活在现在这个年代
* 非羞愧而死不可,为什么?胖呀!但是胖并不影响她入选中国四大美女,说明当时的审美观
* 与现在是有差异的。当然,随着时代的发展我们的审美观也在变化,当你发现有一个女孩,
* 脸蛋不怎么样,身材也一般般,但是气质非常好,我相信大部分人都会把这样的女孩叫美
* 女,审美素质提升了,就产生了气质型美女,但是我们的接口却定义了美女必须是三者都具
* 备,按照这个标准,气质型美女就不能算美女,那怎么办?可能你要说了,我重新扩展一个
* 美女类,只实现greatTemperament方法,其他两个方法置空,什么都不写,不就可以了吗?
* 聪明,但是行不通!为什么呢?星探AbstractSearcher依赖的是IPettyGirl接口,它有三个方
* 法,你只实现了两个方法,星探的方法是不是要修改?我们上面的程序打印出来的信息少了
* 两条,还让星探怎么去辨别是不是美女呢?
*
* 分析到这里,我们发现接口IPettyGirl的设计是有缺陷的,过于庞大了,容纳了一些可变
* 的因素,根据接口隔离原则,星探AbstractSearcher应该依赖于具有部分特质的女孩子,而我
* 们却把这些特质都封装了起来,放到了一个接口中,封装过度了!
*
* 把原IPettyGirl接口拆分为两个接口,一种是外形美的美女IGoodBodyGirl,这类美女的特
* 点就是脸蛋和身材极棒,超一流,但是没有审美素质,比如随地吐痰,文化程度比较低;另
* 外一种是气质美的美女IGreatTemperamentGirl,谈吐和修养都非常高。我们把一个比较臃肿
* 的接口拆分成了两个专门的接口,灵活性提高了,可维护性也增加了,不管以后是要外形美
* 的美女还是气质美的美女都可以轻松地通过PettyGirl定义。
*/ | block_comment | zh-cn | package principle.interfaceisolation.version1;
import principle.interfaceisolation.version1.AbstractSearcher;
import principle.interfaceisolation.version1.IPettyGirl;
import principle.interfaceisolation.version1.PettyGirl;
import principle.interfaceisolation.version1.Searcher;
import principle.interfaceisolation.version2.IGoodBodyGirl;
import principle.interfaceisolation.version2.PettyGirl2;
/**
* @author Lan
* @createTime 2024-03-13 11:18
**/
public class Client {
public static void main(String[] args) {
//定义一个美女
IPettyGirl yanYan = new PettyGirl("嫣嫣");
AbstractSearcher searcher = new Searcher(yanYan);
searcher.show();
}
}
/**
* 思考一 <SUF>*/
| false | 660 | 498 | 852 | 648 | 694 | 505 | 852 | 648 | 1,245 | 1,022 | true | true | true | true | true | false |
2310_2 | package com.ruoyi.erp.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
/**
* 库存客户对象 erp_client
*
* @author kuaizi
* @date 2021-10-25
*/
public class ErpClient extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 客户ID */
private Long id;
/** 客户名称 */
@Excel(name = "客户名称")
private String clientNickname;
/** 客户手机 */
@Excel(name = "客户手机")
private String clientPhone;
/** 客户收货地址 */
@Excel(name = "客户收货地址")
private String shippingAddress;
/** 性别 先生:0 女士:1 */
@Excel(name = "性别 先生:0 女士:1")
private Long gender;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setClientNickname(String clientNickname)
{
this.clientNickname = clientNickname;
}
public String getClientNickname()
{
return clientNickname;
}
public void setClientPhone(String clientPhone)
{
this.clientPhone = clientPhone;
}
public String getClientPhone()
{
return clientPhone;
}
public void setShippingAddress(String shippingAddress)
{
this.shippingAddress = shippingAddress;
}
public String getShippingAddress()
{
return shippingAddress;
}
public void setGender(Long gender)
{
this.gender = gender;
}
public Long getGender()
{
return gender;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("clientNickname", getClientNickname())
.append("clientPhone", getClientPhone())
.append("shippingAddress", getShippingAddress())
.append("gender", getGender())
.toString();
}
}
| Quart233/ruoyi-erp | ruoyi-system/src/main/java/com/ruoyi/erp/domain/ErpClient.java | 535 | /** 客户名称 */ | block_comment | zh-cn | package com.ruoyi.erp.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
/**
* 库存客户对象 erp_client
*
* @author kuaizi
* @date 2021-10-25
*/
public class ErpClient extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 客户ID */
private Long id;
/** 客户名 <SUF>*/
@Excel(name = "客户名称")
private String clientNickname;
/** 客户手机 */
@Excel(name = "客户手机")
private String clientPhone;
/** 客户收货地址 */
@Excel(name = "客户收货地址")
private String shippingAddress;
/** 性别 先生:0 女士:1 */
@Excel(name = "性别 先生:0 女士:1")
private Long gender;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setClientNickname(String clientNickname)
{
this.clientNickname = clientNickname;
}
public String getClientNickname()
{
return clientNickname;
}
public void setClientPhone(String clientPhone)
{
this.clientPhone = clientPhone;
}
public String getClientPhone()
{
return clientPhone;
}
public void setShippingAddress(String shippingAddress)
{
this.shippingAddress = shippingAddress;
}
public String getShippingAddress()
{
return shippingAddress;
}
public void setGender(Long gender)
{
this.gender = gender;
}
public Long getGender()
{
return gender;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("clientNickname", getClientNickname())
.append("clientPhone", getClientPhone())
.append("shippingAddress", getShippingAddress())
.append("gender", getGender())
.toString();
}
}
| false | 492 | 6 | 535 | 5 | 582 | 4 | 535 | 5 | 683 | 7 | false | false | false | false | false | true |
23246_35 | package GUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
//创建窗口
JFrame f = new JFrame("ImageMatting");
//容器放进窗口
Container contentPane = new Container();
f.setContentPane(contentPane);
//设置容器布局
contentPane.setLayout(new BorderLayout());//边界布局
JPanel p1 = new JPanel();
//PS: 设置面板背景色为蓝色,如果不引入AWT包,程序将出错,可以试试看
p1.setBackground(Color.GRAY);
p1.setSize(200,800); //设置面板对象大小
JButton b1 = new JButton("查看所有图片");
b1.setBounds(25,10,150,50);
JButton b2 = new JButton("Start!");
b2.setBounds(25,500,150,50);
//JLabel l = new JLabel("请输入想要处理的图片:");
p1.add(b1);
p1.add(b2);
//p1.add(l);
contentPane.add(p1, BorderLayout.WEST);
JPanel p2 = new JPanel();
contentPane.add(p2, BorderLayout.EAST);
//设置图片路径变量
String str = "C:\\Users\\pc\\Desktop\\image_matting-main\\image_matting-main\\data";//用来打开所有图片文件夹
//b1鼠标点击事件
b1.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {//鼠标点击事件
try {
File file = new File(str); // 创建文件对象
Desktop.getDesktop().open(file); // 启动已在本机桌面上注册的关联应用程序,打开文件文件file。
} catch (IOException | NullPointerException e1) { // 异常处理
System.err.println(e1);
}
}//鼠标点击事件结束
});//按钮监听结束
//b2鼠标点击事件
b2.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {//鼠标点击事件
//接收python给的图地址
try {
//输入
Scanner myscanner = new Scanner(System.in);
String a;//传给python的变量——图片名
System.out.println("请输入图片名:");
a = myscanner.next();
p2.removeAll();//清除面板2中内容
//执行python
String[] args1 = new String[] { "python", "D:\\codespython\\test.py", a };//传参数
//String[] args1 = new String[] { "python", "C:\\Users\\pc\\Desktop\\image_matting-main (1)\\image_matting-main\\main.py", a };//传参数
Process proc = Runtime.getRuntime().exec(args1);// 准备进程 —— 执行py文件
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));//进程
String line = null;
line = in.readLine();
System.out.println(line);//line是返回的地址
//准备图片
int width = 775;
int height = 755;
//创建图片
ImageIcon image = new ImageIcon(line);
//创建面板
image.setImage(image.getImage().getScaledInstance(width,height,Image.SCALE_DEFAULT));
//创建标签,并加入图片
JLabel label = new JLabel(image, JLabel.CENTER);
//面板加入标签
p2.add(label);
//刷新
f.setVisible(false);
f.setVisible(true);
in.close();//关闭BufferedReader
proc.waitFor();//进程proc等待
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}//鼠标点击事件结束
});
//写在最后
//设置号窗口位置
f.setLocation(400,100);
//设置窗口大小
f.setSize(1000,800);
//不能改变大小
f.setResizable(false);
//显示窗口
f.setVisible(true);
}
}
| Quinn777/image_matting | gui.java | 1,197 | //写在最后 | line_comment | zh-cn | package GUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
//创建窗口
JFrame f = new JFrame("ImageMatting");
//容器放进窗口
Container contentPane = new Container();
f.setContentPane(contentPane);
//设置容器布局
contentPane.setLayout(new BorderLayout());//边界布局
JPanel p1 = new JPanel();
//PS: 设置面板背景色为蓝色,如果不引入AWT包,程序将出错,可以试试看
p1.setBackground(Color.GRAY);
p1.setSize(200,800); //设置面板对象大小
JButton b1 = new JButton("查看所有图片");
b1.setBounds(25,10,150,50);
JButton b2 = new JButton("Start!");
b2.setBounds(25,500,150,50);
//JLabel l = new JLabel("请输入想要处理的图片:");
p1.add(b1);
p1.add(b2);
//p1.add(l);
contentPane.add(p1, BorderLayout.WEST);
JPanel p2 = new JPanel();
contentPane.add(p2, BorderLayout.EAST);
//设置图片路径变量
String str = "C:\\Users\\pc\\Desktop\\image_matting-main\\image_matting-main\\data";//用来打开所有图片文件夹
//b1鼠标点击事件
b1.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {//鼠标点击事件
try {
File file = new File(str); // 创建文件对象
Desktop.getDesktop().open(file); // 启动已在本机桌面上注册的关联应用程序,打开文件文件file。
} catch (IOException | NullPointerException e1) { // 异常处理
System.err.println(e1);
}
}//鼠标点击事件结束
});//按钮监听结束
//b2鼠标点击事件
b2.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {//鼠标点击事件
//接收python给的图地址
try {
//输入
Scanner myscanner = new Scanner(System.in);
String a;//传给python的变量——图片名
System.out.println("请输入图片名:");
a = myscanner.next();
p2.removeAll();//清除面板2中内容
//执行python
String[] args1 = new String[] { "python", "D:\\codespython\\test.py", a };//传参数
//String[] args1 = new String[] { "python", "C:\\Users\\pc\\Desktop\\image_matting-main (1)\\image_matting-main\\main.py", a };//传参数
Process proc = Runtime.getRuntime().exec(args1);// 准备进程 —— 执行py文件
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));//进程
String line = null;
line = in.readLine();
System.out.println(line);//line是返回的地址
//准备图片
int width = 775;
int height = 755;
//创建图片
ImageIcon image = new ImageIcon(line);
//创建面板
image.setImage(image.getImage().getScaledInstance(width,height,Image.SCALE_DEFAULT));
//创建标签,并加入图片
JLabel label = new JLabel(image, JLabel.CENTER);
//面板加入标签
p2.add(label);
//刷新
f.setVisible(false);
f.setVisible(true);
in.close();//关闭BufferedReader
proc.waitFor();//进程proc等待
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}//鼠标点击事件结束
});
//写在 <SUF>
//设置号窗口位置
f.setLocation(400,100);
//设置窗口大小
f.setSize(1000,800);
//不能改变大小
f.setResizable(false);
//显示窗口
f.setVisible(true);
}
}
| false | 1,017 | 4 | 1,197 | 4 | 1,324 | 3 | 1,197 | 4 | 1,733 | 5 | false | false | false | false | false | true |
51967_2 | import java.util.*;
public class State implements Comparable<State>{
/*
* 状态 id
*/
Set<Integer> id = new TreeSet<>();
/*
* 是否为结束态
*/
boolean isEnd;
/*
* 优先级 优先级高的先匹配
*/
int Priority = 0;
/*
* 捕获起始态
*/
boolean isCapstart = false;
/*
* 捕获结束态
*/
boolean isCapend = false;
/*
*匹配字符串头
*/
boolean isStrs = false;
/*
* 匹配字符串尾
*/
boolean isStre = false;
@Override
public String toString() {
String re = "";
for (int i : id) {
re += (i+".");
}
re = re.substring(0, re.length() - 1);
if (isStrs) re = 'A' + re;
if (isStre) re = 'B' + re;
return re;
}
@Override
public boolean equals(Object obj) {
State state = (State)obj;
return this.id.equals(state.id);
}
//id 相同 hashCode 就相同
@Override
public int hashCode() {
int hash = 0, k = 1;
for (int i : id) {
hash += (k * i);
k *= 10;
}
return hash;
}
@Override
public int compareTo(State o) {
if (this.Priority > o.Priority)
return -1;
else if (this.Priority < o.Priority)
return 1;
else
return 0;
}
}
| Qzhangqi/Regex | src/State.java | 391 | /*
* 优先级 优先级高的先匹配
*/ | block_comment | zh-cn | import java.util.*;
public class State implements Comparable<State>{
/*
* 状态 id
*/
Set<Integer> id = new TreeSet<>();
/*
* 是否为结束态
*/
boolean isEnd;
/*
* 优先级 <SUF>*/
int Priority = 0;
/*
* 捕获起始态
*/
boolean isCapstart = false;
/*
* 捕获结束态
*/
boolean isCapend = false;
/*
*匹配字符串头
*/
boolean isStrs = false;
/*
* 匹配字符串尾
*/
boolean isStre = false;
@Override
public String toString() {
String re = "";
for (int i : id) {
re += (i+".");
}
re = re.substring(0, re.length() - 1);
if (isStrs) re = 'A' + re;
if (isStre) re = 'B' + re;
return re;
}
@Override
public boolean equals(Object obj) {
State state = (State)obj;
return this.id.equals(state.id);
}
//id 相同 hashCode 就相同
@Override
public int hashCode() {
int hash = 0, k = 1;
for (int i : id) {
hash += (k * i);
k *= 10;
}
return hash;
}
@Override
public int compareTo(State o) {
if (this.Priority > o.Priority)
return -1;
else if (this.Priority < o.Priority)
return 1;
else
return 0;
}
}
| false | 383 | 15 | 391 | 15 | 443 | 16 | 391 | 15 | 513 | 30 | false | false | false | false | false | true |
58179_6 | package moe.feo.bbstoper.gui;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.SkullType;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import moe.feo.bbstoper.BBSToper;
import moe.feo.bbstoper.Crawler;
import moe.feo.bbstoper.Message;
import moe.feo.bbstoper.Option;
import moe.feo.bbstoper.Poster;
import moe.feo.bbstoper.Util;
import moe.feo.bbstoper.sql.SQLer;
public class GUI {
private static SQLer sql;
private Inventory inv;
public static String getTitle() {// 获取插件的gui标题必须用此方法,因为用户可能会修改gui标题
String title = Message.GUI_TITLE.getString().replaceAll("%PREFIX%", Message.PREFIX.getString());
return title;
}
public GUI(Player player) {
createGui(player);
Bukkit.getScheduler().runTask(BBSToper.getInstance(), () -> player.openInventory(inv));
}
class BBSToperGUIHolder implements InventoryHolder {// 定义一个Holder用于识别此插件的GUI
@Override
public Inventory getInventory() {
return getGui();
}
}
@SuppressWarnings("deprecation")
public void createGui(Player player) {
InventoryHolder holder = new BBSToperGUIHolder();
this.setGui(Bukkit.createInventory(holder, InventoryType.CHEST, getTitle()));
for (int i = 0; i < inv.getSize(); i++) {// 设置边框
if (i > 9 && i < 17)
continue;
inv.setItem(i, getRandomPane());
}
ItemStack skull;
try {
skull = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal());
} catch (NoSuchFieldError e) {// 某些高版本服务端不兼容旧版写法
skull = new ItemStack(Material.getMaterial("PLAYER_HEAD"), 1);
}
SkullMeta skullmeta = (SkullMeta) skull.getItemMeta();// 玩家头颅
if (Option.GUI_DISPLAYHEADSKIN.getBoolean()) {// 如果开启了头颅显示,才会设置头颅的所有者
try {
skullmeta.setOwningPlayer(player);
} catch (NoSuchMethodError e) {// 这里为了照顾低版本
skullmeta.setOwner(player.getName());
}
}
skullmeta.setDisplayName(Message.GUI_SKULL.getString().replaceAll("%PLAYER%", player.getName()));
List<String> skulllores = new ArrayList<String>();
Poster poster = sql.getPoster(player.getUniqueId().toString());
if (poster == null) {
skulllores.add(Message.GUI_NOTBOUND.getString());
skulllores.add(Message.GUI_CLICKBOUND.getString());
} else {
skulllores.add(Message.GUI_BBSID.getString().replaceAll("%BBSID%", poster.getBbsname()));
skulllores.add(Message.GUI_POSTTIMES.getString().replaceAll("%TIMES%", "" + poster.getTopStates().size()));
skulllores.add(Message.GUI_CLICKREBOUND.getString());
}
skullmeta.setLore(skulllores);
skull.setItemMeta(skullmeta);
inv.setItem(12, skull);
ItemStack sunflower;
try {
sunflower = new ItemStack(Material.DOUBLE_PLANT);
} catch (NoSuchFieldError e) {// 某些高版本服务端不兼容旧版写法
sunflower = new ItemStack(Material.getMaterial("SUNFLOWER"));
}
ItemMeta sunflowermeta = sunflower.getItemMeta();
sunflowermeta.setDisplayName(Message.GUI_REWARDS.getString());
List<String> sunflowerlores = new ArrayList<String>(Message.GUI_REWARDSINFO.getStringList());// 自定义奖励信息
if (sunflowerlores.isEmpty()) {// 如果没有自定义奖励信息
sunflowerlores.addAll(Option.REWARD_COMMANDS.getStringList());// 直接显示命令
if (Option.REWARD_INCENTIVEREWARD_ENABLE.getBoolean()) {
sunflowerlores.add(Message.GUI_INCENTIVEREWARDS.getString());// 激励奖励
sunflowerlores.addAll(Option.REWARD_INCENTIVEREWARD_COMMANDS.getStringList());// 激励奖励命令
}
if (Option.REWARD_OFFDAYREWARD_ENABLE.getBoolean()) {
sunflowerlores.add(Message.GUI_OFFDAYREWARDS.getString());// 休息日奖励
sunflowerlores.addAll(Option.REWARD_OFFDAYREWARD_COMMANDS.getStringList()); // 休息日奖励命令
}
}
sunflowerlores.add(Message.GUI_CLICKGET.getString());
sunflowermeta.setLore(sunflowerlores);
sunflower.setItemMeta(sunflowermeta);
inv.setItem(13, sunflower);
ItemStack star = new ItemStack(Material.NETHER_STAR);
ItemMeta starmeta = star.getItemMeta();
starmeta.setDisplayName(Message.GUI_TOPS.getString());
List<String> starlores = new ArrayList<String>();
List<Poster> listposter = sql.getTopPosters();
for (int i = 0; i < listposter.size(); i++) {
if (i >= Option.GUI_TOPPLAYERS.getInt())
break;
starlores.add(Message.POSTERPLAYER.getString() + ":" + listposter.get(i).getName() + " "
+ Message.POSTERID.getString() + ":" + listposter.get(i).getBbsname() + " "
+ Message.POSTERNUM.getString() + ":" + listposter.get(i).getCount());
}
starmeta.setLore(starlores);
star.setItemMeta(starmeta);
inv.setItem(14, star);
ItemStack compass = new ItemStack(Material.COMPASS);
ItemMeta compassmeta = compass.getItemMeta();
compassmeta.setDisplayName(Message.GUI_PAGESTATE.getString());
List<String> compasslores = new ArrayList<String>();
compasslores.add(Message.GUI_PAGEID.getString().replaceAll("%PAGEID%", Option.MCBBS_URL.getString()));
Crawler crawler = new Crawler();
if (crawler.visible) {// 如果帖子可视,就获取帖子最近一次顶贴
if (crawler.Time.size() > 0) { // 如果从没有人顶帖,就以“----”代替上次顶帖时间(原来不加判断直接get会报索引范围错误)
compasslores.add(Message.GUI_LASTPOST.getString().replaceAll("%TIME%", crawler.Time.get(0)));
} else {
compasslores.add(Message.GUI_LASTPOST.getString().replaceAll("%TIME%", "----"));
}
} else {
compasslores.add(Message.GUI_PAGENOTVISIBLE.getString());
}
String extra = Util.getExtraReward(crawler);
if (extra != null) {
String extrarewards = Message.GUI_EXTRAREWARDS.getString().replaceAll("%EXTRA%", extra);
compasslores.add(extrarewards);
}
compasslores.add(Message.GUI_CLICKOPEN.getString());
compassmeta.setLore(compasslores);
compass.setItemMeta(compassmeta);
inv.setItem(22, compass);
}
public ItemStack getRandomPane() {// 获取随机一种颜色的玻璃板
short data = (short)(Math.random()* 16);// 这会随机取出0-15的数据值
while (data == 8) {// 8号亮灰色染色玻璃板根本没有颜色
data = (short)(Math.random()* 16);
}
ItemStack frame;
try {
frame = new ItemStack(Material.STAINED_GLASS_PANE, 1, data);
} catch (NoSuchFieldError e) {// 某些高版本服务端不兼容旧版写法
String[] glasspanes = {"WHITE_STAINED_GLASS_PANE", "ORANGE_STAINED_GLASS_PANE", "MAGENTA_STAINED_GLASS_PANE",
"LIGHT_BLUE_STAINED_GLASS_PANE", "YELLOW_STAINED_GLASS_PANE", "LIME_STAINED_GLASS_PANE", "PINK_STAINED_GLASS_PANE",
"GRAY_STAINED_GLASS_PANE", "LIGHT_GRAY_STAINED_GLASS_PANE", "CYAN_STAINED_GLASS_PANE", "PURPLE_STAINED_GLASS_PANE",
"BLUE_STAINED_GLASS_PANE", "BROWN_STAINED_GLASS_PANE", "GREEN_STAINED_GLASS_PANE", "RED_STAINED_GLASS_PANE",
"BLACK_STAINED_GLASS_PANE"};
frame = new ItemStack(Material.getMaterial(glasspanes[data]), 1);
}
ItemMeta framemeta = frame.getItemMeta();
framemeta.setDisplayName(Message.GUI_FRAME.getString());
frame.setItemMeta(framemeta);
return frame;
}
public Inventory getGui() {
return inv;
}
public void setGui(Inventory inv) {
this.inv = inv;
}
public static void setSQLer(SQLer sql) {
GUI.sql = sql;
}
}
| R-Josef/BBSToper | src/moe/feo/bbstoper/gui/GUI.java | 2,518 | // 这里为了照顾低版本 | line_comment | zh-cn | package moe.feo.bbstoper.gui;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.SkullType;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import moe.feo.bbstoper.BBSToper;
import moe.feo.bbstoper.Crawler;
import moe.feo.bbstoper.Message;
import moe.feo.bbstoper.Option;
import moe.feo.bbstoper.Poster;
import moe.feo.bbstoper.Util;
import moe.feo.bbstoper.sql.SQLer;
public class GUI {
private static SQLer sql;
private Inventory inv;
public static String getTitle() {// 获取插件的gui标题必须用此方法,因为用户可能会修改gui标题
String title = Message.GUI_TITLE.getString().replaceAll("%PREFIX%", Message.PREFIX.getString());
return title;
}
public GUI(Player player) {
createGui(player);
Bukkit.getScheduler().runTask(BBSToper.getInstance(), () -> player.openInventory(inv));
}
class BBSToperGUIHolder implements InventoryHolder {// 定义一个Holder用于识别此插件的GUI
@Override
public Inventory getInventory() {
return getGui();
}
}
@SuppressWarnings("deprecation")
public void createGui(Player player) {
InventoryHolder holder = new BBSToperGUIHolder();
this.setGui(Bukkit.createInventory(holder, InventoryType.CHEST, getTitle()));
for (int i = 0; i < inv.getSize(); i++) {// 设置边框
if (i > 9 && i < 17)
continue;
inv.setItem(i, getRandomPane());
}
ItemStack skull;
try {
skull = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal());
} catch (NoSuchFieldError e) {// 某些高版本服务端不兼容旧版写法
skull = new ItemStack(Material.getMaterial("PLAYER_HEAD"), 1);
}
SkullMeta skullmeta = (SkullMeta) skull.getItemMeta();// 玩家头颅
if (Option.GUI_DISPLAYHEADSKIN.getBoolean()) {// 如果开启了头颅显示,才会设置头颅的所有者
try {
skullmeta.setOwningPlayer(player);
} catch (NoSuchMethodError e) {// 这里 <SUF>
skullmeta.setOwner(player.getName());
}
}
skullmeta.setDisplayName(Message.GUI_SKULL.getString().replaceAll("%PLAYER%", player.getName()));
List<String> skulllores = new ArrayList<String>();
Poster poster = sql.getPoster(player.getUniqueId().toString());
if (poster == null) {
skulllores.add(Message.GUI_NOTBOUND.getString());
skulllores.add(Message.GUI_CLICKBOUND.getString());
} else {
skulllores.add(Message.GUI_BBSID.getString().replaceAll("%BBSID%", poster.getBbsname()));
skulllores.add(Message.GUI_POSTTIMES.getString().replaceAll("%TIMES%", "" + poster.getTopStates().size()));
skulllores.add(Message.GUI_CLICKREBOUND.getString());
}
skullmeta.setLore(skulllores);
skull.setItemMeta(skullmeta);
inv.setItem(12, skull);
ItemStack sunflower;
try {
sunflower = new ItemStack(Material.DOUBLE_PLANT);
} catch (NoSuchFieldError e) {// 某些高版本服务端不兼容旧版写法
sunflower = new ItemStack(Material.getMaterial("SUNFLOWER"));
}
ItemMeta sunflowermeta = sunflower.getItemMeta();
sunflowermeta.setDisplayName(Message.GUI_REWARDS.getString());
List<String> sunflowerlores = new ArrayList<String>(Message.GUI_REWARDSINFO.getStringList());// 自定义奖励信息
if (sunflowerlores.isEmpty()) {// 如果没有自定义奖励信息
sunflowerlores.addAll(Option.REWARD_COMMANDS.getStringList());// 直接显示命令
if (Option.REWARD_INCENTIVEREWARD_ENABLE.getBoolean()) {
sunflowerlores.add(Message.GUI_INCENTIVEREWARDS.getString());// 激励奖励
sunflowerlores.addAll(Option.REWARD_INCENTIVEREWARD_COMMANDS.getStringList());// 激励奖励命令
}
if (Option.REWARD_OFFDAYREWARD_ENABLE.getBoolean()) {
sunflowerlores.add(Message.GUI_OFFDAYREWARDS.getString());// 休息日奖励
sunflowerlores.addAll(Option.REWARD_OFFDAYREWARD_COMMANDS.getStringList()); // 休息日奖励命令
}
}
sunflowerlores.add(Message.GUI_CLICKGET.getString());
sunflowermeta.setLore(sunflowerlores);
sunflower.setItemMeta(sunflowermeta);
inv.setItem(13, sunflower);
ItemStack star = new ItemStack(Material.NETHER_STAR);
ItemMeta starmeta = star.getItemMeta();
starmeta.setDisplayName(Message.GUI_TOPS.getString());
List<String> starlores = new ArrayList<String>();
List<Poster> listposter = sql.getTopPosters();
for (int i = 0; i < listposter.size(); i++) {
if (i >= Option.GUI_TOPPLAYERS.getInt())
break;
starlores.add(Message.POSTERPLAYER.getString() + ":" + listposter.get(i).getName() + " "
+ Message.POSTERID.getString() + ":" + listposter.get(i).getBbsname() + " "
+ Message.POSTERNUM.getString() + ":" + listposter.get(i).getCount());
}
starmeta.setLore(starlores);
star.setItemMeta(starmeta);
inv.setItem(14, star);
ItemStack compass = new ItemStack(Material.COMPASS);
ItemMeta compassmeta = compass.getItemMeta();
compassmeta.setDisplayName(Message.GUI_PAGESTATE.getString());
List<String> compasslores = new ArrayList<String>();
compasslores.add(Message.GUI_PAGEID.getString().replaceAll("%PAGEID%", Option.MCBBS_URL.getString()));
Crawler crawler = new Crawler();
if (crawler.visible) {// 如果帖子可视,就获取帖子最近一次顶贴
if (crawler.Time.size() > 0) { // 如果从没有人顶帖,就以“----”代替上次顶帖时间(原来不加判断直接get会报索引范围错误)
compasslores.add(Message.GUI_LASTPOST.getString().replaceAll("%TIME%", crawler.Time.get(0)));
} else {
compasslores.add(Message.GUI_LASTPOST.getString().replaceAll("%TIME%", "----"));
}
} else {
compasslores.add(Message.GUI_PAGENOTVISIBLE.getString());
}
String extra = Util.getExtraReward(crawler);
if (extra != null) {
String extrarewards = Message.GUI_EXTRAREWARDS.getString().replaceAll("%EXTRA%", extra);
compasslores.add(extrarewards);
}
compasslores.add(Message.GUI_CLICKOPEN.getString());
compassmeta.setLore(compasslores);
compass.setItemMeta(compassmeta);
inv.setItem(22, compass);
}
public ItemStack getRandomPane() {// 获取随机一种颜色的玻璃板
short data = (short)(Math.random()* 16);// 这会随机取出0-15的数据值
while (data == 8) {// 8号亮灰色染色玻璃板根本没有颜色
data = (short)(Math.random()* 16);
}
ItemStack frame;
try {
frame = new ItemStack(Material.STAINED_GLASS_PANE, 1, data);
} catch (NoSuchFieldError e) {// 某些高版本服务端不兼容旧版写法
String[] glasspanes = {"WHITE_STAINED_GLASS_PANE", "ORANGE_STAINED_GLASS_PANE", "MAGENTA_STAINED_GLASS_PANE",
"LIGHT_BLUE_STAINED_GLASS_PANE", "YELLOW_STAINED_GLASS_PANE", "LIME_STAINED_GLASS_PANE", "PINK_STAINED_GLASS_PANE",
"GRAY_STAINED_GLASS_PANE", "LIGHT_GRAY_STAINED_GLASS_PANE", "CYAN_STAINED_GLASS_PANE", "PURPLE_STAINED_GLASS_PANE",
"BLUE_STAINED_GLASS_PANE", "BROWN_STAINED_GLASS_PANE", "GREEN_STAINED_GLASS_PANE", "RED_STAINED_GLASS_PANE",
"BLACK_STAINED_GLASS_PANE"};
frame = new ItemStack(Material.getMaterial(glasspanes[data]), 1);
}
ItemMeta framemeta = frame.getItemMeta();
framemeta.setDisplayName(Message.GUI_FRAME.getString());
frame.setItemMeta(framemeta);
return frame;
}
public Inventory getGui() {
return inv;
}
public void setGui(Inventory inv) {
this.inv = inv;
}
public static void setSQLer(SQLer sql) {
GUI.sql = sql;
}
}
| false | 2,022 | 8 | 2,518 | 9 | 2,303 | 7 | 2,518 | 9 | 3,286 | 17 | false | false | false | false | false | true |
31121_4 | package moe.feo.pixivcrawler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class Crawler {
private Map<String, String> cookies = new HashMap<String, String>();
private Config config;
private String jarpath;
public SQLiter db;
public void setJarPath(String path) {
this.jarpath = path;
}
public Crawler(Config config, SQLiter db) {
this.config = config;
this.db = db;
}
public void addCookie(String key, String value) {
cookies.put(key, value);
}
public String resolveListPage(String url) {
String nextpageurl = null;
try {
Response res = null;
while (true) {
try {
res = Jsoup.connect(url).cookies(cookies).method(Method.GET).execute();
break;
} catch (SocketTimeoutException e) {
System.out.println("请求图片列表页面超时, 将重试.");
} catch (SSLHandshakeException e) {
System.out.println("请求图片列表页面被拒绝, 将重试.");
} catch (SSLException e) {
System.out.println("请求图片列表页面被关闭, 将重试.");
} catch (ConnectException e) {// cookie错误将会超时
System.out.println("连接超时, 请检查cookie是否错误或过期.");
} catch (SocketException e) {
System.out.println("意外结束, 将重试.");
} catch (HttpStatusException e) {// cookie不正确或没有将返回错误码
System.out.println("HTTP状态错误" + e.getStatusCode() + " 请填写正确的cookie.");
}
}
Document doc = res.parse();
Elements pages = doc.select("#wrapper").select("div.layout-body").select("div")
.select("div.ui-fixed-container").select("div").select("nav:nth-child(2)").select("ul")
.select("li.after").select("a");
Element nextpage = null;
try {
nextpage = pages.get(0);
} catch (IndexOutOfBoundsException e) {
System.out.println("网页格式错误,请检查cookie是否已经过期 (或者该榜单已被爬取完毕) .");
System.exit(1);
}
nextpageurl = nextpage.absUrl("href");
Elements images = doc.select("#wrapper").select("div.layout-body").select("div")
.select("div.ranking-items-container").select("div.ranking-items.adjust")
.select("section.ranking-item");
for (Element image : images) {
String dataid = image.attr("data-id");
Element imagepage = image.select("div.ranking-image-item").select("a").get(0);
String imagepageurl = imagepage.absUrl("href");
System.out.println("===============" + dataid + "===============");
System.out.println("正在爬取: " + imagepageurl);
resolveImagePage(imagepageurl, dataid);
}
config.setValue("startpage", url);
config.Save();
} catch (IOException e) {
e.printStackTrace();
return nextpageurl;
}
System.out.println(nextpageurl);
return nextpageurl;
}
public void resolveImagePage(String url, String dataid) {
int amount = db.checkArtworks(Integer.parseInt(dataid));// 尝试获取一个值
if (amount == 0) {// 如果为0说明数据库中没有这个数据
System.out.println("数据库中未查到此图片页面的信息, 继续下载操作.");
} else {// 如果不是0说明这些图片已经下载过了
System.out.println("数据库中已查到此图片页面的信息, 图片数量为" + amount + ", 自动跳过.");
return;
}
try {
Response res = null;
while (true) {
try {
res = Jsoup.connect(url).cookies(cookies).method(Method.GET).execute();
break;
} catch (SocketTimeoutException e) {
System.out.println("请求图片页面超时, 将重试.");
} catch (SSLHandshakeException e) {
System.out.println("请求图片页面被拒绝, 将重试.");
} catch (SSLException e) {
System.out.println("请求图片页面被关闭, 将重试.");
} catch (ConnectException e) {// cookie错误将会超时, 但是其实可以不带cookie
System.out.println("连接超时, 请检查cookie是否错误或过期.");
} catch (SocketException e) {
System.out.println("意外结束, 将重试.");
}
}
Document doc = res.parse();
Element meta = doc.select("#meta-preload-data").first();
String content = meta.attr("content");
JSONObject obj = JSON.parseObject(content);
int pagecount = obj.getJSONObject("illust").getJSONObject(dataid).getIntValue("pageCount");
String p0url = obj.getJSONObject("illust").getJSONObject(dataid).getJSONObject("urls")
.getString("original");
for (int i = 0; i < pagecount; i++) {
String imgurl = null;
if (i == 0) {
imgurl = p0url;
} else {
imgurl = p0url.replaceAll("p0", "p" + i);
}
String filename = imgurl.substring(imgurl.lastIndexOf("/") + 1);
// 这里要去掉jarpath末尾的"/"
String imagesavepath = config.getString("imagesavepath").replace("%HERE%",
jarpath.substring(0, jarpath.length() - 1));
File imgfile = Util.createFile(imagesavepath, filename);
Response resimg = null;
while (true) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
resimg = Jsoup.connect(imgurl).cookies(cookies).ignoreContentType(true).maxBodySize(1073741824)
.referrer("https://www.pixiv.net/artworks/" + dataid).execute();
in = resimg.bodyStream();
out = new BufferedOutputStream(new FileOutputStream(imgfile));
byte[] bytes = new byte[1024];
int total = 0;
int count = 0;
while ((count = in.read(bytes)) != -1) {
out.write(bytes, 0, count);
total = total + count;
}
System.out.println("文件" + filename + "保存完成, 共收到" + total + "字节.");
break;
} catch (SocketTimeoutException e) {
System.out.println("请求图片超时, 将重试.");
} catch (SSLHandshakeException e) {
System.out.println("请求图片被拒绝, 将重试.");
} catch (SSLException e) {
System.out.println("请求图片被关闭, 将重试.");
} catch (ConnectException e) {// cookie错误将会超时, 但是其实可以不带cookie
System.out.println("连接超时, 请检查cookie是否错误或过期.");
} catch (SocketException e) {
System.out.println("意外结束, 将重试.");
} catch (HttpStatusException e) {// 防止有画师上传的同一个帖子内文件格式不同
if (imgurl.contains(".jpg")) {
imgurl = imgurl.replaceAll(".jpg", ".png");
} else if (imgurl.contains(".png")) {
imgurl = imgurl.replaceAll(".png", ".jpg");
}
System.out.println("HTTP状态错误:" + e.getStatusCode() + " 将尝试另一后缀名.");
} finally {
try {
in.close();
out.close();
} catch (NullPointerException | SSLException e) {
}
}
}
}
db.addArtworks(Integer.parseInt(dataid), pagecount);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| R-Josef/PixivCrawler | src/moe/feo/pixivcrawler/Crawler.java | 2,218 | // 如果不是0说明这些图片已经下载过了 | line_comment | zh-cn | package moe.feo.pixivcrawler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class Crawler {
private Map<String, String> cookies = new HashMap<String, String>();
private Config config;
private String jarpath;
public SQLiter db;
public void setJarPath(String path) {
this.jarpath = path;
}
public Crawler(Config config, SQLiter db) {
this.config = config;
this.db = db;
}
public void addCookie(String key, String value) {
cookies.put(key, value);
}
public String resolveListPage(String url) {
String nextpageurl = null;
try {
Response res = null;
while (true) {
try {
res = Jsoup.connect(url).cookies(cookies).method(Method.GET).execute();
break;
} catch (SocketTimeoutException e) {
System.out.println("请求图片列表页面超时, 将重试.");
} catch (SSLHandshakeException e) {
System.out.println("请求图片列表页面被拒绝, 将重试.");
} catch (SSLException e) {
System.out.println("请求图片列表页面被关闭, 将重试.");
} catch (ConnectException e) {// cookie错误将会超时
System.out.println("连接超时, 请检查cookie是否错误或过期.");
} catch (SocketException e) {
System.out.println("意外结束, 将重试.");
} catch (HttpStatusException e) {// cookie不正确或没有将返回错误码
System.out.println("HTTP状态错误" + e.getStatusCode() + " 请填写正确的cookie.");
}
}
Document doc = res.parse();
Elements pages = doc.select("#wrapper").select("div.layout-body").select("div")
.select("div.ui-fixed-container").select("div").select("nav:nth-child(2)").select("ul")
.select("li.after").select("a");
Element nextpage = null;
try {
nextpage = pages.get(0);
} catch (IndexOutOfBoundsException e) {
System.out.println("网页格式错误,请检查cookie是否已经过期 (或者该榜单已被爬取完毕) .");
System.exit(1);
}
nextpageurl = nextpage.absUrl("href");
Elements images = doc.select("#wrapper").select("div.layout-body").select("div")
.select("div.ranking-items-container").select("div.ranking-items.adjust")
.select("section.ranking-item");
for (Element image : images) {
String dataid = image.attr("data-id");
Element imagepage = image.select("div.ranking-image-item").select("a").get(0);
String imagepageurl = imagepage.absUrl("href");
System.out.println("===============" + dataid + "===============");
System.out.println("正在爬取: " + imagepageurl);
resolveImagePage(imagepageurl, dataid);
}
config.setValue("startpage", url);
config.Save();
} catch (IOException e) {
e.printStackTrace();
return nextpageurl;
}
System.out.println(nextpageurl);
return nextpageurl;
}
public void resolveImagePage(String url, String dataid) {
int amount = db.checkArtworks(Integer.parseInt(dataid));// 尝试获取一个值
if (amount == 0) {// 如果为0说明数据库中没有这个数据
System.out.println("数据库中未查到此图片页面的信息, 继续下载操作.");
} else {// 如果 <SUF>
System.out.println("数据库中已查到此图片页面的信息, 图片数量为" + amount + ", 自动跳过.");
return;
}
try {
Response res = null;
while (true) {
try {
res = Jsoup.connect(url).cookies(cookies).method(Method.GET).execute();
break;
} catch (SocketTimeoutException e) {
System.out.println("请求图片页面超时, 将重试.");
} catch (SSLHandshakeException e) {
System.out.println("请求图片页面被拒绝, 将重试.");
} catch (SSLException e) {
System.out.println("请求图片页面被关闭, 将重试.");
} catch (ConnectException e) {// cookie错误将会超时, 但是其实可以不带cookie
System.out.println("连接超时, 请检查cookie是否错误或过期.");
} catch (SocketException e) {
System.out.println("意外结束, 将重试.");
}
}
Document doc = res.parse();
Element meta = doc.select("#meta-preload-data").first();
String content = meta.attr("content");
JSONObject obj = JSON.parseObject(content);
int pagecount = obj.getJSONObject("illust").getJSONObject(dataid).getIntValue("pageCount");
String p0url = obj.getJSONObject("illust").getJSONObject(dataid).getJSONObject("urls")
.getString("original");
for (int i = 0; i < pagecount; i++) {
String imgurl = null;
if (i == 0) {
imgurl = p0url;
} else {
imgurl = p0url.replaceAll("p0", "p" + i);
}
String filename = imgurl.substring(imgurl.lastIndexOf("/") + 1);
// 这里要去掉jarpath末尾的"/"
String imagesavepath = config.getString("imagesavepath").replace("%HERE%",
jarpath.substring(0, jarpath.length() - 1));
File imgfile = Util.createFile(imagesavepath, filename);
Response resimg = null;
while (true) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
resimg = Jsoup.connect(imgurl).cookies(cookies).ignoreContentType(true).maxBodySize(1073741824)
.referrer("https://www.pixiv.net/artworks/" + dataid).execute();
in = resimg.bodyStream();
out = new BufferedOutputStream(new FileOutputStream(imgfile));
byte[] bytes = new byte[1024];
int total = 0;
int count = 0;
while ((count = in.read(bytes)) != -1) {
out.write(bytes, 0, count);
total = total + count;
}
System.out.println("文件" + filename + "保存完成, 共收到" + total + "字节.");
break;
} catch (SocketTimeoutException e) {
System.out.println("请求图片超时, 将重试.");
} catch (SSLHandshakeException e) {
System.out.println("请求图片被拒绝, 将重试.");
} catch (SSLException e) {
System.out.println("请求图片被关闭, 将重试.");
} catch (ConnectException e) {// cookie错误将会超时, 但是其实可以不带cookie
System.out.println("连接超时, 请检查cookie是否错误或过期.");
} catch (SocketException e) {
System.out.println("意外结束, 将重试.");
} catch (HttpStatusException e) {// 防止有画师上传的同一个帖子内文件格式不同
if (imgurl.contains(".jpg")) {
imgurl = imgurl.replaceAll(".jpg", ".png");
} else if (imgurl.contains(".png")) {
imgurl = imgurl.replaceAll(".png", ".jpg");
}
System.out.println("HTTP状态错误:" + e.getStatusCode() + " 将尝试另一后缀名.");
} finally {
try {
in.close();
out.close();
} catch (NullPointerException | SSLException e) {
}
}
}
}
db.addArtworks(Integer.parseInt(dataid), pagecount);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| false | 1,872 | 10 | 2,218 | 11 | 2,157 | 10 | 2,218 | 11 | 3,021 | 19 | false | false | false | false | false | true |
50278_4 | package com.xyf.utils;
import java.io.File;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
public class UploadUtils {
private static final Logger logger = (Logger) LogManager.getLogger(UploadUtils.class);
//获得文件扩展名,返回值包括点 .
public static String getExtension(String filename) {
return filename.substring(filename.lastIndexOf('.'), filename.length());
}
//使用七牛来上传文件
public static void uploadwithQiniu(File file,String accessKey,String secretKey,String bucket)
{
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
Auth auth = Auth.create(accessKey, secretKey);
Zone z=Zone.autoZone();
Configuration cfg = new Configuration(Zone.zone0());
String upToken = auth.uploadToken(bucket);
//创建上床对象
UploadManager uploadManager=new UploadManager(cfg);
try {
Response response = uploadManager.put(file, file.getName(), auth.uploadToken(bucket));
//解析上传成功的结果
if(response.isOK())
{
logger.debug("使用七牛云上传文件成功",file.getName());
}
else
{
logger.debug("使用七牛云上传文件失败 失败原因",file.getName(),response.bodyString());
throw new RuntimeException("使用七牛云上传失败"+file.getName());
}
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
throw new RuntimeException("使用七牛云上床失败"+file.getName());
}
}
}
}
| RAOE/RunnerManager | com-xyf-common/src/main/java/com/xyf/utils/UploadUtils.java | 624 | //解析上传成功的结果 | line_comment | zh-cn | package com.xyf.utils;
import java.io.File;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
public class UploadUtils {
private static final Logger logger = (Logger) LogManager.getLogger(UploadUtils.class);
//获得文件扩展名,返回值包括点 .
public static String getExtension(String filename) {
return filename.substring(filename.lastIndexOf('.'), filename.length());
}
//使用七牛来上传文件
public static void uploadwithQiniu(File file,String accessKey,String secretKey,String bucket)
{
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
Auth auth = Auth.create(accessKey, secretKey);
Zone z=Zone.autoZone();
Configuration cfg = new Configuration(Zone.zone0());
String upToken = auth.uploadToken(bucket);
//创建上床对象
UploadManager uploadManager=new UploadManager(cfg);
try {
Response response = uploadManager.put(file, file.getName(), auth.uploadToken(bucket));
//解析 <SUF>
if(response.isOK())
{
logger.debug("使用七牛云上传文件成功",file.getName());
}
else
{
logger.debug("使用七牛云上传文件失败 失败原因",file.getName(),response.bodyString());
throw new RuntimeException("使用七牛云上传失败"+file.getName());
}
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
throw new RuntimeException("使用七牛云上床失败"+file.getName());
}
}
}
}
| false | 490 | 5 | 624 | 6 | 673 | 5 | 624 | 6 | 767 | 12 | false | false | false | false | false | true |
8788_1 | package me.xiongzj.model;
import java.io.Serializable;
import me.xiongzj.exception.ATMException;
import me.xiongzj.exception.NegativeAmountException;
public abstract class Account implements Serializable {
private static final long serialVersionUID = 1L;
private long id; // 账户号码
private String password; // 账户密码
private String name; // 姓名
private String personId; // 身份证
private String email; // 电邮
private double balance; // 账户余额
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof Account))
return false;
return this.id == ((Account) obj).id;
}
@Override
public String toString() {
return "class: Account, id: " + id + ", name: " + name;
}
public static enum Type { // 账户类型
SAVING, CREDIT, LOAN_SAVING, LOAN_CREDIT;
@Override
public String toString() {
switch (this) {
case SAVING:
return "SAVING";
case CREDIT:
return "CREDIT";
case LOAN_SAVING:
return "LOAN_SAVING";
case LOAN_CREDIT:
return "LOAN_CREDIT";
}
return null;
}
public Type toType(String str) {
if("SAVING".equals(str))
return SAVING;
else if("CREDIT".equals(str))
return CREDIT;
else if("LOAN_SAVING".equals(str))
return LOAN_SAVING;
else if("LOAN_CREDIT".equals(str))
return LOAN_CREDIT;
return null;
}
}
public abstract Type getType();
public Account() {
}
public Account(long id, String password, String name, String personId, String email) {
this.id = id;
this.password = password;
this.name = name;
this.personId = personId;
this.email = email;
this.balance = 0;
}
public long getId() { // set(), get()
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public final Account deposit(double money) throws NegativeAmountException { // 存钱, 子类不能修改
if (money < 0) // 这是要干什么???
throw new NegativeAmountException("The money is " + money + ".");
balance += money;
return this;
}
public abstract Account withdraw(double money) throws ATMException; // 取款方法根据不同的子类而不同,改为抽象方法
}
| RRRRRm/nuist_java_final_assignment | src/me/xiongzj/model/Account.java | 904 | // 账户密码
| line_comment | zh-cn | package me.xiongzj.model;
import java.io.Serializable;
import me.xiongzj.exception.ATMException;
import me.xiongzj.exception.NegativeAmountException;
public abstract class Account implements Serializable {
private static final long serialVersionUID = 1L;
private long id; // 账户号码
private String password; // 账户 <SUF>
private String name; // 姓名
private String personId; // 身份证
private String email; // 电邮
private double balance; // 账户余额
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof Account))
return false;
return this.id == ((Account) obj).id;
}
@Override
public String toString() {
return "class: Account, id: " + id + ", name: " + name;
}
public static enum Type { // 账户类型
SAVING, CREDIT, LOAN_SAVING, LOAN_CREDIT;
@Override
public String toString() {
switch (this) {
case SAVING:
return "SAVING";
case CREDIT:
return "CREDIT";
case LOAN_SAVING:
return "LOAN_SAVING";
case LOAN_CREDIT:
return "LOAN_CREDIT";
}
return null;
}
public Type toType(String str) {
if("SAVING".equals(str))
return SAVING;
else if("CREDIT".equals(str))
return CREDIT;
else if("LOAN_SAVING".equals(str))
return LOAN_SAVING;
else if("LOAN_CREDIT".equals(str))
return LOAN_CREDIT;
return null;
}
}
public abstract Type getType();
public Account() {
}
public Account(long id, String password, String name, String personId, String email) {
this.id = id;
this.password = password;
this.name = name;
this.personId = personId;
this.email = email;
this.balance = 0;
}
public long getId() { // set(), get()
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public final Account deposit(double money) throws NegativeAmountException { // 存钱, 子类不能修改
if (money < 0) // 这是要干什么???
throw new NegativeAmountException("The money is " + money + ".");
balance += money;
return this;
}
public abstract Account withdraw(double money) throws ATMException; // 取款方法根据不同的子类而不同,改为抽象方法
}
| false | 721 | 7 | 902 | 5 | 851 | 5 | 902 | 5 | 1,085 | 9 | false | false | false | false | false | true |
24888_1 | package mir;
import frontend.lexer.Token;
import frontend.semantic.InitValue;
import frontend.syntaxChecker.Ast;
import java.util.HashMap;
public class GlobalValue extends Constant {
//constant fixed address (after linking).
//拥有@的全局标识符
public Ast.Ident ident;
public InitValue initValue;
public static final HashMap<Type, GlobalValue> undefTable = new HashMap<>();
public static Constant getUndef(Type type) {
if(type.isInt32Ty()) {
return new Constant.ConstantInt(0);
}
if(type.isFloatTy()) {
return new Constant.ConstantFloat(0);
}
if(undefTable.containsKey(type)) {
return undefTable.get(type);
}
GlobalValue undef = new GlobalValue(type);
undefTable.put(type, undef);
return undef;
}
private GlobalValue(Type type) {
//Type must be pointer,存的是全局变量地址
super(new Type.PointerType(type));
ident = new Ast.Ident(new Token(Token.Type.IDENTIFIER, "undef_" + undefTable.size()));
if(type.isInt32Ty()) {
initValue = new InitValue.ValueInit(new ConstantInt(0), type);
} else if(type.isFloatTy()) {
initValue = new InitValue.ValueInit(new ConstantFloat(0), type);
} else if(type.isPointerTy()) {
initValue = new InitValue.ZeroArrayInit(((Type.PointerType) type).getInnerType());
} else {
throw new RuntimeException("Unsupported type for undef");
}
}
public GlobalValue(Type innerType, Ast.Ident ident, InitValue initValue) {
super(new Type.PointerType(innerType));
this.ident = ident;
this.initValue = initValue;
}
public Type getInnerType() {
Type.PointerType pointerType = (Type.PointerType) getType();
return pointerType.getInnerType();
}
@Override
public Object getConstValue() {
return initValue;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (getClass() != o.getClass()) {
return false;
}
return ident.equals(((GlobalValue) o).ident);
}
@Override
public boolean isZero() {
for (InitValue.Flatten.Slice slice:
initValue.flatten()) {
if (slice.isZero() == false) {
return false;
}
}
return true;
}
@Override
public String getDescriptor() {
return "@"+ident.identifier.content;
}
}
| RRReActor/Compiler_LLVM | mir/GlobalValue.java | 616 | //拥有@的全局标识符 | line_comment | zh-cn | package mir;
import frontend.lexer.Token;
import frontend.semantic.InitValue;
import frontend.syntaxChecker.Ast;
import java.util.HashMap;
public class GlobalValue extends Constant {
//constant fixed address (after linking).
//拥有 <SUF>
public Ast.Ident ident;
public InitValue initValue;
public static final HashMap<Type, GlobalValue> undefTable = new HashMap<>();
public static Constant getUndef(Type type) {
if(type.isInt32Ty()) {
return new Constant.ConstantInt(0);
}
if(type.isFloatTy()) {
return new Constant.ConstantFloat(0);
}
if(undefTable.containsKey(type)) {
return undefTable.get(type);
}
GlobalValue undef = new GlobalValue(type);
undefTable.put(type, undef);
return undef;
}
private GlobalValue(Type type) {
//Type must be pointer,存的是全局变量地址
super(new Type.PointerType(type));
ident = new Ast.Ident(new Token(Token.Type.IDENTIFIER, "undef_" + undefTable.size()));
if(type.isInt32Ty()) {
initValue = new InitValue.ValueInit(new ConstantInt(0), type);
} else if(type.isFloatTy()) {
initValue = new InitValue.ValueInit(new ConstantFloat(0), type);
} else if(type.isPointerTy()) {
initValue = new InitValue.ZeroArrayInit(((Type.PointerType) type).getInnerType());
} else {
throw new RuntimeException("Unsupported type for undef");
}
}
public GlobalValue(Type innerType, Ast.Ident ident, InitValue initValue) {
super(new Type.PointerType(innerType));
this.ident = ident;
this.initValue = initValue;
}
public Type getInnerType() {
Type.PointerType pointerType = (Type.PointerType) getType();
return pointerType.getInnerType();
}
@Override
public Object getConstValue() {
return initValue;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (getClass() != o.getClass()) {
return false;
}
return ident.equals(((GlobalValue) o).ident);
}
@Override
public boolean isZero() {
for (InitValue.Flatten.Slice slice:
initValue.flatten()) {
if (slice.isZero() == false) {
return false;
}
}
return true;
}
@Override
public String getDescriptor() {
return "@"+ident.identifier.content;
}
}
| false | 556 | 7 | 616 | 8 | 684 | 7 | 616 | 8 | 745 | 14 | false | false | false | false | false | true |
36156_5 | package com.example.mycooking.page;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;
import com.example.mycooking.R;
import com.example.mycooking.activity.MsgNotifyActivity;
import com.example.mycooking.activity.shangchuangcaipu.LoadOneActivity;
import com.example.mycooking.view.RefreshScLinearLayout;
/**
* Created by liaozhihua on 2016/9/3.
*/
public class SuggestPage extends BasePage {
private static final String TAG = "SuggestPage";
public View suggestPageView;
private ScrollView scrollView_suggestpage;
private ImageButton bt_suggestPagetitle_left;
public SuggestPage(Activity activity) {
super(activity);
}
@Override
public void initData() {
}
@Override
public View initView() {
//测试
/*TextView textView = new TextView(mActivity);
textView.setText("推荐");
return textView;*/
suggestPageView = View.inflate(mActivity, R.layout.suggest_page_view, null);
ImageButton bt_suggestpage_totop = (ImageButton) suggestPageView.findViewById(R.id.bt_suggestpage_totop);
bt_suggestpage_totop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RefreshScLinearLayout.fun(); //回到顶部
}
});
RefreshScLinearLayout ll_refreshactivity_refresh = (RefreshScLinearLayout) suggestPageView.findViewById(R.id.ll_refreshactivity_refresh);
bt_suggestPagetitle_left = (ImageButton) suggestPageView.findViewById(R.id.bt_suggestPagetitle_left);
bt_suggestPagetitle_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* 上传菜谱
* @param view
*/
mActivity.startActivity(new Intent(mActivity, LoadOneActivity.class));
}
});
ImageButton bt_suggestPagetitle_right = (ImageButton) suggestPageView.findViewById(R.id.bt_suggestPagetitle_right);
bt_suggestPagetitle_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mActivity.startActivity(new Intent(mActivity, MsgNotifyActivity.class));
}
});
ll_refreshactivity_refresh.setRefreshListener(new RefreshScLinearLayout.RefreshListener() {
public static final String TAG = "RefreshCallBack";
@Override
public void doInBackground() {
/*new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(3000);//动画停留三秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});*/
//刷新:在子线程
//Log.i(TAG,"doInBackground");
}
@Override
public void complete() {
//Log.i(TAG,"complete");
}
});
/*scrollView_suggestpage = (ScrollView) suggestPageView.findViewById(R.id.scrollView_suggestpage);
Button bt_suggestpage_sort = (Button) suggestPageView.findViewById(R.id.bt_suggestpage_sort);
Button bt_suggestpage_Rank = (Button) suggestPageView.findViewById(R.id.bt_suggestpage_Rank);
CirclePageIndicator indicator_suggestmeal = (CirclePageIndicator) suggestPageView.findViewById(R.id.indicator_suggestmeal);
ViewPager vp_suggestPage_meal = (ViewPager) suggestPageView.findViewById(R.id.vp_suggestPage_meal);
vp_suggestPage_meal.setAdapter(new MysuggestmealPagerAdapter());
indicator_suggestmeal.setViewPager(vp_suggestPage_meal);
Log.i(TAG,indicator_suggestmeal.toString());
//菜谱分类
bt_suggestpage_sort.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, MenuSortActivity.class);
mActivity.startActivity(intent);
}
});
//排行榜
bt_suggestpage_Rank.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, MenuRankActivity.class);
mActivity.startActivity(intent);
}
});*/
return suggestPageView;
}
class MysuggestmealPagerAdapter extends PagerAdapter {
String[] whichMeal = new String[]{"早餐","午餐","下午茶","晚餐","夜宵"};
String[] mealInfo = new String[]{"早餐早餐早餐","午餐午餐午餐","下午茶下午茶下午茶","晚餐晚餐晚餐","夜宵夜宵夜宵"};
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View page = View.inflate(mActivity, R.layout.viewpager_meal, null);
TextView tv_vpMeal_meal = (TextView) page.findViewById(R.id.tv_vpMeal_meal);
TextView tv_vpMeal_info = (TextView) page.findViewById(R.id.tv_vpMeal_info);
tv_vpMeal_meal.setText(whichMeal[position]);
tv_vpMeal_info.setText(mealInfo[position]);
//将view放入容器中
container.addView(page);
//将object返回
return page;//super.instantiateItem(container, position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
| RSK16/MyCooking | app/src/main/java/com/example/mycooking/page/SuggestPage.java | 1,452 | //刷新:在子线程 | line_comment | zh-cn | package com.example.mycooking.page;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TextView;
import com.example.mycooking.R;
import com.example.mycooking.activity.MsgNotifyActivity;
import com.example.mycooking.activity.shangchuangcaipu.LoadOneActivity;
import com.example.mycooking.view.RefreshScLinearLayout;
/**
* Created by liaozhihua on 2016/9/3.
*/
public class SuggestPage extends BasePage {
private static final String TAG = "SuggestPage";
public View suggestPageView;
private ScrollView scrollView_suggestpage;
private ImageButton bt_suggestPagetitle_left;
public SuggestPage(Activity activity) {
super(activity);
}
@Override
public void initData() {
}
@Override
public View initView() {
//测试
/*TextView textView = new TextView(mActivity);
textView.setText("推荐");
return textView;*/
suggestPageView = View.inflate(mActivity, R.layout.suggest_page_view, null);
ImageButton bt_suggestpage_totop = (ImageButton) suggestPageView.findViewById(R.id.bt_suggestpage_totop);
bt_suggestpage_totop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RefreshScLinearLayout.fun(); //回到顶部
}
});
RefreshScLinearLayout ll_refreshactivity_refresh = (RefreshScLinearLayout) suggestPageView.findViewById(R.id.ll_refreshactivity_refresh);
bt_suggestPagetitle_left = (ImageButton) suggestPageView.findViewById(R.id.bt_suggestPagetitle_left);
bt_suggestPagetitle_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* 上传菜谱
* @param view
*/
mActivity.startActivity(new Intent(mActivity, LoadOneActivity.class));
}
});
ImageButton bt_suggestPagetitle_right = (ImageButton) suggestPageView.findViewById(R.id.bt_suggestPagetitle_right);
bt_suggestPagetitle_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mActivity.startActivity(new Intent(mActivity, MsgNotifyActivity.class));
}
});
ll_refreshactivity_refresh.setRefreshListener(new RefreshScLinearLayout.RefreshListener() {
public static final String TAG = "RefreshCallBack";
@Override
public void doInBackground() {
/*new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(3000);//动画停留三秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});*/
//刷新 <SUF>
//Log.i(TAG,"doInBackground");
}
@Override
public void complete() {
//Log.i(TAG,"complete");
}
});
/*scrollView_suggestpage = (ScrollView) suggestPageView.findViewById(R.id.scrollView_suggestpage);
Button bt_suggestpage_sort = (Button) suggestPageView.findViewById(R.id.bt_suggestpage_sort);
Button bt_suggestpage_Rank = (Button) suggestPageView.findViewById(R.id.bt_suggestpage_Rank);
CirclePageIndicator indicator_suggestmeal = (CirclePageIndicator) suggestPageView.findViewById(R.id.indicator_suggestmeal);
ViewPager vp_suggestPage_meal = (ViewPager) suggestPageView.findViewById(R.id.vp_suggestPage_meal);
vp_suggestPage_meal.setAdapter(new MysuggestmealPagerAdapter());
indicator_suggestmeal.setViewPager(vp_suggestPage_meal);
Log.i(TAG,indicator_suggestmeal.toString());
//菜谱分类
bt_suggestpage_sort.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, MenuSortActivity.class);
mActivity.startActivity(intent);
}
});
//排行榜
bt_suggestpage_Rank.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, MenuRankActivity.class);
mActivity.startActivity(intent);
}
});*/
return suggestPageView;
}
class MysuggestmealPagerAdapter extends PagerAdapter {
String[] whichMeal = new String[]{"早餐","午餐","下午茶","晚餐","夜宵"};
String[] mealInfo = new String[]{"早餐早餐早餐","午餐午餐午餐","下午茶下午茶下午茶","晚餐晚餐晚餐","夜宵夜宵夜宵"};
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View page = View.inflate(mActivity, R.layout.viewpager_meal, null);
TextView tv_vpMeal_meal = (TextView) page.findViewById(R.id.tv_vpMeal_meal);
TextView tv_vpMeal_info = (TextView) page.findViewById(R.id.tv_vpMeal_info);
tv_vpMeal_meal.setText(whichMeal[position]);
tv_vpMeal_info.setText(mealInfo[position]);
//将view放入容器中
container.addView(page);
//将object返回
return page;//super.instantiateItem(container, position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
| false | 1,183 | 7 | 1,452 | 6 | 1,462 | 6 | 1,452 | 6 | 1,825 | 10 | false | false | false | false | false | true |
18842_2 | package xiaor.core.damageCal;
import xiaor.core.charas.Chara;
import xiaor.core.logger.LogType;
import xiaor.core.logger.Logger;
import xiaor.core.msgpack.BuffCalPack;
import xiaor.core.msgpack.DamageRecordPack;
import xiaor.core.msgpack.MessagePack;
import xiaor.core.skillbuilder.skill.BuffType;
import xiaor.core.tools.record.DamageRecord;
import xiaor.core.trigger.TriggerEnum;
import xiaor.core.trigger.TriggerManager;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static xiaor.core.damageCal.DamageCal.InternalBuffType.*;
public class DamageCal {
public final MessagePack pack;
public DamageCal(MessagePack pack) {
this.pack = pack;
}
public void finalDamage(Chara acceptor, double percent, DamageBase baseType, int times, TriggerEnum skillTypeEnum) {
Logger.INSTANCE.log(LogType.触发BUFF, "伤害倍率%s%%,伤害类型:%s,%s次".formatted(percent*100, baseType, times));
double baseDamage = percent * switch (baseType) {
case 攻击 -> pack.caster.getCurrentAttack();
case 生命 -> pack.caster.getCurrentMaxLife();
};
BuffCalPack damageCalPack = new BuffCalPack(pack.caster, acceptor);
TriggerManager.sendMessage(skillTypeEnum, damageCalPack);
TriggerManager.sendMessage(TriggerEnum.伤害计算, damageCalPack);
var buffMap = damageCalPack.getBuffMap();
int finalDamage = (int) damageCalPack.getBuffMap().entrySet().stream()
.filter(entry -> buffTypeMap.get(entry.getKey()) != 属性克制)
.collect(Collectors.groupingBy(entry -> buffTypeMap.get(entry.getKey())))
.values()
.stream()
.mapToDouble(entries -> entries.stream().mapToDouble(Map.Entry::getValue).sum())
.reduce(baseDamage, (a, b) -> (a * (1 + b)));
//属性克制特殊逻辑
double 属性克制 = 0;
if (buffMap.containsKey(BuffType.属性克制)) {
属性克制 = buffMap.get(BuffType.属性克制);
}
double 属性相克效果增减 = 0;
if (buffMap.containsKey(BuffType.属性相克效果)) {
属性相克效果增减 = buffMap.get(BuffType.属性相克效果);
}
finalDamage *= (1 + 属性克制 * (1 - 属性相克效果增减));
for (int i = 0; i < times; i++) {
int currentES = acceptor.getShield();
long lifeRemain = acceptor.getLife();
String msg;
if (currentES != 0) {
if (finalDamage > currentES) {
msg = "%s对%s造成了%d(%d)伤害".formatted(pack.caster, pack.acceptors, finalDamage - currentES, currentES);
lifeRemain -= finalDamage - currentES;
acceptor.setShield(0);
} else {
msg = "%s对%s造成了0(%d)伤害".formatted(pack.caster, pack.acceptors, finalDamage);
acceptor.setShield(currentES - finalDamage);
}
} else {
msg = "%s对%s造成了%d伤害".formatted(pack.caster, pack.acceptors, finalDamage);
lifeRemain -= finalDamage;
}
Logger.INSTANCE.log(LogType.造成伤害, msg);
acceptor.setLife(lifeRemain);
TriggerManager.sendMessage(TriggerEnum.造成伤害, new DamageRecordPack(
new DamageRecord(skillTypeEnum, msg, pack.caster, acceptor, finalDamage)));
}
Logger.INSTANCE.log(LogType.造成伤害, acceptor + "剩余" + acceptor.getLife());
buffMap.clear();
}
public void dotAttack(double multi, DamageBase baseType) {
/**
* dot攻击的特点是伤害并非事实结算,而是附加了一个只吃易伤的dot buff
* 回合结束时。buff才会真正的调用dotAttack
*/
}
/*
伤害计算分为6大区
基本攻击力计算
易伤
属性易伤
造成伤害增加
杂项
属性克制
内部是加减法,外部是乘法,这里需要分类
*/
public enum InternalBuffType {
基本攻击力计算,
易伤,
属性易伤,
造成伤害增加,
杂项,
属性克制
}
private static final HashMap<BuffType, InternalBuffType> buffTypeMap = getBuffTypeMap();
private static HashMap<BuffType, InternalBuffType> getBuffTypeMap() {
HashMap<BuffType, InternalBuffType> buffMap = new HashMap<>();
buffMap.put(BuffType.攻击力数值, 基本攻击力计算);
buffMap.put(BuffType.普攻伤害, 杂项);
buffMap.put(BuffType.攻击力, 基本攻击力计算);
buffMap.put(BuffType.造成伤害, 造成伤害增加);
buffMap.put(BuffType.受到伤害, 易伤);
buffMap.put(BuffType.受到攻击者伤害, 杂项);
buffMap.put(BuffType.受到精灵王伤害, 杂项);
buffMap.put(BuffType.受到自身伤害, 杂项);
buffMap.put(BuffType.受到风属性伤害, 属性易伤);
buffMap.put(BuffType.受到水属性伤害, 属性易伤);
buffMap.put(BuffType.受到光属性伤害, 属性易伤);
buffMap.put(BuffType.受到暗属性伤害, 属性易伤);
buffMap.put(BuffType.受到火属性伤害, 属性易伤);
buffMap.put(BuffType.属性克制, 属性克制);
buffMap.put(BuffType.必杀技伤害, 杂项);
buffMap.put(BuffType.受到普攻伤害, 杂项);
buffMap.put(BuffType.受到必杀伤害, 杂项);
buffMap.put(BuffType.属性相克效果, 属性克制);
return buffMap;
}
public void skillAttack(double multi, DamageBase baseType, int times) {
pack.acceptors.forEach(acceptor -> finalDamage(acceptor, multi, baseType, times, TriggerEnum.技能伤害计算));
}
//普攻
public void normalAttack(double percent, DamageBase baseType, int times) {
pack.acceptors.forEach(acceptor -> finalDamage(acceptor, percent, baseType, times, TriggerEnum.普攻伤害计算));
}
}
| RShock/fumaSim | src/main/java/xiaor/core/damageCal/DamageCal.java | 1,711 | /*
伤害计算分为6大区
基本攻击力计算
易伤
属性易伤
造成伤害增加
杂项
属性克制
内部是加减法,外部是乘法,这里需要分类
*/ | block_comment | zh-cn | package xiaor.core.damageCal;
import xiaor.core.charas.Chara;
import xiaor.core.logger.LogType;
import xiaor.core.logger.Logger;
import xiaor.core.msgpack.BuffCalPack;
import xiaor.core.msgpack.DamageRecordPack;
import xiaor.core.msgpack.MessagePack;
import xiaor.core.skillbuilder.skill.BuffType;
import xiaor.core.tools.record.DamageRecord;
import xiaor.core.trigger.TriggerEnum;
import xiaor.core.trigger.TriggerManager;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static xiaor.core.damageCal.DamageCal.InternalBuffType.*;
public class DamageCal {
public final MessagePack pack;
public DamageCal(MessagePack pack) {
this.pack = pack;
}
public void finalDamage(Chara acceptor, double percent, DamageBase baseType, int times, TriggerEnum skillTypeEnum) {
Logger.INSTANCE.log(LogType.触发BUFF, "伤害倍率%s%%,伤害类型:%s,%s次".formatted(percent*100, baseType, times));
double baseDamage = percent * switch (baseType) {
case 攻击 -> pack.caster.getCurrentAttack();
case 生命 -> pack.caster.getCurrentMaxLife();
};
BuffCalPack damageCalPack = new BuffCalPack(pack.caster, acceptor);
TriggerManager.sendMessage(skillTypeEnum, damageCalPack);
TriggerManager.sendMessage(TriggerEnum.伤害计算, damageCalPack);
var buffMap = damageCalPack.getBuffMap();
int finalDamage = (int) damageCalPack.getBuffMap().entrySet().stream()
.filter(entry -> buffTypeMap.get(entry.getKey()) != 属性克制)
.collect(Collectors.groupingBy(entry -> buffTypeMap.get(entry.getKey())))
.values()
.stream()
.mapToDouble(entries -> entries.stream().mapToDouble(Map.Entry::getValue).sum())
.reduce(baseDamage, (a, b) -> (a * (1 + b)));
//属性克制特殊逻辑
double 属性克制 = 0;
if (buffMap.containsKey(BuffType.属性克制)) {
属性克制 = buffMap.get(BuffType.属性克制);
}
double 属性相克效果增减 = 0;
if (buffMap.containsKey(BuffType.属性相克效果)) {
属性相克效果增减 = buffMap.get(BuffType.属性相克效果);
}
finalDamage *= (1 + 属性克制 * (1 - 属性相克效果增减));
for (int i = 0; i < times; i++) {
int currentES = acceptor.getShield();
long lifeRemain = acceptor.getLife();
String msg;
if (currentES != 0) {
if (finalDamage > currentES) {
msg = "%s对%s造成了%d(%d)伤害".formatted(pack.caster, pack.acceptors, finalDamage - currentES, currentES);
lifeRemain -= finalDamage - currentES;
acceptor.setShield(0);
} else {
msg = "%s对%s造成了0(%d)伤害".formatted(pack.caster, pack.acceptors, finalDamage);
acceptor.setShield(currentES - finalDamage);
}
} else {
msg = "%s对%s造成了%d伤害".formatted(pack.caster, pack.acceptors, finalDamage);
lifeRemain -= finalDamage;
}
Logger.INSTANCE.log(LogType.造成伤害, msg);
acceptor.setLife(lifeRemain);
TriggerManager.sendMessage(TriggerEnum.造成伤害, new DamageRecordPack(
new DamageRecord(skillTypeEnum, msg, pack.caster, acceptor, finalDamage)));
}
Logger.INSTANCE.log(LogType.造成伤害, acceptor + "剩余" + acceptor.getLife());
buffMap.clear();
}
public void dotAttack(double multi, DamageBase baseType) {
/**
* dot攻击的特点是伤害并非事实结算,而是附加了一个只吃易伤的dot buff
* 回合结束时。buff才会真正的调用dotAttack
*/
}
/*
伤害计 <SUF>*/
public enum InternalBuffType {
基本攻击力计算,
易伤,
属性易伤,
造成伤害增加,
杂项,
属性克制
}
private static final HashMap<BuffType, InternalBuffType> buffTypeMap = getBuffTypeMap();
private static HashMap<BuffType, InternalBuffType> getBuffTypeMap() {
HashMap<BuffType, InternalBuffType> buffMap = new HashMap<>();
buffMap.put(BuffType.攻击力数值, 基本攻击力计算);
buffMap.put(BuffType.普攻伤害, 杂项);
buffMap.put(BuffType.攻击力, 基本攻击力计算);
buffMap.put(BuffType.造成伤害, 造成伤害增加);
buffMap.put(BuffType.受到伤害, 易伤);
buffMap.put(BuffType.受到攻击者伤害, 杂项);
buffMap.put(BuffType.受到精灵王伤害, 杂项);
buffMap.put(BuffType.受到自身伤害, 杂项);
buffMap.put(BuffType.受到风属性伤害, 属性易伤);
buffMap.put(BuffType.受到水属性伤害, 属性易伤);
buffMap.put(BuffType.受到光属性伤害, 属性易伤);
buffMap.put(BuffType.受到暗属性伤害, 属性易伤);
buffMap.put(BuffType.受到火属性伤害, 属性易伤);
buffMap.put(BuffType.属性克制, 属性克制);
buffMap.put(BuffType.必杀技伤害, 杂项);
buffMap.put(BuffType.受到普攻伤害, 杂项);
buffMap.put(BuffType.受到必杀伤害, 杂项);
buffMap.put(BuffType.属性相克效果, 属性克制);
return buffMap;
}
public void skillAttack(double multi, DamageBase baseType, int times) {
pack.acceptors.forEach(acceptor -> finalDamage(acceptor, multi, baseType, times, TriggerEnum.技能伤害计算));
}
//普攻
public void normalAttack(double percent, DamageBase baseType, int times) {
pack.acceptors.forEach(acceptor -> finalDamage(acceptor, percent, baseType, times, TriggerEnum.普攻伤害计算));
}
}
| false | 1,474 | 65 | 1,711 | 64 | 1,656 | 57 | 1,711 | 64 | 2,299 | 99 | false | false | false | false | false | true |
10075_4 | import java.io.File;
import java.net.InetAddress;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.jacamars.dsp.rtb.blocks.LookingGlass;
import com.jacamars.dsp.rtb.tools.IsoTwo2Iso3;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Postal;
import com.maxmind.geoip2.record.Subdivision;
import com.maxmind.geoip2.record.Location;
public enum GeoPatch {
GEOPATCH;
static final JsonNodeFactory factory = JsonNodeFactory.instance;
static IsoTwo2Iso3 isoMap;
static DatabaseReader reader = null;
public static void main(String[] args) throws Exception {
InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'US'
System.out.println(country.getName()); // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美国'
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'
City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'
System.out.println(response.getLocation().getLatitude()); // 44.9733
System.out.println(response.getLocation().getLongitude()); // -93.2323)
}
public static GeoPatch getInstance(String fileName) throws Exception {
reader = new DatabaseReader.Builder(new File(fileName)).build();
isoMap = (IsoTwo2Iso3) LookingGlass.symbols.get("@ISO2-3");
return GEOPATCH;
}
public void patch(ObjectNode device) throws Exception {
if (isoMap == null)
isoMap = (IsoTwo2Iso3) LookingGlass.symbols.get("@ISO2-3");
String ip = device.get("ip").asText("");
if (ip.equals(""))
return;
InetAddress ipAddress = InetAddress.getByName(ip);
CityResponse response = null;
City city = null;
Country country = null;
Subdivision subdivision = null;
Postal postal = null;
Location location = null;
ObjectNode geo = (ObjectNode)device.get("geo");
if (geo == null) {
geo = factory.objectNode();
device.set("geo", geo);
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
JsonNode x = null;
if ((x = geo.get("country"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
String iso = country.getIsoCode();
if (iso.length()==2 && isoMap != null) {
iso = isoMap.query(iso);
}
geo.set("country", new TextNode(iso));
}
x = null;
if ((x = geo.get("city"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("city", new TextNode(city.getName()));
}
x = null;;
if ((x = geo.get("state"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("state",new TextNode(subdivision.getIsoCode()));
}
x = null;;
if ((x = geo.get("zipcode"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("zip", new TextNode(postal.getCode()));
}
x = null;;
if ((x = geo.get("lat"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("lat", new DoubleNode(location.getLatitude()));
geo.set("lon", new DoubleNode(location.getLatitude()));
}
}
}
| RTB4FREE/bidder | src/GeoPatch.java | 1,527 | // '美国' | line_comment | zh-cn | import java.io.File;
import java.net.InetAddress;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.jacamars.dsp.rtb.blocks.LookingGlass;
import com.jacamars.dsp.rtb.tools.IsoTwo2Iso3;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Postal;
import com.maxmind.geoip2.record.Subdivision;
import com.maxmind.geoip2.record.Location;
public enum GeoPatch {
GEOPATCH;
static final JsonNodeFactory factory = JsonNodeFactory.instance;
static IsoTwo2Iso3 isoMap;
static DatabaseReader reader = null;
public static void main(String[] args) throws Exception {
InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'US'
System.out.println(country.getName()); // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美 <SUF>
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'
City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'
System.out.println(response.getLocation().getLatitude()); // 44.9733
System.out.println(response.getLocation().getLongitude()); // -93.2323)
}
public static GeoPatch getInstance(String fileName) throws Exception {
reader = new DatabaseReader.Builder(new File(fileName)).build();
isoMap = (IsoTwo2Iso3) LookingGlass.symbols.get("@ISO2-3");
return GEOPATCH;
}
public void patch(ObjectNode device) throws Exception {
if (isoMap == null)
isoMap = (IsoTwo2Iso3) LookingGlass.symbols.get("@ISO2-3");
String ip = device.get("ip").asText("");
if (ip.equals(""))
return;
InetAddress ipAddress = InetAddress.getByName(ip);
CityResponse response = null;
City city = null;
Country country = null;
Subdivision subdivision = null;
Postal postal = null;
Location location = null;
ObjectNode geo = (ObjectNode)device.get("geo");
if (geo == null) {
geo = factory.objectNode();
device.set("geo", geo);
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
JsonNode x = null;
if ((x = geo.get("country"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
String iso = country.getIsoCode();
if (iso.length()==2 && isoMap != null) {
iso = isoMap.query(iso);
}
geo.set("country", new TextNode(iso));
}
x = null;
if ((x = geo.get("city"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("city", new TextNode(city.getName()));
}
x = null;;
if ((x = geo.get("state"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("state",new TextNode(subdivision.getIsoCode()));
}
x = null;;
if ((x = geo.get("zipcode"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("zip", new TextNode(postal.getCode()));
}
x = null;;
if ((x = geo.get("lat"))==null) {
if (response == null) {
response = reader.city(ipAddress);
city = response.getCity();
country = response.getCountry();
subdivision = response.getMostSpecificSubdivision();
postal = response.getPostal();
location = response.getLocation();
}
geo.set("lat", new DoubleNode(location.getLatitude()));
geo.set("lon", new DoubleNode(location.getLatitude()));
}
}
}
| false | 1,255 | 4 | 1,527 | 4 | 1,507 | 4 | 1,527 | 4 | 1,900 | 5 | false | false | false | false | false | true |
16410_1 | package com.DocSystem.dao;
import java.util.HashMap;
import java.util.List;
import com.DocSystem.entity.ReposAuth;
public interface ReposAuthMapper {
int deleteByPrimaryKey(Integer id);
int insert(ReposAuth record);
int insertSelective(ReposAuth record);
ReposAuth selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(ReposAuth record);
int updateByPrimaryKey(ReposAuth record);
List<ReposAuth> selectSelective(ReposAuth reposAuth);
ReposAuth getReposAuth(ReposAuth reposAuth);
//获取所有用户列表(包含授权信息,但这个函数名定义确实有点奇怪)
List<ReposAuth> getReposAllUsers(Integer reposId);
List<ReposAuth> queryReposMemberWithParamLike(HashMap<String, String> param);
List<ReposAuth> getReposAllGroups(Integer reposId);
//获取仓库的所有授权信息
List<ReposAuth> getReposAuthList(Integer reposId);
List<ReposAuth> getReposAuthForUser(ReposAuth reposAuth);
int deleteSelective(ReposAuth reposAuth);
} | RainyGao-GitHub/DocSys | src/com/DocSystem/dao/ReposAuthMapper.java | 269 | //获取仓库的所有授权信息 | line_comment | zh-cn | package com.DocSystem.dao;
import java.util.HashMap;
import java.util.List;
import com.DocSystem.entity.ReposAuth;
public interface ReposAuthMapper {
int deleteByPrimaryKey(Integer id);
int insert(ReposAuth record);
int insertSelective(ReposAuth record);
ReposAuth selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(ReposAuth record);
int updateByPrimaryKey(ReposAuth record);
List<ReposAuth> selectSelective(ReposAuth reposAuth);
ReposAuth getReposAuth(ReposAuth reposAuth);
//获取所有用户列表(包含授权信息,但这个函数名定义确实有点奇怪)
List<ReposAuth> getReposAllUsers(Integer reposId);
List<ReposAuth> queryReposMemberWithParamLike(HashMap<String, String> param);
List<ReposAuth> getReposAllGroups(Integer reposId);
//获取 <SUF>
List<ReposAuth> getReposAuthList(Integer reposId);
List<ReposAuth> getReposAuthForUser(ReposAuth reposAuth);
int deleteSelective(ReposAuth reposAuth);
} | false | 244 | 6 | 269 | 6 | 266 | 6 | 269 | 6 | 326 | 18 | false | false | false | false | false | true |
38287_23 | package algorithm.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* DESCRIPTION
*
* @author lixin
* @create 2019-03-12 下午10:34
**/
public class Sort {
/**
* 交换数组中两个位置的数值
*
* @param arr
* @param i
* @param j
*/
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* 冒泡排序
*
* @param arr 数组
*/
public static void bubbleSort(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
}
/**
* 冒泡优化,已经有序,就不结束排序
*
* @param arr 数组
*/
public static void bubbleSort1(int[] arr) {
if (arr == null) {
return;
}
int border = arr.length - 1;
int lastIndex = 0;
for (int i = 0; i < arr.length - 1; i++) {
boolean sorted = true;
for (int j = 0; j < border; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
sorted = false;
lastIndex = j;
}
}
border = lastIndex;
if (sorted) {
break;
}
}
}
/**
* 插入排序
* 要点:像扑克牌一样,小牌放在左边,插入的牌比左边的某张牌大(左边的牌已经排好大小),
* 该张牌后面的牌依次向右移动一个位置
*
* @param arr 数组
*/
public static void insertSort(int[] arr) {
if (arr == null) {
return;
}
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
/**
* 选择排序
* 每次选择一个最小(或最大)的数,拿走,再从剩下的数中重复选择最小(或最大)的数
*
* @param arr 数组
*/
public static void selectSort(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
swap(arr, min, i);
}
}
}
/**
* 快速排序算法
*
* @param arr 数组
* @param left 左边索引
* @param right 右边索引
*/
public static void quickSort(int[] arr, int left, int right) {
if (left > right) {
return;
}
int index = pivot(arr, left, right);
quickSort(arr, left, index - 1);
quickSort(arr, index + 1, right);
}
/**
* @param arr
* @param left
* @param right
* @return
*/
private static int pivot(int[] arr, int left, int right) {
int i = left;
int j = right;
int pivot = arr[left];
while (i != j) {
while (arr[j] >= pivot && i < j) {
j--;
}
while (arr[i] <= pivot && i < j) {
i++;
}
if (i < j) {
swap(arr, i, j);
}
}
arr[left] = arr[i];
arr[i] = pivot;
return i;
}
/**
* 一个长度为 n 的 double 类型数组,取值为 0 - 10,要求快速将这 20 个 double 元素从小到大排序
*
* @param arr double 数组
* @param bucketNum 桶的数量
*/
public static void bucketSort(double[] arr, int bucketNum) {
if (arr == null) {
return;
}
double max = arr[0];
double min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// 间隔
double d = max - min;
// 创建桶
List<LinkedList<Double>> bucketList = new ArrayList<>();
for (int i = 0; i < bucketNum; i++) {
bucketList.add(new LinkedList<>());
}
// 将数据放入桶中
for (double v : arr) {
int index = (int) ((v - min) / d * (bucketNum - 1));
bucketList.get(index).add(v);
}
// 对每个桶排序
for (LinkedList<Double> linkedList : bucketList) {
Collections.sort(linkedList);
}
// 输出数据
int i = 0;
for (LinkedList<Double> linkedList : bucketList) {
for (Double number : linkedList) {
arr[i++] = number;
}
}
}
/**
* 桶排序 - 整数
*
* @param arr 数组
*/
public static void bucketSort(int[] arr, int bucketSize) {
if (arr == null || arr.length < 2) {
return;
}
int min = arr[0];
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
int bucketCount = (max - min) / bucketSize + 1;
List<List<Integer>> bucketLists = new ArrayList<>(bucketCount);
for (int i = 0; i < bucketCount; i++) {
bucketLists.add(new ArrayList<>());
}
for (int anArr : arr) {
int index = (anArr - min) / bucketSize;
bucketLists.get(index).add(anArr);
}
int k = 0;
for (List<Integer> list : bucketLists) {
if (list.size() > 0) {
Collections.sort(list);
for (int item : list) {
arr[k++] = item;
}
}
}
}
/**
* 计数排序
*
* @param arr 数组
*/
public static int[] countSort(int[] arr) {
if (arr == null) {
return null;
}
int max = arr[0];
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// 创建统计数组,并对每个数据进行计数
int d = max - min;
int[] countArr = new int[d + 1];
for (int i = 0; i < arr.length; i++) {
countArr[arr[i] - min]++;
}
// 对统计数组累计求和
int sum = 0;
for (int i = 0; i < countArr.length; i++) {
sum += countArr[i];
countArr[i] = sum;
}
int[] sortArr = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) {
sortArr[countArr[arr[i] - min] - 1] = arr[i];
countArr[arr[i] - min]--;
}
return sortArr;
}
/**
* 归并排序
*
* @param arr 数组
*/
public static void mergeSort(int[] arr) {
if (arr == null) {
return;
}
int[] temp = new int[arr.length];
mergeSort(arr, 0, arr.length - 1, temp);
}
private static void mergeSort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) >> 1;
mergeSort(arr, left, mid, temp);
mergeSort(arr, mid + 1, right, temp);
merge(arr, left, mid, right, temp);
}
}
private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[t++] = arr[i++];
} else {
temp[t++] = arr[j++];
}
}
// while(i<=mid){//将左边剩余元素填充进temp中
// temp[t++] = arr[i++];
// }
// while(j<=right){//将右序列剩余元素填充进temp中
// temp[t++] = arr[j++];
// }
// t = 0;
// //将temp中的元素全部拷贝到原数组中
// while(left <= right){
// arr[left++] = temp[t++];
// }
if (i <= mid) {
System.arraycopy(arr, i, temp, t, mid - i + 1);
t += mid - i;
}
if (j <= right) {
System.arraycopy(arr, j, temp, t, right - j + 1);
t += right - j;
}
if (left <= right) {
System.arraycopy(temp, 0, arr, left, t + 1);
}
}
}
| RalfNick/DataStruct | src/algorithm/sort/Sort.java | 2,561 | // //将temp中的元素全部拷贝到原数组中 | line_comment | zh-cn | package algorithm.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* DESCRIPTION
*
* @author lixin
* @create 2019-03-12 下午10:34
**/
public class Sort {
/**
* 交换数组中两个位置的数值
*
* @param arr
* @param i
* @param j
*/
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* 冒泡排序
*
* @param arr 数组
*/
public static void bubbleSort(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
}
/**
* 冒泡优化,已经有序,就不结束排序
*
* @param arr 数组
*/
public static void bubbleSort1(int[] arr) {
if (arr == null) {
return;
}
int border = arr.length - 1;
int lastIndex = 0;
for (int i = 0; i < arr.length - 1; i++) {
boolean sorted = true;
for (int j = 0; j < border; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
sorted = false;
lastIndex = j;
}
}
border = lastIndex;
if (sorted) {
break;
}
}
}
/**
* 插入排序
* 要点:像扑克牌一样,小牌放在左边,插入的牌比左边的某张牌大(左边的牌已经排好大小),
* 该张牌后面的牌依次向右移动一个位置
*
* @param arr 数组
*/
public static void insertSort(int[] arr) {
if (arr == null) {
return;
}
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
/**
* 选择排序
* 每次选择一个最小(或最大)的数,拿走,再从剩下的数中重复选择最小(或最大)的数
*
* @param arr 数组
*/
public static void selectSort(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
swap(arr, min, i);
}
}
}
/**
* 快速排序算法
*
* @param arr 数组
* @param left 左边索引
* @param right 右边索引
*/
public static void quickSort(int[] arr, int left, int right) {
if (left > right) {
return;
}
int index = pivot(arr, left, right);
quickSort(arr, left, index - 1);
quickSort(arr, index + 1, right);
}
/**
* @param arr
* @param left
* @param right
* @return
*/
private static int pivot(int[] arr, int left, int right) {
int i = left;
int j = right;
int pivot = arr[left];
while (i != j) {
while (arr[j] >= pivot && i < j) {
j--;
}
while (arr[i] <= pivot && i < j) {
i++;
}
if (i < j) {
swap(arr, i, j);
}
}
arr[left] = arr[i];
arr[i] = pivot;
return i;
}
/**
* 一个长度为 n 的 double 类型数组,取值为 0 - 10,要求快速将这 20 个 double 元素从小到大排序
*
* @param arr double 数组
* @param bucketNum 桶的数量
*/
public static void bucketSort(double[] arr, int bucketNum) {
if (arr == null) {
return;
}
double max = arr[0];
double min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// 间隔
double d = max - min;
// 创建桶
List<LinkedList<Double>> bucketList = new ArrayList<>();
for (int i = 0; i < bucketNum; i++) {
bucketList.add(new LinkedList<>());
}
// 将数据放入桶中
for (double v : arr) {
int index = (int) ((v - min) / d * (bucketNum - 1));
bucketList.get(index).add(v);
}
// 对每个桶排序
for (LinkedList<Double> linkedList : bucketList) {
Collections.sort(linkedList);
}
// 输出数据
int i = 0;
for (LinkedList<Double> linkedList : bucketList) {
for (Double number : linkedList) {
arr[i++] = number;
}
}
}
/**
* 桶排序 - 整数
*
* @param arr 数组
*/
public static void bucketSort(int[] arr, int bucketSize) {
if (arr == null || arr.length < 2) {
return;
}
int min = arr[0];
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
int bucketCount = (max - min) / bucketSize + 1;
List<List<Integer>> bucketLists = new ArrayList<>(bucketCount);
for (int i = 0; i < bucketCount; i++) {
bucketLists.add(new ArrayList<>());
}
for (int anArr : arr) {
int index = (anArr - min) / bucketSize;
bucketLists.get(index).add(anArr);
}
int k = 0;
for (List<Integer> list : bucketLists) {
if (list.size() > 0) {
Collections.sort(list);
for (int item : list) {
arr[k++] = item;
}
}
}
}
/**
* 计数排序
*
* @param arr 数组
*/
public static int[] countSort(int[] arr) {
if (arr == null) {
return null;
}
int max = arr[0];
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// 创建统计数组,并对每个数据进行计数
int d = max - min;
int[] countArr = new int[d + 1];
for (int i = 0; i < arr.length; i++) {
countArr[arr[i] - min]++;
}
// 对统计数组累计求和
int sum = 0;
for (int i = 0; i < countArr.length; i++) {
sum += countArr[i];
countArr[i] = sum;
}
int[] sortArr = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) {
sortArr[countArr[arr[i] - min] - 1] = arr[i];
countArr[arr[i] - min]--;
}
return sortArr;
}
/**
* 归并排序
*
* @param arr 数组
*/
public static void mergeSort(int[] arr) {
if (arr == null) {
return;
}
int[] temp = new int[arr.length];
mergeSort(arr, 0, arr.length - 1, temp);
}
private static void mergeSort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) >> 1;
mergeSort(arr, left, mid, temp);
mergeSort(arr, mid + 1, right, temp);
merge(arr, left, mid, right, temp);
}
}
private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[t++] = arr[i++];
} else {
temp[t++] = arr[j++];
}
}
// while(i<=mid){//将左边剩余元素填充进temp中
// temp[t++] = arr[i++];
// }
// while(j<=right){//将右序列剩余元素填充进temp中
// temp[t++] = arr[j++];
// }
// t = 0;
// //将t <SUF>
// while(left <= right){
// arr[left++] = temp[t++];
// }
if (i <= mid) {
System.arraycopy(arr, i, temp, t, mid - i + 1);
t += mid - i;
}
if (j <= right) {
System.arraycopy(arr, j, temp, t, right - j + 1);
t += right - j;
}
if (left <= right) {
System.arraycopy(temp, 0, arr, left, t + 1);
}
}
}
| false | 2,408 | 14 | 2,561 | 15 | 2,798 | 13 | 2,561 | 15 | 3,120 | 22 | false | false | false | false | false | true |
16488_6 | package com.bean;
/**
* javaBean
*
* @author Rambler
* @version 2016-5-20
*/
public class ApplyBean {
private String name; //姓名
private String sex; //性别
private String className;//班级
private String sno; //学号
private String room; //宿舍
private String college; //学院
private String pnum; //手机号
private String photo; //照片
private String exper; //科技制作经验
private String reward; //获奖情况
private String depart1; //期望部门1
private String depart2; //期望部门2
private String ques1;//问题1:个人简介
private String ques2;//问题2:为什么选择科协
private String ques3;//问题3:其他社团
private String time1; //面试时间1
private String time2; //面试时间2
private String time3; //面试时间3
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getExper() {
return exper;
}
public void setExper(String exper) {
this.exper = exper;
}
public String getReward() {
return reward;
}
public void setReward(String reward) {
this.reward = reward;
}
public String getDepart1() {
return depart1;
}
public void setDepart1(String depart1) {
this.depart1 = depart1;
}
public String getDepart2() {
return depart2;
}
public void setDepart2(String depart2) {
this.depart2 = depart2;
}
public String getQues1() {
return ques1;
}
public void setQues1(String ques1) {
this.ques1 = ques1;
}
public String getQues2() {
return ques2;
}
public void setQues2(String ques2) {
this.ques2 = ques2;
}
public String getQues3() {
return ques3;
}
public void setQues3(String ques3) {
this.ques3 = ques3;
}
public String getTime1() {
return time1;
}
public void setTime1(String time1) {
this.time1 = time1;
}
public String getTime2() {
return time2;
}
public void setTime2(String time2) {
this.time2 = time2;
}
public String getTime3() {
return time3;
}
public void setTime3(String time3) {
this.time3 = time3;
}
}
| RamblerW/WebSignUp | src/com/bean/ApplyBean.java | 1,030 | //问题1:个人简介 | line_comment | zh-cn | package com.bean;
/**
* javaBean
*
* @author Rambler
* @version 2016-5-20
*/
public class ApplyBean {
private String name; //姓名
private String sex; //性别
private String className;//班级
private String sno; //学号
private String room; //宿舍
private String college; //学院
private String pnum; //手机号
private String photo; //照片
private String exper; //科技制作经验
private String reward; //获奖情况
private String depart1; //期望部门1
private String depart2; //期望部门2
private String ques1;//问题 <SUF>
private String ques2;//问题2:为什么选择科协
private String ques3;//问题3:其他社团
private String time1; //面试时间1
private String time2; //面试时间2
private String time3; //面试时间3
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getExper() {
return exper;
}
public void setExper(String exper) {
this.exper = exper;
}
public String getReward() {
return reward;
}
public void setReward(String reward) {
this.reward = reward;
}
public String getDepart1() {
return depart1;
}
public void setDepart1(String depart1) {
this.depart1 = depart1;
}
public String getDepart2() {
return depart2;
}
public void setDepart2(String depart2) {
this.depart2 = depart2;
}
public String getQues1() {
return ques1;
}
public void setQues1(String ques1) {
this.ques1 = ques1;
}
public String getQues2() {
return ques2;
}
public void setQues2(String ques2) {
this.ques2 = ques2;
}
public String getQues3() {
return ques3;
}
public void setQues3(String ques3) {
this.ques3 = ques3;
}
public String getTime1() {
return time1;
}
public void setTime1(String time1) {
this.time1 = time1;
}
public String getTime2() {
return time2;
}
public void setTime2(String time2) {
this.time2 = time2;
}
public String getTime3() {
return time3;
}
public void setTime3(String time3) {
this.time3 = time3;
}
}
| false | 777 | 6 | 1,030 | 7 | 968 | 6 | 1,030 | 7 | 1,129 | 11 | false | false | false | false | false | true |
32889_15 | package com.rance.beautypapa.utils;
import android.content.Context;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
/**
* 作者:Rance on 2016/10/29 15:08
* 邮箱:[email protected]
*/
public class ShareUtils {
/**
* 演示调用ShareSDK执行分享
*
* @param context
*/
public static void showShare(Context context) {
ShareSDK.initSDK(context);
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle("爱啪");
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://u2791965.viewer.maka.im/pcviewer/FZSJ6YJ6");
// text是分享文本,所有平台都需要这个字段
oks.setText("集知乎日报和美拍为一体的供用户休闲的个人开发者软件,开放源码,与广大程序猿共同进步,乐于开源,享受编程带来的乐趣");
//分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
oks.setImageUrl("http://a3.qpic.cn/psb?/V11ezDF63CzHWO/oz.DQPJ*R15QjSrxxF6UpDQD4cHxOUl5wcd.wS9JdwI!/b/dHwBAAAAAAAA&bo=eAB4AAAAAAADByI!&rf=viewer_4");
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://u2791965.viewer.maka.im/pcviewer/FZSJ6YJ6");
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment("集知乎日报和美拍为一体的供用户休闲的个人开发者软件,开放源码,与广大程序猿共同进步,乐于开源,享受编程带来的乐趣");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("爱啪");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl("http://u2791965.viewer.maka.im/pcviewer/FZSJ6YJ6");
// 启动分享GUI
oks.show(context);
}
}
| Rance935/BeautyPaPa | app/src/main/java/com/rance/beautypapa/utils/ShareUtils.java | 781 | // comment是我对这条分享的评论,仅在人人网和QQ空间使用 | line_comment | zh-cn | package com.rance.beautypapa.utils;
import android.content.Context;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
/**
* 作者:Rance on 2016/10/29 15:08
* 邮箱:[email protected]
*/
public class ShareUtils {
/**
* 演示调用ShareSDK执行分享
*
* @param context
*/
public static void showShare(Context context) {
ShareSDK.initSDK(context);
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle("爱啪");
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://u2791965.viewer.maka.im/pcviewer/FZSJ6YJ6");
// text是分享文本,所有平台都需要这个字段
oks.setText("集知乎日报和美拍为一体的供用户休闲的个人开发者软件,开放源码,与广大程序猿共同进步,乐于开源,享受编程带来的乐趣");
//分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
oks.setImageUrl("http://a3.qpic.cn/psb?/V11ezDF63CzHWO/oz.DQPJ*R15QjSrxxF6UpDQD4cHxOUl5wcd.wS9JdwI!/b/dHwBAAAAAAAA&bo=eAB4AAAAAAADByI!&rf=viewer_4");
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://u2791965.viewer.maka.im/pcviewer/FZSJ6YJ6");
// co <SUF>
oks.setComment("集知乎日报和美拍为一体的供用户休闲的个人开发者软件,开放源码,与广大程序猿共同进步,乐于开源,享受编程带来的乐趣");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("爱啪");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl("http://u2791965.viewer.maka.im/pcviewer/FZSJ6YJ6");
// 启动分享GUI
oks.show(context);
}
}
| false | 682 | 17 | 781 | 20 | 724 | 17 | 781 | 20 | 1,085 | 33 | false | false | false | false | false | true |
20682_0 | package com.example.memorandum;
import java.util.ArrayList;
public class note {
private String title;
private String text;
static public final note[] abc = { // 测试数组
new note("没有比脚更长的路", " 那是一支24人组成的探险队,到亚马逊河上游的原始森林去探险。由于热带雨林的特殊气候,许多人因身体严重不适应等原因,相继与探险队失去了联系。\n" +
"\n" +
" 直到两个月以后,才彻底搞清了这支探险队的全部情况:在他们24人当中,有23人因疾病、迷路或饥饿等原因,在原始森林中不幸遇难;他们当中只有一个人创造了生还的奇迹,这个人就是著名的探险家约翰?鲍卢森。\n" +
"\n" +
" 在原始森林中,约翰?鲍卢森患上了严重的哮喘病,饿着肚子在茫茫林海中坚持摸索了整整3天3夜。\n" +
"\n" +
" 在此过程中,他昏死过去十几次,但心底里强烈的求生欲望使他一次又一次地站了起来,继续做顽强的垂死抗争。他一步一步地坚持,一步一步地摸索,生命的奇迹就这样在坚持与摸索中诞生!\n" +
"\n" +
" 后来,许多记者争先恐后地采访约翰?鲍卢森,问到最多的一个问题是:“为什么唯独你能幸运地死里逃生?”\n" +
"\n" +
" 他说了一句非常具有哲理的话:“世界上没有比人更高的山,也没有比脚更长的路。”\n" +
"\n" +
"\n" +
" 天无绝人之路。只要有脚,就会有路。这就是支撑约翰?鲍卢森死里逃生的信念。"),
new note("痛苦的背面", " 从小学到中学,她一直是班干部、三好学生,高中毕业,她以优异的成绩考入一所重点大学,担任系学生会干部,大三时还入了党。\n" +
"\n" +
" 大学最后一年,她参加全市应届毕业生洽谈会,与北京一家很有名的企业达成协议,接收她毕业后去工作。她满怀心喜,只等着七月份一毕业就去北京工作。\n" +
"\n" +
" 可是,就在毕业前一个月,她经不住好友的再三请求,答应替她去参加英语考试。\n" +
"\n" +
" 结果,那次替考被同学发现举报了。当时,学校刚换了一位新校长,正严抓校风、校纪,虽然系里老师再三为她说情开脱,最后她还是被处以开除学籍、勒令退学、并给以开除党籍、留党查看一年的处分。\n" +
"\n" +
" 这样的结果,不仅是她本人,连学校的老师、同学都有些不忍接受。\n" +
"\n" +
" 那段日子,她的痛苦,可想而知。家人怕她想不开自杀,请假轮流陪着她。\n" +
"\n" +
" 男友闻讯从外地赶回来看她。\n" +
"\n" +
" 男友非常爱她,知道她出事后,他也非常难过、痛苦。\n" +
"\n" +
" 看到她现在这个样子,更令他担忧。\n" +
"\n" +
" 他不知道用什么办法,才能安慰她,化解她心中的痛苦。\n" +
"\n" +
" 一连三天,她不吃不喝,蒙头躺在床上。家人的安慰、劝解,她一句也听不进。\n" +
"\n" +
" 到了晚上,男友过来,揭开她蒙在身上和脸上的被子,把一张写满了字的纸放到她眼前,说:“我知道你现在非常痛苦,你也完全有理由痛苦,即使你有100个痛苦也不过份。你看,这张纸写的全是“痛苦”,有100个。我们打个赌,你把它一点点撕成碎片,我保证在10分钟内把它拼好。”\n" +
"\n" +
" 她看了看,接过来,一下一下,撕成碎片,扔在地上。\n" +
"\n" +
" 不一会儿,地下就堆满了碎纸片。男友弯下身,一一拣拣起来,坐在一旁的写字台上,一块一块的拼。果然,用了不到10分钟,就拼好了。\n" +
"\n" +
" 她看着那些刚刚被自己撕成碎片、现在竟又粘贴在一起的“痛苦”,十分惊讶,终于开口,说了第一句话:“你是怎么拼好的?”\n" +
"\n" +
" “很简单。你看,”男友把纸翻过来,只见纸的背面用红色彩笔写着一个硕大的“快乐”,两个字占满了一张纸。“我在它的背面写下‘快乐’两个大字,让它充满整个张纸。拼的时候翻过来,按照‘快乐’的笔画拼,这样,一会儿就把它拼好了。”\n" +
"\n" +
" “亲爱的,无论何时,你要记住,痛苦的背面,就是快乐!中国的大学你读不了,可是,全世界,不止中国有大学呀!你不是一直想去美国留学吗?其实我也非常想去。我们做个比赛好吗?我们俩一起报考托福,一起申请去美国读书,看谁先通过?”\n" +
"\n" +
" 她已是泪流满面,扑进男友的怀抱,用力点点头。\n" +
"\n" +
"悟:\n" +
" 痛苦是一个深渊,如果不能控制,只能是越陷越深。我们应该学会快乐,快乐是战胜自己的前提。"),
new note("信徒与青蛙", " 有一个虔诚的信徒,在湖边的木屋中禁食祈祷,外面几只呱呱大叫的牛蛙吵得很凶。\n" +
"\n" +
" 他想办法充耳不闻,无奈都不得要领,只好推开窗户,大吼一声:“闭嘴!没看到我正在祈祷吗?”\n" +
"\n" +
" 说也奇怪,他吼了一声后,牛蛙立刻就不叫了。\n" +
"\n" +
" 然而,另一个意念却自心底浮起:“说不定,牛蛙的叫声跟我吟唱祷告的声音一样,也能讨上帝的喜悦。”小故事大道理全集\n" +
"\n" +
" 他决定顺服这个意念,探头伸出窗外,喝道:“大伙继续唱啊!”牛蛙整齐的合唱立时弥漫四周。他再侧耳细听,竟然不嫌吵了。他发现,一旦不再存心抗拒,牛蛙的叫声还真能使寂静的夜晚增色不少。\n" +
"\n" +
"【大道理】:\n" +
" 不是只有在顺境中才能成事,而是要有一颗全力以赴的决心。惟有自己才能为自己带来想要的东西。")};
static ArrayList<note> abcd = new ArrayList<note>();
public note(String title, String text){
this.title = title;
this.text = text;
}
public String getText() {
return text;
}
public String getTitle() {
return title;
}
public String toString() {
return this.title;
}
}
| Range479/Android- | Memorandum/app/src/main/java/com/example/memorandum/note.java | 2,321 | // 测试数组 | line_comment | zh-cn | package com.example.memorandum;
import java.util.ArrayList;
public class note {
private String title;
private String text;
static public final note[] abc = { // 测试 <SUF>
new note("没有比脚更长的路", " 那是一支24人组成的探险队,到亚马逊河上游的原始森林去探险。由于热带雨林的特殊气候,许多人因身体严重不适应等原因,相继与探险队失去了联系。\n" +
"\n" +
" 直到两个月以后,才彻底搞清了这支探险队的全部情况:在他们24人当中,有23人因疾病、迷路或饥饿等原因,在原始森林中不幸遇难;他们当中只有一个人创造了生还的奇迹,这个人就是著名的探险家约翰?鲍卢森。\n" +
"\n" +
" 在原始森林中,约翰?鲍卢森患上了严重的哮喘病,饿着肚子在茫茫林海中坚持摸索了整整3天3夜。\n" +
"\n" +
" 在此过程中,他昏死过去十几次,但心底里强烈的求生欲望使他一次又一次地站了起来,继续做顽强的垂死抗争。他一步一步地坚持,一步一步地摸索,生命的奇迹就这样在坚持与摸索中诞生!\n" +
"\n" +
" 后来,许多记者争先恐后地采访约翰?鲍卢森,问到最多的一个问题是:“为什么唯独你能幸运地死里逃生?”\n" +
"\n" +
" 他说了一句非常具有哲理的话:“世界上没有比人更高的山,也没有比脚更长的路。”\n" +
"\n" +
"\n" +
" 天无绝人之路。只要有脚,就会有路。这就是支撑约翰?鲍卢森死里逃生的信念。"),
new note("痛苦的背面", " 从小学到中学,她一直是班干部、三好学生,高中毕业,她以优异的成绩考入一所重点大学,担任系学生会干部,大三时还入了党。\n" +
"\n" +
" 大学最后一年,她参加全市应届毕业生洽谈会,与北京一家很有名的企业达成协议,接收她毕业后去工作。她满怀心喜,只等着七月份一毕业就去北京工作。\n" +
"\n" +
" 可是,就在毕业前一个月,她经不住好友的再三请求,答应替她去参加英语考试。\n" +
"\n" +
" 结果,那次替考被同学发现举报了。当时,学校刚换了一位新校长,正严抓校风、校纪,虽然系里老师再三为她说情开脱,最后她还是被处以开除学籍、勒令退学、并给以开除党籍、留党查看一年的处分。\n" +
"\n" +
" 这样的结果,不仅是她本人,连学校的老师、同学都有些不忍接受。\n" +
"\n" +
" 那段日子,她的痛苦,可想而知。家人怕她想不开自杀,请假轮流陪着她。\n" +
"\n" +
" 男友闻讯从外地赶回来看她。\n" +
"\n" +
" 男友非常爱她,知道她出事后,他也非常难过、痛苦。\n" +
"\n" +
" 看到她现在这个样子,更令他担忧。\n" +
"\n" +
" 他不知道用什么办法,才能安慰她,化解她心中的痛苦。\n" +
"\n" +
" 一连三天,她不吃不喝,蒙头躺在床上。家人的安慰、劝解,她一句也听不进。\n" +
"\n" +
" 到了晚上,男友过来,揭开她蒙在身上和脸上的被子,把一张写满了字的纸放到她眼前,说:“我知道你现在非常痛苦,你也完全有理由痛苦,即使你有100个痛苦也不过份。你看,这张纸写的全是“痛苦”,有100个。我们打个赌,你把它一点点撕成碎片,我保证在10分钟内把它拼好。”\n" +
"\n" +
" 她看了看,接过来,一下一下,撕成碎片,扔在地上。\n" +
"\n" +
" 不一会儿,地下就堆满了碎纸片。男友弯下身,一一拣拣起来,坐在一旁的写字台上,一块一块的拼。果然,用了不到10分钟,就拼好了。\n" +
"\n" +
" 她看着那些刚刚被自己撕成碎片、现在竟又粘贴在一起的“痛苦”,十分惊讶,终于开口,说了第一句话:“你是怎么拼好的?”\n" +
"\n" +
" “很简单。你看,”男友把纸翻过来,只见纸的背面用红色彩笔写着一个硕大的“快乐”,两个字占满了一张纸。“我在它的背面写下‘快乐’两个大字,让它充满整个张纸。拼的时候翻过来,按照‘快乐’的笔画拼,这样,一会儿就把它拼好了。”\n" +
"\n" +
" “亲爱的,无论何时,你要记住,痛苦的背面,就是快乐!中国的大学你读不了,可是,全世界,不止中国有大学呀!你不是一直想去美国留学吗?其实我也非常想去。我们做个比赛好吗?我们俩一起报考托福,一起申请去美国读书,看谁先通过?”\n" +
"\n" +
" 她已是泪流满面,扑进男友的怀抱,用力点点头。\n" +
"\n" +
"悟:\n" +
" 痛苦是一个深渊,如果不能控制,只能是越陷越深。我们应该学会快乐,快乐是战胜自己的前提。"),
new note("信徒与青蛙", " 有一个虔诚的信徒,在湖边的木屋中禁食祈祷,外面几只呱呱大叫的牛蛙吵得很凶。\n" +
"\n" +
" 他想办法充耳不闻,无奈都不得要领,只好推开窗户,大吼一声:“闭嘴!没看到我正在祈祷吗?”\n" +
"\n" +
" 说也奇怪,他吼了一声后,牛蛙立刻就不叫了。\n" +
"\n" +
" 然而,另一个意念却自心底浮起:“说不定,牛蛙的叫声跟我吟唱祷告的声音一样,也能讨上帝的喜悦。”小故事大道理全集\n" +
"\n" +
" 他决定顺服这个意念,探头伸出窗外,喝道:“大伙继续唱啊!”牛蛙整齐的合唱立时弥漫四周。他再侧耳细听,竟然不嫌吵了。他发现,一旦不再存心抗拒,牛蛙的叫声还真能使寂静的夜晚增色不少。\n" +
"\n" +
"【大道理】:\n" +
" 不是只有在顺境中才能成事,而是要有一颗全力以赴的决心。惟有自己才能为自己带来想要的东西。")};
static ArrayList<note> abcd = new ArrayList<note>();
public note(String title, String text){
this.title = title;
this.text = text;
}
public String getText() {
return text;
}
public String getTitle() {
return title;
}
public String toString() {
return this.title;
}
}
| false | 1,683 | 4 | 2,320 | 5 | 1,824 | 3 | 2,321 | 5 | 3,337 | 6 | false | false | false | false | false | true |
61594_1 | package io.openmessaging;
import java.util.Collection;
public abstract class QueueStore {
/**
* 把一条消息写入一个队列;
* 这个接口需要是线程安全的,也即评测程序会并发调用该接口进行put;
* 每个queue中的内容,按发送顺序存储消息(可以理解为Java中的List),同时每个消息会有一个索引,索引从0开始;
* 不同queue中的内容,相互独立,互不影响;
* @param queueName 代表queue名字,如果是第一次put,则自动生产一个queue
* @param message message,代表消息的内容,评测时内容会随机产生,大部分长度在64字节左右,会有少量消息在1k左右
*/
abstract void put(String queueName, byte[] message);
/**
* 从一个队列中读出一批消息,读出的消息要按照发送顺序来;
* 这个接口需要是线程安全的,也即评测程序会并发调用该接口进行get;
* 返回的Collection会被并发读,但不涉及写,因此只需要是线程读安全就可以了;
* @param queueName 代表队列的名字
* @param offset 代表消息的在这个队列中的起始消息索引
* @param num 代表读取的消息的条数,如果消息足够,则返回num条,否则只返回已有的消息即可;没有消息了,则返回一个空的集合
*/
abstract Collection<byte[]> get(String queueName, long offset, long num);
}
| RapidsBlink/message-queue-java | src/main/java/io/openmessaging/QueueStore.java | 354 | /**
* 从一个队列中读出一批消息,读出的消息要按照发送顺序来;
* 这个接口需要是线程安全的,也即评测程序会并发调用该接口进行get;
* 返回的Collection会被并发读,但不涉及写,因此只需要是线程读安全就可以了;
* @param queueName 代表队列的名字
* @param offset 代表消息的在这个队列中的起始消息索引
* @param num 代表读取的消息的条数,如果消息足够,则返回num条,否则只返回已有的消息即可;没有消息了,则返回一个空的集合
*/ | block_comment | zh-cn | package io.openmessaging;
import java.util.Collection;
public abstract class QueueStore {
/**
* 把一条消息写入一个队列;
* 这个接口需要是线程安全的,也即评测程序会并发调用该接口进行put;
* 每个queue中的内容,按发送顺序存储消息(可以理解为Java中的List),同时每个消息会有一个索引,索引从0开始;
* 不同queue中的内容,相互独立,互不影响;
* @param queueName 代表queue名字,如果是第一次put,则自动生产一个queue
* @param message message,代表消息的内容,评测时内容会随机产生,大部分长度在64字节左右,会有少量消息在1k左右
*/
abstract void put(String queueName, byte[] message);
/**
* 从一个 <SUF>*/
abstract Collection<byte[]> get(String queueName, long offset, long num);
}
| false | 340 | 145 | 354 | 147 | 334 | 133 | 354 | 147 | 545 | 239 | false | false | false | false | false | true |
37100_0 | package ray.eldath.avalon.gc.core;
import ray.eldath.avalon.gc.model.GroupMember;
import ray.eldath.avalon.gc.model.Rule;
import ray.eldath.avalon.gc.util.Constant;
import ray.eldath.avalon.gc.util.Variable;
import static ray.eldath.avalon.gc.util.Flag.AT;
public class Core {
private static int kickT = 0, kickNextTimeT = 0, noticeT = 0;
public static void handleOnce(GroupMember member, Rule rule) throws InterruptedException {
String nextTime = rule.kickNextTime(member);
String notice = rule.notice(member);
if (rule.kickNow(member)) {
member.kick();
System.out.println("群员 " + member.getUserUid() + ":" + member.getCard() + " 已被移出。");
kickT++;
} else if (nextTime != null && !nextTime.isEmpty()) {
hold();
KickNextTime.instance().add(member);
member.reply(AT(member) + nextTime + "\n若您不做出修正,则您将在下次运行Avalon-GroupCleaner时被移出本群!");
System.out.println("群员 " + member.getUserUid() + ":" + member.getCard() + " 将在下次运行时移出。");
kickNextTimeT++;
} else if (notice != null && !notice.isEmpty()) {
hold();
member.reply(AT(member) + notice + "\n请您做出修正。");
System.out.println("已提醒群员 " + member.getUserUid() + ":" + member.getCard() + " 做出修正。");
noticeT++;
}
}
private static void hold() throws InterruptedException {
if (!Constant._DEBUG())
if (Variable.ENABLE_ANTI_DISPLAY_OVERLOAD())
Thread.sleep(2500); // 防刷屏
}
public static int kickT() {
return kickT;
}
public static int kickNextTimeT() {
return kickNextTimeT;
}
public static int noticeT() {
return noticeT;
}
}
| Ray-Eldath/Avalon-GroupCleaner | src/main/scala/ray/eldath/avalon/gc/core/Core.java | 555 | // 防刷屏 | line_comment | zh-cn | package ray.eldath.avalon.gc.core;
import ray.eldath.avalon.gc.model.GroupMember;
import ray.eldath.avalon.gc.model.Rule;
import ray.eldath.avalon.gc.util.Constant;
import ray.eldath.avalon.gc.util.Variable;
import static ray.eldath.avalon.gc.util.Flag.AT;
public class Core {
private static int kickT = 0, kickNextTimeT = 0, noticeT = 0;
public static void handleOnce(GroupMember member, Rule rule) throws InterruptedException {
String nextTime = rule.kickNextTime(member);
String notice = rule.notice(member);
if (rule.kickNow(member)) {
member.kick();
System.out.println("群员 " + member.getUserUid() + ":" + member.getCard() + " 已被移出。");
kickT++;
} else if (nextTime != null && !nextTime.isEmpty()) {
hold();
KickNextTime.instance().add(member);
member.reply(AT(member) + nextTime + "\n若您不做出修正,则您将在下次运行Avalon-GroupCleaner时被移出本群!");
System.out.println("群员 " + member.getUserUid() + ":" + member.getCard() + " 将在下次运行时移出。");
kickNextTimeT++;
} else if (notice != null && !notice.isEmpty()) {
hold();
member.reply(AT(member) + notice + "\n请您做出修正。");
System.out.println("已提醒群员 " + member.getUserUid() + ":" + member.getCard() + " 做出修正。");
noticeT++;
}
}
private static void hold() throws InterruptedException {
if (!Constant._DEBUG())
if (Variable.ENABLE_ANTI_DISPLAY_OVERLOAD())
Thread.sleep(2500); // 防刷 <SUF>
}
public static int kickT() {
return kickT;
}
public static int kickNextTimeT() {
return kickNextTimeT;
}
public static int noticeT() {
return noticeT;
}
}
| false | 462 | 6 | 555 | 5 | 539 | 4 | 555 | 5 | 659 | 11 | false | false | false | false | false | true |
59143_3 | /**
* @author: 一只羊驼
* @date: 2024/1/15
*/
package java_Basics.java_obejct;
public class work03 {
public static void main(String args[]) {
Book book1 = new Book("哈利波特", 180);
book1.showInfo();
book1.updatePrice();
book1.showInfo();
}
}
//3.编写类Book,定义方法updatePrice,实现更改某本书的价格,具体:如果价格>150,则更改为150,如果价格>100,更改为100,否则不变
class Book {
String name;
double price;
//创建构造器初始化
public Book(String name, double price) {
this.name = name;
this.price = price;
}
//创建更改价格的方法
public void updatePrice() {
//如果方法中没有局部变量,那么this.XXX 等价于 XXX
if (this.price > 150) {
this.price = 150;
} else if (this.price > 100) {
this.price = 100;
}
}
//显示书籍信息
public void showInfo() {
System.out.println(this.name + ",价格是:" + this.price);
}
} | Ray-wzm/JavaStudy | src/java_Basics/java_obejct/work03.java | 327 | //创建更改价格的方法 | line_comment | zh-cn | /**
* @author: 一只羊驼
* @date: 2024/1/15
*/
package java_Basics.java_obejct;
public class work03 {
public static void main(String args[]) {
Book book1 = new Book("哈利波特", 180);
book1.showInfo();
book1.updatePrice();
book1.showInfo();
}
}
//3.编写类Book,定义方法updatePrice,实现更改某本书的价格,具体:如果价格>150,则更改为150,如果价格>100,更改为100,否则不变
class Book {
String name;
double price;
//创建构造器初始化
public Book(String name, double price) {
this.name = name;
this.price = price;
}
//创建 <SUF>
public void updatePrice() {
//如果方法中没有局部变量,那么this.XXX 等价于 XXX
if (this.price > 150) {
this.price = 150;
} else if (this.price > 100) {
this.price = 100;
}
}
//显示书籍信息
public void showInfo() {
System.out.println(this.name + ",价格是:" + this.price);
}
} | false | 293 | 5 | 327 | 5 | 338 | 5 | 327 | 5 | 410 | 12 | false | false | false | false | false | true |
52415_5 | package com.example.jobbook.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by 椰树 on 2016/7/16.
*/
public class MomentCommentBean implements Parcelable {
// private static final long serialVersionUID = 1L;
/**
* 评论id
*/
private int comment_id;
/**
* 问问id
*/
private int s_id;
/**
* 文章评论者
*/
private PersonBean applier;
/**
* 评论点赞数
*/
private int good;
/**
* 评论踩数
*/
private int bad;
/**
* 评论日期
*/
private String ask_time;
/**
* 评论内容
*/
private String content;
public int getComment_id() {
return comment_id;
}
public void setComment_id(int comment_id) {
this.comment_id = comment_id;
}
public int getS_id() {
return s_id;
}
public void setS_id(int q_id) {
this.s_id = q_id;
}
public PersonBean getApplier() {
return applier;
}
public void setApplier(PersonBean applier) {
this.applier = applier;
}
public int getGood() {
return good;
}
public void setGood(int good) {
this.good = good;
}
public int getBad() {
return bad;
}
public void setBad(int bad) {
this.bad = bad;
}
public String getAsk_time() {
return ask_time;
}
public void setAsk_time(String ask_time) {
this.ask_time = ask_time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String toString(){
return "applier" + applier.toString() + ",good" + good + ",bad" + bad + ",ask_time" + ask_time +
",content" + content;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.comment_id);
dest.writeInt(this.s_id);
dest.writeParcelable(this.applier, flags);
dest.writeInt(this.good);
dest.writeInt(this.bad);
dest.writeString(this.ask_time);
dest.writeString(this.content);
}
public MomentCommentBean() {
}
protected MomentCommentBean(Parcel in) {
this.comment_id = in.readInt();
this.s_id = in.readInt();
this.applier = (PersonBean) in.readSerializable();
this.good = in.readInt();
this.bad = in.readInt();
this.ask_time = in.readString();
this.content = in.readString();
}
public static final Creator<MomentCommentBean> CREATOR = new Creator<MomentCommentBean>() {
@Override
public MomentCommentBean createFromParcel(Parcel source) {
return new MomentCommentBean(source);
}
@Override
public MomentCommentBean[] newArray(int size) {
return new MomentCommentBean[size];
}
};
}
| RaymondTseng/JobBook | app/src/main/java/com/example/jobbook/bean/MomentCommentBean.java | 787 | /**
* 评论点赞数
*/ | block_comment | zh-cn | package com.example.jobbook.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by 椰树 on 2016/7/16.
*/
public class MomentCommentBean implements Parcelable {
// private static final long serialVersionUID = 1L;
/**
* 评论id
*/
private int comment_id;
/**
* 问问id
*/
private int s_id;
/**
* 文章评论者
*/
private PersonBean applier;
/**
* 评论点 <SUF>*/
private int good;
/**
* 评论踩数
*/
private int bad;
/**
* 评论日期
*/
private String ask_time;
/**
* 评论内容
*/
private String content;
public int getComment_id() {
return comment_id;
}
public void setComment_id(int comment_id) {
this.comment_id = comment_id;
}
public int getS_id() {
return s_id;
}
public void setS_id(int q_id) {
this.s_id = q_id;
}
public PersonBean getApplier() {
return applier;
}
public void setApplier(PersonBean applier) {
this.applier = applier;
}
public int getGood() {
return good;
}
public void setGood(int good) {
this.good = good;
}
public int getBad() {
return bad;
}
public void setBad(int bad) {
this.bad = bad;
}
public String getAsk_time() {
return ask_time;
}
public void setAsk_time(String ask_time) {
this.ask_time = ask_time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String toString(){
return "applier" + applier.toString() + ",good" + good + ",bad" + bad + ",ask_time" + ask_time +
",content" + content;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.comment_id);
dest.writeInt(this.s_id);
dest.writeParcelable(this.applier, flags);
dest.writeInt(this.good);
dest.writeInt(this.bad);
dest.writeString(this.ask_time);
dest.writeString(this.content);
}
public MomentCommentBean() {
}
protected MomentCommentBean(Parcel in) {
this.comment_id = in.readInt();
this.s_id = in.readInt();
this.applier = (PersonBean) in.readSerializable();
this.good = in.readInt();
this.bad = in.readInt();
this.ask_time = in.readString();
this.content = in.readString();
}
public static final Creator<MomentCommentBean> CREATOR = new Creator<MomentCommentBean>() {
@Override
public MomentCommentBean createFromParcel(Parcel source) {
return new MomentCommentBean(source);
}
@Override
public MomentCommentBean[] newArray(int size) {
return new MomentCommentBean[size];
}
};
}
| false | 688 | 10 | 787 | 11 | 885 | 11 | 787 | 11 | 1,004 | 19 | false | false | false | false | false | true |